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 % 1840 1703
Test Date: 2026-08-27 14:15:58 Functions: 100.0 % 98 98
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
Branches: 69.1 % 989 683

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

Generated by: LCOV version 2.0-1