LCOV - differential code coverage report
Current view: top level - src/backend/replication/logical - worker.c (source / functions) Coverage Total Hit UNC UBC GBC GNC CBC DUB DCB
Current: f76c13edadc2b319036e0d238703ed56bb23f934 vs 9e17d25e79d4756be08b4a5521b4b58450217137 Lines: 92.8 % 1895 1759 8 128 3 56 1700 8 58
Current Date: 2026-09-20 14:13:17 +0900 Functions: 100.0 % 98 98 24 74 2
Baseline: lcov-20260920-baseline Branches: 67.8 % 1119 759 8 352 2 14 743
Baseline Date: 2026-09-20 14:13:13 +0900 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(7,30] days: 87.5 % 64 56 8 55 1
(30,360] days: 90.8 % 109 99 10 1 98
(360..) days: 93.1 % 1722 1604 118 3 1601
Function coverage date bins:
(7,30] days: 100.0 % 2 2 2
(30,360] days: 100.0 % 5 5 5
(360..) days: 100.0 % 91 91 22 69
Branch coverage date bins:
(7,30] days: 63.6 % 22 14 8 14
(30,360] days: 61.2 % 80 49 31 49
(360..) days: 68.4 % 1017 696 321 2 694

 Age         Owner                    Branch data    TLA  Line data    Source code
                                  1                 :                : /*-------------------------------------------------------------------------
                                  2                 :                :  * worker.c
                                  3                 :                :  *     PostgreSQL logical replication worker (apply)
                                  4                 :                :  *
                                  5                 :                :  * Copyright (c) 2016-2026, PostgreSQL Global Development Group
                                  6                 :                :  *
                                  7                 :                :  * IDENTIFICATION
                                  8                 :                :  *    src/backend/replication/logical/worker.c
                                  9                 :                :  *
                                 10                 :                :  * NOTES
                                 11                 :                :  *    This file contains the worker which applies logical changes as they come
                                 12                 :                :  *    from remote logical replication stream.
                                 13                 :                :  *
                                 14                 :                :  *    The main worker (apply) is started by logical replication worker
                                 15                 :                :  *    launcher for every enabled subscription in a database. It uses
                                 16                 :                :  *    walsender protocol to communicate with publisher.
                                 17                 :                :  *
                                 18                 :                :  *    This module includes server facing code and shares libpqwalreceiver
                                 19                 :                :  *    module with walreceiver for providing the libpq specific functionality.
                                 20                 :                :  *
                                 21                 :                :  *
                                 22                 :                :  * STREAMED TRANSACTIONS
                                 23                 :                :  * ---------------------
                                 24                 :                :  * Streamed transactions (large transactions exceeding a memory limit on the
                                 25                 :                :  * upstream) are applied using one of two approaches:
                                 26                 :                :  *
                                 27                 :                :  * 1) Write to temporary files and apply when the final commit arrives
                                 28                 :                :  *
                                 29                 :                :  * This approach is used when the user has set the subscription's streaming
                                 30                 :                :  * option as on.
                                 31                 :                :  *
                                 32                 :                :  * Unlike the regular (non-streamed) case, handling streamed transactions has
                                 33                 :                :  * to handle aborts of both the toplevel transaction and subtransactions. This
                                 34                 :                :  * is achieved by tracking offsets for subtransactions, which is then used
                                 35                 :                :  * to truncate the file with serialized changes.
                                 36                 :                :  *
                                 37                 :                :  * The files are placed in tmp file directory by default, and the filenames
                                 38                 :                :  * include both the XID of the toplevel transaction and OID of the
                                 39                 :                :  * subscription. This is necessary so that different workers processing a
                                 40                 :                :  * remote transaction with the same XID doesn't interfere.
                                 41                 :                :  *
                                 42                 :                :  * We use BufFiles instead of using normal temporary files because (a) the
                                 43                 :                :  * BufFile infrastructure supports temporary files that exceed the OS file size
                                 44                 :                :  * limit, (b) provides a way for automatic clean up on the error and (c) provides
                                 45                 :                :  * a way to survive these files across local transactions and allow to open and
                                 46                 :                :  * close at stream start and close. We decided to use FileSet
                                 47                 :                :  * infrastructure as without that it deletes the files on the closure of the
                                 48                 :                :  * file and if we decide to keep stream files open across the start/stop stream
                                 49                 :                :  * then it will consume a lot of memory (more than 8K for each BufFile and
                                 50                 :                :  * there could be multiple such BufFiles as the subscriber could receive
                                 51                 :                :  * multiple start/stop streams for different transactions before getting the
                                 52                 :                :  * commit). Moreover, if we don't use FileSet then we also need to invent
                                 53                 :                :  * a new way to pass filenames to BufFile APIs so that we are allowed to open
                                 54                 :                :  * the file we desired across multiple stream-open calls for the same
                                 55                 :                :  * transaction.
                                 56                 :                :  *
                                 57                 :                :  * 2) Parallel apply workers.
                                 58                 :                :  *
                                 59                 :                :  * This approach is used when the user has set the subscription's streaming
                                 60                 :                :  * option as parallel. See logical/applyparallelworker.c for information about
                                 61                 :                :  * this approach.
                                 62                 :                :  *
                                 63                 :                :  * TWO_PHASE TRANSACTIONS
                                 64                 :                :  * ----------------------
                                 65                 :                :  * Two phase transactions are replayed at prepare and then committed or
                                 66                 :                :  * rolled back at commit prepared and rollback prepared respectively. It is
                                 67                 :                :  * possible to have a prepared transaction that arrives at the apply worker
                                 68                 :                :  * when the tablesync is busy doing the initial copy. In this case, the apply
                                 69                 :                :  * worker skips all the prepared operations [e.g. inserts] while the tablesync
                                 70                 :                :  * is still busy (see the condition of should_apply_changes_for_rel). The
                                 71                 :                :  * tablesync worker might not get such a prepared transaction because say it
                                 72                 :                :  * was prior to the initial consistent point but might have got some later
                                 73                 :                :  * commits. Now, the tablesync worker will exit without doing anything for the
                                 74                 :                :  * prepared transaction skipped by the apply worker as the sync location for it
                                 75                 :                :  * will be already ahead of the apply worker's current location. This would lead
                                 76                 :                :  * to an "empty prepare", because later when the apply worker does the commit
                                 77                 :                :  * prepare, there is nothing in it (the inserts were skipped earlier).
                                 78                 :                :  *
                                 79                 :                :  * To avoid this, and similar prepare confusions the subscription's two_phase
                                 80                 :                :  * commit is enabled only after the initial sync is over. The two_phase option
                                 81                 :                :  * has been implemented as a tri-state with values DISABLED, PENDING, and
                                 82                 :                :  * ENABLED.
                                 83                 :                :  *
                                 84                 :                :  * Even if the user specifies they want a subscription with two_phase = on,
                                 85                 :                :  * internally it will start with a tri-state of PENDING which only becomes
                                 86                 :                :  * ENABLED after all tablesync initializations are completed - i.e. when all
                                 87                 :                :  * tablesync workers have reached their READY state. In other words, the value
                                 88                 :                :  * PENDING is only a temporary state for subscription start-up.
                                 89                 :                :  *
                                 90                 :                :  * Until the two_phase is properly available (ENABLED) the subscription will
                                 91                 :                :  * behave as if two_phase = off. When the apply worker detects that all
                                 92                 :                :  * tablesyncs have become READY (while the tri-state was PENDING) it will
                                 93                 :                :  * restart the apply worker process. This happens in
                                 94                 :                :  * ProcessSyncingTablesForApply.
                                 95                 :                :  *
                                 96                 :                :  * When the (re-started) apply worker finds that all tablesyncs are READY for a
                                 97                 :                :  * two_phase tri-state of PENDING it start streaming messages with the
                                 98                 :                :  * two_phase option which in turn enables the decoding of two-phase commits at
                                 99                 :                :  * the publisher. Then, it updates the tri-state value from PENDING to ENABLED.
                                100                 :                :  * Now, it is possible that during the time we have not enabled two_phase, the
                                101                 :                :  * publisher (replication server) would have skipped some prepares but we
                                102                 :                :  * ensure that such prepares are sent along with commit prepare, see
                                103                 :                :  * ReorderBufferFinishPrepared.
                                104                 :                :  *
                                105                 :                :  * If the subscription has no tables then a two_phase tri-state PENDING is
                                106                 :                :  * left unchanged. This lets the user still do an ALTER SUBSCRIPTION REFRESH
                                107                 :                :  * PUBLICATION which might otherwise be disallowed (see below).
                                108                 :                :  *
                                109                 :                :  * If ever a user needs to be aware of the tri-state value, they can fetch it
                                110                 :                :  * from the pg_subscription catalog (see column subtwophasestate).
                                111                 :                :  *
                                112                 :                :  * Finally, to avoid problems mentioned in previous paragraphs from any
                                113                 :                :  * subsequent (not READY) tablesyncs (need to toggle two_phase option from 'on'
                                114                 :                :  * to 'off' and then again back to 'on') there is a restriction for
                                115                 :                :  * ALTER SUBSCRIPTION REFRESH PUBLICATION. This command is not permitted when
                                116                 :                :  * the two_phase tri-state is ENABLED, except when copy_data = false.
                                117                 :                :  *
                                118                 :                :  * We can get prepare of the same GID more than once for the genuine cases
                                119                 :                :  * where we have defined multiple subscriptions for publications on the same
                                120                 :                :  * server and prepared transaction has operations on tables subscribed to those
                                121                 :                :  * subscriptions. For such cases, if we use the GID sent by publisher one of
                                122                 :                :  * the prepares will be successful and others will fail, in which case the
                                123                 :                :  * server will send them again. Now, this can lead to a deadlock if user has
                                124                 :                :  * set synchronous_standby_names for all the subscriptions on subscriber. To
                                125                 :                :  * avoid such deadlocks, we generate a unique GID (consisting of the
                                126                 :                :  * subscription oid and the xid of the prepared transaction) for each prepare
                                127                 :                :  * transaction on the subscriber.
                                128                 :                :  *
                                129                 :                :  * FAILOVER
                                130                 :                :  * ----------------------
                                131                 :                :  * The logical slot on the primary can be synced to the standby by specifying
                                132                 :                :  * failover = true when creating the subscription. Enabling failover allows us
                                133                 :                :  * to smoothly transition to the promoted standby, ensuring that we can
                                134                 :                :  * subscribe to the new primary without losing any data.
                                135                 :                :  *
                                136                 :                :  * RETAIN DEAD TUPLES
                                137                 :                :  * ----------------------
                                138                 :                :  * Each apply worker that enabled retain_dead_tuples option maintains a
                                139                 :                :  * non-removable transaction ID (oldest_nonremovable_xid) in shared memory to
                                140                 :                :  * prevent dead rows from being removed prematurely when the apply worker still
                                141                 :                :  * needs them to detect update_deleted conflicts. Additionally, this helps to
                                142                 :                :  * retain the required commit_ts module information, which further helps to
                                143                 :                :  * detect update_origin_differs and delete_origin_differs conflicts reliably, as
                                144                 :                :  * otherwise, vacuum freeze could remove the required information.
                                145                 :                :  *
                                146                 :                :  * The logical replication launcher manages an internal replication slot named
                                147                 :                :  * "pg_conflict_detection". It asynchronously aggregates the non-removable
                                148                 :                :  * transaction ID from all apply workers to determine the appropriate xmin for
                                149                 :                :  * the slot, thereby retaining necessary tuples.
                                150                 :                :  *
                                151                 :                :  * The non-removable transaction ID in the apply worker is advanced to the
                                152                 :                :  * oldest running transaction ID once all concurrent transactions on the
                                153                 :                :  * publisher have been applied and flushed locally. The process involves:
                                154                 :                :  *
                                155                 :                :  * - RDT_GET_CANDIDATE_XID:
                                156                 :                :  *   Call GetOldestActiveTransactionId() to take oldestRunningXid as the
                                157                 :                :  *   candidate xid.
                                158                 :                :  *
                                159                 :                :  * - RDT_REQUEST_PUBLISHER_STATUS:
                                160                 :                :  *   Send a message to the walsender requesting the publisher status, which
                                161                 :                :  *   includes the latest WAL insert position and information about
                                162                 :                :  *   transactions that are in the commit phase.
                                163                 :                :  *
                                164                 :                :  * - RDT_WAIT_FOR_PUBLISHER_STATUS:
                                165                 :                :  *   Wait for the status from the walsender. After receiving the first status,
                                166                 :                :  *   do not proceed if there are concurrent remote transactions that are still
                                167                 :                :  *   in the commit phase. These transactions might have been assigned an
                                168                 :                :  *   earlier commit timestamp but have not yet written the commit WAL record.
                                169                 :                :  *   Continue to request the publisher status (RDT_REQUEST_PUBLISHER_STATUS)
                                170                 :                :  *   until all these transactions have completed.
                                171                 :                :  *
                                172                 :                :  * - RDT_WAIT_FOR_LOCAL_FLUSH:
                                173                 :                :  *   Advance the non-removable transaction ID if the current flush location has
                                174                 :                :  *   reached or surpassed the last received WAL position.
                                175                 :                :  *
                                176                 :                :  * - RDT_STOP_CONFLICT_INFO_RETENTION:
                                177                 :                :  *   This phase is required only when max_retention_duration is defined. We
                                178                 :                :  *   enter this phase if the wait time in either the
                                179                 :                :  *   RDT_WAIT_FOR_PUBLISHER_STATUS or RDT_WAIT_FOR_LOCAL_FLUSH phase exceeds
                                180                 :                :  *   configured max_retention_duration. In this phase,
                                181                 :                :  *   pg_subscription.subretentionactive is updated to false within a new
                                182                 :                :  *   transaction, and oldest_nonremovable_xid is set to InvalidTransactionId.
                                183                 :                :  *
                                184                 :                :  * - RDT_RESUME_CONFLICT_INFO_RETENTION:
                                185                 :                :  *   This phase is required only when max_retention_duration is defined. We
                                186                 :                :  *   enter this phase if the retention was previously stopped, and the time
                                187                 :                :  *   required to advance the non-removable transaction ID in the
                                188                 :                :  *   RDT_WAIT_FOR_LOCAL_FLUSH phase has decreased to within acceptable limits
                                189                 :                :  *   (or if max_retention_duration is set to 0). During this phase,
                                190                 :                :  *   pg_subscription.subretentionactive is updated to true within a new
                                191                 :                :  *   transaction, and the worker will be restarted.
                                192                 :                :  *
                                193                 :                :  * The overall state progression is: GET_CANDIDATE_XID ->
                                194                 :                :  * REQUEST_PUBLISHER_STATUS -> WAIT_FOR_PUBLISHER_STATUS -> (loop to
                                195                 :                :  * REQUEST_PUBLISHER_STATUS till concurrent remote transactions end) ->
                                196                 :                :  * WAIT_FOR_LOCAL_FLUSH -> loop back to GET_CANDIDATE_XID.
                                197                 :                :  *
                                198                 :                :  * Retaining the dead tuples for this period is sufficient for ensuring
                                199                 :                :  * eventual consistency using last-update-wins strategy, as dead tuples are
                                200                 :                :  * useful for detecting conflicts only during the application of concurrent
                                201                 :                :  * transactions from remote nodes. After applying and flushing all remote
                                202                 :                :  * transactions that occurred concurrently with the tuple DELETE, any
                                203                 :                :  * subsequent UPDATE from a remote node should have a later timestamp. In such
                                204                 :                :  * cases, it is acceptable to detect an update_missing scenario and convert the
                                205                 :                :  * UPDATE to an INSERT when applying it. But, for concurrent remote
                                206                 :                :  * transactions with earlier timestamps than the DELETE, detecting
                                207                 :                :  * update_deleted is necessary, as the UPDATEs in remote transactions should be
                                208                 :                :  * ignored if their timestamp is earlier than that of the dead tuples.
                                209                 :                :  *
                                210                 :                :  * Note that advancing the non-removable transaction ID is not supported if the
                                211                 :                :  * publisher is also a physical standby. This is because the logical walsender
                                212                 :                :  * on the standby can only get the WAL replay position but there may be more
                                213                 :                :  * WALs that are being replicated from the primary and those WALs could have
                                214                 :                :  * earlier commit timestamp.
                                215                 :                :  *
                                216                 :                :  * Similarly, when the publisher has subscribed to another publisher,
                                217                 :                :  * information necessary for conflict detection cannot be retained for
                                218                 :                :  * changes from origins other than the publisher. This is because publisher
                                219                 :                :  * lacks the information on concurrent transactions of other publishers to
                                220                 :                :  * which it subscribes. As the information on concurrent transactions is
                                221                 :                :  * unavailable beyond subscriber's immediate publishers, the non-removable
                                222                 :                :  * transaction ID might be advanced prematurely before changes from other
                                223                 :                :  * origins have been fully applied.
                                224                 :                :  *
                                225                 :                :  * XXX Retaining information for changes from other origins might be possible
                                226                 :                :  * by requesting the subscription on that origin to enable retain_dead_tuples
                                227                 :                :  * and fetching the conflict detection slot.xmin along with the publisher's
                                228                 :                :  * status. In the RDT_WAIT_FOR_PUBLISHER_STATUS phase, the apply worker could
                                229                 :                :  * wait for the remote slot's xmin to reach the oldest active transaction ID,
                                230                 :                :  * ensuring that all transactions from other origins have been applied on the
                                231                 :                :  * publisher, thereby getting the latest WAL position that includes all
                                232                 :                :  * concurrent changes. However, this approach may impact performance, so it
                                233                 :                :  * might not worth the effort.
                                234                 :                :  *
                                235                 :                :  * XXX It seems feasible to get the latest commit's WAL location from the
                                236                 :                :  * publisher and wait till that is applied. However, we can't do that
                                237                 :                :  * because commit timestamps can regress as a commit with a later LSN is not
                                238                 :                :  * guaranteed to have a later timestamp than those with earlier LSNs. Having
                                239                 :                :  * said that, even if that is possible, it won't improve performance much as
                                240                 :                :  * the apply always lag and moves slowly as compared with the transactions
                                241                 :                :  * on the publisher.
                                242                 :                :  *-------------------------------------------------------------------------
                                243                 :                :  */
                                244                 :                : 
                                245                 :                : #include "postgres.h"
                                246                 :                : 
                                247                 :                : #include <sys/stat.h>
                                248                 :                : #include <unistd.h>
                                249                 :                : 
                                250                 :                : #include "access/genam.h"
                                251                 :                : #include "access/commit_ts.h"
                                252                 :                : #include "access/table.h"
                                253                 :                : #include "access/tableam.h"
                                254                 :                : #include "access/tupconvert.h"
                                255                 :                : #include "access/twophase.h"
                                256                 :                : #include "access/xact.h"
                                257                 :                : #include "catalog/indexing.h"
                                258                 :                : #include "catalog/pg_inherits.h"
                                259                 :                : #include "catalog/pg_subscription.h"
                                260                 :                : #include "catalog/pg_subscription_rel.h"
                                261                 :                : #include "commands/subscriptioncmds.h"
                                262                 :                : #include "commands/tablecmds.h"
                                263                 :                : #include "commands/trigger.h"
                                264                 :                : #include "executor/executor.h"
                                265                 :                : #include "executor/execPartition.h"
                                266                 :                : #include "libpq/pqformat.h"
                                267                 :                : #include "miscadmin.h"
                                268                 :                : #include "optimizer/optimizer.h"
                                269                 :                : #include "parser/parse_relation.h"
                                270                 :                : #include "pgstat.h"
                                271                 :                : #include "port/pg_bitutils.h"
                                272                 :                : #include "postmaster/bgworker.h"
                                273                 :                : #include "postmaster/interrupt.h"
                                274                 :                : #include "postmaster/walwriter.h"
                                275                 :                : #include "replication/conflict.h"
                                276                 :                : #include "replication/logicallauncher.h"
                                277                 :                : #include "replication/logicalproto.h"
                                278                 :                : #include "replication/logicalrelation.h"
                                279                 :                : #include "replication/logicalworker.h"
                                280                 :                : #include "replication/origin.h"
                                281                 :                : #include "replication/slot.h"
                                282                 :                : #include "replication/walreceiver.h"
                                283                 :                : #include "replication/worker_internal.h"
                                284                 :                : #include "rewrite/rewriteHandler.h"
                                285                 :                : #include "storage/buffile.h"
                                286                 :                : #include "storage/ipc.h"
                                287                 :                : #include "storage/latch.h"
                                288                 :                : #include "storage/lmgr.h"
                                289                 :                : #include "storage/procarray.h"
                                290                 :                : #include "tcop/tcopprot.h"
                                291                 :                : #include "utils/acl.h"
                                292                 :                : #include "utils/guc.h"
                                293                 :                : #include "utils/inval.h"
                                294                 :                : #include "utils/lsyscache.h"
                                295                 :                : #include "utils/memutils.h"
                                296                 :                : #include "utils/pg_lsn.h"
                                297                 :                : #include "utils/rel.h"
                                298                 :                : #include "utils/rls.h"
                                299                 :                : #include "utils/snapmgr.h"
                                300                 :                : #include "utils/syscache.h"
                                301                 :                : #include "utils/usercontext.h"
                                302                 :                : #include "utils/wait_event.h"
                                303                 :                : 
                                304                 :                : #define NAPTIME_PER_CYCLE 1000  /* max sleep time between cycles (1s) */
                                305                 :                : 
                                306                 :                : typedef struct FlushPosition
                                307                 :                : {
                                308                 :                :     dlist_node  node;
                                309                 :                :     XLogRecPtr  local_end;
                                310                 :                :     XLogRecPtr  remote_end;
                                311                 :                : } FlushPosition;
                                312                 :                : 
                                313                 :                : static dlist_head lsn_mapping = DLIST_STATIC_INIT(lsn_mapping);
                                314                 :                : 
                                315                 :                : typedef struct ApplyExecutionData
                                316                 :                : {
                                317                 :                :     EState     *estate;         /* executor state, used to track resources */
                                318                 :                : 
                                319                 :                :     LogicalRepRelMapEntry *targetRel;   /* replication target rel */
                                320                 :                :     ResultRelInfo *targetRelInfo;   /* ResultRelInfo for same */
                                321                 :                : 
                                322                 :                :     /* These fields are used when the target relation is partitioned: */
                                323                 :                :     ModifyTableState *mtstate;  /* dummy ModifyTable state */
                                324                 :                :     PartitionTupleRouting *proute;  /* partition routing info */
                                325                 :                : } ApplyExecutionData;
                                326                 :                : 
                                327                 :                : /*
                                328                 :                :  * Context describing the remote transaction whose changes are currently
                                329                 :                :  * being applied, and the change within it.
                                330                 :                :  *
                                331                 :                :  * The remote transaction information (remote_xid and finish_lsn) is set when
                                332                 :                :  * the transaction's changes begin to be applied. finish_lsn is invalid when
                                333                 :                :  * the final LSN of the remote transaction is not yet known (e.g. while
                                334                 :                :  * streaming an in-progress transaction).
                                335                 :                :  *
                                336                 :                :  * The remaining fields describe the individual change being applied and are
                                337                 :                :  * used only for error context reporting.
                                338                 :                :  */
                                339                 :                : typedef struct ApplyRemoteCtx
                                340                 :                : {
                                341                 :                :     LogicalRepMsgType command;  /* 0 if invalid */
                                342                 :                :     LogicalRepRelMapEntry *rel;
                                343                 :                : 
                                344                 :                :     /* Remote node information */
                                345                 :                :     int         remote_attnum;  /* -1 if invalid */
                                346                 :                :     TransactionId remote_xid;
                                347                 :                :     XLogRecPtr  finish_lsn;
                                348                 :                :     char       *origin_name;
                                349                 :                : } ApplyRemoteCtx;
                                350                 :                : 
                                351                 :                : /*
                                352                 :                :  * The action to be taken for the changes in the transaction.
                                353                 :                :  *
                                354                 :                :  * TRANS_LEADER_APPLY:
                                355                 :                :  * This action means that we are in the leader apply worker or table sync
                                356                 :                :  * worker. The changes of the transaction are either directly applied or
                                357                 :                :  * are read from temporary files (for streaming transactions) and then
                                358                 :                :  * applied by the worker.
                                359                 :                :  *
                                360                 :                :  * TRANS_LEADER_SERIALIZE:
                                361                 :                :  * This action means that we are in the leader apply worker or table sync
                                362                 :                :  * worker. Changes are written to temporary files and then applied when the
                                363                 :                :  * final commit arrives.
                                364                 :                :  *
                                365                 :                :  * TRANS_LEADER_SEND_TO_PARALLEL:
                                366                 :                :  * This action means that we are in the leader apply worker and need to send
                                367                 :                :  * the changes to the parallel apply worker.
                                368                 :                :  *
                                369                 :                :  * TRANS_LEADER_PARTIAL_SERIALIZE:
                                370                 :                :  * This action means that we are in the leader apply worker and have sent some
                                371                 :                :  * changes directly to the parallel apply worker and the remaining changes are
                                372                 :                :  * serialized to a file, due to timeout while sending data. The parallel apply
                                373                 :                :  * worker will apply these serialized changes when the final commit arrives.
                                374                 :                :  *
                                375                 :                :  * We can't use TRANS_LEADER_SERIALIZE for this case because, in addition to
                                376                 :                :  * serializing changes, the leader worker also needs to serialize the
                                377                 :                :  * STREAM_XXX message to a file, and wait for the parallel apply worker to
                                378                 :                :  * finish the transaction when processing the transaction finish command. So
                                379                 :                :  * this new action was introduced to keep the code and logic clear.
                                380                 :                :  *
                                381                 :                :  * TRANS_PARALLEL_APPLY:
                                382                 :                :  * This action means that we are in the parallel apply worker and changes of
                                383                 :                :  * the transaction are applied directly by the worker.
                                384                 :                :  */
                                385                 :                : typedef enum
                                386                 :                : {
                                387                 :                :     /* The action for non-streaming transactions. */
                                388                 :                :     TRANS_LEADER_APPLY,
                                389                 :                : 
                                390                 :                :     /* Actions for streaming transactions. */
                                391                 :                :     TRANS_LEADER_SERIALIZE,
                                392                 :                :     TRANS_LEADER_SEND_TO_PARALLEL,
                                393                 :                :     TRANS_LEADER_PARTIAL_SERIALIZE,
                                394                 :                :     TRANS_PARALLEL_APPLY,
                                395                 :                : } TransApplyAction;
                                396                 :                : 
                                397                 :                : /*
                                398                 :                :  * The phases involved in advancing the non-removable transaction ID.
                                399                 :                :  *
                                400                 :                :  * See comments atop worker.c for details of the transition between these
                                401                 :                :  * phases.
                                402                 :                :  */
                                403                 :                : typedef enum
                                404                 :                : {
                                405                 :                :     RDT_GET_CANDIDATE_XID,
                                406                 :                :     RDT_REQUEST_PUBLISHER_STATUS,
                                407                 :                :     RDT_WAIT_FOR_PUBLISHER_STATUS,
                                408                 :                :     RDT_WAIT_FOR_LOCAL_FLUSH,
                                409                 :                :     RDT_STOP_CONFLICT_INFO_RETENTION,
                                410                 :                :     RDT_RESUME_CONFLICT_INFO_RETENTION,
                                411                 :                : } RetainDeadTuplesPhase;
                                412                 :                : 
                                413                 :                : /*
                                414                 :                :  * Critical information for managing phase transitions within the
                                415                 :                :  * RetainDeadTuplesPhase.
                                416                 :                :  */
                                417                 :                : typedef struct RetainDeadTuplesData
                                418                 :                : {
                                419                 :                :     RetainDeadTuplesPhase phase;    /* current phase */
                                420                 :                :     XLogRecPtr  remote_lsn;     /* WAL insert position on the publisher */
                                421                 :                : 
                                422                 :                :     /*
                                423                 :                :      * Oldest transaction ID that was in the commit phase on the publisher.
                                424                 :                :      * Use FullTransactionId to prevent issues with transaction ID wraparound,
                                425                 :                :      * where a new remote_oldestxid could falsely appear to originate from the
                                426                 :                :      * past and block advancement.
                                427                 :                :      */
                                428                 :                :     FullTransactionId remote_oldestxid;
                                429                 :                : 
                                430                 :                :     /*
                                431                 :                :      * Next transaction ID to be assigned on the publisher. Use
                                432                 :                :      * FullTransactionId for consistency and to allow straightforward
                                433                 :                :      * comparisons with remote_oldestxid.
                                434                 :                :      */
                                435                 :                :     FullTransactionId remote_nextxid;
                                436                 :                : 
                                437                 :                :     TimestampTz reply_time;     /* when the publisher responds with status */
                                438                 :                : 
                                439                 :                :     /*
                                440                 :                :      * Publisher transaction ID that must be awaited to complete before
                                441                 :                :      * entering the final phase (RDT_WAIT_FOR_LOCAL_FLUSH). Use
                                442                 :                :      * FullTransactionId for the same reason as remote_nextxid.
                                443                 :                :      */
                                444                 :                :     FullTransactionId remote_wait_for;
                                445                 :                : 
                                446                 :                :     TransactionId candidate_xid;    /* candidate for the non-removable
                                447                 :                :                                      * transaction ID */
                                448                 :                :     TimestampTz flushpos_update_time;   /* when the remote flush position was
                                449                 :                :                                          * updated in final phase
                                450                 :                :                                          * (RDT_WAIT_FOR_LOCAL_FLUSH) */
                                451                 :                : 
                                452                 :                :     long        table_sync_wait_time;   /* time spent waiting for table sync
                                453                 :                :                                          * to finish */
                                454                 :                : 
                                455                 :                :     /*
                                456                 :                :      * The following fields are used to determine the timing for the next
                                457                 :                :      * round of transaction ID advancement.
                                458                 :                :      */
                                459                 :                :     TimestampTz last_recv_time; /* when the last message was received */
                                460                 :                :     TimestampTz candidate_xid_time; /* when the candidate_xid is decided */
                                461                 :                :     int         xid_advance_interval;   /* how much time (ms) to wait before
                                462                 :                :                                          * attempting to advance the
                                463                 :                :                                          * non-removable transaction ID */
                                464                 :                : } RetainDeadTuplesData;
                                465                 :                : 
                                466                 :                : /*
                                467                 :                :  * The minimum (100ms) and maximum (3 minutes) intervals for advancing
                                468                 :                :  * non-removable transaction IDs. The maximum interval is a bit arbitrary but
                                469                 :                :  * is sufficient to not cause any undue network traffic.
                                470                 :                :  */
                                471                 :                : #define MIN_XID_ADVANCE_INTERVAL 100
                                472                 :                : #define MAX_XID_ADVANCE_INTERVAL 180000
                                473                 :                : 
                                474                 :                : /* Context of the remote transaction being applied */
                                475                 :                : static ApplyRemoteCtx remote_ctx =
                                476                 :                : {
                                477                 :                :     .command = 0,
                                478                 :                :     .rel = NULL,
                                479                 :                :     .remote_attnum = -1,
                                480                 :                :     .remote_xid = InvalidTransactionId,
                                481                 :                :     .finish_lsn = InvalidXLogRecPtr,
                                482                 :                :     .origin_name = NULL,
                                483                 :                : };
                                484                 :                : 
                                485                 :                : ErrorContextCallback *apply_error_context_stack = NULL;
                                486                 :                : 
                                487                 :                : MemoryContext ApplyMessageContext = NULL;
                                488                 :                : MemoryContext ApplyContext = NULL;
                                489                 :                : 
                                490                 :                : /* per stream context for streaming transactions */
                                491                 :                : static MemoryContext LogicalStreamingContext = NULL;
                                492                 :                : 
                                493                 :                : WalReceiverConn *LogRepWorkerWalRcvConn = NULL;
                                494                 :                : 
                                495                 :                : Subscription *MySubscription = NULL;
                                496                 :                : char       *MySubscriptionConninfo = NULL;
                                497                 :                : static bool MySubscriptionValid = false;
                                498                 :                : 
                                499                 :                : static List *on_commit_wakeup_workers_subids = NIL;
                                500                 :                : 
                                501                 :                : bool        in_remote_transaction = false;
                                502                 :                : 
                                503                 :                : /* fields valid only when processing streamed transaction */
                                504                 :                : static bool in_streamed_transaction = false;
                                505                 :                : 
                                506                 :                : static TransactionId stream_xid = InvalidTransactionId;
                                507                 :                : 
                                508                 :                : /*
                                509                 :                :  * The number of changes applied by parallel apply worker during one streaming
                                510                 :                :  * block.
                                511                 :                :  */
                                512                 :                : static uint32 parallel_stream_nchanges = 0;
                                513                 :                : 
                                514                 :                : /* Are we initializing an apply worker? */
                                515                 :                : bool        InitializingApplyWorker = false;
                                516                 :                : 
                                517                 :                : /*
                                518                 :                :  * We enable skipping all data modification changes (INSERT, UPDATE, etc.) for
                                519                 :                :  * the subscription if the remote transaction's finish LSN matches the subskiplsn.
                                520                 :                :  * Once we start skipping changes, we don't stop it until we skip all changes of
                                521                 :                :  * the transaction even if pg_subscription is updated and MySubscription->skiplsn
                                522                 :                :  * gets changed or reset during that. Also, in streaming transaction cases (streaming = on),
                                523                 :                :  * we don't skip receiving and spooling the changes since we decide whether or not
                                524                 :                :  * to skip applying the changes when starting to apply changes. The subskiplsn is
                                525                 :                :  * cleared after successfully skipping the transaction or applying non-empty
                                526                 :                :  * transaction. The latter prevents the mistakenly specified subskiplsn from
                                527                 :                :  * being left. Note that we cannot skip the streaming transactions when using
                                528                 :                :  * parallel apply workers because we cannot get the finish LSN before applying
                                529                 :                :  * the changes. So, we don't start parallel apply worker when finish LSN is set
                                530                 :                :  * by the user.
                                531                 :                :  */
                                532                 :                : static XLogRecPtr skip_xact_finish_lsn = InvalidXLogRecPtr;
                                533                 :                : #define is_skipping_changes() (unlikely(XLogRecPtrIsValid(skip_xact_finish_lsn)))
                                534                 :                : 
                                535                 :                : /* BufFile handle of the current streaming file */
                                536                 :                : static BufFile *stream_fd = NULL;
                                537                 :                : 
                                538                 :                : /*
                                539                 :                :  * The remote WAL position that has been applied and flushed locally. We record
                                540                 :                :  * and use this information both while sending feedback to the server and
                                541                 :                :  * advancing oldest_nonremovable_xid.
                                542                 :                :  */
                                543                 :                : static XLogRecPtr last_flushpos = InvalidXLogRecPtr;
                                544                 :                : 
                                545                 :                : typedef struct SubXactInfo
                                546                 :                : {
                                547                 :                :     TransactionId xid;          /* XID of the subxact */
                                548                 :                :     int         fileno;         /* file number in the buffile */
                                549                 :                :     pgoff_t     offset;         /* offset in the file */
                                550                 :                : } SubXactInfo;
                                551                 :                : 
                                552                 :                : /* Sub-transaction data for the current streaming transaction */
                                553                 :                : typedef struct ApplySubXactData
                                554                 :                : {
                                555                 :                :     uint32      nsubxacts;      /* number of sub-transactions */
                                556                 :                :     uint32      nsubxacts_max;  /* current capacity of subxacts */
                                557                 :                :     TransactionId subxact_last; /* xid of the last sub-transaction */
                                558                 :                :     SubXactInfo *subxacts;      /* sub-xact offset in changes file */
                                559                 :                : } ApplySubXactData;
                                560                 :                : 
                                561                 :                : static ApplySubXactData subxact_data = {0, 0, InvalidTransactionId, NULL};
                                562                 :                : 
                                563                 :                : static inline void subxact_filename(char *path, Oid subid, TransactionId xid);
                                564                 :                : static inline void changes_filename(char *path, Oid subid, TransactionId xid);
                                565                 :                : 
                                566                 :                : /*
                                567                 :                :  * Information about subtransactions of a given toplevel transaction.
                                568                 :                :  */
                                569                 :                : static void subxact_info_write(Oid subid, TransactionId xid);
                                570                 :                : static void subxact_info_read(Oid subid, TransactionId xid);
                                571                 :                : static void subxact_info_add(TransactionId xid);
                                572                 :                : static inline void cleanup_subxact_info(void);
                                573                 :                : 
                                574                 :                : /*
                                575                 :                :  * Serialize and deserialize changes for a toplevel transaction.
                                576                 :                :  */
                                577                 :                : static void stream_open_file(Oid subid, TransactionId xid,
                                578                 :                :                              bool first_segment);
                                579                 :                : static void stream_write_change(char action, StringInfo s);
                                580                 :                : static void stream_open_and_write_change(TransactionId xid, char action, StringInfo s);
                                581                 :                : static void stream_close_file(void);
                                582                 :                : 
                                583                 :                : static void send_feedback(XLogRecPtr recvpos, bool force, bool requestReply);
                                584                 :                : 
                                585                 :                : static void maybe_advance_nonremovable_xid(RetainDeadTuplesData *rdt_data,
                                586                 :                :                                            bool status_received);
                                587                 :                : static bool can_advance_nonremovable_xid(RetainDeadTuplesData *rdt_data);
                                588                 :                : static void process_rdt_phase_transition(RetainDeadTuplesData *rdt_data,
                                589                 :                :                                          bool status_received);
                                590                 :                : static void get_candidate_xid(RetainDeadTuplesData *rdt_data);
                                591                 :                : static void request_publisher_status(RetainDeadTuplesData *rdt_data);
                                592                 :                : static void wait_for_publisher_status(RetainDeadTuplesData *rdt_data,
                                593                 :                :                                       bool status_received);
                                594                 :                : static void wait_for_local_flush(RetainDeadTuplesData *rdt_data);
                                595                 :                : static bool should_stop_conflict_info_retention(RetainDeadTuplesData *rdt_data);
                                596                 :                : static void stop_conflict_info_retention(RetainDeadTuplesData *rdt_data);
                                597                 :                : static void resume_conflict_info_retention(RetainDeadTuplesData *rdt_data);
                                598                 :                : static bool update_retention_status(bool active);
                                599                 :                : static void reset_retention_data_fields(RetainDeadTuplesData *rdt_data);
                                600                 :                : static void adjust_xid_advance_interval(RetainDeadTuplesData *rdt_data,
                                601                 :                :                                         bool new_xid_found);
                                602                 :                : 
                                603                 :                : static void apply_worker_exit(void);
                                604                 :                : 
                                605                 :                : static void apply_handle_commit_internal(LogicalRepCommitData *commit_data);
                                606                 :                : static void apply_handle_insert_internal(ApplyExecutionData *edata,
                                607                 :                :                                          ResultRelInfo *relinfo,
                                608                 :                :                                          TupleTableSlot *remoteslot);
                                609                 :                : static void apply_handle_update_internal(ApplyExecutionData *edata,
                                610                 :                :                                          ResultRelInfo *relinfo,
                                611                 :                :                                          TupleTableSlot *remoteslot,
                                612                 :                :                                          LogicalRepTupleData *newtup,
                                613                 :                :                                          Oid localindexoid);
                                614                 :                : static void apply_handle_delete_internal(ApplyExecutionData *edata,
                                615                 :                :                                          ResultRelInfo *relinfo,
                                616                 :                :                                          TupleTableSlot *remoteslot,
                                617                 :                :                                          Oid localindexoid);
                                618                 :                : static bool FindReplTupleInLocalRel(ApplyExecutionData *edata, Relation localrel,
                                619                 :                :                                     LogicalRepRelation *remoterel,
                                620                 :                :                                     Oid localidxoid,
                                621                 :                :                                     TupleTableSlot *remoteslot,
                                622                 :                :                                     TupleTableSlot **localslot);
                                623                 :                : static bool FindDeletedTupleInLocalRel(Relation localrel,
                                624                 :                :                                        Oid localidxoid,
                                625                 :                :                                        TupleTableSlot *remoteslot,
                                626                 :                :                                        TransactionId *delete_xid,
                                627                 :                :                                        ReplOriginId *delete_origin,
                                628                 :                :                                        TimestampTz *delete_time);
                                629                 :                : static void apply_handle_tuple_routing(ApplyExecutionData *edata,
                                630                 :                :                                        TupleTableSlot *remoteslot,
                                631                 :                :                                        LogicalRepTupleData *newtup,
                                632                 :                :                                        CmdType operation);
                                633                 :                : 
                                634                 :                : /* Functions for skipping changes */
                                635                 :                : static void maybe_start_skipping_changes(XLogRecPtr finish_lsn);
                                636                 :                : static void stop_skipping_changes(void);
                                637                 :                : static void clear_subscription_skip_lsn(XLogRecPtr finish_lsn);
                                638                 :                : 
                                639                 :                : /* Functions to maintain the context of the remote transaction being applied */
                                640                 :                : static inline void set_remote_transaction_info(TransactionId xid, XLogRecPtr lsn);
                                641                 :                : static inline void reset_apply_remote_context(void);
                                642                 :                : 
                                643                 :                : static TransApplyAction get_transaction_apply_action(TransactionId xid,
                                644                 :                :                                                      ParallelApplyWorkerInfo **winfo);
                                645                 :                : 
                                646                 :                : static void set_wal_receiver_timeout(void);
                                647                 :                : 
                                648                 :                : static void on_exit_clear_xact_state(int code, Datum arg);
                                649                 :                : 
                                650                 :                : /*
                                651                 :                :  * Form the origin name for the subscription.
                                652                 :                :  *
                                653                 :                :  * This is a common function for tablesync and other workers. Tablesync workers
                                654                 :                :  * must pass a valid relid. Other callers must pass relid = InvalidOid.
                                655                 :                :  *
                                656                 :                :  * Return the name in the supplied buffer.
                                657                 :                :  */
                                658                 :                : void
 1440 akapila@postgresql.o      659                 :CBC        1550 : ReplicationOriginNameForLogicalRep(Oid suboid, Oid relid,
                                660                 :                :                                    char *originname, Size szoriginname)
                                661                 :                : {
                                662         [ +  + ]:           1550 :     if (OidIsValid(relid))
                                663                 :                :     {
                                664                 :                :         /* Replication origin name for tablesync workers. */
                                665                 :            828 :         snprintf(originname, szoriginname, "pg_%u_%u", suboid, relid);
                                666                 :                :     }
                                667                 :                :     else
                                668                 :                :     {
                                669                 :                :         /* Replication origin name for non-tablesync workers. */
                                670                 :            722 :         snprintf(originname, szoriginname, "pg_%u", suboid);
                                671                 :                :     }
                                672                 :           1550 : }
                                673                 :                : 
                                674                 :                : /*
                                675                 :                :  * Should this worker apply changes for given relation.
                                676                 :                :  *
                                677                 :                :  * This is mainly needed for initial relation data sync as that runs in
                                678                 :                :  * separate worker process running in parallel and we need some way to skip
                                679                 :                :  * changes coming to the leader apply worker during the sync of a table.
                                680                 :                :  *
                                681                 :                :  * Note we need to do smaller or equals comparison for SYNCDONE state because
                                682                 :                :  * it might hold position of end of initial slot consistent point WAL
                                683                 :                :  * record + 1 (ie start of next record) and next record can be COMMIT of
                                684                 :                :  * transaction we are now processing (which is what we set the finish LSN of
                                685                 :                :  * the remote transaction context to in apply_handle_begin).
                                686                 :                :  *
                                687                 :                :  * Note that for streaming transactions that are being applied in the parallel
                                688                 :                :  * apply worker, we disallow applying changes if the target table in the
                                689                 :                :  * subscription is not in the READY state, because we cannot decide whether to
                                690                 :                :  * apply the change as we won't know the finish LSN of the transaction by
                                691                 :                :  * that time.
                                692                 :                :  *
                                693                 :                :  * We already checked this in pa_can_start() before assigning the
                                694                 :                :  * streaming transaction to the parallel worker, but it also needs to be
                                695                 :                :  * checked here because if the user executes ALTER SUBSCRIPTION ... REFRESH
                                696                 :                :  * PUBLICATION in parallel, the new table can be added to pg_subscription_rel
                                697                 :                :  * while applying this transaction.
                                698                 :                :  */
                                699                 :                : static bool
 3468 peter_e@gmx.net           700                 :         168843 : should_apply_changes_for_rel(LogicalRepRelMapEntry *rel)
                                701                 :                : {
 1125 akapila@postgresql.o      702   [ +  +  +  -  :         168843 :     switch (MyLogicalRepWorker->type)
                                              -  - ]
                                703                 :                :     {
 1125 akapila@postgresql.o      704                 :GBC          10 :         case WORKERTYPE_TABLESYNC:
                                705                 :             10 :             return MyLogicalRepWorker->relid == rel->localreloid;
                                706                 :                : 
 1125 akapila@postgresql.o      707                 :CBC       63407 :         case WORKERTYPE_PARALLEL_APPLY:
                                708                 :                :             /* We don't synchronize rel's that are in unknown state. */
                                709         [ -  + ]:          63407 :             if (rel->state != SUBREL_STATE_READY &&
 1125 akapila@postgresql.o      710         [ #  # ]:UBC           0 :                 rel->state != SUBREL_STATE_UNKNOWN)
                                711         [ #  # ]:              0 :                 ereport(ERROR,
                                712                 :                :                         (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
                                713                 :                :                          errmsg("logical replication parallel apply worker for subscription \"%s\" will stop",
                                714                 :                :                                 MySubscription->name),
                                715                 :                :                          errdetail("Cannot handle streamed replication transactions using parallel apply workers until all tables have been synchronized.")));
                                716                 :                : 
 1125 akapila@postgresql.o      717                 :CBC       63407 :             return rel->state == SUBREL_STATE_READY;
                                718                 :                : 
                                719                 :         105426 :         case WORKERTYPE_APPLY:
                                720         [ +  + ]:         105524 :             return (rel->state == SUBREL_STATE_READY ||
                                721         [ +  + ]:             98 :                     (rel->state == SUBREL_STATE_SYNCDONE &&
   25 akapila@postgresql.o      722         [ +  - ]:GNC          17 :                      rel->statelsn <= remote_ctx.finish_lsn));
                                723                 :                : 
  319 akapila@postgresql.o      724                 :UBC           0 :         case WORKERTYPE_SEQUENCESYNC:
                                725                 :                :             /* Should never happen. */
                                726         [ #  # ]:              0 :             elog(ERROR, "sequence synchronization worker is not expected to apply changes");
                                727                 :                :             break;
                                728                 :                : 
 1125                           729                 :              0 :         case WORKERTYPE_UNKNOWN:
                                730                 :                :             /* Should never happen. */
                                731         [ #  # ]:              0 :             elog(ERROR, "Unknown worker type");
                                732                 :                :     }
                                733                 :                : 
                                734                 :              0 :     return false;               /* dummy for compiler */
                                735                 :                : }
                                736                 :                : 
                                737                 :                : /*
                                738                 :                :  * Begin one step (one INSERT, UPDATE, etc) of a replication transaction.
                                739                 :                :  *
                                740                 :                :  * Start a transaction, if this is the first step (else we keep using the
                                741                 :                :  * existing transaction).
                                742                 :                :  * Also provide a global snapshot and ensure we run in ApplyMessageContext.
                                743                 :                :  */
                                744                 :                : static void
 1928 tgl@sss.pgh.pa.us         745                 :CBC      169305 : begin_replication_step(void)
                                746                 :                : {
                                747                 :         169305 :     SetCurrentStatementStartTimestamp();
                                748                 :                : 
                                749         [ +  + ]:         169305 :     if (!IsTransactionState())
                                750                 :                :     {
                                751                 :            997 :         StartTransactionCommand();
                                752                 :            997 :         maybe_reread_subscription();
                                753                 :                :     }
                                754                 :                : 
                                755                 :         169302 :     PushActiveSnapshot(GetTransactionSnapshot());
                                756                 :                : 
 3421 peter_e@gmx.net           757                 :         169302 :     MemoryContextSwitchTo(ApplyMessageContext);
 1928 tgl@sss.pgh.pa.us         758                 :         169302 : }
                                759                 :                : 
                                760                 :                : /*
                                761                 :                :  * Finish up one step of a replication transaction.
                                762                 :                :  * Callers of begin_replication_step() must also call this.
                                763                 :                :  *
                                764                 :                :  * We don't close out the transaction here, but we should increment
                                765                 :                :  * the command counter to make the effects of this step visible.
                                766                 :                :  */
                                767                 :                : static void
                                768                 :         169237 : end_replication_step(void)
                                769                 :                : {
                                770                 :         169237 :     PopActiveSnapshot();
                                771                 :                : 
                                772                 :         169237 :     CommandCounterIncrement();
 3531 peter_e@gmx.net           773                 :         169237 : }
                                774                 :                : 
                                775                 :                : /*
                                776                 :                :  * Handle streamed transactions for both the leader apply worker and the
                                777                 :                :  * parallel apply workers.
                                778                 :                :  *
                                779                 :                :  * In the streaming case (receiving a block of the streamed transaction), for
                                780                 :                :  * serialize mode, simply redirect it to a file for the proper toplevel
                                781                 :                :  * transaction, and for parallel mode, the leader apply worker will send the
                                782                 :                :  * changes to parallel apply workers and the parallel apply worker will define
                                783                 :                :  * savepoints if needed. (LOGICAL_REP_MSG_RELATION or LOGICAL_REP_MSG_TYPE
                                784                 :                :  * messages will be applied by both leader apply worker and parallel apply
                                785                 :                :  * workers).
                                786                 :                :  *
                                787                 :                :  * Returns true for streamed transactions (when the change is either serialized
                                788                 :                :  * to file or sent to parallel apply worker), false otherwise (regular mode or
                                789                 :                :  * needs to be processed by parallel apply worker).
                                790                 :                :  *
                                791                 :                :  * Exception: If the message being processed is LOGICAL_REP_MSG_RELATION
                                792                 :                :  * or LOGICAL_REP_MSG_TYPE, return false even if the message needs to be sent
                                793                 :                :  * to a parallel apply worker.
                                794                 :                :  */
                                795                 :                : static bool
 2124 akapila@postgresql.o      796                 :         340213 : handle_streamed_transaction(LogicalRepMsgType action, StringInfo s)
                                797                 :                : {
                                798                 :                :     TransactionId current_xid;
                                799                 :                :     ParallelApplyWorkerInfo *winfo;
                                800                 :                :     TransApplyAction apply_action;
                                801                 :                :     StringInfoData original_msg;
                                802                 :                : 
 1350                           803                 :         340213 :     apply_action = get_transaction_apply_action(stream_xid, &winfo);
                                804                 :                : 
                                805                 :                :     /* not in streaming mode */
                                806         [ +  + ]:         340213 :     if (apply_action == TRANS_LEADER_APPLY)
 2208                           807                 :         105868 :         return false;
                                808                 :                : 
                                809         [ -  + ]:         234345 :     Assert(TransactionIdIsValid(stream_xid));
                                810                 :                : 
                                811                 :                :     /*
                                812                 :                :      * The parallel apply worker needs the xid in this message to decide
                                813                 :                :      * whether to define a savepoint, so save the original message that has
                                814                 :                :      * not moved the cursor after the xid. We will serialize this message to a
                                815                 :                :      * file in PARTIAL_SERIALIZE mode.
                                816                 :                :      */
 1350                           817                 :         234345 :     original_msg = *s;
                                818                 :                : 
                                819                 :                :     /*
                                820                 :                :      * We should have received XID of the subxact as the first part of the
                                821                 :                :      * message, so extract it.
                                822                 :                :      */
                                823                 :         234345 :     current_xid = pq_getmsgint(s, 4);
                                824                 :                : 
                                825         [ -  + ]:         234345 :     if (!TransactionIdIsValid(current_xid))
 1926 tgl@sss.pgh.pa.us         826         [ #  # ]:UBC           0 :         ereport(ERROR,
                                827                 :                :                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
                                828                 :                :                  errmsg_internal("invalid transaction ID in streamed replication transaction")));
                                829                 :                : 
 1350 akapila@postgresql.o      830   [ +  +  +  +  :CBC      234345 :     switch (apply_action)
                                                 - ]
                                831                 :                :     {
                                832                 :         102514 :         case TRANS_LEADER_SERIALIZE:
                                833         [ -  + ]:         102514 :             Assert(stream_fd);
                                834                 :                : 
                                835                 :                :             /* Add the new subxact to the array (unless already there). */
                                836                 :         102514 :             subxact_info_add(current_xid);
                                837                 :                : 
                                838                 :                :             /* Write the change to the current file */
                                839                 :         102514 :             stream_write_change(action, s);
                                840                 :         102514 :             return true;
                                841                 :                : 
                                842                 :          63389 :         case TRANS_LEADER_SEND_TO_PARALLEL:
                                843         [ -  + ]:          63389 :             Assert(winfo);
                                844                 :                : 
                                845                 :                :             /*
                                846                 :                :              * XXX The publisher side doesn't always send relation/type update
                                847                 :                :              * messages after the streaming transaction, so also update the
                                848                 :                :              * relation/type in leader apply worker. See function
                                849                 :                :              * cleanup_rel_sync_cache.
                                850                 :                :              */
                                851         [ +  - ]:          63389 :             if (pa_send_data(winfo, s->len, s->data))
                                852   [ +  +  +  - ]:          63389 :                 return (action != LOGICAL_REP_MSG_RELATION &&
                                853                 :                :                         action != LOGICAL_REP_MSG_TYPE);
                                854                 :                : 
                                855                 :                :             /*
                                856                 :                :              * Switch to serialize mode when we are not able to send the
                                857                 :                :              * change to parallel apply worker.
                                858                 :                :              */
 1350 akapila@postgresql.o      859                 :UBC           0 :             pa_switch_to_partial_serialize(winfo, false);
                                860                 :                : 
                                861                 :                :             pg_fallthrough;
 1350 akapila@postgresql.o      862                 :CBC        5006 :         case TRANS_LEADER_PARTIAL_SERIALIZE:
                                863                 :           5006 :             stream_write_change(action, &original_msg);
                                864                 :                : 
                                865                 :                :             /* Same reason as TRANS_LEADER_SEND_TO_PARALLEL case. */
                                866   [ +  +  +  - ]:           5006 :             return (action != LOGICAL_REP_MSG_RELATION &&
                                867                 :                :                     action != LOGICAL_REP_MSG_TYPE);
                                868                 :                : 
                                869                 :          63436 :         case TRANS_PARALLEL_APPLY:
                                870                 :          63436 :             parallel_stream_nchanges += 1;
                                871                 :                : 
                                872                 :                :             /* Define a savepoint for a subxact if needed. */
                                873                 :          63436 :             pa_start_subtrans(current_xid, stream_xid);
                                874                 :          63436 :             return false;
                                875                 :                : 
 1350 akapila@postgresql.o      876                 :UBC           0 :         default:
 1245 msawada@postgresql.o      877         [ #  # ]:              0 :             elog(ERROR, "unexpected apply action: %d", (int) apply_action);
                                878                 :                :             return false;       /* silence compiler warning */
                                879                 :                :     }
                                880                 :                : }
                                881                 :                : 
                                882                 :                : /*
                                883                 :                :  * Executor state preparation for evaluation of constraint expressions,
                                884                 :                :  * indexes and triggers for the specified relation.
                                885                 :                :  *
                                886                 :                :  * Note that the caller must open and close any indexes to be updated.
                                887                 :                :  */
                                888                 :                : static ApplyExecutionData *
 1947 tgl@sss.pgh.pa.us         889                 :CBC      168732 : create_edata_for_relation(LogicalRepRelMapEntry *rel)
                                890                 :                : {
                                891                 :                :     ApplyExecutionData *edata;
                                892                 :                :     EState     *estate;
                                893                 :                :     RangeTblEntry *rte;
 1294                           894                 :         168732 :     List       *perminfos = NIL;
                                895                 :                :     ResultRelInfo *resultRelInfo;
                                896                 :                : 
  284 michael@paquier.xyz       897                 :         168732 :     edata = palloc0_object(ApplyExecutionData);
 1947 tgl@sss.pgh.pa.us         898                 :         168732 :     edata->targetRel = rel;
                                899                 :                : 
                                900                 :         168732 :     edata->estate = estate = CreateExecutorState();
                                901                 :                : 
 3531 peter_e@gmx.net           902                 :         168732 :     rte = makeNode(RangeTblEntry);
                                903                 :         168732 :     rte->rtekind = RTE_RELATION;
                                904                 :         168732 :     rte->relid = RelationGetRelid(rel->localrel);
                                905                 :         168732 :     rte->relkind = rel->localrel->rd_rel->relkind;
 2912 tgl@sss.pgh.pa.us         906                 :         168732 :     rte->rellockmode = AccessShareLock;
                                907                 :                : 
 1294                           908                 :         168732 :     addRTEPermissionInfo(&perminfos, rte);
                                909                 :                : 
  590 amitlan@postgresql.o      910                 :         168732 :     ExecInitRangeTable(estate, list_make1(rte), perminfos,
                                911                 :                :                        bms_make_singleton(1));
                                912                 :                : 
 1947 tgl@sss.pgh.pa.us         913                 :         168732 :     edata->targetRelInfo = resultRelInfo = makeNode(ResultRelInfo);
                                914                 :                : 
                                915                 :                :     /*
                                916                 :                :      * Use Relation opened by logicalrep_rel_open() instead of opening it
                                917                 :                :      * again.
                                918                 :                :      */
                                919                 :         168732 :     InitResultRelInfo(resultRelInfo, rel->localrel, 1, NULL, 0);
                                920                 :                : 
                                921                 :                :     /*
                                922                 :                :      * We put the ResultRelInfo in the es_opened_result_relations list, even
                                923                 :                :      * though we don't populate the es_result_relations array.  That's a bit
                                924                 :                :      * bogus, but it's enough to make ExecGetTriggerResultRel() find them.
                                925                 :                :      *
                                926                 :                :      * ExecOpenIndices() is not called here either, each execution path doing
                                927                 :                :      * an apply operation being responsible for that.
                                928                 :                :      */
 1977 michael@paquier.xyz       929                 :         168732 :     estate->es_opened_result_relations =
 1947 tgl@sss.pgh.pa.us         930                 :         168732 :         lappend(estate->es_opened_result_relations, resultRelInfo);
                                931                 :                : 
 3224 simon@2ndQuadrant.co      932                 :         168732 :     estate->es_output_cid = GetCurrentCommandId(true);
                                933                 :                : 
                                934                 :                :     /* Prepare to catch AFTER triggers. */
 3488 peter_e@gmx.net           935                 :         168732 :     AfterTriggerBeginQuery();
                                936                 :                : 
                                937                 :                :     /* other fields of edata remain NULL for now */
                                938                 :                : 
 1947 tgl@sss.pgh.pa.us         939                 :         168732 :     return edata;
                                940                 :                : }
                                941                 :                : 
                                942                 :                : /*
                                943                 :                :  * Finish any operations related to the executor state created by
                                944                 :                :  * create_edata_for_relation().
                                945                 :                :  */
                                946                 :                : static void
                                947                 :         168678 : finish_edata(ApplyExecutionData *edata)
                                948                 :                : {
                                949                 :         168678 :     EState     *estate = edata->estate;
                                950                 :                : 
                                951                 :                :     /* Handle any queued AFTER triggers. */
 1977 michael@paquier.xyz       952                 :         168678 :     AfterTriggerEndQuery(estate);
                                953                 :                : 
                                954                 :                :     /* Shut down tuple routing, if any was done. */
 1947 tgl@sss.pgh.pa.us         955         [ +  + ]:         168678 :     if (edata->proute)
                                956                 :             74 :         ExecCleanupTupleRouting(edata->mtstate, edata->proute);
                                957                 :                : 
                                958                 :                :     /*
                                959                 :                :      * Close relations opened specifically for trigger targets.  It might seem
                                960                 :                :      * that we should call ExecCloseResultRelations() here, but we
                                961                 :                :      * intentionally don't as that would close the rel we added to
                                962                 :                :      * es_opened_result_relations above, which is wrong because we took no
                                963                 :                :      * corresponding refcount.  ExecCleanupTupleRouting() closes relations
                                964                 :                :      * opened for tuple routing, while ExecCloseTrigTargetRelations() closes
                                965                 :                :      * any relations we opened for AFTER triggers.
                                966                 :                :      */
   24 drowley@postgresql.o      967                 :         168678 :     ExecCloseTrigTargetRelations(estate);
                                968                 :                : 
 1977 michael@paquier.xyz       969                 :         168678 :     ExecResetTupleTable(estate->es_tupleTable, false);
                                970                 :         168678 :     FreeExecutorState(estate);
 1947 tgl@sss.pgh.pa.us         971                 :         168678 :     pfree(edata);
 1977 michael@paquier.xyz       972                 :         168678 : }
                                973                 :                : 
                                974                 :                : /*
                                975                 :                :  * Executes default values for columns for which we can't map to remote
                                976                 :                :  * relation columns.
                                977                 :                :  *
                                978                 :                :  * This allows us to support tables which have more columns on the downstream
                                979                 :                :  * than on the upstream.
                                980                 :                :  */
                                981                 :                : static void
 3531 peter_e@gmx.net           982                 :          96471 : slot_fill_defaults(LogicalRepRelMapEntry *rel, EState *estate,
                                983                 :                :                    TupleTableSlot *slot)
                                984                 :                : {
                                985                 :          96471 :     TupleDesc   desc = RelationGetDescr(rel->localrel);
                                986                 :          96471 :     int         num_phys_attrs = desc->natts;
                                987                 :                :     int         i;
                                988                 :                :     int         attnum,
                                989                 :          96471 :                 num_defaults = 0;
                                990                 :                :     int        *defmap;
                                991                 :                :     ExprState **defexprs;
                                992                 :                :     ExprContext *econtext;
                                993                 :                : 
                                994         [ +  - ]:          96471 :     econtext = GetPerTupleExprContext(estate);
                                995                 :                : 
                                996                 :                :     /* We got all the data via replication, no need to evaluate anything. */
                                997         [ +  + ]:          96471 :     if (num_phys_attrs == rel->remoterel.natts)
                                998                 :          56326 :         return;
                                999                 :                : 
  198 msawada@postgresql.o     1000                 :          40145 :     defmap = palloc_array(int, num_phys_attrs);
                               1001                 :          40145 :     defexprs = palloc_array(ExprState *, num_phys_attrs);
                               1002                 :                : 
 2468 michael@paquier.xyz      1003         [ -  + ]:          40145 :     Assert(rel->attrmap->maplen == num_phys_attrs);
 3531 peter_e@gmx.net          1004         [ +  + ]:         210663 :     for (attnum = 0; attnum < num_phys_attrs; attnum++)
                               1005                 :                :     {
  333 drowley@postgresql.o     1006                 :         170518 :         CompactAttribute *cattr = TupleDescCompactAttr(desc, attnum);
                               1007                 :                :         Expr       *defexpr;
                               1008                 :                : 
                               1009   [ +  -  +  + ]:         170518 :         if (cattr->attisdropped || cattr->attgenerated)
 3531 peter_e@gmx.net          1010                 :              9 :             continue;
                               1011                 :                : 
 2468 michael@paquier.xyz      1012         [ +  + ]:         170509 :         if (rel->attrmap->attnums[attnum] >= 0)
 3531 peter_e@gmx.net          1013                 :          92268 :             continue;
                               1014                 :                : 
                               1015                 :          78241 :         defexpr = (Expr *) build_column_default(rel->localrel, attnum + 1);
                               1016                 :                : 
                               1017         [ +  + ]:          78241 :         if (defexpr != NULL)
                               1018                 :                :         {
                               1019                 :                :             /* Run the expression through planner */
                               1020                 :          70131 :             defexpr = expression_planner(defexpr);
                               1021                 :                : 
                               1022                 :                :             /* Initialize executable expression in copycontext */
                               1023                 :          70131 :             defexprs[num_defaults] = ExecInitExpr(defexpr, NULL);
                               1024                 :          70131 :             defmap[num_defaults] = attnum;
                               1025                 :          70131 :             num_defaults++;
                               1026                 :                :         }
                               1027                 :                :     }
                               1028                 :                : 
                               1029         [ +  + ]:         110276 :     for (i = 0; i < num_defaults; i++)
                               1030                 :          70131 :         slot->tts_values[defmap[i]] =
                               1031                 :          70131 :             ExecEvalExpr(defexprs[i], econtext, &slot->tts_isnull[defmap[i]]);
                               1032                 :                : }
                               1033                 :                : 
                               1034                 :                : /*
                               1035                 :                :  * Store tuple data into slot.
                               1036                 :                :  *
                               1037                 :                :  * Incoming data can be either text or binary format.
                               1038                 :                :  */
                               1039                 :                : static void
 2255 tgl@sss.pgh.pa.us        1040                 :         168746 : slot_store_data(TupleTableSlot *slot, LogicalRepRelMapEntry *rel,
                               1041                 :                :                 LogicalRepTupleData *tupleData)
                               1042                 :                : {
 3413 bruce@momjian.us         1043                 :         168746 :     int         natts = slot->tts_tupleDescriptor->natts;
                               1044                 :                :     int         i;
                               1045                 :                : 
 3531 peter_e@gmx.net          1046                 :         168746 :     ExecClearTuple(slot);
                               1047                 :                : 
                               1048                 :                :     /* Call the "in" function for each non-dropped, non-null attribute */
 2468 michael@paquier.xyz      1049         [ -  + ]:         168746 :     Assert(natts == rel->attrmap->maplen);
 3531 peter_e@gmx.net          1050         [ +  + ]:         699126 :     for (i = 0; i < natts; i++)
                               1051                 :                :     {
 3318 andres@anarazel.de       1052                 :         530380 :         Form_pg_attribute att = TupleDescAttr(slot->tts_tupleDescriptor, i);
 2468 michael@paquier.xyz      1053                 :         530380 :         int         remoteattnum = rel->attrmap->attnums[i];
                               1054                 :                : 
 2255 tgl@sss.pgh.pa.us        1055   [ +  +  +  + ]:         530380 :         if (!att->attisdropped && remoteattnum >= 0)
 3531 peter_e@gmx.net          1056                 :         323463 :         {
                               1057                 :                :             StringInfo  colvalue;
                               1058                 :                : 
  127 noah@leadboat.com        1059         [ -  + ]:         323463 :             if (remoteattnum >= tupleData->ncols)
  127 noah@leadboat.com        1060         [ #  # ]:UBC           0 :                 ereport(ERROR,
                               1061                 :                :                         (errcode(ERRCODE_PROTOCOL_VIOLATION),
                               1062                 :                :                          errmsg_plural("logical replication column %d not found in tuple: only %d column received",
                               1063                 :                :                                        "logical replication column %d not found in tuple: only %d columns received",
                               1064                 :                :                                        tupleData->ncols,
                               1065                 :                :                                        remoteattnum + 1, tupleData->ncols)));
                               1066                 :                : 
  127 noah@leadboat.com        1067                 :CBC      323463 :             colvalue = &tupleData->colvalues[remoteattnum];
                               1068                 :                : 
                               1069                 :                :             /* Set attnum for error callback */
   25 akapila@postgresql.o     1070                 :GNC      323463 :             remote_ctx.remote_attnum = remoteattnum;
                               1071                 :                : 
 2255 tgl@sss.pgh.pa.us        1072         [ +  + ]:CBC      323463 :             if (tupleData->colstatus[remoteattnum] == LOGICALREP_COLUMN_TEXT)
                               1073                 :                :             {
                               1074                 :                :                 Oid         typinput;
                               1075                 :                :                 Oid         typioparam;
                               1076                 :                : 
                               1077                 :         163113 :                 getTypeInputInfo(att->atttypid, &typinput, &typioparam);
                               1078                 :         326226 :                 slot->tts_values[i] =
                               1079                 :         163113 :                     OidInputFunctionCall(typinput, colvalue->data,
                               1080                 :                :                                          typioparam, att->atttypmod);
                               1081                 :         163113 :                 slot->tts_isnull[i] = false;
                               1082                 :                :             }
                               1083         [ +  + ]:         160350 :             else if (tupleData->colstatus[remoteattnum] == LOGICALREP_COLUMN_BINARY)
                               1084                 :                :             {
                               1085                 :                :                 Oid         typreceive;
                               1086                 :                :                 Oid         typioparam;
                               1087                 :                : 
                               1088                 :                :                 /*
                               1089                 :                :                  * In some code paths we may be asked to re-parse the same
                               1090                 :                :                  * tuple data.  Reset the StringInfo's cursor so that works.
                               1091                 :                :                  */
                               1092                 :         110020 :                 colvalue->cursor = 0;
                               1093                 :                : 
                               1094                 :         110020 :                 getTypeBinaryInputInfo(att->atttypid, &typreceive, &typioparam);
                               1095                 :         220040 :                 slot->tts_values[i] =
                               1096                 :         110020 :                     OidReceiveFunctionCall(typreceive, colvalue,
                               1097                 :                :                                            typioparam, att->atttypmod);
                               1098                 :                : 
                               1099                 :                :                 /* Trouble if it didn't eat the whole buffer */
                               1100         [ -  + ]:         110020 :                 if (colvalue->cursor != colvalue->len)
 2255 tgl@sss.pgh.pa.us        1101         [ #  # ]:UBC           0 :                     ereport(ERROR,
                               1102                 :                :                             (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
                               1103                 :                :                              errmsg("incorrect binary data format in logical replication column %d",
                               1104                 :                :                                     remoteattnum + 1)));
 2255 tgl@sss.pgh.pa.us        1105                 :CBC      110020 :                 slot->tts_isnull[i] = false;
                               1106                 :                :             }
                               1107                 :                :             else
                               1108                 :                :             {
                               1109                 :                :                 /*
                               1110                 :                :                  * NULL value from remote.  (We don't expect to see
                               1111                 :                :                  * LOGICALREP_COLUMN_UNCHANGED here, but if we do, treat it as
                               1112                 :                :                  * NULL.)
                               1113                 :                :                  */
                               1114                 :          50330 :                 slot->tts_values[i] = (Datum) 0;
                               1115                 :          50330 :                 slot->tts_isnull[i] = true;
                               1116                 :                :             }
                               1117                 :                : 
                               1118                 :                :             /* Reset attnum for error callback */
   25 akapila@postgresql.o     1119                 :GNC      323463 :             remote_ctx.remote_attnum = -1;
                               1120                 :                :         }
                               1121                 :                :         else
                               1122                 :                :         {
                               1123                 :                :             /*
                               1124                 :                :              * We assign NULL to dropped attributes and missing values
                               1125                 :                :              * (missing values should be later filled using
                               1126                 :                :              * slot_fill_defaults).
                               1127                 :                :              */
 3531 peter_e@gmx.net          1128                 :CBC      206917 :             slot->tts_values[i] = (Datum) 0;
                               1129                 :         206917 :             slot->tts_isnull[i] = true;
                               1130                 :                :         }
                               1131                 :                :     }
                               1132                 :                : 
                               1133                 :         168746 :     ExecStoreVirtualTuple(slot);
                               1134                 :         168746 : }
                               1135                 :                : 
                               1136                 :                : /*
                               1137                 :                :  * Replace updated columns with data from the LogicalRepTupleData struct.
                               1138                 :                :  * This is somewhat similar to heap_modify_tuple but also calls the type
                               1139                 :                :  * input functions on the user data.
                               1140                 :                :  *
                               1141                 :                :  * "slot" is filled with a copy of the tuple in "srcslot", replacing
                               1142                 :                :  * columns provided in "tupleData" and leaving others as-is.
                               1143                 :                :  *
                               1144                 :                :  * Caution: unreplaced pass-by-ref columns in "slot" will point into the
                               1145                 :                :  * storage for "srcslot".  This is OK for current usage, but someday we may
                               1146                 :                :  * need to materialize "slot" at the end to make it independent of "srcslot".
                               1147                 :                :  */
                               1148                 :                : static void
 2255 tgl@sss.pgh.pa.us        1149                 :          31925 : slot_modify_data(TupleTableSlot *slot, TupleTableSlot *srcslot,
                               1150                 :                :                  LogicalRepRelMapEntry *rel,
                               1151                 :                :                  LogicalRepTupleData *tupleData)
                               1152                 :                : {
 3413 bruce@momjian.us         1153                 :          31925 :     int         natts = slot->tts_tupleDescriptor->natts;
                               1154                 :                :     int         i;
                               1155                 :                : 
                               1156                 :                :     /* We'll fill "slot" with a virtual tuple, so we must start with ... */
 3531 peter_e@gmx.net          1157                 :          31925 :     ExecClearTuple(slot);
                               1158                 :                : 
                               1159                 :                :     /*
                               1160                 :                :      * Copy all the column data from srcslot, so that we'll have valid values
                               1161                 :                :      * for unreplaced columns.
                               1162                 :                :      */
 2494 tgl@sss.pgh.pa.us        1163         [ -  + ]:          31925 :     Assert(natts == srcslot->tts_tupleDescriptor->natts);
                               1164                 :          31925 :     slot_getallattrs(srcslot);
                               1165                 :          31925 :     memcpy(slot->tts_values, srcslot->tts_values, natts * sizeof(Datum));
                               1166                 :          31925 :     memcpy(slot->tts_isnull, srcslot->tts_isnull, natts * sizeof(bool));
                               1167                 :                : 
                               1168                 :                :     /* Call the "in" function for each replaced attribute */
 2468 michael@paquier.xyz      1169         [ -  + ]:          31925 :     Assert(natts == rel->attrmap->maplen);
 3531 peter_e@gmx.net          1170         [ +  + ]:         159283 :     for (i = 0; i < natts; i++)
                               1171                 :                :     {
 3318 andres@anarazel.de       1172                 :         127358 :         Form_pg_attribute att = TupleDescAttr(slot->tts_tupleDescriptor, i);
 2468 michael@paquier.xyz      1173                 :         127358 :         int         remoteattnum = rel->attrmap->attnums[i];
                               1174                 :                : 
 3243 peter_e@gmx.net          1175         [ +  + ]:         127358 :         if (remoteattnum < 0)
 3531                          1176                 :          58519 :             continue;
                               1177                 :                : 
  127 noah@leadboat.com        1178         [ -  + ]:          68839 :         if (remoteattnum >= tupleData->ncols)
  127 noah@leadboat.com        1179         [ #  # ]:UBC           0 :             ereport(ERROR,
                               1180                 :                :                     (errcode(ERRCODE_PROTOCOL_VIOLATION),
                               1181                 :                :                      errmsg_plural("logical replication column %d not found in tuple: only %d column received",
                               1182                 :                :                                    "logical replication column %d not found in tuple: only %d columns received",
                               1183                 :                :                                    tupleData->ncols,
                               1184                 :                :                                    remoteattnum + 1, tupleData->ncols)));
                               1185                 :                : 
 2255 tgl@sss.pgh.pa.us        1186         [ +  - ]:CBC       68839 :         if (tupleData->colstatus[remoteattnum] != LOGICALREP_COLUMN_UNCHANGED)
                               1187                 :                :         {
                               1188                 :          68839 :             StringInfo  colvalue = &tupleData->colvalues[remoteattnum];
                               1189                 :                : 
                               1190                 :                :             /* Set attnum for error callback */
   25 akapila@postgresql.o     1191                 :GNC       68839 :             remote_ctx.remote_attnum = remoteattnum;
                               1192                 :                : 
 2255 tgl@sss.pgh.pa.us        1193         [ +  + ]:CBC       68839 :             if (tupleData->colstatus[remoteattnum] == LOGICALREP_COLUMN_TEXT)
                               1194                 :                :             {
                               1195                 :                :                 Oid         typinput;
                               1196                 :                :                 Oid         typioparam;
                               1197                 :                : 
                               1198                 :          25435 :                 getTypeInputInfo(att->atttypid, &typinput, &typioparam);
                               1199                 :          50870 :                 slot->tts_values[i] =
                               1200                 :          25435 :                     OidInputFunctionCall(typinput, colvalue->data,
                               1201                 :                :                                          typioparam, att->atttypmod);
                               1202                 :          25435 :                 slot->tts_isnull[i] = false;
                               1203                 :                :             }
                               1204         [ +  + ]:          43404 :             else if (tupleData->colstatus[remoteattnum] == LOGICALREP_COLUMN_BINARY)
                               1205                 :                :             {
                               1206                 :                :                 Oid         typreceive;
                               1207                 :                :                 Oid         typioparam;
                               1208                 :                : 
                               1209                 :                :                 /*
                               1210                 :                :                  * In some code paths we may be asked to re-parse the same
                               1211                 :                :                  * tuple data.  Reset the StringInfo's cursor so that works.
                               1212                 :                :                  */
                               1213                 :          43356 :                 colvalue->cursor = 0;
                               1214                 :                : 
                               1215                 :          43356 :                 getTypeBinaryInputInfo(att->atttypid, &typreceive, &typioparam);
                               1216                 :          86712 :                 slot->tts_values[i] =
                               1217                 :          43356 :                     OidReceiveFunctionCall(typreceive, colvalue,
                               1218                 :                :                                            typioparam, att->atttypmod);
                               1219                 :                : 
                               1220                 :                :                 /* Trouble if it didn't eat the whole buffer */
                               1221         [ -  + ]:          43356 :                 if (colvalue->cursor != colvalue->len)
 2255 tgl@sss.pgh.pa.us        1222         [ #  # ]:UBC           0 :                     ereport(ERROR,
                               1223                 :                :                             (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
                               1224                 :                :                              errmsg("incorrect binary data format in logical replication column %d",
                               1225                 :                :                                     remoteattnum + 1)));
 2255 tgl@sss.pgh.pa.us        1226                 :CBC       43356 :                 slot->tts_isnull[i] = false;
                               1227                 :                :             }
                               1228                 :                :             else
                               1229                 :                :             {
                               1230                 :                :                 /* must be LOGICALREP_COLUMN_NULL */
                               1231                 :             48 :                 slot->tts_values[i] = (Datum) 0;
                               1232                 :             48 :                 slot->tts_isnull[i] = true;
                               1233                 :                :             }
                               1234                 :                : 
                               1235                 :                :             /* Reset attnum for error callback */
   25 akapila@postgresql.o     1236                 :GNC       68839 :             remote_ctx.remote_attnum = -1;
                               1237                 :                :         }
                               1238                 :                :     }
                               1239                 :                : 
                               1240                 :                :     /* And finally, declare that "slot" contains a valid virtual tuple */
 3531 peter_e@gmx.net          1241                 :CBC       31925 :     ExecStoreVirtualTuple(slot);
                               1242                 :          31925 : }
                               1243                 :                : 
                               1244                 :                : /*
                               1245                 :                :  * Handle BEGIN message.
                               1246                 :                :  */
                               1247                 :                : static void
                               1248                 :            520 : apply_handle_begin(StringInfo s)
                               1249                 :                : {
                               1250                 :                :     LogicalRepBeginData begin_data;
                               1251                 :                : 
                               1252                 :                :     /* There must not be an active streaming transaction. */
 1342 akapila@postgresql.o     1253         [ -  + ]:            520 :     Assert(!TransactionIdIsValid(stream_xid));
                               1254                 :                : 
 3531 peter_e@gmx.net          1255                 :            520 :     logicalrep_read_begin(s, &begin_data);
   25 akapila@postgresql.o     1256                 :GNC         520 :     set_remote_transaction_info(begin_data.xid, begin_data.final_lsn);
                               1257                 :                : 
 1643 akapila@postgresql.o     1258                 :CBC         520 :     maybe_start_skipping_changes(begin_data.final_lsn);
                               1259                 :                : 
 3531 peter_e@gmx.net          1260                 :            520 :     in_remote_transaction = true;
                               1261                 :                : 
                               1262                 :            520 :     pgstat_report_activity(STATE_RUNNING, NULL);
                               1263                 :            520 : }
                               1264                 :                : 
                               1265                 :                : /*
                               1266                 :                :  * Handle COMMIT message.
                               1267                 :                :  *
                               1268                 :                :  * TODO, support tracking of multiple origins
                               1269                 :                :  */
                               1270                 :                : static void
                               1271                 :            453 : apply_handle_commit(StringInfo s)
                               1272                 :                : {
                               1273                 :                :     LogicalRepCommitData commit_data;
                               1274                 :                : 
                               1275                 :            453 :     logicalrep_read_commit(s, &commit_data);
                               1276                 :                : 
   25 akapila@postgresql.o     1277         [ -  + ]:GNC         453 :     if (commit_data.commit_lsn != remote_ctx.finish_lsn)
 1926 tgl@sss.pgh.pa.us        1278         [ #  # ]:UBC           0 :         ereport(ERROR,
                               1279                 :                :                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
                               1280                 :                :                  errmsg_internal("incorrect commit LSN %X/%08X in commit message (expected %X/%08X)",
                               1281                 :                :                                  LSN_FORMAT_ARGS(commit_data.commit_lsn),
                               1282                 :                :                                  LSN_FORMAT_ARGS(remote_ctx.finish_lsn))));
                               1283                 :                : 
 1878 akapila@postgresql.o     1284                 :CBC         453 :     apply_handle_commit_internal(&commit_data);
                               1285                 :                : 
                               1286                 :                :     /*
                               1287                 :                :      * Process any tables that are being synchronized in parallel, as well as
                               1288                 :                :      * any newly added tables or sequences.
                               1289                 :                :      */
  339                          1290                 :            453 :     ProcessSyncingRelations(commit_data.end_lsn);
                               1291                 :                : 
 3531 peter_e@gmx.net          1292                 :            453 :     pgstat_report_activity(STATE_IDLE, NULL);
   25 akapila@postgresql.o     1293                 :GNC         453 :     reset_apply_remote_context();
 3531 peter_e@gmx.net          1294                 :CBC         453 : }
                               1295                 :                : 
                               1296                 :                : /*
                               1297                 :                :  * Handle BEGIN PREPARE message.
                               1298                 :                :  */
                               1299                 :                : static void
 1894 akapila@postgresql.o     1300                 :             17 : apply_handle_begin_prepare(StringInfo s)
                               1301                 :                : {
                               1302                 :                :     LogicalRepPreparedTxnData begin_data;
                               1303                 :                : 
                               1304                 :                :     /* Tablesync should never receive prepare. */
                               1305         [ -  + ]:             17 :     if (am_tablesync_worker())
 1894 akapila@postgresql.o     1306         [ #  # ]:UBC           0 :         ereport(ERROR,
                               1307                 :                :                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
                               1308                 :                :                  errmsg_internal("tablesync worker received a BEGIN PREPARE message")));
                               1309                 :                : 
                               1310                 :                :     /* There must not be an active streaming transaction. */
 1342 akapila@postgresql.o     1311         [ -  + ]:CBC          17 :     Assert(!TransactionIdIsValid(stream_xid));
                               1312                 :                : 
 1894                          1313                 :             17 :     logicalrep_read_begin_prepare(s, &begin_data);
   25 akapila@postgresql.o     1314                 :GNC          17 :     set_remote_transaction_info(begin_data.xid, begin_data.prepare_lsn);
                               1315                 :                : 
 1643 akapila@postgresql.o     1316                 :CBC          17 :     maybe_start_skipping_changes(begin_data.prepare_lsn);
                               1317                 :                : 
 1894                          1318                 :             17 :     in_remote_transaction = true;
                               1319                 :                : 
                               1320                 :             17 :     pgstat_report_activity(STATE_RUNNING, NULL);
                               1321                 :             17 : }
                               1322                 :                : 
                               1323                 :                : /*
                               1324                 :                :  * Common function to prepare the GID.
                               1325                 :                :  */
                               1326                 :                : static void
 1879                          1327                 :             26 : apply_handle_prepare_internal(LogicalRepPreparedTxnData *prepare_data)
                               1328                 :                : {
                               1329                 :                :     char        gid[GIDSIZE];
                               1330                 :                : 
                               1331                 :                :     /*
                               1332                 :                :      * Compute unique GID for two_phase transactions. We don't use GID of
                               1333                 :                :      * prepared transaction sent by server as that can lead to deadlock when
                               1334                 :                :      * we have multiple subscriptions from same node point to publications on
                               1335                 :                :      * the same node. See comments atop worker.c
                               1336                 :                :      */
                               1337                 :             26 :     TwoPhaseTransactionGid(MySubscription->oid, prepare_data->xid,
                               1338                 :                :                            gid, sizeof(gid));
                               1339                 :                : 
                               1340                 :                :     /*
                               1341                 :                :      * BeginTransactionBlock is necessary to balance the EndTransactionBlock
                               1342                 :                :      * called within the PrepareTransactionBlock below.
                               1343                 :                :      */
 1350                          1344         [ +  - ]:             26 :     if (!IsTransactionBlock())
                               1345                 :                :     {
                               1346                 :             26 :         BeginTransactionBlock();
                               1347                 :             26 :         CommitTransactionCommand(); /* Completes the preceding Begin command. */
                               1348                 :                :     }
                               1349                 :                : 
                               1350                 :                :     /*
                               1351                 :                :      * Update origin state so we can restart streaming from correct position
                               1352                 :                :      * in case of crash.
                               1353                 :                :      */
  235 msawada@postgresql.o     1354                 :             26 :     replorigin_xact_state.origin_lsn = prepare_data->end_lsn;
                               1355                 :             26 :     replorigin_xact_state.origin_timestamp = prepare_data->prepare_time;
                               1356                 :                : 
 1879 akapila@postgresql.o     1357                 :             26 :     PrepareTransactionBlock(gid);
                               1358                 :             26 : }
                               1359                 :                : 
                               1360                 :                : /*
                               1361                 :                :  * Handle PREPARE message.
                               1362                 :                :  */
                               1363                 :                : static void
 1894                          1364                 :             16 : apply_handle_prepare(StringInfo s)
                               1365                 :                : {
                               1366                 :                :     LogicalRepPreparedTxnData prepare_data;
                               1367                 :                : 
                               1368                 :             16 :     logicalrep_read_prepare(s, &prepare_data);
                               1369                 :                : 
   25 akapila@postgresql.o     1370         [ -  + ]:GNC          16 :     if (prepare_data.prepare_lsn != remote_ctx.finish_lsn)
 1894 akapila@postgresql.o     1371         [ #  # ]:UBC           0 :         ereport(ERROR,
                               1372                 :                :                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
                               1373                 :                :                  errmsg_internal("incorrect prepare LSN %X/%08X in prepare message (expected %X/%08X)",
                               1374                 :                :                                  LSN_FORMAT_ARGS(prepare_data.prepare_lsn),
                               1375                 :                :                                  LSN_FORMAT_ARGS(remote_ctx.finish_lsn))));
                               1376                 :                : 
                               1377                 :                :     /*
                               1378                 :                :      * Unlike commit, here, we always prepare the transaction even though no
                               1379                 :                :      * change has happened in this transaction or all changes are skipped. It
                               1380                 :                :      * is done this way because at commit prepared time, we won't know whether
                               1381                 :                :      * we have skipped preparing a transaction because of those reasons.
                               1382                 :                :      *
                               1383                 :                :      * XXX, We can optimize such that at commit prepared time, we first check
                               1384                 :                :      * whether we have prepared the transaction or not but that doesn't seem
                               1385                 :                :      * worthwhile because such cases shouldn't be common.
                               1386                 :                :      */
 1894 akapila@postgresql.o     1387                 :CBC          16 :     begin_replication_step();
                               1388                 :                : 
 1879                          1389                 :             16 :     apply_handle_prepare_internal(&prepare_data);
                               1390                 :                : 
 1894                          1391                 :             16 :     end_replication_step();
                               1392                 :             16 :     CommitTransactionCommand();
                               1393                 :             15 :     pgstat_report_stat(false);
                               1394                 :                : 
                               1395                 :                :     /*
                               1396                 :                :      * It is okay not to set the local_end LSN for the prepare because we
                               1397                 :                :      * always flush the prepare record. So, we can send the acknowledgment of
                               1398                 :                :      * the remote_end LSN as soon as prepare is finished.
                               1399                 :                :      *
                               1400                 :                :      * XXX For the sake of consistency with commit, we could have set it with
                               1401                 :                :      * the LSN of prepare but as of now we don't track that value similar to
                               1402                 :                :      * XactLastCommitEnd, and adding it for this purpose doesn't seems worth
                               1403                 :                :      * it.
                               1404                 :                :      */
  772                          1405                 :             15 :     store_flush_position(prepare_data.end_lsn, InvalidXLogRecPtr);
                               1406                 :                : 
 1894                          1407                 :             15 :     in_remote_transaction = false;
                               1408                 :                : 
                               1409                 :                :     /*
                               1410                 :                :      * Process any tables that are being synchronized in parallel, as well as
                               1411                 :                :      * any newly added tables or sequences.
                               1412                 :                :      */
  339                          1413                 :             15 :     ProcessSyncingRelations(prepare_data.end_lsn);
                               1414                 :                : 
                               1415                 :                :     /*
                               1416                 :                :      * Since we have already prepared the transaction, in a case where the
                               1417                 :                :      * server crashes before clearing the subskiplsn, it will be left but the
                               1418                 :                :      * transaction won't be resent. But that's okay because it's a rare case
                               1419                 :                :      * and the subskiplsn will be cleared when finishing the next transaction.
                               1420                 :                :      */
 1643                          1421                 :             15 :     stop_skipping_changes();
                               1422                 :             15 :     clear_subscription_skip_lsn(prepare_data.prepare_lsn);
                               1423                 :                : 
 1894                          1424                 :             15 :     pgstat_report_activity(STATE_IDLE, NULL);
   25 akapila@postgresql.o     1425                 :GNC          15 :     reset_apply_remote_context();
 1894 akapila@postgresql.o     1426                 :CBC          15 : }
                               1427                 :                : 
                               1428                 :                : /*
                               1429                 :                :  * Handle a COMMIT PREPARED of a previously PREPARED transaction.
                               1430                 :                :  *
                               1431                 :                :  * Note that we don't need to wait here if the transaction was prepared in a
                               1432                 :                :  * parallel apply worker. In that case, we have already waited for the prepare
                               1433                 :                :  * to finish in apply_handle_stream_prepare() which will ensure all the
                               1434                 :                :  * operations in that transaction have happened in the subscriber, so no
                               1435                 :                :  * concurrent transaction can cause deadlock or transaction dependency issues.
                               1436                 :                :  */
                               1437                 :                : static void
                               1438                 :             22 : apply_handle_commit_prepared(StringInfo s)
                               1439                 :                : {
                               1440                 :                :     LogicalRepCommitPreparedTxnData prepare_data;
                               1441                 :                :     char        gid[GIDSIZE];
                               1442                 :                : 
                               1443                 :             22 :     logicalrep_read_commit_prepared(s, &prepare_data);
   25 akapila@postgresql.o     1444                 :GNC          22 :     set_remote_transaction_info(prepare_data.xid, prepare_data.commit_lsn);
                               1445                 :                : 
                               1446                 :                :     /* Compute GID for two_phase transactions. */
 1894 akapila@postgresql.o     1447                 :CBC          22 :     TwoPhaseTransactionGid(MySubscription->oid, prepare_data.xid,
                               1448                 :                :                            gid, sizeof(gid));
                               1449                 :                : 
                               1450                 :                :     /* There is no transaction when COMMIT PREPARED is called */
                               1451                 :             22 :     begin_replication_step();
                               1452                 :                : 
                               1453                 :                :     /*
                               1454                 :                :      * Update origin state so we can restart streaming from correct position
                               1455                 :                :      * in case of crash.
                               1456                 :                :      */
  235 msawada@postgresql.o     1457                 :             22 :     replorigin_xact_state.origin_lsn = prepare_data.end_lsn;
                               1458                 :             22 :     replorigin_xact_state.origin_timestamp = prepare_data.commit_time;
                               1459                 :                : 
 1894 akapila@postgresql.o     1460                 :             22 :     FinishPreparedTransaction(gid, true);
                               1461                 :             22 :     end_replication_step();
                               1462                 :             22 :     CommitTransactionCommand();
                               1463                 :             22 :     pgstat_report_stat(false);
                               1464                 :                : 
 1350                          1465                 :             22 :     store_flush_position(prepare_data.end_lsn, XactLastCommitEnd);
 1894                          1466                 :             22 :     in_remote_transaction = false;
                               1467                 :                : 
                               1468                 :                :     /*
                               1469                 :                :      * Process any tables that are being synchronized in parallel, as well as
                               1470                 :                :      * any newly added tables or sequences.
                               1471                 :                :      */
  339                          1472                 :             22 :     ProcessSyncingRelations(prepare_data.end_lsn);
                               1473                 :                : 
 1643                          1474                 :             22 :     clear_subscription_skip_lsn(prepare_data.end_lsn);
                               1475                 :                : 
 1894                          1476                 :             22 :     pgstat_report_activity(STATE_IDLE, NULL);
   25 akapila@postgresql.o     1477                 :GNC          22 :     reset_apply_remote_context();
 1894 akapila@postgresql.o     1478                 :CBC          22 : }
                               1479                 :                : 
                               1480                 :                : /*
                               1481                 :                :  * Handle a ROLLBACK PREPARED of a previously PREPARED TRANSACTION.
                               1482                 :                :  *
                               1483                 :                :  * Note that we don't need to wait here if the transaction was prepared in a
                               1484                 :                :  * parallel apply worker. In that case, we have already waited for the prepare
                               1485                 :                :  * to finish in apply_handle_stream_prepare() which will ensure all the
                               1486                 :                :  * operations in that transaction have happened in the subscriber, so no
                               1487                 :                :  * concurrent transaction can cause deadlock or transaction dependency issues.
                               1488                 :                :  */
                               1489                 :                : static void
                               1490                 :              5 : apply_handle_rollback_prepared(StringInfo s)
                               1491                 :                : {
                               1492                 :                :     LogicalRepRollbackPreparedTxnData rollback_data;
                               1493                 :                :     char        gid[GIDSIZE];
                               1494                 :                : 
                               1495                 :              5 :     logicalrep_read_rollback_prepared(s, &rollback_data);
   25 akapila@postgresql.o     1496                 :GNC           5 :     set_remote_transaction_info(rollback_data.xid, rollback_data.rollback_end_lsn);
                               1497                 :                : 
                               1498                 :                :     /* Compute GID for two_phase transactions. */
 1894 akapila@postgresql.o     1499                 :CBC           5 :     TwoPhaseTransactionGid(MySubscription->oid, rollback_data.xid,
                               1500                 :                :                            gid, sizeof(gid));
                               1501                 :                : 
                               1502                 :                :     /*
                               1503                 :                :      * It is possible that we haven't received prepare because it occurred
                               1504                 :                :      * before walsender reached a consistent point or the two_phase was still
                               1505                 :                :      * not enabled by that time, so in such cases, we need to skip rollback
                               1506                 :                :      * prepared.
                               1507                 :                :      */
                               1508         [ +  - ]:              5 :     if (LookupGXact(gid, rollback_data.prepare_end_lsn,
                               1509                 :                :                     rollback_data.prepare_time))
                               1510                 :                :     {
                               1511                 :                :         /*
                               1512                 :                :          * Update origin state so we can restart streaming from correct
                               1513                 :                :          * position in case of crash.
                               1514                 :                :          */
  235 msawada@postgresql.o     1515                 :              5 :         replorigin_xact_state.origin_lsn = rollback_data.rollback_end_lsn;
                               1516                 :              5 :         replorigin_xact_state.origin_timestamp = rollback_data.rollback_time;
                               1517                 :                : 
                               1518                 :                :         /* There is no transaction when ABORT/ROLLBACK PREPARED is called */
 1894 akapila@postgresql.o     1519                 :              5 :         begin_replication_step();
                               1520                 :              5 :         FinishPreparedTransaction(gid, false);
                               1521                 :              5 :         end_replication_step();
                               1522                 :              5 :         CommitTransactionCommand();
                               1523                 :                : 
 1643                          1524                 :              5 :         clear_subscription_skip_lsn(rollback_data.rollback_end_lsn);
                               1525                 :                :     }
                               1526                 :                : 
 1894                          1527                 :              5 :     pgstat_report_stat(false);
                               1528                 :                : 
                               1529                 :                :     /*
                               1530                 :                :      * It is okay not to set the local_end LSN for the rollback of prepared
                               1531                 :                :      * transaction because we always flush the WAL record for it. See
                               1532                 :                :      * apply_handle_prepare.
                               1533                 :                :      */
  772                          1534                 :              5 :     store_flush_position(rollback_data.rollback_end_lsn, InvalidXLogRecPtr);
 1894                          1535                 :              5 :     in_remote_transaction = false;
                               1536                 :                : 
                               1537                 :                :     /*
                               1538                 :                :      * Process any tables that are being synchronized in parallel, as well as
                               1539                 :                :      * any newly added tables or sequences.
                               1540                 :                :      */
  339                          1541                 :              5 :     ProcessSyncingRelations(rollback_data.rollback_end_lsn);
                               1542                 :                : 
 1894                          1543                 :              5 :     pgstat_report_activity(STATE_IDLE, NULL);
   25 akapila@postgresql.o     1544                 :GNC           5 :     reset_apply_remote_context();
 1894 akapila@postgresql.o     1545                 :CBC           5 : }
                               1546                 :                : 
                               1547                 :                : /*
                               1548                 :                :  * Handle STREAM PREPARE.
                               1549                 :                :  */
                               1550                 :                : static void
 1873                          1551                 :             15 : apply_handle_stream_prepare(StringInfo s)
                               1552                 :                : {
                               1553                 :                :     LogicalRepPreparedTxnData prepare_data;
                               1554                 :                :     ParallelApplyWorkerInfo *winfo;
                               1555                 :                :     TransApplyAction apply_action;
                               1556                 :                : 
                               1557                 :                :     /* Save the message before it is consumed. */
 1350                          1558                 :             15 :     StringInfoData original_msg = *s;
                               1559                 :                : 
 1873                          1560         [ -  + ]:             15 :     if (in_streamed_transaction)
 1873 akapila@postgresql.o     1561         [ #  # ]:UBC           0 :         ereport(ERROR,
                               1562                 :                :                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
                               1563                 :                :                  errmsg_internal("STREAM PREPARE message without STREAM STOP")));
                               1564                 :                : 
                               1565                 :                :     /* Tablesync should never receive prepare. */
 1873 akapila@postgresql.o     1566         [ -  + ]:CBC          15 :     if (am_tablesync_worker())
 1873 akapila@postgresql.o     1567         [ #  # ]:UBC           0 :         ereport(ERROR,
                               1568                 :                :                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
                               1569                 :                :                  errmsg_internal("tablesync worker received a STREAM PREPARE message")));
                               1570                 :                : 
 1873 akapila@postgresql.o     1571                 :CBC          15 :     logicalrep_read_stream_prepare(s, &prepare_data);
   25 akapila@postgresql.o     1572                 :GNC          15 :     set_remote_transaction_info(prepare_data.xid, prepare_data.prepare_lsn);
                               1573                 :                : 
 1350 akapila@postgresql.o     1574                 :CBC          15 :     apply_action = get_transaction_apply_action(prepare_data.xid, &winfo);
                               1575                 :                : 
                               1576   [ +  +  +  +  :             15 :     switch (apply_action)
                                                 - ]
                               1577                 :                :     {
 1342                          1578                 :              5 :         case TRANS_LEADER_APPLY:
                               1579                 :                : 
                               1580                 :                :             /*
                               1581                 :                :              * The transaction has been serialized to file, so replay all the
                               1582                 :                :              * spooled operations.
                               1583                 :                :              */
 1350                          1584                 :              5 :             apply_spooled_messages(MyLogicalRepWorker->stream_fileset,
                               1585                 :                :                                    prepare_data.xid, prepare_data.prepare_lsn);
                               1586                 :                : 
                               1587                 :                :             /* Mark the transaction as prepared. */
                               1588                 :              5 :             apply_handle_prepare_internal(&prepare_data);
                               1589                 :                : 
                               1590                 :              5 :             CommitTransactionCommand();
                               1591                 :                : 
                               1592                 :                :             /*
                               1593                 :                :              * It is okay not to set the local_end LSN for the prepare because
                               1594                 :                :              * we always flush the prepare record. See apply_handle_prepare.
                               1595                 :                :              */
  772                          1596                 :              5 :             store_flush_position(prepare_data.end_lsn, InvalidXLogRecPtr);
                               1597                 :                : 
 1350                          1598                 :              5 :             in_remote_transaction = false;
                               1599                 :                : 
                               1600                 :                :             /* Unlink the files with serialized changes and subxact info. */
                               1601                 :              5 :             stream_cleanup_files(MyLogicalRepWorker->subid, prepare_data.xid);
                               1602                 :                : 
                               1603         [ -  + ]:              5 :             elog(DEBUG1, "finished processing the STREAM PREPARE command");
                               1604                 :              5 :             break;
                               1605                 :                : 
                               1606                 :              4 :         case TRANS_LEADER_SEND_TO_PARALLEL:
                               1607         [ -  + ]:              4 :             Assert(winfo);
                               1608                 :                : 
                               1609         [ +  - ]:              4 :             if (pa_send_data(winfo, s->len, s->data))
                               1610                 :                :             {
                               1611                 :                :                 /* Finish processing the streaming transaction. */
                               1612                 :              4 :                 pa_xact_finish(winfo, prepare_data.end_lsn);
                               1613                 :              3 :                 break;
                               1614                 :                :             }
                               1615                 :                : 
                               1616                 :                :             /*
                               1617                 :                :              * Switch to serialize mode when we are not able to send the
                               1618                 :                :              * change to parallel apply worker.
                               1619                 :                :              */
 1350 akapila@postgresql.o     1620                 :UBC           0 :             pa_switch_to_partial_serialize(winfo, true);
                               1621                 :                : 
                               1622                 :                :             pg_fallthrough;
 1350 akapila@postgresql.o     1623                 :CBC           1 :         case TRANS_LEADER_PARTIAL_SERIALIZE:
                               1624         [ -  + ]:              1 :             Assert(winfo);
                               1625                 :                : 
                               1626                 :              1 :             stream_open_and_write_change(prepare_data.xid,
                               1627                 :                :                                          LOGICAL_REP_MSG_STREAM_PREPARE,
                               1628                 :                :                                          &original_msg);
                               1629                 :                : 
                               1630                 :              1 :             pa_set_fileset_state(winfo->shared, FS_SERIALIZE_DONE);
                               1631                 :                : 
                               1632                 :                :             /* Finish processing the streaming transaction. */
                               1633                 :              1 :             pa_xact_finish(winfo, prepare_data.end_lsn);
                               1634                 :              1 :             break;
                               1635                 :                : 
                               1636                 :              5 :         case TRANS_PARALLEL_APPLY:
                               1637                 :                : 
                               1638                 :                :             /*
                               1639                 :                :              * If the parallel apply worker is applying spooled messages then
                               1640                 :                :              * close the file before preparing.
                               1641                 :                :              */
                               1642         [ +  + ]:              5 :             if (stream_fd)
                               1643                 :              1 :                 stream_close_file();
                               1644                 :                : 
                               1645                 :              5 :             begin_replication_step();
                               1646                 :                : 
                               1647                 :                :             /* Mark the transaction as prepared. */
                               1648                 :              5 :             apply_handle_prepare_internal(&prepare_data);
                               1649                 :                : 
                               1650                 :              5 :             end_replication_step();
                               1651                 :                : 
                               1652                 :              5 :             CommitTransactionCommand();
                               1653                 :                : 
                               1654                 :                :             /*
                               1655                 :                :              * It is okay not to set the local_end LSN for the prepare because
                               1656                 :                :              * we always flush the prepare record. See apply_handle_prepare.
                               1657                 :                :              */
  772                          1658                 :              4 :             MyParallelShared->last_commit_end = InvalidXLogRecPtr;
                               1659                 :                : 
 1350                          1660                 :              4 :             pa_set_xact_state(MyParallelShared, PARALLEL_TRANS_FINISHED);
                               1661                 :              4 :             pa_unlock_transaction(MyParallelShared->xid, AccessExclusiveLock);
                               1662                 :                : 
                               1663                 :              4 :             pa_reset_subtrans();
                               1664                 :                : 
                               1665         [ +  + ]:              4 :             elog(DEBUG1, "finished processing the STREAM PREPARE command");
                               1666                 :              4 :             break;
                               1667                 :                : 
 1350 akapila@postgresql.o     1668                 :UBC           0 :         default:
 1342                          1669         [ #  # ]:              0 :             elog(ERROR, "unexpected apply action: %d", (int) apply_action);
                               1670                 :                :             break;
                               1671                 :                :     }
                               1672                 :                : 
 1350 akapila@postgresql.o     1673                 :CBC          13 :     pgstat_report_stat(false);
                               1674                 :                : 
                               1675                 :                :     /*
                               1676                 :                :      * Process any tables that are being synchronized in parallel, as well as
                               1677                 :                :      * any newly added tables or sequences.
                               1678                 :                :      */
  339                          1679                 :             13 :     ProcessSyncingRelations(prepare_data.end_lsn);
                               1680                 :                : 
                               1681                 :                :     /*
                               1682                 :                :      * Similar to prepare case, the subskiplsn could be left in a case of
                               1683                 :                :      * server crash but it's okay. See the comments in apply_handle_prepare().
                               1684                 :                :      */
 1643                          1685                 :             13 :     stop_skipping_changes();
                               1686                 :             13 :     clear_subscription_skip_lsn(prepare_data.prepare_lsn);
                               1687                 :                : 
 1873                          1688                 :             13 :     pgstat_report_activity(STATE_IDLE, NULL);
                               1689                 :                : 
   25 akapila@postgresql.o     1690                 :GNC          13 :     reset_apply_remote_context();
 1873 akapila@postgresql.o     1691                 :CBC          13 : }
                               1692                 :                : 
                               1693                 :                : /*
                               1694                 :                :  * Handle ORIGIN message.
                               1695                 :                :  *
                               1696                 :                :  * TODO, support tracking of multiple origins
                               1697                 :                :  */
                               1698                 :                : static void
 3531 peter_e@gmx.net          1699                 :             10 : apply_handle_origin(StringInfo s)
                               1700                 :                : {
                               1701                 :                :     /*
                               1702                 :                :      * ORIGIN message can only come inside streaming transaction or inside
                               1703                 :                :      * remote transaction and before any actual writes.
                               1704                 :                :      */
 2208 akapila@postgresql.o     1705         [ +  + ]:             10 :     if (!in_streamed_transaction &&
                               1706   [ +  -  -  + ]:             16 :         (!in_remote_transaction ||
                               1707         [ -  - ]:              8 :          (IsTransactionState() && !am_tablesync_worker())))
 3531 peter_e@gmx.net          1708         [ #  # ]:UBC           0 :         ereport(ERROR,
                               1709                 :                :                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
                               1710                 :                :                  errmsg_internal("ORIGIN message sent out of order")));
 3531 peter_e@gmx.net          1711                 :CBC          10 : }
                               1712                 :                : 
                               1713                 :                : /*
                               1714                 :                :  * Initialize fileset (if not already done).
                               1715                 :                :  *
                               1716                 :                :  * Create a new file when first_segment is true, otherwise open the existing
                               1717                 :                :  * file.
                               1718                 :                :  */
                               1719                 :                : void
 1350 akapila@postgresql.o     1720                 :            362 : stream_start_internal(TransactionId xid, bool first_segment)
                               1721                 :                : {
                               1722                 :            362 :     begin_replication_step();
                               1723                 :                : 
                               1724                 :                :     /*
                               1725                 :                :      * Initialize the worker's stream_fileset if we haven't yet. This will be
                               1726                 :                :      * used for the entire duration of the worker so create it in a permanent
                               1727                 :                :      * context. We create this on the very first streaming message from any
                               1728                 :                :      * transaction and then use it for this and other streaming transactions.
                               1729                 :                :      * Now, we could create a fileset at the start of the worker as well but
                               1730                 :                :      * then we won't be sure that it will ever be used.
                               1731                 :                :      */
                               1732         [ +  + ]:            362 :     if (!MyLogicalRepWorker->stream_fileset)
                               1733                 :                :     {
                               1734                 :                :         MemoryContext oldctx;
                               1735                 :                : 
                               1736                 :             14 :         oldctx = MemoryContextSwitchTo(ApplyContext);
                               1737                 :                : 
  284 michael@paquier.xyz      1738                 :             14 :         MyLogicalRepWorker->stream_fileset = palloc_object(FileSet);
 1350 akapila@postgresql.o     1739                 :             14 :         FileSetInit(MyLogicalRepWorker->stream_fileset);
                               1740                 :                : 
                               1741                 :             14 :         MemoryContextSwitchTo(oldctx);
                               1742                 :                :     }
                               1743                 :                : 
                               1744                 :                :     /* Open the spool file for this transaction. */
                               1745                 :            362 :     stream_open_file(MyLogicalRepWorker->subid, xid, first_segment);
                               1746                 :                : 
                               1747                 :                :     /* If this is not the first segment, open existing subxact file. */
                               1748         [ +  + ]:            362 :     if (!first_segment)
                               1749                 :            330 :         subxact_info_read(MyLogicalRepWorker->subid, xid);
                               1750                 :                : 
                               1751                 :            362 :     end_replication_step();
                               1752                 :            362 : }
                               1753                 :                : 
                               1754                 :                : /*
                               1755                 :                :  * Handle STREAM START message.
                               1756                 :                :  */
                               1757                 :                : static void
 2208                          1758                 :            838 : apply_handle_stream_start(StringInfo s)
                               1759                 :                : {
                               1760                 :                :     bool        first_segment;
                               1761                 :                :     ParallelApplyWorkerInfo *winfo;
                               1762                 :                :     TransApplyAction apply_action;
                               1763                 :                : 
                               1764                 :                :     /* Save the message before it is consumed. */
 1350                          1765                 :            838 :     StringInfoData original_msg = *s;
                               1766                 :                : 
 1926 tgl@sss.pgh.pa.us        1767         [ -  + ]:            838 :     if (in_streamed_transaction)
 1926 tgl@sss.pgh.pa.us        1768         [ #  # ]:UBC           0 :         ereport(ERROR,
                               1769                 :                :                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
                               1770                 :                :                  errmsg_internal("duplicate STREAM START message")));
                               1771                 :                : 
                               1772                 :                :     /* There must not be an active streaming transaction. */
 1342 akapila@postgresql.o     1773         [ -  + ]:CBC         838 :     Assert(!TransactionIdIsValid(stream_xid));
                               1774                 :                : 
                               1775                 :                :     /* notify handle methods we're processing a remote transaction */
 2208                          1776                 :            838 :     in_streamed_transaction = true;
                               1777                 :                : 
                               1778                 :                :     /* extract XID of the top-level transaction */
                               1779                 :            838 :     stream_xid = logicalrep_read_stream_start(s, &first_segment);
                               1780                 :                : 
 1926 tgl@sss.pgh.pa.us        1781         [ -  + ]:            838 :     if (!TransactionIdIsValid(stream_xid))
 1926 tgl@sss.pgh.pa.us        1782         [ #  # ]:UBC           0 :         ereport(ERROR,
                               1783                 :                :                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
                               1784                 :                :                  errmsg_internal("invalid transaction ID in streamed replication transaction")));
                               1785                 :                : 
                               1786                 :                :     /*
                               1787                 :                :      * The final LSN of the streamed transaction is known only when its commit
                               1788                 :                :      * record arrives.
                               1789                 :                :      */
   25 akapila@postgresql.o     1790                 :GNC         838 :     set_remote_transaction_info(stream_xid, InvalidXLogRecPtr);
                               1791                 :                : 
                               1792                 :                :     /* Try to allocate a worker for the streaming transaction. */
 1350 akapila@postgresql.o     1793         [ +  + ]:CBC         838 :     if (first_segment)
                               1794                 :             84 :         pa_allocate_worker(stream_xid);
                               1795                 :                : 
                               1796                 :            838 :     apply_action = get_transaction_apply_action(stream_xid, &winfo);
                               1797                 :                : 
                               1798   [ +  +  +  +  :            838 :     switch (apply_action)
                                                 - ]
                               1799                 :                :     {
                               1800                 :            342 :         case TRANS_LEADER_SERIALIZE:
                               1801                 :                : 
                               1802                 :                :             /*
                               1803                 :                :              * Function stream_start_internal starts a transaction. This
                               1804                 :                :              * transaction will be committed on the stream stop unless it is a
                               1805                 :                :              * tablesync worker in which case it will be committed after
                               1806                 :                :              * processing all the messages. We need this transaction for
                               1807                 :                :              * handling the BufFile, used for serializing the streaming data
                               1808                 :                :              * and subxact info.
                               1809                 :                :              */
                               1810                 :            342 :             stream_start_internal(stream_xid, first_segment);
                               1811                 :            342 :             break;
                               1812                 :                : 
                               1813                 :            242 :         case TRANS_LEADER_SEND_TO_PARALLEL:
                               1814         [ -  + ]:            242 :             Assert(winfo);
                               1815                 :                : 
                               1816                 :                :             /*
                               1817                 :                :              * Once we start serializing the changes, the parallel apply
                               1818                 :                :              * worker will wait for the leader to release the stream lock
                               1819                 :                :              * until the end of the transaction. So, we don't need to release
                               1820                 :                :              * the lock or increment the stream count in that case.
                               1821                 :                :              */
                               1822         [ +  + ]:            242 :             if (pa_send_data(winfo, s->len, s->data))
                               1823                 :                :             {
                               1824                 :                :                 /*
                               1825                 :                :                  * Unlock the shared object lock so that the parallel apply
                               1826                 :                :                  * worker can continue to receive changes.
                               1827                 :                :                  */
                               1828         [ +  + ]:            238 :                 if (!first_segment)
                               1829                 :            214 :                     pa_unlock_stream(winfo->shared->xid, AccessExclusiveLock);
                               1830                 :                : 
                               1831                 :                :                 /*
                               1832                 :                :                  * Increment the number of streaming blocks waiting to be
                               1833                 :                :                  * processed by parallel apply worker.
                               1834                 :                :                  */
                               1835                 :            238 :                 pg_atomic_add_fetch_u32(&winfo->shared->pending_stream_count, 1);
                               1836                 :                : 
                               1837                 :                :                 /* Cache the parallel apply worker for this transaction. */
                               1838                 :            238 :                 pa_set_stream_apply_worker(winfo);
                               1839                 :            238 :                 break;
                               1840                 :                :             }
                               1841                 :                : 
                               1842                 :                :             /*
                               1843                 :                :              * Switch to serialize mode when we are not able to send the
                               1844                 :                :              * change to parallel apply worker.
                               1845                 :                :              */
                               1846                 :              4 :             pa_switch_to_partial_serialize(winfo, !first_segment);
                               1847                 :                : 
                               1848                 :                :             pg_fallthrough;
                               1849                 :             15 :         case TRANS_LEADER_PARTIAL_SERIALIZE:
                               1850         [ -  + ]:             15 :             Assert(winfo);
                               1851                 :                : 
                               1852                 :                :             /*
                               1853                 :                :              * Open the spool file unless it was already opened when switching
                               1854                 :                :              * to serialize mode. The transaction started in
                               1855                 :                :              * stream_start_internal will be committed on the stream stop.
                               1856                 :                :              */
                               1857         [ +  + ]:             15 :             if (apply_action != TRANS_LEADER_SEND_TO_PARALLEL)
                               1858                 :             11 :                 stream_start_internal(stream_xid, first_segment);
                               1859                 :                : 
                               1860                 :             15 :             stream_write_change(LOGICAL_REP_MSG_STREAM_START, &original_msg);
                               1861                 :                : 
                               1862                 :                :             /* Cache the parallel apply worker for this transaction. */
                               1863                 :             15 :             pa_set_stream_apply_worker(winfo);
                               1864                 :             15 :             break;
                               1865                 :                : 
                               1866                 :            243 :         case TRANS_PARALLEL_APPLY:
                               1867         [ +  + ]:            243 :             if (first_segment)
                               1868                 :                :             {
                               1869                 :                :                 /* Hold the lock until the end of the transaction. */
                               1870                 :             28 :                 pa_lock_transaction(MyParallelShared->xid, AccessExclusiveLock);
                               1871                 :             28 :                 pa_set_xact_state(MyParallelShared, PARALLEL_TRANS_STARTED);
                               1872                 :                : 
                               1873                 :                :                 /*
                               1874                 :                :                  * Signal the leader apply worker, as it may be waiting for
                               1875                 :                :                  * us.
                               1876                 :                :                  */
  327                          1877                 :             28 :                 logicalrep_worker_wakeup(WORKERTYPE_APPLY,
                               1878                 :             28 :                                          MyLogicalRepWorker->subid, InvalidOid);
                               1879                 :                :             }
                               1880                 :                : 
 1350                          1881                 :            243 :             parallel_stream_nchanges = 0;
                               1882                 :            243 :             break;
                               1883                 :                : 
 1350 akapila@postgresql.o     1884                 :UBC           0 :         default:
 1342                          1885         [ #  # ]:              0 :             elog(ERROR, "unexpected apply action: %d", (int) apply_action);
                               1886                 :                :             break;
                               1887                 :                :     }
                               1888                 :                : 
 1350 akapila@postgresql.o     1889                 :CBC         838 :     pgstat_report_activity(STATE_RUNNING, NULL);
 2208                          1890                 :            838 : }
                               1891                 :                : 
                               1892                 :                : /*
                               1893                 :                :  * Update the information about subxacts and close the file.
                               1894                 :                :  *
                               1895                 :                :  * This function should be called when the stream_start_internal function has
                               1896                 :                :  * been called.
                               1897                 :                :  */
                               1898                 :                : void
 1350                          1899                 :            362 : stream_stop_internal(TransactionId xid)
                               1900                 :                : {
                               1901                 :                :     /*
                               1902                 :                :      * Serialize information about subxacts for the toplevel transaction, then
                               1903                 :                :      * close the stream messages spool file.
                               1904                 :                :      */
                               1905                 :            362 :     subxact_info_write(MyLogicalRepWorker->subid, xid);
 2208                          1906                 :            362 :     stream_close_file();
                               1907                 :                : 
                               1908                 :                :     /* We must be in a valid transaction state */
                               1909         [ -  + ]:            362 :     Assert(IsTransactionState());
                               1910                 :                : 
                               1911                 :                :     /* Commit the per-stream transaction */
 2046                          1912                 :            362 :     CommitTransactionCommand();
                               1913                 :                : 
                               1914                 :                :     /* Reset per-stream context */
 2208                          1915                 :            362 :     MemoryContextReset(LogicalStreamingContext);
                               1916                 :            362 : }
                               1917                 :                : 
                               1918                 :                : /*
                               1919                 :                :  * Handle STREAM STOP message.
                               1920                 :                :  */
                               1921                 :                : static void
 1350                          1922                 :            837 : apply_handle_stream_stop(StringInfo s)
                               1923                 :                : {
                               1924                 :                :     ParallelApplyWorkerInfo *winfo;
                               1925                 :                :     TransApplyAction apply_action;
                               1926                 :                : 
                               1927         [ -  + ]:            837 :     if (!in_streamed_transaction)
 1926 tgl@sss.pgh.pa.us        1928         [ #  # ]:UBC           0 :         ereport(ERROR,
                               1929                 :                :                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
                               1930                 :                :                  errmsg_internal("STREAM STOP message without STREAM START")));
                               1931                 :                : 
 1350 akapila@postgresql.o     1932                 :CBC         837 :     apply_action = get_transaction_apply_action(stream_xid, &winfo);
                               1933                 :                : 
                               1934   [ +  +  +  +  :            837 :     switch (apply_action)
                                                 - ]
                               1935                 :                :     {
                               1936                 :            342 :         case TRANS_LEADER_SERIALIZE:
                               1937                 :            342 :             stream_stop_internal(stream_xid);
                               1938                 :            342 :             break;
                               1939                 :                : 
                               1940                 :            238 :         case TRANS_LEADER_SEND_TO_PARALLEL:
                               1941         [ -  + ]:            238 :             Assert(winfo);
                               1942                 :                : 
                               1943                 :                :             /*
                               1944                 :                :              * Lock before sending the STREAM_STOP message so that the leader
                               1945                 :                :              * can hold the lock first and the parallel apply worker will wait
                               1946                 :                :              * for leader to release the lock. See Locking Considerations atop
                               1947                 :                :              * applyparallelworker.c.
                               1948                 :                :              */
                               1949                 :            238 :             pa_lock_stream(winfo->shared->xid, AccessExclusiveLock);
                               1950                 :                : 
                               1951         [ +  - ]:            238 :             if (pa_send_data(winfo, s->len, s->data))
                               1952                 :                :             {
                               1953                 :            238 :                 pa_set_stream_apply_worker(NULL);
                               1954                 :            238 :                 break;
                               1955                 :                :             }
                               1956                 :                : 
                               1957                 :                :             /*
                               1958                 :                :              * Switch to serialize mode when we are not able to send the
                               1959                 :                :              * change to parallel apply worker.
                               1960                 :                :              */
 1350 akapila@postgresql.o     1961                 :UBC           0 :             pa_switch_to_partial_serialize(winfo, true);
                               1962                 :                : 
                               1963                 :                :             pg_fallthrough;
 1350 akapila@postgresql.o     1964                 :CBC          15 :         case TRANS_LEADER_PARTIAL_SERIALIZE:
                               1965                 :             15 :             stream_write_change(LOGICAL_REP_MSG_STREAM_STOP, s);
                               1966                 :             15 :             stream_stop_internal(stream_xid);
                               1967                 :             15 :             pa_set_stream_apply_worker(NULL);
                               1968                 :             15 :             break;
                               1969                 :                : 
                               1970                 :            242 :         case TRANS_PARALLEL_APPLY:
                               1971         [ +  + ]:            242 :             elog(DEBUG1, "applied %u changes in the streaming chunk",
                               1972                 :                :                  parallel_stream_nchanges);
                               1973                 :                : 
                               1974                 :                :             /*
                               1975                 :                :              * By the time parallel apply worker is processing the changes in
                               1976                 :                :              * the current streaming block, the leader apply worker may have
                               1977                 :                :              * sent multiple streaming blocks. This can lead to parallel apply
                               1978                 :                :              * worker start waiting even when there are more chunk of streams
                               1979                 :                :              * in the queue. So, try to lock only if there is no message left
                               1980                 :                :              * in the queue. See Locking Considerations atop
                               1981                 :                :              * applyparallelworker.c.
                               1982                 :                :              *
                               1983                 :                :              * Note that here we have a race condition where we can start
                               1984                 :                :              * waiting even when there are pending streaming chunks. This can
                               1985                 :                :              * happen if the leader sends another streaming block and acquires
                               1986                 :                :              * the stream lock again after the parallel apply worker checks
                               1987                 :                :              * that there is no pending streaming block and before it actually
                               1988                 :                :              * starts waiting on a lock. We can handle this case by not
                               1989                 :                :              * allowing the leader to increment the stream block count during
                               1990                 :                :              * the time parallel apply worker acquires the lock but it is not
                               1991                 :                :              * clear whether that is worth the complexity.
                               1992                 :                :              *
                               1993                 :                :              * Now, if this missed chunk contains rollback to savepoint, then
                               1994                 :                :              * there is a risk of deadlock which probably shouldn't happen
                               1995                 :                :              * after restart.
                               1996                 :                :              */
                               1997                 :            242 :             pa_decr_and_wait_stream_block();
                               1998                 :            240 :             break;
                               1999                 :                : 
 1350 akapila@postgresql.o     2000                 :UBC           0 :         default:
 1342                          2001         [ #  # ]:              0 :             elog(ERROR, "unexpected apply action: %d", (int) apply_action);
                               2002                 :                :             break;
                               2003                 :                :     }
                               2004                 :                : 
 1350 akapila@postgresql.o     2005                 :CBC         835 :     in_streamed_transaction = false;
 1342                          2006                 :            835 :     stream_xid = InvalidTransactionId;
                               2007                 :                : 
                               2008                 :                :     /*
                               2009                 :                :      * The parallel apply worker could be in a transaction in which case we
                               2010                 :                :      * need to report the state as STATE_IDLEINTRANSACTION.
                               2011                 :                :      */
 1350                          2012         [ +  + ]:            835 :     if (IsTransactionOrTransactionBlock())
                               2013                 :            240 :         pgstat_report_activity(STATE_IDLEINTRANSACTION, NULL);
                               2014                 :                :     else
                               2015                 :            595 :         pgstat_report_activity(STATE_IDLE, NULL);
                               2016                 :                : 
   25 akapila@postgresql.o     2017                 :GNC         835 :     reset_apply_remote_context();
 1350 akapila@postgresql.o     2018                 :CBC         835 : }
                               2019                 :                : 
                               2020                 :                : /*
                               2021                 :                :  * Helper function to handle STREAM ABORT message when the transaction was
                               2022                 :                :  * serialized to file.
                               2023                 :                :  */
                               2024                 :                : static void
                               2025                 :             14 : stream_abort_internal(TransactionId xid, TransactionId subxid)
                               2026                 :                : {
                               2027                 :                :     /*
                               2028                 :                :      * If the two XIDs are the same, it's in fact abort of toplevel xact, so
                               2029                 :                :      * just delete the files with serialized info.
                               2030                 :                :      */
 2208                          2031         [ +  + ]:             14 :     if (xid == subxid)
                               2032                 :              1 :         stream_cleanup_files(MyLogicalRepWorker->subid, xid);
                               2033                 :                :     else
                               2034                 :                :     {
                               2035                 :                :         /*
                               2036                 :                :          * OK, so it's a subxact. We need to read the subxact file for the
                               2037                 :                :          * toplevel transaction, determine the offset tracked for the subxact,
                               2038                 :                :          * and truncate the file with changes. We also remove the subxacts
                               2039                 :                :          * with higher offsets (or rather higher XIDs).
                               2040                 :                :          *
                               2041                 :                :          * We intentionally scan the array from the tail, because we're likely
                               2042                 :                :          * aborting a change for the most recent subtransactions.
                               2043                 :                :          *
                               2044                 :                :          * We can't use the binary search here as subxact XIDs won't
                               2045                 :                :          * necessarily arrive in sorted order, consider the case where we have
                               2046                 :                :          * released the savepoint for multiple subtransactions and then
                               2047                 :                :          * performed rollback to savepoint for one of the earlier
                               2048                 :                :          * sub-transaction.
                               2049                 :                :          */
                               2050                 :                :         int64       i;
                               2051                 :                :         int64       subidx;
                               2052                 :                :         BufFile    *fd;
                               2053                 :             13 :         bool        found = false;
                               2054                 :                :         char        path[MAXPGPATH];
                               2055                 :                : 
                               2056                 :             13 :         subidx = -1;
 1928 tgl@sss.pgh.pa.us        2057                 :             13 :         begin_replication_step();
 2208 akapila@postgresql.o     2058                 :             13 :         subxact_info_read(MyLogicalRepWorker->subid, xid);
                               2059                 :                : 
                               2060         [ +  + ]:             15 :         for (i = subxact_data.nsubxacts; i > 0; i--)
                               2061                 :                :         {
                               2062         [ +  + ]:             11 :             if (subxact_data.subxacts[i - 1].xid == subxid)
                               2063                 :                :             {
                               2064                 :              9 :                 subidx = (i - 1);
                               2065                 :              9 :                 found = true;
                               2066                 :              9 :                 break;
                               2067                 :                :             }
                               2068                 :                :         }
                               2069                 :                : 
                               2070                 :                :         /*
                               2071                 :                :          * If it's an empty sub-transaction then we will not find the subxid
                               2072                 :                :          * here so just cleanup the subxact info and return.
                               2073                 :                :          */
                               2074         [ +  + ]:             13 :         if (!found)
                               2075                 :                :         {
                               2076                 :                :             /* Cleanup the subxact info */
                               2077                 :              4 :             cleanup_subxact_info();
 1928 tgl@sss.pgh.pa.us        2078                 :              4 :             end_replication_step();
 2046 akapila@postgresql.o     2079                 :              4 :             CommitTransactionCommand();
 2208                          2080                 :              4 :             return;
                               2081                 :                :         }
                               2082                 :                : 
                               2083                 :                :         /* open the changes file */
 1350                          2084                 :              9 :         changes_filename(path, MyLogicalRepWorker->subid, xid);
                               2085                 :              9 :         fd = BufFileOpenFileSet(MyLogicalRepWorker->stream_fileset, path,
                               2086                 :                :                                 O_RDWR, false);
                               2087                 :                : 
                               2088                 :                :         /* OK, truncate the file at the right offset */
                               2089                 :              9 :         BufFileTruncateFileSet(fd, subxact_data.subxacts[subidx].fileno,
                               2090                 :              9 :                                subxact_data.subxacts[subidx].offset);
                               2091                 :              9 :         BufFileClose(fd);
                               2092                 :                : 
                               2093                 :                :         /* discard the subxacts added later */
                               2094                 :              9 :         subxact_data.nsubxacts = subidx;
                               2095                 :                : 
                               2096                 :                :         /* write the updated subxact list */
                               2097                 :              9 :         subxact_info_write(MyLogicalRepWorker->subid, xid);
                               2098                 :                : 
                               2099                 :              9 :         end_replication_step();
                               2100                 :              9 :         CommitTransactionCommand();
                               2101                 :                :     }
                               2102                 :                : }
                               2103                 :                : 
                               2104                 :                : /*
                               2105                 :                :  * Handle STREAM ABORT message.
                               2106                 :                :  */
                               2107                 :                : static void
                               2108                 :             38 : apply_handle_stream_abort(StringInfo s)
                               2109                 :                : {
                               2110                 :                :     TransactionId xid;
                               2111                 :                :     TransactionId subxid;
                               2112                 :                :     LogicalRepStreamAbortData abort_data;
                               2113                 :                :     ParallelApplyWorkerInfo *winfo;
                               2114                 :                :     TransApplyAction apply_action;
                               2115                 :                : 
                               2116                 :                :     /* Save the message before it is consumed. */
                               2117                 :             38 :     StringInfoData original_msg = *s;
                               2118                 :                :     bool        toplevel_xact;
                               2119                 :                : 
                               2120         [ -  + ]:             38 :     if (in_streamed_transaction)
 1350 akapila@postgresql.o     2121         [ #  # ]:UBC           0 :         ereport(ERROR,
                               2122                 :                :                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
                               2123                 :                :                  errmsg_internal("STREAM ABORT message without STREAM STOP")));
                               2124                 :                : 
                               2125                 :                :     /* We receive abort information only when we can apply in parallel. */
 1350 akapila@postgresql.o     2126                 :CBC          38 :     logicalrep_read_stream_abort(s, &abort_data,
                               2127                 :             38 :                                  MyLogicalRepWorker->parallel_apply);
                               2128                 :                : 
                               2129                 :             38 :     xid = abort_data.xid;
                               2130                 :             38 :     subxid = abort_data.subxid;
                               2131                 :             38 :     toplevel_xact = (xid == subxid);
                               2132                 :                : 
                               2133                 :                :     /*
                               2134                 :                :      * Record the xid of the (sub)transaction being aborted, so that the error
                               2135                 :                :      * context names whatever failed. Note this is the top-level xid itself
                               2136                 :                :      * when a top-level transaction aborts, and a subxid only when a
                               2137                 :                :      * subtransaction rolls back. See set_remote_transaction_info().
                               2138                 :                :      */
   25 akapila@postgresql.o     2139                 :GNC          38 :     set_remote_transaction_info(subxid, abort_data.abort_lsn);
                               2140                 :                : 
 1350 akapila@postgresql.o     2141                 :CBC          38 :     apply_action = get_transaction_apply_action(xid, &winfo);
                               2142                 :                : 
                               2143   [ +  +  +  +  :             38 :     switch (apply_action)
                                                 - ]
                               2144                 :                :     {
 1342                          2145                 :             14 :         case TRANS_LEADER_APPLY:
                               2146                 :                : 
                               2147                 :                :             /*
                               2148                 :                :              * We are in the leader apply worker and the transaction has been
                               2149                 :                :              * serialized to file.
                               2150                 :                :              */
 1350                          2151                 :             14 :             stream_abort_internal(xid, subxid);
                               2152                 :                : 
                               2153         [ -  + ]:             14 :             elog(DEBUG1, "finished processing the STREAM ABORT command");
                               2154                 :             14 :             break;
                               2155                 :                : 
                               2156                 :             10 :         case TRANS_LEADER_SEND_TO_PARALLEL:
                               2157         [ -  + ]:             10 :             Assert(winfo);
                               2158                 :                : 
                               2159                 :                :             /*
                               2160                 :                :              * For the case of aborting the subtransaction, we increment the
                               2161                 :                :              * number of streaming blocks and take the lock again before
                               2162                 :                :              * sending the STREAM_ABORT to ensure that the parallel apply
                               2163                 :                :              * worker will wait on the lock for the next set of changes after
                               2164                 :                :              * processing the STREAM_ABORT message if it is not already
                               2165                 :                :              * waiting for STREAM_STOP message.
                               2166                 :                :              *
                               2167                 :                :              * It is important to perform this locking before sending the
                               2168                 :                :              * STREAM_ABORT message so that the leader can hold the lock first
                               2169                 :                :              * and the parallel apply worker will wait for the leader to
                               2170                 :                :              * release the lock. This is the same as what we do in
                               2171                 :                :              * apply_handle_stream_stop. See Locking Considerations atop
                               2172                 :                :              * applyparallelworker.c.
                               2173                 :                :              */
                               2174         [ +  + ]:             10 :             if (!toplevel_xact)
                               2175                 :                :             {
                               2176                 :              9 :                 pa_unlock_stream(xid, AccessExclusiveLock);
                               2177                 :              9 :                 pg_atomic_add_fetch_u32(&winfo->shared->pending_stream_count, 1);
                               2178                 :              9 :                 pa_lock_stream(xid, AccessExclusiveLock);
                               2179                 :                :             }
                               2180                 :                : 
                               2181         [ +  - ]:             10 :             if (pa_send_data(winfo, s->len, s->data))
                               2182                 :                :             {
                               2183                 :                :                 /*
                               2184                 :                :                  * Unlike STREAM_COMMIT and STREAM_PREPARE, we don't need to
                               2185                 :                :                  * wait here for the parallel apply worker to finish as that
                               2186                 :                :                  * is not required to maintain the commit order and won't have
                               2187                 :                :                  * the risk of failures due to transaction dependencies and
                               2188                 :                :                  * deadlocks. However, it is possible that before the parallel
                               2189                 :                :                  * worker finishes and we clear the worker info, the xid
                               2190                 :                :                  * wraparound happens on the upstream and a new transaction
                               2191                 :                :                  * with the same xid can appear and that can lead to duplicate
                               2192                 :                :                  * entries in ParallelApplyTxnHash. Yet another problem could
                               2193                 :                :                  * be that we may have serialized the changes in partial
                               2194                 :                :                  * serialize mode and the file containing xact changes may
                               2195                 :                :                  * already exist, and after xid wraparound trying to create
                               2196                 :                :                  * the file for the same xid can lead to an error. To avoid
                               2197                 :                :                  * these problems, we decide to wait for the aborts to finish.
                               2198                 :                :                  *
                               2199                 :                :                  * Note, it is okay to not update the flush location position
                               2200                 :                :                  * for aborts as in worst case that means such a transaction
                               2201                 :                :                  * won't be sent again after restart.
                               2202                 :                :                  */
                               2203         [ +  + ]:             10 :                 if (toplevel_xact)
                               2204                 :              1 :                     pa_xact_finish(winfo, InvalidXLogRecPtr);
                               2205                 :                : 
                               2206                 :             10 :                 break;
                               2207                 :                :             }
                               2208                 :                : 
                               2209                 :                :             /*
                               2210                 :                :              * Switch to serialize mode when we are not able to send the
                               2211                 :                :              * change to parallel apply worker.
                               2212                 :                :              */
 1350 akapila@postgresql.o     2213                 :UBC           0 :             pa_switch_to_partial_serialize(winfo, true);
                               2214                 :                : 
                               2215                 :                :             pg_fallthrough;
 1350 akapila@postgresql.o     2216                 :CBC           2 :         case TRANS_LEADER_PARTIAL_SERIALIZE:
                               2217         [ -  + ]:              2 :             Assert(winfo);
                               2218                 :                : 
                               2219                 :                :             /*
                               2220                 :                :              * Parallel apply worker might have applied some changes, so write
                               2221                 :                :              * the STREAM_ABORT message so that it can rollback the
                               2222                 :                :              * subtransaction if needed.
                               2223                 :                :              */
                               2224                 :              2 :             stream_open_and_write_change(xid, LOGICAL_REP_MSG_STREAM_ABORT,
                               2225                 :                :                                          &original_msg);
                               2226                 :                : 
                               2227         [ +  + ]:              2 :             if (toplevel_xact)
                               2228                 :                :             {
                               2229                 :              1 :                 pa_set_fileset_state(winfo->shared, FS_SERIALIZE_DONE);
                               2230                 :              1 :                 pa_xact_finish(winfo, InvalidXLogRecPtr);
                               2231                 :                :             }
                               2232                 :              2 :             break;
                               2233                 :                : 
                               2234                 :             12 :         case TRANS_PARALLEL_APPLY:
                               2235                 :                : 
                               2236                 :                :             /*
                               2237                 :                :              * If the parallel apply worker is applying spooled messages then
                               2238                 :                :              * close the file before aborting.
                               2239                 :                :              */
                               2240   [ +  +  +  + ]:             12 :             if (toplevel_xact && stream_fd)
                               2241                 :              1 :                 stream_close_file();
                               2242                 :                : 
                               2243                 :             12 :             pa_stream_abort(&abort_data);
                               2244                 :                : 
                               2245                 :                :             /*
                               2246                 :                :              * We need to wait after processing rollback to savepoint for the
                               2247                 :                :              * next set of changes.
                               2248                 :                :              *
                               2249                 :                :              * We have a race condition here due to which we can start waiting
                               2250                 :                :              * here when there are more chunk of streams in the queue. See
                               2251                 :                :              * apply_handle_stream_stop.
                               2252                 :                :              */
                               2253         [ +  + ]:             12 :             if (!toplevel_xact)
                               2254                 :             10 :                 pa_decr_and_wait_stream_block();
                               2255                 :                : 
                               2256         [ +  + ]:             12 :             elog(DEBUG1, "finished processing the STREAM ABORT command");
                               2257                 :             12 :             break;
                               2258                 :                : 
 1350 akapila@postgresql.o     2259                 :UBC           0 :         default:
 1342                          2260         [ #  # ]:              0 :             elog(ERROR, "unexpected apply action: %d", (int) apply_action);
                               2261                 :                :             break;
                               2262                 :                :     }
                               2263                 :                : 
   25 akapila@postgresql.o     2264                 :GNC          38 :     reset_apply_remote_context();
 1350 akapila@postgresql.o     2265                 :CBC          38 : }
                               2266                 :                : 
                               2267                 :                : /*
                               2268                 :                :  * Ensure that the passed location is fileset's end.
                               2269                 :                :  */
                               2270                 :                : static void
                               2271                 :              4 : ensure_last_message(FileSet *stream_fileset, TransactionId xid, int fileno,
                               2272                 :                :                     pgoff_t offset)
                               2273                 :                : {
                               2274                 :                :     char        path[MAXPGPATH];
                               2275                 :                :     BufFile    *fd;
                               2276                 :                :     int         last_fileno;
                               2277                 :                :     pgoff_t     last_offset;
                               2278                 :                : 
                               2279         [ -  + ]:              4 :     Assert(!IsTransactionState());
                               2280                 :                : 
                               2281                 :              4 :     begin_replication_step();
                               2282                 :                : 
                               2283                 :              4 :     changes_filename(path, MyLogicalRepWorker->subid, xid);
                               2284                 :                : 
                               2285                 :              4 :     fd = BufFileOpenFileSet(stream_fileset, path, O_RDONLY, false);
                               2286                 :                : 
                               2287                 :              4 :     BufFileSeek(fd, 0, 0, SEEK_END);
                               2288                 :              4 :     BufFileTell(fd, &last_fileno, &last_offset);
                               2289                 :                : 
                               2290                 :              4 :     BufFileClose(fd);
                               2291                 :                : 
                               2292                 :              4 :     end_replication_step();
                               2293                 :                : 
                               2294   [ +  -  -  + ]:              4 :     if (last_fileno != fileno || last_offset != offset)
 1350 akapila@postgresql.o     2295         [ #  # ]:UBC           0 :         elog(ERROR, "unexpected message left in streaming transaction's changes file \"%s\"",
                               2296                 :                :              path);
 2208 akapila@postgresql.o     2297                 :CBC           4 : }
                               2298                 :                : 
                               2299                 :                : /*
                               2300                 :                :  * Common spoolfile processing.
                               2301                 :                :  */
                               2302                 :                : void
 1350                          2303                 :             31 : apply_spooled_messages(FileSet *stream_fileset, TransactionId xid,
                               2304                 :                :                        XLogRecPtr lsn)
                               2305                 :                : {
                               2306                 :                :     int         nchanges;
                               2307                 :                :     char        path[MAXPGPATH];
 2208                          2308                 :             31 :     char       *buffer = NULL;
                               2309                 :                :     MemoryContext oldcxt;
                               2310                 :                :     ResourceOwner oldowner;
                               2311                 :                :     int         fileno;
                               2312                 :                :     pgoff_t     offset;
                               2313                 :                : 
 1350                          2314         [ +  + ]:             31 :     if (!am_parallel_apply_worker())
                               2315                 :             27 :         maybe_start_skipping_changes(lsn);
                               2316                 :                : 
                               2317                 :                :     /* Make sure we have an open transaction */
 1928 tgl@sss.pgh.pa.us        2318                 :             31 :     begin_replication_step();
                               2319                 :                : 
                               2320                 :                :     /*
                               2321                 :                :      * Allocate file handle and memory required to process all the messages in
                               2322                 :                :      * TopTransactionContext to avoid them getting reset after each message is
                               2323                 :                :      * processed.
                               2324                 :                :      */
 2208 akapila@postgresql.o     2325                 :             31 :     oldcxt = MemoryContextSwitchTo(TopTransactionContext);
                               2326                 :                : 
                               2327                 :                :     /* Open the spool file for the committed/prepared transaction */
                               2328                 :             31 :     changes_filename(path, MyLogicalRepWorker->subid, xid);
                               2329         [ -  + ]:             31 :     elog(DEBUG1, "replaying changes from file \"%s\"", path);
                               2330                 :                : 
                               2331                 :                :     /*
                               2332                 :                :      * Make sure the file is owned by the toplevel transaction so that the
                               2333                 :                :      * file will not be accidentally closed when aborting a subtransaction.
                               2334                 :                :      */
 1350                          2335                 :             31 :     oldowner = CurrentResourceOwner;
                               2336                 :             31 :     CurrentResourceOwner = TopTransactionResourceOwner;
                               2337                 :                : 
                               2338                 :             31 :     stream_fd = BufFileOpenFileSet(stream_fileset, path, O_RDONLY, false);
                               2339                 :                : 
                               2340                 :             31 :     CurrentResourceOwner = oldowner;
                               2341                 :                : 
 2208                          2342                 :             31 :     buffer = palloc(BLCKSZ);
                               2343                 :                : 
                               2344                 :             31 :     MemoryContextSwitchTo(oldcxt);
                               2345                 :                : 
                               2346                 :                :     /*
                               2347                 :                :      * Make sure the handle apply_dispatch methods are aware we're in a remote
                               2348                 :                :      * transaction.
                               2349                 :                :      */
                               2350                 :             31 :     in_remote_transaction = true;
                               2351                 :             31 :     pgstat_report_activity(STATE_RUNNING, NULL);
                               2352                 :                : 
 1928 tgl@sss.pgh.pa.us        2353                 :             31 :     end_replication_step();
                               2354                 :                : 
                               2355                 :                :     /*
                               2356                 :                :      * Read the entries one by one and pass them through the same logic as in
                               2357                 :                :      * apply_dispatch.
                               2358                 :                :      */
 2208 akapila@postgresql.o     2359                 :             31 :     nchanges = 0;
                               2360                 :                :     while (true)
                               2361                 :          88471 :     {
                               2362                 :                :         StringInfoData s2;
                               2363                 :                :         size_t      nbytes;
                               2364                 :                :         int         len;
                               2365                 :                : 
                               2366         [ -  + ]:          88502 :         CHECK_FOR_INTERRUPTS();
                               2367                 :                : 
                               2368                 :                :         /* read length of the on-disk record */
 1343 peter@eisentraut.org     2369                 :          88502 :         nbytes = BufFileReadMaybeEOF(stream_fd, &len, sizeof(len), true);
                               2370                 :                : 
                               2371                 :                :         /* have we reached end of the file? */
 2208 akapila@postgresql.o     2372         [ +  + ]:          88502 :         if (nbytes == 0)
                               2373                 :             26 :             break;
                               2374                 :                : 
                               2375                 :                :         /* do we have a correct length? */
 1926 tgl@sss.pgh.pa.us        2376         [ -  + ]:          88476 :         if (len <= 0)
 1926 tgl@sss.pgh.pa.us        2377         [ #  # ]:UBC           0 :             elog(ERROR, "incorrect length %d in streaming transaction's changes file \"%s\"",
                               2378                 :                :                  len, path);
                               2379                 :                : 
                               2380                 :                :         /* make sure we have sufficiently large buffer */
 2208 akapila@postgresql.o     2381                 :CBC       88476 :         buffer = repalloc(buffer, len);
                               2382                 :                : 
                               2383                 :                :         /* and finally read the data into the buffer */
 1343 peter@eisentraut.org     2384                 :          88476 :         BufFileReadExact(stream_fd, buffer, len);
                               2385                 :                : 
 1350 akapila@postgresql.o     2386                 :          88476 :         BufFileTell(stream_fd, &fileno, &offset);
                               2387                 :                : 
                               2388                 :                :         /* init a stringinfo using the buffer and call apply_dispatch */
 1048 drowley@postgresql.o     2389                 :          88476 :         initReadOnlyStringInfo(&s2, buffer, len);
                               2390                 :                : 
                               2391                 :                :         /* Ensure we are reading the data into our memory context. */
 2208 akapila@postgresql.o     2392                 :          88476 :         oldcxt = MemoryContextSwitchTo(ApplyMessageContext);
                               2393                 :                : 
                               2394                 :          88476 :         apply_dispatch(&s2);
                               2395                 :                : 
                               2396                 :          88475 :         MemoryContextReset(ApplyMessageContext);
                               2397                 :                : 
                               2398                 :          88475 :         MemoryContextSwitchTo(oldcxt);
                               2399                 :                : 
                               2400                 :          88475 :         nchanges++;
                               2401                 :                : 
                               2402                 :                :         /*
                               2403                 :                :          * It is possible the file has been closed because we have processed
                               2404                 :                :          * the transaction end message like stream_commit in which case that
                               2405                 :                :          * must be the last message.
                               2406                 :                :          */
 1350                          2407         [ +  + ]:          88475 :         if (!stream_fd)
                               2408                 :                :         {
                               2409                 :              4 :             ensure_last_message(stream_fileset, xid, fileno, offset);
                               2410                 :              4 :             break;
                               2411                 :                :         }
                               2412                 :                : 
 2208                          2413         [ +  + ]:          88471 :         if (nchanges % 1000 == 0)
 1926 tgl@sss.pgh.pa.us        2414         [ -  + ]:             84 :             elog(DEBUG1, "replayed %d changes from file \"%s\"",
                               2415                 :                :                  nchanges, path);
                               2416                 :                :     }
                               2417                 :                : 
 1350 akapila@postgresql.o     2418         [ +  + ]:             30 :     if (stream_fd)
                               2419                 :             26 :         stream_close_file();
                               2420                 :                : 
 2208                          2421         [ -  + ]:             30 :     elog(DEBUG1, "replayed %d (all) changes from file \"%s\"",
                               2422                 :                :          nchanges, path);
                               2423                 :                : 
 1879                          2424                 :             30 :     return;
                               2425                 :                : }
                               2426                 :                : 
                               2427                 :                : /*
                               2428                 :                :  * Handle STREAM COMMIT message.
                               2429                 :                :  */
                               2430                 :                : static void
                               2431                 :             59 : apply_handle_stream_commit(StringInfo s)
                               2432                 :                : {
                               2433                 :                :     TransactionId xid;
                               2434                 :                :     LogicalRepCommitData commit_data;
                               2435                 :                :     ParallelApplyWorkerInfo *winfo;
                               2436                 :                :     TransApplyAction apply_action;
                               2437                 :                : 
                               2438                 :                :     /* Save the message before it is consumed. */
 1350                          2439                 :             59 :     StringInfoData original_msg = *s;
                               2440                 :                : 
 1879                          2441         [ -  + ]:             59 :     if (in_streamed_transaction)
 1879 akapila@postgresql.o     2442         [ #  # ]:UBC           0 :         ereport(ERROR,
                               2443                 :                :                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
                               2444                 :                :                  errmsg_internal("STREAM COMMIT message without STREAM STOP")));
                               2445                 :                : 
 1879 akapila@postgresql.o     2446                 :CBC          59 :     xid = logicalrep_read_stream_commit(s, &commit_data);
   25 akapila@postgresql.o     2447                 :GNC          59 :     set_remote_transaction_info(xid, commit_data.commit_lsn);
                               2448                 :                : 
 1350 akapila@postgresql.o     2449                 :CBC          59 :     apply_action = get_transaction_apply_action(xid, &winfo);
                               2450                 :                : 
                               2451   [ +  +  +  +  :             59 :     switch (apply_action)
                                                 - ]
                               2452                 :                :     {
 1342                          2453                 :             22 :         case TRANS_LEADER_APPLY:
                               2454                 :                : 
                               2455                 :                :             /*
                               2456                 :                :              * The transaction has been serialized to file, so replay all the
                               2457                 :                :              * spooled operations.
                               2458                 :                :              */
 1350                          2459                 :             22 :             apply_spooled_messages(MyLogicalRepWorker->stream_fileset, xid,
                               2460                 :                :                                    commit_data.commit_lsn);
                               2461                 :                : 
                               2462                 :             21 :             apply_handle_commit_internal(&commit_data);
                               2463                 :                : 
                               2464                 :                :             /* Unlink the files with serialized changes and subxact info. */
                               2465                 :             21 :             stream_cleanup_files(MyLogicalRepWorker->subid, xid);
                               2466                 :                : 
                               2467         [ -  + ]:             21 :             elog(DEBUG1, "finished processing the STREAM COMMIT command");
                               2468                 :             21 :             break;
                               2469                 :                : 
                               2470                 :             17 :         case TRANS_LEADER_SEND_TO_PARALLEL:
                               2471         [ -  + ]:             17 :             Assert(winfo);
                               2472                 :                : 
                               2473         [ +  - ]:             17 :             if (pa_send_data(winfo, s->len, s->data))
                               2474                 :                :             {
                               2475                 :                :                 /* Finish processing the streaming transaction. */
                               2476                 :             17 :                 pa_xact_finish(winfo, commit_data.end_lsn);
                               2477                 :             16 :                 break;
                               2478                 :                :             }
                               2479                 :                : 
                               2480                 :                :             /*
                               2481                 :                :              * Switch to serialize mode when we are not able to send the
                               2482                 :                :              * change to parallel apply worker.
                               2483                 :                :              */
 1350 akapila@postgresql.o     2484                 :UBC           0 :             pa_switch_to_partial_serialize(winfo, true);
                               2485                 :                : 
                               2486                 :                :             pg_fallthrough;
 1350 akapila@postgresql.o     2487                 :CBC           2 :         case TRANS_LEADER_PARTIAL_SERIALIZE:
                               2488         [ -  + ]:              2 :             Assert(winfo);
                               2489                 :                : 
                               2490                 :              2 :             stream_open_and_write_change(xid, LOGICAL_REP_MSG_STREAM_COMMIT,
                               2491                 :                :                                          &original_msg);
                               2492                 :                : 
                               2493                 :              2 :             pa_set_fileset_state(winfo->shared, FS_SERIALIZE_DONE);
                               2494                 :                : 
                               2495                 :                :             /* Finish processing the streaming transaction. */
                               2496                 :              2 :             pa_xact_finish(winfo, commit_data.end_lsn);
                               2497                 :              2 :             break;
                               2498                 :                : 
                               2499                 :             18 :         case TRANS_PARALLEL_APPLY:
                               2500                 :                : 
                               2501                 :                :             /*
                               2502                 :                :              * If the parallel apply worker is applying spooled messages then
                               2503                 :                :              * close the file before committing.
                               2504                 :                :              */
                               2505         [ +  + ]:             18 :             if (stream_fd)
                               2506                 :              2 :                 stream_close_file();
                               2507                 :                : 
                               2508                 :             18 :             apply_handle_commit_internal(&commit_data);
                               2509                 :                : 
                               2510                 :             18 :             MyParallelShared->last_commit_end = XactLastCommitEnd;
                               2511                 :                : 
                               2512                 :                :             /*
                               2513                 :                :              * It is important to set the transaction state as finished before
                               2514                 :                :              * releasing the lock. See pa_wait_for_xact_finish.
                               2515                 :                :              */
                               2516                 :             18 :             pa_set_xact_state(MyParallelShared, PARALLEL_TRANS_FINISHED);
                               2517                 :             18 :             pa_unlock_transaction(xid, AccessExclusiveLock);
                               2518                 :                : 
                               2519                 :             18 :             pa_reset_subtrans();
                               2520                 :                : 
                               2521         [ +  + ]:             18 :             elog(DEBUG1, "finished processing the STREAM COMMIT command");
                               2522                 :             18 :             break;
                               2523                 :                : 
 1350 akapila@postgresql.o     2524                 :UBC           0 :         default:
 1342                          2525         [ #  # ]:              0 :             elog(ERROR, "unexpected apply action: %d", (int) apply_action);
                               2526                 :                :             break;
                               2527                 :                :     }
                               2528                 :                : 
                               2529                 :                :     /*
                               2530                 :                :      * Process any tables that are being synchronized in parallel, as well as
                               2531                 :                :      * any newly added tables or sequences.
                               2532                 :                :      */
  339 akapila@postgresql.o     2533                 :CBC          57 :     ProcessSyncingRelations(commit_data.end_lsn);
                               2534                 :                : 
 2208                          2535                 :             57 :     pgstat_report_activity(STATE_IDLE, NULL);
                               2536                 :                : 
   25 akapila@postgresql.o     2537                 :GNC          57 :     reset_apply_remote_context();
 2208 akapila@postgresql.o     2538                 :CBC          57 : }
                               2539                 :                : 
                               2540                 :                : /*
                               2541                 :                :  * Helper function for apply_handle_commit and apply_handle_stream_commit.
                               2542                 :                :  */
                               2543                 :                : static void
 1878                          2544                 :            492 : apply_handle_commit_internal(LogicalRepCommitData *commit_data)
                               2545                 :                : {
 1643                          2546         [ +  + ]:            492 :     if (is_skipping_changes())
                               2547                 :                :     {
                               2548                 :              2 :         stop_skipping_changes();
                               2549                 :                : 
                               2550                 :                :         /*
                               2551                 :                :          * Start a new transaction to clear the subskiplsn, if not started
                               2552                 :                :          * yet.
                               2553                 :                :          */
                               2554         [ +  + ]:              2 :         if (!IsTransactionState())
                               2555                 :              1 :             StartTransactionCommand();
                               2556                 :                :     }
                               2557                 :                : 
 2046                          2558         [ +  - ]:            492 :     if (IsTransactionState())
                               2559                 :                :     {
                               2560                 :                :         /*
                               2561                 :                :          * The transaction is either non-empty or skipped, so we clear the
                               2562                 :                :          * subskiplsn.
                               2563                 :                :          */
 1643                          2564                 :            492 :         clear_subscription_skip_lsn(commit_data->commit_lsn);
                               2565                 :                : 
                               2566                 :                :         /*
                               2567                 :                :          * Update origin state so we can restart streaming from correct
                               2568                 :                :          * position in case of crash.
                               2569                 :                :          */
  235 msawada@postgresql.o     2570                 :            492 :         replorigin_xact_state.origin_lsn = commit_data->end_lsn;
                               2571                 :            492 :         replorigin_xact_state.origin_timestamp = commit_data->committime;
                               2572                 :                : 
 2123 akapila@postgresql.o     2573                 :            492 :         CommitTransactionCommand();
                               2574                 :                : 
 1350                          2575         [ +  + ]:            492 :         if (IsTransactionBlock())
                               2576                 :                :         {
                               2577                 :              4 :             EndTransactionBlock(false);
                               2578                 :              4 :             CommitTransactionCommand();
                               2579                 :                :         }
                               2580                 :                : 
 2123                          2581                 :            492 :         pgstat_report_stat(false);
                               2582                 :                : 
 1350                          2583                 :            492 :         store_flush_position(commit_data->end_lsn, XactLastCommitEnd);
                               2584                 :                :     }
                               2585                 :                :     else
                               2586                 :                :     {
                               2587                 :                :         /* Process any invalidation messages that might have accumulated. */
 2123 akapila@postgresql.o     2588                 :UBC           0 :         AcceptInvalidationMessages();
                               2589                 :              0 :         maybe_reread_subscription();
                               2590                 :                :     }
                               2591                 :                : 
 2123 akapila@postgresql.o     2592                 :CBC         492 :     in_remote_transaction = false;
                               2593                 :            492 : }
                               2594                 :                : 
                               2595                 :                : /*
                               2596                 :                :  * Handle RELATION message.
                               2597                 :                :  *
                               2598                 :                :  * Note we don't do validation against local schema here. The validation
                               2599                 :                :  * against local schema is postponed until first change for given relation
                               2600                 :                :  * comes as we only care about it when applying changes for it anyway and we
                               2601                 :                :  * do less locking this way.
                               2602                 :                :  */
                               2603                 :                : static void
 3531 peter_e@gmx.net          2604                 :            505 : apply_handle_relation(StringInfo s)
                               2605                 :                : {
                               2606                 :                :     LogicalRepRelation *rel;
                               2607                 :                : 
 2124 akapila@postgresql.o     2608         [ +  + ]:            505 :     if (handle_streamed_transaction(LOGICAL_REP_MSG_RELATION, s))
 2208                          2609                 :             37 :         return;
                               2610                 :                : 
 3531 peter_e@gmx.net          2611                 :            468 :     rel = logicalrep_read_rel(s);
                               2612                 :            468 :     logicalrep_relmap_update(rel);
                               2613                 :                : 
                               2614                 :                :     /* Also reset all entries in the partition map that refer to remoterel. */
 1557 akapila@postgresql.o     2615                 :            468 :     logicalrep_partmap_reset_relmap(rel);
                               2616                 :                : }
                               2617                 :                : 
                               2618                 :                : /*
                               2619                 :                :  * Handle TYPE message.
                               2620                 :                :  *
                               2621                 :                :  * This implementation pays no attention to TYPE messages; we expect the user
                               2622                 :                :  * to have set things up so that the incoming data is acceptable to the input
                               2623                 :                :  * functions for the locally subscribed tables.  Hence, we just read and
                               2624                 :                :  * discard the message.
                               2625                 :                :  */
                               2626                 :                : static void
 3531 peter_e@gmx.net          2627                 :             18 : apply_handle_type(StringInfo s)
                               2628                 :                : {
                               2629                 :                :     LogicalRepTyp typ;
                               2630                 :                : 
 2124 akapila@postgresql.o     2631         [ -  + ]:             18 :     if (handle_streamed_transaction(LOGICAL_REP_MSG_TYPE, s))
 2208 akapila@postgresql.o     2632                 :UBC           0 :         return;
                               2633                 :                : 
 3531 peter_e@gmx.net          2634                 :CBC          18 :     logicalrep_read_typ(s, &typ);
                               2635                 :                : }
                               2636                 :                : 
                               2637                 :                : /*
                               2638                 :                :  * Check that we (the subscription owner) have sufficient privileges on the
                               2639                 :                :  * target relation to perform the given operation.
                               2640                 :                :  */
                               2641                 :                : static void
 1717 jdavis@postgresql.or     2642                 :         241006 : TargetPrivilegesCheck(Relation rel, AclMode mode)
                               2643                 :                : {
                               2644                 :                :     Oid         relid;
                               2645                 :                :     AclResult   aclresult;
                               2646                 :                : 
                               2647                 :         241006 :     relid = RelationGetRelid(rel);
                               2648                 :         241006 :     aclresult = pg_class_aclcheck(relid, GetUserId(), mode);
                               2649         [ +  + ]:         241006 :     if (aclresult != ACLCHECK_OK)
                               2650                 :              9 :         aclcheck_error(aclresult,
                               2651                 :              9 :                        get_relkind_objtype(rel->rd_rel->relkind),
                               2652                 :              9 :                        get_rel_name(relid));
                               2653                 :                : 
                               2654                 :                :     /*
                               2655                 :                :      * We lack the infrastructure to honor RLS policies.  It might be possible
                               2656                 :                :      * to add such infrastructure here, but tablesync workers lack it, too, so
                               2657                 :                :      * we don't bother.  RLS does not ordinarily apply to TRUNCATE commands,
                               2658                 :                :      * but it seems dangerous to replicate a TRUNCATE and then refuse to
                               2659                 :                :      * replicate subsequent INSERTs, so we forbid all commands the same.
                               2660                 :                :      */
                               2661         [ +  + ]:         240997 :     if (check_enable_rls(relid, InvalidOid, false) == RLS_ENABLED)
                               2662         [ +  - ]:              3 :         ereport(ERROR,
                               2663                 :                :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                               2664                 :                :                  errmsg("user \"%s\" cannot replicate into relation with row-level security enabled: \"%s\"",
                               2665                 :                :                         GetUserNameFromId(GetUserId(), true),
                               2666                 :                :                         RelationGetRelationName(rel))));
                               2667                 :         240994 : }
                               2668                 :                : 
                               2669                 :                : /*
                               2670                 :                :  * Handle INSERT message.
                               2671                 :                :  */
                               2672                 :                : 
                               2673                 :                : static void
 3531 peter_e@gmx.net          2674                 :         201573 : apply_handle_insert(StringInfo s)
                               2675                 :                : {
                               2676                 :                :     LogicalRepRelMapEntry *rel;
                               2677                 :                :     LogicalRepTupleData newtup;
                               2678                 :                :     LogicalRepRelId relid;
                               2679                 :                :     UserContext ucxt;
                               2680                 :                :     ApplyExecutionData *edata;
                               2681                 :                :     EState     *estate;
                               2682                 :                :     TupleTableSlot *remoteslot;
                               2683                 :                :     MemoryContext oldctx;
                               2684                 :                :     bool        run_as_owner;
                               2685                 :                : 
                               2686                 :                :     /*
                               2687                 :                :      * Quick return if we are skipping data modification changes or handling
                               2688                 :                :      * streamed transactions.
                               2689                 :                :      */
 1643 akapila@postgresql.o     2690   [ +  +  +  + ]:         393145 :     if (is_skipping_changes() ||
                               2691                 :         191572 :         handle_streamed_transaction(LOGICAL_REP_MSG_INSERT, s))
 2208                          2692                 :         105090 :         return;
                               2693                 :                : 
 1928 tgl@sss.pgh.pa.us        2694                 :          96564 :     begin_replication_step();
                               2695                 :                : 
 3531 peter_e@gmx.net          2696                 :          96562 :     relid = logicalrep_read_insert(s, &newtup);
                               2697                 :          96562 :     rel = logicalrep_rel_open(relid, RowExclusiveLock);
 3468                          2698         [ +  + ]:          96552 :     if (!should_apply_changes_for_rel(rel))
                               2699                 :                :     {
                               2700                 :                :         /*
                               2701                 :                :          * The relation can't become interesting in the middle of the
                               2702                 :                :          * transaction so it's safe to unlock it.
                               2703                 :                :          */
                               2704                 :             81 :         logicalrep_rel_close(rel, RowExclusiveLock);
 1928 tgl@sss.pgh.pa.us        2705                 :             81 :         end_replication_step();
 3468 peter_e@gmx.net          2706                 :             81 :         return;
                               2707                 :                :     }
                               2708                 :                : 
                               2709                 :                :     /*
                               2710                 :                :      * Make sure that any user-supplied code runs as the table owner, unless
                               2711                 :                :      * the user has opted out of that behavior.
                               2712                 :                :      */
 1265 rhaas@postgresql.org     2713                 :          96471 :     run_as_owner = MySubscription->runasowner;
                               2714         [ +  + ]:          96471 :     if (!run_as_owner)
                               2715                 :          96462 :         SwitchToUntrustedUser(rel->localrel->rd_rel->relowner, &ucxt);
                               2716                 :                : 
                               2717                 :                :     /* Set relation for error callback */
   25 akapila@postgresql.o     2718                 :GNC       96471 :     remote_ctx.rel = rel;
                               2719                 :                : 
                               2720                 :                :     /* Initialize the executor state. */
 1947 tgl@sss.pgh.pa.us        2721                 :CBC       96471 :     edata = create_edata_for_relation(rel);
                               2722                 :          96471 :     estate = edata->estate;
 3138 andres@anarazel.de       2723                 :          96471 :     remoteslot = ExecInitExtraTupleSlot(estate,
 2866                          2724                 :          96471 :                                         RelationGetDescr(rel->localrel),
                               2725                 :                :                                         &TTSOpsVirtual);
                               2726                 :                : 
                               2727                 :                :     /* Process and store remote tuple in the slot */
 3531 peter_e@gmx.net          2728         [ -  + ]:          96471 :     oldctx = MemoryContextSwitchTo(GetPerTupleMemoryContext(estate));
 2255 tgl@sss.pgh.pa.us        2729                 :          96471 :     slot_store_data(remoteslot, rel, &newtup);
 3531 peter_e@gmx.net          2730                 :          96471 :     slot_fill_defaults(rel, estate, remoteslot);
                               2731                 :          96471 :     MemoryContextSwitchTo(oldctx);
                               2732                 :                : 
                               2733                 :                :     /* For a partitioned table, insert the tuple into a partition. */
 2358 peter@eisentraut.org     2734         [ +  + ]:          96471 :     if (rel->localrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
 1947 tgl@sss.pgh.pa.us        2735                 :             75 :         apply_handle_tuple_routing(edata,
                               2736                 :                :                                    remoteslot, NULL, CMD_INSERT);
                               2737                 :                :     else
                               2738                 :                :     {
  578                          2739                 :          96396 :         ResultRelInfo *relinfo = edata->targetRelInfo;
                               2740                 :                : 
  530 akapila@postgresql.o     2741                 :          96396 :         ExecOpenIndices(relinfo, false);
  578 tgl@sss.pgh.pa.us        2742                 :          96396 :         apply_handle_insert_internal(edata, relinfo, remoteslot);
                               2743                 :          96379 :         ExecCloseIndices(relinfo);
                               2744                 :                :     }
                               2745                 :                : 
 1947                          2746                 :          96423 :     finish_edata(edata);
                               2747                 :                : 
                               2748                 :                :     /* Reset relation for error callback */
   25 akapila@postgresql.o     2749                 :GNC       96423 :     remote_ctx.rel = NULL;
                               2750                 :                : 
 1265 rhaas@postgresql.org     2751         [ +  + ]:CBC       96423 :     if (!run_as_owner)
                               2752                 :          96418 :         RestoreUserContext(&ucxt);
                               2753                 :                : 
 3531 peter_e@gmx.net          2754                 :          96423 :     logicalrep_rel_close(rel, NoLock);
                               2755                 :                : 
 1928 tgl@sss.pgh.pa.us        2756                 :          96423 :     end_replication_step();
                               2757                 :                : }
                               2758                 :                : 
                               2759                 :                : /*
                               2760                 :                :  * Workhorse for apply_handle_insert()
                               2761                 :                :  * relinfo is for the relation we're actually inserting into
                               2762                 :                :  * (could be a child partition of edata->targetRelInfo)
                               2763                 :                :  */
                               2764                 :                : static void
 1947                          2765                 :          96472 : apply_handle_insert_internal(ApplyExecutionData *edata,
                               2766                 :                :                              ResultRelInfo *relinfo,
                               2767                 :                :                              TupleTableSlot *remoteslot)
                               2768                 :                : {
                               2769                 :          96472 :     EState     *estate = edata->estate;
                               2770                 :                : 
                               2771                 :                :     /* Caller should have opened indexes already. */
  578                          2772   [ +  +  +  +  :          96472 :     Assert(relinfo->ri_IndexRelationDescs != NULL ||
                                              -  + ]
                               2773                 :                :            !relinfo->ri_RelationDesc->rd_rel->relhasindex ||
                               2774                 :                :            RelationGetIndexList(relinfo->ri_RelationDesc) == NIL);
                               2775                 :                : 
                               2776                 :                :     /* Caller will not have done this bit. */
                               2777         [ -  + ]:          96472 :     Assert(relinfo->ri_onConflictArbiterIndexes == NIL);
  761 akapila@postgresql.o     2778                 :          96472 :     InitConflictIndexes(relinfo);
                               2779                 :                : 
                               2780                 :                :     /* Do the insert. */
 1717 jdavis@postgresql.or     2781                 :          96472 :     TargetPrivilegesCheck(relinfo->ri_RelationDesc, ACL_INSERT);
 2167 heikki.linnakangas@i     2782                 :          96464 :     ExecSimpleRelationInsert(relinfo, estate, remoteslot);
 2371 peter@eisentraut.org     2783                 :          96424 : }
                               2784                 :                : 
                               2785                 :                : /*
                               2786                 :                :  * Check if the logical replication relation is updatable and throw
                               2787                 :                :  * appropriate error if it isn't.
                               2788                 :                :  */
                               2789                 :                : static void
 3531 peter_e@gmx.net          2790                 :          72292 : check_relation_updatable(LogicalRepRelMapEntry *rel)
                               2791                 :                : {
                               2792                 :                :     /*
                               2793                 :                :      * For partitioned tables, we only need to care if the target partition is
                               2794                 :                :      * updatable (aka has PK or RI defined for it).
                               2795                 :                :      */
 1552 akapila@postgresql.o     2796         [ +  + ]:          72292 :     if (rel->localrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
                               2797                 :             30 :         return;
                               2798                 :                : 
                               2799                 :                :     /* Updatable, no error. */
 3531 peter_e@gmx.net          2800         [ +  - ]:          72262 :     if (rel->updatable)
                               2801                 :          72262 :         return;
                               2802                 :                : 
                               2803                 :                :     /*
                               2804                 :                :      * We are in error mode so it's fine this is somewhat slow. It's better to
                               2805                 :                :      * give user correct error.
                               2806                 :                :      */
 3531 peter_e@gmx.net          2807         [ #  # ]:UBC           0 :     if (OidIsValid(GetRelationIdentityOrPK(rel->localrel)))
                               2808                 :                :     {
                               2809         [ #  # ]:              0 :         ereport(ERROR,
                               2810                 :                :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
                               2811                 :                :                  errmsg("publisher did not send replica identity column "
                               2812                 :                :                         "expected by the logical replication target relation \"%s.%s\"",
                               2813                 :                :                         rel->remoterel.nspname, rel->remoterel.relname)));
                               2814                 :                :     }
                               2815                 :                : 
                               2816         [ #  # ]:              0 :     ereport(ERROR,
                               2817                 :                :             (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
                               2818                 :                :              errmsg("logical replication target relation \"%s.%s\" has "
                               2819                 :                :                     "neither REPLICA IDENTITY index nor PRIMARY "
                               2820                 :                :                     "KEY and published relation does not have "
                               2821                 :                :                     "REPLICA IDENTITY FULL",
                               2822                 :                :                     rel->remoterel.nspname, rel->remoterel.relname)));
                               2823                 :                : }
                               2824                 :                : 
                               2825                 :                : /*
                               2826                 :                :  * Handle UPDATE message.
                               2827                 :                :  *
                               2828                 :                :  * TODO: FDW support
                               2829                 :                :  */
                               2830                 :                : static void
 3531 peter_e@gmx.net          2831                 :CBC       66165 : apply_handle_update(StringInfo s)
                               2832                 :                : {
                               2833                 :                :     LogicalRepRelMapEntry *rel;
                               2834                 :                :     LogicalRepRelId relid;
                               2835                 :                :     UserContext ucxt;
                               2836                 :                :     ApplyExecutionData *edata;
                               2837                 :                :     EState     *estate;
                               2838                 :                :     LogicalRepTupleData oldtup;
                               2839                 :                :     LogicalRepTupleData newtup;
                               2840                 :                :     bool        has_oldtup;
                               2841                 :                :     TupleTableSlot *remoteslot;
                               2842                 :                :     RTEPermissionInfo *target_perminfo;
                               2843                 :                :     MemoryContext oldctx;
                               2844                 :                :     bool        run_as_owner;
                               2845                 :                : 
                               2846                 :                :     /*
                               2847                 :                :      * Quick return if we are skipping data modification changes or handling
                               2848                 :                :      * streamed transactions.
                               2849                 :                :      */
 1643 akapila@postgresql.o     2850   [ +  +  +  + ]:         132327 :     if (is_skipping_changes() ||
                               2851                 :          66162 :         handle_streamed_transaction(LOGICAL_REP_MSG_UPDATE, s))
 2208                          2852                 :          34223 :         return;
                               2853                 :                : 
 1928 tgl@sss.pgh.pa.us        2854                 :          31942 :     begin_replication_step();
                               2855                 :                : 
 3531 peter_e@gmx.net          2856                 :          31941 :     relid = logicalrep_read_update(s, &has_oldtup, &oldtup,
                               2857                 :                :                                    &newtup);
                               2858                 :          31941 :     rel = logicalrep_rel_open(relid, RowExclusiveLock);
 3468                          2859         [ -  + ]:          31941 :     if (!should_apply_changes_for_rel(rel))
                               2860                 :                :     {
                               2861                 :                :         /*
                               2862                 :                :          * The relation can't become interesting in the middle of the
                               2863                 :                :          * transaction so it's safe to unlock it.
                               2864                 :                :          */
 3468 peter_e@gmx.net          2865                 :UBC           0 :         logicalrep_rel_close(rel, RowExclusiveLock);
 1928 tgl@sss.pgh.pa.us        2866                 :              0 :         end_replication_step();
 3468 peter_e@gmx.net          2867                 :              0 :         return;
                               2868                 :                :     }
                               2869                 :                : 
                               2870                 :                :     /* Set relation for error callback */
   25 akapila@postgresql.o     2871                 :GNC       31941 :     remote_ctx.rel = rel;
                               2872                 :                : 
                               2873                 :                :     /* Check if we can do the update. */
 3531 peter_e@gmx.net          2874                 :CBC       31941 :     check_relation_updatable(rel);
                               2875                 :                : 
                               2876                 :                :     /*
                               2877                 :                :      * Make sure that any user-supplied code runs as the table owner, unless
                               2878                 :                :      * the user has opted out of that behavior.
                               2879                 :                :      */
 1265 rhaas@postgresql.org     2880                 :          31941 :     run_as_owner = MySubscription->runasowner;
                               2881         [ +  + ]:          31941 :     if (!run_as_owner)
                               2882                 :          31938 :         SwitchToUntrustedUser(rel->localrel->rd_rel->relowner, &ucxt);
                               2883                 :                : 
                               2884                 :                :     /* Initialize the executor state. */
 1947 tgl@sss.pgh.pa.us        2885                 :          31940 :     edata = create_edata_for_relation(rel);
                               2886                 :          31940 :     estate = edata->estate;
 3138 andres@anarazel.de       2887                 :          31940 :     remoteslot = ExecInitExtraTupleSlot(estate,
 2866                          2888                 :          31940 :                                         RelationGetDescr(rel->localrel),
                               2889                 :                :                                         &TTSOpsVirtual);
                               2890                 :                : 
                               2891                 :                :     /*
                               2892                 :                :      * Populate updatedCols so that per-column triggers can fire, and so
                               2893                 :                :      * executor can correctly pass down indexUnchanged hint.  This could
                               2894                 :                :      * include more columns than were actually changed on the publisher
                               2895                 :                :      * because the logical replication protocol doesn't contain that
                               2896                 :                :      * information.  But it would for example exclude columns that only exist
                               2897                 :                :      * on the subscriber, since we are not touching those.
                               2898                 :                :      */
 1384 alvherre@alvh.no-ip.     2899                 :          31940 :     target_perminfo = list_nth(estate->es_rteperminfos, 0);
 2449 peter@eisentraut.org     2900         [ +  + ]:         159324 :     for (int i = 0; i < remoteslot->tts_tupleDescriptor->natts; i++)
                               2901                 :                :     {
  333 drowley@postgresql.o     2902                 :         127384 :         CompactAttribute *att = TupleDescCompactAttr(remoteslot->tts_tupleDescriptor, i);
 2253 tgl@sss.pgh.pa.us        2903                 :         127384 :         int         remoteattnum = rel->attrmap->attnums[i];
                               2904                 :                : 
                               2905   [ +  +  +  + ]:         127384 :         if (!att->attisdropped && remoteattnum >= 0)
                               2906                 :                :         {
  127 noah@leadboat.com        2907         [ -  + ]:          68867 :             if (remoteattnum >= newtup.ncols)
  127 noah@leadboat.com        2908         [ #  # ]:UBC           0 :                 ereport(ERROR,
                               2909                 :                :                         (errcode(ERRCODE_PROTOCOL_VIOLATION),
                               2910                 :                :                          errmsg_plural("logical replication column %d not found in tuple: only %d column received",
                               2911                 :                :                                        "logical replication column %d not found in tuple: only %d columns received",
                               2912                 :                :                                        newtup.ncols,
                               2913                 :                :                                        remoteattnum + 1, newtup.ncols)));
                               2914                 :                : 
 2253 tgl@sss.pgh.pa.us        2915         [ +  - ]:CBC       68867 :             if (newtup.colstatus[remoteattnum] != LOGICALREP_COLUMN_UNCHANGED)
 1384 alvherre@alvh.no-ip.     2916                 :          68867 :                 target_perminfo->updatedCols =
                               2917                 :          68867 :                     bms_add_member(target_perminfo->updatedCols,
                               2918                 :                :                                    i + 1 - FirstLowInvalidHeapAttributeNumber);
                               2919                 :                :         }
                               2920                 :                :     }
                               2921                 :                : 
                               2922                 :                :     /* Build the search tuple. */
 3531 peter_e@gmx.net          2923         [ -  + ]:          31940 :     oldctx = MemoryContextSwitchTo(GetPerTupleMemoryContext(estate));
 2255 tgl@sss.pgh.pa.us        2924                 :          31940 :     slot_store_data(remoteslot, rel,
                               2925         [ +  + ]:          31940 :                     has_oldtup ? &oldtup : &newtup);
 3531 peter_e@gmx.net          2926                 :          31940 :     MemoryContextSwitchTo(oldctx);
                               2927                 :                : 
                               2928                 :                :     /* For a partitioned table, apply update to correct partition. */
 2358 peter@eisentraut.org     2929         [ +  + ]:          31940 :     if (rel->localrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
 1947 tgl@sss.pgh.pa.us        2930                 :             13 :         apply_handle_tuple_routing(edata,
                               2931                 :                :                                    remoteslot, &newtup, CMD_UPDATE);
                               2932                 :                :     else
                               2933                 :          31927 :         apply_handle_update_internal(edata, edata->targetRelInfo,
                               2934                 :                :                                      remoteslot, &newtup, rel->localindexoid);
                               2935                 :                : 
                               2936                 :          31934 :     finish_edata(edata);
                               2937                 :                : 
                               2938                 :                :     /* Reset relation for error callback */
   25 akapila@postgresql.o     2939                 :GNC       31934 :     remote_ctx.rel = NULL;
                               2940                 :                : 
 1265 rhaas@postgresql.org     2941         [ +  + ]:CBC       31934 :     if (!run_as_owner)
                               2942                 :          31932 :         RestoreUserContext(&ucxt);
                               2943                 :                : 
 2371 peter@eisentraut.org     2944                 :          31934 :     logicalrep_rel_close(rel, NoLock);
                               2945                 :                : 
 1928 tgl@sss.pgh.pa.us        2946                 :          31934 :     end_replication_step();
                               2947                 :                : }
                               2948                 :                : 
                               2949                 :                : /*
                               2950                 :                :  * Workhorse for apply_handle_update()
                               2951                 :                :  * relinfo is for the relation we're actually updating in
                               2952                 :                :  * (could be a child partition of edata->targetRelInfo)
                               2953                 :                :  */
                               2954                 :                : static void
 1947                          2955                 :          31927 : apply_handle_update_internal(ApplyExecutionData *edata,
                               2956                 :                :                              ResultRelInfo *relinfo,
                               2957                 :                :                              TupleTableSlot *remoteslot,
                               2958                 :                :                              LogicalRepTupleData *newtup,
                               2959                 :                :                              Oid localindexoid)
                               2960                 :                : {
                               2961                 :          31927 :     EState     *estate = edata->estate;
                               2962                 :          31927 :     LogicalRepRelMapEntry *relmapentry = edata->targetRel;
 2371 peter@eisentraut.org     2963                 :          31927 :     Relation    localrel = relinfo->ri_RelationDesc;
                               2964                 :                :     EPQState    epqstate;
  545 akapila@postgresql.o     2965                 :          31927 :     TupleTableSlot *localslot = NULL;
                               2966                 :          31927 :     ConflictTupleInfo conflicttuple = {0};
                               2967                 :                :     bool        found;
                               2968                 :                :     MemoryContext oldctx;
                               2969                 :                : 
 1220 tgl@sss.pgh.pa.us        2970                 :          31927 :     EvalPlanQualInit(&epqstate, estate, NULL, NIL, -1, NIL);
  530 akapila@postgresql.o     2971                 :          31927 :     ExecOpenIndices(relinfo, false);
                               2972                 :                : 
 1153 msawada@postgresql.o     2973                 :          31927 :     found = FindReplTupleInLocalRel(edata, localrel,
                               2974                 :                :                                     &relmapentry->remoterel,
                               2975                 :                :                                     localindexoid,
                               2976                 :                :                                     remoteslot, &localslot);
                               2977                 :                : 
                               2978                 :                :     /*
                               2979                 :                :      * Tuple found.
                               2980                 :                :      *
                               2981                 :                :      * Note this will fail if there are other conflicting unique indexes.
                               2982                 :                :      */
 3531 peter_e@gmx.net          2983         [ +  + ]:          31923 :     if (found)
                               2984                 :                :     {
                               2985                 :                :         /*
                               2986                 :                :          * Report the conflict if the tuple was modified by a different
                               2987                 :                :          * origin.
                               2988                 :                :          */
  545 akapila@postgresql.o     2989         [ +  + ]:          31914 :         if (GetTupleTransactionInfo(localslot, &conflicttuple.xmin,
                               2990                 :              2 :                                     &conflicttuple.origin, &conflicttuple.ts) &&
  235 msawada@postgresql.o     2991         [ +  - ]:              2 :             conflicttuple.origin != replorigin_xact_state.origin)
                               2992                 :                :         {
                               2993                 :                :             TupleTableSlot *newslot;
                               2994                 :                : 
                               2995                 :                :             /* Store the new tuple for conflict reporting */
  761 akapila@postgresql.o     2996                 :              2 :             newslot = table_slot_create(localrel, &estate->es_tupleTable);
                               2997                 :              2 :             slot_store_data(newslot, relmapentry, newtup);
                               2998                 :                : 
  545                          2999                 :              2 :             conflicttuple.slot = localslot;
                               3000                 :                : 
  752                          3001                 :              2 :             ReportApplyConflict(estate, relinfo, LOG, CT_UPDATE_ORIGIN_DIFFERS,
                               3002                 :                :                                 remoteslot, newslot,
                               3003                 :                :                                 list_make1(&conflicttuple));
                               3004                 :                :         }
                               3005                 :                : 
                               3006                 :                :         /* Process and store remote tuple in the slot */
 3531 peter_e@gmx.net          3007         [ +  - ]:          31914 :         oldctx = MemoryContextSwitchTo(GetPerTupleMemoryContext(estate));
 2255 tgl@sss.pgh.pa.us        3008                 :          31914 :         slot_modify_data(remoteslot, localslot, relmapentry, newtup);
 3531 peter_e@gmx.net          3009                 :          31914 :         MemoryContextSwitchTo(oldctx);
                               3010                 :                : 
                               3011                 :          31914 :         EvalPlanQualSetSlot(&epqstate, remoteslot);
                               3012                 :                : 
  761 akapila@postgresql.o     3013                 :          31914 :         InitConflictIndexes(relinfo);
                               3014                 :                : 
                               3015                 :                :         /* Do the actual update. */
 1717 jdavis@postgresql.or     3016                 :          31914 :         TargetPrivilegesCheck(relinfo->ri_RelationDesc, ACL_UPDATE);
 2167 heikki.linnakangas@i     3017                 :          31914 :         ExecSimpleRelationUpdate(relinfo, estate, &epqstate, localslot,
                               3018                 :                :                                  remoteslot);
                               3019                 :                :     }
                               3020                 :                :     else
                               3021                 :                :     {
                               3022                 :                :         ConflictType type;
  761 akapila@postgresql.o     3023                 :              9 :         TupleTableSlot *newslot = localslot;
                               3024                 :                : 
                               3025                 :                :         /*
                               3026                 :                :          * Detecting whether the tuple was recently deleted or never existed
                               3027                 :                :          * is crucial to avoid misleading the user during conflict handling.
                               3028                 :                :          */
  412                          3029         [ +  + ]:              9 :         if (FindDeletedTupleInLocalRel(localrel, localindexoid, remoteslot,
                               3030                 :                :                                        &conflicttuple.xmin,
                               3031                 :                :                                        &conflicttuple.origin,
                               3032                 :              3 :                                        &conflicttuple.ts) &&
  235 msawada@postgresql.o     3033         [ +  - ]:              3 :             conflicttuple.origin != replorigin_xact_state.origin)
  412 akapila@postgresql.o     3034                 :              3 :             type = CT_UPDATE_DELETED;
                               3035                 :                :         else
                               3036                 :              6 :             type = CT_UPDATE_MISSING;
                               3037                 :                : 
                               3038                 :                :         /* Store the new tuple for conflict reporting */
  761                          3039                 :              9 :         slot_store_data(newslot, relmapentry, newtup);
                               3040                 :                : 
                               3041                 :                :         /*
                               3042                 :                :          * The tuple to be updated could not be found or was deleted.  Do
                               3043                 :                :          * nothing except for emitting a log message.
                               3044                 :                :          */
  412                          3045                 :              9 :         ReportApplyConflict(estate, relinfo, LOG, type, remoteslot, newslot,
                               3046                 :                :                             list_make1(&conflicttuple));
                               3047                 :                :     }
                               3048                 :                : 
                               3049                 :                :     /* Cleanup. */
 2371 peter@eisentraut.org     3050                 :          31921 :     ExecCloseIndices(relinfo);
 3531 peter_e@gmx.net          3051                 :          31921 :     EvalPlanQualEnd(&epqstate);
                               3052                 :          31921 : }
                               3053                 :                : 
                               3054                 :                : /*
                               3055                 :                :  * Handle DELETE message.
                               3056                 :                :  *
                               3057                 :                :  * TODO: FDW support
                               3058                 :                :  */
                               3059                 :                : static void
                               3060                 :          81936 : apply_handle_delete(StringInfo s)
                               3061                 :                : {
                               3062                 :                :     LogicalRepRelMapEntry *rel;
                               3063                 :                :     LogicalRepTupleData oldtup;
                               3064                 :                :     LogicalRepRelId relid;
                               3065                 :                :     UserContext ucxt;
                               3066                 :                :     ApplyExecutionData *edata;
                               3067                 :                :     EState     *estate;
                               3068                 :                :     TupleTableSlot *remoteslot;
                               3069                 :                :     MemoryContext oldctx;
                               3070                 :                :     bool        run_as_owner;
                               3071                 :                : 
                               3072                 :                :     /*
                               3073                 :                :      * Quick return if we are skipping data modification changes or handling
                               3074                 :                :      * streamed transactions.
                               3075                 :                :      */
 1643 akapila@postgresql.o     3076   [ +  -  +  + ]:         163872 :     if (is_skipping_changes() ||
                               3077                 :          81936 :         handle_streamed_transaction(LOGICAL_REP_MSG_DELETE, s))
 2208                          3078                 :          41615 :         return;
                               3079                 :                : 
 1928 tgl@sss.pgh.pa.us        3080                 :          40321 :     begin_replication_step();
                               3081                 :                : 
 3531 peter_e@gmx.net          3082                 :          40321 :     relid = logicalrep_read_delete(s, &oldtup);
                               3083                 :          40321 :     rel = logicalrep_rel_open(relid, RowExclusiveLock);
 3468                          3084         [ -  + ]:          40321 :     if (!should_apply_changes_for_rel(rel))
                               3085                 :                :     {
                               3086                 :                :         /*
                               3087                 :                :          * The relation can't become interesting in the middle of the
                               3088                 :                :          * transaction so it's safe to unlock it.
                               3089                 :                :          */
 3468 peter_e@gmx.net          3090                 :UBC           0 :         logicalrep_rel_close(rel, RowExclusiveLock);
 1928 tgl@sss.pgh.pa.us        3091                 :              0 :         end_replication_step();
 3468 peter_e@gmx.net          3092                 :              0 :         return;
                               3093                 :                :     }
                               3094                 :                : 
                               3095                 :                :     /* Set relation for error callback */
   25 akapila@postgresql.o     3096                 :GNC       40321 :     remote_ctx.rel = rel;
                               3097                 :                : 
                               3098                 :                :     /* Check if we can do the delete. */
 3531 peter_e@gmx.net          3099                 :CBC       40321 :     check_relation_updatable(rel);
                               3100                 :                : 
                               3101                 :                :     /*
                               3102                 :                :      * Make sure that any user-supplied code runs as the table owner, unless
                               3103                 :                :      * the user has opted out of that behavior.
                               3104                 :                :      */
 1265 rhaas@postgresql.org     3105                 :          40321 :     run_as_owner = MySubscription->runasowner;
                               3106         [ +  + ]:          40321 :     if (!run_as_owner)
                               3107                 :          40319 :         SwitchToUntrustedUser(rel->localrel->rd_rel->relowner, &ucxt);
                               3108                 :                : 
                               3109                 :                :     /* Initialize the executor state. */
 1947 tgl@sss.pgh.pa.us        3110                 :          40321 :     edata = create_edata_for_relation(rel);
                               3111                 :          40321 :     estate = edata->estate;
 3138 andres@anarazel.de       3112                 :          40321 :     remoteslot = ExecInitExtraTupleSlot(estate,
 2866                          3113                 :          40321 :                                         RelationGetDescr(rel->localrel),
                               3114                 :                :                                         &TTSOpsVirtual);
                               3115                 :                : 
                               3116                 :                :     /* Build the search tuple. */
 3531 peter_e@gmx.net          3117         [ -  + ]:          40321 :     oldctx = MemoryContextSwitchTo(GetPerTupleMemoryContext(estate));
 2255 tgl@sss.pgh.pa.us        3118                 :          40321 :     slot_store_data(remoteslot, rel, &oldtup);
 3531 peter_e@gmx.net          3119                 :          40321 :     MemoryContextSwitchTo(oldctx);
                               3120                 :                : 
                               3121                 :                :     /* For a partitioned table, apply delete to correct partition. */
 2358 peter@eisentraut.org     3122         [ +  + ]:          40321 :     if (rel->localrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
 1947 tgl@sss.pgh.pa.us        3123                 :             17 :         apply_handle_tuple_routing(edata,
                               3124                 :                :                                    remoteslot, NULL, CMD_DELETE);
                               3125                 :                :     else
                               3126                 :                :     {
  578                          3127                 :          40304 :         ResultRelInfo *relinfo = edata->targetRelInfo;
                               3128                 :                : 
                               3129                 :          40304 :         ExecOpenIndices(relinfo, false);
                               3130                 :          40304 :         apply_handle_delete_internal(edata, relinfo,
                               3131                 :                :                                      remoteslot, rel->localindexoid);
                               3132                 :          40304 :         ExecCloseIndices(relinfo);
                               3133                 :                :     }
                               3134                 :                : 
 1947                          3135                 :          40321 :     finish_edata(edata);
                               3136                 :                : 
                               3137                 :                :     /* Reset relation for error callback */
   25 akapila@postgresql.o     3138                 :GNC       40321 :     remote_ctx.rel = NULL;
                               3139                 :                : 
 1265 rhaas@postgresql.org     3140         [ +  + ]:CBC       40321 :     if (!run_as_owner)
                               3141                 :          40319 :         RestoreUserContext(&ucxt);
                               3142                 :                : 
 2371 peter@eisentraut.org     3143                 :          40321 :     logicalrep_rel_close(rel, NoLock);
                               3144                 :                : 
 1928 tgl@sss.pgh.pa.us        3145                 :          40321 :     end_replication_step();
                               3146                 :                : }
                               3147                 :                : 
                               3148                 :                : /*
                               3149                 :                :  * Workhorse for apply_handle_delete()
                               3150                 :                :  * relinfo is for the relation we're actually deleting from
                               3151                 :                :  * (could be a child partition of edata->targetRelInfo)
                               3152                 :                :  */
                               3153                 :                : static void
 1947                          3154                 :          40321 : apply_handle_delete_internal(ApplyExecutionData *edata,
                               3155                 :                :                              ResultRelInfo *relinfo,
                               3156                 :                :                              TupleTableSlot *remoteslot,
                               3157                 :                :                              Oid localindexoid)
                               3158                 :                : {
                               3159                 :          40321 :     EState     *estate = edata->estate;
 2371 peter@eisentraut.org     3160                 :          40321 :     Relation    localrel = relinfo->ri_RelationDesc;
 1947 tgl@sss.pgh.pa.us        3161                 :          40321 :     LogicalRepRelation *remoterel = &edata->targetRel->remoterel;
                               3162                 :                :     EPQState    epqstate;
                               3163                 :                :     TupleTableSlot *localslot;
  545 akapila@postgresql.o     3164                 :          40321 :     ConflictTupleInfo conflicttuple = {0};
                               3165                 :                :     bool        found;
                               3166                 :                : 
 1220 tgl@sss.pgh.pa.us        3167                 :          40321 :     EvalPlanQualInit(&epqstate, estate, NULL, NIL, -1, NIL);
                               3168                 :                : 
                               3169                 :                :     /* Caller should have opened indexes already. */
  578                          3170   [ +  +  +  +  :          40321 :     Assert(relinfo->ri_IndexRelationDescs != NULL ||
                                              -  + ]
                               3171                 :                :            !localrel->rd_rel->relhasindex ||
                               3172                 :                :            RelationGetIndexList(localrel) == NIL);
                               3173                 :                : 
 1153 msawada@postgresql.o     3174                 :          40321 :     found = FindReplTupleInLocalRel(edata, localrel, remoterel, localindexoid,
                               3175                 :                :                                     remoteslot, &localslot);
                               3176                 :                : 
                               3177                 :                :     /* If found delete it. */
 3531 peter_e@gmx.net          3178         [ +  + ]:          40321 :     if (found)
                               3179                 :                :     {
                               3180                 :                :         /*
                               3181                 :                :          * Report the conflict if the tuple was modified by a different
                               3182                 :                :          * origin.
                               3183                 :                :          */
  545 akapila@postgresql.o     3184         [ +  + ]:          40312 :         if (GetTupleTransactionInfo(localslot, &conflicttuple.xmin,
                               3185                 :              6 :                                     &conflicttuple.origin, &conflicttuple.ts) &&
  235 msawada@postgresql.o     3186         [ +  + ]:              6 :             conflicttuple.origin != replorigin_xact_state.origin)
                               3187                 :                :         {
  545 akapila@postgresql.o     3188                 :              5 :             conflicttuple.slot = localslot;
  752                          3189                 :              5 :             ReportApplyConflict(estate, relinfo, LOG, CT_DELETE_ORIGIN_DIFFERS,
                               3190                 :                :                                 remoteslot, NULL,
                               3191                 :                :                                 list_make1(&conflicttuple));
                               3192                 :                :         }
                               3193                 :                : 
 3531 peter_e@gmx.net          3194                 :          40312 :         EvalPlanQualSetSlot(&epqstate, localslot);
                               3195                 :                : 
                               3196                 :                :         /* Do the actual delete. */
 1717 jdavis@postgresql.or     3197                 :          40312 :         TargetPrivilegesCheck(relinfo->ri_RelationDesc, ACL_DELETE);
 2167 heikki.linnakangas@i     3198                 :          40312 :         ExecSimpleRelationDelete(relinfo, estate, &epqstate, localslot);
                               3199                 :                :     }
                               3200                 :                :     else
                               3201                 :                :     {
                               3202                 :                :         /*
                               3203                 :                :          * The tuple to be deleted could not be found.  Do nothing except for
                               3204                 :                :          * emitting a log message.
                               3205                 :                :          */
  761 akapila@postgresql.o     3206                 :              9 :         ReportApplyConflict(estate, relinfo, LOG, CT_DELETE_MISSING,
                               3207                 :                :                             remoteslot, NULL, list_make1(&conflicttuple));
                               3208                 :                :     }
                               3209                 :                : 
                               3210                 :                :     /* Cleanup. */
 3531 peter_e@gmx.net          3211                 :          40321 :     EvalPlanQualEnd(&epqstate);
                               3212                 :          40321 : }
                               3213                 :                : 
                               3214                 :                : /*
                               3215                 :                :  * Try to find a tuple received from the publication side (in 'remoteslot') in
                               3216                 :                :  * the corresponding local relation using either replica identity index,
                               3217                 :                :  * primary key, index or if needed, sequential scan.
                               3218                 :                :  *
                               3219                 :                :  * Local tuple, if found, is returned in '*localslot'.
                               3220                 :                :  */
                               3221                 :                : static bool
 1153 msawada@postgresql.o     3222                 :          72261 : FindReplTupleInLocalRel(ApplyExecutionData *edata, Relation localrel,
                               3223                 :                :                         LogicalRepRelation *remoterel,
                               3224                 :                :                         Oid localidxoid,
                               3225                 :                :                         TupleTableSlot *remoteslot,
                               3226                 :                :                         TupleTableSlot **localslot)
                               3227                 :                : {
                               3228                 :          72261 :     EState     *estate = edata->estate;
                               3229                 :                :     bool        found;
                               3230                 :                : 
                               3231                 :                :     /*
                               3232                 :                :      * Regardless of the top-level operation, we're performing a read here, so
                               3233                 :                :      * check for SELECT privileges.
                               3234                 :                :      */
 1716 jdavis@postgresql.or     3235                 :          72261 :     TargetPrivilegesCheck(localrel, ACL_SELECT);
                               3236                 :                : 
 2363 peter@eisentraut.org     3237                 :          72257 :     *localslot = table_slot_create(localrel, &estate->es_tupleTable);
                               3238                 :                : 
 1285 akapila@postgresql.o     3239   [ +  +  -  + ]:          72257 :     Assert(OidIsValid(localidxoid) ||
                               3240                 :                :            (remoterel->replident == REPLICA_IDENTITY_FULL));
                               3241                 :                : 
                               3242         [ +  + ]:          72257 :     if (OidIsValid(localidxoid))
                               3243                 :                :     {
                               3244                 :                : #ifdef USE_ASSERT_CHECKING
 1153 msawada@postgresql.o     3245                 :          72105 :         Relation    idxrel = index_open(localidxoid, AccessShareLock);
                               3246                 :                : 
                               3247                 :                :         /* Index must be PK, RI, or usable for REPLICA IDENTITY FULL tables */
  739 akapila@postgresql.o     3248   [ +  +  +  -  :          72105 :         Assert(GetRelationIdentityOrPK(localrel) == localidxoid ||
                                              -  + ]
                               3249                 :                :                (remoterel->replident == REPLICA_IDENTITY_FULL &&
                               3250                 :                :                 IsIndexUsableForReplicaIdentityFull(idxrel,
                               3251                 :                :                                                     edata->targetRel->attrmap)));
 1153 msawada@postgresql.o     3252                 :          72105 :         index_close(idxrel, AccessShareLock);
                               3253                 :                : #endif
                               3254                 :                : 
 1285 akapila@postgresql.o     3255                 :          72105 :         found = RelationFindReplTupleByIndex(localrel, localidxoid,
                               3256                 :                :                                              LockTupleExclusive,
                               3257                 :                :                                              remoteslot, *localslot);
                               3258                 :                :     }
                               3259                 :                :     else
 2363 peter@eisentraut.org     3260                 :            152 :         found = RelationFindReplTupleSeq(localrel, LockTupleExclusive,
                               3261                 :                :                                          remoteslot, *localslot);
                               3262                 :                : 
                               3263                 :          72257 :     return found;
                               3264                 :                : }
                               3265                 :                : 
                               3266                 :                : /*
                               3267                 :                :  * Determine whether the index can reliably locate the deleted tuple in the
                               3268                 :                :  * local relation.
                               3269                 :                :  *
                               3270                 :                :  * An index may exclude deleted tuples if it was re-indexed or re-created during
                               3271                 :                :  * change application. Therefore, an index is considered usable only if the
                               3272                 :                :  * conflict detection slot.xmin (conflict_detection_xmin) is greater than the
                               3273                 :                :  * index tuple's xmin. This ensures that any tuples deleted prior to the index
                               3274                 :                :  * creation or re-indexing are not relevant for conflict detection in the
                               3275                 :                :  * current apply worker.
                               3276                 :                :  *
                               3277                 :                :  * Note that indexes may also be excluded if they were modified by other DDL
                               3278                 :                :  * operations, such as ALTER INDEX. However, this is acceptable, as the
                               3279                 :                :  * likelihood of such DDL changes coinciding with the need to scan dead
                               3280                 :                :  * tuples for the update_deleted is low.
                               3281                 :                :  */
                               3282                 :                : static bool
  412 akapila@postgresql.o     3283                 :              1 : IsIndexUsableForFindingDeletedTuple(Oid localindexoid,
                               3284                 :                :                                     TransactionId conflict_detection_xmin)
                               3285                 :                : {
                               3286                 :                :     HeapTuple   index_tuple;
                               3287                 :                :     TransactionId index_xmin;
                               3288                 :                : 
                               3289                 :              1 :     index_tuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(localindexoid));
                               3290                 :                : 
                               3291         [ -  + ]:              1 :     if (!HeapTupleIsValid(index_tuple)) /* should not happen */
  412 akapila@postgresql.o     3292         [ #  # ]:UBC           0 :         elog(ERROR, "cache lookup failed for index %u", localindexoid);
                               3293                 :                : 
                               3294                 :                :     /*
                               3295                 :                :      * No need to check for a frozen transaction ID, as
                               3296                 :                :      * TransactionIdPrecedes() manages it internally, treating it as falling
                               3297                 :                :      * behind the conflict_detection_xmin.
                               3298                 :                :      */
  412 akapila@postgresql.o     3299                 :CBC           1 :     index_xmin = HeapTupleHeaderGetXmin(index_tuple->t_data);
                               3300                 :                : 
                               3301                 :              1 :     ReleaseSysCache(index_tuple);
                               3302                 :                : 
                               3303                 :              1 :     return TransactionIdPrecedes(index_xmin, conflict_detection_xmin);
                               3304                 :                : }
                               3305                 :                : 
                               3306                 :                : /*
                               3307                 :                :  * Attempts to locate a deleted tuple in the local relation that matches the
                               3308                 :                :  * values of the tuple received from the publication side (in 'remoteslot').
                               3309                 :                :  * The search is performed using either the replica identity index, primary
                               3310                 :                :  * key, other available index, or a sequential scan if necessary.
                               3311                 :                :  *
                               3312                 :                :  * Returns true if the deleted tuple is found. If found, the transaction ID,
                               3313                 :                :  * origin, and commit timestamp of the deletion are stored in '*delete_xid',
                               3314                 :                :  * '*delete_origin', and '*delete_time' respectively.
                               3315                 :                :  */
                               3316                 :                : static bool
                               3317                 :             11 : FindDeletedTupleInLocalRel(Relation localrel, Oid localidxoid,
                               3318                 :                :                            TupleTableSlot *remoteslot,
                               3319                 :                :                            TransactionId *delete_xid, ReplOriginId *delete_origin,
                               3320                 :                :                            TimestampTz *delete_time)
                               3321                 :                : {
                               3322                 :                :     TransactionId oldestxmin;
                               3323                 :                : 
                               3324                 :                :     /*
                               3325                 :                :      * Return false if either dead tuples are not retained or commit timestamp
                               3326                 :                :      * data is not available.
                               3327                 :                :      */
                               3328   [ +  +  -  + ]:             11 :     if (!MySubscription->retaindeadtuples || !track_commit_timestamp)
                               3329                 :              8 :         return false;
                               3330                 :                : 
                               3331                 :                :     /*
                               3332                 :                :      * For conflict detection, we use the leader worker's
                               3333                 :                :      * oldest_nonremovable_xid value instead of invoking
                               3334                 :                :      * GetOldestNonRemovableTransactionId() or using the conflict detection
                               3335                 :                :      * slot's xmin. The oldest_nonremovable_xid acts as a threshold to
                               3336                 :                :      * identify tuples that were recently deleted. These deleted tuples are no
                               3337                 :                :      * longer visible to concurrent transactions. However, if a remote update
                               3338                 :                :      * matches such a tuple, we log an update_deleted conflict.
                               3339                 :                :      *
                               3340                 :                :      * While GetOldestNonRemovableTransactionId() and slot.xmin may return
                               3341                 :                :      * transaction IDs older than oldest_nonremovable_xid, for our current
                               3342                 :                :      * purpose, it is acceptable to treat tuples deleted by transactions prior
                               3343                 :                :      * to oldest_nonremovable_xid as update_missing conflicts.
                               3344                 :                :      */
  383                          3345         [ +  - ]:              3 :     if (am_leader_apply_worker())
                               3346                 :                :     {
                               3347                 :              3 :         oldestxmin = MyLogicalRepWorker->oldest_nonremovable_xid;
                               3348                 :                :     }
                               3349                 :                :     else
                               3350                 :                :     {
                               3351                 :                :         LogicalRepWorker *leader;
                               3352                 :                : 
                               3353                 :                :         /*
                               3354                 :                :          * Obtain the information from the leader apply worker as only the
                               3355                 :                :          * leader manages oldest_nonremovable_xid (see
                               3356                 :                :          * maybe_advance_nonremovable_xid() for details).
                               3357                 :                :          */
  383 akapila@postgresql.o     3358                 :UBC           0 :         LWLockAcquire(LogicalRepWorkerLock, LW_SHARED);
  327                          3359                 :              0 :         leader = logicalrep_worker_find(WORKERTYPE_APPLY,
                               3360                 :              0 :                                         MyLogicalRepWorker->subid, InvalidOid,
                               3361                 :                :                                         false);
  376                          3362         [ #  # ]:              0 :         if (!leader)
                               3363                 :                :         {
                               3364         [ #  # ]:              0 :             ereport(ERROR,
                               3365                 :                :                     (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
                               3366                 :                :                      errmsg("could not detect conflict as the leader apply worker has exited")));
                               3367                 :                :         }
                               3368                 :                : 
  383                          3369                 :              0 :         SpinLockAcquire(&leader->relmutex);
                               3370                 :              0 :         oldestxmin = leader->oldest_nonremovable_xid;
                               3371                 :              0 :         SpinLockRelease(&leader->relmutex);
                               3372                 :              0 :         LWLockRelease(LogicalRepWorkerLock);
                               3373                 :                :     }
                               3374                 :                : 
                               3375                 :                :     /*
                               3376                 :                :      * Return false if the leader apply worker has stopped retaining
                               3377                 :                :      * information for detecting conflicts. This implies that update_deleted
                               3378                 :                :      * can no longer be reliably detected.
                               3379                 :                :      */
  383 akapila@postgresql.o     3380         [ -  + ]:CBC           3 :     if (!TransactionIdIsValid(oldestxmin))
  383 akapila@postgresql.o     3381                 :UBC           0 :         return false;
                               3382                 :                : 
  412 akapila@postgresql.o     3383   [ +  +  +  - ]:CBC           4 :     if (OidIsValid(localidxoid) &&
                               3384                 :              1 :         IsIndexUsableForFindingDeletedTuple(localidxoid, oldestxmin))
                               3385                 :              1 :         return RelationFindDeletedTupleInfoByIndex(localrel, localidxoid,
                               3386                 :                :                                                    remoteslot, oldestxmin,
                               3387                 :                :                                                    delete_xid, delete_origin,
                               3388                 :                :                                                    delete_time);
                               3389                 :                :     else
                               3390                 :              2 :         return RelationFindDeletedTupleInfoSeq(localrel, remoteslot,
                               3391                 :                :                                                oldestxmin, delete_xid,
                               3392                 :                :                                                delete_origin, delete_time);
                               3393                 :                : }
                               3394                 :                : 
                               3395                 :                : /*
                               3396                 :                :  * This handles insert, update, delete on a partitioned table.
                               3397                 :                :  */
                               3398                 :                : static void
 1947 tgl@sss.pgh.pa.us        3399                 :            105 : apply_handle_tuple_routing(ApplyExecutionData *edata,
                               3400                 :                :                            TupleTableSlot *remoteslot,
                               3401                 :                :                            LogicalRepTupleData *newtup,
                               3402                 :                :                            CmdType operation)
                               3403                 :                : {
                               3404                 :            105 :     EState     *estate = edata->estate;
                               3405                 :            105 :     LogicalRepRelMapEntry *relmapentry = edata->targetRel;
                               3406                 :            105 :     ResultRelInfo *relinfo = edata->targetRelInfo;
 2358 peter@eisentraut.org     3407                 :            105 :     Relation    parentrel = relinfo->ri_RelationDesc;
                               3408                 :                :     ModifyTableState *mtstate;
                               3409                 :                :     PartitionTupleRouting *proute;
                               3410                 :                :     ResultRelInfo *partrelinfo;
                               3411                 :                :     Relation    partrel;
                               3412                 :                :     TupleTableSlot *remoteslot_part;
                               3413                 :                :     TupleConversionMap *map;
                               3414                 :                :     MemoryContext oldctx;
 1552 akapila@postgresql.o     3415                 :            105 :     LogicalRepRelMapEntry *part_entry = NULL;
                               3416                 :            105 :     AttrMap    *attrmap = NULL;
                               3417                 :                : 
                               3418                 :                :     /* ModifyTableState is needed for ExecFindPartition(). */
 1947 tgl@sss.pgh.pa.us        3419                 :            105 :     edata->mtstate = mtstate = makeNode(ModifyTableState);
 2358 peter@eisentraut.org     3420                 :            105 :     mtstate->ps.plan = NULL;
                               3421                 :            105 :     mtstate->ps.state = estate;
                               3422                 :            105 :     mtstate->operation = operation;
                               3423                 :            105 :     mtstate->resultRelInfo = relinfo;
                               3424                 :                : 
                               3425                 :                :     /* ... as is PartitionTupleRouting. */
 1947 tgl@sss.pgh.pa.us        3426                 :            105 :     edata->proute = proute = ExecSetupPartitionTupleRouting(estate, parentrel);
                               3427                 :                : 
                               3428                 :                :     /*
                               3429                 :                :      * Find the partition to which the "search tuple" belongs.
                               3430                 :                :      */
 2358 peter@eisentraut.org     3431         [ -  + ]:            105 :     Assert(remoteslot != NULL);
                               3432         [ +  - ]:            105 :     oldctx = MemoryContextSwitchTo(GetPerTupleMemoryContext(estate));
                               3433                 :            105 :     partrelinfo = ExecFindPartition(mtstate, relinfo, proute,
                               3434                 :                :                                     remoteslot, estate);
                               3435         [ -  + ]:            105 :     Assert(partrelinfo != NULL);
                               3436                 :            105 :     partrel = partrelinfo->ri_RelationDesc;
                               3437                 :                : 
                               3438                 :                :     /*
                               3439                 :                :      * Check for supported relkind.  We need this since partitions might be of
                               3440                 :                :      * unsupported relkinds; and the set of partitions can change, so checking
                               3441                 :                :      * at CREATE/ALTER SUBSCRIPTION would be insufficient.
                               3442                 :                :      */
 1418 tgl@sss.pgh.pa.us        3443                 :            105 :     CheckSubscriptionRelkind(partrel->rd_rel->relkind,
  332 akapila@postgresql.o     3444                 :            105 :                              relmapentry->remoterel.relkind,
 1418 tgl@sss.pgh.pa.us        3445                 :            105 :                              get_namespace_name(RelationGetNamespace(partrel)),
                               3446                 :            105 :                              RelationGetRelationName(partrel));
                               3447                 :                : 
                               3448                 :                :     /*
                               3449                 :                :      * To perform any of the operations below, the tuple must match the
                               3450                 :                :      * partition's rowtype. Convert if needed or just copy, using a dedicated
                               3451                 :                :      * slot to store the tuple in any case.
                               3452                 :                :      */
 2162 heikki.linnakangas@i     3453                 :            105 :     remoteslot_part = partrelinfo->ri_PartitionTupleSlot;
 2358 peter@eisentraut.org     3454         [ +  + ]:            105 :     if (remoteslot_part == NULL)
                               3455                 :             72 :         remoteslot_part = table_slot_create(partrel, &estate->es_tupleTable);
 1388 alvherre@alvh.no-ip.     3456                 :            105 :     map = ExecGetRootToChildMap(partrelinfo, estate);
 2358 peter@eisentraut.org     3457         [ +  + ]:            105 :     if (map != NULL)
                               3458                 :                :     {
 1552 akapila@postgresql.o     3459                 :             33 :         attrmap = map->attrMap;
                               3460                 :             33 :         remoteslot_part = execute_attr_map_slot(attrmap, remoteslot,
                               3461                 :                :                                                 remoteslot_part);
                               3462                 :                :     }
                               3463                 :                :     else
                               3464                 :                :     {
 2358 peter@eisentraut.org     3465                 :             72 :         remoteslot_part = ExecCopySlot(remoteslot_part, remoteslot);
                               3466                 :             72 :         slot_getallattrs(remoteslot_part);
                               3467                 :                :     }
                               3468                 :            105 :     MemoryContextSwitchTo(oldctx);
                               3469                 :                : 
                               3470                 :                :     /* Check if we can do the update or delete on the leaf partition. */
 1552 akapila@postgresql.o     3471   [ +  +  +  + ]:            105 :     if (operation == CMD_UPDATE || operation == CMD_DELETE)
                               3472                 :                :     {
                               3473                 :             30 :         part_entry = logicalrep_partition_open(relmapentry, partrel,
                               3474                 :                :                                                attrmap);
                               3475                 :             30 :         check_relation_updatable(part_entry);
                               3476                 :                :     }
                               3477                 :                : 
 2358 peter@eisentraut.org     3478   [ +  +  +  - ]:            105 :     switch (operation)
                               3479                 :                :     {
                               3480                 :             75 :         case CMD_INSERT:
 1947 tgl@sss.pgh.pa.us        3481                 :             75 :             apply_handle_insert_internal(edata, partrelinfo,
                               3482                 :                :                                          remoteslot_part);
 2358 peter@eisentraut.org     3483                 :             44 :             break;
                               3484                 :                : 
                               3485                 :             17 :         case CMD_DELETE:
 1947 tgl@sss.pgh.pa.us        3486                 :             17 :             apply_handle_delete_internal(edata, partrelinfo,
                               3487                 :                :                                          remoteslot_part,
                               3488                 :                :                                          part_entry->localindexoid);
 2358 peter@eisentraut.org     3489                 :             17 :             break;
                               3490                 :                : 
                               3491                 :             13 :         case CMD_UPDATE:
                               3492                 :                : 
                               3493                 :                :             /*
                               3494                 :                :              * For UPDATE, depending on whether or not the updated tuple
                               3495                 :                :              * satisfies the partition's constraint, perform a simple UPDATE
                               3496                 :                :              * of the partition or move the updated tuple into a different
                               3497                 :                :              * suitable partition.
                               3498                 :                :              */
                               3499                 :                :             {
                               3500                 :                :                 TupleTableSlot *localslot;
                               3501                 :                :                 ResultRelInfo *partrelinfo_new;
                               3502                 :                :                 Relation    partrel_new;
                               3503                 :                :                 bool        found;
                               3504                 :                :                 EPQState    epqstate;
  545 akapila@postgresql.o     3505                 :             13 :                 ConflictTupleInfo conflicttuple = {0};
                               3506                 :                : 
                               3507                 :                :                 /* Get the matching local tuple from the partition. */
 1153 msawada@postgresql.o     3508                 :             13 :                 found = FindReplTupleInLocalRel(edata, partrel,
                               3509                 :                :                                                 &part_entry->remoterel,
                               3510                 :                :                                                 part_entry->localindexoid,
                               3511                 :                :                                                 remoteslot_part, &localslot);
 1927 tgl@sss.pgh.pa.us        3512         [ +  + ]:             13 :                 if (!found)
                               3513                 :                :                 {
                               3514                 :                :                     ConflictType type;
  761 akapila@postgresql.o     3515                 :              2 :                     TupleTableSlot *newslot = localslot;
                               3516                 :                : 
                               3517                 :                :                     /*
                               3518                 :                :                      * Detecting whether the tuple was recently deleted or
                               3519                 :                :                      * never existed is crucial to avoid misleading the user
                               3520                 :                :                      * during conflict handling.
                               3521                 :                :                      */
  412                          3522         [ -  + ]:              2 :                     if (FindDeletedTupleInLocalRel(partrel,
                               3523                 :                :                                                    part_entry->localindexoid,
                               3524                 :                :                                                    remoteslot_part,
                               3525                 :                :                                                    &conflicttuple.xmin,
                               3526                 :                :                                                    &conflicttuple.origin,
  412 akapila@postgresql.o     3527                 :UBC           0 :                                                    &conflicttuple.ts) &&
  235 msawada@postgresql.o     3528         [ #  # ]:              0 :                         conflicttuple.origin != replorigin_xact_state.origin)
  412 akapila@postgresql.o     3529                 :              0 :                         type = CT_UPDATE_DELETED;
                               3530                 :                :                     else
  412 akapila@postgresql.o     3531                 :CBC           2 :                         type = CT_UPDATE_MISSING;
                               3532                 :                : 
                               3533                 :                :                     /* Store the new tuple for conflict reporting */
  761                          3534                 :              2 :                     slot_store_data(newslot, part_entry, newtup);
                               3535                 :                : 
                               3536                 :                :                     /*
                               3537                 :                :                      * The tuple to be updated could not be found or was
                               3538                 :                :                      * deleted.  Do nothing except for emitting a log message.
                               3539                 :                :                      */
  545                          3540                 :              2 :                     ReportApplyConflict(estate, partrelinfo, LOG,
                               3541                 :                :                                         type, remoteslot_part, newslot,
                               3542                 :                :                                         list_make1(&conflicttuple));
                               3543                 :                : 
 1927 tgl@sss.pgh.pa.us        3544                 :              2 :                     return;
                               3545                 :                :                 }
                               3546                 :                : 
                               3547                 :                :                 /*
                               3548                 :                :                  * Report the conflict if the tuple was modified by a
                               3549                 :                :                  * different origin.
                               3550                 :                :                  */
  545 akapila@postgresql.o     3551         [ +  + ]:             11 :                 if (GetTupleTransactionInfo(localslot, &conflicttuple.xmin,
                               3552                 :                :                                             &conflicttuple.origin,
                               3553                 :              1 :                                             &conflicttuple.ts) &&
  235 msawada@postgresql.o     3554         [ +  - ]:              1 :                     conflicttuple.origin != replorigin_xact_state.origin)
                               3555                 :                :                 {
                               3556                 :                :                     TupleTableSlot *newslot;
                               3557                 :                : 
                               3558                 :                :                     /* Store the new tuple for conflict reporting */
  761 akapila@postgresql.o     3559                 :              1 :                     newslot = table_slot_create(partrel, &estate->es_tupleTable);
                               3560                 :              1 :                     slot_store_data(newslot, part_entry, newtup);
                               3561                 :                : 
  545                          3562                 :              1 :                     conflicttuple.slot = localslot;
                               3563                 :                : 
  752                          3564                 :              1 :                     ReportApplyConflict(estate, partrelinfo, LOG, CT_UPDATE_ORIGIN_DIFFERS,
                               3565                 :                :                                         remoteslot_part, newslot,
                               3566                 :                :                                         list_make1(&conflicttuple));
                               3567                 :                :                 }
                               3568                 :                : 
                               3569                 :                :                 /*
                               3570                 :                :                  * Apply the update to the local tuple, putting the result in
                               3571                 :                :                  * remoteslot_part.
                               3572                 :                :                  */
 1927 tgl@sss.pgh.pa.us        3573         [ +  - ]:             11 :                 oldctx = MemoryContextSwitchTo(GetPerTupleMemoryContext(estate));
                               3574                 :             11 :                 slot_modify_data(remoteslot_part, localslot, part_entry,
                               3575                 :                :                                  newtup);
                               3576                 :             11 :                 MemoryContextSwitchTo(oldctx);
                               3577                 :                : 
  780 akapila@postgresql.o     3578                 :             11 :                 EvalPlanQualInit(&epqstate, estate, NULL, NIL, -1, NIL);
                               3579                 :                : 
                               3580                 :                :                 /*
                               3581                 :                :                  * Does the updated tuple still satisfy the current
                               3582                 :                :                  * partition's constraint?
                               3583                 :                :                  */
 2195 tgl@sss.pgh.pa.us        3584   [ +  -  +  + ]:             22 :                 if (!partrel->rd_rel->relispartition ||
 2358 peter@eisentraut.org     3585                 :             11 :                     ExecPartitionCheck(partrelinfo, remoteslot_part, estate,
                               3586                 :                :                                        false))
                               3587                 :                :                 {
                               3588                 :                :                     /*
                               3589                 :                :                      * Yes, so simply UPDATE the partition.  We don't call
                               3590                 :                :                      * apply_handle_update_internal() here, which would
                               3591                 :                :                      * normally do the following work, to avoid repeating some
                               3592                 :                :                      * work already done above to find the local tuple in the
                               3593                 :                :                      * partition.
                               3594                 :                :                      */
  761 akapila@postgresql.o     3595                 :             10 :                     InitConflictIndexes(partrelinfo);
                               3596                 :                : 
 2358 peter@eisentraut.org     3597                 :             10 :                     EvalPlanQualSetSlot(&epqstate, remoteslot_part);
 1717 jdavis@postgresql.or     3598                 :             10 :                     TargetPrivilegesCheck(partrelinfo->ri_RelationDesc,
                               3599                 :                :                                           ACL_UPDATE);
 2167 heikki.linnakangas@i     3600                 :             10 :                     ExecSimpleRelationUpdate(partrelinfo, estate, &epqstate,
                               3601                 :                :                                              localslot, remoteslot_part);
                               3602                 :                :                 }
                               3603                 :                :                 else
                               3604                 :                :                 {
                               3605                 :                :                     /* Move the tuple into the new partition. */
                               3606                 :                : 
                               3607                 :                :                     /*
                               3608                 :                :                      * New partition will be found using tuple routing, which
                               3609                 :                :                      * can only occur via the parent table.  We might need to
                               3610                 :                :                      * convert the tuple to the parent's rowtype.  Note that
                               3611                 :                :                      * this is the tuple found in the partition, not the
                               3612                 :                :                      * original search tuple received by this function.
                               3613                 :                :                      */
 2358 peter@eisentraut.org     3614         [ +  - ]:              1 :                     if (map)
                               3615                 :                :                     {
                               3616                 :                :                         TupleConversionMap *PartitionToRootMap =
 1220 tgl@sss.pgh.pa.us        3617                 :              1 :                             convert_tuples_by_name(RelationGetDescr(partrel),
                               3618                 :                :                                                    RelationGetDescr(parentrel));
                               3619                 :                : 
                               3620                 :                :                         remoteslot =
 2358 peter@eisentraut.org     3621                 :              1 :                             execute_attr_map_slot(PartitionToRootMap->attrMap,
                               3622                 :                :                                                   remoteslot_part, remoteslot);
                               3623                 :                :                     }
                               3624                 :                :                     else
                               3625                 :                :                     {
 2358 peter@eisentraut.org     3626                 :UBC           0 :                         remoteslot = ExecCopySlot(remoteslot, remoteslot_part);
                               3627                 :              0 :                         slot_getallattrs(remoteslot);
                               3628                 :                :                     }
                               3629                 :                : 
                               3630                 :                :                     /* Find the new partition. */
 2358 peter@eisentraut.org     3631         [ +  - ]:CBC           1 :                     oldctx = MemoryContextSwitchTo(GetPerTupleMemoryContext(estate));
                               3632                 :              1 :                     partrelinfo_new = ExecFindPartition(mtstate, relinfo,
                               3633                 :                :                                                         proute, remoteslot,
                               3634                 :                :                                                         estate);
                               3635                 :              1 :                     MemoryContextSwitchTo(oldctx);
                               3636         [ -  + ]:              1 :                     Assert(partrelinfo_new != partrelinfo);
 1418 tgl@sss.pgh.pa.us        3637                 :              1 :                     partrel_new = partrelinfo_new->ri_RelationDesc;
                               3638                 :                : 
                               3639                 :                :                     /* Check that new partition also has supported relkind. */
                               3640                 :              1 :                     CheckSubscriptionRelkind(partrel_new->rd_rel->relkind,
  332 akapila@postgresql.o     3641                 :              1 :                                              relmapentry->remoterel.relkind,
 1418 tgl@sss.pgh.pa.us        3642                 :              1 :                                              get_namespace_name(RelationGetNamespace(partrel_new)),
                               3643                 :              1 :                                              RelationGetRelationName(partrel_new));
                               3644                 :                : 
                               3645                 :                :                     /* DELETE old tuple found in the old partition. */
  780 akapila@postgresql.o     3646                 :              1 :                     EvalPlanQualSetSlot(&epqstate, localslot);
                               3647                 :              1 :                     TargetPrivilegesCheck(partrelinfo->ri_RelationDesc, ACL_DELETE);
                               3648                 :              1 :                     ExecSimpleRelationDelete(partrelinfo, estate, &epqstate, localslot);
                               3649                 :                : 
                               3650                 :                :                     /* INSERT new tuple into the new partition. */
                               3651                 :                : 
                               3652                 :                :                     /*
                               3653                 :                :                      * Convert the replacement tuple to match the destination
                               3654                 :                :                      * partition rowtype.
                               3655                 :                :                      */
 2358 peter@eisentraut.org     3656         [ +  - ]:              1 :                     oldctx = MemoryContextSwitchTo(GetPerTupleMemoryContext(estate));
 2162 heikki.linnakangas@i     3657                 :              1 :                     remoteslot_part = partrelinfo_new->ri_PartitionTupleSlot;
 2358 peter@eisentraut.org     3658         [ +  - ]:              1 :                     if (remoteslot_part == NULL)
 1418 tgl@sss.pgh.pa.us        3659                 :              1 :                         remoteslot_part = table_slot_create(partrel_new,
                               3660                 :                :                                                             &estate->es_tupleTable);
 1388 alvherre@alvh.no-ip.     3661                 :              1 :                     map = ExecGetRootToChildMap(partrelinfo_new, estate);
 2358 peter@eisentraut.org     3662         [ -  + ]:              1 :                     if (map != NULL)
                               3663                 :                :                     {
 2358 peter@eisentraut.org     3664                 :UBC           0 :                         remoteslot_part = execute_attr_map_slot(map->attrMap,
                               3665                 :                :                                                                 remoteslot,
                               3666                 :                :                                                                 remoteslot_part);
                               3667                 :                :                     }
                               3668                 :                :                     else
                               3669                 :                :                     {
 2358 peter@eisentraut.org     3670                 :CBC           1 :                         remoteslot_part = ExecCopySlot(remoteslot_part,
                               3671                 :                :                                                        remoteslot);
                               3672                 :              1 :                         slot_getallattrs(remoteslot);
                               3673                 :                :                     }
                               3674                 :              1 :                     MemoryContextSwitchTo(oldctx);
 1947 tgl@sss.pgh.pa.us        3675                 :              1 :                     apply_handle_insert_internal(edata, partrelinfo_new,
                               3676                 :                :                                                  remoteslot_part);
                               3677                 :                :                 }
                               3678                 :                : 
  780 akapila@postgresql.o     3679                 :             11 :                 EvalPlanQualEnd(&epqstate);
                               3680                 :                :             }
 2358 peter@eisentraut.org     3681                 :             11 :             break;
                               3682                 :                : 
 2358 peter@eisentraut.org     3683                 :UBC           0 :         default:
                               3684         [ #  # ]:              0 :             elog(ERROR, "unrecognized CmdType: %d", (int) operation);
                               3685                 :                :             break;
                               3686                 :                :     }
                               3687                 :                : }
                               3688                 :                : 
                               3689                 :                : /*
                               3690                 :                :  * Handle TRUNCATE message.
                               3691                 :                :  *
                               3692                 :                :  * TODO: FDW support
                               3693                 :                :  */
                               3694                 :                : static void
 3088 peter_e@gmx.net          3695                 :CBC          20 : apply_handle_truncate(StringInfo s)
                               3696                 :                : {
 3069 tgl@sss.pgh.pa.us        3697                 :             20 :     bool        cascade = false;
                               3698                 :             20 :     bool        restart_seqs = false;
                               3699                 :             20 :     List       *remote_relids = NIL;
                               3700                 :             20 :     List       *remote_rels = NIL;
                               3701                 :             20 :     List       *rels = NIL;
 2358 peter@eisentraut.org     3702                 :             20 :     List       *part_rels = NIL;
 3069 tgl@sss.pgh.pa.us        3703                 :             20 :     List       *relids = NIL;
                               3704                 :             20 :     List       *relids_logged = NIL;
                               3705                 :                :     ListCell   *lc;
 1948                          3706                 :             20 :     LOCKMODE    lockmode = AccessExclusiveLock;
                               3707                 :                : 
                               3708                 :                :     /*
                               3709                 :                :      * Quick return if we are skipping data modification changes or handling
                               3710                 :                :      * streamed transactions.
                               3711                 :                :      */
 1643 akapila@postgresql.o     3712   [ +  -  -  + ]:             40 :     if (is_skipping_changes() ||
                               3713                 :             20 :         handle_streamed_transaction(LOGICAL_REP_MSG_TRUNCATE, s))
 2208 akapila@postgresql.o     3714                 :UBC           0 :         return;
                               3715                 :                : 
 1928 tgl@sss.pgh.pa.us        3716                 :CBC          20 :     begin_replication_step();
                               3717                 :                : 
 3088 peter_e@gmx.net          3718                 :             20 :     remote_relids = logicalrep_read_truncate(s, &cascade, &restart_seqs);
                               3719                 :                : 
                               3720   [ +  -  +  +  :             49 :     foreach(lc, remote_relids)
                                              +  + ]
                               3721                 :                :     {
                               3722                 :             29 :         LogicalRepRelId relid = lfirst_oid(lc);
                               3723                 :                :         LogicalRepRelMapEntry *rel;
                               3724                 :                : 
 1948 akapila@postgresql.o     3725                 :             29 :         rel = logicalrep_rel_open(relid, lockmode);
 3088 peter_e@gmx.net          3726         [ -  + ]:             29 :         if (!should_apply_changes_for_rel(rel))
                               3727                 :                :         {
                               3728                 :                :             /*
                               3729                 :                :              * The relation can't become interesting in the middle of the
                               3730                 :                :              * transaction so it's safe to unlock it.
                               3731                 :                :              */
 1948 akapila@postgresql.o     3732                 :UBC           0 :             logicalrep_rel_close(rel, lockmode);
 3088 peter_e@gmx.net          3733                 :              0 :             continue;
                               3734                 :                :         }
                               3735                 :                : 
 3088 peter_e@gmx.net          3736                 :CBC          29 :         remote_rels = lappend(remote_rels, rel);
 1717 jdavis@postgresql.or     3737                 :             29 :         TargetPrivilegesCheck(rel->localrel, ACL_TRUNCATE);
 3088 peter_e@gmx.net          3738                 :             29 :         rels = lappend(rels, rel->localrel);
                               3739                 :             29 :         relids = lappend_oid(relids, rel->localreloid);
                               3740   [ +  +  -  +  :             29 :         if (RelationIsLogicallyLogged(rel->localrel))
                                     +  -  -  +  -  
                                     -  -  -  +  -  
                                              +  - ]
 3072                          3741                 :              1 :             relids_logged = lappend_oid(relids_logged, rel->localreloid);
                               3742                 :                : 
                               3743                 :                :         /*
                               3744                 :                :          * Truncate partitions if we got a message to truncate a partitioned
                               3745                 :                :          * table.
                               3746                 :                :          */
 2358 peter@eisentraut.org     3747         [ +  + ]:             29 :         if (rel->localrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
                               3748                 :                :         {
                               3749                 :                :             ListCell   *child;
                               3750                 :              4 :             List       *children = find_all_inheritors(rel->localreloid,
                               3751                 :                :                                                        lockmode,
                               3752                 :                :                                                        NULL);
                               3753                 :                : 
                               3754   [ +  -  +  +  :             15 :             foreach(child, children)
                                              +  + ]
                               3755                 :                :             {
                               3756                 :             11 :                 Oid         childrelid = lfirst_oid(child);
                               3757                 :                :                 Relation    childrel;
                               3758                 :                : 
                               3759         [ +  + ]:             11 :                 if (list_member_oid(relids, childrelid))
                               3760                 :              4 :                     continue;
                               3761                 :                : 
                               3762                 :                :                 /* find_all_inheritors already got lock */
                               3763                 :              7 :                 childrel = table_open(childrelid, NoLock);
                               3764                 :                : 
                               3765                 :                :                 /*
                               3766                 :                :                  * Ignore temp tables of other backends.  See similar code in
                               3767                 :                :                  * ExecuteTruncate().
                               3768                 :                :                  */
                               3769   [ -  +  -  - ]:              7 :                 if (RELATION_IS_OTHER_TEMP(childrel))
                               3770                 :                :                 {
 1948 akapila@postgresql.o     3771                 :UBC           0 :                     table_close(childrel, lockmode);
 2358 peter@eisentraut.org     3772                 :              0 :                     continue;
                               3773                 :                :                 }
                               3774                 :                : 
 1717 jdavis@postgresql.or     3775                 :CBC           7 :                 TargetPrivilegesCheck(childrel, ACL_TRUNCATE);
 2358 peter@eisentraut.org     3776                 :              7 :                 rels = lappend(rels, childrel);
                               3777                 :              7 :                 part_rels = lappend(part_rels, childrel);
                               3778                 :              7 :                 relids = lappend_oid(relids, childrelid);
                               3779                 :                :                 /* Log this relation only if needed for logical decoding */
                               3780   [ +  -  -  +  :              7 :                 if (RelationIsLogicallyLogged(childrel))
                                     -  -  -  -  -  
                                     -  -  -  -  -  
                                              -  - ]
 2358 peter@eisentraut.org     3781                 :UBC           0 :                     relids_logged = lappend_oid(relids_logged, childrelid);
                               3782                 :                :             }
                               3783                 :                :         }
                               3784                 :                :     }
                               3785                 :                : 
                               3786                 :                :     /*
                               3787                 :                :      * Even if we used CASCADE on the upstream primary we explicitly default
                               3788                 :                :      * to replaying changes without further cascading. This might be later
                               3789                 :                :      * changeable with a user specified option.
                               3790                 :                :      *
                               3791                 :                :      * MySubscription->runasowner tells us whether we want to execute
                               3792                 :                :      * replication actions as the subscription owner; the last argument to
                               3793                 :                :      * TruncateGuts tells it whether we want to switch to the table owner.
                               3794                 :                :      * Those are exactly opposite conditions.
                               3795                 :                :      */
 1991 fujii@postgresql.org     3796                 :CBC          20 :     ExecuteTruncateGuts(rels,
                               3797                 :                :                         relids,
                               3798                 :                :                         relids_logged,
                               3799                 :                :                         DROP_RESTRICT,
                               3800                 :                :                         restart_seqs,
 1265 rhaas@postgresql.org     3801                 :             20 :                         !MySubscription->runasowner);
 3088 peter_e@gmx.net          3802   [ +  -  +  +  :             49 :     foreach(lc, remote_rels)
                                              +  + ]
                               3803                 :                :     {
                               3804                 :             29 :         LogicalRepRelMapEntry *rel = lfirst(lc);
                               3805                 :                : 
                               3806                 :             29 :         logicalrep_rel_close(rel, NoLock);
                               3807                 :                :     }
 2358 peter@eisentraut.org     3808   [ +  +  +  +  :             27 :     foreach(lc, part_rels)
                                              +  + ]
                               3809                 :                :     {
                               3810                 :              7 :         Relation    rel = lfirst(lc);
                               3811                 :                : 
                               3812                 :              7 :         table_close(rel, NoLock);
                               3813                 :                :     }
                               3814                 :                : 
 1928 tgl@sss.pgh.pa.us        3815                 :             20 :     end_replication_step();
                               3816                 :                : }
                               3817                 :                : 
                               3818                 :                : 
                               3819                 :                : /*
                               3820                 :                :  * Logical replication protocol message dispatcher.
                               3821                 :                :  */
                               3822                 :                : void
 3531 peter_e@gmx.net          3823                 :         353047 : apply_dispatch(StringInfo s)
                               3824                 :                : {
 2148 akapila@postgresql.o     3825                 :         353047 :     LogicalRepMsgType action = pq_getmsgbyte(s);
                               3826                 :                :     LogicalRepMsgType saved_command;
                               3827                 :                : 
                               3828                 :                :     /*
                               3829                 :                :      * Set the current command being applied. Since this function can be
                               3830                 :                :      * called recursively when applying spooled changes, save the current
                               3831                 :                :      * command.
                               3832                 :                :      */
   25 akapila@postgresql.o     3833                 :GNC      353047 :     saved_command = remote_ctx.command;
                               3834                 :         353047 :     remote_ctx.command = action;
                               3835                 :                : 
 3531 peter_e@gmx.net          3836   [ +  +  +  +  :CBC      353047 :     switch (action)
                                     +  +  +  +  +  
                                     -  +  +  +  +  
                                     +  +  +  +  +  
                                                 - ]
                               3837                 :                :     {
 2148 akapila@postgresql.o     3838                 :            520 :         case LOGICAL_REP_MSG_BEGIN:
 3531 peter_e@gmx.net          3839                 :            520 :             apply_handle_begin(s);
 1850 akapila@postgresql.o     3840                 :            520 :             break;
                               3841                 :                : 
 2148                          3842                 :            453 :         case LOGICAL_REP_MSG_COMMIT:
 3531 peter_e@gmx.net          3843                 :            453 :             apply_handle_commit(s);
 1850 akapila@postgresql.o     3844                 :            453 :             break;
                               3845                 :                : 
 2148                          3846                 :         201573 :         case LOGICAL_REP_MSG_INSERT:
 3531 peter_e@gmx.net          3847                 :         201573 :             apply_handle_insert(s);
 1850 akapila@postgresql.o     3848                 :         201513 :             break;
                               3849                 :                : 
 2148                          3850                 :          66165 :         case LOGICAL_REP_MSG_UPDATE:
 3531 peter_e@gmx.net          3851                 :          66165 :             apply_handle_update(s);
 1850 akapila@postgresql.o     3852                 :          66157 :             break;
                               3853                 :                : 
 2148                          3854                 :          81936 :         case LOGICAL_REP_MSG_DELETE:
 3531 peter_e@gmx.net          3855                 :          81936 :             apply_handle_delete(s);
 1850 akapila@postgresql.o     3856                 :          81936 :             break;
                               3857                 :                : 
 2148                          3858                 :             20 :         case LOGICAL_REP_MSG_TRUNCATE:
 3088 peter_e@gmx.net          3859                 :             20 :             apply_handle_truncate(s);
 1850 akapila@postgresql.o     3860                 :             20 :             break;
                               3861                 :                : 
 2148                          3862                 :            505 :         case LOGICAL_REP_MSG_RELATION:
 3531 peter_e@gmx.net          3863                 :            505 :             apply_handle_relation(s);
 1850 akapila@postgresql.o     3864                 :            505 :             break;
                               3865                 :                : 
 2148                          3866                 :             18 :         case LOGICAL_REP_MSG_TYPE:
 3531 peter_e@gmx.net          3867                 :             18 :             apply_handle_type(s);
 1850 akapila@postgresql.o     3868                 :             18 :             break;
                               3869                 :                : 
 2148                          3870                 :             10 :         case LOGICAL_REP_MSG_ORIGIN:
 3531 peter_e@gmx.net          3871                 :             10 :             apply_handle_origin(s);
 1850 akapila@postgresql.o     3872                 :             10 :             break;
                               3873                 :                : 
 1993 akapila@postgresql.o     3874                 :UBC           0 :         case LOGICAL_REP_MSG_MESSAGE:
                               3875                 :                : 
                               3876                 :                :             /*
                               3877                 :                :              * Logical replication does not use generic logical messages yet.
                               3878                 :                :              * Although, it could be used by other applications that use this
                               3879                 :                :              * output plugin.
                               3880                 :                :              */
 1850                          3881                 :              0 :             break;
                               3882                 :                : 
 2148 akapila@postgresql.o     3883                 :CBC         838 :         case LOGICAL_REP_MSG_STREAM_START:
 2208                          3884                 :            838 :             apply_handle_stream_start(s);
 1850                          3885                 :            838 :             break;
                               3886                 :                : 
 1858                          3887                 :            837 :         case LOGICAL_REP_MSG_STREAM_STOP:
 2208                          3888                 :            837 :             apply_handle_stream_stop(s);
 1850                          3889                 :            835 :             break;
                               3890                 :                : 
 2148                          3891                 :             38 :         case LOGICAL_REP_MSG_STREAM_ABORT:
 2208                          3892                 :             38 :             apply_handle_stream_abort(s);
 1850                          3893                 :             38 :             break;
                               3894                 :                : 
 2148                          3895                 :             59 :         case LOGICAL_REP_MSG_STREAM_COMMIT:
 2208                          3896                 :             59 :             apply_handle_stream_commit(s);
 1850                          3897                 :             57 :             break;
                               3898                 :                : 
 1894                          3899                 :             17 :         case LOGICAL_REP_MSG_BEGIN_PREPARE:
                               3900                 :             17 :             apply_handle_begin_prepare(s);
 1850                          3901                 :             17 :             break;
                               3902                 :                : 
 1894                          3903                 :             16 :         case LOGICAL_REP_MSG_PREPARE:
                               3904                 :             16 :             apply_handle_prepare(s);
 1850                          3905                 :             15 :             break;
                               3906                 :                : 
 1894                          3907                 :             22 :         case LOGICAL_REP_MSG_COMMIT_PREPARED:
                               3908                 :             22 :             apply_handle_commit_prepared(s);
 1850                          3909                 :             22 :             break;
                               3910                 :                : 
 1894                          3911                 :              5 :         case LOGICAL_REP_MSG_ROLLBACK_PREPARED:
                               3912                 :              5 :             apply_handle_rollback_prepared(s);
 1850                          3913                 :              5 :             break;
                               3914                 :                : 
 1873                          3915                 :             15 :         case LOGICAL_REP_MSG_STREAM_PREPARE:
                               3916                 :             15 :             apply_handle_stream_prepare(s);
 1850                          3917                 :             13 :             break;
                               3918                 :                : 
 1850 akapila@postgresql.o     3919                 :UBC           0 :         default:
                               3920         [ #  # ]:              0 :             ereport(ERROR,
                               3921                 :                :                     (errcode(ERRCODE_PROTOCOL_VIOLATION),
                               3922                 :                :                      errmsg("invalid logical replication message type \"??? (%d)\"", action)));
                               3923                 :                :     }
                               3924                 :                : 
                               3925                 :                :     /* Reset the current command */
   25 akapila@postgresql.o     3926                 :GNC      352972 :     remote_ctx.command = saved_command;
 3531 peter_e@gmx.net          3927                 :CBC      352972 : }
                               3928                 :                : 
                               3929                 :                : /*
                               3930                 :                :  * Figure out which write/flush positions to report to the walsender process.
                               3931                 :                :  *
                               3932                 :                :  * We can't simply report back the last LSN the walsender sent us because the
                               3933                 :                :  * local transaction might not yet be flushed to disk locally. Instead we
                               3934                 :                :  * build a list that associates local with remote LSNs for every commit. When
                               3935                 :                :  * reporting back the flush position to the sender we iterate that list and
                               3936                 :                :  * check which entries on it are already locally flushed. Those we can report
                               3937                 :                :  * as having been flushed.
                               3938                 :                :  *
                               3939                 :                :  * The have_pending_txes is true if there are outstanding transactions that
                               3940                 :                :  * need to be flushed.
                               3941                 :                :  */
                               3942                 :                : static void
                               3943                 :          36739 : get_flush_position(XLogRecPtr *write, XLogRecPtr *flush,
                               3944                 :                :                    bool *have_pending_txes)
                               3945                 :                : {
                               3946                 :                :     dlist_mutable_iter iter;
 1780 rhaas@postgresql.org     3947                 :          36739 :     XLogRecPtr  local_flush = GetFlushRecPtr(NULL);
                               3948                 :                : 
 3531 peter_e@gmx.net          3949                 :          36739 :     *write = InvalidXLogRecPtr;
                               3950                 :          36739 :     *flush = InvalidXLogRecPtr;
                               3951                 :                : 
                               3952   [ +  -  +  + ]:          37262 :     dlist_foreach_modify(iter, &lsn_mapping)
                               3953                 :                :     {
                               3954                 :           3936 :         FlushPosition *pos =
                               3955                 :                :             dlist_container(FlushPosition, node, iter.cur);
                               3956                 :                : 
                               3957                 :           3936 :         *write = pos->remote_end;
                               3958                 :                : 
                               3959         [ +  + ]:           3936 :         if (pos->local_end <= local_flush)
                               3960                 :                :         {
                               3961                 :            523 :             *flush = pos->remote_end;
                               3962                 :            523 :             dlist_delete(iter.cur);
                               3963                 :            523 :             pfree(pos);
                               3964                 :                :         }
                               3965                 :                :         else
                               3966                 :                :         {
                               3967                 :                :             /*
                               3968                 :                :              * Don't want to uselessly iterate over the rest of the list which
                               3969                 :                :              * could potentially be long. Instead get the last element and
                               3970                 :                :              * grab the write position from there.
                               3971                 :                :              */
                               3972                 :           3413 :             pos = dlist_tail_element(FlushPosition, node,
                               3973                 :                :                                      &lsn_mapping);
                               3974                 :           3413 :             *write = pos->remote_end;
                               3975                 :           3413 :             *have_pending_txes = true;
                               3976                 :           3413 :             return;
                               3977                 :                :         }
                               3978                 :                :     }
                               3979                 :                : 
                               3980                 :          33326 :     *have_pending_txes = !dlist_is_empty(&lsn_mapping);
                               3981                 :                : }
                               3982                 :                : 
                               3983                 :                : /*
                               3984                 :                :  * Store current remote/local lsn pair in the tracking list.
                               3985                 :                :  */
                               3986                 :                : void
 1350 akapila@postgresql.o     3987                 :            561 : store_flush_position(XLogRecPtr remote_lsn, XLogRecPtr local_lsn)
                               3988                 :                : {
                               3989                 :                :     FlushPosition *flushpos;
                               3990                 :                : 
                               3991                 :                :     /*
                               3992                 :                :      * Skip for parallel apply workers, because the lsn_mapping is maintained
                               3993                 :                :      * by the leader apply worker.
                               3994                 :                :      */
                               3995         [ +  + ]:            561 :     if (am_parallel_apply_worker())
                               3996                 :             18 :         return;
                               3997                 :                : 
                               3998                 :                :     /* Need to do this in permanent context */
 3421 peter_e@gmx.net          3999                 :            543 :     MemoryContextSwitchTo(ApplyContext);
                               4000                 :                : 
                               4001                 :                :     /* Track commit lsn  */
  284 michael@paquier.xyz      4002                 :            543 :     flushpos = palloc_object(FlushPosition);
 1350 akapila@postgresql.o     4003                 :            543 :     flushpos->local_end = local_lsn;
 3531 peter_e@gmx.net          4004                 :            543 :     flushpos->remote_end = remote_lsn;
                               4005                 :                : 
                               4006                 :            543 :     dlist_push_tail(&lsn_mapping, &flushpos->node);
 3421                          4007                 :            543 :     MemoryContextSwitchTo(ApplyMessageContext);
                               4008                 :                : }
                               4009                 :                : 
                               4010                 :                : 
                               4011                 :                : /* Update statistics of the worker. */
                               4012                 :                : static void
 3531                          4013                 :         209889 : UpdateWorkerStats(XLogRecPtr last_lsn, TimestampTz send_time, bool reply)
                               4014                 :                : {
                               4015                 :         209889 :     MyLogicalRepWorker->last_lsn = last_lsn;
                               4016                 :         209889 :     MyLogicalRepWorker->last_send_time = send_time;
                               4017                 :         209889 :     MyLogicalRepWorker->last_recv_time = GetCurrentTimestamp();
                               4018         [ +  + ]:         209889 :     if (reply)
                               4019                 :                :     {
                               4020                 :           2068 :         MyLogicalRepWorker->reply_lsn = last_lsn;
                               4021                 :           2068 :         MyLogicalRepWorker->reply_time = send_time;
                               4022                 :                :     }
                               4023                 :         209889 : }
                               4024                 :                : 
                               4025                 :                : /*
                               4026                 :                :  * Apply main loop.
                               4027                 :                :  */
                               4028                 :                : static void
 3468                          4029                 :            466 : LogicalRepApplyLoop(XLogRecPtr last_received)
                               4030                 :                : {
 2529 michael@paquier.xyz      4031                 :            466 :     TimestampTz last_recv_timestamp = GetCurrentTimestamp();
 2207 tgl@sss.pgh.pa.us        4032                 :            466 :     bool        ping_sent = false;
                               4033                 :                :     TimeLineID  tli;
                               4034                 :                :     ErrorContextCallback errcallback;
  424 akapila@postgresql.o     4035                 :            466 :     RetainDeadTuplesData rdt_data = {0};
                               4036                 :                : 
                               4037                 :                :     /*
                               4038                 :                :      * Init the ApplyMessageContext which we clean up after each replication
                               4039                 :                :      * protocol message.
                               4040                 :                :      */
 3421 peter_e@gmx.net          4041                 :            466 :     ApplyMessageContext = AllocSetContextCreate(ApplyContext,
                               4042                 :                :                                                 "ApplyMessageContext",
                               4043                 :                :                                                 ALLOCSET_DEFAULT_SIZES);
                               4044                 :                : 
                               4045                 :                :     /*
                               4046                 :                :      * This memory context is used for per-stream data when the streaming mode
                               4047                 :                :      * is enabled. This context is reset on each stream stop.
                               4048                 :                :      */
 2208 akapila@postgresql.o     4049                 :            466 :     LogicalStreamingContext = AllocSetContextCreate(ApplyContext,
                               4050                 :                :                                                     "LogicalStreamingContext",
                               4051                 :                :                                                     ALLOCSET_DEFAULT_SIZES);
                               4052                 :                : 
                               4053                 :                :     /* mark as idle, before starting to loop */
 3531 peter_e@gmx.net          4054                 :            466 :     pgstat_report_activity(STATE_IDLE, NULL);
                               4055                 :                : 
                               4056                 :                :     /*
                               4057                 :                :      * Push apply error context callback. Fields will be filled while applying
                               4058                 :                :      * a change.
                               4059                 :                :      */
 1850 akapila@postgresql.o     4060                 :            466 :     errcallback.callback = apply_error_callback;
                               4061                 :            466 :     errcallback.previous = error_context_stack;
                               4062                 :            466 :     error_context_stack = &errcallback;
 1350                          4063                 :            466 :     apply_error_context_stack = error_context_stack;
                               4064                 :                : 
                               4065                 :                :     /* This outer loop iterates once per wait. */
                               4066                 :                :     for (;;)
 3531 peter_e@gmx.net          4067                 :          33979 :     {
                               4068                 :          34445 :         pgsocket    fd = PGINVALID_SOCKET;
                               4069                 :                :         int         rc;
                               4070                 :                :         int         len;
                               4071                 :          34445 :         char       *buf = NULL;
                               4072                 :          34445 :         bool        endofstream = false;
                               4073                 :                :         long        wait_time;
                               4074                 :                : 
 3397                          4075         [ +  + ]:          34445 :         CHECK_FOR_INTERRUPTS();
                               4076                 :                : 
 3421                          4077                 :          34444 :         MemoryContextSwitchTo(ApplyMessageContext);
                               4078                 :                : 
 1957 alvherre@alvh.no-ip.     4079                 :          34444 :         len = walrcv_receive(LogRepWorkerWalRcvConn, &buf, &fd);
                               4080                 :                : 
 3531 peter_e@gmx.net          4081         [ +  + ]:          34424 :         if (len != 0)
                               4082                 :                :         {
                               4083                 :                :             /* Loop to process all available data (without blocking). */
                               4084                 :                :             for (;;)
                               4085                 :                :             {
                               4086         [ -  + ]:         243082 :                 CHECK_FOR_INTERRUPTS();
                               4087                 :                : 
                               4088         [ +  + ]:         243082 :                 if (len == 0)
                               4089                 :                :                 {
                               4090                 :          33178 :                     break;
                               4091                 :                :                 }
                               4092         [ +  + ]:         209904 :                 else if (len < 0)
                               4093                 :                :                 {
                               4094         [ +  - ]:             14 :                     ereport(LOG,
                               4095                 :                :                             (errmsg("data stream from publisher has ended")));
                               4096                 :             14 :                     endofstream = true;
                               4097                 :             14 :                     break;
                               4098                 :                :                 }
                               4099                 :                :                 else
                               4100                 :                :                 {
                               4101                 :                :                     int         c;
                               4102                 :                :                     StringInfoData s;
                               4103                 :                : 
 1201 akapila@postgresql.o     4104         [ -  + ]:         209890 :                     if (ConfigReloadPending)
                               4105                 :                :                     {
 1201 akapila@postgresql.o     4106                 :UBC           0 :                         ConfigReloadPending = false;
                               4107                 :              0 :                         ProcessConfigFile(PGC_SIGHUP);
                               4108                 :                :                     }
                               4109                 :                : 
                               4110                 :                :                     /* Reset timeout. */
 3531 peter_e@gmx.net          4111                 :CBC      209890 :                     last_recv_timestamp = GetCurrentTimestamp();
                               4112                 :         209890 :                     ping_sent = false;
                               4113                 :                : 
  424 akapila@postgresql.o     4114                 :         209890 :                     rdt_data.last_recv_time = last_recv_timestamp;
                               4115                 :                : 
                               4116                 :                :                     /* Ensure we are reading the data into our memory context. */
 3421 peter_e@gmx.net          4117                 :         209890 :                     MemoryContextSwitchTo(ApplyMessageContext);
                               4118                 :                : 
 1060 drowley@postgresql.o     4119                 :         209890 :                     initReadOnlyStringInfo(&s, buf, len);
                               4120                 :                : 
 3531 peter_e@gmx.net          4121                 :         209890 :                     c = pq_getmsgbyte(&s);
                               4122                 :                : 
  410 nathan@postgresql.or     4123         [ +  + ]:         209890 :                     if (c == PqReplMsg_WALData)
                               4124                 :                :                     {
                               4125                 :                :                         XLogRecPtr  start_lsn;
                               4126                 :                :                         XLogRecPtr  end_lsn;
                               4127                 :                :                         TimestampTz send_time;
                               4128                 :                : 
 3531 peter_e@gmx.net          4129                 :         205656 :                         start_lsn = pq_getmsgint64(&s);
                               4130                 :         205656 :                         end_lsn = pq_getmsgint64(&s);
 3496 tgl@sss.pgh.pa.us        4131                 :         205656 :                         send_time = pq_getmsgint64(&s);
                               4132                 :                : 
 3531 peter_e@gmx.net          4133         [ +  + ]:         205656 :                         if (last_received < start_lsn)
                               4134                 :         141420 :                             last_received = start_lsn;
                               4135                 :                : 
                               4136         [ -  + ]:         205656 :                         if (last_received < end_lsn)
 3531 peter_e@gmx.net          4137                 :UBC           0 :                             last_received = end_lsn;
                               4138                 :                : 
 3531 peter_e@gmx.net          4139                 :CBC      205656 :                         UpdateWorkerStats(last_received, send_time, false);
                               4140                 :                : 
                               4141                 :         205656 :                         apply_dispatch(&s);
                               4142                 :                : 
  424 akapila@postgresql.o     4143                 :         205585 :                         maybe_advance_nonremovable_xid(&rdt_data, false);
                               4144                 :                :                     }
  410 nathan@postgresql.or     4145         [ +  + ]:           4234 :                     else if (c == PqReplMsg_Keepalive)
                               4146                 :                :                     {
                               4147                 :                :                         XLogRecPtr  end_lsn;
                               4148                 :                :                         TimestampTz timestamp;
                               4149                 :                :                         bool        reply_requested;
                               4150                 :                : 
 3468 peter_e@gmx.net          4151                 :           2069 :                         end_lsn = pq_getmsgint64(&s);
 3496 tgl@sss.pgh.pa.us        4152                 :           2069 :                         timestamp = pq_getmsgint64(&s);
 3531 peter_e@gmx.net          4153                 :           2069 :                         reply_requested = pq_getmsgbyte(&s);
                               4154                 :                : 
 3468                          4155         [ +  + ]:           2069 :                         if (last_received < end_lsn)
                               4156                 :           1223 :                             last_received = end_lsn;
                               4157                 :                : 
                               4158                 :           2069 :                         send_feedback(last_received, reply_requested, false);
                               4159                 :                : 
  424 akapila@postgresql.o     4160                 :           2068 :                         maybe_advance_nonremovable_xid(&rdt_data, false);
                               4161                 :                : 
 3531 peter_e@gmx.net          4162                 :           2068 :                         UpdateWorkerStats(last_received, timestamp, true);
                               4163                 :                :                     }
  410 nathan@postgresql.or     4164         [ +  - ]:           2165 :                     else if (c == PqReplMsg_PrimaryStatusUpdate)
                               4165                 :                :                     {
  424 akapila@postgresql.o     4166                 :           2165 :                         rdt_data.remote_lsn = pq_getmsgint64(&s);
                               4167                 :           2165 :                         rdt_data.remote_oldestxid = FullTransactionIdFromU64((uint64) pq_getmsgint64(&s));
                               4168                 :           2165 :                         rdt_data.remote_nextxid = FullTransactionIdFromU64((uint64) pq_getmsgint64(&s));
                               4169                 :           2165 :                         rdt_data.reply_time = pq_getmsgint64(&s);
                               4170                 :                : 
                               4171                 :                :                         /*
                               4172                 :                :                          * This should never happen, see
                               4173                 :                :                          * ProcessStandbyPSRequestMessage. But if it happens
                               4174                 :                :                          * due to a bug, we don't want to proceed as it can
                               4175                 :                :                          * incorrectly advance oldest_nonremovable_xid.
                               4176                 :                :                          */
  318 alvherre@kurilemu.de     4177         [ -  + ]:           2165 :                         if (!XLogRecPtrIsValid(rdt_data.remote_lsn))
  424 akapila@postgresql.o     4178         [ #  # ]:UBC           0 :                             elog(ERROR, "cannot get the latest WAL position from the publisher");
                               4179                 :                : 
  424 akapila@postgresql.o     4180                 :CBC        2165 :                         maybe_advance_nonremovable_xid(&rdt_data, true);
                               4181                 :                : 
                               4182                 :           2165 :                         UpdateWorkerStats(last_received, rdt_data.reply_time, false);
                               4183                 :                :                     }
                               4184                 :                :                     /* other message types are purposefully ignored */
                               4185                 :                : 
 3421 peter_e@gmx.net          4186                 :         209818 :                     MemoryContextReset(ApplyMessageContext);
                               4187                 :                :                 }
                               4188                 :                : 
 1957 alvherre@alvh.no-ip.     4189                 :         209818 :                 len = walrcv_receive(LogRepWorkerWalRcvConn, &buf, &fd);
                               4190                 :                :             }
                               4191                 :                :         }
                               4192                 :                : 
                               4193                 :                :         /* confirm all writes so far */
 3368 tgl@sss.pgh.pa.us        4194                 :          34351 :         send_feedback(last_received, false, false);
                               4195                 :                : 
                               4196                 :                :         /* Reset the timestamp if no message was received */
  424 akapila@postgresql.o     4197                 :          34351 :         rdt_data.last_recv_time = 0;
                               4198                 :                : 
                               4199                 :          34351 :         maybe_advance_nonremovable_xid(&rdt_data, false);
                               4200                 :                : 
 2208                          4201   [ +  +  +  + ]:          34350 :         if (!in_remote_transaction && !in_streamed_transaction)
                               4202                 :                :         {
                               4203                 :                :             /*
                               4204                 :                :              * If we didn't get any transactions for a while there might be
                               4205                 :                :              * unconsumed invalidation messages in the queue, consume them
                               4206                 :                :              * now.
                               4207                 :                :              */
 3468 peter_e@gmx.net          4208                 :           4839 :             AcceptInvalidationMessages();
 3396                          4209                 :           4839 :             maybe_reread_subscription();
                               4210                 :                : 
                               4211                 :                :             /*
                               4212                 :                :              * Process any relations that are being synchronized in parallel
                               4213                 :                :              * and any newly added tables or sequences.
                               4214                 :                :              */
  339 akapila@postgresql.o     4215                 :           4794 :             ProcessSyncingRelations(last_received);
                               4216                 :                :         }
                               4217                 :                : 
                               4218                 :                :         /* Cleanup the memory. */
 1040 nathan@postgresql.or     4219                 :          34096 :         MemoryContextReset(ApplyMessageContext);
 3531 peter_e@gmx.net          4220                 :          34096 :         MemoryContextSwitchTo(TopMemoryContext);
                               4221                 :                : 
                               4222                 :                :         /* Check if we need to exit the streaming loop. */
                               4223         [ +  + ]:          34096 :         if (endofstream)
                               4224                 :             14 :             break;
                               4225                 :                : 
                               4226                 :                :         /*
                               4227                 :                :          * Wait for more data or latch.  If we have unflushed transactions,
                               4228                 :                :          * wake up after WalWriterDelay to see if they've been flushed yet (in
                               4229                 :                :          * which case we should send a feedback message).  Otherwise, there's
                               4230                 :                :          * no particular urgency about waking up unless we get data or a
                               4231                 :                :          * signal.
                               4232                 :                :          */
 3368 tgl@sss.pgh.pa.us        4233         [ +  + ]:          34082 :         if (!dlist_is_empty(&lsn_mapping))
                               4234                 :           2895 :             wait_time = WalWriterDelay;
                               4235                 :                :         else
                               4236                 :          31187 :             wait_time = NAPTIME_PER_CYCLE;
                               4237                 :                : 
                               4238                 :                :         /*
                               4239                 :                :          * Ensure to wake up when it's possible to advance the non-removable
                               4240                 :                :          * transaction ID, or when the retention duration may have exceeded
                               4241                 :                :          * max_retention_duration.
                               4242                 :                :          */
  383 akapila@postgresql.o     4243         [ +  + ]:          34082 :         if (MySubscription->retentionactive)
                               4244                 :                :         {
                               4245         [ +  + ]:           1951 :             if (rdt_data.phase == RDT_GET_CANDIDATE_XID &&
                               4246         [ +  - ]:            169 :                 rdt_data.xid_advance_interval)
                               4247                 :            169 :                 wait_time = Min(wait_time, rdt_data.xid_advance_interval);
                               4248         [ +  + ]:           1782 :             else if (MySubscription->maxretention > 0)
                               4249                 :              1 :                 wait_time = Min(wait_time, MySubscription->maxretention);
                               4250                 :                :         }
                               4251                 :                : 
 3393 andres@anarazel.de       4252                 :          34082 :         rc = WaitLatchOrSocket(MyLatch,
                               4253                 :                :                                WL_SOCKET_READABLE | WL_LATCH_SET |
                               4254                 :                :                                WL_TIMEOUT | WL_EXIT_ON_PM_DEATH,
                               4255                 :                :                                fd, wait_time,
                               4256                 :                :                                WAIT_EVENT_LOGICAL_APPLY_MAIN);
                               4257                 :                : 
                               4258         [ +  + ]:          34082 :         if (rc & WL_LATCH_SET)
                               4259                 :                :         {
                               4260                 :            797 :             ResetLatch(MyLatch);
                               4261         [ +  + ]:            797 :             CHECK_FOR_INTERRUPTS();
                               4262                 :                :         }
                               4263                 :                : 
 2469 rhaas@postgresql.org     4264         [ +  + ]:          33979 :         if (ConfigReloadPending)
                               4265                 :                :         {
                               4266                 :             12 :             ConfigReloadPending = false;
 3450 peter_e@gmx.net          4267                 :             12 :             ProcessConfigFile(PGC_SIGHUP);
                               4268                 :                :         }
                               4269                 :                : 
 3531                          4270         [ +  + ]:          33979 :         if (rc & WL_TIMEOUT)
                               4271                 :                :         {
                               4272                 :                :             /*
                               4273                 :                :              * We didn't receive anything new. If we haven't heard anything
                               4274                 :                :              * from the server for more than wal_receiver_timeout / 2, ping
                               4275                 :                :              * the server. Also, if it's been longer than
                               4276                 :                :              * wal_receiver_status_interval since the last update we sent,
                               4277                 :                :              * send a status update to the primary anyway, to report any
                               4278                 :                :              * progress in applying WAL.
                               4279                 :                :              */
                               4280                 :            304 :             bool        requestReply = false;
                               4281                 :                : 
                               4282                 :                :             /*
                               4283                 :                :              * Check if time since last receive from primary has reached the
                               4284                 :                :              * configured limit.
                               4285                 :                :              */
                               4286         [ +  - ]:            304 :             if (wal_receiver_timeout > 0)
                               4287                 :                :             {
                               4288                 :            304 :                 TimestampTz now = GetCurrentTimestamp();
                               4289                 :                :                 TimestampTz timeout;
                               4290                 :                : 
                               4291                 :            304 :                 timeout =
                               4292                 :            304 :                     TimestampTzPlusMilliseconds(last_recv_timestamp,
                               4293                 :                :                                                 wal_receiver_timeout);
                               4294                 :                : 
                               4295         [ -  + ]:            304 :                 if (now >= timeout)
 3531 peter_e@gmx.net          4296         [ #  # ]:UBC           0 :                     ereport(ERROR,
                               4297                 :                :                             (errcode(ERRCODE_CONNECTION_FAILURE),
                               4298                 :                :                              errmsg("terminating logical replication worker due to timeout")));
                               4299                 :                : 
                               4300                 :                :                 /* Check to see if it's time for a ping. */
 3531 peter_e@gmx.net          4301         [ +  - ]:CBC         304 :                 if (!ping_sent)
                               4302                 :                :                 {
                               4303                 :            304 :                     timeout = TimestampTzPlusMilliseconds(last_recv_timestamp,
                               4304                 :                :                                                           (wal_receiver_timeout / 2));
                               4305         [ -  + ]:            304 :                     if (now >= timeout)
                               4306                 :                :                     {
 3531 peter_e@gmx.net          4307                 :UBC           0 :                         requestReply = true;
                               4308                 :              0 :                         ping_sent = true;
                               4309                 :                :                     }
                               4310                 :                :                 }
                               4311                 :                :             }
                               4312                 :                : 
 3531 peter_e@gmx.net          4313                 :CBC         304 :             send_feedback(last_received, requestReply, requestReply);
                               4314                 :                : 
  424 akapila@postgresql.o     4315                 :            304 :             maybe_advance_nonremovable_xid(&rdt_data, false);
                               4316                 :                : 
                               4317                 :                :             /*
                               4318                 :                :              * Force reporting to ensure long idle periods don't lead to
                               4319                 :                :              * arbitrarily delayed stats. Stats can only be reported outside
                               4320                 :                :              * of (implicit or explicit) transactions. That shouldn't lead to
                               4321                 :                :              * stats being delayed for long, because transactions are either
                               4322                 :                :              * sent as a whole on commit or streamed. Streamed transactions
                               4323                 :                :              * are spilled to disk and applied on commit.
                               4324                 :                :              */
 1592 andres@anarazel.de       4325         [ +  - ]:            304 :             if (!IsTransactionState())
                               4326                 :            304 :                 pgstat_report_stat(true);
                               4327                 :                :         }
                               4328                 :                :     }
                               4329                 :                : 
                               4330                 :                :     /* Pop the error context stack */
 1850 akapila@postgresql.o     4331                 :             14 :     error_context_stack = errcallback.previous;
 1350                          4332                 :             14 :     apply_error_context_stack = error_context_stack;
                               4333                 :                : 
                               4334                 :                :     /* All done */
 1957 alvherre@alvh.no-ip.     4335                 :             14 :     walrcv_endstreaming(LogRepWorkerWalRcvConn, &tli);
 3531 peter_e@gmx.net          4336                 :UBC           0 : }
                               4337                 :                : 
                               4338                 :                : /*
                               4339                 :                :  * Send a Standby Status Update message to server.
                               4340                 :                :  *
                               4341                 :                :  * 'recvpos' is the latest LSN we've received data to, force is set if we need
                               4342                 :                :  * to send a response to avoid timeouts.
                               4343                 :                :  */
                               4344                 :                : static void
 3531 peter_e@gmx.net          4345                 :CBC       36724 : send_feedback(XLogRecPtr recvpos, bool force, bool requestReply)
                               4346                 :                : {
                               4347                 :                :     static StringInfo reply_message = NULL;
                               4348                 :                :     static TimestampTz send_time = 0;
                               4349                 :                : 
                               4350                 :                :     static XLogRecPtr last_recvpos = InvalidXLogRecPtr;
                               4351                 :                :     static XLogRecPtr last_writepos = InvalidXLogRecPtr;
                               4352                 :                : 
                               4353                 :                :     XLogRecPtr  writepos;
                               4354                 :                :     XLogRecPtr  flushpos;
                               4355                 :                :     TimestampTz now;
                               4356                 :                :     bool        have_pending_txes;
                               4357                 :                : 
                               4358                 :                :     /*
                               4359                 :                :      * If the user doesn't want status to be reported to the publisher, be
                               4360                 :                :      * sure to exit before doing anything at all.
                               4361                 :                :      */
                               4362   [ +  +  -  + ]:          36724 :     if (!force && wal_receiver_status_interval <= 0)
                               4363                 :          12659 :         return;
                               4364                 :                : 
                               4365                 :                :     /* It's legal to not pass a recvpos */
                               4366         [ -  + ]:          36724 :     if (recvpos < last_recvpos)
 3531 peter_e@gmx.net          4367                 :UBC           0 :         recvpos = last_recvpos;
                               4368                 :                : 
 3531 peter_e@gmx.net          4369                 :CBC       36724 :     get_flush_position(&writepos, &flushpos, &have_pending_txes);
                               4370                 :                : 
                               4371                 :                :     /*
                               4372                 :                :      * No outstanding transactions to flush, we can report the latest received
                               4373                 :                :      * position. This is important for synchronous replication.
                               4374                 :                :      */
                               4375         [ +  + ]:          36724 :     if (!have_pending_txes)
                               4376                 :          33313 :         flushpos = writepos = recvpos;
                               4377                 :                : 
                               4378         [ -  + ]:          36724 :     if (writepos < last_writepos)
 3531 peter_e@gmx.net          4379                 :UBC           0 :         writepos = last_writepos;
                               4380                 :                : 
 3531 peter_e@gmx.net          4381         [ +  + ]:CBC       36724 :     if (flushpos < last_flushpos)
                               4382                 :           3362 :         flushpos = last_flushpos;
                               4383                 :                : 
                               4384                 :          36724 :     now = GetCurrentTimestamp();
                               4385                 :                : 
                               4386                 :                :     /* if we've already reported everything we're good */
                               4387         [ +  + ]:          36724 :     if (!force &&
                               4388         [ +  + ]:          36721 :         writepos == last_writepos &&
                               4389         [ +  + ]:          12935 :         flushpos == last_flushpos &&
                               4390         [ +  + ]:          12744 :         !TimestampDifferenceExceeds(send_time, now,
                               4391                 :                :                                     wal_receiver_status_interval * 1000))
                               4392                 :          12659 :         return;
                               4393                 :          24065 :     send_time = now;
                               4394                 :                : 
                               4395         [ +  + ]:          24065 :     if (!reply_message)
                               4396                 :                :     {
 3413 bruce@momjian.us         4397                 :            466 :         MemoryContext oldctx = MemoryContextSwitchTo(ApplyContext);
                               4398                 :                : 
 3531 peter_e@gmx.net          4399                 :            466 :         reply_message = makeStringInfo();
                               4400                 :            466 :         MemoryContextSwitchTo(oldctx);
                               4401                 :                :     }
                               4402                 :                :     else
                               4403                 :          23599 :         resetStringInfo(reply_message);
                               4404                 :                : 
  410 nathan@postgresql.or     4405                 :          24065 :     pq_sendbyte(reply_message, PqReplMsg_StandbyStatusUpdate);
 3378 tgl@sss.pgh.pa.us        4406                 :          24065 :     pq_sendint64(reply_message, recvpos);   /* write */
                               4407                 :          24065 :     pq_sendint64(reply_message, flushpos);  /* flush */
                               4408                 :          24065 :     pq_sendint64(reply_message, writepos);  /* apply */
 3413 bruce@momjian.us         4409                 :          24065 :     pq_sendint64(reply_message, now);   /* sendTime */
 3531 peter_e@gmx.net          4410                 :          24065 :     pq_sendbyte(reply_message, requestReply);   /* replyRequested */
                               4411                 :                : 
  440 alvherre@kurilemu.de     4412         [ +  + ]:          24065 :     elog(DEBUG2, "sending feedback (force %d) to recv %X/%08X, write %X/%08X, flush %X/%08X",
                               4413                 :                :          force,
                               4414                 :                :          LSN_FORMAT_ARGS(recvpos),
                               4415                 :                :          LSN_FORMAT_ARGS(writepos),
                               4416                 :                :          LSN_FORMAT_ARGS(flushpos));
                               4417                 :                : 
 1957 alvherre@alvh.no-ip.     4418                 :          24065 :     walrcv_send(LogRepWorkerWalRcvConn,
                               4419                 :                :                 reply_message->data, reply_message->len);
                               4420                 :                : 
 3531 peter_e@gmx.net          4421         [ +  + ]:          24064 :     if (recvpos > last_recvpos)
                               4422                 :          23784 :         last_recvpos = recvpos;
                               4423         [ +  + ]:          24064 :     if (writepos > last_writepos)
                               4424                 :          23788 :         last_writepos = writepos;
                               4425         [ +  + ]:          24064 :     if (flushpos > last_flushpos)
                               4426                 :          23586 :         last_flushpos = flushpos;
                               4427                 :                : }
                               4428                 :                : 
                               4429                 :                : /*
                               4430                 :                :  * Attempt to advance the non-removable transaction ID.
                               4431                 :                :  *
                               4432                 :                :  * See comments atop worker.c for details.
                               4433                 :                :  */
                               4434                 :                : static void
  424 akapila@postgresql.o     4435                 :         244473 : maybe_advance_nonremovable_xid(RetainDeadTuplesData *rdt_data,
                               4436                 :                :                                bool status_received)
                               4437                 :                : {
                               4438         [ +  + ]:         244473 :     if (!can_advance_nonremovable_xid(rdt_data))
                               4439                 :         240055 :         return;
                               4440                 :                : 
                               4441                 :           4418 :     process_rdt_phase_transition(rdt_data, status_received);
                               4442                 :                : }
                               4443                 :                : 
                               4444                 :                : /*
                               4445                 :                :  * Preliminary check to determine if advancing the non-removable transaction ID
                               4446                 :                :  * is allowed.
                               4447                 :                :  */
                               4448                 :                : static bool
                               4449                 :         244473 : can_advance_nonremovable_xid(RetainDeadTuplesData *rdt_data)
                               4450                 :                : {
                               4451                 :                :     /*
                               4452                 :                :      * It is sufficient to manage non-removable transaction ID for a
                               4453                 :                :      * subscription by the main apply worker to detect update_deleted reliably
                               4454                 :                :      * even for table sync or parallel apply workers.
                               4455                 :                :      */
                               4456         [ +  + ]:         244473 :     if (!am_leader_apply_worker())
                               4457                 :            420 :         return false;
                               4458                 :                : 
                               4459                 :                :     /* No need to advance if retaining dead tuples is not required */
                               4460         [ +  + ]:         244053 :     if (!MySubscription->retaindeadtuples)
                               4461                 :         239635 :         return false;
                               4462                 :                : 
                               4463                 :           4418 :     return true;
                               4464                 :                : }
                               4465                 :                : 
                               4466                 :                : /*
                               4467                 :                :  * Process phase transitions during the non-removable transaction ID
                               4468                 :                :  * advancement. See comments atop worker.c for details of the transition.
                               4469                 :                :  */
                               4470                 :                : static void
                               4471                 :           6683 : process_rdt_phase_transition(RetainDeadTuplesData *rdt_data,
                               4472                 :                :                              bool status_received)
                               4473                 :                : {
                               4474   [ +  +  +  +  :           6683 :     switch (rdt_data->phase)
                                           +  +  - ]
                               4475                 :                :     {
                               4476                 :            411 :         case RDT_GET_CANDIDATE_XID:
                               4477                 :            411 :             get_candidate_xid(rdt_data);
                               4478                 :            411 :             break;
                               4479                 :           2166 :         case RDT_REQUEST_PUBLISHER_STATUS:
                               4480                 :           2166 :             request_publisher_status(rdt_data);
                               4481                 :           2166 :             break;
                               4482                 :           3983 :         case RDT_WAIT_FOR_PUBLISHER_STATUS:
                               4483                 :           3983 :             wait_for_publisher_status(rdt_data, status_received);
                               4484                 :           3983 :             break;
                               4485                 :            121 :         case RDT_WAIT_FOR_LOCAL_FLUSH:
                               4486                 :            121 :             wait_for_local_flush(rdt_data);
                               4487                 :            121 :             break;
  383                          4488                 :              1 :         case RDT_STOP_CONFLICT_INFO_RETENTION:
                               4489                 :              1 :             stop_conflict_info_retention(rdt_data);
                               4490                 :              1 :             break;
  370                          4491                 :              1 :         case RDT_RESUME_CONFLICT_INFO_RETENTION:
                               4492                 :              1 :             resume_conflict_info_retention(rdt_data);
  370 akapila@postgresql.o     4493                 :UBC           0 :             break;
                               4494                 :                :     }
  424 akapila@postgresql.o     4495                 :CBC        6682 : }
                               4496                 :                : 
                               4497                 :                : /*
                               4498                 :                :  * Workhorse for the RDT_GET_CANDIDATE_XID phase.
                               4499                 :                :  */
                               4500                 :                : static void
                               4501                 :            411 : get_candidate_xid(RetainDeadTuplesData *rdt_data)
                               4502                 :                : {
                               4503                 :                :     TransactionId oldest_running_xid;
                               4504                 :                :     TimestampTz now;
                               4505                 :                : 
                               4506                 :                :     /*
                               4507                 :                :      * Use last_recv_time when applying changes in the loop to avoid
                               4508                 :                :      * unnecessary system time retrieval. If last_recv_time is not available,
                               4509                 :                :      * obtain the current timestamp.
                               4510                 :                :      */
                               4511         [ +  + ]:            411 :     now = rdt_data->last_recv_time ? rdt_data->last_recv_time : GetCurrentTimestamp();
                               4512                 :                : 
                               4513                 :                :     /*
                               4514                 :                :      * Compute the candidate_xid and request the publisher status at most once
                               4515                 :                :      * per xid_advance_interval. Refer to adjust_xid_advance_interval() for
                               4516                 :                :      * details on how this value is dynamically adjusted. This is to avoid
                               4517                 :                :      * using CPU and network resources without making much progress.
                               4518                 :                :      */
                               4519         [ +  + ]:            411 :     if (!TimestampDifferenceExceeds(rdt_data->candidate_xid_time, now,
                               4520                 :                :                                     rdt_data->xid_advance_interval))
                               4521                 :            314 :         return;
                               4522                 :                : 
                               4523                 :                :     /*
                               4524                 :                :      * Immediately update the timer, even if the function returns later
                               4525                 :                :      * without setting candidate_xid due to inactivity on the subscriber. This
                               4526                 :                :      * avoids frequent calls to GetOldestActiveTransactionId.
                               4527                 :                :      */
                               4528                 :             97 :     rdt_data->candidate_xid_time = now;
                               4529                 :                : 
                               4530                 :                :     /*
                               4531                 :                :      * Consider transactions in the current database, as only dead tuples from
                               4532                 :                :      * this database are required for conflict detection.
                               4533                 :                :      */
                               4534                 :             97 :     oldest_running_xid = GetOldestActiveTransactionId(false, false);
                               4535                 :                : 
                               4536                 :                :     /*
                               4537                 :                :      * Oldest active transaction ID (oldest_running_xid) can't be behind any
                               4538                 :                :      * of its previously computed value.
                               4539                 :                :      */
                               4540         [ -  + ]:             97 :     Assert(TransactionIdPrecedesOrEquals(MyLogicalRepWorker->oldest_nonremovable_xid,
                               4541                 :                :                                          oldest_running_xid));
                               4542                 :                : 
                               4543                 :                :     /* Return if the oldest_nonremovable_xid cannot be advanced */
                               4544         [ +  + ]:             97 :     if (TransactionIdEquals(MyLogicalRepWorker->oldest_nonremovable_xid,
                               4545                 :                :                             oldest_running_xid))
                               4546                 :                :     {
                               4547                 :             45 :         adjust_xid_advance_interval(rdt_data, false);
                               4548                 :             45 :         return;
                               4549                 :                :     }
                               4550                 :                : 
                               4551                 :             52 :     adjust_xid_advance_interval(rdt_data, true);
                               4552                 :                : 
                               4553                 :             52 :     rdt_data->candidate_xid = oldest_running_xid;
                               4554                 :             52 :     rdt_data->phase = RDT_REQUEST_PUBLISHER_STATUS;
                               4555                 :                : 
                               4556                 :                :     /* process the next phase */
                               4557                 :             52 :     process_rdt_phase_transition(rdt_data, false);
                               4558                 :                : }
                               4559                 :                : 
                               4560                 :                : /*
                               4561                 :                :  * Workhorse for the RDT_REQUEST_PUBLISHER_STATUS phase.
                               4562                 :                :  */
                               4563                 :                : static void
                               4564                 :           2166 : request_publisher_status(RetainDeadTuplesData *rdt_data)
                               4565                 :                : {
                               4566                 :                :     static StringInfo request_message = NULL;
                               4567                 :                : 
                               4568         [ +  + ]:           2166 :     if (!request_message)
                               4569                 :                :     {
                               4570                 :             13 :         MemoryContext oldctx = MemoryContextSwitchTo(ApplyContext);
                               4571                 :                : 
                               4572                 :             13 :         request_message = makeStringInfo();
                               4573                 :             13 :         MemoryContextSwitchTo(oldctx);
                               4574                 :                :     }
                               4575                 :                :     else
                               4576                 :           2153 :         resetStringInfo(request_message);
                               4577                 :                : 
                               4578                 :                :     /*
                               4579                 :                :      * Send the current time to update the remote walsender's latest reply
                               4580                 :                :      * message received time.
                               4581                 :                :      */
  410 nathan@postgresql.or     4582                 :           2166 :     pq_sendbyte(request_message, PqReplMsg_PrimaryStatusRequest);
  424 akapila@postgresql.o     4583                 :           2166 :     pq_sendint64(request_message, GetCurrentTimestamp());
                               4584                 :                : 
                               4585         [ +  + ]:           2166 :     elog(DEBUG2, "sending publisher status request message");
                               4586                 :                : 
                               4587                 :                :     /* Send a request for the publisher status */
                               4588                 :           2166 :     walrcv_send(LogRepWorkerWalRcvConn,
                               4589                 :                :                 request_message->data, request_message->len);
                               4590                 :                : 
                               4591                 :           2166 :     rdt_data->phase = RDT_WAIT_FOR_PUBLISHER_STATUS;
                               4592                 :                : 
                               4593                 :                :     /*
                               4594                 :                :      * Skip calling maybe_advance_nonremovable_xid() since further transition
                               4595                 :                :      * is possible only once we receive the publisher status message.
                               4596                 :                :      */
                               4597                 :           2166 : }
                               4598                 :                : 
                               4599                 :                : /*
                               4600                 :                :  * Workhorse for the RDT_WAIT_FOR_PUBLISHER_STATUS phase.
                               4601                 :                :  */
                               4602                 :                : static void
                               4603                 :           3983 : wait_for_publisher_status(RetainDeadTuplesData *rdt_data,
                               4604                 :                :                           bool status_received)
                               4605                 :                : {
                               4606                 :                :     /*
                               4607                 :                :      * Return if we have requested but not yet received the publisher status.
                               4608                 :                :      */
                               4609         [ +  + ]:           3983 :     if (!status_received)
                               4610                 :           1818 :         return;
                               4611                 :                : 
                               4612                 :                :     /*
                               4613                 :                :      * We don't need to maintain oldest_nonremovable_xid if we decide to stop
                               4614                 :                :      * retaining conflict information for this worker.
                               4615                 :                :      */
  383                          4616         [ -  + ]:           2165 :     if (should_stop_conflict_info_retention(rdt_data))
                               4617                 :                :     {
  370 akapila@postgresql.o     4618                 :UBC           0 :         rdt_data->phase = RDT_STOP_CONFLICT_INFO_RETENTION;
  383                          4619                 :              0 :         return;
                               4620                 :                :     }
                               4621                 :                : 
  424 akapila@postgresql.o     4622         [ +  + ]:CBC        2165 :     if (!FullTransactionIdIsValid(rdt_data->remote_wait_for))
                               4623                 :             51 :         rdt_data->remote_wait_for = rdt_data->remote_nextxid;
                               4624                 :                : 
                               4625                 :                :     /*
                               4626                 :                :      * Check if all remote concurrent transactions that were active at the
                               4627                 :                :      * first status request have now completed. If completed, proceed to the
                               4628                 :                :      * next phase; otherwise, continue checking the publisher status until
                               4629                 :                :      * these transactions finish.
                               4630                 :                :      *
                               4631                 :                :      * It's possible that transactions in the commit phase during the last
                               4632                 :                :      * cycle have now finished committing, but remote_oldestxid remains older
                               4633                 :                :      * than remote_wait_for. This can happen if some old transaction came in
                               4634                 :                :      * the commit phase when we requested status in this cycle. We do not
                               4635                 :                :      * handle this case explicitly as it's rare and the benefit doesn't
                               4636                 :                :      * justify the required complexity. Tracking would require either caching
                               4637                 :                :      * all xids at the publisher or sending them to subscribers. The condition
                               4638                 :                :      * will resolve naturally once the remaining transactions are finished.
                               4639                 :                :      *
                               4640                 :                :      * Directly advancing the non-removable transaction ID is possible if
                               4641                 :                :      * there are no activities on the publisher since the last advancement
                               4642                 :                :      * cycle. However, it requires maintaining two fields, last_remote_nextxid
                               4643                 :                :      * and last_remote_lsn, within the structure for comparison with the
                               4644                 :                :      * current cycle's values. Considering the minimal cost of continuing in
                               4645                 :                :      * RDT_WAIT_FOR_LOCAL_FLUSH without awaiting changes, we opted not to
                               4646                 :                :      * advance the transaction ID here.
                               4647                 :                :      */
                               4648         [ +  + ]:           2165 :     if (FullTransactionIdPrecedesOrEquals(rdt_data->remote_wait_for,
                               4649                 :                :                                           rdt_data->remote_oldestxid))
                               4650                 :             51 :         rdt_data->phase = RDT_WAIT_FOR_LOCAL_FLUSH;
                               4651                 :                :     else
                               4652                 :           2114 :         rdt_data->phase = RDT_REQUEST_PUBLISHER_STATUS;
                               4653                 :                : 
                               4654                 :                :     /* process the next phase */
                               4655                 :           2165 :     process_rdt_phase_transition(rdt_data, false);
                               4656                 :                : }
                               4657                 :                : 
                               4658                 :                : /*
                               4659                 :                :  * Workhorse for the RDT_WAIT_FOR_LOCAL_FLUSH phase.
                               4660                 :                :  */
                               4661                 :                : static void
                               4662                 :            121 : wait_for_local_flush(RetainDeadTuplesData *rdt_data)
                               4663                 :                : {
  318 alvherre@kurilemu.de     4664   [ +  -  -  + ]:            121 :     Assert(XLogRecPtrIsValid(rdt_data->remote_lsn) &&
                               4665                 :                :            TransactionIdIsValid(rdt_data->candidate_xid));
                               4666                 :                : 
                               4667                 :                :     /*
                               4668                 :                :      * We expect the publisher and subscriber clocks to be in sync using time
                               4669                 :                :      * sync service like NTP. Otherwise, we will advance this worker's
                               4670                 :                :      * oldest_nonremovable_xid prematurely, leading to the removal of rows
                               4671                 :                :      * required to detect update_deleted reliably. This check primarily
                               4672                 :                :      * addresses scenarios where the publisher's clock falls behind; if the
                               4673                 :                :      * publisher's clock is ahead, subsequent transactions will naturally bear
                               4674                 :                :      * later commit timestamps, conforming to the design outlined atop
                               4675                 :                :      * worker.c.
                               4676                 :                :      *
                               4677                 :                :      * XXX Consider waiting for the publisher's clock to catch up with the
                               4678                 :                :      * subscriber's before proceeding to the next phase.
                               4679                 :                :      */
  424 akapila@postgresql.o     4680         [ -  + ]:            121 :     if (TimestampDifferenceExceeds(rdt_data->reply_time,
                               4681                 :                :                                    rdt_data->candidate_xid_time, 0))
  424 akapila@postgresql.o     4682         [ #  # ]:UBC           0 :         ereport(ERROR,
                               4683                 :                :                 errmsg_internal("oldest_nonremovable_xid transaction ID could be advanced prematurely"),
                               4684                 :                :                 errdetail_internal("The clock on the publisher is behind that of the subscriber."));
                               4685                 :                : 
                               4686                 :                :     /*
                               4687                 :                :      * Do not attempt to advance the non-removable transaction ID when table
                               4688                 :                :      * sync is in progress. During this time, changes from a single
                               4689                 :                :      * transaction may be applied by multiple table sync workers corresponding
                               4690                 :                :      * to the target tables. So, it's necessary for all table sync workers to
                               4691                 :                :      * apply and flush the corresponding changes before advancing the
                               4692                 :                :      * transaction ID, otherwise, dead tuples that are still needed for
                               4693                 :                :      * conflict detection in table sync workers could be removed prematurely.
                               4694                 :                :      * However, confirming the apply and flush progress across all table sync
                               4695                 :                :      * workers is complex and not worth the effort, so we simply return if not
                               4696                 :                :      * all tables are in the READY state.
                               4697                 :                :      *
                               4698                 :                :      * Advancing the transaction ID is necessary even when no tables are
                               4699                 :                :      * currently subscribed, to avoid retaining dead tuples unnecessarily.
                               4700                 :                :      * While it might seem safe to skip all phases and directly assign
                               4701                 :                :      * candidate_xid to oldest_nonremovable_xid during the
                               4702                 :                :      * RDT_GET_CANDIDATE_XID phase in such cases, this is unsafe. If users
                               4703                 :                :      * concurrently add tables to the subscription, the apply worker may not
                               4704                 :                :      * process invalidations in time. Consequently,
                               4705                 :                :      * HasSubscriptionTablesCached() might miss the new tables, leading to
                               4706                 :                :      * premature advancement of oldest_nonremovable_xid.
                               4707                 :                :      *
                               4708                 :                :      * Performing the check during RDT_WAIT_FOR_LOCAL_FLUSH is safe, as
                               4709                 :                :      * invalidations are guaranteed to be processed before applying changes
                               4710                 :                :      * from newly added tables while waiting for the local flush to reach
                               4711                 :                :      * remote_lsn.
                               4712                 :                :      *
                               4713                 :                :      * Additionally, even if we check for subscription tables during
                               4714                 :                :      * RDT_GET_CANDIDATE_XID, they might be dropped before reaching
                               4715                 :                :      * RDT_WAIT_FOR_LOCAL_FLUSH. Therefore, it's still necessary to verify
                               4716                 :                :      * subscription tables at this stage to prevent unnecessary tuple
                               4717                 :                :      * retention.
                               4718                 :                :      */
  339 akapila@postgresql.o     4719   [ +  +  +  + ]:CBC         121 :     if (HasSubscriptionTablesCached() && !AllTablesyncsReady())
                               4720                 :                :     {
                               4721                 :                :         TimestampTz now;
                               4722                 :                : 
  383                          4723                 :             22 :         now = rdt_data->last_recv_time
                               4724         [ +  + ]:             11 :             ? rdt_data->last_recv_time : GetCurrentTimestamp();
                               4725                 :                : 
                               4726                 :                :         /*
                               4727                 :                :          * Record the time spent waiting for table sync, it is needed for the
                               4728                 :                :          * timeout check in should_stop_conflict_info_retention().
                               4729                 :                :          */
                               4730                 :             11 :         rdt_data->table_sync_wait_time =
                               4731                 :             11 :             TimestampDifferenceMilliseconds(rdt_data->candidate_xid_time, now);
                               4732                 :                : 
                               4733                 :             11 :         return;
                               4734                 :                :     }
                               4735                 :                : 
                               4736                 :                :     /*
                               4737                 :                :      * We don't need to maintain oldest_nonremovable_xid if we decide to stop
                               4738                 :                :      * retaining conflict information for this worker.
                               4739                 :                :      */
                               4740         [ +  + ]:            110 :     if (should_stop_conflict_info_retention(rdt_data))
                               4741                 :                :     {
  370                          4742                 :              1 :         rdt_data->phase = RDT_STOP_CONFLICT_INFO_RETENTION;
  424                          4743                 :              1 :         return;
                               4744                 :                :     }
                               4745                 :                : 
                               4746                 :                :     /*
                               4747                 :                :      * Update and check the remote flush position if we are applying changes
                               4748                 :                :      * in a loop. This is done at most once per WalWriterDelay to avoid
                               4749                 :                :      * performing costly operations in get_flush_position() too frequently
                               4750                 :                :      * during change application.
                               4751                 :                :      */
                               4752   [ +  +  +  +  :            148 :     if (last_flushpos < rdt_data->remote_lsn && rdt_data->last_recv_time &&
                                              +  + ]
                               4753                 :             39 :         TimestampDifferenceExceeds(rdt_data->flushpos_update_time,
                               4754                 :                :                                    rdt_data->last_recv_time, WalWriterDelay))
                               4755                 :                :     {
                               4756                 :                :         XLogRecPtr  writepos;
                               4757                 :                :         XLogRecPtr  flushpos;
                               4758                 :                :         bool        have_pending_txes;
                               4759                 :                : 
                               4760                 :                :         /* Fetch the latest remote flush position */
                               4761                 :             15 :         get_flush_position(&writepos, &flushpos, &have_pending_txes);
                               4762                 :                : 
                               4763         [ +  + ]:             15 :         if (flushpos > last_flushpos)
  424 akapila@postgresql.o     4764                 :GBC           1 :             last_flushpos = flushpos;
                               4765                 :                : 
  424 akapila@postgresql.o     4766                 :CBC          15 :         rdt_data->flushpos_update_time = rdt_data->last_recv_time;
                               4767                 :                :     }
                               4768                 :                : 
                               4769                 :                :     /* Return to wait for the changes to be applied */
                               4770         [ +  + ]:            109 :     if (last_flushpos < rdt_data->remote_lsn)
                               4771                 :             60 :         return;
                               4772                 :                : 
                               4773                 :                :     /*
                               4774                 :                :      * Reaching this point implies should_stop_conflict_info_retention()
                               4775                 :                :      * returned false earlier, meaning that the most recent duration for
                               4776                 :                :      * advancing the non-removable transaction ID is within the
                               4777                 :                :      * max_retention_duration or max_retention_duration is set to 0.
                               4778                 :                :      *
                               4779                 :                :      * Therefore, if conflict info retention was previously stopped due to a
                               4780                 :                :      * timeout, it is now safe to resume retention.
                               4781                 :                :      */
  370                          4782         [ +  + ]:             49 :     if (!MySubscription->retentionactive)
                               4783                 :                :     {
                               4784                 :              1 :         rdt_data->phase = RDT_RESUME_CONFLICT_INFO_RETENTION;
                               4785                 :              1 :         return;
                               4786                 :                :     }
                               4787                 :                : 
                               4788                 :                :     /*
                               4789                 :                :      * Reaching here means the remote WAL position has been received, and all
                               4790                 :                :      * transactions up to that position on the publisher have been applied and
                               4791                 :                :      * flushed locally. So, we can advance the non-removable transaction ID.
                               4792                 :                :      */
  424                          4793                 :             48 :     SpinLockAcquire(&MyLogicalRepWorker->relmutex);
                               4794                 :             48 :     MyLogicalRepWorker->oldest_nonremovable_xid = rdt_data->candidate_xid;
                               4795                 :             48 :     SpinLockRelease(&MyLogicalRepWorker->relmutex);
                               4796                 :                : 
  402 heikki.linnakangas@i     4797         [ +  + ]:             48 :     elog(DEBUG2, "confirmed flush up to remote lsn %X/%08X: new oldest_nonremovable_xid %u",
                               4798                 :                :          LSN_FORMAT_ARGS(rdt_data->remote_lsn),
                               4799                 :                :          rdt_data->candidate_xid);
                               4800                 :                : 
                               4801                 :                :     /* Notify launcher to update the xmin of the conflict slot */
  424 akapila@postgresql.o     4802                 :             48 :     ApplyLauncherWakeup();
                               4803                 :                : 
  383                          4804                 :             48 :     reset_retention_data_fields(rdt_data);
                               4805                 :                : 
                               4806                 :                :     /* process the next phase */
                               4807                 :             48 :     process_rdt_phase_transition(rdt_data, false);
                               4808                 :                : }
                               4809                 :                : 
                               4810                 :                : /*
                               4811                 :                :  * Check whether conflict information retention should be stopped due to
                               4812                 :                :  * exceeding the maximum wait time (max_retention_duration).
                               4813                 :                :  *
                               4814                 :                :  * If retention should be stopped, return true. Otherwise, return false.
                               4815                 :                :  */
                               4816                 :                : static bool
                               4817                 :           2275 : should_stop_conflict_info_retention(RetainDeadTuplesData *rdt_data)
                               4818                 :                : {
                               4819                 :                :     TimestampTz now;
                               4820                 :                : 
                               4821         [ -  + ]:           2275 :     Assert(TransactionIdIsValid(rdt_data->candidate_xid));
                               4822   [ +  +  -  + ]:           2275 :     Assert(rdt_data->phase == RDT_WAIT_FOR_PUBLISHER_STATUS ||
                               4823                 :                :            rdt_data->phase == RDT_WAIT_FOR_LOCAL_FLUSH);
                               4824                 :                : 
                               4825         [ +  + ]:           2275 :     if (!MySubscription->maxretention)
                               4826                 :           2274 :         return false;
                               4827                 :                : 
                               4828                 :                :     /*
                               4829                 :                :      * Use last_recv_time when applying changes in the loop to avoid
                               4830                 :                :      * unnecessary system time retrieval. If last_recv_time is not available,
                               4831                 :                :      * obtain the current timestamp.
                               4832                 :                :      */
                               4833         [ -  + ]:              1 :     now = rdt_data->last_recv_time ? rdt_data->last_recv_time : GetCurrentTimestamp();
                               4834                 :                : 
                               4835                 :                :     /*
                               4836                 :                :      * Return early if the wait time has not exceeded the configured maximum
                               4837                 :                :      * (max_retention_duration). Time spent waiting for table synchronization
                               4838                 :                :      * is excluded from this calculation, as it occurs infrequently.
                               4839                 :                :      */
                               4840         [ -  + ]:              1 :     if (!TimestampDifferenceExceeds(rdt_data->candidate_xid_time, now,
                               4841                 :              1 :                                     MySubscription->maxretention +
                               4842                 :              1 :                                     rdt_data->table_sync_wait_time))
  383 akapila@postgresql.o     4843                 :UBC           0 :         return false;
                               4844                 :                : 
  383 akapila@postgresql.o     4845                 :CBC           1 :     return true;
                               4846                 :                : }
                               4847                 :                : 
                               4848                 :                : /*
                               4849                 :                :  * Workhorse for the RDT_STOP_CONFLICT_INFO_RETENTION phase.
                               4850                 :                :  */
                               4851                 :                : static void
                               4852                 :              1 : stop_conflict_info_retention(RetainDeadTuplesData *rdt_data)
                               4853                 :                : {
                               4854                 :                :     /* Stop retention if not yet */
  370                          4855         [ +  - ]:              1 :     if (MySubscription->retentionactive)
                               4856                 :                :     {
                               4857                 :                :         /*
                               4858                 :                :          * If the retention status cannot be updated (e.g., due to active
                               4859                 :                :          * transaction), skip further processing to avoid inconsistent
                               4860                 :                :          * retention behavior.
                               4861                 :                :          */
                               4862         [ -  + ]:              1 :         if (!update_retention_status(false))
  370 akapila@postgresql.o     4863                 :UBC           0 :             return;
                               4864                 :                : 
  370 akapila@postgresql.o     4865                 :CBC           1 :         SpinLockAcquire(&MyLogicalRepWorker->relmutex);
                               4866                 :              1 :         MyLogicalRepWorker->oldest_nonremovable_xid = InvalidTransactionId;
                               4867                 :              1 :         SpinLockRelease(&MyLogicalRepWorker->relmutex);
                               4868                 :                : 
                               4869         [ +  - ]:              1 :         ereport(LOG,
                               4870                 :                :                 errmsg("logical replication worker for subscription \"%s\" has stopped retaining the information for detecting conflicts",
                               4871                 :                :                        MySubscription->name),
                               4872                 :                :                 errdetail("Retention is stopped because the apply process has not caught up with the publisher within the configured max_retention_duration."));
                               4873                 :                :     }
                               4874                 :                : 
                               4875         [ -  + ]:              1 :     Assert(!TransactionIdIsValid(MyLogicalRepWorker->oldest_nonremovable_xid));
                               4876                 :                : 
                               4877                 :                :     /*
                               4878                 :                :      * If retention has been stopped, reset to the initial phase to retry
                               4879                 :                :      * resuming retention. This reset is required to recalculate the current
                               4880                 :                :      * wait time and resume retention if the time falls within
                               4881                 :                :      * max_retention_duration.
                               4882                 :                :      */
                               4883                 :              1 :     reset_retention_data_fields(rdt_data);
                               4884                 :                : }
                               4885                 :                : 
                               4886                 :                : /*
                               4887                 :                :  * Workhorse for the RDT_RESUME_CONFLICT_INFO_RETENTION phase.
                               4888                 :                :  */
                               4889                 :                : static void
                               4890                 :              1 : resume_conflict_info_retention(RetainDeadTuplesData *rdt_data)
                               4891                 :                : {
                               4892                 :                :     /* We can't resume retention without updating retention status. */
                               4893         [ -  + ]:              1 :     if (!update_retention_status(true))
  370 akapila@postgresql.o     4894                 :UBC           0 :         return;
                               4895                 :                : 
  370 akapila@postgresql.o     4896   [ +  -  -  + ]:CBC           1 :     ereport(LOG,
                               4897                 :                :             errmsg("logical replication worker for subscription \"%s\" will resume retaining the information for detecting conflicts",
                               4898                 :                :                    MySubscription->name),
                               4899                 :                :             MySubscription->maxretention
                               4900                 :                :             ? errdetail("Retention is re-enabled because the apply process has caught up with the publisher within the configured max_retention_duration.")
                               4901                 :                :             : errdetail("Retention is re-enabled because max_retention_duration has been set to unlimited."));
                               4902                 :                : 
                               4903                 :                :     /*
                               4904                 :                :      * Restart the worker to let the launcher initialize
                               4905                 :                :      * oldest_nonremovable_xid at startup.
                               4906                 :                :      *
                               4907                 :                :      * While it's technically possible to derive this value on-the-fly using
                               4908                 :                :      * the conflict detection slot's xmin, doing so risks a race condition:
                               4909                 :                :      * the launcher might clean slot.xmin just after retention resumes. This
                               4910                 :                :      * would make oldest_nonremovable_xid unreliable, especially during xid
                               4911                 :                :      * wraparound.
                               4912                 :                :      *
                               4913                 :                :      * Although this can be prevented by introducing heavy weight locking, the
                               4914                 :                :      * complexity it will bring doesn't seem worthwhile given how rarely
                               4915                 :                :      * retention is resumed.
                               4916                 :                :      */
                               4917                 :              1 :     apply_worker_exit();
                               4918                 :                : }
                               4919                 :                : 
                               4920                 :                : /*
                               4921                 :                :  * Updates pg_subscription.subretentionactive to the given value within a
                               4922                 :                :  * new transaction.
                               4923                 :                :  *
                               4924                 :                :  * If already inside an active transaction, skips the update and returns
                               4925                 :                :  * false.
                               4926                 :                :  *
                               4927                 :                :  * Returns true if the update is successfully performed.
                               4928                 :                :  */
                               4929                 :                : static bool
                               4930                 :              2 : update_retention_status(bool active)
                               4931                 :                : {
                               4932                 :                :     /*
                               4933                 :                :      * Do not update the catalog during an active transaction. The transaction
                               4934                 :                :      * may be started during change application, leading to a possible
                               4935                 :                :      * rollback of catalog updates if the application fails subsequently.
                               4936                 :                :      */
  383                          4937         [ -  + ]:              2 :     if (IsTransactionState())
  370 akapila@postgresql.o     4938                 :UBC           0 :         return false;
                               4939                 :                : 
  383 akapila@postgresql.o     4940                 :CBC           2 :     StartTransactionCommand();
                               4941                 :                : 
                               4942                 :                :     /*
                               4943                 :                :      * Updating pg_subscription might involve TOAST table access, so ensure we
                               4944                 :                :      * have a valid snapshot.
                               4945                 :                :      */
                               4946                 :              2 :     PushActiveSnapshot(GetTransactionSnapshot());
                               4947                 :                : 
                               4948                 :                :     /* Update pg_subscription.subretentionactive */
  370                          4949                 :              2 :     UpdateDeadTupleRetentionStatus(MySubscription->oid, active);
                               4950                 :                : 
  383                          4951                 :              2 :     PopActiveSnapshot();
                               4952                 :              2 :     CommitTransactionCommand();
                               4953                 :                : 
                               4954                 :                :     /* Notify launcher to update the conflict slot */
                               4955                 :              2 :     ApplyLauncherWakeup();
                               4956                 :                : 
  370                          4957                 :              2 :     MySubscription->retentionactive = active;
                               4958                 :                : 
                               4959                 :              2 :     return true;
                               4960                 :                : }
                               4961                 :                : 
                               4962                 :                : /*
                               4963                 :                :  * Reset all data fields of RetainDeadTuplesData except those used to
                               4964                 :                :  * determine the timing for the next round of transaction ID advancement. We
                               4965                 :                :  * can even use flushpos_update_time in the next round to decide whether to get
                               4966                 :                :  * the latest flush position.
                               4967                 :                :  */
                               4968                 :                : static void
  383                          4969                 :             49 : reset_retention_data_fields(RetainDeadTuplesData *rdt_data)
                               4970                 :                : {
  424                          4971                 :             49 :     rdt_data->phase = RDT_GET_CANDIDATE_XID;
                               4972                 :             49 :     rdt_data->remote_lsn = InvalidXLogRecPtr;
                               4973                 :             49 :     rdt_data->remote_oldestxid = InvalidFullTransactionId;
                               4974                 :             49 :     rdt_data->remote_nextxid = InvalidFullTransactionId;
                               4975                 :             49 :     rdt_data->reply_time = 0;
                               4976                 :             49 :     rdt_data->remote_wait_for = InvalidFullTransactionId;
                               4977                 :             49 :     rdt_data->candidate_xid = InvalidTransactionId;
  383                          4978                 :             49 :     rdt_data->table_sync_wait_time = 0;
  424                          4979                 :             49 : }
                               4980                 :                : 
                               4981                 :                : /*
                               4982                 :                :  * Adjust the interval for advancing non-removable transaction IDs.
                               4983                 :                :  *
                               4984                 :                :  * If there is no activity on the node or retention has been stopped, we
                               4985                 :                :  * progressively double the interval used to advance non-removable transaction
                               4986                 :                :  * ID. This helps conserve CPU and network resources when there's little benefit
                               4987                 :                :  * to frequent updates.
                               4988                 :                :  *
                               4989                 :                :  * The interval is capped by the lowest of the following:
                               4990                 :                :  * - wal_receiver_status_interval (if set and retention is active),
                               4991                 :                :  * - a default maximum of 3 minutes,
                               4992                 :                :  * - max_retention_duration (if retention is active).
                               4993                 :                :  *
                               4994                 :                :  * This ensures the interval never exceeds the retention boundary, even if other
                               4995                 :                :  * limits are higher. Once activity resumes on the node and the retention is
                               4996                 :                :  * active, the interval is reset to lesser of 100ms and max_retention_duration,
                               4997                 :                :  * allowing timely advancement of non-removable transaction ID.
                               4998                 :                :  *
                               4999                 :                :  * XXX The use of wal_receiver_status_interval is a bit arbitrary so we can
                               5000                 :                :  * consider the other interval or a separate GUC if the need arises.
                               5001                 :                :  */
                               5002                 :                : static void
                               5003                 :             97 : adjust_xid_advance_interval(RetainDeadTuplesData *rdt_data, bool new_xid_found)
                               5004                 :                : {
  370                          5005   [ +  +  +  + ]:             97 :     if (rdt_data->xid_advance_interval && !new_xid_found)
  424                          5006                 :             39 :     {
                               5007                 :             39 :         int         max_interval = wal_receiver_status_interval
                               5008                 :             78 :             ? wal_receiver_status_interval * 1000
                               5009         [ +  - ]:             39 :             : MAX_XID_ADVANCE_INTERVAL;
                               5010                 :                : 
                               5011                 :                :         /*
                               5012                 :                :          * No new transaction ID has been assigned since the last check, so
                               5013                 :                :          * double the interval, but not beyond the maximum allowable value.
                               5014                 :                :          */
                               5015                 :             39 :         rdt_data->xid_advance_interval = Min(rdt_data->xid_advance_interval * 2,
                               5016                 :                :                                              max_interval);
                               5017                 :                :     }
  370                          5018         [ +  + ]:             58 :     else if (rdt_data->xid_advance_interval &&
                               5019         [ +  + ]:             44 :              !MySubscription->retentionactive)
                               5020                 :                :     {
                               5021                 :                :         /*
                               5022                 :                :          * Retention has been stopped, so double the interval-capped at a
                               5023                 :                :          * maximum of 3 minutes. The wal_receiver_status_interval is
                               5024                 :                :          * intentionally not used as an upper bound, since the likelihood of
                               5025                 :                :          * retention resuming is lower than that of general activity resuming.
                               5026                 :                :          */
                               5027                 :              1 :         rdt_data->xid_advance_interval = Min(rdt_data->xid_advance_interval * 2,
                               5028                 :                :                                              MAX_XID_ADVANCE_INTERVAL);
                               5029                 :                :     }
                               5030                 :                :     else
                               5031                 :                :     {
                               5032                 :                :         /*
                               5033                 :                :          * A new transaction ID was found or the interval is not yet
                               5034                 :                :          * initialized, so set the interval to the minimum value.
                               5035                 :                :          */
  424                          5036                 :             57 :         rdt_data->xid_advance_interval = MIN_XID_ADVANCE_INTERVAL;
                               5037                 :                :     }
                               5038                 :                : 
                               5039                 :                :     /*
                               5040                 :                :      * Ensure the wait time remains within the maximum retention time limit
                               5041                 :                :      * when retention is active.  Skip this cap when maxretention is zero,
                               5042                 :                :      * which means unlimited retention (no timeout).
                               5043                 :                :      */
  145                          5044   [ +  +  -  + ]:             97 :     if (MySubscription->retentionactive && MySubscription->maxretention > 0)
  370 akapila@postgresql.o     5045                 :UBC           0 :         rdt_data->xid_advance_interval = Min(rdt_data->xid_advance_interval,
                               5046                 :                :                                              MySubscription->maxretention);
  424 akapila@postgresql.o     5047                 :CBC          97 : }
                               5048                 :                : 
                               5049                 :                : /*
                               5050                 :                :  * Exit routine for apply workers due to subscription parameter changes.
                               5051                 :                :  */
                               5052                 :                : static void
 1350                          5053                 :             49 : apply_worker_exit(void)
                               5054                 :                : {
                               5055         [ -  + ]:             49 :     if (am_parallel_apply_worker())
                               5056                 :                :     {
                               5057                 :                :         /*
                               5058                 :                :          * Don't stop the parallel apply worker as the leader will detect the
                               5059                 :                :          * subscription parameter change and restart logical replication later
                               5060                 :                :          * anyway. This also prevents the leader from reporting errors when
                               5061                 :                :          * trying to communicate with a stopped parallel apply worker, which
                               5062                 :                :          * would accidentally disable subscriptions if disable_on_error was
                               5063                 :                :          * set.
                               5064                 :                :          */
 1350 akapila@postgresql.o     5065                 :UBC           0 :         return;
                               5066                 :                :     }
                               5067                 :                : 
                               5068                 :                :     /*
                               5069                 :                :      * Reset the last-start time for this apply worker so that the launcher
                               5070                 :                :      * will restart it without waiting for wal_retrieve_retry_interval if the
                               5071                 :                :      * subscription is still active, and so that we won't leak that hash table
                               5072                 :                :      * entry if it isn't.
                               5073                 :                :      */
 1143 akapila@postgresql.o     5074         [ +  - ]:CBC          49 :     if (am_leader_apply_worker())
 1337 tgl@sss.pgh.pa.us        5075                 :             49 :         ApplyLauncherForgetWorkerStartTime(MyLogicalRepWorker->subid);
                               5076                 :                : 
 1350 akapila@postgresql.o     5077                 :             49 :     proc_exit(0);
                               5078                 :                : }
                               5079                 :                : 
                               5080                 :                : /*
                               5081                 :                :  * Reread subscription info if needed.
                               5082                 :                :  *
                               5083                 :                :  * For significant changes, we react by exiting the current process; a new
                               5084                 :                :  * one will be launched afterwards if needed.
                               5085                 :                :  */
                               5086                 :                : void
 3396 peter_e@gmx.net          5087                 :           5922 : maybe_reread_subscription(void)
                               5088                 :                : {
                               5089                 :                :     Subscription *newsub;
                               5090                 :                :     char       *old_conninfo;
                               5091                 :                :     char       *new_conninfo;
 3413 bruce@momjian.us         5092                 :           5922 :     bool        started_tx = false;
                               5093                 :                : 
                               5094                 :                :     /* When cache state is valid there is nothing to do here. */
 3396 peter_e@gmx.net          5095         [ +  + ]:           5922 :     if (MySubscriptionValid)
                               5096                 :           5821 :         return;
                               5097                 :                : 
                               5098                 :                :     /* This function might be called inside or outside of transaction. */
 3468                          5099         [ +  + ]:            101 :     if (!IsTransactionState())
                               5100                 :                :     {
                               5101                 :             97 :         StartTransactionCommand();
                               5102                 :             97 :         started_tx = true;
                               5103                 :                :     }
                               5104                 :                : 
   46 jdavis@postgresql.or     5105                 :            101 :     newsub = GetSubscription(MyLogicalRepWorker->subid, true);
                               5106                 :                : 
  180                          5107         [ +  - ]:            101 :     if (newsub)
                               5108                 :                :     {
                               5109                 :            101 :         MemoryContextSetParent(newsub->cxt, ApplyContext);
                               5110                 :                :     }
                               5111                 :                :     else
                               5112                 :                :     {
                               5113                 :                :         /*
                               5114                 :                :          * Exit if the subscription was removed. This normally should not
                               5115                 :                :          * happen as the worker gets killed during DROP SUBSCRIPTION.
                               5116                 :                :          */
 3531 peter_e@gmx.net          5117         [ #  # ]:UBC           0 :         ereport(LOG,
                               5118                 :                :                 (errmsg("logical replication worker for subscription \"%s\" will stop because the subscription was removed",
                               5119                 :                :                         MySubscription->name)));
                               5120                 :                : 
                               5121                 :                :         /* Ensure we remove no-longer-useful entry for worker's start time */
 1143 akapila@postgresql.o     5122         [ #  # ]:              0 :         if (am_leader_apply_worker())
 1337 tgl@sss.pgh.pa.us        5123                 :              0 :             ApplyLauncherForgetWorkerStartTime(MyLogicalRepWorker->subid);
                               5124                 :                : 
 3531 peter_e@gmx.net          5125                 :              0 :         proc_exit(0);
                               5126                 :                :     }
                               5127                 :                : 
                               5128                 :                :     /* Exit if the subscription was disabled. */
 3421 peter_e@gmx.net          5129         [ +  + ]:CBC         101 :     if (!newsub->enabled)
                               5130                 :                :     {
                               5131         [ +  - ]:             14 :         ereport(LOG,
                               5132                 :                :                 (errmsg("logical replication worker for subscription \"%s\" will stop because the subscription was disabled",
                               5133                 :                :                         MySubscription->name)));
                               5134                 :                : 
 1350 akapila@postgresql.o     5135                 :             14 :         apply_worker_exit();
                               5136                 :                :     }
                               5137                 :                : 
                               5138                 :                :     /*
                               5139                 :                :      * May raise error, so build conninfo after checking that the subscription
                               5140                 :                :      * is enabled. Allocated in transaction context; must be copied to
                               5141                 :                :      * ApplyContext when we set MySubscriptionConninfo.
                               5142                 :                :      */
   46 jdavis@postgresql.or     5143                 :             87 :     new_conninfo = SubscriptionConninfo(newsub);
                               5144                 :                : 
                               5145                 :                :     /* !slotname should never happen when enabled is true. */
 3421 peter_e@gmx.net          5146         [ -  + ]:             87 :     Assert(newsub->slotname);
                               5147                 :                : 
                               5148                 :                :     /* two-phase cannot be altered while the worker is running */
 1894 akapila@postgresql.o     5149         [ -  + ]:             87 :     Assert(newsub->twophasestate == MySubscription->twophasestate);
                               5150                 :                : 
                               5151                 :                :     /*
                               5152                 :                :      * Exit if any parameter that affects the remote connection was changed.
                               5153                 :                :      * The launcher will start a new worker but note that the parallel apply
                               5154                 :                :      * worker won't restart if the streaming option's value is changed from
                               5155                 :                :      * 'parallel' to any other value or the server decides not to stream the
                               5156                 :                :      * in-progress transaction.
                               5157                 :                :      */
   46 jdavis@postgresql.or     5158         [ +  + ]:             87 :     if (strcmp(new_conninfo, MySubscriptionConninfo) != 0 ||
 2255 tgl@sss.pgh.pa.us        5159         [ +  + ]:             82 :         strcmp(newsub->name, MySubscription->name) != 0 ||
                               5160         [ +  - ]:             81 :         strcmp(newsub->slotname, MySubscription->slotname) != 0 ||
                               5161         [ +  + ]:             81 :         newsub->binary != MySubscription->binary ||
 2208 akapila@postgresql.o     5162         [ +  + ]:             75 :         newsub->stream != MySubscription->stream ||
 1249                          5163         [ +  - ]:             70 :         newsub->passwordrequired != MySubscription->passwordrequired ||
 1522                          5164         [ +  + ]:             70 :         strcmp(newsub->origin, MySubscription->origin) != 0 ||
 1717 jdavis@postgresql.or     5165         [ +  + ]:             68 :         newsub->owner != MySubscription->owner ||
 2255 tgl@sss.pgh.pa.us        5166         [ +  + ]:             67 :         !equal(newsub->publications, MySubscription->publications))
                               5167                 :                :     {
 1350 akapila@postgresql.o     5168         [ -  + ]:             30 :         if (am_parallel_apply_worker())
 1350 akapila@postgresql.o     5169         [ #  # ]:UBC           0 :             ereport(LOG,
                               5170                 :                :                     (errmsg("logical replication parallel apply worker for subscription \"%s\" will stop because of a parameter change",
                               5171                 :                :                             MySubscription->name)));
                               5172                 :                :         else
 1350 akapila@postgresql.o     5173         [ +  - ]:CBC          30 :             ereport(LOG,
                               5174                 :                :                     (errmsg("logical replication worker for subscription \"%s\" will restart because of a parameter change",
                               5175                 :                :                             MySubscription->name)));
                               5176                 :                : 
                               5177                 :             30 :         apply_worker_exit();
                               5178                 :                :     }
                               5179                 :                : 
                               5180                 :                :     /*
                               5181                 :                :      * Exit if the subscription owner's superuser privileges have been
                               5182                 :                :      * revoked.
                               5183                 :                :      */
 1069                          5184   [ +  +  +  + ]:             57 :     if (!newsub->ownersuperuser && MySubscription->ownersuperuser)
                               5185                 :                :     {
                               5186         [ -  + ]:              4 :         if (am_parallel_apply_worker())
 1069 akapila@postgresql.o     5187         [ #  # ]:UBC           0 :             ereport(LOG,
                               5188                 :                :                     errmsg("logical replication parallel apply worker for subscription \"%s\" will stop because the subscription owner's superuser privileges have been revoked",
                               5189                 :                :                            MySubscription->name));
                               5190                 :                :         else
 1069 akapila@postgresql.o     5191         [ +  - ]:CBC           4 :             ereport(LOG,
                               5192                 :                :                     errmsg("logical replication worker for subscription \"%s\" will restart because the subscription owner's superuser privileges have been revoked",
                               5193                 :                :                            MySubscription->name));
                               5194                 :                : 
                               5195                 :              4 :         apply_worker_exit();
                               5196                 :                :     }
                               5197                 :                : 
                               5198                 :                :     /* Check for other changes that should never happen too. */
 3457 peter_e@gmx.net          5199         [ -  + ]:             53 :     if (newsub->dbid != MySubscription->dbid)
                               5200                 :                :     {
 3531 peter_e@gmx.net          5201         [ #  # ]:UBC           0 :         elog(ERROR, "subscription %u changed unexpectedly",
                               5202                 :                :              MyLogicalRepWorker->subid);
                               5203                 :                :     }
                               5204                 :                : 
                               5205                 :                :     /* Clean old subscription info and switch to new one. */
  180 jdavis@postgresql.or     5206                 :CBC          53 :     MemoryContextDelete(MySubscription->cxt);
 3531 peter_e@gmx.net          5207                 :             53 :     MySubscription = newsub;
                               5208                 :                : 
                               5209                 :                :     /* copy to ApplyContext and update MySubscriptionConninfo */
   46 jdavis@postgresql.or     5210                 :             53 :     old_conninfo = MySubscriptionConninfo;
                               5211                 :             53 :     MySubscriptionConninfo = MemoryContextStrdup(ApplyContext, new_conninfo);
                               5212                 :             53 :     pfree(old_conninfo);
                               5213                 :                : 
                               5214                 :                :     /* Change synchronous commit according to the user's wishes */
 3446 peter_e@gmx.net          5215                 :             53 :     SetConfigOption("synchronous_commit", MySubscription->synccommit,
                               5216                 :                :                     PGC_BACKEND, PGC_S_OVERRIDE);
                               5217                 :                : 
                               5218                 :                :     /* Change wal_receiver_timeout according to the user's wishes */
  212 fujii@postgresql.org     5219                 :             53 :     set_wal_receiver_timeout();
                               5220                 :                : 
 3468 peter_e@gmx.net          5221         [ +  + ]:             53 :     if (started_tx)
                               5222                 :             52 :         CommitTransactionCommand();
                               5223                 :                : 
 3531                          5224                 :             53 :     MySubscriptionValid = true;
                               5225                 :                : }
                               5226                 :                : 
                               5227                 :                : /*
                               5228                 :                :  * Change wal_receiver_timeout to MySubscription->walrcvtimeout.
                               5229                 :                :  */
                               5230                 :                : static void
  212 fujii@postgresql.org     5231                 :            607 : set_wal_receiver_timeout(void)
                               5232                 :                : {
                               5233                 :                :     bool        parsed;
                               5234                 :                :     int         val;
                               5235                 :            607 :     int         prev_timeout = wal_receiver_timeout;
                               5236                 :                : 
                               5237                 :                :     /*
                               5238                 :                :      * Set the wal_receiver_timeout GUC to MySubscription->walrcvtimeout,
                               5239                 :                :      * which comes from the subscription's wal_receiver_timeout option. If the
                               5240                 :                :      * value is -1, reset the GUC to its default, meaning it will inherit from
                               5241                 :                :      * the server config, command line, or role/database settings.
                               5242                 :                :      */
                               5243                 :            607 :     parsed = parse_int(MySubscription->walrcvtimeout, &val, 0, NULL);
                               5244   [ +  -  +  - ]:            607 :     if (parsed && val == -1)
                               5245                 :            607 :         SetConfigOption("wal_receiver_timeout", NULL,
                               5246                 :                :                         PGC_BACKEND, PGC_S_SESSION);
                               5247                 :                :     else
  212 fujii@postgresql.org     5248                 :UBC           0 :         SetConfigOption("wal_receiver_timeout", MySubscription->walrcvtimeout,
                               5249                 :                :                         PGC_BACKEND, PGC_S_SESSION);
                               5250                 :                : 
                               5251                 :                :     /*
                               5252                 :                :      * Log the wal_receiver_timeout setting (in milliseconds) as a debug
                               5253                 :                :      * message when it changes, to verify it was set correctly.
                               5254                 :                :      */
  212 fujii@postgresql.org     5255         [ -  + ]:CBC         607 :     if (prev_timeout != wal_receiver_timeout)
  212 fujii@postgresql.org     5256         [ #  # ]:UBC           0 :         elog(DEBUG1, "logical replication worker for subscription \"%s\" wal_receiver_timeout: %d ms",
                               5257                 :                :              MySubscription->name, wal_receiver_timeout);
  212 fujii@postgresql.org     5258                 :CBC         607 : }
                               5259                 :                : 
                               5260                 :                : /*
                               5261                 :                :  * Callback from subscription syscache invalidation. Also needed for server or
                               5262                 :                :  * user mapping invalidation, which can change the connection information for
                               5263                 :                :  * subscriptions that connect using a server object.
                               5264                 :                :  */
                               5265                 :                : static void
  214 michael@paquier.xyz      5266                 :            104 : subscription_change_cb(Datum arg, SysCacheIdentifier cacheid, uint32 hashvalue)
                               5267                 :                : {
 3531 peter_e@gmx.net          5268                 :            104 :     MySubscriptionValid = false;
                               5269                 :            104 : }
                               5270                 :                : 
                               5271                 :                : /*
                               5272                 :                :  * subxact_info_write
                               5273                 :                :  *    Store information about subxacts for a toplevel transaction.
                               5274                 :                :  *
                               5275                 :                :  * For each subxact we store offset of its first change in the main file.
                               5276                 :                :  * The file is always over-written as a whole.
                               5277                 :                :  *
                               5278                 :                :  * XXX We should only store subxacts that were not aborted yet.
                               5279                 :                :  */
                               5280                 :                : static void
 2208 akapila@postgresql.o     5281                 :            371 : subxact_info_write(Oid subid, TransactionId xid)
                               5282                 :                : {
                               5283                 :                :     char        path[MAXPGPATH];
                               5284                 :                :     Size        len;
                               5285                 :                :     BufFile    *fd;
                               5286                 :                : 
                               5287         [ -  + ]:            371 :     Assert(TransactionIdIsValid(xid));
                               5288                 :                : 
                               5289                 :                :     /* construct the subxact filename */
 1844                          5290                 :            371 :     subxact_filename(path, subid, xid);
                               5291                 :                : 
                               5292                 :                :     /* Delete the subxacts file, if exists. */
 2208                          5293         [ +  + ]:            371 :     if (subxact_data.nsubxacts == 0)
                               5294                 :                :     {
 1844                          5295                 :            289 :         cleanup_subxact_info();
                               5296                 :            289 :         BufFileDeleteFileSet(MyLogicalRepWorker->stream_fileset, path, true);
                               5297                 :                : 
 2208                          5298                 :            289 :         return;
                               5299                 :                :     }
                               5300                 :                : 
                               5301                 :                :     /*
                               5302                 :                :      * Create the subxact file if it not already created, otherwise open the
                               5303                 :                :      * existing file.
                               5304                 :                :      */
 1844                          5305                 :             82 :     fd = BufFileOpenFileSet(MyLogicalRepWorker->stream_fileset, path, O_RDWR,
                               5306                 :                :                             true);
                               5307         [ +  + ]:             82 :     if (fd == NULL)
                               5308                 :              8 :         fd = BufFileCreateFileSet(MyLogicalRepWorker->stream_fileset, path);
                               5309                 :                : 
 2208                          5310                 :             82 :     len = sizeof(SubXactInfo) * subxact_data.nsubxacts;
                               5311                 :                : 
                               5312                 :                :     /* Write the subxact count and subxact info */
                               5313                 :             82 :     BufFileWrite(fd, &subxact_data.nsubxacts, sizeof(subxact_data.nsubxacts));
                               5314                 :             82 :     BufFileWrite(fd, subxact_data.subxacts, len);
                               5315                 :                : 
                               5316                 :             82 :     BufFileClose(fd);
                               5317                 :                : 
                               5318                 :                :     /* free the memory allocated for subxact info */
                               5319                 :             82 :     cleanup_subxact_info();
                               5320                 :                : }
                               5321                 :                : 
                               5322                 :                : /*
                               5323                 :                :  * subxact_info_read
                               5324                 :                :  *    Restore information about subxacts of a streamed transaction.
                               5325                 :                :  *
                               5326                 :                :  * Read information about subxacts into the structure subxact_data that can be
                               5327                 :                :  * used later.
                               5328                 :                :  */
                               5329                 :                : static void
                               5330                 :            343 : subxact_info_read(Oid subid, TransactionId xid)
                               5331                 :                : {
                               5332                 :                :     char        path[MAXPGPATH];
                               5333                 :                :     Size        len;
                               5334                 :                :     BufFile    *fd;
                               5335                 :                :     MemoryContext oldctx;
                               5336                 :                : 
                               5337         [ -  + ]:            343 :     Assert(!subxact_data.subxacts);
                               5338         [ -  + ]:            343 :     Assert(subxact_data.nsubxacts == 0);
                               5339         [ -  + ]:            343 :     Assert(subxact_data.nsubxacts_max == 0);
                               5340                 :                : 
                               5341                 :                :     /*
                               5342                 :                :      * If the subxact file doesn't exist that means we don't have any subxact
                               5343                 :                :      * info.
                               5344                 :                :      */
                               5345                 :            343 :     subxact_filename(path, subid, xid);
 1844                          5346                 :            343 :     fd = BufFileOpenFileSet(MyLogicalRepWorker->stream_fileset, path, O_RDONLY,
                               5347                 :                :                             true);
                               5348         [ +  + ]:            343 :     if (fd == NULL)
                               5349                 :            264 :         return;
                               5350                 :                : 
                               5351                 :                :     /* read number of subxact items */
 1343 peter@eisentraut.org     5352                 :             79 :     BufFileReadExact(fd, &subxact_data.nsubxacts, sizeof(subxact_data.nsubxacts));
                               5353                 :                : 
 2208 akapila@postgresql.o     5354                 :             79 :     len = sizeof(SubXactInfo) * subxact_data.nsubxacts;
                               5355                 :                : 
                               5356                 :                :     /* we keep the maximum as a power of 2 */
  375 michael@paquier.xyz      5357                 :             79 :     subxact_data.nsubxacts_max = 1 << pg_ceil_log2_32(subxact_data.nsubxacts);
                               5358                 :                : 
                               5359                 :                :     /*
                               5360                 :                :      * Allocate subxact information in the logical streaming context. We need
                               5361                 :                :      * this information during the complete stream so that we can add the sub
                               5362                 :                :      * transaction info to this. On stream stop we will flush this information
                               5363                 :                :      * to the subxact file and reset the logical streaming context.
                               5364                 :                :      */
 2208 akapila@postgresql.o     5365                 :             79 :     oldctx = MemoryContextSwitchTo(LogicalStreamingContext);
  198 msawada@postgresql.o     5366                 :             79 :     subxact_data.subxacts = palloc_array(SubXactInfo,
                               5367                 :                :                                          subxact_data.nsubxacts_max);
 2208 akapila@postgresql.o     5368                 :             79 :     MemoryContextSwitchTo(oldctx);
                               5369                 :                : 
 1343 peter@eisentraut.org     5370         [ +  - ]:             79 :     if (len > 0)
                               5371                 :             79 :         BufFileReadExact(fd, subxact_data.subxacts, len);
                               5372                 :                : 
 2208 akapila@postgresql.o     5373                 :             79 :     BufFileClose(fd);
                               5374                 :                : }
                               5375                 :                : 
                               5376                 :                : /*
                               5377                 :                :  * subxact_info_add
                               5378                 :                :  *    Add information about a subxact (offset in the main file).
                               5379                 :                :  */
                               5380                 :                : static void
                               5381                 :         102514 : subxact_info_add(TransactionId xid)
                               5382                 :                : {
                               5383                 :         102514 :     SubXactInfo *subxacts = subxact_data.subxacts;
                               5384                 :                :     int64       i;
                               5385                 :                : 
                               5386                 :                :     /* We must have a valid top level stream xid and a stream fd. */
                               5387         [ -  + ]:         102514 :     Assert(TransactionIdIsValid(stream_xid));
                               5388         [ -  + ]:         102514 :     Assert(stream_fd != NULL);
                               5389                 :                : 
                               5390                 :                :     /*
                               5391                 :                :      * If the XID matches the toplevel transaction, we don't want to add it.
                               5392                 :                :      */
                               5393         [ +  + ]:         102514 :     if (stream_xid == xid)
                               5394                 :          92390 :         return;
                               5395                 :                : 
                               5396                 :                :     /*
                               5397                 :                :      * In most cases we're checking the same subxact as we've already seen in
                               5398                 :                :      * the last call, so make sure to ignore it (this change comes later).
                               5399                 :                :      */
                               5400         [ +  + ]:          10124 :     if (subxact_data.subxact_last == xid)
                               5401                 :          10048 :         return;
                               5402                 :                : 
                               5403                 :                :     /* OK, remember we're processing this XID. */
                               5404                 :             76 :     subxact_data.subxact_last = xid;
                               5405                 :                : 
                               5406                 :                :     /*
                               5407                 :                :      * Check if the transaction is already present in the array of subxact. We
                               5408                 :                :      * intentionally scan the array from the tail, because we're likely adding
                               5409                 :                :      * a change for the most recent subtransactions.
                               5410                 :                :      *
                               5411                 :                :      * XXX Can we rely on the subxact XIDs arriving in sorted order? That
                               5412                 :                :      * would allow us to use binary search here.
                               5413                 :                :      */
                               5414         [ +  + ]:             95 :     for (i = subxact_data.nsubxacts; i > 0; i--)
                               5415                 :                :     {
                               5416                 :                :         /* found, so we're done */
                               5417         [ +  + ]:             76 :         if (subxacts[i - 1].xid == xid)
                               5418                 :             57 :             return;
                               5419                 :                :     }
                               5420                 :                : 
                               5421                 :                :     /* This is a new subxact, so we need to add it to the array. */
                               5422         [ +  + ]:             19 :     if (subxact_data.nsubxacts == 0)
                               5423                 :                :     {
                               5424                 :                :         MemoryContext oldctx;
                               5425                 :                : 
                               5426                 :              8 :         subxact_data.nsubxacts_max = 128;
                               5427                 :                : 
                               5428                 :                :         /*
                               5429                 :                :          * Allocate this memory for subxacts in per-stream context, see
                               5430                 :                :          * subxact_info_read.
                               5431                 :                :          */
                               5432                 :              8 :         oldctx = MemoryContextSwitchTo(LogicalStreamingContext);
  198 msawada@postgresql.o     5433                 :              8 :         subxacts = palloc_array(SubXactInfo, subxact_data.nsubxacts_max);
 2208 akapila@postgresql.o     5434                 :              8 :         MemoryContextSwitchTo(oldctx);
                               5435                 :                :     }
                               5436         [ +  + ]:             11 :     else if (subxact_data.nsubxacts == subxact_data.nsubxacts_max)
                               5437                 :                :     {
                               5438                 :             10 :         subxact_data.nsubxacts_max *= 2;
  198 msawada@postgresql.o     5439                 :             10 :         subxacts = repalloc_array(subxacts, SubXactInfo,
                               5440                 :                :                                   subxact_data.nsubxacts_max);
                               5441                 :                :     }
                               5442                 :                : 
 2208 akapila@postgresql.o     5443                 :             19 :     subxacts[subxact_data.nsubxacts].xid = xid;
                               5444                 :                : 
                               5445                 :                :     /*
                               5446                 :                :      * Get the current offset of the stream file and store it as offset of
                               5447                 :                :      * this subxact.
                               5448                 :                :      */
                               5449                 :             19 :     BufFileTell(stream_fd,
                               5450                 :             19 :                 &subxacts[subxact_data.nsubxacts].fileno,
                               5451                 :             19 :                 &subxacts[subxact_data.nsubxacts].offset);
                               5452                 :                : 
                               5453                 :             19 :     subxact_data.nsubxacts++;
                               5454                 :             19 :     subxact_data.subxacts = subxacts;
                               5455                 :                : }
                               5456                 :                : 
                               5457                 :                : /* format filename for file containing the info about subxacts */
                               5458                 :                : static inline void
                               5459                 :            745 : subxact_filename(char *path, Oid subid, TransactionId xid)
                               5460                 :                : {
                               5461                 :            745 :     snprintf(path, MAXPGPATH, "%u-%u.subxacts", subid, xid);
                               5462                 :            745 : }
                               5463                 :                : 
                               5464                 :                : /* format filename for file containing serialized changes */
                               5465                 :                : static inline void
                               5466                 :            437 : changes_filename(char *path, Oid subid, TransactionId xid)
                               5467                 :                : {
                               5468                 :            437 :     snprintf(path, MAXPGPATH, "%u-%u.changes", subid, xid);
                               5469                 :            437 : }
                               5470                 :                : 
                               5471                 :                : /*
                               5472                 :                :  * stream_cleanup_files
                               5473                 :                :  *    Cleanup files for a subscription / toplevel transaction.
                               5474                 :                :  *
                               5475                 :                :  * Remove files with serialized changes and subxact info for a particular
                               5476                 :                :  * toplevel transaction. Each subscription has a separate set of files
                               5477                 :                :  * for any toplevel transaction.
                               5478                 :                :  */
                               5479                 :                : void
                               5480                 :             31 : stream_cleanup_files(Oid subid, TransactionId xid)
                               5481                 :                : {
                               5482                 :                :     char        path[MAXPGPATH];
                               5483                 :                : 
                               5484                 :                :     /* Delete the changes file. */
                               5485                 :             31 :     changes_filename(path, subid, xid);
 1844                          5486                 :             31 :     BufFileDeleteFileSet(MyLogicalRepWorker->stream_fileset, path, false);
                               5487                 :                : 
                               5488                 :                :     /* Delete the subxact file, if it exists. */
                               5489                 :             31 :     subxact_filename(path, subid, xid);
                               5490                 :             31 :     BufFileDeleteFileSet(MyLogicalRepWorker->stream_fileset, path, true);
 2208                          5491                 :             31 : }
                               5492                 :                : 
                               5493                 :                : /*
                               5494                 :                :  * stream_open_file
                               5495                 :                :  *    Open a file that we'll use to serialize changes for a toplevel
                               5496                 :                :  * transaction.
                               5497                 :                :  *
                               5498                 :                :  * Open a file for streamed changes from a toplevel transaction identified
                               5499                 :                :  * by stream_xid (global variable). If it's the first chunk of streamed
                               5500                 :                :  * changes for this transaction, create the buffile, otherwise open the
                               5501                 :                :  * previously created file.
                               5502                 :                :  */
                               5503                 :                : static void
                               5504                 :            362 : stream_open_file(Oid subid, TransactionId xid, bool first_segment)
                               5505                 :                : {
                               5506                 :                :     char        path[MAXPGPATH];
                               5507                 :                :     MemoryContext oldcxt;
                               5508                 :                : 
                               5509         [ -  + ]:            362 :     Assert(OidIsValid(subid));
                               5510         [ -  + ]:            362 :     Assert(TransactionIdIsValid(xid));
                               5511         [ -  + ]:            362 :     Assert(stream_fd == NULL);
                               5512                 :                : 
                               5513                 :                : 
                               5514                 :            362 :     changes_filename(path, subid, xid);
                               5515         [ -  + ]:            362 :     elog(DEBUG1, "opening file \"%s\" for streamed changes", path);
                               5516                 :                : 
                               5517                 :                :     /*
                               5518                 :                :      * Create/open the buffiles under the logical streaming context so that we
                               5519                 :                :      * have those files until stream stop.
                               5520                 :                :      */
                               5521                 :            362 :     oldcxt = MemoryContextSwitchTo(LogicalStreamingContext);
                               5522                 :                : 
                               5523                 :                :     /*
                               5524                 :                :      * If this is the first streamed segment, create the changes file.
                               5525                 :                :      * Otherwise, just open the file for writing, in append mode.
                               5526                 :                :      */
                               5527         [ +  + ]:            362 :     if (first_segment)
 1844                          5528                 :             32 :         stream_fd = BufFileCreateFileSet(MyLogicalRepWorker->stream_fileset,
                               5529                 :                :                                          path);
                               5530                 :                :     else
                               5531                 :                :     {
                               5532                 :                :         /*
                               5533                 :                :          * Open the file and seek to the end of the file because we always
                               5534                 :                :          * append the changes file.
                               5535                 :                :          */
                               5536                 :            330 :         stream_fd = BufFileOpenFileSet(MyLogicalRepWorker->stream_fileset,
                               5537                 :                :                                        path, O_RDWR, false);
 2208                          5538                 :            330 :         BufFileSeek(stream_fd, 0, 0, SEEK_END);
                               5539                 :                :     }
                               5540                 :                : 
                               5541                 :            362 :     MemoryContextSwitchTo(oldcxt);
                               5542                 :            362 : }
                               5543                 :                : 
                               5544                 :                : /*
                               5545                 :                :  * stream_close_file
                               5546                 :                :  *    Close the currently open file with streamed changes.
                               5547                 :                :  */
                               5548                 :                : static void
                               5549                 :            392 : stream_close_file(void)
                               5550                 :                : {
                               5551         [ -  + ]:            392 :     Assert(stream_fd != NULL);
                               5552                 :                : 
                               5553                 :            392 :     BufFileClose(stream_fd);
                               5554                 :                : 
                               5555                 :            392 :     stream_fd = NULL;
                               5556                 :            392 : }
                               5557                 :                : 
                               5558                 :                : /*
                               5559                 :                :  * stream_write_change
                               5560                 :                :  *    Serialize a change to a file for the current toplevel transaction.
                               5561                 :                :  *
                               5562                 :                :  * The change is serialized in a simple format, with length (not including
                               5563                 :                :  * the length), action code (identifying the message type) and message
                               5564                 :                :  * contents (without the subxact TransactionId value).
                               5565                 :                :  */
                               5566                 :                : static void
                               5567                 :         107555 : stream_write_change(char action, StringInfo s)
                               5568                 :                : {
                               5569                 :                :     int         len;
                               5570                 :                : 
                               5571         [ -  + ]:         107555 :     Assert(stream_fd != NULL);
                               5572                 :                : 
                               5573                 :                :     /* total on-disk size, including the action type character */
                               5574                 :         107555 :     len = (s->len - s->cursor) + sizeof(char);
                               5575                 :                : 
                               5576                 :                :     /* first write the size */
                               5577                 :         107555 :     BufFileWrite(stream_fd, &len, sizeof(len));
                               5578                 :                : 
                               5579                 :                :     /* then the action */
                               5580                 :         107555 :     BufFileWrite(stream_fd, &action, sizeof(action));
                               5581                 :                : 
                               5582                 :                :     /* and finally the remaining part of the buffer (after the XID) */
                               5583                 :         107555 :     len = (s->len - s->cursor);
                               5584                 :                : 
                               5585                 :         107555 :     BufFileWrite(stream_fd, &s->data[s->cursor], len);
                               5586                 :         107555 : }
                               5587                 :                : 
                               5588                 :                : /*
                               5589                 :                :  * stream_open_and_write_change
                               5590                 :                :  *    Serialize a message to a file for the given transaction.
                               5591                 :                :  *
                               5592                 :                :  * This function is similar to stream_write_change except that it will open the
                               5593                 :                :  * target file if not already before writing the message and close the file at
                               5594                 :                :  * the end.
                               5595                 :                :  */
                               5596                 :                : static void
 1350                          5597                 :              5 : stream_open_and_write_change(TransactionId xid, char action, StringInfo s)
                               5598                 :                : {
                               5599         [ -  + ]:              5 :     Assert(!in_streamed_transaction);
                               5600                 :                : 
                               5601         [ +  - ]:              5 :     if (!stream_fd)
                               5602                 :              5 :         stream_start_internal(xid, false);
                               5603                 :                : 
                               5604                 :              5 :     stream_write_change(action, s);
                               5605                 :              5 :     stream_stop_internal(xid);
                               5606                 :              5 : }
                               5607                 :                : 
                               5608                 :                : /*
                               5609                 :                :  * Sets streaming options including replication slot name and origin start
                               5610                 :                :  * position. Workers need these options for logical replication.
                               5611                 :                :  */
                               5612                 :                : void
 1144                          5613                 :            467 : set_stream_options(WalRcvStreamOptions *options,
                               5614                 :                :                    char *slotname,
                               5615                 :                :                    XLogRecPtr *origin_startpos)
                               5616                 :                : {
                               5617                 :                :     int         server_version;
                               5618                 :                : 
                               5619                 :            467 :     options->logical = true;
                               5620                 :            467 :     options->startpoint = *origin_startpos;
                               5621                 :            467 :     options->slotname = slotname;
                               5622                 :                : 
                               5623                 :            467 :     server_version = walrcv_server_version(LogRepWorkerWalRcvConn);
                               5624                 :            467 :     options->proto.logical.proto_version =
                               5625   [ -  +  -  -  :            467 :         server_version >= 160000 ? LOGICALREP_PROTO_STREAM_PARALLEL_VERSION_NUM :
                                              -  - ]
                               5626                 :                :         server_version >= 150000 ? LOGICALREP_PROTO_TWOPHASE_VERSION_NUM :
                               5627                 :                :         server_version >= 140000 ? LOGICALREP_PROTO_STREAM_VERSION_NUM :
                               5628                 :                :         LOGICALREP_PROTO_VERSION_NUM;
                               5629                 :                : 
                               5630                 :            467 :     options->proto.logical.publication_names = MySubscription->publications;
                               5631                 :            467 :     options->proto.logical.binary = MySubscription->binary;
                               5632                 :                : 
                               5633                 :                :     /*
                               5634                 :                :      * Assign the appropriate option value for streaming option according to
                               5635                 :                :      * the 'streaming' mode and the publisher's ability to support that mode.
                               5636                 :                :      */
                               5637         [ +  - ]:            467 :     if (server_version >= 160000 &&
                               5638         [ +  + ]:            467 :         MySubscription->stream == LOGICALREP_STREAM_PARALLEL)
                               5639                 :                :     {
                               5640                 :            433 :         options->proto.logical.streaming_str = "parallel";
                               5641                 :            433 :         MyLogicalRepWorker->parallel_apply = true;
                               5642                 :                :     }
                               5643         [ +  - ]:             34 :     else if (server_version >= 140000 &&
                               5644         [ +  + ]:             34 :              MySubscription->stream != LOGICALREP_STREAM_OFF)
                               5645                 :                :     {
                               5646                 :             26 :         options->proto.logical.streaming_str = "on";
                               5647                 :             26 :         MyLogicalRepWorker->parallel_apply = false;
                               5648                 :                :     }
                               5649                 :                :     else
                               5650                 :                :     {
                               5651                 :              8 :         options->proto.logical.streaming_str = NULL;
                               5652                 :              8 :         MyLogicalRepWorker->parallel_apply = false;
                               5653                 :                :     }
                               5654                 :                : 
                               5655                 :            467 :     options->proto.logical.twophase = false;
                               5656                 :            467 :     options->proto.logical.origin = pstrdup(MySubscription->origin);
                               5657                 :            467 : }
                               5658                 :                : 
                               5659                 :                : /*
                               5660                 :                :  * Cleanup the memory for subxacts and reset the related variables.
                               5661                 :                :  */
                               5662                 :                : static inline void
  291 nathan@postgresql.or     5663                 :            375 : cleanup_subxact_info(void)
                               5664                 :                : {
 2208 akapila@postgresql.o     5665         [ +  + ]:            375 :     if (subxact_data.subxacts)
                               5666                 :             87 :         pfree(subxact_data.subxacts);
                               5667                 :                : 
                               5668                 :            375 :     subxact_data.subxacts = NULL;
                               5669                 :            375 :     subxact_data.subxact_last = InvalidTransactionId;
                               5670                 :            375 :     subxact_data.nsubxacts = 0;
                               5671                 :            375 :     subxact_data.nsubxacts_max = 0;
                               5672                 :            375 : }
                               5673                 :                : 
                               5674                 :                : /*
                               5675                 :                :  * Common function to run the apply loop with error handling. Disable the
                               5676                 :                :  * subscription, if necessary.
                               5677                 :                :  *
                               5678                 :                :  * Note that we don't handle FATAL errors which are probably because
                               5679                 :                :  * of system resource error and are not repeatable.
                               5680                 :                :  */
                               5681                 :                : void
 1144                          5682                 :            466 : start_apply(XLogRecPtr origin_startpos)
                               5683                 :                : {
 1651                          5684         [ +  + ]:            466 :     PG_TRY();
                               5685                 :                :     {
 1144                          5686                 :            466 :         LogicalRepApplyLoop(origin_startpos);
                               5687                 :                :     }
 1651                          5688                 :            104 :     PG_CATCH();
                               5689                 :                :     {
                               5690                 :                :         /*
                               5691                 :                :          * Reset the origin state to prevent the advancement of origin
                               5692                 :                :          * progress if we fail to apply. Otherwise, this will result in
                               5693                 :                :          * transaction loss as that transaction won't be sent again by the
                               5694                 :                :          * server.
                               5695                 :                :          */
  235 msawada@postgresql.o     5696                 :            104 :         replorigin_xact_clear(true);
                               5697                 :                : 
 1651 akapila@postgresql.o     5698         [ +  + ]:            104 :         if (MySubscription->disableonerr)
                               5699                 :              3 :             DisableSubscriptionAndExit();
                               5700                 :                :         else
                               5701                 :                :         {
                               5702                 :                :             /*
                               5703                 :                :              * Report the worker failed while applying changes. Abort the
                               5704                 :                :              * current transaction so that the stats message is sent in an
                               5705                 :                :              * idle state.
                               5706                 :                :              */
                               5707                 :            101 :             AbortOutOfAnyTransaction();
  212                          5708                 :            101 :             pgstat_report_subscription_error(MySubscription->oid);
                               5709                 :                : 
 1651                          5710                 :            101 :             PG_RE_THROW();
                               5711                 :                :         }
                               5712                 :                :     }
 1651 akapila@postgresql.o     5713         [ #  # ]:UBC           0 :     PG_END_TRY();
                               5714                 :              0 : }
                               5715                 :                : 
                               5716                 :                : /*
                               5717                 :                :  * Runs the leader apply worker.
                               5718                 :                :  *
                               5719                 :                :  * It sets up replication origin, streaming options and then starts streaming.
                               5720                 :                :  */
                               5721                 :                : static void
  291 nathan@postgresql.or     5722                 :CBC         310 : run_apply_worker(void)
                               5723                 :                : {
                               5724                 :                :     char        originname[NAMEDATALEN];
 1144 akapila@postgresql.o     5725                 :            310 :     XLogRecPtr  origin_startpos = InvalidXLogRecPtr;
                               5726                 :            310 :     char       *slotname = NULL;
                               5727                 :                :     WalRcvStreamOptions options;
                               5728                 :                :     ReplOriginId originid;
                               5729                 :                :     TimeLineID  startpointTLI;
                               5730                 :                :     char       *err;
                               5731                 :                :     bool        must_use_password;
                               5732                 :                : 
                               5733                 :            310 :     slotname = MySubscription->slotname;
                               5734                 :                : 
                               5735                 :                :     /*
                               5736                 :                :      * This shouldn't happen if the subscription is enabled, but guard against
                               5737                 :                :      * DDL bugs or manual catalog changes.  (libpqwalreceiver will crash if
                               5738                 :                :      * slot is NULL.)
                               5739                 :                :      */
                               5740         [ -  + ]:            310 :     if (!slotname)
 1144 akapila@postgresql.o     5741         [ #  # ]:UBC           0 :         ereport(ERROR,
                               5742                 :                :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
                               5743                 :                :                  errmsg("subscription has no replication slot set")));
                               5744                 :                : 
                               5745                 :                :     /* Setup replication origin tracking. */
 1144 akapila@postgresql.o     5746                 :CBC         310 :     ReplicationOriginNameForLogicalRep(MySubscription->oid, InvalidOid,
                               5747                 :                :                                        originname, sizeof(originname));
                               5748                 :            310 :     StartTransactionCommand();
                               5749                 :            310 :     originid = replorigin_by_name(originname, true);
                               5750         [ -  + ]:            310 :     if (!OidIsValid(originid))
 1144 akapila@postgresql.o     5751                 :UBC           0 :         originid = replorigin_create(originname);
 1144 akapila@postgresql.o     5752                 :CBC         310 :     replorigin_session_setup(originid, 0);
  235 msawada@postgresql.o     5753                 :            310 :     replorigin_xact_state.origin = originid;
 1144 akapila@postgresql.o     5754                 :            310 :     origin_startpos = replorigin_session_get_progress(false);
 1069                          5755                 :            310 :     CommitTransactionCommand();
                               5756                 :                : 
                               5757                 :                :     /* Is the use of a password mandatory? */
 1144                          5758         [ +  + ]:            596 :     must_use_password = MySubscription->passwordrequired &&
 1069                          5759         [ +  + ]:            286 :         !MySubscription->ownersuperuser;
                               5760                 :                : 
   46 jdavis@postgresql.or     5761                 :            310 :     LogRepWorkerWalRcvConn = walrcv_connect(MySubscriptionConninfo, true,
                               5762                 :                :                                             true, must_use_password,
                               5763                 :                :                                             MySubscription->name, &err);
                               5764                 :                : 
 1144 akapila@postgresql.o     5765         [ +  + ]:            303 :     if (LogRepWorkerWalRcvConn == NULL)
                               5766         [ +  - ]:             39 :         ereport(ERROR,
                               5767                 :                :                 (errcode(ERRCODE_CONNECTION_FAILURE),
                               5768                 :                :                  errmsg("apply worker for subscription \"%s\" could not connect to the publisher: %s",
                               5769                 :                :                         MySubscription->name, err)));
                               5770                 :                : 
                               5771                 :                :     /*
                               5772                 :                :      * We don't really use the output identify_system for anything but it does
                               5773                 :                :      * some initializations on the upstream so let's still call it.
                               5774                 :                :      */
   53 alvherre@kurilemu.de     5775                 :            264 :     (void) walrcv_identify_system(LogRepWorkerWalRcvConn, &startpointTLI, NULL);
                               5776                 :                : 
                               5777                 :                :     /*
                               5778                 :                :      * If retain_dead_tuples is enabled, verify that the publisher is
                               5779                 :                :      * suitable, that is, it runs a version that supports the feature and is
                               5780                 :                :      * not in recovery. This is the authoritative check. Although the same
                               5781                 :                :      * validation is performed opportunistically at DDL time, the publisher's
                               5782                 :                :      * version or recovery status may have changed since then, for example
                               5783                 :                :      * after a failover.
                               5784                 :                :      */
   47 akapila@postgresql.o     5785         [ +  + ]:            264 :     if (MySubscription->retaindeadtuples)
                               5786                 :                :     {
                               5787                 :             14 :         StartTransactionCommand();
                               5788                 :             14 :         CheckPubDeadTupleRetention(LogRepWorkerWalRcvConn);
                               5789                 :             14 :         CommitTransactionCommand();
                               5790                 :                :     }
                               5791                 :                : 
 1144                          5792                 :            264 :     set_apply_error_context_origin(originname);
                               5793                 :                : 
                               5794                 :            264 :     set_stream_options(&options, slotname, &origin_startpos);
                               5795                 :                : 
                               5796                 :                :     /*
                               5797                 :                :      * Even when the two_phase mode is requested by the user, it remains as
                               5798                 :                :      * the tri-state PENDING until all tablesyncs have reached READY state.
                               5799                 :                :      * Only then, can it become ENABLED.
                               5800                 :                :      *
                               5801                 :                :      * Note: If the subscription has no tables then leave the state as
                               5802                 :                :      * PENDING, which allows ALTER SUBSCRIPTION ... REFRESH PUBLICATION to
                               5803                 :                :      * work.
                               5804                 :                :      */
                               5805   [ +  +  +  + ]:            280 :     if (MySubscription->twophasestate == LOGICALREP_TWOPHASE_STATE_PENDING &&
                               5806                 :             16 :         AllTablesyncsReady())
                               5807                 :                :     {
                               5808                 :                :         /* Start streaming with two_phase enabled */
                               5809                 :              9 :         options.proto.logical.twophase = true;
                               5810                 :              9 :         walrcv_startstreaming(LogRepWorkerWalRcvConn, &options);
                               5811                 :                : 
                               5812                 :              9 :         StartTransactionCommand();
                               5813                 :                : 
                               5814                 :                :         /*
                               5815                 :                :          * Updating pg_subscription might involve TOAST table access, so
                               5816                 :                :          * ensure we have a valid snapshot.
                               5817                 :                :          */
  478 nathan@postgresql.or     5818                 :              9 :         PushActiveSnapshot(GetTransactionSnapshot());
                               5819                 :                : 
 1144 akapila@postgresql.o     5820                 :              9 :         UpdateTwoPhaseState(MySubscription->oid, LOGICALREP_TWOPHASE_STATE_ENABLED);
                               5821                 :              9 :         MySubscription->twophasestate = LOGICALREP_TWOPHASE_STATE_ENABLED;
  478 nathan@postgresql.or     5822                 :              9 :         PopActiveSnapshot();
 1144 akapila@postgresql.o     5823                 :              9 :         CommitTransactionCommand();
                               5824                 :                :     }
                               5825                 :                :     else
                               5826                 :                :     {
                               5827                 :            255 :         walrcv_startstreaming(LogRepWorkerWalRcvConn, &options);
                               5828                 :                :     }
                               5829                 :                : 
                               5830   [ +  +  +  +  :            263 :     ereport(DEBUG1,
                                        +  -  +  - ]
                               5831                 :                :             (errmsg_internal("logical replication apply worker for subscription \"%s\" two_phase is %s",
                               5832                 :                :                              MySubscription->name,
                               5833                 :                :                              MySubscription->twophasestate == LOGICALREP_TWOPHASE_STATE_DISABLED ? "DISABLED" :
                               5834                 :                :                              MySubscription->twophasestate == LOGICALREP_TWOPHASE_STATE_PENDING ? "PENDING" :
                               5835                 :                :                              MySubscription->twophasestate == LOGICALREP_TWOPHASE_STATE_ENABLED ? "ENABLED" :
                               5836                 :                :                              "?")));
                               5837                 :                : 
                               5838                 :                :     /* Run the main loop. */
                               5839                 :            263 :     start_apply(origin_startpos);
 1651 akapila@postgresql.o     5840                 :UBC           0 : }
                               5841                 :                : 
                               5842                 :                : /*
                               5843                 :                :  * Common initialization for leader apply worker, parallel apply worker,
                               5844                 :                :  * tablesync worker and sequencesync worker.
                               5845                 :                :  *
                               5846                 :                :  * Initialize the database connection, in-memory subscription and necessary
                               5847                 :                :  * config options.
                               5848                 :                :  */
                               5849                 :                : void
 1144 akapila@postgresql.o     5850                 :CBC         635 : InitializeLogRepWorker(void)
                               5851                 :                : {
                               5852                 :                :     /* Run as replica session replication role. */
 3531 peter_e@gmx.net          5853                 :            635 :     SetConfigOption("session_replication_role", "replica",
                               5854                 :                :                     PGC_SUSET, PGC_S_OVERRIDE);
                               5855                 :                : 
                               5856                 :                :     /* Connect to our database. */
                               5857                 :            635 :     BackgroundWorkerInitializeConnectionByOid(MyLogicalRepWorker->dbid,
 3090 magnus@hagander.net      5858                 :            635 :                                               MyLogicalRepWorker->userid,
                               5859                 :                :                                               0);
                               5860                 :                : 
                               5861                 :                :     /*
                               5862                 :                :      * Set always-secure search path, so malicious users can't redirect user
                               5863                 :                :      * code (e.g. pg_index.indexprs).
                               5864                 :                :      */
 2232 noah@leadboat.com        5865                 :            627 :     SetConfigOption("search_path", "", PGC_SUSET, PGC_S_OVERRIDE);
                               5866                 :                : 
                               5867                 :                :     /*
                               5868                 :                :      * Ignore default_transaction_read_only for logical replication workers,
                               5869                 :                :      * as they need to be able to modify subscriber-side state regardless of
                               5870                 :                :      * that setting.
                               5871                 :                :      */
   61 akapila@postgresql.o     5872                 :GNC         627 :     SetConfigOption("default_transaction_read_only", "off", PGC_SUSET,
                               5873                 :                :                     PGC_S_OVERRIDE);
                               5874                 :                : 
 3421 peter_e@gmx.net          5875                 :CBC         627 :     ApplyContext = AllocSetContextCreate(TopMemoryContext,
                               5876                 :                :                                          "ApplyContext",
                               5877                 :                :                                          ALLOCSET_DEFAULT_SIZES);
                               5878                 :                : 
 3531                          5879                 :            627 :     StartTransactionCommand();
                               5880                 :                : 
                               5881                 :                :     /*
                               5882                 :                :      * Lock the subscription to prevent it from being concurrently dropped,
                               5883                 :                :      * then re-verify its existence. After the initialization, the worker will
                               5884                 :                :      * be terminated gracefully if the subscription is dropped.
                               5885                 :                :      */
  397 akapila@postgresql.o     5886                 :            627 :     LockSharedObject(SubscriptionRelationId, MyLogicalRepWorker->subid, 0,
                               5887                 :                :                      AccessShareLock);
                               5888                 :                : 
   46 jdavis@postgresql.or     5889                 :            627 :     MySubscription = GetSubscription(MyLogicalRepWorker->subid, true);
                               5890                 :                : 
  180                          5891         [ +  + ]:            627 :     if (MySubscription)
                               5892                 :                :     {
                               5893                 :            554 :         MemoryContextSetParent(MySubscription->cxt, ApplyContext);
                               5894                 :                :     }
                               5895                 :                :     else
                               5896                 :                :     {
 3089 peter_e@gmx.net          5897         [ +  - ]:             73 :         ereport(LOG,
                               5898                 :                :                 (errmsg("logical replication worker for subscription %u will not start because the subscription was removed during startup",
                               5899                 :                :                         MyLogicalRepWorker->subid)));
                               5900                 :                : 
                               5901                 :                :         /* Ensure we remove no-longer-useful entry for worker's start time */
 1143 akapila@postgresql.o     5902         [ +  - ]:             73 :         if (am_leader_apply_worker())
 1337 tgl@sss.pgh.pa.us        5903                 :             73 :             ApplyLauncherForgetWorkerStartTime(MyLogicalRepWorker->subid);
                               5904                 :                : 
 3089 peter_e@gmx.net          5905                 :             73 :         proc_exit(0);
                               5906                 :                :     }
                               5907                 :                : 
 3531                          5908         [ -  + ]:            554 :     if (!MySubscription->enabled)
                               5909                 :                :     {
 3531 peter_e@gmx.net          5910         [ #  # ]:UBC           0 :         ereport(LOG,
                               5911                 :                :                 (errmsg("logical replication worker for subscription \"%s\" will not start because the subscription was disabled during startup",
                               5912                 :                :                         MySubscription->name)));
                               5913                 :                : 
 1350 akapila@postgresql.o     5914                 :              0 :         apply_worker_exit();
                               5915                 :                :     }
                               5916                 :                : 
                               5917                 :                :     /*
                               5918                 :                :      * May raise error for server-based subscriptions, so build conninfo after
                               5919                 :                :      * checking that the subscription is enabled. Build in transaction context
                               5920                 :                :      * and copy to ApplyContext.
                               5921                 :                :      */
   46 jdavis@postgresql.or     5922                 :CBC         554 :     MySubscriptionConninfo =
                               5923                 :            554 :         MemoryContextStrdup(ApplyContext,
                               5924                 :            554 :                             SubscriptionConninfo(MySubscription));
                               5925                 :                : 
                               5926                 :            554 :     MySubscriptionValid = true;
                               5927                 :                : 
                               5928                 :                :     /*
                               5929                 :                :      * Restart the worker if retain_dead_tuples was enabled during startup.
                               5930                 :                :      *
                               5931                 :                :      * At this point, the replication slot used for conflict detection might
                               5932                 :                :      * not exist yet, or could be dropped soon if the launcher perceives
                               5933                 :                :      * retain_dead_tuples as disabled. To avoid unnecessary tracking of
                               5934                 :                :      * oldest_nonremovable_xid when the slot is absent or at risk of being
                               5935                 :                :      * dropped, a restart is initiated.
                               5936                 :                :      *
                               5937                 :                :      * The oldest_nonremovable_xid should be initialized only when the
                               5938                 :                :      * subscription's retention is active before launching the worker. See
                               5939                 :                :      * logicalrep_worker_launch.
                               5940                 :                :      */
  424 akapila@postgresql.o     5941         [ +  + ]:            554 :     if (am_leader_apply_worker() &&
                               5942         [ +  + ]:            310 :         MySubscription->retaindeadtuples &&
  383                          5943         [ +  - ]:             16 :         MySubscription->retentionactive &&
  424                          5944         [ -  + ]:             16 :         !TransactionIdIsValid(MyLogicalRepWorker->oldest_nonremovable_xid))
                               5945                 :                :     {
  424 akapila@postgresql.o     5946         [ #  # ]:UBC           0 :         ereport(LOG,
                               5947                 :                :                 errmsg("logical replication worker for subscription \"%s\" will restart because the option %s was enabled during startup",
                               5948                 :                :                        MySubscription->name, "retain_dead_tuples"));
                               5949                 :                : 
                               5950                 :              0 :         apply_worker_exit();
                               5951                 :                :     }
                               5952                 :                : 
                               5953                 :                :     /* Setup synchronous commit according to the user's wishes */
 3089 peter_e@gmx.net          5954                 :CBC         554 :     SetConfigOption("synchronous_commit", MySubscription->synccommit,
                               5955                 :                :                     PGC_BACKEND, PGC_S_OVERRIDE);
                               5956                 :                : 
                               5957                 :                :     /* Change wal_receiver_timeout according to the user's wishes */
  212 fujii@postgresql.org     5958                 :            554 :     set_wal_receiver_timeout();
                               5959                 :                : 
                               5960                 :                :     /*
                               5961                 :                :      * Keep us informed about subscription or role changes. Note that the
                               5962                 :                :      * role's superuser privilege can be revoked.
                               5963                 :                :      */
 3531 peter_e@gmx.net          5964                 :            554 :     CacheRegisterSyscacheCallback(SUBSCRIPTIONOID,
                               5965                 :                :                                   subscription_change_cb,
                               5966                 :                :                                   (Datum) 0);
                               5967                 :                :     /* Changes to foreign servers may affect subscriptions using SERVER. */
  198 jdavis@postgresql.or     5968                 :            554 :     CacheRegisterSyscacheCallback(FOREIGNSERVEROID,
                               5969                 :                :                                   subscription_change_cb,
                               5970                 :                :                                   (Datum) 0);
                               5971                 :                :     /* Changes to user mappings may affect subscriptions using SERVER. */
                               5972                 :            554 :     CacheRegisterSyscacheCallback(USERMAPPINGOID,
                               5973                 :                :                                   subscription_change_cb,
                               5974                 :                :                                   (Datum) 0);
                               5975                 :                : 
                               5976                 :                :     /*
                               5977                 :                :      * Changes to FDW connection_function may affect subscriptions using
                               5978                 :                :      * SERVER.
                               5979                 :                :      */
                               5980                 :            554 :     CacheRegisterSyscacheCallback(FOREIGNDATAWRAPPEROID,
                               5981                 :                :                                   subscription_change_cb,
                               5982                 :                :                                   (Datum) 0);
                               5983                 :                : 
 1069 akapila@postgresql.o     5984                 :            554 :     CacheRegisterSyscacheCallback(AUTHOID,
                               5985                 :                :                                   subscription_change_cb,
                               5986                 :                :                                   (Datum) 0);
                               5987                 :                : 
 3468 peter_e@gmx.net          5988         [ +  + ]:            554 :     if (am_tablesync_worker())
 3406                          5989         [ +  - ]:            217 :         ereport(LOG,
                               5990                 :                :                 errmsg("logical replication table synchronization worker for subscription \"%s\", table \"%s\" has started",
                               5991                 :                :                        MySubscription->name,
                               5992                 :                :                        get_rel_name(MyLogicalRepWorker->relid)));
  319 akapila@postgresql.o     5993         [ +  + ]:            337 :     else if (am_sequencesync_worker())
                               5994         [ +  - ]:             15 :         ereport(LOG,
                               5995                 :                :                 errmsg("logical replication sequence synchronization worker for subscription \"%s\" has started",
                               5996                 :                :                        MySubscription->name));
                               5997                 :                :     else
 3406 peter_e@gmx.net          5998         [ +  - ]:            322 :         ereport(LOG,
                               5999                 :                :                 errmsg("logical replication apply worker for subscription \"%s\" has started",
                               6000                 :                :                        MySubscription->name));
                               6001                 :                : 
 3531                          6002                 :            554 :     CommitTransactionCommand();
                               6003                 :                : 
                               6004                 :                :     /*
                               6005                 :                :      * Register a callback to reset the origin state before aborting any
                               6006                 :                :      * pending transaction during shutdown (see ShutdownPostgres()). This will
                               6007                 :                :      * avoid origin advancement for an incomplete transaction which could
                               6008                 :                :      * otherwise lead to its loss as such a transaction won't be sent by the
                               6009                 :                :      * server again.
                               6010                 :                :      *
                               6011                 :                :      * Note that even a LOG or DEBUG statement placed after setting the origin
                               6012                 :                :      * state may process a shutdown signal before committing the current apply
                               6013                 :                :      * operation. So, it is important to register such a callback here.
                               6014                 :                :      *
                               6015                 :                :      * Register this callback here to ensure that all types of logical
                               6016                 :                :      * replication workers that set up origins and apply remote transactions
                               6017                 :                :      * are protected.
                               6018                 :                :      */
  235 msawada@postgresql.o     6019                 :            554 :     before_shmem_exit(on_exit_clear_xact_state, (Datum) 0);
 1350 akapila@postgresql.o     6020                 :            554 : }
                               6021                 :                : 
                               6022                 :                : /*
                               6023                 :                :  * Callback on exit to clear transaction-level replication origin state.
                               6024                 :                :  */
                               6025                 :                : static void
  235 msawada@postgresql.o     6026                 :            554 : on_exit_clear_xact_state(int code, Datum arg)
                               6027                 :                : {
                               6028                 :            554 :     replorigin_xact_clear(true);
  760 akapila@postgresql.o     6029                 :            554 : }
                               6030                 :                : 
                               6031                 :                : /*
                               6032                 :                :  * Common function to setup the leader apply, tablesync and sequencesync worker.
                               6033                 :                :  */
                               6034                 :                : void
 1144                          6035                 :            623 : SetupApplyOrSyncWorker(int worker_slot)
                               6036                 :                : {
                               6037                 :                :     /* Attach to slot */
 1350                          6038                 :            623 :     logicalrep_worker_attach(worker_slot);
                               6039                 :                : 
  319                          6040   [ +  +  +  +  :            623 :     Assert(am_tablesync_worker() || am_sequencesync_worker() || am_leader_apply_worker());
                                              -  + ]
                               6041                 :                : 
                               6042                 :                :     /* Setup signal handling */
 1350                          6043                 :            623 :     pqsignal(SIGHUP, SignalHandlerForConfigReload);
                               6044                 :            623 :     BackgroundWorkerUnblockSignals();
                               6045                 :                : 
                               6046                 :                :     /*
                               6047                 :                :      * We don't currently need any ResourceOwner in a walreceiver process, but
                               6048                 :                :      * if we did, we could call CreateAuxProcessResourceOwner here.
                               6049                 :                :      */
                               6050                 :                : 
                               6051                 :                :     /* Initialise stats to a sanish value */
   55                          6052         [ +  + ]:            623 :     if (am_sequencesync_worker())
                               6053                 :                :     {
                               6054                 :             15 :         MyLogicalRepWorker->last_send_time =
                               6055                 :             15 :             MyLogicalRepWorker->last_recv_time =
                               6056                 :             15 :             MyLogicalRepWorker->reply_time = 0;
                               6057                 :                :     }
                               6058                 :                :     else
                               6059                 :                :     {
                               6060                 :            608 :         MyLogicalRepWorker->last_send_time =
                               6061                 :            608 :             MyLogicalRepWorker->last_recv_time =
                               6062                 :            608 :             MyLogicalRepWorker->reply_time = GetCurrentTimestamp();
                               6063                 :                :     }
                               6064                 :                : 
                               6065                 :                :     /* Load the libpq-specific functions */
 1350                          6066                 :            623 :     load_file("libpqwalreceiver", false);
                               6067                 :                : 
 1144                          6068                 :            623 :     InitializeLogRepWorker();
                               6069                 :                : 
                               6070                 :                :     /*
                               6071                 :                :      * Setup callback for syscache so that we know when something changes in
                               6072                 :                :      * the subscription relation state.
                               6073                 :                :      */
 3468 peter_e@gmx.net          6074                 :            542 :     CacheRegisterSyscacheCallback(SUBSCRIPTIONRELMAP,
                               6075                 :                :                                   InvalidateSyncingRelStates,
                               6076                 :                :                                   (Datum) 0);
 1144 akapila@postgresql.o     6077                 :            542 : }
                               6078                 :                : 
                               6079                 :                : /* Logical Replication Apply worker entry point */
                               6080                 :                : void
                               6081                 :            391 : ApplyWorkerMain(Datum main_arg)
                               6082                 :                : {
                               6083                 :            391 :     int         worker_slot = DatumGetInt32(main_arg);
                               6084                 :                : 
                               6085                 :            391 :     InitializingApplyWorker = true;
                               6086                 :                : 
                               6087                 :            391 :     SetupApplyOrSyncWorker(worker_slot);
                               6088                 :                : 
                               6089                 :            310 :     InitializingApplyWorker = false;
                               6090                 :                : 
                               6091                 :            310 :     run_apply_worker();
                               6092                 :                : 
 1651 akapila@postgresql.o     6093                 :UBC           0 :     proc_exit(0);
                               6094                 :                : }
                               6095                 :                : 
                               6096                 :                : /*
                               6097                 :                :  * After error recovery, disable the subscription in a new transaction
                               6098                 :                :  * and exit cleanly.
                               6099                 :                :  */
                               6100                 :                : void
 1651 akapila@postgresql.o     6101                 :CBC           4 : DisableSubscriptionAndExit(void)
                               6102                 :                : {
                               6103                 :                :     /*
                               6104                 :                :      * Emit the error message, and recover from the error state to an idle
                               6105                 :                :      * state
                               6106                 :                :      */
                               6107                 :              4 :     HOLD_INTERRUPTS();
                               6108                 :                : 
                               6109                 :              4 :     EmitErrorReport();
                               6110                 :              4 :     AbortOutOfAnyTransaction();
                               6111                 :              4 :     FlushErrorState();
                               6112                 :                : 
                               6113         [ -  + ]:              4 :     RESUME_INTERRUPTS();
                               6114                 :                : 
                               6115                 :                :     /*
                               6116                 :                :      * Report the worker failed during sequence synchronization, table
                               6117                 :                :      * synchronization, or apply.
                               6118                 :                :      */
  212                          6119                 :              4 :     pgstat_report_subscription_error(MyLogicalRepWorker->subid);
                               6120                 :                : 
                               6121                 :                :     /* Disable the subscription */
 1651                          6122                 :              4 :     StartTransactionCommand();
                               6123                 :                : 
                               6124                 :                :     /*
                               6125                 :                :      * Updating pg_subscription might involve TOAST table access, so ensure we
                               6126                 :                :      * have a valid snapshot.
                               6127                 :                :      */
  478 nathan@postgresql.or     6128                 :              4 :     PushActiveSnapshot(GetTransactionSnapshot());
                               6129                 :                : 
 1651 akapila@postgresql.o     6130                 :              4 :     DisableSubscription(MySubscription->oid);
  478 nathan@postgresql.or     6131                 :              4 :     PopActiveSnapshot();
 1651 akapila@postgresql.o     6132                 :              4 :     CommitTransactionCommand();
                               6133                 :                : 
                               6134                 :                :     /* Ensure we remove no-longer-useful entry for worker's start time */
 1143                          6135         [ +  + ]:              4 :     if (am_leader_apply_worker())
 1337 tgl@sss.pgh.pa.us        6136                 :              3 :         ApplyLauncherForgetWorkerStartTime(MyLogicalRepWorker->subid);
                               6137                 :                : 
                               6138                 :                :     /* Notify the subscription has been disabled and exit */
 1651 akapila@postgresql.o     6139         [ +  - ]:              4 :     ereport(LOG,
                               6140                 :                :             errmsg("subscription \"%s\" has been disabled because of an error",
                               6141                 :                :                    MySubscription->name));
                               6142                 :                : 
                               6143                 :                :     /*
                               6144                 :                :      * Skip the track_commit_timestamp check when disabling the worker due to
                               6145                 :                :      * an error, as verifying commit timestamps is unnecessary in this
                               6146                 :                :      * context.
                               6147                 :                :      */
  383                          6148                 :              4 :     CheckSubDeadTupleRetention(false, true, WARNING,
                               6149                 :              4 :                                MySubscription->retaindeadtuples,
                               6150                 :              4 :                                MySubscription->retentionactive, false);
                               6151                 :                : 
 3531 peter_e@gmx.net          6152                 :              4 :     proc_exit(0);
                               6153                 :                : }
                               6154                 :                : 
                               6155                 :                : /*
                               6156                 :                :  * Is current process a logical replication worker?
                               6157                 :                :  */
                               6158                 :                : bool
 3397                          6159                 :           2801 : IsLogicalWorker(void)
                               6160                 :                : {
                               6161                 :           2801 :     return MyLogicalRepWorker != NULL;
                               6162                 :                : }
                               6163                 :                : 
                               6164                 :                : /*
                               6165                 :                :  * Is current process a logical replication parallel apply worker?
                               6166                 :                :  */
                               6167                 :                : bool
 1350 akapila@postgresql.o     6168                 :           2028 : IsLogicalParallelApplyWorker(void)
                               6169                 :                : {
                               6170   [ +  +  +  - ]:           2028 :     return IsLogicalWorker() && am_parallel_apply_worker();
                               6171                 :                : }
                               6172                 :                : 
                               6173                 :                : /*
                               6174                 :                :  * Start skipping changes of the transaction if the given LSN matches the
                               6175                 :                :  * LSN specified by subscription's skiplsn.
                               6176                 :                :  */
                               6177                 :                : static void
 1643                          6178                 :            564 : maybe_start_skipping_changes(XLogRecPtr finish_lsn)
                               6179                 :                : {
                               6180         [ -  + ]:            564 :     Assert(!is_skipping_changes());
                               6181         [ -  + ]:            564 :     Assert(!in_remote_transaction);
                               6182         [ -  + ]:            564 :     Assert(!in_streamed_transaction);
                               6183                 :                : 
                               6184                 :                :     /*
                               6185                 :                :      * Quick return if it's not requested to skip this transaction. This
                               6186                 :                :      * function is called for every remote transaction and we assume that
                               6187                 :                :      * skipping the transaction is not used often.
                               6188                 :                :      */
  318 alvherre@kurilemu.de     6189   [ +  +  -  +  :            564 :     if (likely(!XLogRecPtrIsValid(MySubscription->skiplsn) ||
                                              +  + ]
                               6190                 :                :                MySubscription->skiplsn != finish_lsn))
 1643 akapila@postgresql.o     6191                 :            561 :         return;
                               6192                 :                : 
                               6193                 :                :     /* Start skipping all changes of this transaction */
                               6194                 :              3 :     skip_xact_finish_lsn = finish_lsn;
                               6195                 :                : 
                               6196         [ +  - ]:              3 :     ereport(LOG,
                               6197                 :                :             errmsg("logical replication starts skipping transaction at LSN %X/%08X",
                               6198                 :                :                    LSN_FORMAT_ARGS(skip_xact_finish_lsn)));
                               6199                 :                : }
                               6200                 :                : 
                               6201                 :                : /*
                               6202                 :                :  * Stop skipping changes by resetting skip_xact_finish_lsn if enabled.
                               6203                 :                :  */
                               6204                 :                : static void
                               6205                 :             30 : stop_skipping_changes(void)
                               6206                 :                : {
                               6207         [ +  + ]:             30 :     if (!is_skipping_changes())
                               6208                 :             27 :         return;
                               6209                 :                : 
                               6210         [ +  - ]:              3 :     ereport(LOG,
                               6211                 :                :             errmsg("logical replication completed skipping transaction at LSN %X/%08X",
                               6212                 :                :                    LSN_FORMAT_ARGS(skip_xact_finish_lsn)));
                               6213                 :                : 
                               6214                 :                :     /* Stop skipping changes */
                               6215                 :              3 :     skip_xact_finish_lsn = InvalidXLogRecPtr;
                               6216                 :                : }
                               6217                 :                : 
                               6218                 :                : /*
                               6219                 :                :  * Clear subskiplsn of pg_subscription catalog.
                               6220                 :                :  *
                               6221                 :                :  * finish_lsn is the transaction's finish LSN that is used to check if the
                               6222                 :                :  * subskiplsn matches it. If not matched, we raise a warning when clearing the
                               6223                 :                :  * subskiplsn in order to inform users for cases e.g., where the user mistakenly
                               6224                 :                :  * specified the wrong subskiplsn.
                               6225                 :                :  */
                               6226                 :                : static void
                               6227                 :            547 : clear_subscription_skip_lsn(XLogRecPtr finish_lsn)
                               6228                 :                : {
                               6229                 :                :     Relation    rel;
                               6230                 :                :     Form_pg_subscription subform;
                               6231                 :                :     HeapTuple   tup;
                               6232                 :            547 :     XLogRecPtr  myskiplsn = MySubscription->skiplsn;
                               6233                 :            547 :     bool        started_tx = false;
                               6234                 :                : 
  318 alvherre@kurilemu.de     6235   [ +  +  -  + ]:            547 :     if (likely(!XLogRecPtrIsValid(myskiplsn)) || am_parallel_apply_worker())
 1643 akapila@postgresql.o     6236                 :            544 :         return;
                               6237                 :                : 
                               6238         [ +  + ]:              3 :     if (!IsTransactionState())
                               6239                 :                :     {
                               6240                 :              1 :         StartTransactionCommand();
                               6241                 :              1 :         started_tx = true;
                               6242                 :                :     }
                               6243                 :                : 
                               6244                 :                :     /*
                               6245                 :                :      * Updating pg_subscription might involve TOAST table access, so ensure we
                               6246                 :                :      * have a valid snapshot.
                               6247                 :                :      */
  478 nathan@postgresql.or     6248                 :              3 :     PushActiveSnapshot(GetTransactionSnapshot());
                               6249                 :                : 
                               6250                 :                :     /*
                               6251                 :                :      * Protect subskiplsn of pg_subscription from being concurrently updated
                               6252                 :                :      * while clearing it.
                               6253                 :                :      */
 1643 akapila@postgresql.o     6254                 :              3 :     LockSharedObject(SubscriptionRelationId, MySubscription->oid, 0,
                               6255                 :                :                      AccessShareLock);
                               6256                 :                : 
                               6257                 :              3 :     rel = table_open(SubscriptionRelationId, RowExclusiveLock);
                               6258                 :                : 
                               6259                 :                :     /* Fetch the existing tuple. */
                               6260                 :              3 :     tup = SearchSysCacheCopy1(SUBSCRIPTIONOID,
                               6261                 :                :                               ObjectIdGetDatum(MySubscription->oid));
                               6262                 :                : 
                               6263         [ -  + ]:              3 :     if (!HeapTupleIsValid(tup))
 1643 akapila@postgresql.o     6264         [ #  # ]:UBC           0 :         elog(ERROR, "subscription \"%s\" does not exist", MySubscription->name);
                               6265                 :                : 
 1643 akapila@postgresql.o     6266                 :CBC           3 :     subform = (Form_pg_subscription) GETSTRUCT(tup);
                               6267                 :                : 
                               6268                 :                :     /*
                               6269                 :                :      * Clear the subskiplsn. If the user has already changed subskiplsn before
                               6270                 :                :      * clearing it we don't update the catalog and the replication origin
                               6271                 :                :      * state won't get advanced. So in the worst case, if the server crashes
                               6272                 :                :      * before sending an acknowledgment of the flush position the transaction
                               6273                 :                :      * will be sent again and the user needs to set subskiplsn again. We can
                               6274                 :                :      * reduce the possibility by logging a replication origin WAL record to
                               6275                 :                :      * advance the origin LSN instead but there is no way to advance the
                               6276                 :                :      * origin timestamp and it doesn't seem to be worth doing anything about
                               6277                 :                :      * it since it's a very rare case.
                               6278                 :                :      */
                               6279         [ +  - ]:              3 :     if (subform->subskiplsn == myskiplsn)
                               6280                 :                :     {
                               6281                 :                :         bool        nulls[Natts_pg_subscription];
                               6282                 :                :         bool        replaces[Natts_pg_subscription];
                               6283                 :                :         Datum       values[Natts_pg_subscription];
                               6284                 :                : 
                               6285                 :              3 :         memset(values, 0, sizeof(values));
                               6286                 :              3 :         memset(nulls, false, sizeof(nulls));
                               6287                 :              3 :         memset(replaces, false, sizeof(replaces));
                               6288                 :                : 
                               6289                 :                :         /* reset subskiplsn */
                               6290                 :              3 :         values[Anum_pg_subscription_subskiplsn - 1] = LSNGetDatum(InvalidXLogRecPtr);
                               6291                 :              3 :         replaces[Anum_pg_subscription_subskiplsn - 1] = true;
                               6292                 :                : 
                               6293                 :              3 :         tup = heap_modify_tuple(tup, RelationGetDescr(rel), values, nulls,
                               6294                 :                :                                 replaces);
                               6295                 :              3 :         CatalogTupleUpdate(rel, &tup->t_self, tup);
                               6296                 :                : 
                               6297         [ -  + ]:              3 :         if (myskiplsn != finish_lsn)
 1643 akapila@postgresql.o     6298         [ #  # ]:UBC           0 :             ereport(WARNING,
                               6299                 :                :                     errmsg("skip-LSN of subscription \"%s\" cleared", MySubscription->name),
                               6300                 :                :                     errdetail("Remote transaction's finish WAL location (LSN) %X/%08X did not match skip-LSN %X/%08X.",
                               6301                 :                :                               LSN_FORMAT_ARGS(finish_lsn),
                               6302                 :                :                               LSN_FORMAT_ARGS(myskiplsn)));
                               6303                 :                :     }
                               6304                 :                : 
 1643 akapila@postgresql.o     6305                 :CBC           3 :     heap_freetuple(tup);
                               6306                 :              3 :     table_close(rel, NoLock);
                               6307                 :                : 
  478 nathan@postgresql.or     6308                 :              3 :     PopActiveSnapshot();
                               6309                 :                : 
 1643 akapila@postgresql.o     6310         [ +  + ]:              3 :     if (started_tx)
                               6311                 :              1 :         CommitTransactionCommand();
                               6312                 :                : }
                               6313                 :                : 
                               6314                 :                : /* Error callback to give more context info about the change being applied */
                               6315                 :                : void
 1850                          6316                 :           2992 : apply_error_callback(void *arg)
                               6317                 :                : {
   25 akapila@postgresql.o     6318                 :GNC        2992 :     ApplyRemoteCtx *ctx = &remote_ctx;
                               6319                 :                : 
                               6320         [ +  + ]:           2992 :     if (ctx->command == 0)
 1850 akapila@postgresql.o     6321                 :CBC        2570 :         return;
                               6322                 :                : 
   25 akapila@postgresql.o     6323         [ -  + ]:GNC         422 :     Assert(ctx->origin_name);
                               6324                 :                : 
                               6325         [ +  + ]:            422 :     if (ctx->rel == NULL)
                               6326                 :                :     {
                               6327         [ -  + ]:            335 :         if (!TransactionIdIsValid(ctx->remote_xid))
 1457 peter@eisentraut.org     6328                 :UBC           0 :             errcontext("processing remote data for replication origin \"%s\" during message type \"%s\"",
                               6329                 :                :                        ctx->origin_name,
                               6330                 :                :                        logicalrep_message_type(ctx->command));
   25 akapila@postgresql.o     6331         [ +  + ]:GNC         335 :         else if (!XLogRecPtrIsValid(ctx->finish_lsn))
 1457 peter@eisentraut.org     6332                 :CBC         260 :             errcontext("processing remote data for replication origin \"%s\" during message type \"%s\" in transaction %u",
                               6333                 :                :                        ctx->origin_name,
                               6334                 :                :                        logicalrep_message_type(ctx->command),
                               6335                 :                :                        ctx->remote_xid);
                               6336                 :                :         else
  440 alvherre@kurilemu.de     6337                 :            150 :             errcontext("processing remote data for replication origin \"%s\" during message type \"%s\" in transaction %u, finished at %X/%08X",
                               6338                 :                :                        ctx->origin_name,
                               6339                 :                :                        logicalrep_message_type(ctx->command),
                               6340                 :                :                        ctx->remote_xid,
   25 akapila@postgresql.o     6341                 :GNC          75 :                        LSN_FORMAT_ARGS(ctx->finish_lsn));
                               6342                 :                :     }
                               6343                 :                :     else
                               6344                 :                :     {
                               6345         [ +  - ]:             87 :         if (ctx->remote_attnum < 0)
                               6346                 :                :         {
                               6347         [ +  + ]:             87 :             if (!XLogRecPtrIsValid(ctx->finish_lsn))
 1350 akapila@postgresql.o     6348                 :CBC           4 :                 errcontext("processing remote data for replication origin \"%s\" during message type \"%s\" for replication target relation \"%s.%s\" in transaction %u",
                               6349                 :                :                            ctx->origin_name,
                               6350                 :                :                            logicalrep_message_type(ctx->command),
   25 akapila@postgresql.o     6351                 :GNC           2 :                            ctx->rel->remoterel.nspname,
                               6352                 :              2 :                            ctx->rel->remoterel.relname,
                               6353                 :                :                            ctx->remote_xid);
                               6354                 :                :             else
  440 alvherre@kurilemu.de     6355                 :CBC         170 :                 errcontext("processing remote data for replication origin \"%s\" during message type \"%s\" for replication target relation \"%s.%s\" in transaction %u, finished at %X/%08X",
                               6356                 :                :                            ctx->origin_name,
                               6357                 :                :                            logicalrep_message_type(ctx->command),
   25 akapila@postgresql.o     6358                 :GNC          85 :                            ctx->rel->remoterel.nspname,
                               6359                 :             85 :                            ctx->rel->remoterel.relname,
                               6360                 :                :                            ctx->remote_xid,
                               6361                 :             85 :                            LSN_FORMAT_ARGS(ctx->finish_lsn));
                               6362                 :                :         }
                               6363                 :                :         else
                               6364                 :                :         {
   25 akapila@postgresql.o     6365         [ #  # ]:UNC           0 :             if (!XLogRecPtrIsValid(ctx->finish_lsn))
 1350 akapila@postgresql.o     6366                 :UBC           0 :                 errcontext("processing remote data for replication origin \"%s\" during message type \"%s\" for replication target relation \"%s.%s\" column \"%s\" in transaction %u",
                               6367                 :                :                            ctx->origin_name,
                               6368                 :                :                            logicalrep_message_type(ctx->command),
   25 akapila@postgresql.o     6369                 :UNC           0 :                            ctx->rel->remoterel.nspname,
                               6370                 :              0 :                            ctx->rel->remoterel.relname,
                               6371                 :              0 :                            ctx->rel->remoterel.attnames[ctx->remote_attnum],
                               6372                 :                :                            ctx->remote_xid);
                               6373                 :                :             else
  440 alvherre@kurilemu.de     6374                 :UBC           0 :                 errcontext("processing remote data for replication origin \"%s\" during message type \"%s\" for replication target relation \"%s.%s\" column \"%s\" in transaction %u, finished at %X/%08X",
                               6375                 :                :                            ctx->origin_name,
                               6376                 :                :                            logicalrep_message_type(ctx->command),
   25 akapila@postgresql.o     6377                 :UNC           0 :                            ctx->rel->remoterel.nspname,
                               6378                 :              0 :                            ctx->rel->remoterel.relname,
                               6379                 :              0 :                            ctx->rel->remoterel.attnames[ctx->remote_attnum],
                               6380                 :                :                            ctx->remote_xid,
                               6381                 :              0 :                            LSN_FORMAT_ARGS(ctx->finish_lsn));
                               6382                 :                :         }
                               6383                 :                :     }
                               6384                 :                : }
                               6385                 :                : 
                               6386                 :                : /*
                               6387                 :                :  * Set information identifying the remote transaction currently being
                               6388                 :                :  * applied, kept for the duration of that transaction.
                               6389                 :                :  *
                               6390                 :                :  * This must be called for every message type that begins or resumes applying
                               6391                 :                :  * a remote transaction's changes (BEGIN, BEGIN PREPARE, STREAM START, STREAM
                               6392                 :                :  * COMMIT, STREAM PREPARE), since interleaved transactions (possible only for
                               6393                 :                :  * streaming) would otherwise leave stale values from whichever transaction
                               6394                 :                :  * last called this.
                               6395                 :                :  *
                               6396                 :                :  * Callers normally pass the top-level transaction's xid. The exception is a
                               6397                 :                :  * STREAM ABORT, which passes the xid of the (sub)transaction being aborted so
                               6398                 :                :  * that the error context names whatever failed; that is a subxid only when a
                               6399                 :                :  * subtransaction rolls back, and the top-level xid otherwise. Nothing else
                               6400                 :                :  * observes a subxid recorded this way, because no change is applied between a
                               6401                 :                :  * STREAM ABORT and the STREAM START or STREAM COMMIT/PREPARE that follows it,
                               6402                 :                :  * and each of those calls this again with the transaction's own values.
                               6403                 :                :  */
                               6404                 :                : static inline void
   25 akapila@postgresql.o     6405                 :GNC        2952 : set_remote_transaction_info(TransactionId xid, XLogRecPtr lsn)
                               6406                 :                : {
                               6407                 :           2952 :     remote_ctx.remote_xid = xid;
                               6408                 :           2952 :     remote_ctx.finish_lsn = lsn;
 1850 akapila@postgresql.o     6409                 :CBC        2952 : }
                               6410                 :                : 
                               6411                 :                : /* Reset all information of the remote transaction context */
                               6412                 :                : static inline void
   25 akapila@postgresql.o     6413                 :GNC        1438 : reset_apply_remote_context(void)
                               6414                 :                : {
                               6415                 :           1438 :     remote_ctx.command = 0;
                               6416                 :           1438 :     remote_ctx.rel = NULL;
                               6417                 :           1438 :     remote_ctx.remote_attnum = -1;
                               6418                 :           1438 :     set_remote_transaction_info(InvalidTransactionId, InvalidXLogRecPtr);
 1850 akapila@postgresql.o     6419                 :CBC        1438 : }
                               6420                 :                : 
                               6421                 :                : /*
                               6422                 :                :  * Request wakeup of the workers for the given subscription OID
                               6423                 :                :  * at commit of the current transaction.
                               6424                 :                :  *
                               6425                 :                :  * This is used to ensure that the workers process assorted changes
                               6426                 :                :  * as soon as possible.
                               6427                 :                :  */
                               6428                 :                : void
 1353 tgl@sss.pgh.pa.us        6429                 :            395 : LogicalRepWorkersWakeupAtCommit(Oid subid)
                               6430                 :                : {
                               6431                 :                :     MemoryContext oldcxt;
                               6432                 :                : 
                               6433                 :            395 :     oldcxt = MemoryContextSwitchTo(TopTransactionContext);
                               6434                 :            395 :     on_commit_wakeup_workers_subids =
                               6435                 :            395 :         list_append_unique_oid(on_commit_wakeup_workers_subids, subid);
                               6436                 :            395 :     MemoryContextSwitchTo(oldcxt);
                               6437                 :            395 : }
                               6438                 :                : 
                               6439                 :                : /*
                               6440                 :                :  * Wake up the workers of any subscriptions that were changed in this xact.
                               6441                 :                :  */
                               6442                 :                : void
                               6443                 :         426048 : AtEOXact_LogicalRepWorkers(bool isCommit)
                               6444                 :                : {
                               6445   [ +  +  +  + ]:         426048 :     if (isCommit && on_commit_wakeup_workers_subids != NIL)
                               6446                 :                :     {
                               6447                 :                :         ListCell   *lc;
                               6448                 :                : 
                               6449                 :            381 :         LWLockAcquire(LogicalRepWorkerLock, LW_SHARED);
                               6450   [ +  -  +  +  :            762 :         foreach(lc, on_commit_wakeup_workers_subids)
                                              +  + ]
                               6451                 :                :         {
                               6452                 :            381 :             Oid         subid = lfirst_oid(lc);
                               6453                 :                :             List       *workers;
                               6454                 :                :             ListCell   *lc2;
                               6455                 :                : 
  788 akapila@postgresql.o     6456                 :            381 :             workers = logicalrep_workers_find(subid, true, false);
 1353 tgl@sss.pgh.pa.us        6457   [ +  +  +  +  :            467 :             foreach(lc2, workers)
                                              +  + ]
                               6458                 :                :             {
                               6459                 :             86 :                 LogicalRepWorker *worker = (LogicalRepWorker *) lfirst(lc2);
                               6460                 :                : 
                               6461                 :             86 :                 logicalrep_worker_wakeup_ptr(worker);
                               6462                 :                :             }
                               6463                 :                :         }
                               6464                 :            381 :         LWLockRelease(LogicalRepWorkerLock);
                               6465                 :                :     }
                               6466                 :                : 
                               6467                 :                :     /* The List storage will be reclaimed automatically in xact cleanup. */
                               6468                 :         426048 :     on_commit_wakeup_workers_subids = NIL;
                               6469                 :         426048 : }
                               6470                 :                : 
                               6471                 :                : /*
                               6472                 :                :  * Allocate the origin name in long-lived context for error context message.
                               6473                 :                :  */
                               6474                 :                : void
 1350 akapila@postgresql.o     6475                 :            479 : set_apply_error_context_origin(char *originname)
                               6476                 :                : {
   25 akapila@postgresql.o     6477                 :GNC         479 :     remote_ctx.origin_name = MemoryContextStrdup(ApplyContext, originname);
 1350 akapila@postgresql.o     6478                 :CBC         479 : }
                               6479                 :                : 
                               6480                 :                : /*
                               6481                 :                :  * Return the action to be taken for the given transaction. See
                               6482                 :                :  * TransApplyAction for information on each of the actions.
                               6483                 :                :  *
                               6484                 :                :  * *winfo is assigned to the destination parallel worker info when the leader
                               6485                 :                :  * apply worker has to pass all the transaction's changes to the parallel
                               6486                 :                :  * apply worker.
                               6487                 :                :  */
                               6488                 :                : static TransApplyAction
                               6489                 :         342000 : get_transaction_apply_action(TransactionId xid, ParallelApplyWorkerInfo **winfo)
                               6490                 :                : {
                               6491                 :         342000 :     *winfo = NULL;
                               6492                 :                : 
                               6493         [ +  + ]:         342000 :     if (am_parallel_apply_worker())
                               6494                 :                :     {
                               6495                 :          63956 :         return TRANS_PARALLEL_APPLY;
                               6496                 :                :     }
                               6497                 :                : 
                               6498                 :                :     /*
                               6499                 :                :      * If we are processing this transaction using a parallel apply worker
                               6500                 :                :      * then either we send the changes to the parallel worker or if the worker
                               6501                 :                :      * is busy then serialize the changes to the file which will later be
                               6502                 :                :      * processed by the parallel worker.
                               6503                 :                :      */
                               6504                 :         278044 :     *winfo = pa_find_worker(xid);
                               6505                 :                : 
 1342                          6506   [ +  +  +  + ]:         278044 :     if (*winfo && (*winfo)->serialize_changes)
                               6507                 :                :     {
                               6508                 :           5037 :         return TRANS_LEADER_PARTIAL_SERIALIZE;
                               6509                 :                :     }
                               6510         [ +  + ]:         273007 :     else if (*winfo)
                               6511                 :                :     {
                               6512                 :          63900 :         return TRANS_LEADER_SEND_TO_PARALLEL;
                               6513                 :                :     }
                               6514                 :                : 
                               6515                 :                :     /*
                               6516                 :                :      * If there is no parallel worker involved to process this transaction
                               6517                 :                :      * then we either directly apply the change or serialize it to a file
                               6518                 :                :      * which will later be applied when the transaction finish message is
                               6519                 :                :      * processed.
                               6520                 :                :      */
                               6521         [ +  + ]:         209107 :     else if (in_streamed_transaction)
                               6522                 :                :     {
                               6523                 :         103198 :         return TRANS_LEADER_SERIALIZE;
                               6524                 :                :     }
                               6525                 :                :     else
                               6526                 :                :     {
                               6527                 :         105909 :         return TRANS_LEADER_APPLY;
                               6528                 :                :     }
                               6529                 :                : }
        

Generated by: LCOV version 2.0-1