LCOV - differential code coverage report
Current view: top level - src/backend/replication/logical - worker.c (source / functions) Coverage Total Hit UNC LBC UBC GBC GNC CBC DUB DCB
Current: ba12a202ce1b5581dc0ed149cf3f637d7897ad5d vs 2866d8c7dbfc9d882a7d80fef93fbbe763709932 Lines: 92.7 % 1895 1757 8 6 124 2 56 1699 8 58
Current Date: 2026-08-27 14:31:44 +0300 Functions: 100.0 % 98 98 24 74 2
Baseline: lcov-20260827-baseline Branches: 67.6 % 1119 757 8 7 347 2 14 741
Baseline Date: 2026-08-27 14:31:58 +0300 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
[..1] days: 87.5 % 64 56 8 55 1
(7,30] days: 100.0 % 17 17 17
(30,360] days: 86.0 % 179 154 1 24 2 1 151
(360..) days: 93.6 % 1635 1530 5 100 1530
Function coverage date bins:
[..1] days: 100.0 % 2 2 2
(30,360] days: 100.0 % 10 10 10
(360..) days: 100.0 % 86 86 22 64
Branch coverage date bins:
[..1] days: 63.6 % 22 14 8 14
(7,30] days: 100.0 % 4 4 4
(30,360] days: 62.3 % 138 86 3 49 2 84
(360..) days: 68.4 % 955 653 4 298 653

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

Generated by: LCOV version 2.0-1