LCOV - code coverage report
Current view: top level - src/backend/replication/logical - worker.c (source / functions) Coverage Total Hit
Test: PostgreSQL 20devel Lines: 92.6 % 1839 1702
Test Date: 2026-08-26 14:16:01 Functions: 100.0 % 98 98
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
Branches: 69.2 % 989 684

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

Generated by: LCOV version 2.0-1