LCOV - code coverage report
Current view: top level - src/backend/replication/logical - reorderbuffer.c (source / functions) Hit Total Coverage
Test: PostgreSQL 19devel Lines: 1498 1609 93.1 %
Date: 2025-07-05 08:17:45 Functions: 94 94 100.0 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /*-------------------------------------------------------------------------
       2             :  *
       3             :  * reorderbuffer.c
       4             :  *    PostgreSQL logical replay/reorder buffer management
       5             :  *
       6             :  *
       7             :  * Copyright (c) 2012-2025, PostgreSQL Global Development Group
       8             :  *
       9             :  *
      10             :  * IDENTIFICATION
      11             :  *    src/backend/replication/logical/reorderbuffer.c
      12             :  *
      13             :  * NOTES
      14             :  *    This module gets handed individual pieces of transactions in the order
      15             :  *    they are written to the WAL and is responsible to reassemble them into
      16             :  *    toplevel transaction sized pieces. When a transaction is completely
      17             :  *    reassembled - signaled by reading the transaction commit record - it
      18             :  *    will then call the output plugin (cf. ReorderBufferCommit()) with the
      19             :  *    individual changes. The output plugins rely on snapshots built by
      20             :  *    snapbuild.c which hands them to us.
      21             :  *
      22             :  *    Transactions and subtransactions/savepoints in postgres are not
      23             :  *    immediately linked to each other from outside the performing
      24             :  *    backend. Only at commit/abort (or special xact_assignment records) they
      25             :  *    are linked together. Which means that we will have to splice together a
      26             :  *    toplevel transaction from its subtransactions. To do that efficiently we
      27             :  *    build a binary heap indexed by the smallest current lsn of the individual
      28             :  *    subtransactions' changestreams. As the individual streams are inherently
      29             :  *    ordered by LSN - since that is where we build them from - the transaction
      30             :  *    can easily be reassembled by always using the subtransaction with the
      31             :  *    smallest current LSN from the heap.
      32             :  *
      33             :  *    In order to cope with large transactions - which can be several times as
      34             :  *    big as the available memory - this module supports spooling the contents
      35             :  *    of large transactions to disk. When the transaction is replayed the
      36             :  *    contents of individual (sub-)transactions will be read from disk in
      37             :  *    chunks.
      38             :  *
      39             :  *    This module also has to deal with reassembling toast records from the
      40             :  *    individual chunks stored in WAL. When a new (or initial) version of a
      41             :  *    tuple is stored in WAL it will always be preceded by the toast chunks
      42             :  *    emitted for the columns stored out of line. Within a single toplevel
      43             :  *    transaction there will be no other data carrying records between a row's
      44             :  *    toast chunks and the row data itself. See ReorderBufferToast* for
      45             :  *    details.
      46             :  *
      47             :  *    ReorderBuffer uses two special memory context types - SlabContext for
      48             :  *    allocations of fixed-length structures (changes and transactions), and
      49             :  *    GenerationContext for the variable-length transaction data (allocated
      50             :  *    and freed in groups with similar lifespans).
      51             :  *
      52             :  *    To limit the amount of memory used by decoded changes, we track memory
      53             :  *    used at the reorder buffer level (i.e. total amount of memory), and for
      54             :  *    each transaction. When the total amount of used memory exceeds the
      55             :  *    limit, the transaction consuming the most memory is then serialized to
      56             :  *    disk.
      57             :  *
      58             :  *    Only decoded changes are evicted from memory (spilled to disk), not the
      59             :  *    transaction records. The number of toplevel transactions is limited,
      60             :  *    but a transaction with many subtransactions may still consume significant
      61             :  *    amounts of memory. However, the transaction records are fairly small and
      62             :  *    are not included in the memory limit.
      63             :  *
      64             :  *    The current eviction algorithm is very simple - the transaction is
      65             :  *    picked merely by size, while it might be useful to also consider age
      66             :  *    (LSN) of the changes for example. With the new Generational memory
      67             :  *    allocator, evicting the oldest changes would make it more likely the
      68             :  *    memory gets actually freed.
      69             :  *
      70             :  *    We use a max-heap with transaction size as the key to efficiently find
      71             :  *    the largest transaction. We update the max-heap whenever the memory
      72             :  *    counter is updated; however transactions with size 0 are not stored in
      73             :  *    the heap, because they have no changes to evict.
      74             :  *
      75             :  *    We still rely on max_changes_in_memory when loading serialized changes
      76             :  *    back into memory. At that point we can't use the memory limit directly
      77             :  *    as we load the subxacts independently. One option to deal with this
      78             :  *    would be to count the subxacts, and allow each to allocate 1/N of the
      79             :  *    memory limit. That however does not seem very appealing, because with
      80             :  *    many subtransactions it may easily cause thrashing (short cycles of
      81             :  *    deserializing and applying very few changes). We probably should give
      82             :  *    a bit more memory to the oldest subtransactions, because it's likely
      83             :  *    they are the source for the next sequence of changes.
      84             :  *
      85             :  * -------------------------------------------------------------------------
      86             :  */
      87             : #include "postgres.h"
      88             : 
      89             : #include <unistd.h>
      90             : #include <sys/stat.h>
      91             : 
      92             : #include "access/detoast.h"
      93             : #include "access/heapam.h"
      94             : #include "access/rewriteheap.h"
      95             : #include "access/transam.h"
      96             : #include "access/xact.h"
      97             : #include "access/xlog_internal.h"
      98             : #include "catalog/catalog.h"
      99             : #include "common/int.h"
     100             : #include "lib/binaryheap.h"
     101             : #include "miscadmin.h"
     102             : #include "pgstat.h"
     103             : #include "replication/logical.h"
     104             : #include "replication/reorderbuffer.h"
     105             : #include "replication/slot.h"
     106             : #include "replication/snapbuild.h"    /* just for SnapBuildSnapDecRefcount */
     107             : #include "storage/bufmgr.h"
     108             : #include "storage/fd.h"
     109             : #include "storage/procarray.h"
     110             : #include "storage/sinval.h"
     111             : #include "utils/builtins.h"
     112             : #include "utils/inval.h"
     113             : #include "utils/memutils.h"
     114             : #include "utils/rel.h"
     115             : #include "utils/relfilenumbermap.h"
     116             : 
     117             : /*
     118             :  * Each transaction has an 8MB limit for invalidation messages distributed from
     119             :  * other transactions. This limit is set considering scenarios with many
     120             :  * concurrent logical decoding operations. When the distributed invalidation
     121             :  * messages reach this threshold, the transaction is marked as
     122             :  * RBTXN_DISTR_INVAL_OVERFLOWED to invalidate the complete cache as we have lost
     123             :  * some inval messages and hence don't know what needs to be invalidated.
     124             :  */
     125             : #define MAX_DISTR_INVAL_MSG_PER_TXN \
     126             :     ((8 * 1024 * 1024) / sizeof(SharedInvalidationMessage))
     127             : 
     128             : /* entry for a hash table we use to map from xid to our transaction state */
     129             : typedef struct ReorderBufferTXNByIdEnt
     130             : {
     131             :     TransactionId xid;
     132             :     ReorderBufferTXN *txn;
     133             : } ReorderBufferTXNByIdEnt;
     134             : 
     135             : /* data structures for (relfilelocator, ctid) => (cmin, cmax) mapping */
     136             : typedef struct ReorderBufferTupleCidKey
     137             : {
     138             :     RelFileLocator rlocator;
     139             :     ItemPointerData tid;
     140             : } ReorderBufferTupleCidKey;
     141             : 
     142             : typedef struct ReorderBufferTupleCidEnt
     143             : {
     144             :     ReorderBufferTupleCidKey key;
     145             :     CommandId   cmin;
     146             :     CommandId   cmax;
     147             :     CommandId   combocid;       /* just for debugging */
     148             : } ReorderBufferTupleCidEnt;
     149             : 
     150             : /* Virtual file descriptor with file offset tracking */
     151             : typedef struct TXNEntryFile
     152             : {
     153             :     File        vfd;            /* -1 when the file is closed */
     154             :     off_t       curOffset;      /* offset for next write or read. Reset to 0
     155             :                                  * when vfd is opened. */
     156             : } TXNEntryFile;
     157             : 
     158             : /* k-way in-order change iteration support structures */
     159             : typedef struct ReorderBufferIterTXNEntry
     160             : {
     161             :     XLogRecPtr  lsn;
     162             :     ReorderBufferChange *change;
     163             :     ReorderBufferTXN *txn;
     164             :     TXNEntryFile file;
     165             :     XLogSegNo   segno;
     166             : } ReorderBufferIterTXNEntry;
     167             : 
     168             : typedef struct ReorderBufferIterTXNState
     169             : {
     170             :     binaryheap *heap;
     171             :     Size        nr_txns;
     172             :     dlist_head  old_change;
     173             :     ReorderBufferIterTXNEntry entries[FLEXIBLE_ARRAY_MEMBER];
     174             : } ReorderBufferIterTXNState;
     175             : 
     176             : /* toast datastructures */
     177             : typedef struct ReorderBufferToastEnt
     178             : {
     179             :     Oid         chunk_id;       /* toast_table.chunk_id */
     180             :     int32       last_chunk_seq; /* toast_table.chunk_seq of the last chunk we
     181             :                                  * have seen */
     182             :     Size        num_chunks;     /* number of chunks we've already seen */
     183             :     Size        size;           /* combined size of chunks seen */
     184             :     dlist_head  chunks;         /* linked list of chunks */
     185             :     struct varlena *reconstructed;  /* reconstructed varlena now pointed to in
     186             :                                      * main tup */
     187             : } ReorderBufferToastEnt;
     188             : 
     189             : /* Disk serialization support datastructures */
     190             : typedef struct ReorderBufferDiskChange
     191             : {
     192             :     Size        size;
     193             :     ReorderBufferChange change;
     194             :     /* data follows */
     195             : } ReorderBufferDiskChange;
     196             : 
     197             : #define IsSpecInsert(action) \
     198             : ( \
     199             :     ((action) == REORDER_BUFFER_CHANGE_INTERNAL_SPEC_INSERT) \
     200             : )
     201             : #define IsSpecConfirmOrAbort(action) \
     202             : ( \
     203             :     (((action) == REORDER_BUFFER_CHANGE_INTERNAL_SPEC_CONFIRM) || \
     204             :     ((action) == REORDER_BUFFER_CHANGE_INTERNAL_SPEC_ABORT)) \
     205             : )
     206             : #define IsInsertOrUpdate(action) \
     207             : ( \
     208             :     (((action) == REORDER_BUFFER_CHANGE_INSERT) || \
     209             :     ((action) == REORDER_BUFFER_CHANGE_UPDATE) || \
     210             :     ((action) == REORDER_BUFFER_CHANGE_INTERNAL_SPEC_INSERT)) \
     211             : )
     212             : 
     213             : /*
     214             :  * Maximum number of changes kept in memory, per transaction. After that,
     215             :  * changes are spooled to disk.
     216             :  *
     217             :  * The current value should be sufficient to decode the entire transaction
     218             :  * without hitting disk in OLTP workloads, while starting to spool to disk in
     219             :  * other workloads reasonably fast.
     220             :  *
     221             :  * At some point in the future it probably makes sense to have a more elaborate
     222             :  * resource management here, but it's not entirely clear what that would look
     223             :  * like.
     224             :  */
     225             : int         logical_decoding_work_mem;
     226             : static const Size max_changes_in_memory = 4096; /* XXX for restore only */
     227             : 
     228             : /* GUC variable */
     229             : int         debug_logical_replication_streaming = DEBUG_LOGICAL_REP_STREAMING_BUFFERED;
     230             : 
     231             : /* ---------------------------------------
     232             :  * primary reorderbuffer support routines
     233             :  * ---------------------------------------
     234             :  */
     235             : static ReorderBufferTXN *ReorderBufferAllocTXN(ReorderBuffer *rb);
     236             : static void ReorderBufferFreeTXN(ReorderBuffer *rb, ReorderBufferTXN *txn);
     237             : static ReorderBufferTXN *ReorderBufferTXNByXid(ReorderBuffer *rb,
     238             :                                                TransactionId xid, bool create, bool *is_new,
     239             :                                                XLogRecPtr lsn, bool create_as_top);
     240             : static void ReorderBufferTransferSnapToParent(ReorderBufferTXN *txn,
     241             :                                               ReorderBufferTXN *subtxn);
     242             : 
     243             : static void AssertTXNLsnOrder(ReorderBuffer *rb);
     244             : 
     245             : /* ---------------------------------------
     246             :  * support functions for lsn-order iterating over the ->changes of a
     247             :  * transaction and its subtransactions
     248             :  *
     249             :  * used for iteration over the k-way heap merge of a transaction and its
     250             :  * subtransactions
     251             :  * ---------------------------------------
     252             :  */
     253             : static void ReorderBufferIterTXNInit(ReorderBuffer *rb, ReorderBufferTXN *txn,
     254             :                                      ReorderBufferIterTXNState *volatile *iter_state);
     255             : static ReorderBufferChange *ReorderBufferIterTXNNext(ReorderBuffer *rb, ReorderBufferIterTXNState *state);
     256             : static void ReorderBufferIterTXNFinish(ReorderBuffer *rb,
     257             :                                        ReorderBufferIterTXNState *state);
     258             : static void ReorderBufferExecuteInvalidations(uint32 nmsgs, SharedInvalidationMessage *msgs);
     259             : 
     260             : /*
     261             :  * ---------------------------------------
     262             :  * Disk serialization support functions
     263             :  * ---------------------------------------
     264             :  */
     265             : static void ReorderBufferCheckMemoryLimit(ReorderBuffer *rb);
     266             : static void ReorderBufferSerializeTXN(ReorderBuffer *rb, ReorderBufferTXN *txn);
     267             : static void ReorderBufferSerializeChange(ReorderBuffer *rb, ReorderBufferTXN *txn,
     268             :                                          int fd, ReorderBufferChange *change);
     269             : static Size ReorderBufferRestoreChanges(ReorderBuffer *rb, ReorderBufferTXN *txn,
     270             :                                         TXNEntryFile *file, XLogSegNo *segno);
     271             : static void ReorderBufferRestoreChange(ReorderBuffer *rb, ReorderBufferTXN *txn,
     272             :                                        char *data);
     273             : static void ReorderBufferRestoreCleanup(ReorderBuffer *rb, ReorderBufferTXN *txn);
     274             : static void ReorderBufferTruncateTXN(ReorderBuffer *rb, ReorderBufferTXN *txn,
     275             :                                      bool txn_prepared);
     276             : static void ReorderBufferMaybeMarkTXNStreamed(ReorderBuffer *rb, ReorderBufferTXN *txn);
     277             : static bool ReorderBufferCheckAndTruncateAbortedTXN(ReorderBuffer *rb, ReorderBufferTXN *txn);
     278             : static void ReorderBufferCleanupSerializedTXNs(const char *slotname);
     279             : static void ReorderBufferSerializedPath(char *path, ReplicationSlot *slot,
     280             :                                         TransactionId xid, XLogSegNo segno);
     281             : static int  ReorderBufferTXNSizeCompare(const pairingheap_node *a, const pairingheap_node *b, void *arg);
     282             : 
     283             : static void ReorderBufferFreeSnap(ReorderBuffer *rb, Snapshot snap);
     284             : static Snapshot ReorderBufferCopySnap(ReorderBuffer *rb, Snapshot orig_snap,
     285             :                                       ReorderBufferTXN *txn, CommandId cid);
     286             : 
     287             : /*
     288             :  * ---------------------------------------
     289             :  * Streaming support functions
     290             :  * ---------------------------------------
     291             :  */
     292             : static inline bool ReorderBufferCanStream(ReorderBuffer *rb);
     293             : static inline bool ReorderBufferCanStartStreaming(ReorderBuffer *rb);
     294             : static void ReorderBufferStreamTXN(ReorderBuffer *rb, ReorderBufferTXN *txn);
     295             : static void ReorderBufferStreamCommit(ReorderBuffer *rb, ReorderBufferTXN *txn);
     296             : 
     297             : /* ---------------------------------------
     298             :  * toast reassembly support
     299             :  * ---------------------------------------
     300             :  */
     301             : static void ReorderBufferToastInitHash(ReorderBuffer *rb, ReorderBufferTXN *txn);
     302             : static void ReorderBufferToastReset(ReorderBuffer *rb, ReorderBufferTXN *txn);
     303             : static void ReorderBufferToastReplace(ReorderBuffer *rb, ReorderBufferTXN *txn,
     304             :                                       Relation relation, ReorderBufferChange *change);
     305             : static void ReorderBufferToastAppendChunk(ReorderBuffer *rb, ReorderBufferTXN *txn,
     306             :                                           Relation relation, ReorderBufferChange *change);
     307             : 
     308             : /*
     309             :  * ---------------------------------------
     310             :  * memory accounting
     311             :  * ---------------------------------------
     312             :  */
     313             : static Size ReorderBufferChangeSize(ReorderBufferChange *change);
     314             : static void ReorderBufferChangeMemoryUpdate(ReorderBuffer *rb,
     315             :                                             ReorderBufferChange *change,
     316             :                                             ReorderBufferTXN *txn,
     317             :                                             bool addition, Size sz);
     318             : 
     319             : /*
     320             :  * Allocate a new ReorderBuffer and clean out any old serialized state from
     321             :  * prior ReorderBuffer instances for the same slot.
     322             :  */
     323             : ReorderBuffer *
     324        2108 : ReorderBufferAllocate(void)
     325             : {
     326             :     ReorderBuffer *buffer;
     327             :     HASHCTL     hash_ctl;
     328             :     MemoryContext new_ctx;
     329             : 
     330             :     Assert(MyReplicationSlot != NULL);
     331             : 
     332             :     /* allocate memory in own context, to have better accountability */
     333        2108 :     new_ctx = AllocSetContextCreate(CurrentMemoryContext,
     334             :                                     "ReorderBuffer",
     335             :                                     ALLOCSET_DEFAULT_SIZES);
     336             : 
     337             :     buffer =
     338        2108 :         (ReorderBuffer *) MemoryContextAlloc(new_ctx, sizeof(ReorderBuffer));
     339             : 
     340        2108 :     memset(&hash_ctl, 0, sizeof(hash_ctl));
     341             : 
     342        2108 :     buffer->context = new_ctx;
     343             : 
     344        2108 :     buffer->change_context = SlabContextCreate(new_ctx,
     345             :                                                "Change",
     346             :                                                SLAB_DEFAULT_BLOCK_SIZE,
     347             :                                                sizeof(ReorderBufferChange));
     348             : 
     349        2108 :     buffer->txn_context = SlabContextCreate(new_ctx,
     350             :                                             "TXN",
     351             :                                             SLAB_DEFAULT_BLOCK_SIZE,
     352             :                                             sizeof(ReorderBufferTXN));
     353             : 
     354             :     /*
     355             :      * To minimize memory fragmentation caused by long-running transactions
     356             :      * with changes spanning multiple memory blocks, we use a single
     357             :      * fixed-size memory block for decoded tuple storage. The performance
     358             :      * testing showed that the default memory block size maintains logical
     359             :      * decoding performance without causing fragmentation due to concurrent
     360             :      * transactions. One might think that we can use the max size as
     361             :      * SLAB_LARGE_BLOCK_SIZE but the test also showed it doesn't help resolve
     362             :      * the memory fragmentation.
     363             :      */
     364        2108 :     buffer->tup_context = GenerationContextCreate(new_ctx,
     365             :                                                   "Tuples",
     366             :                                                   SLAB_DEFAULT_BLOCK_SIZE,
     367             :                                                   SLAB_DEFAULT_BLOCK_SIZE,
     368             :                                                   SLAB_DEFAULT_BLOCK_SIZE);
     369             : 
     370        2108 :     hash_ctl.keysize = sizeof(TransactionId);
     371        2108 :     hash_ctl.entrysize = sizeof(ReorderBufferTXNByIdEnt);
     372        2108 :     hash_ctl.hcxt = buffer->context;
     373             : 
     374        2108 :     buffer->by_txn = hash_create("ReorderBufferByXid", 1000, &hash_ctl,
     375             :                                  HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
     376             : 
     377        2108 :     buffer->by_txn_last_xid = InvalidTransactionId;
     378        2108 :     buffer->by_txn_last_txn = NULL;
     379             : 
     380        2108 :     buffer->outbuf = NULL;
     381        2108 :     buffer->outbufsize = 0;
     382        2108 :     buffer->size = 0;
     383             : 
     384             :     /* txn_heap is ordered by transaction size */
     385        2108 :     buffer->txn_heap = pairingheap_allocate(ReorderBufferTXNSizeCompare, NULL);
     386             : 
     387        2108 :     buffer->spillTxns = 0;
     388        2108 :     buffer->spillCount = 0;
     389        2108 :     buffer->spillBytes = 0;
     390        2108 :     buffer->streamTxns = 0;
     391        2108 :     buffer->streamCount = 0;
     392        2108 :     buffer->streamBytes = 0;
     393        2108 :     buffer->totalTxns = 0;
     394        2108 :     buffer->totalBytes = 0;
     395             : 
     396        2108 :     buffer->current_restart_decoding_lsn = InvalidXLogRecPtr;
     397             : 
     398        2108 :     dlist_init(&buffer->toplevel_by_lsn);
     399        2108 :     dlist_init(&buffer->txns_by_base_snapshot_lsn);
     400        2108 :     dclist_init(&buffer->catchange_txns);
     401             : 
     402             :     /*
     403             :      * Ensure there's no stale data from prior uses of this slot, in case some
     404             :      * prior exit avoided calling ReorderBufferFree. Failure to do this can
     405             :      * produce duplicated txns, and it's very cheap if there's nothing there.
     406             :      */
     407        2108 :     ReorderBufferCleanupSerializedTXNs(NameStr(MyReplicationSlot->data.name));
     408             : 
     409        2108 :     return buffer;
     410             : }
     411             : 
     412             : /*
     413             :  * Free a ReorderBuffer
     414             :  */
     415             : void
     416        1720 : ReorderBufferFree(ReorderBuffer *rb)
     417             : {
     418        1720 :     MemoryContext context = rb->context;
     419             : 
     420             :     /*
     421             :      * We free separately allocated data by entirely scrapping reorderbuffer's
     422             :      * memory context.
     423             :      */
     424        1720 :     MemoryContextDelete(context);
     425             : 
     426             :     /* Free disk space used by unconsumed reorder buffers */
     427        1720 :     ReorderBufferCleanupSerializedTXNs(NameStr(MyReplicationSlot->data.name));
     428        1720 : }
     429             : 
     430             : /*
     431             :  * Allocate a new ReorderBufferTXN.
     432             :  */
     433             : static ReorderBufferTXN *
     434        7126 : ReorderBufferAllocTXN(ReorderBuffer *rb)
     435             : {
     436             :     ReorderBufferTXN *txn;
     437             : 
     438             :     txn = (ReorderBufferTXN *)
     439        7126 :         MemoryContextAlloc(rb->txn_context, sizeof(ReorderBufferTXN));
     440             : 
     441        7126 :     memset(txn, 0, sizeof(ReorderBufferTXN));
     442             : 
     443        7126 :     dlist_init(&txn->changes);
     444        7126 :     dlist_init(&txn->tuplecids);
     445        7126 :     dlist_init(&txn->subtxns);
     446             : 
     447             :     /* InvalidCommandId is not zero, so set it explicitly */
     448        7126 :     txn->command_id = InvalidCommandId;
     449        7126 :     txn->output_plugin_private = NULL;
     450             : 
     451        7126 :     return txn;
     452             : }
     453             : 
     454             : /*
     455             :  * Free a ReorderBufferTXN.
     456             :  */
     457             : static void
     458        7006 : ReorderBufferFreeTXN(ReorderBuffer *rb, ReorderBufferTXN *txn)
     459             : {
     460             :     /* clean the lookup cache if we were cached (quite likely) */
     461        7006 :     if (rb->by_txn_last_xid == txn->xid)
     462             :     {
     463        6636 :         rb->by_txn_last_xid = InvalidTransactionId;
     464        6636 :         rb->by_txn_last_txn = NULL;
     465             :     }
     466             : 
     467             :     /* free data that's contained */
     468             : 
     469        7006 :     if (txn->gid != NULL)
     470             :     {
     471          84 :         pfree(txn->gid);
     472          84 :         txn->gid = NULL;
     473             :     }
     474             : 
     475        7006 :     if (txn->tuplecid_hash != NULL)
     476             :     {
     477        1032 :         hash_destroy(txn->tuplecid_hash);
     478        1032 :         txn->tuplecid_hash = NULL;
     479             :     }
     480             : 
     481        7006 :     if (txn->invalidations)
     482             :     {
     483        2106 :         pfree(txn->invalidations);
     484        2106 :         txn->invalidations = NULL;
     485             :     }
     486             : 
     487        7006 :     if (txn->invalidations_distributed)
     488             :     {
     489          44 :         pfree(txn->invalidations_distributed);
     490          44 :         txn->invalidations_distributed = NULL;
     491             :     }
     492             : 
     493             :     /* Reset the toast hash */
     494        7006 :     ReorderBufferToastReset(rb, txn);
     495             : 
     496             :     /* All changes must be deallocated */
     497             :     Assert(txn->size == 0);
     498             : 
     499        7006 :     pfree(txn);
     500        7006 : }
     501             : 
     502             : /*
     503             :  * Allocate a ReorderBufferChange.
     504             :  */
     505             : ReorderBufferChange *
     506     3481542 : ReorderBufferAllocChange(ReorderBuffer *rb)
     507             : {
     508             :     ReorderBufferChange *change;
     509             : 
     510             :     change = (ReorderBufferChange *)
     511     3481542 :         MemoryContextAlloc(rb->change_context, sizeof(ReorderBufferChange));
     512             : 
     513     3481542 :     memset(change, 0, sizeof(ReorderBufferChange));
     514     3481542 :     return change;
     515             : }
     516             : 
     517             : /*
     518             :  * Free a ReorderBufferChange and update memory accounting, if requested.
     519             :  */
     520             : void
     521     3481076 : ReorderBufferFreeChange(ReorderBuffer *rb, ReorderBufferChange *change,
     522             :                         bool upd_mem)
     523             : {
     524             :     /* update memory accounting info */
     525     3481076 :     if (upd_mem)
     526      403292 :         ReorderBufferChangeMemoryUpdate(rb, change, NULL, false,
     527             :                                         ReorderBufferChangeSize(change));
     528             : 
     529             :     /* free contained data */
     530     3481076 :     switch (change->action)
     531             :     {
     532     3335632 :         case REORDER_BUFFER_CHANGE_INSERT:
     533             :         case REORDER_BUFFER_CHANGE_UPDATE:
     534             :         case REORDER_BUFFER_CHANGE_DELETE:
     535             :         case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_INSERT:
     536     3335632 :             if (change->data.tp.newtuple)
     537             :             {
     538     2906784 :                 ReorderBufferFreeTupleBuf(change->data.tp.newtuple);
     539     2906784 :                 change->data.tp.newtuple = NULL;
     540             :             }
     541             : 
     542     3335632 :             if (change->data.tp.oldtuple)
     543             :             {
     544      292152 :                 ReorderBufferFreeTupleBuf(change->data.tp.oldtuple);
     545      292152 :                 change->data.tp.oldtuple = NULL;
     546             :             }
     547     3335632 :             break;
     548          80 :         case REORDER_BUFFER_CHANGE_MESSAGE:
     549          80 :             if (change->data.msg.prefix != NULL)
     550          80 :                 pfree(change->data.msg.prefix);
     551          80 :             change->data.msg.prefix = NULL;
     552          80 :             if (change->data.msg.message != NULL)
     553          80 :                 pfree(change->data.msg.message);
     554          80 :             change->data.msg.message = NULL;
     555          80 :             break;
     556        9726 :         case REORDER_BUFFER_CHANGE_INVALIDATION:
     557        9726 :             if (change->data.inval.invalidations)
     558        9726 :                 pfree(change->data.inval.invalidations);
     559        9726 :             change->data.inval.invalidations = NULL;
     560        9726 :             break;
     561        2166 :         case REORDER_BUFFER_CHANGE_INTERNAL_SNAPSHOT:
     562        2166 :             if (change->data.snapshot)
     563             :             {
     564        2166 :                 ReorderBufferFreeSnap(rb, change->data.snapshot);
     565        2166 :                 change->data.snapshot = NULL;
     566             :             }
     567        2166 :             break;
     568             :             /* no data in addition to the struct itself */
     569          80 :         case REORDER_BUFFER_CHANGE_TRUNCATE:
     570          80 :             if (change->data.truncate.relids != NULL)
     571             :             {
     572          80 :                 ReorderBufferFreeRelids(rb, change->data.truncate.relids);
     573          80 :                 change->data.truncate.relids = NULL;
     574             :             }
     575          80 :             break;
     576      133392 :         case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_CONFIRM:
     577             :         case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_ABORT:
     578             :         case REORDER_BUFFER_CHANGE_INTERNAL_COMMAND_ID:
     579             :         case REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID:
     580      133392 :             break;
     581             :     }
     582             : 
     583     3481076 :     pfree(change);
     584     3481076 : }
     585             : 
     586             : /*
     587             :  * Allocate a HeapTuple fitting a tuple of size tuple_len (excluding header
     588             :  * overhead).
     589             :  */
     590             : HeapTuple
     591     3199028 : ReorderBufferAllocTupleBuf(ReorderBuffer *rb, Size tuple_len)
     592             : {
     593             :     HeapTuple   tuple;
     594             :     Size        alloc_len;
     595             : 
     596     3199028 :     alloc_len = tuple_len + SizeofHeapTupleHeader;
     597             : 
     598     3199028 :     tuple = (HeapTuple) MemoryContextAlloc(rb->tup_context,
     599             :                                            HEAPTUPLESIZE + alloc_len);
     600     3199028 :     tuple->t_data = (HeapTupleHeader) ((char *) tuple + HEAPTUPLESIZE);
     601             : 
     602     3199028 :     return tuple;
     603             : }
     604             : 
     605             : /*
     606             :  * Free a HeapTuple returned by ReorderBufferAllocTupleBuf().
     607             :  */
     608             : void
     609     3198936 : ReorderBufferFreeTupleBuf(HeapTuple tuple)
     610             : {
     611     3198936 :     pfree(tuple);
     612     3198936 : }
     613             : 
     614             : /*
     615             :  * Allocate an array for relids of truncated relations.
     616             :  *
     617             :  * We use the global memory context (for the whole reorder buffer), because
     618             :  * none of the existing ones seems like a good match (some are SLAB, so we
     619             :  * can't use those, and tup_context is meant for tuple data, not relids). We
     620             :  * could add yet another context, but it seems like an overkill - TRUNCATE is
     621             :  * not particularly common operation, so it does not seem worth it.
     622             :  */
     623             : Oid *
     624          90 : ReorderBufferAllocRelids(ReorderBuffer *rb, int nrelids)
     625             : {
     626             :     Oid        *relids;
     627             :     Size        alloc_len;
     628             : 
     629          90 :     alloc_len = sizeof(Oid) * nrelids;
     630             : 
     631          90 :     relids = (Oid *) MemoryContextAlloc(rb->context, alloc_len);
     632             : 
     633          90 :     return relids;
     634             : }
     635             : 
     636             : /*
     637             :  * Free an array of relids.
     638             :  */
     639             : void
     640          80 : ReorderBufferFreeRelids(ReorderBuffer *rb, Oid *relids)
     641             : {
     642          80 :     pfree(relids);
     643          80 : }
     644             : 
     645             : /*
     646             :  * Return the ReorderBufferTXN from the given buffer, specified by Xid.
     647             :  * If create is true, and a transaction doesn't already exist, create it
     648             :  * (with the given LSN, and as top transaction if that's specified);
     649             :  * when this happens, is_new is set to true.
     650             :  */
     651             : static ReorderBufferTXN *
     652    11564216 : ReorderBufferTXNByXid(ReorderBuffer *rb, TransactionId xid, bool create,
     653             :                       bool *is_new, XLogRecPtr lsn, bool create_as_top)
     654             : {
     655             :     ReorderBufferTXN *txn;
     656             :     ReorderBufferTXNByIdEnt *ent;
     657             :     bool        found;
     658             : 
     659             :     Assert(TransactionIdIsValid(xid));
     660             : 
     661             :     /*
     662             :      * Check the one-entry lookup cache first
     663             :      */
     664    11564216 :     if (TransactionIdIsValid(rb->by_txn_last_xid) &&
     665    11557502 :         rb->by_txn_last_xid == xid)
     666             :     {
     667     9577748 :         txn = rb->by_txn_last_txn;
     668             : 
     669     9577748 :         if (txn != NULL)
     670             :         {
     671             :             /* found it, and it's valid */
     672     9577724 :             if (is_new)
     673        5588 :                 *is_new = false;
     674     9577724 :             return txn;
     675             :         }
     676             : 
     677             :         /*
     678             :          * cached as non-existent, and asked not to create? Then nothing else
     679             :          * to do.
     680             :          */
     681          24 :         if (!create)
     682          18 :             return NULL;
     683             :         /* otherwise fall through to create it */
     684             :     }
     685             : 
     686             :     /*
     687             :      * If the cache wasn't hit or it yielded a "does-not-exist" and we want to
     688             :      * create an entry.
     689             :      */
     690             : 
     691             :     /* search the lookup table */
     692             :     ent = (ReorderBufferTXNByIdEnt *)
     693     1986474 :         hash_search(rb->by_txn,
     694             :                     &xid,
     695             :                     create ? HASH_ENTER : HASH_FIND,
     696             :                     &found);
     697     1986474 :     if (found)
     698     1976782 :         txn = ent->txn;
     699        9692 :     else if (create)
     700             :     {
     701             :         /* initialize the new entry, if creation was requested */
     702             :         Assert(ent != NULL);
     703             :         Assert(lsn != InvalidXLogRecPtr);
     704             : 
     705        7126 :         ent->txn = ReorderBufferAllocTXN(rb);
     706        7126 :         ent->txn->xid = xid;
     707        7126 :         txn = ent->txn;
     708        7126 :         txn->first_lsn = lsn;
     709        7126 :         txn->restart_decoding_lsn = rb->current_restart_decoding_lsn;
     710             : 
     711        7126 :         if (create_as_top)
     712             :         {
     713        5760 :             dlist_push_tail(&rb->toplevel_by_lsn, &txn->node);
     714        5760 :             AssertTXNLsnOrder(rb);
     715             :         }
     716             :     }
     717             :     else
     718        2566 :         txn = NULL;             /* not found and not asked to create */
     719             : 
     720             :     /* update cache */
     721     1986474 :     rb->by_txn_last_xid = xid;
     722     1986474 :     rb->by_txn_last_txn = txn;
     723             : 
     724     1986474 :     if (is_new)
     725        3590 :         *is_new = !found;
     726             : 
     727             :     Assert(!create || txn != NULL);
     728     1986474 :     return txn;
     729             : }
     730             : 
     731             : /*
     732             :  * Record the partial change for the streaming of in-progress transactions.  We
     733             :  * can stream only complete changes so if we have a partial change like toast
     734             :  * table insert or speculative insert then we mark such a 'txn' so that it
     735             :  * can't be streamed.  We also ensure that if the changes in such a 'txn' can
     736             :  * be streamed and are above logical_decoding_work_mem threshold then we stream
     737             :  * them as soon as we have a complete change.
     738             :  */
     739             : static void
     740     3059228 : ReorderBufferProcessPartialChange(ReorderBuffer *rb, ReorderBufferTXN *txn,
     741             :                                   ReorderBufferChange *change,
     742             :                                   bool toast_insert)
     743             : {
     744             :     ReorderBufferTXN *toptxn;
     745             : 
     746             :     /*
     747             :      * The partial changes need to be processed only while streaming
     748             :      * in-progress transactions.
     749             :      */
     750     3059228 :     if (!ReorderBufferCanStream(rb))
     751     2420784 :         return;
     752             : 
     753             :     /* Get the top transaction. */
     754      638444 :     toptxn = rbtxn_get_toptxn(txn);
     755             : 
     756             :     /*
     757             :      * Indicate a partial change for toast inserts.  The change will be
     758             :      * considered as complete once we get the insert or update on the main
     759             :      * table and we are sure that the pending toast chunks are not required
     760             :      * anymore.
     761             :      *
     762             :      * If we allow streaming when there are pending toast chunks then such
     763             :      * chunks won't be released till the insert (multi_insert) is complete and
     764             :      * we expect the txn to have streamed all changes after streaming.  This
     765             :      * restriction is mainly to ensure the correctness of streamed
     766             :      * transactions and it doesn't seem worth uplifting such a restriction
     767             :      * just to allow this case because anyway we will stream the transaction
     768             :      * once such an insert is complete.
     769             :      */
     770      638444 :     if (toast_insert)
     771        3332 :         toptxn->txn_flags |= RBTXN_HAS_PARTIAL_CHANGE;
     772      635112 :     else if (rbtxn_has_partial_change(toptxn) &&
     773         126 :              IsInsertOrUpdate(change->action) &&
     774         126 :              change->data.tp.clear_toast_afterwards)
     775          86 :         toptxn->txn_flags &= ~RBTXN_HAS_PARTIAL_CHANGE;
     776             : 
     777             :     /*
     778             :      * Indicate a partial change for speculative inserts.  The change will be
     779             :      * considered as complete once we get the speculative confirm or abort
     780             :      * token.
     781             :      */
     782      638444 :     if (IsSpecInsert(change->action))
     783           0 :         toptxn->txn_flags |= RBTXN_HAS_PARTIAL_CHANGE;
     784      638444 :     else if (rbtxn_has_partial_change(toptxn) &&
     785        3372 :              IsSpecConfirmOrAbort(change->action))
     786           0 :         toptxn->txn_flags &= ~RBTXN_HAS_PARTIAL_CHANGE;
     787             : 
     788             :     /*
     789             :      * Stream the transaction if it is serialized before and the changes are
     790             :      * now complete in the top-level transaction.
     791             :      *
     792             :      * The reason for doing the streaming of such a transaction as soon as we
     793             :      * get the complete change for it is that previously it would have reached
     794             :      * the memory threshold and wouldn't get streamed because of incomplete
     795             :      * changes.  Delaying such transactions would increase apply lag for them.
     796             :      */
     797      638444 :     if (ReorderBufferCanStartStreaming(rb) &&
     798      343766 :         !(rbtxn_has_partial_change(toptxn)) &&
     799      340694 :         rbtxn_is_serialized(txn) &&
     800          78 :         rbtxn_has_streamable_change(toptxn))
     801          18 :         ReorderBufferStreamTXN(rb, toptxn);
     802             : }
     803             : 
     804             : /*
     805             :  * Queue a change into a transaction so it can be replayed upon commit or will be
     806             :  * streamed when we reach logical_decoding_work_mem threshold.
     807             :  */
     808             : void
     809     3078046 : ReorderBufferQueueChange(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn,
     810             :                          ReorderBufferChange *change, bool toast_insert)
     811             : {
     812             :     ReorderBufferTXN *txn;
     813             : 
     814     3078046 :     txn = ReorderBufferTXNByXid(rb, xid, true, NULL, lsn, true);
     815             : 
     816             :     /*
     817             :      * If we have detected that the transaction is aborted while streaming the
     818             :      * previous changes or by checking its CLOG, there is no point in
     819             :      * collecting further changes for it.
     820             :      */
     821     3078046 :     if (rbtxn_is_aborted(txn))
     822             :     {
     823             :         /*
     824             :          * We don't need to update memory accounting for this change as we
     825             :          * have not added it to the queue yet.
     826             :          */
     827       18818 :         ReorderBufferFreeChange(rb, change, false);
     828       18818 :         return;
     829             :     }
     830             : 
     831             :     /*
     832             :      * The changes that are sent downstream are considered streamable.  We
     833             :      * remember such transactions so that only those will later be considered
     834             :      * for streaming.
     835             :      */
     836     3059228 :     if (change->action == REORDER_BUFFER_CHANGE_INSERT ||
     837      854860 :         change->action == REORDER_BUFFER_CHANGE_UPDATE ||
     838      535618 :         change->action == REORDER_BUFFER_CHANGE_DELETE ||
     839      130510 :         change->action == REORDER_BUFFER_CHANGE_INTERNAL_SPEC_INSERT ||
     840       94678 :         change->action == REORDER_BUFFER_CHANGE_TRUNCATE ||
     841       94608 :         change->action == REORDER_BUFFER_CHANGE_MESSAGE)
     842             :     {
     843     2964698 :         ReorderBufferTXN *toptxn = rbtxn_get_toptxn(txn);
     844             : 
     845     2964698 :         toptxn->txn_flags |= RBTXN_HAS_STREAMABLE_CHANGE;
     846             :     }
     847             : 
     848     3059228 :     change->lsn = lsn;
     849     3059228 :     change->txn = txn;
     850             : 
     851             :     Assert(InvalidXLogRecPtr != lsn);
     852     3059228 :     dlist_push_tail(&txn->changes, &change->node);
     853     3059228 :     txn->nentries++;
     854     3059228 :     txn->nentries_mem++;
     855             : 
     856             :     /* update memory accounting information */
     857     3059228 :     ReorderBufferChangeMemoryUpdate(rb, change, NULL, true,
     858             :                                     ReorderBufferChangeSize(change));
     859             : 
     860             :     /* process partial change */
     861     3059228 :     ReorderBufferProcessPartialChange(rb, txn, change, toast_insert);
     862             : 
     863             :     /* check the memory limits and evict something if needed */
     864     3059228 :     ReorderBufferCheckMemoryLimit(rb);
     865             : }
     866             : 
     867             : /*
     868             :  * A transactional message is queued to be processed upon commit and a
     869             :  * non-transactional message gets processed immediately.
     870             :  */
     871             : void
     872          94 : ReorderBufferQueueMessage(ReorderBuffer *rb, TransactionId xid,
     873             :                           Snapshot snap, XLogRecPtr lsn,
     874             :                           bool transactional, const char *prefix,
     875             :                           Size message_size, const char *message)
     876             : {
     877          94 :     if (transactional)
     878             :     {
     879             :         MemoryContext oldcontext;
     880             :         ReorderBufferChange *change;
     881             : 
     882             :         Assert(xid != InvalidTransactionId);
     883             : 
     884             :         /*
     885             :          * We don't expect snapshots for transactional changes - we'll use the
     886             :          * snapshot derived later during apply (unless the change gets
     887             :          * skipped).
     888             :          */
     889             :         Assert(!snap);
     890             : 
     891          78 :         oldcontext = MemoryContextSwitchTo(rb->context);
     892             : 
     893          78 :         change = ReorderBufferAllocChange(rb);
     894          78 :         change->action = REORDER_BUFFER_CHANGE_MESSAGE;
     895          78 :         change->data.msg.prefix = pstrdup(prefix);
     896          78 :         change->data.msg.message_size = message_size;
     897          78 :         change->data.msg.message = palloc(message_size);
     898          78 :         memcpy(change->data.msg.message, message, message_size);
     899             : 
     900          78 :         ReorderBufferQueueChange(rb, xid, lsn, change, false);
     901             : 
     902          78 :         MemoryContextSwitchTo(oldcontext);
     903             :     }
     904             :     else
     905             :     {
     906          16 :         ReorderBufferTXN *txn = NULL;
     907          16 :         volatile Snapshot snapshot_now = snap;
     908             : 
     909             :         /* Non-transactional changes require a valid snapshot. */
     910             :         Assert(snapshot_now);
     911             : 
     912          16 :         if (xid != InvalidTransactionId)
     913           6 :             txn = ReorderBufferTXNByXid(rb, xid, true, NULL, lsn, true);
     914             : 
     915             :         /* setup snapshot to allow catalog access */
     916          16 :         SetupHistoricSnapshot(snapshot_now, NULL);
     917          16 :         PG_TRY();
     918             :         {
     919          16 :             rb->message(rb, txn, lsn, false, prefix, message_size, message);
     920             : 
     921          16 :             TeardownHistoricSnapshot(false);
     922             :         }
     923           0 :         PG_CATCH();
     924             :         {
     925           0 :             TeardownHistoricSnapshot(true);
     926           0 :             PG_RE_THROW();
     927             :         }
     928          16 :         PG_END_TRY();
     929             :     }
     930          94 : }
     931             : 
     932             : /*
     933             :  * AssertTXNLsnOrder
     934             :  *      Verify LSN ordering of transaction lists in the reorderbuffer
     935             :  *
     936             :  * Other LSN-related invariants are checked too.
     937             :  *
     938             :  * No-op if assertions are not in use.
     939             :  */
     940             : static void
     941       14416 : AssertTXNLsnOrder(ReorderBuffer *rb)
     942             : {
     943             : #ifdef USE_ASSERT_CHECKING
     944             :     LogicalDecodingContext *ctx = rb->private_data;
     945             :     dlist_iter  iter;
     946             :     XLogRecPtr  prev_first_lsn = InvalidXLogRecPtr;
     947             :     XLogRecPtr  prev_base_snap_lsn = InvalidXLogRecPtr;
     948             : 
     949             :     /*
     950             :      * Skip the verification if we don't reach the LSN at which we start
     951             :      * decoding the contents of transactions yet because until we reach the
     952             :      * LSN, we could have transactions that don't have the association between
     953             :      * the top-level transaction and subtransaction yet and consequently have
     954             :      * the same LSN.  We don't guarantee this association until we try to
     955             :      * decode the actual contents of transaction. The ordering of the records
     956             :      * prior to the start_decoding_at LSN should have been checked before the
     957             :      * restart.
     958             :      */
     959             :     if (SnapBuildXactNeedsSkip(ctx->snapshot_builder, ctx->reader->EndRecPtr))
     960             :         return;
     961             : 
     962             :     dlist_foreach(iter, &rb->toplevel_by_lsn)
     963             :     {
     964             :         ReorderBufferTXN *cur_txn = dlist_container(ReorderBufferTXN, node,
     965             :                                                     iter.cur);
     966             : 
     967             :         /* start LSN must be set */
     968             :         Assert(cur_txn->first_lsn != InvalidXLogRecPtr);
     969             : 
     970             :         /* If there is an end LSN, it must be higher than start LSN */
     971             :         if (cur_txn->end_lsn != InvalidXLogRecPtr)
     972             :             Assert(cur_txn->first_lsn <= cur_txn->end_lsn);
     973             : 
     974             :         /* Current initial LSN must be strictly higher than previous */
     975             :         if (prev_first_lsn != InvalidXLogRecPtr)
     976             :             Assert(prev_first_lsn < cur_txn->first_lsn);
     977             : 
     978             :         /* known-as-subtxn txns must not be listed */
     979             :         Assert(!rbtxn_is_known_subxact(cur_txn));
     980             : 
     981             :         prev_first_lsn = cur_txn->first_lsn;
     982             :     }
     983             : 
     984             :     dlist_foreach(iter, &rb->txns_by_base_snapshot_lsn)
     985             :     {
     986             :         ReorderBufferTXN *cur_txn = dlist_container(ReorderBufferTXN,
     987             :                                                     base_snapshot_node,
     988             :                                                     iter.cur);
     989             : 
     990             :         /* base snapshot (and its LSN) must be set */
     991             :         Assert(cur_txn->base_snapshot != NULL);
     992             :         Assert(cur_txn->base_snapshot_lsn != InvalidXLogRecPtr);
     993             : 
     994             :         /* current LSN must be strictly higher than previous */
     995             :         if (prev_base_snap_lsn != InvalidXLogRecPtr)
     996             :             Assert(prev_base_snap_lsn < cur_txn->base_snapshot_lsn);
     997             : 
     998             :         /* known-as-subtxn txns must not be listed */
     999             :         Assert(!rbtxn_is_known_subxact(cur_txn));
    1000             : 
    1001             :         prev_base_snap_lsn = cur_txn->base_snapshot_lsn;
    1002             :     }
    1003             : #endif
    1004       14416 : }
    1005             : 
    1006             : /*
    1007             :  * AssertChangeLsnOrder
    1008             :  *
    1009             :  * Check ordering of changes in the (sub)transaction.
    1010             :  */
    1011             : static void
    1012        4834 : AssertChangeLsnOrder(ReorderBufferTXN *txn)
    1013             : {
    1014             : #ifdef USE_ASSERT_CHECKING
    1015             :     dlist_iter  iter;
    1016             :     XLogRecPtr  prev_lsn = txn->first_lsn;
    1017             : 
    1018             :     dlist_foreach(iter, &txn->changes)
    1019             :     {
    1020             :         ReorderBufferChange *cur_change;
    1021             : 
    1022             :         cur_change = dlist_container(ReorderBufferChange, node, iter.cur);
    1023             : 
    1024             :         Assert(txn->first_lsn != InvalidXLogRecPtr);
    1025             :         Assert(cur_change->lsn != InvalidXLogRecPtr);
    1026             :         Assert(txn->first_lsn <= cur_change->lsn);
    1027             : 
    1028             :         if (txn->end_lsn != InvalidXLogRecPtr)
    1029             :             Assert(cur_change->lsn <= txn->end_lsn);
    1030             : 
    1031             :         Assert(prev_lsn <= cur_change->lsn);
    1032             : 
    1033             :         prev_lsn = cur_change->lsn;
    1034             :     }
    1035             : #endif
    1036        4834 : }
    1037             : 
    1038             : /*
    1039             :  * ReorderBufferGetOldestTXN
    1040             :  *      Return oldest transaction in reorderbuffer
    1041             :  */
    1042             : ReorderBufferTXN *
    1043         774 : ReorderBufferGetOldestTXN(ReorderBuffer *rb)
    1044             : {
    1045             :     ReorderBufferTXN *txn;
    1046             : 
    1047         774 :     AssertTXNLsnOrder(rb);
    1048             : 
    1049         774 :     if (dlist_is_empty(&rb->toplevel_by_lsn))
    1050         662 :         return NULL;
    1051             : 
    1052         112 :     txn = dlist_head_element(ReorderBufferTXN, node, &rb->toplevel_by_lsn);
    1053             : 
    1054             :     Assert(!rbtxn_is_known_subxact(txn));
    1055             :     Assert(txn->first_lsn != InvalidXLogRecPtr);
    1056         112 :     return txn;
    1057             : }
    1058             : 
    1059             : /*
    1060             :  * ReorderBufferGetOldestXmin
    1061             :  *      Return oldest Xmin in reorderbuffer
    1062             :  *
    1063             :  * Returns oldest possibly running Xid from the point of view of snapshots
    1064             :  * used in the transactions kept by reorderbuffer, or InvalidTransactionId if
    1065             :  * there are none.
    1066             :  *
    1067             :  * Since snapshots are assigned monotonically, this equals the Xmin of the
    1068             :  * base snapshot with minimal base_snapshot_lsn.
    1069             :  */
    1070             : TransactionId
    1071         814 : ReorderBufferGetOldestXmin(ReorderBuffer *rb)
    1072             : {
    1073             :     ReorderBufferTXN *txn;
    1074             : 
    1075         814 :     AssertTXNLsnOrder(rb);
    1076             : 
    1077         814 :     if (dlist_is_empty(&rb->txns_by_base_snapshot_lsn))
    1078         720 :         return InvalidTransactionId;
    1079             : 
    1080          94 :     txn = dlist_head_element(ReorderBufferTXN, base_snapshot_node,
    1081             :                              &rb->txns_by_base_snapshot_lsn);
    1082          94 :     return txn->base_snapshot->xmin;
    1083             : }
    1084             : 
    1085             : void
    1086         862 : ReorderBufferSetRestartPoint(ReorderBuffer *rb, XLogRecPtr ptr)
    1087             : {
    1088         862 :     rb->current_restart_decoding_lsn = ptr;
    1089         862 : }
    1090             : 
    1091             : /*
    1092             :  * ReorderBufferAssignChild
    1093             :  *
    1094             :  * Make note that we know that subxid is a subtransaction of xid, seen as of
    1095             :  * the given lsn.
    1096             :  */
    1097             : void
    1098        1738 : ReorderBufferAssignChild(ReorderBuffer *rb, TransactionId xid,
    1099             :                          TransactionId subxid, XLogRecPtr lsn)
    1100             : {
    1101             :     ReorderBufferTXN *txn;
    1102             :     ReorderBufferTXN *subtxn;
    1103             :     bool        new_top;
    1104             :     bool        new_sub;
    1105             : 
    1106        1738 :     txn = ReorderBufferTXNByXid(rb, xid, true, &new_top, lsn, true);
    1107        1738 :     subtxn = ReorderBufferTXNByXid(rb, subxid, true, &new_sub, lsn, false);
    1108             : 
    1109        1738 :     if (!new_sub)
    1110             :     {
    1111         372 :         if (rbtxn_is_known_subxact(subtxn))
    1112             :         {
    1113             :             /* already associated, nothing to do */
    1114         372 :             return;
    1115             :         }
    1116             :         else
    1117             :         {
    1118             :             /*
    1119             :              * We already saw this transaction, but initially added it to the
    1120             :              * list of top-level txns.  Now that we know it's not top-level,
    1121             :              * remove it from there.
    1122             :              */
    1123           0 :             dlist_delete(&subtxn->node);
    1124             :         }
    1125             :     }
    1126             : 
    1127        1366 :     subtxn->txn_flags |= RBTXN_IS_SUBXACT;
    1128        1366 :     subtxn->toplevel_xid = xid;
    1129             :     Assert(subtxn->nsubtxns == 0);
    1130             : 
    1131             :     /* set the reference to top-level transaction */
    1132        1366 :     subtxn->toptxn = txn;
    1133             : 
    1134             :     /* add to subtransaction list */
    1135        1366 :     dlist_push_tail(&txn->subtxns, &subtxn->node);
    1136        1366 :     txn->nsubtxns++;
    1137             : 
    1138             :     /* Possibly transfer the subtxn's snapshot to its top-level txn. */
    1139        1366 :     ReorderBufferTransferSnapToParent(txn, subtxn);
    1140             : 
    1141             :     /* Verify LSN-ordering invariant */
    1142        1366 :     AssertTXNLsnOrder(rb);
    1143             : }
    1144             : 
    1145             : /*
    1146             :  * ReorderBufferTransferSnapToParent
    1147             :  *      Transfer base snapshot from subtxn to top-level txn, if needed
    1148             :  *
    1149             :  * This is done if the top-level txn doesn't have a base snapshot, or if the
    1150             :  * subtxn's base snapshot has an earlier LSN than the top-level txn's base
    1151             :  * snapshot's LSN.  This can happen if there are no changes in the toplevel
    1152             :  * txn but there are some in the subtxn, or the first change in subtxn has
    1153             :  * earlier LSN than first change in the top-level txn and we learned about
    1154             :  * their kinship only now.
    1155             :  *
    1156             :  * The subtransaction's snapshot is cleared regardless of the transfer
    1157             :  * happening, since it's not needed anymore in either case.
    1158             :  *
    1159             :  * We do this as soon as we become aware of their kinship, to avoid queueing
    1160             :  * extra snapshots to txns known-as-subtxns -- only top-level txns will
    1161             :  * receive further snapshots.
    1162             :  */
    1163             : static void
    1164        1374 : ReorderBufferTransferSnapToParent(ReorderBufferTXN *txn,
    1165             :                                   ReorderBufferTXN *subtxn)
    1166             : {
    1167             :     Assert(subtxn->toplevel_xid == txn->xid);
    1168             : 
    1169        1374 :     if (subtxn->base_snapshot != NULL)
    1170             :     {
    1171           0 :         if (txn->base_snapshot == NULL ||
    1172           0 :             subtxn->base_snapshot_lsn < txn->base_snapshot_lsn)
    1173             :         {
    1174             :             /*
    1175             :              * If the toplevel transaction already has a base snapshot but
    1176             :              * it's newer than the subxact's, purge it.
    1177             :              */
    1178           0 :             if (txn->base_snapshot != NULL)
    1179             :             {
    1180           0 :                 SnapBuildSnapDecRefcount(txn->base_snapshot);
    1181           0 :                 dlist_delete(&txn->base_snapshot_node);
    1182             :             }
    1183             : 
    1184             :             /*
    1185             :              * The snapshot is now the top transaction's; transfer it, and
    1186             :              * adjust the list position of the top transaction in the list by
    1187             :              * moving it to where the subtransaction is.
    1188             :              */
    1189           0 :             txn->base_snapshot = subtxn->base_snapshot;
    1190           0 :             txn->base_snapshot_lsn = subtxn->base_snapshot_lsn;
    1191           0 :             dlist_insert_before(&subtxn->base_snapshot_node,
    1192             :                                 &txn->base_snapshot_node);
    1193             : 
    1194             :             /*
    1195             :              * The subtransaction doesn't have a snapshot anymore (so it
    1196             :              * mustn't be in the list.)
    1197             :              */
    1198           0 :             subtxn->base_snapshot = NULL;
    1199           0 :             subtxn->base_snapshot_lsn = InvalidXLogRecPtr;
    1200           0 :             dlist_delete(&subtxn->base_snapshot_node);
    1201             :         }
    1202             :         else
    1203             :         {
    1204             :             /* Base snap of toplevel is fine, so subxact's is not needed */
    1205           0 :             SnapBuildSnapDecRefcount(subtxn->base_snapshot);
    1206           0 :             dlist_delete(&subtxn->base_snapshot_node);
    1207           0 :             subtxn->base_snapshot = NULL;
    1208           0 :             subtxn->base_snapshot_lsn = InvalidXLogRecPtr;
    1209             :         }
    1210             :     }
    1211        1374 : }
    1212             : 
    1213             : /*
    1214             :  * Associate a subtransaction with its toplevel transaction at commit
    1215             :  * time. There may be no further changes added after this.
    1216             :  */
    1217             : void
    1218         534 : ReorderBufferCommitChild(ReorderBuffer *rb, TransactionId xid,
    1219             :                          TransactionId subxid, XLogRecPtr commit_lsn,
    1220             :                          XLogRecPtr end_lsn)
    1221             : {
    1222             :     ReorderBufferTXN *subtxn;
    1223             : 
    1224         534 :     subtxn = ReorderBufferTXNByXid(rb, subxid, false, NULL,
    1225             :                                    InvalidXLogRecPtr, false);
    1226             : 
    1227             :     /*
    1228             :      * No need to do anything if that subtxn didn't contain any changes
    1229             :      */
    1230         534 :     if (!subtxn)
    1231         162 :         return;
    1232             : 
    1233         372 :     subtxn->final_lsn = commit_lsn;
    1234         372 :     subtxn->end_lsn = end_lsn;
    1235             : 
    1236             :     /*
    1237             :      * Assign this subxact as a child of the toplevel xact (no-op if already
    1238             :      * done.)
    1239             :      */
    1240         372 :     ReorderBufferAssignChild(rb, xid, subxid, InvalidXLogRecPtr);
    1241             : }
    1242             : 
    1243             : 
    1244             : /*
    1245             :  * Support for efficiently iterating over a transaction's and its
    1246             :  * subtransactions' changes.
    1247             :  *
    1248             :  * We do by doing a k-way merge between transactions/subtransactions. For that
    1249             :  * we model the current heads of the different transactions as a binary heap
    1250             :  * so we easily know which (sub-)transaction has the change with the smallest
    1251             :  * lsn next.
    1252             :  *
    1253             :  * We assume the changes in individual transactions are already sorted by LSN.
    1254             :  */
    1255             : 
    1256             : /*
    1257             :  * Binary heap comparison function.
    1258             :  */
    1259             : static int
    1260      103136 : ReorderBufferIterCompare(Datum a, Datum b, void *arg)
    1261             : {
    1262      103136 :     ReorderBufferIterTXNState *state = (ReorderBufferIterTXNState *) arg;
    1263      103136 :     XLogRecPtr  pos_a = state->entries[DatumGetInt32(a)].lsn;
    1264      103136 :     XLogRecPtr  pos_b = state->entries[DatumGetInt32(b)].lsn;
    1265             : 
    1266      103136 :     if (pos_a < pos_b)
    1267      101424 :         return 1;
    1268        1712 :     else if (pos_a == pos_b)
    1269           0 :         return 0;
    1270        1712 :     return -1;
    1271             : }
    1272             : 
    1273             : /*
    1274             :  * Allocate & initialize an iterator which iterates in lsn order over a
    1275             :  * transaction and all its subtransactions.
    1276             :  *
    1277             :  * Note: The iterator state is returned through iter_state parameter rather
    1278             :  * than the function's return value.  This is because the state gets cleaned up
    1279             :  * in a PG_CATCH block in the caller, so we want to make sure the caller gets
    1280             :  * back the state even if this function throws an exception.
    1281             :  */
    1282             : static void
    1283        3908 : ReorderBufferIterTXNInit(ReorderBuffer *rb, ReorderBufferTXN *txn,
    1284             :                          ReorderBufferIterTXNState *volatile *iter_state)
    1285             : {
    1286        3908 :     Size        nr_txns = 0;
    1287             :     ReorderBufferIterTXNState *state;
    1288             :     dlist_iter  cur_txn_i;
    1289             :     int32       off;
    1290             : 
    1291        3908 :     *iter_state = NULL;
    1292             : 
    1293             :     /* Check ordering of changes in the toplevel transaction. */
    1294        3908 :     AssertChangeLsnOrder(txn);
    1295             : 
    1296             :     /*
    1297             :      * Calculate the size of our heap: one element for every transaction that
    1298             :      * contains changes.  (Besides the transactions already in the reorder
    1299             :      * buffer, we count the one we were directly passed.)
    1300             :      */
    1301        3908 :     if (txn->nentries > 0)
    1302        3544 :         nr_txns++;
    1303             : 
    1304        4834 :     dlist_foreach(cur_txn_i, &txn->subtxns)
    1305             :     {
    1306             :         ReorderBufferTXN *cur_txn;
    1307             : 
    1308         926 :         cur_txn = dlist_container(ReorderBufferTXN, node, cur_txn_i.cur);
    1309             : 
    1310             :         /* Check ordering of changes in this subtransaction. */
    1311         926 :         AssertChangeLsnOrder(cur_txn);
    1312             : 
    1313         926 :         if (cur_txn->nentries > 0)
    1314         602 :             nr_txns++;
    1315             :     }
    1316             : 
    1317             :     /* allocate iteration state */
    1318             :     state = (ReorderBufferIterTXNState *)
    1319        3908 :         MemoryContextAllocZero(rb->context,
    1320             :                                sizeof(ReorderBufferIterTXNState) +
    1321        3908 :                                sizeof(ReorderBufferIterTXNEntry) * nr_txns);
    1322             : 
    1323        3908 :     state->nr_txns = nr_txns;
    1324        3908 :     dlist_init(&state->old_change);
    1325             : 
    1326        8054 :     for (off = 0; off < state->nr_txns; off++)
    1327             :     {
    1328        4146 :         state->entries[off].file.vfd = -1;
    1329        4146 :         state->entries[off].segno = 0;
    1330             :     }
    1331             : 
    1332             :     /* allocate heap */
    1333        3908 :     state->heap = binaryheap_allocate(state->nr_txns,
    1334             :                                       ReorderBufferIterCompare,
    1335             :                                       state);
    1336             : 
    1337             :     /* Now that the state fields are initialized, it is safe to return it. */
    1338        3908 :     *iter_state = state;
    1339             : 
    1340             :     /*
    1341             :      * Now insert items into the binary heap, in an unordered fashion.  (We
    1342             :      * will run a heap assembly step at the end; this is more efficient.)
    1343             :      */
    1344             : 
    1345        3908 :     off = 0;
    1346             : 
    1347             :     /* add toplevel transaction if it contains changes */
    1348        3908 :     if (txn->nentries > 0)
    1349             :     {
    1350             :         ReorderBufferChange *cur_change;
    1351             : 
    1352        3544 :         if (rbtxn_is_serialized(txn))
    1353             :         {
    1354             :             /* serialize remaining changes */
    1355          46 :             ReorderBufferSerializeTXN(rb, txn);
    1356          46 :             ReorderBufferRestoreChanges(rb, txn, &state->entries[off].file,
    1357             :                                         &state->entries[off].segno);
    1358             :         }
    1359             : 
    1360        3544 :         cur_change = dlist_head_element(ReorderBufferChange, node,
    1361             :                                         &txn->changes);
    1362             : 
    1363        3544 :         state->entries[off].lsn = cur_change->lsn;
    1364        3544 :         state->entries[off].change = cur_change;
    1365        3544 :         state->entries[off].txn = txn;
    1366             : 
    1367        3544 :         binaryheap_add_unordered(state->heap, Int32GetDatum(off++));
    1368             :     }
    1369             : 
    1370             :     /* add subtransactions if they contain changes */
    1371        4834 :     dlist_foreach(cur_txn_i, &txn->subtxns)
    1372             :     {
    1373             :         ReorderBufferTXN *cur_txn;
    1374             : 
    1375         926 :         cur_txn = dlist_container(ReorderBufferTXN, node, cur_txn_i.cur);
    1376             : 
    1377         926 :         if (cur_txn->nentries > 0)
    1378             :         {
    1379             :             ReorderBufferChange *cur_change;
    1380             : 
    1381         602 :             if (rbtxn_is_serialized(cur_txn))
    1382             :             {
    1383             :                 /* serialize remaining changes */
    1384          34 :                 ReorderBufferSerializeTXN(rb, cur_txn);
    1385          34 :                 ReorderBufferRestoreChanges(rb, cur_txn,
    1386             :                                             &state->entries[off].file,
    1387             :                                             &state->entries[off].segno);
    1388             :             }
    1389         602 :             cur_change = dlist_head_element(ReorderBufferChange, node,
    1390             :                                             &cur_txn->changes);
    1391             : 
    1392         602 :             state->entries[off].lsn = cur_change->lsn;
    1393         602 :             state->entries[off].change = cur_change;
    1394         602 :             state->entries[off].txn = cur_txn;
    1395             : 
    1396         602 :             binaryheap_add_unordered(state->heap, Int32GetDatum(off++));
    1397             :         }
    1398             :     }
    1399             : 
    1400             :     /* assemble a valid binary heap */
    1401        3908 :     binaryheap_build(state->heap);
    1402        3908 : }
    1403             : 
    1404             : /*
    1405             :  * Return the next change when iterating over a transaction and its
    1406             :  * subtransactions.
    1407             :  *
    1408             :  * Returns NULL when no further changes exist.
    1409             :  */
    1410             : static ReorderBufferChange *
    1411      722192 : ReorderBufferIterTXNNext(ReorderBuffer *rb, ReorderBufferIterTXNState *state)
    1412             : {
    1413             :     ReorderBufferChange *change;
    1414             :     ReorderBufferIterTXNEntry *entry;
    1415             :     int32       off;
    1416             : 
    1417             :     /* nothing there anymore */
    1418      722192 :     if (binaryheap_empty(state->heap))
    1419        3890 :         return NULL;
    1420             : 
    1421      718302 :     off = DatumGetInt32(binaryheap_first(state->heap));
    1422      718302 :     entry = &state->entries[off];
    1423             : 
    1424             :     /* free memory we might have "leaked" in the previous *Next call */
    1425      718302 :     if (!dlist_is_empty(&state->old_change))
    1426             :     {
    1427          90 :         change = dlist_container(ReorderBufferChange, node,
    1428             :                                  dlist_pop_head_node(&state->old_change));
    1429          90 :         ReorderBufferFreeChange(rb, change, true);
    1430             :         Assert(dlist_is_empty(&state->old_change));
    1431             :     }
    1432             : 
    1433      718302 :     change = entry->change;
    1434             : 
    1435             :     /*
    1436             :      * update heap with information about which transaction has the next
    1437             :      * relevant change in LSN order
    1438             :      */
    1439             : 
    1440             :     /* there are in-memory changes */
    1441      718302 :     if (dlist_has_next(&entry->txn->changes, &entry->change->node))
    1442             :     {
    1443      714090 :         dlist_node *next = dlist_next_node(&entry->txn->changes, &change->node);
    1444      714090 :         ReorderBufferChange *next_change =
    1445      714090 :             dlist_container(ReorderBufferChange, node, next);
    1446             : 
    1447             :         /* txn stays the same */
    1448      714090 :         state->entries[off].lsn = next_change->lsn;
    1449      714090 :         state->entries[off].change = next_change;
    1450             : 
    1451      714090 :         binaryheap_replace_first(state->heap, Int32GetDatum(off));
    1452      714090 :         return change;
    1453             :     }
    1454             : 
    1455             :     /* try to load changes from disk */
    1456        4212 :     if (entry->txn->nentries != entry->txn->nentries_mem)
    1457             :     {
    1458             :         /*
    1459             :          * Ugly: restoring changes will reuse *Change records, thus delete the
    1460             :          * current one from the per-tx list and only free in the next call.
    1461             :          */
    1462         130 :         dlist_delete(&change->node);
    1463         130 :         dlist_push_tail(&state->old_change, &change->node);
    1464             : 
    1465             :         /*
    1466             :          * Update the total bytes processed by the txn for which we are
    1467             :          * releasing the current set of changes and restoring the new set of
    1468             :          * changes.
    1469             :          */
    1470         130 :         rb->totalBytes += entry->txn->size;
    1471         130 :         if (ReorderBufferRestoreChanges(rb, entry->txn, &entry->file,
    1472             :                                         &state->entries[off].segno))
    1473             :         {
    1474             :             /* successfully restored changes from disk */
    1475             :             ReorderBufferChange *next_change =
    1476          72 :                 dlist_head_element(ReorderBufferChange, node,
    1477             :                                    &entry->txn->changes);
    1478             : 
    1479          72 :             elog(DEBUG2, "restored %u/%u changes from disk",
    1480             :                  (uint32) entry->txn->nentries_mem,
    1481             :                  (uint32) entry->txn->nentries);
    1482             : 
    1483             :             Assert(entry->txn->nentries_mem);
    1484             :             /* txn stays the same */
    1485          72 :             state->entries[off].lsn = next_change->lsn;
    1486          72 :             state->entries[off].change = next_change;
    1487          72 :             binaryheap_replace_first(state->heap, Int32GetDatum(off));
    1488             : 
    1489          72 :             return change;
    1490             :         }
    1491             :     }
    1492             : 
    1493             :     /* ok, no changes there anymore, remove */
    1494        4140 :     binaryheap_remove_first(state->heap);
    1495             : 
    1496        4140 :     return change;
    1497             : }
    1498             : 
    1499             : /*
    1500             :  * Deallocate the iterator
    1501             :  */
    1502             : static void
    1503        3908 : ReorderBufferIterTXNFinish(ReorderBuffer *rb,
    1504             :                            ReorderBufferIterTXNState *state)
    1505             : {
    1506             :     int32       off;
    1507             : 
    1508        8054 :     for (off = 0; off < state->nr_txns; off++)
    1509             :     {
    1510        4146 :         if (state->entries[off].file.vfd != -1)
    1511           0 :             FileClose(state->entries[off].file.vfd);
    1512             :     }
    1513             : 
    1514             :     /* free memory we might have "leaked" in the last *Next call */
    1515        3908 :     if (!dlist_is_empty(&state->old_change))
    1516             :     {
    1517             :         ReorderBufferChange *change;
    1518             : 
    1519          38 :         change = dlist_container(ReorderBufferChange, node,
    1520             :                                  dlist_pop_head_node(&state->old_change));
    1521          38 :         ReorderBufferFreeChange(rb, change, true);
    1522             :         Assert(dlist_is_empty(&state->old_change));
    1523             :     }
    1524             : 
    1525        3908 :     binaryheap_free(state->heap);
    1526        3908 :     pfree(state);
    1527        3908 : }
    1528             : 
    1529             : /*
    1530             :  * Cleanup the contents of a transaction, usually after the transaction
    1531             :  * committed or aborted.
    1532             :  */
    1533             : static void
    1534        7006 : ReorderBufferCleanupTXN(ReorderBuffer *rb, ReorderBufferTXN *txn)
    1535             : {
    1536             :     bool        found;
    1537             :     dlist_mutable_iter iter;
    1538        7006 :     Size        mem_freed = 0;
    1539             : 
    1540             :     /* cleanup subtransactions & their changes */
    1541        7376 :     dlist_foreach_modify(iter, &txn->subtxns)
    1542             :     {
    1543             :         ReorderBufferTXN *subtxn;
    1544             : 
    1545         370 :         subtxn = dlist_container(ReorderBufferTXN, node, iter.cur);
    1546             : 
    1547             :         /*
    1548             :          * Subtransactions are always associated to the toplevel TXN, even if
    1549             :          * they originally were happening inside another subtxn, so we won't
    1550             :          * ever recurse more than one level deep here.
    1551             :          */
    1552             :         Assert(rbtxn_is_known_subxact(subtxn));
    1553             :         Assert(subtxn->nsubtxns == 0);
    1554             : 
    1555         370 :         ReorderBufferCleanupTXN(rb, subtxn);
    1556             :     }
    1557             : 
    1558             :     /* cleanup changes in the txn */
    1559      159706 :     dlist_foreach_modify(iter, &txn->changes)
    1560             :     {
    1561             :         ReorderBufferChange *change;
    1562             : 
    1563      152700 :         change = dlist_container(ReorderBufferChange, node, iter.cur);
    1564             : 
    1565             :         /* Check we're not mixing changes from different transactions. */
    1566             :         Assert(change->txn == txn);
    1567             : 
    1568             :         /*
    1569             :          * Instead of updating the memory counter for individual changes, we
    1570             :          * sum up the size of memory to free so we can update the memory
    1571             :          * counter all together below. This saves costs of maintaining the
    1572             :          * max-heap.
    1573             :          */
    1574      152700 :         mem_freed += ReorderBufferChangeSize(change);
    1575             : 
    1576      152700 :         ReorderBufferFreeChange(rb, change, false);
    1577             :     }
    1578             : 
    1579             :     /* Update the memory counter */
    1580        7006 :     ReorderBufferChangeMemoryUpdate(rb, NULL, txn, false, mem_freed);
    1581             : 
    1582             :     /*
    1583             :      * Cleanup the tuplecids we stored for decoding catalog snapshot access.
    1584             :      * They are always stored in the toplevel transaction.
    1585             :      */
    1586       53558 :     dlist_foreach_modify(iter, &txn->tuplecids)
    1587             :     {
    1588             :         ReorderBufferChange *change;
    1589             : 
    1590       46552 :         change = dlist_container(ReorderBufferChange, node, iter.cur);
    1591             : 
    1592             :         /* Check we're not mixing changes from different transactions. */
    1593             :         Assert(change->txn == txn);
    1594             :         Assert(change->action == REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID);
    1595             : 
    1596       46552 :         ReorderBufferFreeChange(rb, change, true);
    1597             :     }
    1598             : 
    1599             :     /*
    1600             :      * Cleanup the base snapshot, if set.
    1601             :      */
    1602        7006 :     if (txn->base_snapshot != NULL)
    1603             :     {
    1604        5604 :         SnapBuildSnapDecRefcount(txn->base_snapshot);
    1605        5604 :         dlist_delete(&txn->base_snapshot_node);
    1606             :     }
    1607             : 
    1608             :     /*
    1609             :      * Cleanup the snapshot for the last streamed run.
    1610             :      */
    1611        7006 :     if (txn->snapshot_now != NULL)
    1612             :     {
    1613             :         Assert(rbtxn_is_streamed(txn));
    1614         132 :         ReorderBufferFreeSnap(rb, txn->snapshot_now);
    1615             :     }
    1616             : 
    1617             :     /*
    1618             :      * Remove TXN from its containing lists.
    1619             :      *
    1620             :      * Note: if txn is known as subxact, we are deleting the TXN from its
    1621             :      * parent's list of known subxacts; this leaves the parent's nsubxacts
    1622             :      * count too high, but we don't care.  Otherwise, we are deleting the TXN
    1623             :      * from the LSN-ordered list of toplevel TXNs. We remove the TXN from the
    1624             :      * list of catalog modifying transactions as well.
    1625             :      */
    1626        7006 :     dlist_delete(&txn->node);
    1627        7006 :     if (rbtxn_has_catalog_changes(txn))
    1628        2224 :         dclist_delete_from(&rb->catchange_txns, &txn->catchange_node);
    1629             : 
    1630             :     /* now remove reference from buffer */
    1631        7006 :     hash_search(rb->by_txn, &txn->xid, HASH_REMOVE, &found);
    1632             :     Assert(found);
    1633             : 
    1634             :     /* remove entries spilled to disk */
    1635        7006 :     if (rbtxn_is_serialized(txn))
    1636         552 :         ReorderBufferRestoreCleanup(rb, txn);
    1637             : 
    1638             :     /* deallocate */
    1639        7006 :     ReorderBufferFreeTXN(rb, txn);
    1640        7006 : }
    1641             : 
    1642             : /*
    1643             :  * Discard changes from a transaction (and subtransactions), either after
    1644             :  * streaming, decoding them at PREPARE, or detecting the transaction abort.
    1645             :  * Keep the remaining info - transactions, tuplecids, invalidations and
    1646             :  * snapshots.
    1647             :  *
    1648             :  * We additionally remove tuplecids after decoding the transaction at prepare
    1649             :  * time as we only need to perform invalidation at rollback or commit prepared.
    1650             :  *
    1651             :  * 'txn_prepared' indicates that we have decoded the transaction at prepare
    1652             :  * time.
    1653             :  */
    1654             : static void
    1655        2128 : ReorderBufferTruncateTXN(ReorderBuffer *rb, ReorderBufferTXN *txn, bool txn_prepared)
    1656             : {
    1657             :     dlist_mutable_iter iter;
    1658        2128 :     Size        mem_freed = 0;
    1659             : 
    1660             :     /* cleanup subtransactions & their changes */
    1661        2722 :     dlist_foreach_modify(iter, &txn->subtxns)
    1662             :     {
    1663             :         ReorderBufferTXN *subtxn;
    1664             : 
    1665         594 :         subtxn = dlist_container(ReorderBufferTXN, node, iter.cur);
    1666             : 
    1667             :         /*
    1668             :          * Subtransactions are always associated to the toplevel TXN, even if
    1669             :          * they originally were happening inside another subtxn, so we won't
    1670             :          * ever recurse more than one level deep here.
    1671             :          */
    1672             :         Assert(rbtxn_is_known_subxact(subtxn));
    1673             :         Assert(subtxn->nsubtxns == 0);
    1674             : 
    1675         594 :         ReorderBufferMaybeMarkTXNStreamed(rb, subtxn);
    1676         594 :         ReorderBufferTruncateTXN(rb, subtxn, txn_prepared);
    1677             :     }
    1678             : 
    1679             :     /* cleanup changes in the txn */
    1680      317874 :     dlist_foreach_modify(iter, &txn->changes)
    1681             :     {
    1682             :         ReorderBufferChange *change;
    1683             : 
    1684      315746 :         change = dlist_container(ReorderBufferChange, node, iter.cur);
    1685             : 
    1686             :         /* Check we're not mixing changes from different transactions. */
    1687             :         Assert(change->txn == txn);
    1688             : 
    1689             :         /* remove the change from its containing list */
    1690      315746 :         dlist_delete(&change->node);
    1691             : 
    1692             :         /*
    1693             :          * Instead of updating the memory counter for individual changes, we
    1694             :          * sum up the size of memory to free so we can update the memory
    1695             :          * counter all together below. This saves costs of maintaining the
    1696             :          * max-heap.
    1697             :          */
    1698      315746 :         mem_freed += ReorderBufferChangeSize(change);
    1699             : 
    1700      315746 :         ReorderBufferFreeChange(rb, change, false);
    1701             :     }
    1702             : 
    1703             :     /* Update the memory counter */
    1704        2128 :     ReorderBufferChangeMemoryUpdate(rb, NULL, txn, false, mem_freed);
    1705             : 
    1706        2128 :     if (txn_prepared)
    1707             :     {
    1708             :         /*
    1709             :          * If this is a prepared txn, cleanup the tuplecids we stored for
    1710             :          * decoding catalog snapshot access. They are always stored in the
    1711             :          * toplevel transaction.
    1712             :          */
    1713         364 :         dlist_foreach_modify(iter, &txn->tuplecids)
    1714             :         {
    1715             :             ReorderBufferChange *change;
    1716             : 
    1717         246 :             change = dlist_container(ReorderBufferChange, node, iter.cur);
    1718             : 
    1719             :             /* Check we're not mixing changes from different transactions. */
    1720             :             Assert(change->txn == txn);
    1721             :             Assert(change->action == REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID);
    1722             : 
    1723             :             /* Remove the change from its containing list. */
    1724         246 :             dlist_delete(&change->node);
    1725             : 
    1726         246 :             ReorderBufferFreeChange(rb, change, true);
    1727             :         }
    1728             :     }
    1729             : 
    1730             :     /*
    1731             :      * Destroy the (relfilelocator, ctid) hashtable, so that we don't leak any
    1732             :      * memory. We could also keep the hash table and update it with new ctid
    1733             :      * values, but this seems simpler and good enough for now.
    1734             :      */
    1735        2128 :     if (txn->tuplecid_hash != NULL)
    1736             :     {
    1737         102 :         hash_destroy(txn->tuplecid_hash);
    1738         102 :         txn->tuplecid_hash = NULL;
    1739             :     }
    1740             : 
    1741             :     /* If this txn is serialized then clean the disk space. */
    1742        2128 :     if (rbtxn_is_serialized(txn))
    1743             :     {
    1744          18 :         ReorderBufferRestoreCleanup(rb, txn);
    1745          18 :         txn->txn_flags &= ~RBTXN_IS_SERIALIZED;
    1746             : 
    1747             :         /*
    1748             :          * We set this flag to indicate if the transaction is ever serialized.
    1749             :          * We need this to accurately update the stats as otherwise the same
    1750             :          * transaction can be counted as serialized multiple times.
    1751             :          */
    1752          18 :         txn->txn_flags |= RBTXN_IS_SERIALIZED_CLEAR;
    1753             :     }
    1754             : 
    1755             :     /* also reset the number of entries in the transaction */
    1756        2128 :     txn->nentries_mem = 0;
    1757        2128 :     txn->nentries = 0;
    1758        2128 : }
    1759             : 
    1760             : /*
    1761             :  * Check the transaction status by CLOG lookup and discard all changes if
    1762             :  * the transaction is aborted. The transaction status is cached in
    1763             :  * txn->txn_flags so we can skip future changes and avoid CLOG lookups on the
    1764             :  * next call.
    1765             :  *
    1766             :  * Return true if the transaction is aborted, otherwise return false.
    1767             :  *
    1768             :  * When the 'debug_logical_replication_streaming' is set to "immediate", we
    1769             :  * don't check the transaction status, meaning the caller will always process
    1770             :  * this transaction.
    1771             :  */
    1772             : static bool
    1773        8726 : ReorderBufferCheckAndTruncateAbortedTXN(ReorderBuffer *rb, ReorderBufferTXN *txn)
    1774             : {
    1775             :     /* Quick return for regression tests */
    1776        8726 :     if (unlikely(debug_logical_replication_streaming == DEBUG_LOGICAL_REP_STREAMING_IMMEDIATE))
    1777        1924 :         return false;
    1778             : 
    1779             :     /*
    1780             :      * Quick return if the transaction status is already known.
    1781             :      */
    1782             : 
    1783        6802 :     if (rbtxn_is_committed(txn))
    1784        5862 :         return false;
    1785         940 :     if (rbtxn_is_aborted(txn))
    1786             :     {
    1787             :         /* Already-aborted transactions should not have any changes */
    1788             :         Assert(txn->size == 0);
    1789             : 
    1790           0 :         return true;
    1791             :     }
    1792             : 
    1793             :     /* Otherwise, check the transaction status using CLOG lookup */
    1794             : 
    1795         940 :     if (TransactionIdIsInProgress(txn->xid))
    1796         458 :         return false;
    1797             : 
    1798         482 :     if (TransactionIdDidCommit(txn->xid))
    1799             :     {
    1800             :         /*
    1801             :          * Remember the transaction is committed so that we can skip CLOG
    1802             :          * check next time, avoiding the pressure on CLOG lookup.
    1803             :          */
    1804             :         Assert(!rbtxn_is_aborted(txn));
    1805         464 :         txn->txn_flags |= RBTXN_IS_COMMITTED;
    1806         464 :         return false;
    1807             :     }
    1808             : 
    1809             :     /*
    1810             :      * The transaction aborted. We discard both the changes collected so far
    1811             :      * and the toast reconstruction data. The full cleanup will happen as part
    1812             :      * of decoding ABORT record of this transaction.
    1813             :      */
    1814          18 :     ReorderBufferTruncateTXN(rb, txn, rbtxn_is_prepared(txn));
    1815          18 :     ReorderBufferToastReset(rb, txn);
    1816             : 
    1817             :     /* All changes should be discarded */
    1818             :     Assert(txn->size == 0);
    1819             : 
    1820             :     /*
    1821             :      * Mark the transaction as aborted so we can ignore future changes of this
    1822             :      * transaction.
    1823             :      */
    1824             :     Assert(!rbtxn_is_committed(txn));
    1825          18 :     txn->txn_flags |= RBTXN_IS_ABORTED;
    1826             : 
    1827          18 :     return true;
    1828             : }
    1829             : 
    1830             : /*
    1831             :  * Build a hash with a (relfilelocator, ctid) -> (cmin, cmax) mapping for use by
    1832             :  * HeapTupleSatisfiesHistoricMVCC.
    1833             :  */
    1834             : static void
    1835        3908 : ReorderBufferBuildTupleCidHash(ReorderBuffer *rb, ReorderBufferTXN *txn)
    1836             : {
    1837             :     dlist_iter  iter;
    1838             :     HASHCTL     hash_ctl;
    1839             : 
    1840        3908 :     if (!rbtxn_has_catalog_changes(txn) || dlist_is_empty(&txn->tuplecids))
    1841        2774 :         return;
    1842             : 
    1843        1134 :     hash_ctl.keysize = sizeof(ReorderBufferTupleCidKey);
    1844        1134 :     hash_ctl.entrysize = sizeof(ReorderBufferTupleCidEnt);
    1845        1134 :     hash_ctl.hcxt = rb->context;
    1846             : 
    1847             :     /*
    1848             :      * create the hash with the exact number of to-be-stored tuplecids from
    1849             :      * the start
    1850             :      */
    1851        1134 :     txn->tuplecid_hash =
    1852        1134 :         hash_create("ReorderBufferTupleCid", txn->ntuplecids, &hash_ctl,
    1853             :                     HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
    1854             : 
    1855       24634 :     dlist_foreach(iter, &txn->tuplecids)
    1856             :     {
    1857             :         ReorderBufferTupleCidKey key;
    1858             :         ReorderBufferTupleCidEnt *ent;
    1859             :         bool        found;
    1860             :         ReorderBufferChange *change;
    1861             : 
    1862       23500 :         change = dlist_container(ReorderBufferChange, node, iter.cur);
    1863             : 
    1864             :         Assert(change->action == REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID);
    1865             : 
    1866             :         /* be careful about padding */
    1867       23500 :         memset(&key, 0, sizeof(ReorderBufferTupleCidKey));
    1868             : 
    1869       23500 :         key.rlocator = change->data.tuplecid.locator;
    1870             : 
    1871       23500 :         ItemPointerCopy(&change->data.tuplecid.tid,
    1872             :                         &key.tid);
    1873             : 
    1874             :         ent = (ReorderBufferTupleCidEnt *)
    1875       23500 :             hash_search(txn->tuplecid_hash, &key, HASH_ENTER, &found);
    1876       23500 :         if (!found)
    1877             :         {
    1878       20214 :             ent->cmin = change->data.tuplecid.cmin;
    1879       20214 :             ent->cmax = change->data.tuplecid.cmax;
    1880       20214 :             ent->combocid = change->data.tuplecid.combocid;
    1881             :         }
    1882             :         else
    1883             :         {
    1884             :             /*
    1885             :              * Maybe we already saw this tuple before in this transaction, but
    1886             :              * if so it must have the same cmin.
    1887             :              */
    1888             :             Assert(ent->cmin == change->data.tuplecid.cmin);
    1889             : 
    1890             :             /*
    1891             :              * cmax may be initially invalid, but once set it can only grow,
    1892             :              * and never become invalid again.
    1893             :              */
    1894             :             Assert((ent->cmax == InvalidCommandId) ||
    1895             :                    ((change->data.tuplecid.cmax != InvalidCommandId) &&
    1896             :                     (change->data.tuplecid.cmax > ent->cmax)));
    1897        3286 :             ent->cmax = change->data.tuplecid.cmax;
    1898             :         }
    1899             :     }
    1900             : }
    1901             : 
    1902             : /*
    1903             :  * Copy a provided snapshot so we can modify it privately. This is needed so
    1904             :  * that catalog modifying transactions can look into intermediate catalog
    1905             :  * states.
    1906             :  */
    1907             : static Snapshot
    1908        3514 : ReorderBufferCopySnap(ReorderBuffer *rb, Snapshot orig_snap,
    1909             :                       ReorderBufferTXN *txn, CommandId cid)
    1910             : {
    1911             :     Snapshot    snap;
    1912             :     dlist_iter  iter;
    1913        3514 :     int         i = 0;
    1914             :     Size        size;
    1915             : 
    1916        3514 :     size = sizeof(SnapshotData) +
    1917        3514 :         sizeof(TransactionId) * orig_snap->xcnt +
    1918        3514 :         sizeof(TransactionId) * (txn->nsubtxns + 1);
    1919             : 
    1920        3514 :     snap = MemoryContextAllocZero(rb->context, size);
    1921        3514 :     memcpy(snap, orig_snap, sizeof(SnapshotData));
    1922             : 
    1923        3514 :     snap->copied = true;
    1924        3514 :     snap->active_count = 1;      /* mark as active so nobody frees it */
    1925        3514 :     snap->regd_count = 0;
    1926        3514 :     snap->xip = (TransactionId *) (snap + 1);
    1927             : 
    1928        3514 :     memcpy(snap->xip, orig_snap->xip, sizeof(TransactionId) * snap->xcnt);
    1929             : 
    1930             :     /*
    1931             :      * snap->subxip contains all txids that belong to our transaction which we
    1932             :      * need to check via cmin/cmax. That's why we store the toplevel
    1933             :      * transaction in there as well.
    1934             :      */
    1935        3514 :     snap->subxip = snap->xip + snap->xcnt;
    1936        3514 :     snap->subxip[i++] = txn->xid;
    1937             : 
    1938             :     /*
    1939             :      * txn->nsubtxns isn't decreased when subtransactions abort, so count
    1940             :      * manually. Since it's an upper boundary it is safe to use it for the
    1941             :      * allocation above.
    1942             :      */
    1943        3514 :     snap->subxcnt = 1;
    1944             : 
    1945        4132 :     dlist_foreach(iter, &txn->subtxns)
    1946             :     {
    1947             :         ReorderBufferTXN *sub_txn;
    1948             : 
    1949         618 :         sub_txn = dlist_container(ReorderBufferTXN, node, iter.cur);
    1950         618 :         snap->subxip[i++] = sub_txn->xid;
    1951         618 :         snap->subxcnt++;
    1952             :     }
    1953             : 
    1954             :     /* sort so we can bsearch() later */
    1955        3514 :     qsort(snap->subxip, snap->subxcnt, sizeof(TransactionId), xidComparator);
    1956             : 
    1957             :     /* store the specified current CommandId */
    1958        3514 :     snap->curcid = cid;
    1959             : 
    1960        3514 :     return snap;
    1961             : }
    1962             : 
    1963             : /*
    1964             :  * Free a previously ReorderBufferCopySnap'ed snapshot
    1965             :  */
    1966             : static void
    1967        5668 : ReorderBufferFreeSnap(ReorderBuffer *rb, Snapshot snap)
    1968             : {
    1969        5668 :     if (snap->copied)
    1970        3506 :         pfree(snap);
    1971             :     else
    1972        2162 :         SnapBuildSnapDecRefcount(snap);
    1973        5668 : }
    1974             : 
    1975             : /*
    1976             :  * If the transaction was (partially) streamed, we need to prepare or commit
    1977             :  * it in a 'streamed' way.  That is, we first stream the remaining part of the
    1978             :  * transaction, and then invoke stream_prepare or stream_commit message as per
    1979             :  * the case.
    1980             :  */
    1981             : static void
    1982         132 : ReorderBufferStreamCommit(ReorderBuffer *rb, ReorderBufferTXN *txn)
    1983             : {
    1984             :     /* we should only call this for previously streamed transactions */
    1985             :     Assert(rbtxn_is_streamed(txn));
    1986             : 
    1987         132 :     ReorderBufferStreamTXN(rb, txn);
    1988             : 
    1989         132 :     if (rbtxn_is_prepared(txn))
    1990             :     {
    1991             :         /*
    1992             :          * Note, we send stream prepare even if a concurrent abort is
    1993             :          * detected. See DecodePrepare for more information.
    1994             :          */
    1995             :         Assert(!rbtxn_sent_prepare(txn));
    1996          30 :         rb->stream_prepare(rb, txn, txn->final_lsn);
    1997          30 :         txn->txn_flags |= RBTXN_SENT_PREPARE;
    1998             : 
    1999             :         /*
    2000             :          * This is a PREPARED transaction, part of a two-phase commit. The
    2001             :          * full cleanup will happen as part of the COMMIT PREPAREDs, so now
    2002             :          * just truncate txn by removing changes and tuplecids.
    2003             :          */
    2004          30 :         ReorderBufferTruncateTXN(rb, txn, true);
    2005             :         /* Reset the CheckXidAlive */
    2006          30 :         CheckXidAlive = InvalidTransactionId;
    2007             :     }
    2008             :     else
    2009             :     {
    2010         102 :         rb->stream_commit(rb, txn, txn->final_lsn);
    2011         102 :         ReorderBufferCleanupTXN(rb, txn);
    2012             :     }
    2013         132 : }
    2014             : 
    2015             : /*
    2016             :  * Set xid to detect concurrent aborts.
    2017             :  *
    2018             :  * While streaming an in-progress transaction or decoding a prepared
    2019             :  * transaction there is a possibility that the (sub)transaction might get
    2020             :  * aborted concurrently.  In such case if the (sub)transaction has catalog
    2021             :  * update then we might decode the tuple using wrong catalog version.  For
    2022             :  * example, suppose there is one catalog tuple with (xmin: 500, xmax: 0).  Now,
    2023             :  * the transaction 501 updates the catalog tuple and after that we will have
    2024             :  * two tuples (xmin: 500, xmax: 501) and (xmin: 501, xmax: 0).  Now, if 501 is
    2025             :  * aborted and some other transaction say 502 updates the same catalog tuple
    2026             :  * then the first tuple will be changed to (xmin: 500, xmax: 502).  So, the
    2027             :  * problem is that when we try to decode the tuple inserted/updated in 501
    2028             :  * after the catalog update, we will see the catalog tuple with (xmin: 500,
    2029             :  * xmax: 502) as visible because it will consider that the tuple is deleted by
    2030             :  * xid 502 which is not visible to our snapshot.  And when we will try to
    2031             :  * decode with that catalog tuple, it can lead to a wrong result or a crash.
    2032             :  * So, it is necessary to detect concurrent aborts to allow streaming of
    2033             :  * in-progress transactions or decoding of prepared transactions.
    2034             :  *
    2035             :  * For detecting the concurrent abort we set CheckXidAlive to the current
    2036             :  * (sub)transaction's xid for which this change belongs to.  And, during
    2037             :  * catalog scan we can check the status of the xid and if it is aborted we will
    2038             :  * report a specific error so that we can stop streaming current transaction
    2039             :  * and discard the already streamed changes on such an error.  We might have
    2040             :  * already streamed some of the changes for the aborted (sub)transaction, but
    2041             :  * that is fine because when we decode the abort we will stream abort message
    2042             :  * to truncate the changes in the subscriber. Similarly, for prepared
    2043             :  * transactions, we stop decoding if concurrent abort is detected and then
    2044             :  * rollback the changes when rollback prepared is encountered. See
    2045             :  * DecodePrepare.
    2046             :  */
    2047             : static inline void
    2048      355740 : SetupCheckXidLive(TransactionId xid)
    2049             : {
    2050             :     /*
    2051             :      * If the input transaction id is already set as a CheckXidAlive then
    2052             :      * nothing to do.
    2053             :      */
    2054      355740 :     if (TransactionIdEquals(CheckXidAlive, xid))
    2055      186320 :         return;
    2056             : 
    2057             :     /*
    2058             :      * setup CheckXidAlive if it's not committed yet.  We don't check if the
    2059             :      * xid is aborted.  That will happen during catalog access.
    2060             :      */
    2061      169420 :     if (!TransactionIdDidCommit(xid))
    2062         884 :         CheckXidAlive = xid;
    2063             :     else
    2064      168536 :         CheckXidAlive = InvalidTransactionId;
    2065             : }
    2066             : 
    2067             : /*
    2068             :  * Helper function for ReorderBufferProcessTXN for applying change.
    2069             :  */
    2070             : static inline void
    2071      674298 : ReorderBufferApplyChange(ReorderBuffer *rb, ReorderBufferTXN *txn,
    2072             :                          Relation relation, ReorderBufferChange *change,
    2073             :                          bool streaming)
    2074             : {
    2075      674298 :     if (streaming)
    2076      352012 :         rb->stream_change(rb, txn, relation, change);
    2077             :     else
    2078      322286 :         rb->apply_change(rb, txn, relation, change);
    2079      674296 : }
    2080             : 
    2081             : /*
    2082             :  * Helper function for ReorderBufferProcessTXN for applying the truncate.
    2083             :  */
    2084             : static inline void
    2085          44 : ReorderBufferApplyTruncate(ReorderBuffer *rb, ReorderBufferTXN *txn,
    2086             :                            int nrelations, Relation *relations,
    2087             :                            ReorderBufferChange *change, bool streaming)
    2088             : {
    2089          44 :     if (streaming)
    2090           0 :         rb->stream_truncate(rb, txn, nrelations, relations, change);
    2091             :     else
    2092          44 :         rb->apply_truncate(rb, txn, nrelations, relations, change);
    2093          44 : }
    2094             : 
    2095             : /*
    2096             :  * Helper function for ReorderBufferProcessTXN for applying the message.
    2097             :  */
    2098             : static inline void
    2099          22 : ReorderBufferApplyMessage(ReorderBuffer *rb, ReorderBufferTXN *txn,
    2100             :                           ReorderBufferChange *change, bool streaming)
    2101             : {
    2102          22 :     if (streaming)
    2103           6 :         rb->stream_message(rb, txn, change->lsn, true,
    2104           6 :                            change->data.msg.prefix,
    2105             :                            change->data.msg.message_size,
    2106           6 :                            change->data.msg.message);
    2107             :     else
    2108          16 :         rb->message(rb, txn, change->lsn, true,
    2109          16 :                     change->data.msg.prefix,
    2110             :                     change->data.msg.message_size,
    2111          16 :                     change->data.msg.message);
    2112          22 : }
    2113             : 
    2114             : /*
    2115             :  * Function to store the command id and snapshot at the end of the current
    2116             :  * stream so that we can reuse the same while sending the next stream.
    2117             :  */
    2118             : static inline void
    2119        1432 : ReorderBufferSaveTXNSnapshot(ReorderBuffer *rb, ReorderBufferTXN *txn,
    2120             :                              Snapshot snapshot_now, CommandId command_id)
    2121             : {
    2122        1432 :     txn->command_id = command_id;
    2123             : 
    2124             :     /* Avoid copying if it's already copied. */
    2125        1432 :     if (snapshot_now->copied)
    2126        1432 :         txn->snapshot_now = snapshot_now;
    2127             :     else
    2128           0 :         txn->snapshot_now = ReorderBufferCopySnap(rb, snapshot_now,
    2129             :                                                   txn, command_id);
    2130        1432 : }
    2131             : 
    2132             : /*
    2133             :  * Mark the given transaction as streamed if it's a top-level transaction
    2134             :  * or has changes.
    2135             :  */
    2136             : static void
    2137        2026 : ReorderBufferMaybeMarkTXNStreamed(ReorderBuffer *rb, ReorderBufferTXN *txn)
    2138             : {
    2139             :     /*
    2140             :      * The top-level transaction, is marked as streamed always, even if it
    2141             :      * does not contain any changes (that is, when all the changes are in
    2142             :      * subtransactions).
    2143             :      *
    2144             :      * For subtransactions, we only mark them as streamed when there are
    2145             :      * changes in them.
    2146             :      *
    2147             :      * We do it this way because of aborts - we don't want to send aborts for
    2148             :      * XIDs the downstream is not aware of. And of course, it always knows
    2149             :      * about the top-level xact (we send the XID in all messages), but we
    2150             :      * never stream XIDs of empty subxacts.
    2151             :      */
    2152        2026 :     if (rbtxn_is_toptxn(txn) || (txn->nentries_mem != 0))
    2153        1702 :         txn->txn_flags |= RBTXN_IS_STREAMED;
    2154        2026 : }
    2155             : 
    2156             : /*
    2157             :  * Helper function for ReorderBufferProcessTXN to handle the concurrent
    2158             :  * abort of the streaming transaction.  This resets the TXN such that it
    2159             :  * can be used to stream the remaining data of transaction being processed.
    2160             :  * This can happen when the subtransaction is aborted and we still want to
    2161             :  * continue processing the main or other subtransactions data.
    2162             :  */
    2163             : static void
    2164          16 : ReorderBufferResetTXN(ReorderBuffer *rb, ReorderBufferTXN *txn,
    2165             :                       Snapshot snapshot_now,
    2166             :                       CommandId command_id,
    2167             :                       XLogRecPtr last_lsn,
    2168             :                       ReorderBufferChange *specinsert)
    2169             : {
    2170             :     /* Discard the changes that we just streamed */
    2171          16 :     ReorderBufferTruncateTXN(rb, txn, rbtxn_is_prepared(txn));
    2172             : 
    2173             :     /* Free all resources allocated for toast reconstruction */
    2174          16 :     ReorderBufferToastReset(rb, txn);
    2175             : 
    2176             :     /* Return the spec insert change if it is not NULL */
    2177          16 :     if (specinsert != NULL)
    2178             :     {
    2179           0 :         ReorderBufferFreeChange(rb, specinsert, true);
    2180           0 :         specinsert = NULL;
    2181             :     }
    2182             : 
    2183             :     /*
    2184             :      * For the streaming case, stop the stream and remember the command ID and
    2185             :      * snapshot for the streaming run.
    2186             :      */
    2187          16 :     if (rbtxn_is_streamed(txn))
    2188             :     {
    2189          16 :         rb->stream_stop(rb, txn, last_lsn);
    2190          16 :         ReorderBufferSaveTXNSnapshot(rb, txn, snapshot_now, command_id);
    2191             :     }
    2192             : 
    2193             :     /* All changes must be deallocated */
    2194             :     Assert(txn->size == 0);
    2195          16 : }
    2196             : 
    2197             : /*
    2198             :  * Helper function for ReorderBufferReplay and ReorderBufferStreamTXN.
    2199             :  *
    2200             :  * Send data of a transaction (and its subtransactions) to the
    2201             :  * output plugin. We iterate over the top and subtransactions (using a k-way
    2202             :  * merge) and replay the changes in lsn order.
    2203             :  *
    2204             :  * If streaming is true then data will be sent using stream API.
    2205             :  *
    2206             :  * Note: "volatile" markers on some parameters are to avoid trouble with
    2207             :  * PG_TRY inside the function.
    2208             :  */
    2209             : static void
    2210        3908 : ReorderBufferProcessTXN(ReorderBuffer *rb, ReorderBufferTXN *txn,
    2211             :                         XLogRecPtr commit_lsn,
    2212             :                         volatile Snapshot snapshot_now,
    2213             :                         volatile CommandId command_id,
    2214             :                         bool streaming)
    2215             : {
    2216             :     bool        using_subtxn;
    2217        3908 :     MemoryContext ccxt = CurrentMemoryContext;
    2218        3908 :     ReorderBufferIterTXNState *volatile iterstate = NULL;
    2219        3908 :     volatile XLogRecPtr prev_lsn = InvalidXLogRecPtr;
    2220        3908 :     ReorderBufferChange *volatile specinsert = NULL;
    2221        3908 :     volatile bool stream_started = false;
    2222        3908 :     ReorderBufferTXN *volatile curtxn = NULL;
    2223             : 
    2224             :     /* build data to be able to lookup the CommandIds of catalog tuples */
    2225        3908 :     ReorderBufferBuildTupleCidHash(rb, txn);
    2226             : 
    2227             :     /* setup the initial snapshot */
    2228        3908 :     SetupHistoricSnapshot(snapshot_now, txn->tuplecid_hash);
    2229             : 
    2230             :     /*
    2231             :      * Decoding needs access to syscaches et al., which in turn use
    2232             :      * heavyweight locks and such. Thus we need to have enough state around to
    2233             :      * keep track of those.  The easiest way is to simply use a transaction
    2234             :      * internally.  That also allows us to easily enforce that nothing writes
    2235             :      * to the database by checking for xid assignments.
    2236             :      *
    2237             :      * When we're called via the SQL SRF there's already a transaction
    2238             :      * started, so start an explicit subtransaction there.
    2239             :      */
    2240        3908 :     using_subtxn = IsTransactionOrTransactionBlock();
    2241             : 
    2242        3908 :     PG_TRY();
    2243             :     {
    2244             :         ReorderBufferChange *change;
    2245        3908 :         int         changes_count = 0;  /* used to accumulate the number of
    2246             :                                          * changes */
    2247             : 
    2248        3908 :         if (using_subtxn)
    2249         984 :             BeginInternalSubTransaction(streaming ? "stream" : "replay");
    2250             :         else
    2251        2924 :             StartTransactionCommand();
    2252             : 
    2253             :         /*
    2254             :          * We only need to send begin/begin-prepare for non-streamed
    2255             :          * transactions.
    2256             :          */
    2257        3908 :         if (!streaming)
    2258             :         {
    2259        2476 :             if (rbtxn_is_prepared(txn))
    2260          54 :                 rb->begin_prepare(rb, txn);
    2261             :             else
    2262        2422 :                 rb->begin(rb, txn);
    2263             :         }
    2264             : 
    2265        3908 :         ReorderBufferIterTXNInit(rb, txn, &iterstate);
    2266      726100 :         while ((change = ReorderBufferIterTXNNext(rb, iterstate)) != NULL)
    2267             :         {
    2268      718302 :             Relation    relation = NULL;
    2269             :             Oid         reloid;
    2270             : 
    2271      718302 :             CHECK_FOR_INTERRUPTS();
    2272             : 
    2273             :             /*
    2274             :              * We can't call start stream callback before processing first
    2275             :              * change.
    2276             :              */
    2277      718302 :             if (prev_lsn == InvalidXLogRecPtr)
    2278             :             {
    2279        3830 :                 if (streaming)
    2280             :                 {
    2281        1356 :                     txn->origin_id = change->origin_id;
    2282        1356 :                     rb->stream_start(rb, txn, change->lsn);
    2283        1356 :                     stream_started = true;
    2284             :                 }
    2285             :             }
    2286             : 
    2287             :             /*
    2288             :              * Enforce correct ordering of changes, merged from multiple
    2289             :              * subtransactions. The changes may have the same LSN due to
    2290             :              * MULTI_INSERT xlog records.
    2291             :              */
    2292             :             Assert(prev_lsn == InvalidXLogRecPtr || prev_lsn <= change->lsn);
    2293             : 
    2294      718302 :             prev_lsn = change->lsn;
    2295             : 
    2296             :             /*
    2297             :              * Set the current xid to detect concurrent aborts. This is
    2298             :              * required for the cases when we decode the changes before the
    2299             :              * COMMIT record is processed.
    2300             :              */
    2301      718302 :             if (streaming || rbtxn_is_prepared(change->txn))
    2302             :             {
    2303      355740 :                 curtxn = change->txn;
    2304      355740 :                 SetupCheckXidLive(curtxn->xid);
    2305             :             }
    2306             : 
    2307      718302 :             switch (change->action)
    2308             :             {
    2309        3564 :                 case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_CONFIRM:
    2310             : 
    2311             :                     /*
    2312             :                      * Confirmation for speculative insertion arrived. Simply
    2313             :                      * use as a normal record. It'll be cleaned up at the end
    2314             :                      * of INSERT processing.
    2315             :                      */
    2316        3564 :                     if (specinsert == NULL)
    2317           0 :                         elog(ERROR, "invalid ordering of speculative insertion changes");
    2318             :                     Assert(specinsert->data.tp.oldtuple == NULL);
    2319        3564 :                     change = specinsert;
    2320        3564 :                     change->action = REORDER_BUFFER_CHANGE_INSERT;
    2321             : 
    2322             :                     /* intentionally fall through */
    2323      687396 :                 case REORDER_BUFFER_CHANGE_INSERT:
    2324             :                 case REORDER_BUFFER_CHANGE_UPDATE:
    2325             :                 case REORDER_BUFFER_CHANGE_DELETE:
    2326             :                     Assert(snapshot_now);
    2327             : 
    2328      687396 :                     reloid = RelidByRelfilenumber(change->data.tp.rlocator.spcOid,
    2329             :                                                   change->data.tp.rlocator.relNumber);
    2330             : 
    2331             :                     /*
    2332             :                      * Mapped catalog tuple without data, emitted while
    2333             :                      * catalog table was in the process of being rewritten. We
    2334             :                      * can fail to look up the relfilenumber, because the
    2335             :                      * relmapper has no "historic" view, in contrast to the
    2336             :                      * normal catalog during decoding. Thus repeated rewrites
    2337             :                      * can cause a lookup failure. That's OK because we do not
    2338             :                      * decode catalog changes anyway. Normally such tuples
    2339             :                      * would be skipped over below, but we can't identify
    2340             :                      * whether the table should be logically logged without
    2341             :                      * mapping the relfilenumber to the oid.
    2342             :                      */
    2343      687380 :                     if (reloid == InvalidOid &&
    2344         166 :                         change->data.tp.newtuple == NULL &&
    2345         166 :                         change->data.tp.oldtuple == NULL)
    2346         166 :                         goto change_done;
    2347      687214 :                     else if (reloid == InvalidOid)
    2348           0 :                         elog(ERROR, "could not map filenumber \"%s\" to relation OID",
    2349             :                              relpathperm(change->data.tp.rlocator,
    2350             :                                          MAIN_FORKNUM).str);
    2351             : 
    2352      687214 :                     relation = RelationIdGetRelation(reloid);
    2353             : 
    2354      687214 :                     if (!RelationIsValid(relation))
    2355           0 :                         elog(ERROR, "could not open relation with OID %u (for filenumber \"%s\")",
    2356             :                              reloid,
    2357             :                              relpathperm(change->data.tp.rlocator,
    2358             :                                          MAIN_FORKNUM).str);
    2359             : 
    2360      687214 :                     if (!RelationIsLogicallyLogged(relation))
    2361        8742 :                         goto change_done;
    2362             : 
    2363             :                     /*
    2364             :                      * Ignore temporary heaps created during DDL unless the
    2365             :                      * plugin has asked for them.
    2366             :                      */
    2367      678472 :                     if (relation->rd_rel->relrewrite && !rb->output_rewrites)
    2368          52 :                         goto change_done;
    2369             : 
    2370             :                     /*
    2371             :                      * For now ignore sequence changes entirely. Most of the
    2372             :                      * time they don't log changes using records we
    2373             :                      * understand, so it doesn't make sense to handle the few
    2374             :                      * cases we do.
    2375             :                      */
    2376      678420 :                     if (relation->rd_rel->relkind == RELKIND_SEQUENCE)
    2377           0 :                         goto change_done;
    2378             : 
    2379             :                     /* user-triggered change */
    2380      678420 :                     if (!IsToastRelation(relation))
    2381             :                     {
    2382      674298 :                         ReorderBufferToastReplace(rb, txn, relation, change);
    2383      674298 :                         ReorderBufferApplyChange(rb, txn, relation, change,
    2384             :                                                  streaming);
    2385             : 
    2386             :                         /*
    2387             :                          * Only clear reassembled toast chunks if we're sure
    2388             :                          * they're not required anymore. The creator of the
    2389             :                          * tuple tells us.
    2390             :                          */
    2391      674296 :                         if (change->data.tp.clear_toast_afterwards)
    2392      673836 :                             ReorderBufferToastReset(rb, txn);
    2393             :                     }
    2394             :                     /* we're not interested in toast deletions */
    2395        4122 :                     else if (change->action == REORDER_BUFFER_CHANGE_INSERT)
    2396             :                     {
    2397             :                         /*
    2398             :                          * Need to reassemble the full toasted Datum in
    2399             :                          * memory, to ensure the chunks don't get reused till
    2400             :                          * we're done remove it from the list of this
    2401             :                          * transaction's changes. Otherwise it will get
    2402             :                          * freed/reused while restoring spooled data from
    2403             :                          * disk.
    2404             :                          */
    2405             :                         Assert(change->data.tp.newtuple != NULL);
    2406             : 
    2407        3660 :                         dlist_delete(&change->node);
    2408        3660 :                         ReorderBufferToastAppendChunk(rb, txn, relation,
    2409             :                                                       change);
    2410             :                     }
    2411             : 
    2412         462 :             change_done:
    2413             : 
    2414             :                     /*
    2415             :                      * If speculative insertion was confirmed, the record
    2416             :                      * isn't needed anymore.
    2417             :                      */
    2418      687378 :                     if (specinsert != NULL)
    2419             :                     {
    2420        3564 :                         ReorderBufferFreeChange(rb, specinsert, true);
    2421        3564 :                         specinsert = NULL;
    2422             :                     }
    2423             : 
    2424      687378 :                     if (RelationIsValid(relation))
    2425             :                     {
    2426      687212 :                         RelationClose(relation);
    2427      687212 :                         relation = NULL;
    2428             :                     }
    2429      687378 :                     break;
    2430             : 
    2431        3564 :                 case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_INSERT:
    2432             : 
    2433             :                     /*
    2434             :                      * Speculative insertions are dealt with by delaying the
    2435             :                      * processing of the insert until the confirmation record
    2436             :                      * arrives. For that we simply unlink the record from the
    2437             :                      * chain, so it does not get freed/reused while restoring
    2438             :                      * spooled data from disk.
    2439             :                      *
    2440             :                      * This is safe in the face of concurrent catalog changes
    2441             :                      * because the relevant relation can't be changed between
    2442             :                      * speculative insertion and confirmation due to
    2443             :                      * CheckTableNotInUse() and locking.
    2444             :                      */
    2445             : 
    2446             :                     /* clear out a pending (and thus failed) speculation */
    2447        3564 :                     if (specinsert != NULL)
    2448             :                     {
    2449           0 :                         ReorderBufferFreeChange(rb, specinsert, true);
    2450           0 :                         specinsert = NULL;
    2451             :                     }
    2452             : 
    2453             :                     /* and memorize the pending insertion */
    2454        3564 :                     dlist_delete(&change->node);
    2455        3564 :                     specinsert = change;
    2456        3564 :                     break;
    2457             : 
    2458           0 :                 case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_ABORT:
    2459             : 
    2460             :                     /*
    2461             :                      * Abort for speculative insertion arrived. So cleanup the
    2462             :                      * specinsert tuple and toast hash.
    2463             :                      *
    2464             :                      * Note that we get the spec abort change for each toast
    2465             :                      * entry but we need to perform the cleanup only the first
    2466             :                      * time we get it for the main table.
    2467             :                      */
    2468           0 :                     if (specinsert != NULL)
    2469             :                     {
    2470             :                         /*
    2471             :                          * We must clean the toast hash before processing a
    2472             :                          * completely new tuple to avoid confusion about the
    2473             :                          * previous tuple's toast chunks.
    2474             :                          */
    2475             :                         Assert(change->data.tp.clear_toast_afterwards);
    2476           0 :                         ReorderBufferToastReset(rb, txn);
    2477             : 
    2478             :                         /* We don't need this record anymore. */
    2479           0 :                         ReorderBufferFreeChange(rb, specinsert, true);
    2480           0 :                         specinsert = NULL;
    2481             :                     }
    2482           0 :                     break;
    2483             : 
    2484          44 :                 case REORDER_BUFFER_CHANGE_TRUNCATE:
    2485             :                     {
    2486             :                         int         i;
    2487          44 :                         int         nrelids = change->data.truncate.nrelids;
    2488          44 :                         int         nrelations = 0;
    2489             :                         Relation   *relations;
    2490             : 
    2491          44 :                         relations = palloc0(nrelids * sizeof(Relation));
    2492         128 :                         for (i = 0; i < nrelids; i++)
    2493             :                         {
    2494          84 :                             Oid         relid = change->data.truncate.relids[i];
    2495             :                             Relation    rel;
    2496             : 
    2497          84 :                             rel = RelationIdGetRelation(relid);
    2498             : 
    2499          84 :                             if (!RelationIsValid(rel))
    2500           0 :                                 elog(ERROR, "could not open relation with OID %u", relid);
    2501             : 
    2502          84 :                             if (!RelationIsLogicallyLogged(rel))
    2503           0 :                                 continue;
    2504             : 
    2505          84 :                             relations[nrelations++] = rel;
    2506             :                         }
    2507             : 
    2508             :                         /* Apply the truncate. */
    2509          44 :                         ReorderBufferApplyTruncate(rb, txn, nrelations,
    2510             :                                                    relations, change,
    2511             :                                                    streaming);
    2512             : 
    2513         128 :                         for (i = 0; i < nrelations; i++)
    2514          84 :                             RelationClose(relations[i]);
    2515             : 
    2516          44 :                         break;
    2517             :                     }
    2518             : 
    2519          22 :                 case REORDER_BUFFER_CHANGE_MESSAGE:
    2520          22 :                     ReorderBufferApplyMessage(rb, txn, change, streaming);
    2521          22 :                     break;
    2522             : 
    2523        4490 :                 case REORDER_BUFFER_CHANGE_INVALIDATION:
    2524             :                     /* Execute the invalidation messages locally */
    2525        4490 :                     ReorderBufferExecuteInvalidations(change->data.inval.ninvalidations,
    2526             :                                                       change->data.inval.invalidations);
    2527        4490 :                     break;
    2528             : 
    2529        1096 :                 case REORDER_BUFFER_CHANGE_INTERNAL_SNAPSHOT:
    2530             :                     /* get rid of the old */
    2531        1096 :                     TeardownHistoricSnapshot(false);
    2532             : 
    2533        1096 :                     if (snapshot_now->copied)
    2534             :                     {
    2535        1046 :                         ReorderBufferFreeSnap(rb, snapshot_now);
    2536        1046 :                         snapshot_now =
    2537        1046 :                             ReorderBufferCopySnap(rb, change->data.snapshot,
    2538             :                                                   txn, command_id);
    2539             :                     }
    2540             : 
    2541             :                     /*
    2542             :                      * Restored from disk, need to be careful not to double
    2543             :                      * free. We could introduce refcounting for that, but for
    2544             :                      * now this seems infrequent enough not to care.
    2545             :                      */
    2546          50 :                     else if (change->data.snapshot->copied)
    2547             :                     {
    2548           0 :                         snapshot_now =
    2549           0 :                             ReorderBufferCopySnap(rb, change->data.snapshot,
    2550             :                                                   txn, command_id);
    2551             :                     }
    2552             :                     else
    2553             :                     {
    2554          50 :                         snapshot_now = change->data.snapshot;
    2555             :                     }
    2556             : 
    2557             :                     /* and continue with the new one */
    2558        1096 :                     SetupHistoricSnapshot(snapshot_now, txn->tuplecid_hash);
    2559        1096 :                     break;
    2560             : 
    2561       21690 :                 case REORDER_BUFFER_CHANGE_INTERNAL_COMMAND_ID:
    2562             :                     Assert(change->data.command_id != InvalidCommandId);
    2563             : 
    2564       21690 :                     if (command_id < change->data.command_id)
    2565             :                     {
    2566        3858 :                         command_id = change->data.command_id;
    2567             : 
    2568        3858 :                         if (!snapshot_now->copied)
    2569             :                         {
    2570             :                             /* we don't use the global one anymore */
    2571        1036 :                             snapshot_now = ReorderBufferCopySnap(rb, snapshot_now,
    2572             :                                                                  txn, command_id);
    2573             :                         }
    2574             : 
    2575        3858 :                         snapshot_now->curcid = command_id;
    2576             : 
    2577        3858 :                         TeardownHistoricSnapshot(false);
    2578        3858 :                         SetupHistoricSnapshot(snapshot_now, txn->tuplecid_hash);
    2579             :                     }
    2580             : 
    2581       21690 :                     break;
    2582             : 
    2583           0 :                 case REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID:
    2584           0 :                     elog(ERROR, "tuplecid value in changequeue");
    2585             :                     break;
    2586             :             }
    2587             : 
    2588             :             /*
    2589             :              * It is possible that the data is not sent to downstream for a
    2590             :              * long time either because the output plugin filtered it or there
    2591             :              * is a DDL that generates a lot of data that is not processed by
    2592             :              * the plugin. So, in such cases, the downstream can timeout. To
    2593             :              * avoid that we try to send a keepalive message if required.
    2594             :              * Trying to send a keepalive message after every change has some
    2595             :              * overhead, but testing showed there is no noticeable overhead if
    2596             :              * we do it after every ~100 changes.
    2597             :              */
    2598             : #define CHANGES_THRESHOLD 100
    2599             : 
    2600      718284 :             if (++changes_count >= CHANGES_THRESHOLD)
    2601             :             {
    2602        6274 :                 rb->update_progress_txn(rb, txn, change->lsn);
    2603        6274 :                 changes_count = 0;
    2604             :             }
    2605             :         }
    2606             : 
    2607             :         /* speculative insertion record must be freed by now */
    2608             :         Assert(!specinsert);
    2609             : 
    2610             :         /* clean up the iterator */
    2611        3890 :         ReorderBufferIterTXNFinish(rb, iterstate);
    2612        3890 :         iterstate = NULL;
    2613             : 
    2614             :         /*
    2615             :          * Update total transaction count and total bytes processed by the
    2616             :          * transaction and its subtransactions. Ensure to not count the
    2617             :          * streamed transaction multiple times.
    2618             :          *
    2619             :          * Note that the statistics computation has to be done after
    2620             :          * ReorderBufferIterTXNFinish as it releases the serialized change
    2621             :          * which we have already accounted in ReorderBufferIterTXNNext.
    2622             :          */
    2623        3890 :         if (!rbtxn_is_streamed(txn))
    2624        2610 :             rb->totalTxns++;
    2625             : 
    2626        3890 :         rb->totalBytes += txn->total_size;
    2627             : 
    2628             :         /*
    2629             :          * Done with current changes, send the last message for this set of
    2630             :          * changes depending upon streaming mode.
    2631             :          */
    2632        3890 :         if (streaming)
    2633             :         {
    2634        1416 :             if (stream_started)
    2635             :             {
    2636        1340 :                 rb->stream_stop(rb, txn, prev_lsn);
    2637        1340 :                 stream_started = false;
    2638             :             }
    2639             :         }
    2640             :         else
    2641             :         {
    2642             :             /*
    2643             :              * Call either PREPARE (for two-phase transactions) or COMMIT (for
    2644             :              * regular ones).
    2645             :              */
    2646        2474 :             if (rbtxn_is_prepared(txn))
    2647             :             {
    2648             :                 Assert(!rbtxn_sent_prepare(txn));
    2649          54 :                 rb->prepare(rb, txn, commit_lsn);
    2650          54 :                 txn->txn_flags |= RBTXN_SENT_PREPARE;
    2651             :             }
    2652             :             else
    2653        2420 :                 rb->commit(rb, txn, commit_lsn);
    2654             :         }
    2655             : 
    2656             :         /* this is just a sanity check against bad output plugin behaviour */
    2657        3874 :         if (GetCurrentTransactionIdIfAny() != InvalidTransactionId)
    2658           0 :             elog(ERROR, "output plugin used XID %u",
    2659             :                  GetCurrentTransactionId());
    2660             : 
    2661             :         /*
    2662             :          * Remember the command ID and snapshot for the next set of changes in
    2663             :          * streaming mode.
    2664             :          */
    2665        3874 :         if (streaming)
    2666        1416 :             ReorderBufferSaveTXNSnapshot(rb, txn, snapshot_now, command_id);
    2667        2458 :         else if (snapshot_now->copied)
    2668        1036 :             ReorderBufferFreeSnap(rb, snapshot_now);
    2669             : 
    2670             :         /* cleanup */
    2671        3874 :         TeardownHistoricSnapshot(false);
    2672             : 
    2673             :         /*
    2674             :          * Aborting the current (sub-)transaction as a whole has the right
    2675             :          * semantics. We want all locks acquired in here to be released, not
    2676             :          * reassigned to the parent and we do not want any database access
    2677             :          * have persistent effects.
    2678             :          */
    2679        3874 :         AbortCurrentTransaction();
    2680             : 
    2681             :         /* make sure there's no cache pollution */
    2682        3874 :         if (rbtxn_distr_inval_overflowed(txn))
    2683             :         {
    2684             :             Assert(txn->ninvalidations_distributed == 0);
    2685           0 :             InvalidateSystemCaches();
    2686             :         }
    2687             :         else
    2688             :         {
    2689        3874 :             ReorderBufferExecuteInvalidations(txn->ninvalidations, txn->invalidations);
    2690        3874 :             ReorderBufferExecuteInvalidations(txn->ninvalidations_distributed,
    2691             :                                               txn->invalidations_distributed);
    2692             :         }
    2693             : 
    2694        3874 :         if (using_subtxn)
    2695         976 :             RollbackAndReleaseCurrentSubTransaction();
    2696             : 
    2697             :         /*
    2698             :          * We are here due to one of the four reasons: 1. Decoding an
    2699             :          * in-progress txn. 2. Decoding a prepared txn. 3. Decoding of a
    2700             :          * prepared txn that was (partially) streamed. 4. Decoding a committed
    2701             :          * txn.
    2702             :          *
    2703             :          * For 1, we allow truncation of txn data by removing the changes
    2704             :          * already streamed but still keeping other things like invalidations,
    2705             :          * snapshot, and tuplecids. For 2 and 3, we indicate
    2706             :          * ReorderBufferTruncateTXN to do more elaborate truncation of txn
    2707             :          * data as the entire transaction has been decoded except for commit.
    2708             :          * For 4, as the entire txn has been decoded, we can fully clean up
    2709             :          * the TXN reorder buffer.
    2710             :          */
    2711        3874 :         if (streaming || rbtxn_is_prepared(txn))
    2712             :         {
    2713        1470 :             if (streaming)
    2714        1416 :                 ReorderBufferMaybeMarkTXNStreamed(rb, txn);
    2715             : 
    2716        1470 :             ReorderBufferTruncateTXN(rb, txn, rbtxn_is_prepared(txn));
    2717             :             /* Reset the CheckXidAlive */
    2718        1470 :             CheckXidAlive = InvalidTransactionId;
    2719             :         }
    2720             :         else
    2721        2404 :             ReorderBufferCleanupTXN(rb, txn);
    2722             :     }
    2723          18 :     PG_CATCH();
    2724             :     {
    2725          18 :         MemoryContext ecxt = MemoryContextSwitchTo(ccxt);
    2726          18 :         ErrorData  *errdata = CopyErrorData();
    2727             : 
    2728             :         /* TODO: Encapsulate cleanup from the PG_TRY and PG_CATCH blocks */
    2729          18 :         if (iterstate)
    2730          18 :             ReorderBufferIterTXNFinish(rb, iterstate);
    2731             : 
    2732          18 :         TeardownHistoricSnapshot(true);
    2733             : 
    2734             :         /*
    2735             :          * Force cache invalidation to happen outside of a valid transaction
    2736             :          * to prevent catalog access as we just caught an error.
    2737             :          */
    2738          18 :         AbortCurrentTransaction();
    2739             : 
    2740             :         /* make sure there's no cache pollution */
    2741          18 :         if (rbtxn_distr_inval_overflowed(txn))
    2742             :         {
    2743             :             Assert(txn->ninvalidations_distributed == 0);
    2744           0 :             InvalidateSystemCaches();
    2745             :         }
    2746             :         else
    2747             :         {
    2748          18 :             ReorderBufferExecuteInvalidations(txn->ninvalidations, txn->invalidations);
    2749          18 :             ReorderBufferExecuteInvalidations(txn->ninvalidations_distributed,
    2750             :                                               txn->invalidations_distributed);
    2751             :         }
    2752             : 
    2753          18 :         if (using_subtxn)
    2754           8 :             RollbackAndReleaseCurrentSubTransaction();
    2755             : 
    2756             :         /*
    2757             :          * The error code ERRCODE_TRANSACTION_ROLLBACK indicates a concurrent
    2758             :          * abort of the (sub)transaction we are streaming or preparing. We
    2759             :          * need to do the cleanup and return gracefully on this error, see
    2760             :          * SetupCheckXidLive.
    2761             :          *
    2762             :          * This error code can be thrown by one of the callbacks we call
    2763             :          * during decoding so we need to ensure that we return gracefully only
    2764             :          * when we are sending the data in streaming mode and the streaming is
    2765             :          * not finished yet or when we are sending the data out on a PREPARE
    2766             :          * during a two-phase commit.
    2767             :          */
    2768          18 :         if (errdata->sqlerrcode == ERRCODE_TRANSACTION_ROLLBACK &&
    2769          16 :             (stream_started || rbtxn_is_prepared(txn)))
    2770             :         {
    2771             :             /* curtxn must be set for streaming or prepared transactions */
    2772             :             Assert(curtxn);
    2773             : 
    2774             :             /* Cleanup the temporary error state. */
    2775          16 :             FlushErrorState();
    2776          16 :             FreeErrorData(errdata);
    2777          16 :             errdata = NULL;
    2778             : 
    2779             :             /* Remember the transaction is aborted. */
    2780             :             Assert(!rbtxn_is_committed(curtxn));
    2781          16 :             curtxn->txn_flags |= RBTXN_IS_ABORTED;
    2782             : 
    2783             :             /* Mark the transaction is streamed if appropriate */
    2784          16 :             if (stream_started)
    2785          16 :                 ReorderBufferMaybeMarkTXNStreamed(rb, txn);
    2786             : 
    2787             :             /* Reset the TXN so that it is allowed to stream remaining data. */
    2788          16 :             ReorderBufferResetTXN(rb, txn, snapshot_now,
    2789             :                                   command_id, prev_lsn,
    2790             :                                   specinsert);
    2791             :         }
    2792             :         else
    2793             :         {
    2794           2 :             ReorderBufferCleanupTXN(rb, txn);
    2795           2 :             MemoryContextSwitchTo(ecxt);
    2796           2 :             PG_RE_THROW();
    2797             :         }
    2798             :     }
    2799        3890 :     PG_END_TRY();
    2800        3890 : }
    2801             : 
    2802             : /*
    2803             :  * Perform the replay of a transaction and its non-aborted subtransactions.
    2804             :  *
    2805             :  * Subtransactions previously have to be processed by
    2806             :  * ReorderBufferCommitChild(), even if previously assigned to the toplevel
    2807             :  * transaction with ReorderBufferAssignChild.
    2808             :  *
    2809             :  * This interface is called once a prepare or toplevel commit is read for both
    2810             :  * streamed as well as non-streamed transactions.
    2811             :  */
    2812             : static void
    2813        2614 : ReorderBufferReplay(ReorderBufferTXN *txn,
    2814             :                     ReorderBuffer *rb, TransactionId xid,
    2815             :                     XLogRecPtr commit_lsn, XLogRecPtr end_lsn,
    2816             :                     TimestampTz commit_time,
    2817             :                     RepOriginId origin_id, XLogRecPtr origin_lsn)
    2818             : {
    2819             :     Snapshot    snapshot_now;
    2820        2614 :     CommandId   command_id = FirstCommandId;
    2821             : 
    2822        2614 :     txn->final_lsn = commit_lsn;
    2823        2614 :     txn->end_lsn = end_lsn;
    2824        2614 :     txn->xact_time.commit_time = commit_time;
    2825        2614 :     txn->origin_id = origin_id;
    2826        2614 :     txn->origin_lsn = origin_lsn;
    2827             : 
    2828             :     /*
    2829             :      * If the transaction was (partially) streamed, we need to commit it in a
    2830             :      * 'streamed' way. That is, we first stream the remaining part of the
    2831             :      * transaction, and then invoke stream_commit message.
    2832             :      *
    2833             :      * Called after everything (origin ID, LSN, ...) is stored in the
    2834             :      * transaction to avoid passing that information directly.
    2835             :      */
    2836        2614 :     if (rbtxn_is_streamed(txn))
    2837             :     {
    2838         132 :         ReorderBufferStreamCommit(rb, txn);
    2839         132 :         return;
    2840             :     }
    2841             : 
    2842             :     /*
    2843             :      * If this transaction has no snapshot, it didn't make any changes to the
    2844             :      * database, so there's nothing to decode.  Note that
    2845             :      * ReorderBufferCommitChild will have transferred any snapshots from
    2846             :      * subtransactions if there were any.
    2847             :      */
    2848        2482 :     if (txn->base_snapshot == NULL)
    2849             :     {
    2850             :         Assert(txn->ninvalidations == 0);
    2851             : 
    2852             :         /*
    2853             :          * Removing this txn before a commit might result in the computation
    2854             :          * of an incorrect restart_lsn. See SnapBuildProcessRunningXacts.
    2855             :          */
    2856           6 :         if (!rbtxn_is_prepared(txn))
    2857           6 :             ReorderBufferCleanupTXN(rb, txn);
    2858           6 :         return;
    2859             :     }
    2860             : 
    2861        2476 :     snapshot_now = txn->base_snapshot;
    2862             : 
    2863             :     /* Process and send the changes to output plugin. */
    2864        2476 :     ReorderBufferProcessTXN(rb, txn, commit_lsn, snapshot_now,
    2865             :                             command_id, false);
    2866             : }
    2867             : 
    2868             : /*
    2869             :  * Commit a transaction.
    2870             :  *
    2871             :  * See comments for ReorderBufferReplay().
    2872             :  */
    2873             : void
    2874        2532 : ReorderBufferCommit(ReorderBuffer *rb, TransactionId xid,
    2875             :                     XLogRecPtr commit_lsn, XLogRecPtr end_lsn,
    2876             :                     TimestampTz commit_time,
    2877             :                     RepOriginId origin_id, XLogRecPtr origin_lsn)
    2878             : {
    2879             :     ReorderBufferTXN *txn;
    2880             : 
    2881        2532 :     txn = ReorderBufferTXNByXid(rb, xid, false, NULL, InvalidXLogRecPtr,
    2882             :                                 false);
    2883             : 
    2884             :     /* unknown transaction, nothing to replay */
    2885        2532 :     if (txn == NULL)
    2886           2 :         return;
    2887             : 
    2888        2530 :     ReorderBufferReplay(txn, rb, xid, commit_lsn, end_lsn, commit_time,
    2889             :                         origin_id, origin_lsn);
    2890             : }
    2891             : 
    2892             : /*
    2893             :  * Record the prepare information for a transaction. Also, mark the transaction
    2894             :  * as a prepared transaction.
    2895             :  */
    2896             : bool
    2897         286 : ReorderBufferRememberPrepareInfo(ReorderBuffer *rb, TransactionId xid,
    2898             :                                  XLogRecPtr prepare_lsn, XLogRecPtr end_lsn,
    2899             :                                  TimestampTz prepare_time,
    2900             :                                  RepOriginId origin_id, XLogRecPtr origin_lsn)
    2901             : {
    2902             :     ReorderBufferTXN *txn;
    2903             : 
    2904         286 :     txn = ReorderBufferTXNByXid(rb, xid, false, NULL, InvalidXLogRecPtr, false);
    2905             : 
    2906             :     /* unknown transaction, nothing to do */
    2907         286 :     if (txn == NULL)
    2908           0 :         return false;
    2909             : 
    2910             :     /*
    2911             :      * Remember the prepare information to be later used by commit prepared in
    2912             :      * case we skip doing prepare.
    2913             :      */
    2914         286 :     txn->final_lsn = prepare_lsn;
    2915         286 :     txn->end_lsn = end_lsn;
    2916         286 :     txn->xact_time.prepare_time = prepare_time;
    2917         286 :     txn->origin_id = origin_id;
    2918         286 :     txn->origin_lsn = origin_lsn;
    2919             : 
    2920             :     /* Mark this transaction as a prepared transaction */
    2921             :     Assert((txn->txn_flags & RBTXN_PREPARE_STATUS_MASK) == 0);
    2922         286 :     txn->txn_flags |= RBTXN_IS_PREPARED;
    2923             : 
    2924         286 :     return true;
    2925             : }
    2926             : 
    2927             : /* Remember that we have skipped prepare */
    2928             : void
    2929         208 : ReorderBufferSkipPrepare(ReorderBuffer *rb, TransactionId xid)
    2930             : {
    2931             :     ReorderBufferTXN *txn;
    2932             : 
    2933         208 :     txn = ReorderBufferTXNByXid(rb, xid, false, NULL, InvalidXLogRecPtr, false);
    2934             : 
    2935             :     /* unknown transaction, nothing to do */
    2936         208 :     if (txn == NULL)
    2937           0 :         return;
    2938             : 
    2939             :     /* txn must have been marked as a prepared transaction */
    2940             :     Assert((txn->txn_flags & RBTXN_PREPARE_STATUS_MASK) == RBTXN_IS_PREPARED);
    2941         208 :     txn->txn_flags |= RBTXN_SKIPPED_PREPARE;
    2942             : }
    2943             : 
    2944             : /*
    2945             :  * Prepare a two-phase transaction.
    2946             :  *
    2947             :  * See comments for ReorderBufferReplay().
    2948             :  */
    2949             : void
    2950          78 : ReorderBufferPrepare(ReorderBuffer *rb, TransactionId xid,
    2951             :                      char *gid)
    2952             : {
    2953             :     ReorderBufferTXN *txn;
    2954             : 
    2955          78 :     txn = ReorderBufferTXNByXid(rb, xid, false, NULL, InvalidXLogRecPtr,
    2956             :                                 false);
    2957             : 
    2958             :     /* unknown transaction, nothing to replay */
    2959          78 :     if (txn == NULL)
    2960           0 :         return;
    2961             : 
    2962             :     /*
    2963             :      * txn must have been marked as a prepared transaction and must have
    2964             :      * neither been skipped nor sent a prepare. Also, the prepare info must
    2965             :      * have been updated in it by now.
    2966             :      */
    2967             :     Assert((txn->txn_flags & RBTXN_PREPARE_STATUS_MASK) == RBTXN_IS_PREPARED);
    2968             :     Assert(txn->final_lsn != InvalidXLogRecPtr);
    2969             : 
    2970          78 :     txn->gid = pstrdup(gid);
    2971             : 
    2972          78 :     ReorderBufferReplay(txn, rb, xid, txn->final_lsn, txn->end_lsn,
    2973          78 :                         txn->xact_time.prepare_time, txn->origin_id, txn->origin_lsn);
    2974             : 
    2975             :     /*
    2976             :      * Send a prepare if not already done so. This might occur if we have
    2977             :      * detected a concurrent abort while replaying the non-streaming
    2978             :      * transaction.
    2979             :      */
    2980          78 :     if (!rbtxn_sent_prepare(txn))
    2981             :     {
    2982           0 :         rb->prepare(rb, txn, txn->final_lsn);
    2983           0 :         txn->txn_flags |= RBTXN_SENT_PREPARE;
    2984             :     }
    2985             : }
    2986             : 
    2987             : /*
    2988             :  * This is used to handle COMMIT/ROLLBACK PREPARED.
    2989             :  */
    2990             : void
    2991          84 : ReorderBufferFinishPrepared(ReorderBuffer *rb, TransactionId xid,
    2992             :                             XLogRecPtr commit_lsn, XLogRecPtr end_lsn,
    2993             :                             XLogRecPtr two_phase_at,
    2994             :                             TimestampTz commit_time, RepOriginId origin_id,
    2995             :                             XLogRecPtr origin_lsn, char *gid, bool is_commit)
    2996             : {
    2997             :     ReorderBufferTXN *txn;
    2998             :     XLogRecPtr  prepare_end_lsn;
    2999             :     TimestampTz prepare_time;
    3000             : 
    3001          84 :     txn = ReorderBufferTXNByXid(rb, xid, false, NULL, commit_lsn, false);
    3002             : 
    3003             :     /* unknown transaction, nothing to do */
    3004          84 :     if (txn == NULL)
    3005           0 :         return;
    3006             : 
    3007             :     /*
    3008             :      * By this time the txn has the prepare record information, remember it to
    3009             :      * be later used for rollback.
    3010             :      */
    3011          84 :     prepare_end_lsn = txn->end_lsn;
    3012          84 :     prepare_time = txn->xact_time.prepare_time;
    3013             : 
    3014             :     /* add the gid in the txn */
    3015          84 :     txn->gid = pstrdup(gid);
    3016             : 
    3017             :     /*
    3018             :      * It is possible that this transaction is not decoded at prepare time
    3019             :      * either because by that time we didn't have a consistent snapshot, or
    3020             :      * two_phase was not enabled, or it was decoded earlier but we have
    3021             :      * restarted. We only need to send the prepare if it was not decoded
    3022             :      * earlier. We don't need to decode the xact for aborts if it is not done
    3023             :      * already.
    3024             :      */
    3025          84 :     if ((txn->final_lsn < two_phase_at) && is_commit)
    3026             :     {
    3027             :         /*
    3028             :          * txn must have been marked as a prepared transaction and skipped but
    3029             :          * not sent a prepare. Also, the prepare info must have been updated
    3030             :          * in txn even if we skip prepare.
    3031             :          */
    3032             :         Assert((txn->txn_flags & RBTXN_PREPARE_STATUS_MASK) ==
    3033             :                (RBTXN_IS_PREPARED | RBTXN_SKIPPED_PREPARE));
    3034             :         Assert(txn->final_lsn != InvalidXLogRecPtr);
    3035             : 
    3036             :         /*
    3037             :          * By this time the txn has the prepare record information and it is
    3038             :          * important to use that so that downstream gets the accurate
    3039             :          * information. If instead, we have passed commit information here
    3040             :          * then downstream can behave as it has already replayed commit
    3041             :          * prepared after the restart.
    3042             :          */
    3043           6 :         ReorderBufferReplay(txn, rb, xid, txn->final_lsn, txn->end_lsn,
    3044           6 :                             txn->xact_time.prepare_time, txn->origin_id, txn->origin_lsn);
    3045             :     }
    3046             : 
    3047          84 :     txn->final_lsn = commit_lsn;
    3048          84 :     txn->end_lsn = end_lsn;
    3049          84 :     txn->xact_time.commit_time = commit_time;
    3050          84 :     txn->origin_id = origin_id;
    3051          84 :     txn->origin_lsn = origin_lsn;
    3052             : 
    3053          84 :     if (is_commit)
    3054          64 :         rb->commit_prepared(rb, txn, commit_lsn);
    3055             :     else
    3056          20 :         rb->rollback_prepared(rb, txn, prepare_end_lsn, prepare_time);
    3057             : 
    3058             :     /* cleanup: make sure there's no cache pollution */
    3059          84 :     ReorderBufferExecuteInvalidations(txn->ninvalidations,
    3060             :                                       txn->invalidations);
    3061          84 :     ReorderBufferCleanupTXN(rb, txn);
    3062             : }
    3063             : 
    3064             : /*
    3065             :  * Abort a transaction that possibly has previous changes. Needs to be first
    3066             :  * called for subtransactions and then for the toplevel xid.
    3067             :  *
    3068             :  * NB: Transactions handled here have to have actively aborted (i.e. have
    3069             :  * produced an abort record). Implicitly aborted transactions are handled via
    3070             :  * ReorderBufferAbortOld(); transactions we're just not interested in, but
    3071             :  * which have committed are handled in ReorderBufferForget().
    3072             :  *
    3073             :  * This function purges this transaction and its contents from memory and
    3074             :  * disk.
    3075             :  */
    3076             : void
    3077         220 : ReorderBufferAbort(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn,
    3078             :                    TimestampTz abort_time)
    3079             : {
    3080             :     ReorderBufferTXN *txn;
    3081             : 
    3082         220 :     txn = ReorderBufferTXNByXid(rb, xid, false, NULL, InvalidXLogRecPtr,
    3083             :                                 false);
    3084             : 
    3085             :     /* unknown, nothing to remove */
    3086         220 :     if (txn == NULL)
    3087           0 :         return;
    3088             : 
    3089         220 :     txn->xact_time.abort_time = abort_time;
    3090             : 
    3091             :     /* For streamed transactions notify the remote node about the abort. */
    3092         220 :     if (rbtxn_is_streamed(txn))
    3093             :     {
    3094          60 :         rb->stream_abort(rb, txn, lsn);
    3095             : 
    3096             :         /*
    3097             :          * We might have decoded changes for this transaction that could load
    3098             :          * the cache as per the current transaction's view (consider DDL's
    3099             :          * happened in this transaction). We don't want the decoding of future
    3100             :          * transactions to use those cache entries so execute only the inval
    3101             :          * messages in this transaction.
    3102             :          */
    3103          60 :         if (txn->ninvalidations > 0)
    3104           0 :             ReorderBufferImmediateInvalidation(rb, txn->ninvalidations,
    3105             :                                                txn->invalidations);
    3106             :     }
    3107             : 
    3108             :     /* cosmetic... */
    3109         220 :     txn->final_lsn = lsn;
    3110             : 
    3111             :     /* remove potential on-disk data, and deallocate */
    3112         220 :     ReorderBufferCleanupTXN(rb, txn);
    3113             : }
    3114             : 
    3115             : /*
    3116             :  * Abort all transactions that aren't actually running anymore because the
    3117             :  * server restarted.
    3118             :  *
    3119             :  * NB: These really have to be transactions that have aborted due to a server
    3120             :  * crash/immediate restart, as we don't deal with invalidations here.
    3121             :  */
    3122             : void
    3123        2682 : ReorderBufferAbortOld(ReorderBuffer *rb, TransactionId oldestRunningXid)
    3124             : {
    3125             :     dlist_mutable_iter it;
    3126             : 
    3127             :     /*
    3128             :      * Iterate through all (potential) toplevel TXNs and abort all that are
    3129             :      * older than what possibly can be running. Once we've found the first
    3130             :      * that is alive we stop, there might be some that acquired an xid earlier
    3131             :      * but started writing later, but it's unlikely and they will be cleaned
    3132             :      * up in a later call to this function.
    3133             :      */
    3134        2696 :     dlist_foreach_modify(it, &rb->toplevel_by_lsn)
    3135             :     {
    3136             :         ReorderBufferTXN *txn;
    3137             : 
    3138         128 :         txn = dlist_container(ReorderBufferTXN, node, it.cur);
    3139             : 
    3140         128 :         if (TransactionIdPrecedes(txn->xid, oldestRunningXid))
    3141             :         {
    3142          14 :             elog(DEBUG2, "aborting old transaction %u", txn->xid);
    3143             : 
    3144             :             /* Notify the remote node about the crash/immediate restart. */
    3145          14 :             if (rbtxn_is_streamed(txn))
    3146           0 :                 rb->stream_abort(rb, txn, InvalidXLogRecPtr);
    3147             : 
    3148             :             /* remove potential on-disk data, and deallocate this tx */
    3149          14 :             ReorderBufferCleanupTXN(rb, txn);
    3150             :         }
    3151             :         else
    3152         114 :             return;
    3153             :     }
    3154             : }
    3155             : 
    3156             : /*
    3157             :  * Forget the contents of a transaction if we aren't interested in its
    3158             :  * contents. Needs to be first called for subtransactions and then for the
    3159             :  * toplevel xid.
    3160             :  *
    3161             :  * This is significantly different to ReorderBufferAbort() because
    3162             :  * transactions that have committed need to be treated differently from aborted
    3163             :  * ones since they may have modified the catalog.
    3164             :  *
    3165             :  * Note that this is only allowed to be called in the moment a transaction
    3166             :  * commit has just been read, not earlier; otherwise later records referring
    3167             :  * to this xid might re-create the transaction incompletely.
    3168             :  */
    3169             : void
    3170        4926 : ReorderBufferForget(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn)
    3171             : {
    3172             :     ReorderBufferTXN *txn;
    3173             : 
    3174        4926 :     txn = ReorderBufferTXNByXid(rb, xid, false, NULL, InvalidXLogRecPtr,
    3175             :                                 false);
    3176             : 
    3177             :     /* unknown, nothing to forget */
    3178        4926 :     if (txn == NULL)
    3179        1122 :         return;
    3180             : 
    3181             :     /* this transaction mustn't be streamed */
    3182             :     Assert(!rbtxn_is_streamed(txn));
    3183             : 
    3184             :     /* cosmetic... */
    3185        3804 :     txn->final_lsn = lsn;
    3186             : 
    3187             :     /*
    3188             :      * Process only cache invalidation messages in this transaction if there
    3189             :      * are any. Even if we're not interested in the transaction's contents, it
    3190             :      * could have manipulated the catalog and we need to update the caches
    3191             :      * according to that.
    3192             :      */
    3193        3804 :     if (txn->base_snapshot != NULL && txn->ninvalidations > 0)
    3194        1052 :         ReorderBufferImmediateInvalidation(rb, txn->ninvalidations,
    3195             :                                            txn->invalidations);
    3196             :     else
    3197             :         Assert(txn->ninvalidations == 0);
    3198             : 
    3199             :     /* remove potential on-disk data, and deallocate */
    3200        3804 :     ReorderBufferCleanupTXN(rb, txn);
    3201             : }
    3202             : 
    3203             : /*
    3204             :  * Invalidate cache for those transactions that need to be skipped just in case
    3205             :  * catalogs were manipulated as part of the transaction.
    3206             :  *
    3207             :  * Note that this is a special-purpose function for prepared transactions where
    3208             :  * we don't want to clean up the TXN even when we decide to skip it. See
    3209             :  * DecodePrepare.
    3210             :  */
    3211             : void
    3212         202 : ReorderBufferInvalidate(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn)
    3213             : {
    3214             :     ReorderBufferTXN *txn;
    3215             : 
    3216         202 :     txn = ReorderBufferTXNByXid(rb, xid, false, NULL, InvalidXLogRecPtr,
    3217             :                                 false);
    3218             : 
    3219             :     /* unknown, nothing to do */
    3220         202 :     if (txn == NULL)
    3221           0 :         return;
    3222             : 
    3223             :     /*
    3224             :      * Process cache invalidation messages if there are any. Even if we're not
    3225             :      * interested in the transaction's contents, it could have manipulated the
    3226             :      * catalog and we need to update the caches according to that.
    3227             :      */
    3228         202 :     if (txn->base_snapshot != NULL && txn->ninvalidations > 0)
    3229          58 :         ReorderBufferImmediateInvalidation(rb, txn->ninvalidations,
    3230             :                                            txn->invalidations);
    3231             :     else
    3232             :         Assert(txn->ninvalidations == 0);
    3233             : }
    3234             : 
    3235             : 
    3236             : /*
    3237             :  * Execute invalidations happening outside the context of a decoded
    3238             :  * transaction. That currently happens either for xid-less commits
    3239             :  * (cf. RecordTransactionCommit()) or for invalidations in uninteresting
    3240             :  * transactions (via ReorderBufferForget()).
    3241             :  */
    3242             : void
    3243        1114 : ReorderBufferImmediateInvalidation(ReorderBuffer *rb, uint32 ninvalidations,
    3244             :                                    SharedInvalidationMessage *invalidations)
    3245             : {
    3246        1114 :     bool        use_subtxn = IsTransactionOrTransactionBlock();
    3247             :     int         i;
    3248             : 
    3249        1114 :     if (use_subtxn)
    3250         870 :         BeginInternalSubTransaction("replay");
    3251             : 
    3252             :     /*
    3253             :      * Force invalidations to happen outside of a valid transaction - that way
    3254             :      * entries will just be marked as invalid without accessing the catalog.
    3255             :      * That's advantageous because we don't need to setup the full state
    3256             :      * necessary for catalog access.
    3257             :      */
    3258        1114 :     if (use_subtxn)
    3259         870 :         AbortCurrentTransaction();
    3260             : 
    3261       48768 :     for (i = 0; i < ninvalidations; i++)
    3262       47654 :         LocalExecuteInvalidationMessage(&invalidations[i]);
    3263             : 
    3264        1114 :     if (use_subtxn)
    3265         870 :         RollbackAndReleaseCurrentSubTransaction();
    3266        1114 : }
    3267             : 
    3268             : /*
    3269             :  * Tell reorderbuffer about an xid seen in the WAL stream. Has to be called at
    3270             :  * least once for every xid in XLogRecord->xl_xid (other places in records
    3271             :  * may, but do not have to be passed through here).
    3272             :  *
    3273             :  * Reorderbuffer keeps some data structures about transactions in LSN order,
    3274             :  * for efficiency. To do that it has to know about when transactions are seen
    3275             :  * first in the WAL. As many types of records are not actually interesting for
    3276             :  * logical decoding, they do not necessarily pass through here.
    3277             :  */
    3278             : void
    3279     4325186 : ReorderBufferProcessXid(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn)
    3280             : {
    3281             :     /* many records won't have an xid assigned, centralize check here */
    3282     4325186 :     if (xid != InvalidTransactionId)
    3283     4321408 :         ReorderBufferTXNByXid(rb, xid, true, NULL, lsn, true);
    3284     4325186 : }
    3285             : 
    3286             : /*
    3287             :  * Add a new snapshot to this transaction that may only used after lsn 'lsn'
    3288             :  * because the previous snapshot doesn't describe the catalog correctly for
    3289             :  * following rows.
    3290             :  */
    3291             : void
    3292        2178 : ReorderBufferAddSnapshot(ReorderBuffer *rb, TransactionId xid,
    3293             :                          XLogRecPtr lsn, Snapshot snap)
    3294             : {
    3295        2178 :     ReorderBufferChange *change = ReorderBufferAllocChange(rb);
    3296             : 
    3297        2178 :     change->data.snapshot = snap;
    3298        2178 :     change->action = REORDER_BUFFER_CHANGE_INTERNAL_SNAPSHOT;
    3299             : 
    3300        2178 :     ReorderBufferQueueChange(rb, xid, lsn, change, false);
    3301        2178 : }
    3302             : 
    3303             : /*
    3304             :  * Set up the transaction's base snapshot.
    3305             :  *
    3306             :  * If we know that xid is a subtransaction, set the base snapshot on the
    3307             :  * top-level transaction instead.
    3308             :  */
    3309             : void
    3310        5702 : ReorderBufferSetBaseSnapshot(ReorderBuffer *rb, TransactionId xid,
    3311             :                              XLogRecPtr lsn, Snapshot snap)
    3312             : {
    3313             :     ReorderBufferTXN *txn;
    3314             :     bool        is_new;
    3315             : 
    3316             :     Assert(snap != NULL);
    3317             : 
    3318             :     /*
    3319             :      * Fetch the transaction to operate on.  If we know it's a subtransaction,
    3320             :      * operate on its top-level transaction instead.
    3321             :      */
    3322        5702 :     txn = ReorderBufferTXNByXid(rb, xid, true, &is_new, lsn, true);
    3323        5702 :     if (rbtxn_is_known_subxact(txn))
    3324         244 :         txn = ReorderBufferTXNByXid(rb, txn->toplevel_xid, false,
    3325             :                                     NULL, InvalidXLogRecPtr, false);
    3326             :     Assert(txn->base_snapshot == NULL);
    3327             : 
    3328        5702 :     txn->base_snapshot = snap;
    3329        5702 :     txn->base_snapshot_lsn = lsn;
    3330        5702 :     dlist_push_tail(&rb->txns_by_base_snapshot_lsn, &txn->base_snapshot_node);
    3331             : 
    3332        5702 :     AssertTXNLsnOrder(rb);
    3333        5702 : }
    3334             : 
    3335             : /*
    3336             :  * Access the catalog with this CommandId at this point in the changestream.
    3337             :  *
    3338             :  * May only be called for command ids > 1
    3339             :  */
    3340             : void
    3341       47028 : ReorderBufferAddNewCommandId(ReorderBuffer *rb, TransactionId xid,
    3342             :                              XLogRecPtr lsn, CommandId cid)
    3343             : {
    3344       47028 :     ReorderBufferChange *change = ReorderBufferAllocChange(rb);
    3345             : 
    3346       47028 :     change->data.command_id = cid;
    3347       47028 :     change->action = REORDER_BUFFER_CHANGE_INTERNAL_COMMAND_ID;
    3348             : 
    3349       47028 :     ReorderBufferQueueChange(rb, xid, lsn, change, false);
    3350       47028 : }
    3351             : 
    3352             : /*
    3353             :  * Update memory counters to account for the new or removed change.
    3354             :  *
    3355             :  * We update two counters - in the reorder buffer, and in the transaction
    3356             :  * containing the change. The reorder buffer counter allows us to quickly
    3357             :  * decide if we reached the memory limit, the transaction counter allows
    3358             :  * us to quickly pick the largest transaction for eviction.
    3359             :  *
    3360             :  * Either txn or change must be non-NULL at least. We update the memory
    3361             :  * counter of txn if it's non-NULL, otherwise change->txn.
    3362             :  *
    3363             :  * When streaming is enabled, we need to update the toplevel transaction
    3364             :  * counters instead - we don't really care about subtransactions as we
    3365             :  * can't stream them individually anyway, and we only pick toplevel
    3366             :  * transactions for eviction. So only toplevel transactions matter.
    3367             :  */
    3368             : static void
    3369     3837150 : ReorderBufferChangeMemoryUpdate(ReorderBuffer *rb,
    3370             :                                 ReorderBufferChange *change,
    3371             :                                 ReorderBufferTXN *txn,
    3372             :                                 bool addition, Size sz)
    3373             : {
    3374             :     ReorderBufferTXN *toptxn;
    3375             : 
    3376             :     Assert(txn || change);
    3377             : 
    3378             :     /*
    3379             :      * Ignore tuple CID changes, because those are not evicted when reaching
    3380             :      * memory limit. So we just don't count them, because it might easily
    3381             :      * trigger a pointless attempt to spill.
    3382             :      */
    3383     3837150 :     if (change && change->action == REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID)
    3384       46798 :         return;
    3385             : 
    3386     3790352 :     if (sz == 0)
    3387        1940 :         return;
    3388             : 
    3389     3788412 :     if (txn == NULL)
    3390     3773174 :         txn = change->txn;
    3391             :     Assert(txn != NULL);
    3392             : 
    3393             :     /*
    3394             :      * Update the total size in top level as well. This is later used to
    3395             :      * compute the decoding stats.
    3396             :      */
    3397     3788412 :     toptxn = rbtxn_get_toptxn(txn);
    3398             : 
    3399     3788412 :     if (addition)
    3400             :     {
    3401     3416188 :         Size        oldsize = txn->size;
    3402             : 
    3403     3416188 :         txn->size += sz;
    3404     3416188 :         rb->size += sz;
    3405             : 
    3406             :         /* Update the total size in the top transaction. */
    3407     3416188 :         toptxn->total_size += sz;
    3408             : 
    3409             :         /* Update the max-heap */
    3410     3416188 :         if (oldsize != 0)
    3411     3400816 :             pairingheap_remove(rb->txn_heap, &txn->txn_node);
    3412     3416188 :         pairingheap_add(rb->txn_heap, &txn->txn_node);
    3413             :     }
    3414             :     else
    3415             :     {
    3416             :         Assert((rb->size >= sz) && (txn->size >= sz));
    3417      372224 :         txn->size -= sz;
    3418      372224 :         rb->size -= sz;
    3419             : 
    3420             :         /* Update the total size in the top transaction. */
    3421      372224 :         toptxn->total_size -= sz;
    3422             : 
    3423             :         /* Update the max-heap */
    3424      372224 :         pairingheap_remove(rb->txn_heap, &txn->txn_node);
    3425      372224 :         if (txn->size != 0)
    3426      356928 :             pairingheap_add(rb->txn_heap, &txn->txn_node);
    3427             :     }
    3428             : 
    3429             :     Assert(txn->size <= rb->size);
    3430             : }
    3431             : 
    3432             : /*
    3433             :  * Add new (relfilelocator, tid) -> (cmin, cmax) mappings.
    3434             :  *
    3435             :  * We do not include this change type in memory accounting, because we
    3436             :  * keep CIDs in a separate list and do not evict them when reaching
    3437             :  * the memory limit.
    3438             :  */
    3439             : void
    3440       47028 : ReorderBufferAddNewTupleCids(ReorderBuffer *rb, TransactionId xid,
    3441             :                              XLogRecPtr lsn, RelFileLocator locator,
    3442             :                              ItemPointerData tid, CommandId cmin,
    3443             :                              CommandId cmax, CommandId combocid)
    3444             : {
    3445       47028 :     ReorderBufferChange *change = ReorderBufferAllocChange(rb);
    3446             :     ReorderBufferTXN *txn;
    3447             : 
    3448       47028 :     txn = ReorderBufferTXNByXid(rb, xid, true, NULL, lsn, true);
    3449             : 
    3450       47028 :     change->data.tuplecid.locator = locator;
    3451       47028 :     change->data.tuplecid.tid = tid;
    3452       47028 :     change->data.tuplecid.cmin = cmin;
    3453       47028 :     change->data.tuplecid.cmax = cmax;
    3454       47028 :     change->data.tuplecid.combocid = combocid;
    3455       47028 :     change->lsn = lsn;
    3456       47028 :     change->txn = txn;
    3457       47028 :     change->action = REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID;
    3458             : 
    3459       47028 :     dlist_push_tail(&txn->tuplecids, &change->node);
    3460       47028 :     txn->ntuplecids++;
    3461       47028 : }
    3462             : 
    3463             : /*
    3464             :  * Add new invalidation messages to the reorder buffer queue.
    3465             :  */
    3466             : static void
    3467        9714 : ReorderBufferQueueInvalidations(ReorderBuffer *rb, TransactionId xid,
    3468             :                                 XLogRecPtr lsn, Size nmsgs,
    3469             :                                 SharedInvalidationMessage *msgs)
    3470             : {
    3471             :     ReorderBufferChange *change;
    3472             : 
    3473        9714 :     change = ReorderBufferAllocChange(rb);
    3474        9714 :     change->action = REORDER_BUFFER_CHANGE_INVALIDATION;
    3475        9714 :     change->data.inval.ninvalidations = nmsgs;
    3476        9714 :     change->data.inval.invalidations = (SharedInvalidationMessage *)
    3477        9714 :         palloc(sizeof(SharedInvalidationMessage) * nmsgs);
    3478        9714 :     memcpy(change->data.inval.invalidations, msgs,
    3479             :            sizeof(SharedInvalidationMessage) * nmsgs);
    3480             : 
    3481        9714 :     ReorderBufferQueueChange(rb, xid, lsn, change, false);
    3482        9714 : }
    3483             : 
    3484             : /*
    3485             :  * A helper function for ReorderBufferAddInvalidations() and
    3486             :  * ReorderBufferAddDistributedInvalidations() to accumulate the invalidation
    3487             :  * messages to the **invals_out.
    3488             :  */
    3489             : static void
    3490        9714 : ReorderBufferAccumulateInvalidations(SharedInvalidationMessage **invals_out,
    3491             :                                      uint32 *ninvals_out,
    3492             :                                      SharedInvalidationMessage *msgs_new,
    3493             :                                      Size nmsgs_new)
    3494             : {
    3495        9714 :     if (*ninvals_out == 0)
    3496             :     {
    3497        2190 :         *ninvals_out = nmsgs_new;
    3498        2190 :         *invals_out = (SharedInvalidationMessage *)
    3499        2190 :             palloc(sizeof(SharedInvalidationMessage) * nmsgs_new);
    3500        2190 :         memcpy(*invals_out, msgs_new, sizeof(SharedInvalidationMessage) * nmsgs_new);
    3501             :     }
    3502             :     else
    3503             :     {
    3504             :         /* Enlarge the array of inval messages */
    3505        7524 :         *invals_out = (SharedInvalidationMessage *)
    3506        7524 :             repalloc(*invals_out, sizeof(SharedInvalidationMessage) *
    3507        7524 :                      (*ninvals_out + nmsgs_new));
    3508        7524 :         memcpy(*invals_out + *ninvals_out, msgs_new,
    3509             :                nmsgs_new * sizeof(SharedInvalidationMessage));
    3510        7524 :         *ninvals_out += nmsgs_new;
    3511             :     }
    3512        9714 : }
    3513             : 
    3514             : /*
    3515             :  * Accumulate the invalidations for executing them later.
    3516             :  *
    3517             :  * This needs to be called for each XLOG_XACT_INVALIDATIONS message and
    3518             :  * accumulates all the invalidation messages in the toplevel transaction, if
    3519             :  * available, otherwise in the current transaction, as well as in the form of
    3520             :  * change in reorder buffer.  We require to record it in form of the change
    3521             :  * so that we can execute only the required invalidations instead of executing
    3522             :  * all the invalidations on each CommandId increment.  We also need to
    3523             :  * accumulate these in the txn buffer because in some cases where we skip
    3524             :  * processing the transaction (see ReorderBufferForget), we need to execute
    3525             :  * all the invalidations together.
    3526             :  */
    3527             : void
    3528        9656 : ReorderBufferAddInvalidations(ReorderBuffer *rb, TransactionId xid,
    3529             :                               XLogRecPtr lsn, Size nmsgs,
    3530             :                               SharedInvalidationMessage *msgs)
    3531             : {
    3532             :     ReorderBufferTXN *txn;
    3533             :     MemoryContext oldcontext;
    3534             : 
    3535        9656 :     txn = ReorderBufferTXNByXid(rb, xid, true, NULL, lsn, true);
    3536             : 
    3537        9656 :     oldcontext = MemoryContextSwitchTo(rb->context);
    3538             : 
    3539             :     /*
    3540             :      * Collect all the invalidations under the top transaction, if available,
    3541             :      * so that we can execute them all together.  See comments atop this
    3542             :      * function.
    3543             :      */
    3544        9656 :     txn = rbtxn_get_toptxn(txn);
    3545             : 
    3546             :     Assert(nmsgs > 0);
    3547             : 
    3548        9656 :     ReorderBufferAccumulateInvalidations(&txn->invalidations,
    3549             :                                          &txn->ninvalidations,
    3550             :                                          msgs, nmsgs);
    3551             : 
    3552        9656 :     ReorderBufferQueueInvalidations(rb, xid, lsn, nmsgs, msgs);
    3553             : 
    3554        9656 :     MemoryContextSwitchTo(oldcontext);
    3555        9656 : }
    3556             : 
    3557             : /*
    3558             :  * Accumulate the invalidations distributed by other committed transactions
    3559             :  * for executing them later.
    3560             :  *
    3561             :  * This function is similar to ReorderBufferAddInvalidations() but stores
    3562             :  * the given inval messages to the txn->invalidations_distributed with the
    3563             :  * overflow check.
    3564             :  *
    3565             :  * This needs to be called by committed transactions to distribute their
    3566             :  * inval messages to in-progress transactions.
    3567             :  */
    3568             : void
    3569          58 : ReorderBufferAddDistributedInvalidations(ReorderBuffer *rb, TransactionId xid,
    3570             :                                          XLogRecPtr lsn, Size nmsgs,
    3571             :                                          SharedInvalidationMessage *msgs)
    3572             : {
    3573             :     ReorderBufferTXN *txn;
    3574             :     MemoryContext oldcontext;
    3575             : 
    3576          58 :     txn = ReorderBufferTXNByXid(rb, xid, true, NULL, lsn, true);
    3577             : 
    3578          58 :     oldcontext = MemoryContextSwitchTo(rb->context);
    3579             : 
    3580             :     /*
    3581             :      * Collect all the invalidations under the top transaction, if available,
    3582             :      * so that we can execute them all together.  See comments
    3583             :      * ReorderBufferAddInvalidations.
    3584             :      */
    3585          58 :     txn = rbtxn_get_toptxn(txn);
    3586             : 
    3587             :     Assert(nmsgs > 0);
    3588             : 
    3589          58 :     if (!rbtxn_distr_inval_overflowed(txn))
    3590             :     {
    3591             :         /*
    3592             :          * Check the transaction has enough space for storing distributed
    3593             :          * invalidation messages.
    3594             :          */
    3595          58 :         if (txn->ninvalidations_distributed + nmsgs >= MAX_DISTR_INVAL_MSG_PER_TXN)
    3596             :         {
    3597             :             /*
    3598             :              * Mark the invalidation message as overflowed and free up the
    3599             :              * messages accumulated so far.
    3600             :              */
    3601           0 :             txn->txn_flags |= RBTXN_DISTR_INVAL_OVERFLOWED;
    3602             : 
    3603           0 :             if (txn->invalidations_distributed)
    3604             :             {
    3605           0 :                 pfree(txn->invalidations_distributed);
    3606           0 :                 txn->invalidations_distributed = NULL;
    3607           0 :                 txn->ninvalidations_distributed = 0;
    3608             :             }
    3609             :         }
    3610             :         else
    3611          58 :             ReorderBufferAccumulateInvalidations(&txn->invalidations_distributed,
    3612             :                                                  &txn->ninvalidations_distributed,
    3613             :                                                  msgs, nmsgs);
    3614             :     }
    3615             : 
    3616             :     /* Queue the invalidation messages into the transaction */
    3617          58 :     ReorderBufferQueueInvalidations(rb, xid, lsn, nmsgs, msgs);
    3618             : 
    3619          58 :     MemoryContextSwitchTo(oldcontext);
    3620          58 : }
    3621             : 
    3622             : /*
    3623             :  * Apply all invalidations we know. Possibly we only need parts at this point
    3624             :  * in the changestream but we don't know which those are.
    3625             :  */
    3626             : static void
    3627       12358 : ReorderBufferExecuteInvalidations(uint32 nmsgs, SharedInvalidationMessage *msgs)
    3628             : {
    3629             :     int         i;
    3630             : 
    3631       96178 :     for (i = 0; i < nmsgs; i++)
    3632       83820 :         LocalExecuteInvalidationMessage(&msgs[i]);
    3633       12358 : }
    3634             : 
    3635             : /*
    3636             :  * Mark a transaction as containing catalog changes
    3637             :  */
    3638             : void
    3639       56756 : ReorderBufferXidSetCatalogChanges(ReorderBuffer *rb, TransactionId xid,
    3640             :                                   XLogRecPtr lsn)
    3641             : {
    3642             :     ReorderBufferTXN *txn;
    3643             : 
    3644       56756 :     txn = ReorderBufferTXNByXid(rb, xid, true, NULL, lsn, true);
    3645             : 
    3646       56756 :     if (!rbtxn_has_catalog_changes(txn))
    3647             :     {
    3648        2220 :         txn->txn_flags |= RBTXN_HAS_CATALOG_CHANGES;
    3649        2220 :         dclist_push_tail(&rb->catchange_txns, &txn->catchange_node);
    3650             :     }
    3651             : 
    3652             :     /*
    3653             :      * Mark top-level transaction as having catalog changes too if one of its
    3654             :      * children has so that the ReorderBufferBuildTupleCidHash can
    3655             :      * conveniently check just top-level transaction and decide whether to
    3656             :      * build the hash table or not.
    3657             :      */
    3658       56756 :     if (rbtxn_is_subtxn(txn))
    3659             :     {
    3660        1792 :         ReorderBufferTXN *toptxn = rbtxn_get_toptxn(txn);
    3661             : 
    3662        1792 :         if (!rbtxn_has_catalog_changes(toptxn))
    3663             :         {
    3664          40 :             toptxn->txn_flags |= RBTXN_HAS_CATALOG_CHANGES;
    3665          40 :             dclist_push_tail(&rb->catchange_txns, &toptxn->catchange_node);
    3666             :         }
    3667             :     }
    3668       56756 : }
    3669             : 
    3670             : /*
    3671             :  * Return palloc'ed array of the transactions that have changed catalogs.
    3672             :  * The returned array is sorted in xidComparator order.
    3673             :  *
    3674             :  * The caller must free the returned array when done with it.
    3675             :  */
    3676             : TransactionId *
    3677         586 : ReorderBufferGetCatalogChangesXacts(ReorderBuffer *rb)
    3678             : {
    3679             :     dlist_iter  iter;
    3680         586 :     TransactionId *xids = NULL;
    3681         586 :     size_t      xcnt = 0;
    3682             : 
    3683             :     /* Quick return if the list is empty */
    3684         586 :     if (dclist_count(&rb->catchange_txns) == 0)
    3685         568 :         return NULL;
    3686             : 
    3687             :     /* Initialize XID array */
    3688          18 :     xids = (TransactionId *) palloc(sizeof(TransactionId) *
    3689          18 :                                     dclist_count(&rb->catchange_txns));
    3690          42 :     dclist_foreach(iter, &rb->catchange_txns)
    3691             :     {
    3692          24 :         ReorderBufferTXN *txn = dclist_container(ReorderBufferTXN,
    3693             :                                                  catchange_node,
    3694             :                                                  iter.cur);
    3695             : 
    3696             :         Assert(rbtxn_has_catalog_changes(txn));
    3697             : 
    3698          24 :         xids[xcnt++] = txn->xid;
    3699             :     }
    3700             : 
    3701          18 :     qsort(xids, xcnt, sizeof(TransactionId), xidComparator);
    3702             : 
    3703             :     Assert(xcnt == dclist_count(&rb->catchange_txns));
    3704          18 :     return xids;
    3705             : }
    3706             : 
    3707             : /*
    3708             :  * Query whether a transaction is already *known* to contain catalog
    3709             :  * changes. This can be wrong until directly before the commit!
    3710             :  */
    3711             : bool
    3712        8054 : ReorderBufferXidHasCatalogChanges(ReorderBuffer *rb, TransactionId xid)
    3713             : {
    3714             :     ReorderBufferTXN *txn;
    3715             : 
    3716        8054 :     txn = ReorderBufferTXNByXid(rb, xid, false, NULL, InvalidXLogRecPtr,
    3717             :                                 false);
    3718        8054 :     if (txn == NULL)
    3719        1292 :         return false;
    3720             : 
    3721        6762 :     return rbtxn_has_catalog_changes(txn);
    3722             : }
    3723             : 
    3724             : /*
    3725             :  * ReorderBufferXidHasBaseSnapshot
    3726             :  *      Have we already set the base snapshot for the given txn/subtxn?
    3727             :  */
    3728             : bool
    3729     3040582 : ReorderBufferXidHasBaseSnapshot(ReorderBuffer *rb, TransactionId xid)
    3730             : {
    3731             :     ReorderBufferTXN *txn;
    3732             : 
    3733     3040582 :     txn = ReorderBufferTXNByXid(rb, xid, false,
    3734             :                                 NULL, InvalidXLogRecPtr, false);
    3735             : 
    3736             :     /* transaction isn't known yet, ergo no snapshot */
    3737     3040582 :     if (txn == NULL)
    3738           6 :         return false;
    3739             : 
    3740             :     /* a known subtxn? operate on top-level txn instead */
    3741     3040576 :     if (rbtxn_is_known_subxact(txn))
    3742      984064 :         txn = ReorderBufferTXNByXid(rb, txn->toplevel_xid, false,
    3743             :                                     NULL, InvalidXLogRecPtr, false);
    3744             : 
    3745     3040576 :     return txn->base_snapshot != NULL;
    3746             : }
    3747             : 
    3748             : 
    3749             : /*
    3750             :  * ---------------------------------------
    3751             :  * Disk serialization support
    3752             :  * ---------------------------------------
    3753             :  */
    3754             : 
    3755             : /*
    3756             :  * Ensure the IO buffer is >= sz.
    3757             :  */
    3758             : static void
    3759     5859438 : ReorderBufferSerializeReserve(ReorderBuffer *rb, Size sz)
    3760             : {
    3761     5859438 :     if (!rb->outbufsize)
    3762             :     {
    3763          92 :         rb->outbuf = MemoryContextAlloc(rb->context, sz);
    3764          92 :         rb->outbufsize = sz;
    3765             :     }
    3766     5859346 :     else if (rb->outbufsize < sz)
    3767             :     {
    3768         578 :         rb->outbuf = repalloc(rb->outbuf, sz);
    3769         578 :         rb->outbufsize = sz;
    3770             :     }
    3771     5859438 : }
    3772             : 
    3773             : 
    3774             : /* Compare two transactions by size */
    3775             : static int
    3776      636934 : ReorderBufferTXNSizeCompare(const pairingheap_node *a, const pairingheap_node *b, void *arg)
    3777             : {
    3778      636934 :     const ReorderBufferTXN *ta = pairingheap_const_container(ReorderBufferTXN, txn_node, a);
    3779      636934 :     const ReorderBufferTXN *tb = pairingheap_const_container(ReorderBufferTXN, txn_node, b);
    3780             : 
    3781      636934 :     if (ta->size < tb->size)
    3782      453316 :         return -1;
    3783      183618 :     if (ta->size > tb->size)
    3784      181824 :         return 1;
    3785        1794 :     return 0;
    3786             : }
    3787             : 
    3788             : /*
    3789             :  * Find the largest transaction (toplevel or subxact) to evict (spill to disk).
    3790             :  */
    3791             : static ReorderBufferTXN *
    3792        7444 : ReorderBufferLargestTXN(ReorderBuffer *rb)
    3793             : {
    3794             :     ReorderBufferTXN *largest;
    3795             : 
    3796             :     /* Get the largest transaction from the max-heap */
    3797        7444 :     largest = pairingheap_container(ReorderBufferTXN, txn_node,
    3798             :                                     pairingheap_first(rb->txn_heap));
    3799             : 
    3800             :     Assert(largest);
    3801             :     Assert(largest->size > 0);
    3802             :     Assert(largest->size <= rb->size);
    3803             : 
    3804        7444 :     return largest;
    3805             : }
    3806             : 
    3807             : /*
    3808             :  * Find the largest streamable (and non-aborted) toplevel transaction to evict
    3809             :  * (by streaming).
    3810             :  *
    3811             :  * This can be seen as an optimized version of ReorderBufferLargestTXN, which
    3812             :  * should give us the same transaction (because we don't update memory account
    3813             :  * for subtransaction with streaming, so it's always 0). But we can simply
    3814             :  * iterate over the limited number of toplevel transactions that have a base
    3815             :  * snapshot. There is no use of selecting a transaction that doesn't have base
    3816             :  * snapshot because we don't decode such transactions.  Also, we do not select
    3817             :  * the transaction which doesn't have any streamable change.
    3818             :  *
    3819             :  * Note that, we skip transactions that contain incomplete changes. There
    3820             :  * is a scope of optimization here such that we can select the largest
    3821             :  * transaction which has incomplete changes.  But that will make the code and
    3822             :  * design quite complex and that might not be worth the benefit.  If we plan to
    3823             :  * stream the transactions that contain incomplete changes then we need to
    3824             :  * find a way to partially stream/truncate the transaction changes in-memory
    3825             :  * and build a mechanism to partially truncate the spilled files.
    3826             :  * Additionally, whenever we partially stream the transaction we need to
    3827             :  * maintain the last streamed lsn and next time we need to restore from that
    3828             :  * segment and the offset in WAL.  As we stream the changes from the top
    3829             :  * transaction and restore them subtransaction wise, we need to even remember
    3830             :  * the subxact from where we streamed the last change.
    3831             :  */
    3832             : static ReorderBufferTXN *
    3833        1636 : ReorderBufferLargestStreamableTopTXN(ReorderBuffer *rb)
    3834             : {
    3835             :     dlist_iter  iter;
    3836        1636 :     Size        largest_size = 0;
    3837        1636 :     ReorderBufferTXN *largest = NULL;
    3838             : 
    3839             :     /* Find the largest top-level transaction having a base snapshot. */
    3840        3496 :     dlist_foreach(iter, &rb->txns_by_base_snapshot_lsn)
    3841             :     {
    3842             :         ReorderBufferTXN *txn;
    3843             : 
    3844        1860 :         txn = dlist_container(ReorderBufferTXN, base_snapshot_node, iter.cur);
    3845             : 
    3846             :         /* must not be a subtxn */
    3847             :         Assert(!rbtxn_is_known_subxact(txn));
    3848             :         /* base_snapshot must be set */
    3849             :         Assert(txn->base_snapshot != NULL);
    3850             : 
    3851             :         /* Don't consider these kinds of transactions for eviction. */
    3852        1860 :         if (rbtxn_has_partial_change(txn) ||
    3853        1566 :             !rbtxn_has_streamable_change(txn) ||
    3854        1506 :             rbtxn_is_aborted(txn))
    3855         354 :             continue;
    3856             : 
    3857             :         /* Find the largest of the eviction candidates. */
    3858        1506 :         if ((largest == NULL || txn->total_size > largest_size) &&
    3859        1506 :             (txn->total_size > 0))
    3860             :         {
    3861        1414 :             largest = txn;
    3862        1414 :             largest_size = txn->total_size;
    3863             :         }
    3864             :     }
    3865             : 
    3866        1636 :     return largest;
    3867             : }
    3868             : 
    3869             : /*
    3870             :  * Check whether the logical_decoding_work_mem limit was reached, and if yes
    3871             :  * pick the largest (sub)transaction at-a-time to evict and spill its changes to
    3872             :  * disk or send to the output plugin until we reach under the memory limit.
    3873             :  *
    3874             :  * If debug_logical_replication_streaming is set to "immediate", stream or
    3875             :  * serialize the changes immediately.
    3876             :  *
    3877             :  * XXX At this point we select the transactions until we reach under the memory
    3878             :  * limit, but we might also adapt a more elaborate eviction strategy - for example
    3879             :  * evicting enough transactions to free certain fraction (e.g. 50%) of the memory
    3880             :  * limit.
    3881             :  */
    3882             : static void
    3883     3059228 : ReorderBufferCheckMemoryLimit(ReorderBuffer *rb)
    3884             : {
    3885             :     ReorderBufferTXN *txn;
    3886             : 
    3887             :     /*
    3888             :      * Bail out if debug_logical_replication_streaming is buffered and we
    3889             :      * haven't exceeded the memory limit.
    3890             :      */
    3891     3059228 :     if (debug_logical_replication_streaming == DEBUG_LOGICAL_REP_STREAMING_BUFFERED &&
    3892     3057298 :         rb->size < logical_decoding_work_mem * (Size) 1024)
    3893     3050496 :         return;
    3894             : 
    3895             :     /*
    3896             :      * If debug_logical_replication_streaming is immediate, loop until there's
    3897             :      * no change. Otherwise, loop until we reach under the memory limit. One
    3898             :      * might think that just by evicting the largest (sub)transaction we will
    3899             :      * come under the memory limit based on assumption that the selected
    3900             :      * transaction is at least as large as the most recent change (which
    3901             :      * caused us to go over the memory limit). However, that is not true
    3902             :      * because a user can reduce the logical_decoding_work_mem to a smaller
    3903             :      * value before the most recent change.
    3904             :      */
    3905       17458 :     while (rb->size >= logical_decoding_work_mem * (Size) 1024 ||
    3906       10656 :            (debug_logical_replication_streaming == DEBUG_LOGICAL_REP_STREAMING_IMMEDIATE &&
    3907        3854 :             rb->size > 0))
    3908             :     {
    3909             :         /*
    3910             :          * Pick the largest non-aborted transaction and evict it from memory
    3911             :          * by streaming, if possible.  Otherwise, spill to disk.
    3912             :          */
    3913       10362 :         if (ReorderBufferCanStartStreaming(rb) &&
    3914        1636 :             (txn = ReorderBufferLargestStreamableTopTXN(rb)) != NULL)
    3915             :         {
    3916             :             /* we know there has to be one, because the size is not zero */
    3917             :             Assert(txn && rbtxn_is_toptxn(txn));
    3918             :             Assert(txn->total_size > 0);
    3919             :             Assert(rb->size >= txn->total_size);
    3920             : 
    3921             :             /* skip the transaction if aborted */
    3922        1282 :             if (ReorderBufferCheckAndTruncateAbortedTXN(rb, txn))
    3923           0 :                 continue;
    3924             : 
    3925        1282 :             ReorderBufferStreamTXN(rb, txn);
    3926             :         }
    3927             :         else
    3928             :         {
    3929             :             /*
    3930             :              * Pick the largest transaction (or subtransaction) and evict it
    3931             :              * from memory by serializing it to disk.
    3932             :              */
    3933        7444 :             txn = ReorderBufferLargestTXN(rb);
    3934             : 
    3935             :             /* we know there has to be one, because the size is not zero */
    3936             :             Assert(txn);
    3937             :             Assert(txn->size > 0);
    3938             :             Assert(rb->size >= txn->size);
    3939             : 
    3940             :             /* skip the transaction if aborted */
    3941        7444 :             if (ReorderBufferCheckAndTruncateAbortedTXN(rb, txn))
    3942          18 :                 continue;
    3943             : 
    3944        7426 :             ReorderBufferSerializeTXN(rb, txn);
    3945             :         }
    3946             : 
    3947             :         /*
    3948             :          * After eviction, the transaction should have no entries in memory,
    3949             :          * and should use 0 bytes for changes.
    3950             :          */
    3951             :         Assert(txn->size == 0);
    3952             :         Assert(txn->nentries_mem == 0);
    3953             :     }
    3954             : 
    3955             :     /* We must be under the memory limit now. */
    3956             :     Assert(rb->size < logical_decoding_work_mem * (Size) 1024);
    3957             : }
    3958             : 
    3959             : /*
    3960             :  * Spill data of a large transaction (and its subtransactions) to disk.
    3961             :  */
    3962             : static void
    3963        8044 : ReorderBufferSerializeTXN(ReorderBuffer *rb, ReorderBufferTXN *txn)
    3964             : {
    3965             :     dlist_iter  subtxn_i;
    3966             :     dlist_mutable_iter change_i;
    3967        8044 :     int         fd = -1;
    3968        8044 :     XLogSegNo   curOpenSegNo = 0;
    3969        8044 :     Size        spilled = 0;
    3970        8044 :     Size        size = txn->size;
    3971             : 
    3972        8044 :     elog(DEBUG2, "spill %u changes in XID %u to disk",
    3973             :          (uint32) txn->nentries_mem, txn->xid);
    3974             : 
    3975             :     /* do the same to all child TXs */
    3976        8582 :     dlist_foreach(subtxn_i, &txn->subtxns)
    3977             :     {
    3978             :         ReorderBufferTXN *subtxn;
    3979             : 
    3980         538 :         subtxn = dlist_container(ReorderBufferTXN, node, subtxn_i.cur);
    3981         538 :         ReorderBufferSerializeTXN(rb, subtxn);
    3982             :     }
    3983             : 
    3984             :     /* serialize changestream */
    3985     2598564 :     dlist_foreach_modify(change_i, &txn->changes)
    3986             :     {
    3987             :         ReorderBufferChange *change;
    3988             : 
    3989     2590520 :         change = dlist_container(ReorderBufferChange, node, change_i.cur);
    3990             : 
    3991             :         /*
    3992             :          * store in segment in which it belongs by start lsn, don't split over
    3993             :          * multiple segments tho
    3994             :          */
    3995     2590520 :         if (fd == -1 ||
    3996     2582980 :             !XLByteInSeg(change->lsn, curOpenSegNo, wal_segment_size))
    3997             :         {
    3998             :             char        path[MAXPGPATH];
    3999             : 
    4000        7546 :             if (fd != -1)
    4001           6 :                 CloseTransientFile(fd);
    4002             : 
    4003        7546 :             XLByteToSeg(change->lsn, curOpenSegNo, wal_segment_size);
    4004             : 
    4005             :             /*
    4006             :              * No need to care about TLIs here, only used during a single run,
    4007             :              * so each LSN only maps to a specific WAL record.
    4008             :              */
    4009        7546 :             ReorderBufferSerializedPath(path, MyReplicationSlot, txn->xid,
    4010             :                                         curOpenSegNo);
    4011             : 
    4012             :             /* open segment, create it if necessary */
    4013        7546 :             fd = OpenTransientFile(path,
    4014             :                                    O_CREAT | O_WRONLY | O_APPEND | PG_BINARY);
    4015             : 
    4016        7546 :             if (fd < 0)
    4017           0 :                 ereport(ERROR,
    4018             :                         (errcode_for_file_access(),
    4019             :                          errmsg("could not open file \"%s\": %m", path)));
    4020             :         }
    4021             : 
    4022     2590520 :         ReorderBufferSerializeChange(rb, txn, fd, change);
    4023     2590520 :         dlist_delete(&change->node);
    4024     2590520 :         ReorderBufferFreeChange(rb, change, false);
    4025             : 
    4026     2590520 :         spilled++;
    4027             :     }
    4028             : 
    4029             :     /* Update the memory counter */
    4030        8044 :     ReorderBufferChangeMemoryUpdate(rb, NULL, txn, false, size);
    4031             : 
    4032             :     /* update the statistics iff we have spilled anything */
    4033        8044 :     if (spilled)
    4034             :     {
    4035        7540 :         rb->spillCount += 1;
    4036        7540 :         rb->spillBytes += size;
    4037             : 
    4038             :         /* don't consider already serialized transactions */
    4039        7540 :         rb->spillTxns += (rbtxn_is_serialized(txn) || rbtxn_is_serialized_clear(txn)) ? 0 : 1;
    4040             : 
    4041             :         /* update the decoding stats */
    4042        7540 :         UpdateDecodingStats((LogicalDecodingContext *) rb->private_data);
    4043             :     }
    4044             : 
    4045             :     Assert(spilled == txn->nentries_mem);
    4046             :     Assert(dlist_is_empty(&txn->changes));
    4047        8044 :     txn->nentries_mem = 0;
    4048        8044 :     txn->txn_flags |= RBTXN_IS_SERIALIZED;
    4049             : 
    4050        8044 :     if (fd != -1)
    4051        7540 :         CloseTransientFile(fd);
    4052        8044 : }
    4053             : 
    4054             : /*
    4055             :  * Serialize individual change to disk.
    4056             :  */
    4057             : static void
    4058     2590520 : ReorderBufferSerializeChange(ReorderBuffer *rb, ReorderBufferTXN *txn,
    4059             :                              int fd, ReorderBufferChange *change)
    4060             : {
    4061             :     ReorderBufferDiskChange *ondisk;
    4062     2590520 :     Size        sz = sizeof(ReorderBufferDiskChange);
    4063             : 
    4064     2590520 :     ReorderBufferSerializeReserve(rb, sz);
    4065             : 
    4066     2590520 :     ondisk = (ReorderBufferDiskChange *) rb->outbuf;
    4067     2590520 :     memcpy(&ondisk->change, change, sizeof(ReorderBufferChange));
    4068             : 
    4069     2590520 :     switch (change->action)
    4070             :     {
    4071             :             /* fall through these, they're all similar enough */
    4072     2555544 :         case REORDER_BUFFER_CHANGE_INSERT:
    4073             :         case REORDER_BUFFER_CHANGE_UPDATE:
    4074             :         case REORDER_BUFFER_CHANGE_DELETE:
    4075             :         case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_INSERT:
    4076             :             {
    4077             :                 char       *data;
    4078             :                 HeapTuple   oldtup,
    4079             :                             newtup;
    4080     2555544 :                 Size        oldlen = 0;
    4081     2555544 :                 Size        newlen = 0;
    4082             : 
    4083     2555544 :                 oldtup = change->data.tp.oldtuple;
    4084     2555544 :                 newtup = change->data.tp.newtuple;
    4085             : 
    4086     2555544 :                 if (oldtup)
    4087             :                 {
    4088      194002 :                     sz += sizeof(HeapTupleData);
    4089      194002 :                     oldlen = oldtup->t_len;
    4090      194002 :                     sz += oldlen;
    4091             :                 }
    4092             : 
    4093     2555544 :                 if (newtup)
    4094             :                 {
    4095     2254112 :                     sz += sizeof(HeapTupleData);
    4096     2254112 :                     newlen = newtup->t_len;
    4097     2254112 :                     sz += newlen;
    4098             :                 }
    4099             : 
    4100             :                 /* make sure we have enough space */
    4101     2555544 :                 ReorderBufferSerializeReserve(rb, sz);
    4102             : 
    4103     2555544 :                 data = ((char *) rb->outbuf) + sizeof(ReorderBufferDiskChange);
    4104             :                 /* might have been reallocated above */
    4105     2555544 :                 ondisk = (ReorderBufferDiskChange *) rb->outbuf;
    4106             : 
    4107     2555544 :                 if (oldlen)
    4108             :                 {
    4109      194002 :                     memcpy(data, oldtup, sizeof(HeapTupleData));
    4110      194002 :                     data += sizeof(HeapTupleData);
    4111             : 
    4112      194002 :                     memcpy(data, oldtup->t_data, oldlen);
    4113      194002 :                     data += oldlen;
    4114             :                 }
    4115             : 
    4116     2555544 :                 if (newlen)
    4117             :                 {
    4118     2254112 :                     memcpy(data, newtup, sizeof(HeapTupleData));
    4119     2254112 :                     data += sizeof(HeapTupleData);
    4120             : 
    4121     2254112 :                     memcpy(data, newtup->t_data, newlen);
    4122     2254112 :                     data += newlen;
    4123             :                 }
    4124     2555544 :                 break;
    4125             :             }
    4126          26 :         case REORDER_BUFFER_CHANGE_MESSAGE:
    4127             :             {
    4128             :                 char       *data;
    4129          26 :                 Size        prefix_size = strlen(change->data.msg.prefix) + 1;
    4130             : 
    4131          26 :                 sz += prefix_size + change->data.msg.message_size +
    4132             :                     sizeof(Size) + sizeof(Size);
    4133          26 :                 ReorderBufferSerializeReserve(rb, sz);
    4134             : 
    4135          26 :                 data = ((char *) rb->outbuf) + sizeof(ReorderBufferDiskChange);
    4136             : 
    4137             :                 /* might have been reallocated above */
    4138          26 :                 ondisk = (ReorderBufferDiskChange *) rb->outbuf;
    4139             : 
    4140             :                 /* write the prefix including the size */
    4141          26 :                 memcpy(data, &prefix_size, sizeof(Size));
    4142          26 :                 data += sizeof(Size);
    4143          26 :                 memcpy(data, change->data.msg.prefix,
    4144             :                        prefix_size);
    4145          26 :                 data += prefix_size;
    4146             : 
    4147             :                 /* write the message including the size */
    4148          26 :                 memcpy(data, &change->data.msg.message_size, sizeof(Size));
    4149          26 :                 data += sizeof(Size);
    4150          26 :                 memcpy(data, change->data.msg.message,
    4151             :                        change->data.msg.message_size);
    4152          26 :                 data += change->data.msg.message_size;
    4153             : 
    4154          26 :                 break;
    4155             :             }
    4156         308 :         case REORDER_BUFFER_CHANGE_INVALIDATION:
    4157             :             {
    4158             :                 char       *data;
    4159         308 :                 Size        inval_size = sizeof(SharedInvalidationMessage) *
    4160         308 :                     change->data.inval.ninvalidations;
    4161             : 
    4162         308 :                 sz += inval_size;
    4163             : 
    4164         308 :                 ReorderBufferSerializeReserve(rb, sz);
    4165         308 :                 data = ((char *) rb->outbuf) + sizeof(ReorderBufferDiskChange);
    4166             : 
    4167             :                 /* might have been reallocated above */
    4168         308 :                 ondisk = (ReorderBufferDiskChange *) rb->outbuf;
    4169         308 :                 memcpy(data, change->data.inval.invalidations, inval_size);
    4170         308 :                 data += inval_size;
    4171             : 
    4172         308 :                 break;
    4173             :             }
    4174          16 :         case REORDER_BUFFER_CHANGE_INTERNAL_SNAPSHOT:
    4175             :             {
    4176             :                 Snapshot    snap;
    4177             :                 char       *data;
    4178             : 
    4179          16 :                 snap = change->data.snapshot;
    4180             : 
    4181          16 :                 sz += sizeof(SnapshotData) +
    4182          16 :                     sizeof(TransactionId) * snap->xcnt +
    4183          16 :                     sizeof(TransactionId) * snap->subxcnt;
    4184             : 
    4185             :                 /* make sure we have enough space */
    4186          16 :                 ReorderBufferSerializeReserve(rb, sz);
    4187          16 :                 data = ((char *) rb->outbuf) + sizeof(ReorderBufferDiskChange);
    4188             :                 /* might have been reallocated above */
    4189          16 :                 ondisk = (ReorderBufferDiskChange *) rb->outbuf;
    4190             : 
    4191          16 :                 memcpy(data, snap, sizeof(SnapshotData));
    4192          16 :                 data += sizeof(SnapshotData);
    4193             : 
    4194          16 :                 if (snap->xcnt)
    4195             :                 {
    4196          16 :                     memcpy(data, snap->xip,
    4197          16 :                            sizeof(TransactionId) * snap->xcnt);
    4198          16 :                     data += sizeof(TransactionId) * snap->xcnt;
    4199             :                 }
    4200             : 
    4201          16 :                 if (snap->subxcnt)
    4202             :                 {
    4203           0 :                     memcpy(data, snap->subxip,
    4204           0 :                            sizeof(TransactionId) * snap->subxcnt);
    4205           0 :                     data += sizeof(TransactionId) * snap->subxcnt;
    4206             :                 }
    4207          16 :                 break;
    4208             :             }
    4209           4 :         case REORDER_BUFFER_CHANGE_TRUNCATE:
    4210             :             {
    4211             :                 Size        size;
    4212             :                 char       *data;
    4213             : 
    4214             :                 /* account for the OIDs of truncated relations */
    4215           4 :                 size = sizeof(Oid) * change->data.truncate.nrelids;
    4216           4 :                 sz += size;
    4217             : 
    4218             :                 /* make sure we have enough space */
    4219           4 :                 ReorderBufferSerializeReserve(rb, sz);
    4220             : 
    4221           4 :                 data = ((char *) rb->outbuf) + sizeof(ReorderBufferDiskChange);
    4222             :                 /* might have been reallocated above */
    4223           4 :                 ondisk = (ReorderBufferDiskChange *) rb->outbuf;
    4224             : 
    4225           4 :                 memcpy(data, change->data.truncate.relids, size);
    4226           4 :                 data += size;
    4227             : 
    4228           4 :                 break;
    4229             :             }
    4230       34622 :         case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_CONFIRM:
    4231             :         case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_ABORT:
    4232             :         case REORDER_BUFFER_CHANGE_INTERNAL_COMMAND_ID:
    4233             :         case REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID:
    4234             :             /* ReorderBufferChange contains everything important */
    4235       34622 :             break;
    4236             :     }
    4237             : 
    4238     2590520 :     ondisk->size = sz;
    4239             : 
    4240     2590520 :     errno = 0;
    4241     2590520 :     pgstat_report_wait_start(WAIT_EVENT_REORDER_BUFFER_WRITE);
    4242     2590520 :     if (write(fd, rb->outbuf, ondisk->size) != ondisk->size)
    4243             :     {
    4244           0 :         int         save_errno = errno;
    4245             : 
    4246           0 :         CloseTransientFile(fd);
    4247             : 
    4248             :         /* if write didn't set errno, assume problem is no disk space */
    4249           0 :         errno = save_errno ? save_errno : ENOSPC;
    4250           0 :         ereport(ERROR,
    4251             :                 (errcode_for_file_access(),
    4252             :                  errmsg("could not write to data file for XID %u: %m",
    4253             :                         txn->xid)));
    4254             :     }
    4255     2590520 :     pgstat_report_wait_end();
    4256             : 
    4257             :     /*
    4258             :      * Keep the transaction's final_lsn up to date with each change we send to
    4259             :      * disk, so that ReorderBufferRestoreCleanup works correctly.  (We used to
    4260             :      * only do this on commit and abort records, but that doesn't work if a
    4261             :      * system crash leaves a transaction without its abort record).
    4262             :      *
    4263             :      * Make sure not to move it backwards.
    4264             :      */
    4265     2590520 :     if (txn->final_lsn < change->lsn)
    4266     2581554 :         txn->final_lsn = change->lsn;
    4267             : 
    4268             :     Assert(ondisk->change.action == change->action);
    4269     2590520 : }
    4270             : 
    4271             : /* Returns true, if the output plugin supports streaming, false, otherwise. */
    4272             : static inline bool
    4273     3706398 : ReorderBufferCanStream(ReorderBuffer *rb)
    4274             : {
    4275     3706398 :     LogicalDecodingContext *ctx = rb->private_data;
    4276             : 
    4277     3706398 :     return ctx->streaming;
    4278             : }
    4279             : 
    4280             : /* Returns true, if the streaming can be started now, false, otherwise. */
    4281             : static inline bool
    4282      647170 : ReorderBufferCanStartStreaming(ReorderBuffer *rb)
    4283             : {
    4284      647170 :     LogicalDecodingContext *ctx = rb->private_data;
    4285      647170 :     SnapBuild  *builder = ctx->snapshot_builder;
    4286             : 
    4287             :     /* We can't start streaming unless a consistent state is reached. */
    4288      647170 :     if (SnapBuildCurrentState(builder) < SNAPBUILD_CONSISTENT)
    4289           0 :         return false;
    4290             : 
    4291             :     /*
    4292             :      * We can't start streaming immediately even if the streaming is enabled
    4293             :      * because we previously decoded this transaction and now just are
    4294             :      * restarting.
    4295             :      */
    4296      647170 :     if (ReorderBufferCanStream(rb) &&
    4297      641874 :         !SnapBuildXactNeedsSkip(builder, ctx->reader->ReadRecPtr))
    4298      345402 :         return true;
    4299             : 
    4300      301768 :     return false;
    4301             : }
    4302             : 
    4303             : /*
    4304             :  * Send data of a large transaction (and its subtransactions) to the
    4305             :  * output plugin, but using the stream API.
    4306             :  */
    4307             : static void
    4308        1432 : ReorderBufferStreamTXN(ReorderBuffer *rb, ReorderBufferTXN *txn)
    4309             : {
    4310             :     Snapshot    snapshot_now;
    4311             :     CommandId   command_id;
    4312             :     Size        stream_bytes;
    4313             :     bool        txn_is_streamed;
    4314             : 
    4315             :     /* We can never reach here for a subtransaction. */
    4316             :     Assert(rbtxn_is_toptxn(txn));
    4317             : 
    4318             :     /*
    4319             :      * We can't make any assumptions about base snapshot here, similar to what
    4320             :      * ReorderBufferCommit() does. That relies on base_snapshot getting
    4321             :      * transferred from subxact in ReorderBufferCommitChild(), but that was
    4322             :      * not yet called as the transaction is in-progress.
    4323             :      *
    4324             :      * So just walk the subxacts and use the same logic here. But we only need
    4325             :      * to do that once, when the transaction is streamed for the first time.
    4326             :      * After that we need to reuse the snapshot from the previous run.
    4327             :      *
    4328             :      * Unlike DecodeCommit which adds xids of all the subtransactions in
    4329             :      * snapshot's xip array via SnapBuildCommitTxn, we can't do that here but
    4330             :      * we do add them to subxip array instead via ReorderBufferCopySnap. This
    4331             :      * allows the catalog changes made in subtransactions decoded till now to
    4332             :      * be visible.
    4333             :      */
    4334        1432 :     if (txn->snapshot_now == NULL)
    4335             :     {
    4336             :         dlist_iter  subxact_i;
    4337             : 
    4338             :         /* make sure this transaction is streamed for the first time */
    4339             :         Assert(!rbtxn_is_streamed(txn));
    4340             : 
    4341             :         /* at the beginning we should have invalid command ID */
    4342             :         Assert(txn->command_id == InvalidCommandId);
    4343             : 
    4344         152 :         dlist_foreach(subxact_i, &txn->subtxns)
    4345             :         {
    4346             :             ReorderBufferTXN *subtxn;
    4347             : 
    4348           8 :             subtxn = dlist_container(ReorderBufferTXN, node, subxact_i.cur);
    4349           8 :             ReorderBufferTransferSnapToParent(txn, subtxn);
    4350             :         }
    4351             : 
    4352             :         /*
    4353             :          * If this transaction has no snapshot, it didn't make any changes to
    4354             :          * the database till now, so there's nothing to decode.
    4355             :          */
    4356         144 :         if (txn->base_snapshot == NULL)
    4357             :         {
    4358             :             Assert(txn->ninvalidations == 0);
    4359           0 :             return;
    4360             :         }
    4361             : 
    4362         144 :         command_id = FirstCommandId;
    4363         144 :         snapshot_now = ReorderBufferCopySnap(rb, txn->base_snapshot,
    4364             :                                              txn, command_id);
    4365             :     }
    4366             :     else
    4367             :     {
    4368             :         /* the transaction must have been already streamed */
    4369             :         Assert(rbtxn_is_streamed(txn));
    4370             : 
    4371             :         /*
    4372             :          * Nah, we already have snapshot from the previous streaming run. We
    4373             :          * assume new subxacts can't move the LSN backwards, and so can't beat
    4374             :          * the LSN condition in the previous branch (so no need to walk
    4375             :          * through subxacts again). In fact, we must not do that as we may be
    4376             :          * using snapshot half-way through the subxact.
    4377             :          */
    4378        1288 :         command_id = txn->command_id;
    4379             : 
    4380             :         /*
    4381             :          * We can't use txn->snapshot_now directly because after the last
    4382             :          * streaming run, we might have got some new sub-transactions. So we
    4383             :          * need to add them to the snapshot.
    4384             :          */
    4385        1288 :         snapshot_now = ReorderBufferCopySnap(rb, txn->snapshot_now,
    4386             :                                              txn, command_id);
    4387             : 
    4388             :         /* Free the previously copied snapshot. */
    4389             :         Assert(txn->snapshot_now->copied);
    4390        1288 :         ReorderBufferFreeSnap(rb, txn->snapshot_now);
    4391        1288 :         txn->snapshot_now = NULL;
    4392             :     }
    4393             : 
    4394             :     /*
    4395             :      * Remember this information to be used later to update stats. We can't
    4396             :      * update the stats here as an error while processing the changes would
    4397             :      * lead to the accumulation of stats even though we haven't streamed all
    4398             :      * the changes.
    4399             :      */
    4400        1432 :     txn_is_streamed = rbtxn_is_streamed(txn);
    4401        1432 :     stream_bytes = txn->total_size;
    4402             : 
    4403             :     /* Process and send the changes to output plugin. */
    4404        1432 :     ReorderBufferProcessTXN(rb, txn, InvalidXLogRecPtr, snapshot_now,
    4405             :                             command_id, true);
    4406             : 
    4407        1432 :     rb->streamCount += 1;
    4408        1432 :     rb->streamBytes += stream_bytes;
    4409             : 
    4410             :     /* Don't consider already streamed transaction. */
    4411        1432 :     rb->streamTxns += (txn_is_streamed) ? 0 : 1;
    4412             : 
    4413             :     /* update the decoding stats */
    4414        1432 :     UpdateDecodingStats((LogicalDecodingContext *) rb->private_data);
    4415             : 
    4416             :     Assert(dlist_is_empty(&txn->changes));
    4417             :     Assert(txn->nentries == 0);
    4418             :     Assert(txn->nentries_mem == 0);
    4419             : }
    4420             : 
    4421             : /*
    4422             :  * Size of a change in memory.
    4423             :  */
    4424             : static Size
    4425     4288418 : ReorderBufferChangeSize(ReorderBufferChange *change)
    4426             : {
    4427     4288418 :     Size        sz = sizeof(ReorderBufferChange);
    4428             : 
    4429     4288418 :     switch (change->action)
    4430             :     {
    4431             :             /* fall through these, they're all similar enough */
    4432     4079656 :         case REORDER_BUFFER_CHANGE_INSERT:
    4433             :         case REORDER_BUFFER_CHANGE_UPDATE:
    4434             :         case REORDER_BUFFER_CHANGE_DELETE:
    4435             :         case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_INSERT:
    4436             :             {
    4437             :                 HeapTuple   oldtup,
    4438             :                             newtup;
    4439     4079656 :                 Size        oldlen = 0;
    4440     4079656 :                 Size        newlen = 0;
    4441             : 
    4442     4079656 :                 oldtup = change->data.tp.oldtuple;
    4443     4079656 :                 newtup = change->data.tp.newtuple;
    4444             : 
    4445     4079656 :                 if (oldtup)
    4446             :                 {
    4447      390320 :                     sz += sizeof(HeapTupleData);
    4448      390320 :                     oldlen = oldtup->t_len;
    4449      390320 :                     sz += oldlen;
    4450             :                 }
    4451             : 
    4452     4079656 :                 if (newtup)
    4453             :                 {
    4454     3523510 :                     sz += sizeof(HeapTupleData);
    4455     3523510 :                     newlen = newtup->t_len;
    4456     3523510 :                     sz += newlen;
    4457             :                 }
    4458             : 
    4459     4079656 :                 break;
    4460             :             }
    4461         134 :         case REORDER_BUFFER_CHANGE_MESSAGE:
    4462             :             {
    4463         134 :                 Size        prefix_size = strlen(change->data.msg.prefix) + 1;
    4464             : 
    4465         134 :                 sz += prefix_size + change->data.msg.message_size +
    4466             :                     sizeof(Size) + sizeof(Size);
    4467             : 
    4468         134 :                 break;
    4469             :             }
    4470       19006 :         case REORDER_BUFFER_CHANGE_INVALIDATION:
    4471             :             {
    4472       19006 :                 sz += sizeof(SharedInvalidationMessage) *
    4473       19006 :                     change->data.inval.ninvalidations;
    4474       19006 :                 break;
    4475             :             }
    4476        4332 :         case REORDER_BUFFER_CHANGE_INTERNAL_SNAPSHOT:
    4477             :             {
    4478             :                 Snapshot    snap;
    4479             : 
    4480        4332 :                 snap = change->data.snapshot;
    4481             : 
    4482        4332 :                 sz += sizeof(SnapshotData) +
    4483        4332 :                     sizeof(TransactionId) * snap->xcnt +
    4484        4332 :                     sizeof(TransactionId) * snap->subxcnt;
    4485             : 
    4486        4332 :                 break;
    4487             :             }
    4488         126 :         case REORDER_BUFFER_CHANGE_TRUNCATE:
    4489             :             {
    4490         126 :                 sz += sizeof(Oid) * change->data.truncate.nrelids;
    4491             : 
    4492         126 :                 break;
    4493             :             }
    4494      185164 :         case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_CONFIRM:
    4495             :         case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_ABORT:
    4496             :         case REORDER_BUFFER_CHANGE_INTERNAL_COMMAND_ID:
    4497             :         case REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID:
    4498             :             /* ReorderBufferChange contains everything important */
    4499      185164 :             break;
    4500             :     }
    4501             : 
    4502     4288418 :     return sz;
    4503             : }
    4504             : 
    4505             : 
    4506             : /*
    4507             :  * Restore a number of changes spilled to disk back into memory.
    4508             :  */
    4509             : static Size
    4510         210 : ReorderBufferRestoreChanges(ReorderBuffer *rb, ReorderBufferTXN *txn,
    4511             :                             TXNEntryFile *file, XLogSegNo *segno)
    4512             : {
    4513         210 :     Size        restored = 0;
    4514             :     XLogSegNo   last_segno;
    4515             :     dlist_mutable_iter cleanup_iter;
    4516         210 :     File       *fd = &file->vfd;
    4517             : 
    4518             :     Assert(txn->first_lsn != InvalidXLogRecPtr);
    4519             :     Assert(txn->final_lsn != InvalidXLogRecPtr);
    4520             : 
    4521             :     /* free current entries, so we have memory for more */
    4522      349352 :     dlist_foreach_modify(cleanup_iter, &txn->changes)
    4523             :     {
    4524      349142 :         ReorderBufferChange *cleanup =
    4525      349142 :             dlist_container(ReorderBufferChange, node, cleanup_iter.cur);
    4526             : 
    4527      349142 :         dlist_delete(&cleanup->node);
    4528      349142 :         ReorderBufferFreeChange(rb, cleanup, true);
    4529             :     }
    4530         210 :     txn->nentries_mem = 0;
    4531             :     Assert(dlist_is_empty(&txn->changes));
    4532             : 
    4533         210 :     XLByteToSeg(txn->final_lsn, last_segno, wal_segment_size);
    4534             : 
    4535      356762 :     while (restored < max_changes_in_memory && *segno <= last_segno)
    4536             :     {
    4537             :         int         readBytes;
    4538             :         ReorderBufferDiskChange *ondisk;
    4539             : 
    4540      356552 :         CHECK_FOR_INTERRUPTS();
    4541             : 
    4542      356552 :         if (*fd == -1)
    4543             :         {
    4544             :             char        path[MAXPGPATH];
    4545             : 
    4546             :             /* first time in */
    4547          84 :             if (*segno == 0)
    4548          80 :                 XLByteToSeg(txn->first_lsn, *segno, wal_segment_size);
    4549             : 
    4550             :             Assert(*segno != 0 || dlist_is_empty(&txn->changes));
    4551             : 
    4552             :             /*
    4553             :              * No need to care about TLIs here, only used during a single run,
    4554             :              * so each LSN only maps to a specific WAL record.
    4555             :              */
    4556          84 :             ReorderBufferSerializedPath(path, MyReplicationSlot, txn->xid,
    4557             :                                         *segno);
    4558             : 
    4559          84 :             *fd = PathNameOpenFile(path, O_RDONLY | PG_BINARY);
    4560             : 
    4561             :             /* No harm in resetting the offset even in case of failure */
    4562          84 :             file->curOffset = 0;
    4563             : 
    4564          84 :             if (*fd < 0 && errno == ENOENT)
    4565             :             {
    4566           0 :                 *fd = -1;
    4567           0 :                 (*segno)++;
    4568           0 :                 continue;
    4569             :             }
    4570          84 :             else if (*fd < 0)
    4571           0 :                 ereport(ERROR,
    4572             :                         (errcode_for_file_access(),
    4573             :                          errmsg("could not open file \"%s\": %m",
    4574             :                                 path)));
    4575             :         }
    4576             : 
    4577             :         /*
    4578             :          * Read the statically sized part of a change which has information
    4579             :          * about the total size. If we couldn't read a record, we're at the
    4580             :          * end of this file.
    4581             :          */
    4582      356552 :         ReorderBufferSerializeReserve(rb, sizeof(ReorderBufferDiskChange));
    4583      356552 :         readBytes = FileRead(file->vfd, rb->outbuf,
    4584             :                              sizeof(ReorderBufferDiskChange),
    4585             :                              file->curOffset, WAIT_EVENT_REORDER_BUFFER_READ);
    4586             : 
    4587             :         /* eof */
    4588      356552 :         if (readBytes == 0)
    4589             :         {
    4590          84 :             FileClose(*fd);
    4591          84 :             *fd = -1;
    4592          84 :             (*segno)++;
    4593          84 :             continue;
    4594             :         }
    4595      356468 :         else if (readBytes < 0)
    4596           0 :             ereport(ERROR,
    4597             :                     (errcode_for_file_access(),
    4598             :                      errmsg("could not read from reorderbuffer spill file: %m")));
    4599      356468 :         else if (readBytes != sizeof(ReorderBufferDiskChange))
    4600           0 :             ereport(ERROR,
    4601             :                     (errcode_for_file_access(),
    4602             :                      errmsg("could not read from reorderbuffer spill file: read %d instead of %u bytes",
    4603             :                             readBytes,
    4604             :                             (uint32) sizeof(ReorderBufferDiskChange))));
    4605             : 
    4606      356468 :         file->curOffset += readBytes;
    4607             : 
    4608      356468 :         ondisk = (ReorderBufferDiskChange *) rb->outbuf;
    4609             : 
    4610      356468 :         ReorderBufferSerializeReserve(rb,
    4611      356468 :                                       sizeof(ReorderBufferDiskChange) + ondisk->size);
    4612      356468 :         ondisk = (ReorderBufferDiskChange *) rb->outbuf;
    4613             : 
    4614      712936 :         readBytes = FileRead(file->vfd,
    4615      356468 :                              rb->outbuf + sizeof(ReorderBufferDiskChange),
    4616      356468 :                              ondisk->size - sizeof(ReorderBufferDiskChange),
    4617             :                              file->curOffset,
    4618             :                              WAIT_EVENT_REORDER_BUFFER_READ);
    4619             : 
    4620      356468 :         if (readBytes < 0)
    4621           0 :             ereport(ERROR,
    4622             :                     (errcode_for_file_access(),
    4623             :                      errmsg("could not read from reorderbuffer spill file: %m")));
    4624      356468 :         else if (readBytes != ondisk->size - sizeof(ReorderBufferDiskChange))
    4625           0 :             ereport(ERROR,
    4626             :                     (errcode_for_file_access(),
    4627             :                      errmsg("could not read from reorderbuffer spill file: read %d instead of %u bytes",
    4628             :                             readBytes,
    4629             :                             (uint32) (ondisk->size - sizeof(ReorderBufferDiskChange)))));
    4630             : 
    4631      356468 :         file->curOffset += readBytes;
    4632             : 
    4633             :         /*
    4634             :          * ok, read a full change from disk, now restore it into proper
    4635             :          * in-memory format
    4636             :          */
    4637      356468 :         ReorderBufferRestoreChange(rb, txn, rb->outbuf);
    4638      356468 :         restored++;
    4639             :     }
    4640             : 
    4641         210 :     return restored;
    4642             : }
    4643             : 
    4644             : /*
    4645             :  * Convert change from its on-disk format to in-memory format and queue it onto
    4646             :  * the TXN's ->changes list.
    4647             :  *
    4648             :  * Note: although "data" is declared char*, at entry it points to a
    4649             :  * maxalign'd buffer, making it safe in most of this function to assume
    4650             :  * that the pointed-to data is suitably aligned for direct access.
    4651             :  */
    4652             : static void
    4653      356468 : ReorderBufferRestoreChange(ReorderBuffer *rb, ReorderBufferTXN *txn,
    4654             :                            char *data)
    4655             : {
    4656             :     ReorderBufferDiskChange *ondisk;
    4657             :     ReorderBufferChange *change;
    4658             : 
    4659      356468 :     ondisk = (ReorderBufferDiskChange *) data;
    4660             : 
    4661      356468 :     change = ReorderBufferAllocChange(rb);
    4662             : 
    4663             :     /* copy static part */
    4664      356468 :     memcpy(change, &ondisk->change, sizeof(ReorderBufferChange));
    4665             : 
    4666      356468 :     data += sizeof(ReorderBufferDiskChange);
    4667             : 
    4668             :     /* restore individual stuff */
    4669      356468 :     switch (change->action)
    4670             :     {
    4671             :             /* fall through these, they're all similar enough */
    4672      352610 :         case REORDER_BUFFER_CHANGE_INSERT:
    4673             :         case REORDER_BUFFER_CHANGE_UPDATE:
    4674             :         case REORDER_BUFFER_CHANGE_DELETE:
    4675             :         case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_INSERT:
    4676      352610 :             if (change->data.tp.oldtuple)
    4677             :             {
    4678       10012 :                 uint32      tuplelen = ((HeapTuple) data)->t_len;
    4679             : 
    4680       10012 :                 change->data.tp.oldtuple =
    4681       10012 :                     ReorderBufferAllocTupleBuf(rb, tuplelen - SizeofHeapTupleHeader);
    4682             : 
    4683             :                 /* restore ->tuple */
    4684       10012 :                 memcpy(change->data.tp.oldtuple, data,
    4685             :                        sizeof(HeapTupleData));
    4686       10012 :                 data += sizeof(HeapTupleData);
    4687             : 
    4688             :                 /* reset t_data pointer into the new tuplebuf */
    4689       10012 :                 change->data.tp.oldtuple->t_data =
    4690       10012 :                     (HeapTupleHeader) ((char *) change->data.tp.oldtuple + HEAPTUPLESIZE);
    4691             : 
    4692             :                 /* restore tuple data itself */
    4693       10012 :                 memcpy(change->data.tp.oldtuple->t_data, data, tuplelen);
    4694       10012 :                 data += tuplelen;
    4695             :             }
    4696             : 
    4697      352610 :             if (change->data.tp.newtuple)
    4698             :             {
    4699             :                 /* here, data might not be suitably aligned! */
    4700             :                 uint32      tuplelen;
    4701             : 
    4702      332168 :                 memcpy(&tuplelen, data + offsetof(HeapTupleData, t_len),
    4703             :                        sizeof(uint32));
    4704             : 
    4705      332168 :                 change->data.tp.newtuple =
    4706      332168 :                     ReorderBufferAllocTupleBuf(rb, tuplelen - SizeofHeapTupleHeader);
    4707             : 
    4708             :                 /* restore ->tuple */
    4709      332168 :                 memcpy(change->data.tp.newtuple, data,
    4710             :                        sizeof(HeapTupleData));
    4711      332168 :                 data += sizeof(HeapTupleData);
    4712             : 
    4713             :                 /* reset t_data pointer into the new tuplebuf */
    4714      332168 :                 change->data.tp.newtuple->t_data =
    4715      332168 :                     (HeapTupleHeader) ((char *) change->data.tp.newtuple + HEAPTUPLESIZE);
    4716             : 
    4717             :                 /* restore tuple data itself */
    4718      332168 :                 memcpy(change->data.tp.newtuple->t_data, data, tuplelen);
    4719      332168 :                 data += tuplelen;
    4720             :             }
    4721             : 
    4722      352610 :             break;
    4723           2 :         case REORDER_BUFFER_CHANGE_MESSAGE:
    4724             :             {
    4725             :                 Size        prefix_size;
    4726             : 
    4727             :                 /* read prefix */
    4728           2 :                 memcpy(&prefix_size, data, sizeof(Size));
    4729           2 :                 data += sizeof(Size);
    4730           2 :                 change->data.msg.prefix = MemoryContextAlloc(rb->context,
    4731             :                                                              prefix_size);
    4732           2 :                 memcpy(change->data.msg.prefix, data, prefix_size);
    4733             :                 Assert(change->data.msg.prefix[prefix_size - 1] == '\0');
    4734           2 :                 data += prefix_size;
    4735             : 
    4736             :                 /* read the message */
    4737           2 :                 memcpy(&change->data.msg.message_size, data, sizeof(Size));
    4738           2 :                 data += sizeof(Size);
    4739           2 :                 change->data.msg.message = MemoryContextAlloc(rb->context,
    4740             :                                                               change->data.msg.message_size);
    4741           2 :                 memcpy(change->data.msg.message, data,
    4742             :                        change->data.msg.message_size);
    4743           2 :                 data += change->data.msg.message_size;
    4744             : 
    4745           2 :                 break;
    4746             :             }
    4747          46 :         case REORDER_BUFFER_CHANGE_INVALIDATION:
    4748             :             {
    4749          46 :                 Size        inval_size = sizeof(SharedInvalidationMessage) *
    4750          46 :                     change->data.inval.ninvalidations;
    4751             : 
    4752          46 :                 change->data.inval.invalidations =
    4753          46 :                     MemoryContextAlloc(rb->context, inval_size);
    4754             : 
    4755             :                 /* read the message */
    4756          46 :                 memcpy(change->data.inval.invalidations, data, inval_size);
    4757             : 
    4758          46 :                 break;
    4759             :             }
    4760           4 :         case REORDER_BUFFER_CHANGE_INTERNAL_SNAPSHOT:
    4761             :             {
    4762             :                 Snapshot    oldsnap;
    4763             :                 Snapshot    newsnap;
    4764             :                 Size        size;
    4765             : 
    4766           4 :                 oldsnap = (Snapshot) data;
    4767             : 
    4768           4 :                 size = sizeof(SnapshotData) +
    4769           4 :                     sizeof(TransactionId) * oldsnap->xcnt +
    4770           4 :                     sizeof(TransactionId) * (oldsnap->subxcnt + 0);
    4771             : 
    4772           4 :                 change->data.snapshot = MemoryContextAllocZero(rb->context, size);
    4773             : 
    4774           4 :                 newsnap = change->data.snapshot;
    4775             : 
    4776           4 :                 memcpy(newsnap, data, size);
    4777           4 :                 newsnap->xip = (TransactionId *)
    4778             :                     (((char *) newsnap) + sizeof(SnapshotData));
    4779           4 :                 newsnap->subxip = newsnap->xip + newsnap->xcnt;
    4780           4 :                 newsnap->copied = true;
    4781           4 :                 break;
    4782             :             }
    4783             :             /* the base struct contains all the data, easy peasy */
    4784           0 :         case REORDER_BUFFER_CHANGE_TRUNCATE:
    4785             :             {
    4786             :                 Oid        *relids;
    4787             : 
    4788           0 :                 relids = ReorderBufferAllocRelids(rb, change->data.truncate.nrelids);
    4789           0 :                 memcpy(relids, data, change->data.truncate.nrelids * sizeof(Oid));
    4790           0 :                 change->data.truncate.relids = relids;
    4791             : 
    4792           0 :                 break;
    4793             :             }
    4794        3806 :         case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_CONFIRM:
    4795             :         case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_ABORT:
    4796             :         case REORDER_BUFFER_CHANGE_INTERNAL_COMMAND_ID:
    4797             :         case REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID:
    4798        3806 :             break;
    4799             :     }
    4800             : 
    4801      356468 :     dlist_push_tail(&txn->changes, &change->node);
    4802      356468 :     txn->nentries_mem++;
    4803             : 
    4804             :     /*
    4805             :      * Update memory accounting for the restored change.  We need to do this
    4806             :      * although we don't check the memory limit when restoring the changes in
    4807             :      * this branch (we only do that when initially queueing the changes after
    4808             :      * decoding), because we will release the changes later, and that will
    4809             :      * update the accounting too (subtracting the size from the counters). And
    4810             :      * we don't want to underflow there.
    4811             :      */
    4812      356468 :     ReorderBufferChangeMemoryUpdate(rb, change, NULL, true,
    4813             :                                     ReorderBufferChangeSize(change));
    4814      356468 : }
    4815             : 
    4816             : /*
    4817             :  * Remove all on-disk stored for the passed in transaction.
    4818             :  */
    4819             : static void
    4820         570 : ReorderBufferRestoreCleanup(ReorderBuffer *rb, ReorderBufferTXN *txn)
    4821             : {
    4822             :     XLogSegNo   first;
    4823             :     XLogSegNo   cur;
    4824             :     XLogSegNo   last;
    4825             : 
    4826             :     Assert(txn->first_lsn != InvalidXLogRecPtr);
    4827             :     Assert(txn->final_lsn != InvalidXLogRecPtr);
    4828             : 
    4829         570 :     XLByteToSeg(txn->first_lsn, first, wal_segment_size);
    4830         570 :     XLByteToSeg(txn->final_lsn, last, wal_segment_size);
    4831             : 
    4832             :     /* iterate over all possible filenames, and delete them */
    4833        1158 :     for (cur = first; cur <= last; cur++)
    4834             :     {
    4835             :         char        path[MAXPGPATH];
    4836             : 
    4837         588 :         ReorderBufferSerializedPath(path, MyReplicationSlot, txn->xid, cur);
    4838         588 :         if (unlink(path) != 0 && errno != ENOENT)
    4839           0 :             ereport(ERROR,
    4840             :                     (errcode_for_file_access(),
    4841             :                      errmsg("could not remove file \"%s\": %m", path)));
    4842             :     }
    4843         570 : }
    4844             : 
    4845             : /*
    4846             :  * Remove any leftover serialized reorder buffers from a slot directory after a
    4847             :  * prior crash or decoding session exit.
    4848             :  */
    4849             : static void
    4850        3976 : ReorderBufferCleanupSerializedTXNs(const char *slotname)
    4851             : {
    4852             :     DIR        *spill_dir;
    4853             :     struct dirent *spill_de;
    4854             :     struct stat statbuf;
    4855             :     char        path[MAXPGPATH * 2 + sizeof(PG_REPLSLOT_DIR)];
    4856             : 
    4857        3976 :     sprintf(path, "%s/%s", PG_REPLSLOT_DIR, slotname);
    4858             : 
    4859             :     /* we're only handling directories here, skip if it's not ours */
    4860        3976 :     if (lstat(path, &statbuf) == 0 && !S_ISDIR(statbuf.st_mode))
    4861           0 :         return;
    4862             : 
    4863        3976 :     spill_dir = AllocateDir(path);
    4864       19880 :     while ((spill_de = ReadDirExtended(spill_dir, path, INFO)) != NULL)
    4865             :     {
    4866             :         /* only look at names that can be ours */
    4867       11928 :         if (strncmp(spill_de->d_name, "xid", 3) == 0)
    4868             :         {
    4869           0 :             snprintf(path, sizeof(path),
    4870             :                      "%s/%s/%s", PG_REPLSLOT_DIR, slotname,
    4871           0 :                      spill_de->d_name);
    4872             : 
    4873           0 :             if (unlink(path) != 0)
    4874           0 :                 ereport(ERROR,
    4875             :                         (errcode_for_file_access(),
    4876             :                          errmsg("could not remove file \"%s\" during removal of %s/%s/xid*: %m",
    4877             :                                 path, PG_REPLSLOT_DIR, slotname)));
    4878             :         }
    4879             :     }
    4880        3976 :     FreeDir(spill_dir);
    4881             : }
    4882             : 
    4883             : /*
    4884             :  * Given a replication slot, transaction ID and segment number, fill in the
    4885             :  * corresponding spill file into 'path', which is a caller-owned buffer of size
    4886             :  * at least MAXPGPATH.
    4887             :  */
    4888             : static void
    4889        8218 : ReorderBufferSerializedPath(char *path, ReplicationSlot *slot, TransactionId xid,
    4890             :                             XLogSegNo segno)
    4891             : {
    4892             :     XLogRecPtr  recptr;
    4893             : 
    4894        8218 :     XLogSegNoOffsetToRecPtr(segno, 0, wal_segment_size, recptr);
    4895             : 
    4896        8218 :     snprintf(path, MAXPGPATH, "%s/%s/xid-%u-lsn-%X-%X.spill",
    4897             :              PG_REPLSLOT_DIR,
    4898        8218 :              NameStr(MyReplicationSlot->data.name),
    4899        8218 :              xid, LSN_FORMAT_ARGS(recptr));
    4900        8218 : }
    4901             : 
    4902             : /*
    4903             :  * Delete all data spilled to disk after we've restarted/crashed. It will be
    4904             :  * recreated when the respective slots are reused.
    4905             :  */
    4906             : void
    4907        1844 : StartupReorderBuffer(void)
    4908             : {
    4909             :     DIR        *logical_dir;
    4910             :     struct dirent *logical_de;
    4911             : 
    4912        1844 :     logical_dir = AllocateDir(PG_REPLSLOT_DIR);
    4913        5680 :     while ((logical_de = ReadDir(logical_dir, PG_REPLSLOT_DIR)) != NULL)
    4914             :     {
    4915        3836 :         if (strcmp(logical_de->d_name, ".") == 0 ||
    4916        1992 :             strcmp(logical_de->d_name, "..") == 0)
    4917        3688 :             continue;
    4918             : 
    4919             :         /* if it cannot be a slot, skip the directory */
    4920         148 :         if (!ReplicationSlotValidateName(logical_de->d_name, DEBUG2))
    4921           0 :             continue;
    4922             : 
    4923             :         /*
    4924             :          * ok, has to be a surviving logical slot, iterate and delete
    4925             :          * everything starting with xid-*
    4926             :          */
    4927         148 :         ReorderBufferCleanupSerializedTXNs(logical_de->d_name);
    4928             :     }
    4929        1844 :     FreeDir(logical_dir);
    4930        1844 : }
    4931             : 
    4932             : /* ---------------------------------------
    4933             :  * toast reassembly support
    4934             :  * ---------------------------------------
    4935             :  */
    4936             : 
    4937             : /*
    4938             :  * Initialize per tuple toast reconstruction support.
    4939             :  */
    4940             : static void
    4941          70 : ReorderBufferToastInitHash(ReorderBuffer *rb, ReorderBufferTXN *txn)
    4942             : {
    4943             :     HASHCTL     hash_ctl;
    4944             : 
    4945             :     Assert(txn->toast_hash == NULL);
    4946             : 
    4947          70 :     hash_ctl.keysize = sizeof(Oid);
    4948          70 :     hash_ctl.entrysize = sizeof(ReorderBufferToastEnt);
    4949          70 :     hash_ctl.hcxt = rb->context;
    4950          70 :     txn->toast_hash = hash_create("ReorderBufferToastHash", 5, &hash_ctl,
    4951             :                                   HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
    4952          70 : }
    4953             : 
    4954             : /*
    4955             :  * Per toast-chunk handling for toast reconstruction
    4956             :  *
    4957             :  * Appends a toast chunk so we can reconstruct it when the tuple "owning" the
    4958             :  * toasted Datum comes along.
    4959             :  */
    4960             : static void
    4961        3660 : ReorderBufferToastAppendChunk(ReorderBuffer *rb, ReorderBufferTXN *txn,
    4962             :                               Relation relation, ReorderBufferChange *change)
    4963             : {
    4964             :     ReorderBufferToastEnt *ent;
    4965             :     HeapTuple   newtup;
    4966             :     bool        found;
    4967             :     int32       chunksize;
    4968             :     bool        isnull;
    4969             :     Pointer     chunk;
    4970        3660 :     TupleDesc   desc = RelationGetDescr(relation);
    4971             :     Oid         chunk_id;
    4972             :     int32       chunk_seq;
    4973             : 
    4974        3660 :     if (txn->toast_hash == NULL)
    4975          70 :         ReorderBufferToastInitHash(rb, txn);
    4976             : 
    4977             :     Assert(IsToastRelation(relation));
    4978             : 
    4979        3660 :     newtup = change->data.tp.newtuple;
    4980        3660 :     chunk_id = DatumGetObjectId(fastgetattr(newtup, 1, desc, &isnull));
    4981             :     Assert(!isnull);
    4982        3660 :     chunk_seq = DatumGetInt32(fastgetattr(newtup, 2, desc, &isnull));
    4983             :     Assert(!isnull);
    4984             : 
    4985             :     ent = (ReorderBufferToastEnt *)
    4986        3660 :         hash_search(txn->toast_hash, &chunk_id, HASH_ENTER, &found);
    4987             : 
    4988        3660 :     if (!found)
    4989             :     {
    4990             :         Assert(ent->chunk_id == chunk_id);
    4991          98 :         ent->num_chunks = 0;
    4992          98 :         ent->last_chunk_seq = 0;
    4993          98 :         ent->size = 0;
    4994          98 :         ent->reconstructed = NULL;
    4995          98 :         dlist_init(&ent->chunks);
    4996             : 
    4997          98 :         if (chunk_seq != 0)
    4998           0 :             elog(ERROR, "got sequence entry %d for toast chunk %u instead of seq 0",
    4999             :                  chunk_seq, chunk_id);
    5000             :     }
    5001        3562 :     else if (found && chunk_seq != ent->last_chunk_seq + 1)
    5002           0 :         elog(ERROR, "got sequence entry %d for toast chunk %u instead of seq %d",
    5003             :              chunk_seq, chunk_id, ent->last_chunk_seq + 1);
    5004             : 
    5005        3660 :     chunk = DatumGetPointer(fastgetattr(newtup, 3, desc, &isnull));
    5006             :     Assert(!isnull);
    5007             : 
    5008             :     /* calculate size so we can allocate the right size at once later */
    5009        3660 :     if (!VARATT_IS_EXTENDED(chunk))
    5010        3660 :         chunksize = VARSIZE(chunk) - VARHDRSZ;
    5011           0 :     else if (VARATT_IS_SHORT(chunk))
    5012             :         /* could happen due to heap_form_tuple doing its thing */
    5013           0 :         chunksize = VARSIZE_SHORT(chunk) - VARHDRSZ_SHORT;
    5014             :     else
    5015           0 :         elog(ERROR, "unexpected type of toast chunk");
    5016             : 
    5017        3660 :     ent->size += chunksize;
    5018        3660 :     ent->last_chunk_seq = chunk_seq;
    5019        3660 :     ent->num_chunks++;
    5020        3660 :     dlist_push_tail(&ent->chunks, &change->node);
    5021        3660 : }
    5022             : 
    5023             : /*
    5024             :  * Rejigger change->newtuple to point to in-memory toast tuples instead of
    5025             :  * on-disk toast tuples that may no longer exist (think DROP TABLE or VACUUM).
    5026             :  *
    5027             :  * We cannot replace unchanged toast tuples though, so those will still point
    5028             :  * to on-disk toast data.
    5029             :  *
    5030             :  * While updating the existing change with detoasted tuple data, we need to
    5031             :  * update the memory accounting info, because the change size will differ.
    5032             :  * Otherwise the accounting may get out of sync, triggering serialization
    5033             :  * at unexpected times.
    5034             :  *
    5035             :  * We simply subtract size of the change before rejiggering the tuple, and
    5036             :  * then add the new size. This makes it look like the change was removed
    5037             :  * and then added back, except it only tweaks the accounting info.
    5038             :  *
    5039             :  * In particular it can't trigger serialization, which would be pointless
    5040             :  * anyway as it happens during commit processing right before handing
    5041             :  * the change to the output plugin.
    5042             :  */
    5043             : static void
    5044      674298 : ReorderBufferToastReplace(ReorderBuffer *rb, ReorderBufferTXN *txn,
    5045             :                           Relation relation, ReorderBufferChange *change)
    5046             : {
    5047             :     TupleDesc   desc;
    5048             :     int         natt;
    5049             :     Datum      *attrs;
    5050             :     bool       *isnull;
    5051             :     bool       *free;
    5052             :     HeapTuple   tmphtup;
    5053             :     Relation    toast_rel;
    5054             :     TupleDesc   toast_desc;
    5055             :     MemoryContext oldcontext;
    5056             :     HeapTuple   newtup;
    5057             :     Size        old_size;
    5058             : 
    5059             :     /* no toast tuples changed */
    5060      674298 :     if (txn->toast_hash == NULL)
    5061      673806 :         return;
    5062             : 
    5063             :     /*
    5064             :      * We're going to modify the size of the change. So, to make sure the
    5065             :      * accounting is correct we record the current change size and then after
    5066             :      * re-computing the change we'll subtract the recorded size and then
    5067             :      * re-add the new change size at the end. We don't immediately subtract
    5068             :      * the old size because if there is any error before we add the new size,
    5069             :      * we will release the changes and that will update the accounting info
    5070             :      * (subtracting the size from the counters). And we don't want to
    5071             :      * underflow there.
    5072             :      */
    5073         492 :     old_size = ReorderBufferChangeSize(change);
    5074             : 
    5075         492 :     oldcontext = MemoryContextSwitchTo(rb->context);
    5076             : 
    5077             :     /* we should only have toast tuples in an INSERT or UPDATE */
    5078             :     Assert(change->data.tp.newtuple);
    5079             : 
    5080         492 :     desc = RelationGetDescr(relation);
    5081             : 
    5082         492 :     toast_rel = RelationIdGetRelation(relation->rd_rel->reltoastrelid);
    5083         492 :     if (!RelationIsValid(toast_rel))
    5084           0 :         elog(ERROR, "could not open toast relation with OID %u (base relation \"%s\")",
    5085             :              relation->rd_rel->reltoastrelid, RelationGetRelationName(relation));
    5086             : 
    5087         492 :     toast_desc = RelationGetDescr(toast_rel);
    5088             : 
    5089             :     /* should we allocate from stack instead? */
    5090         492 :     attrs = palloc0(sizeof(Datum) * desc->natts);
    5091         492 :     isnull = palloc0(sizeof(bool) * desc->natts);
    5092         492 :     free = palloc0(sizeof(bool) * desc->natts);
    5093             : 
    5094         492 :     newtup = change->data.tp.newtuple;
    5095             : 
    5096         492 :     heap_deform_tuple(newtup, desc, attrs, isnull);
    5097             : 
    5098        1514 :     for (natt = 0; natt < desc->natts; natt++)
    5099             :     {
    5100        1022 :         Form_pg_attribute attr = TupleDescAttr(desc, natt);
    5101             :         ReorderBufferToastEnt *ent;
    5102             :         struct varlena *varlena;
    5103             : 
    5104             :         /* va_rawsize is the size of the original datum -- including header */
    5105             :         struct varatt_external toast_pointer;
    5106             :         struct varatt_indirect redirect_pointer;
    5107        1022 :         struct varlena *new_datum = NULL;
    5108             :         struct varlena *reconstructed;
    5109             :         dlist_iter  it;
    5110        1022 :         Size        data_done = 0;
    5111             : 
    5112             :         /* system columns aren't toasted */
    5113        1022 :         if (attr->attnum < 0)
    5114         926 :             continue;
    5115             : 
    5116        1022 :         if (attr->attisdropped)
    5117           0 :             continue;
    5118             : 
    5119             :         /* not a varlena datatype */
    5120        1022 :         if (attr->attlen != -1)
    5121         482 :             continue;
    5122             : 
    5123             :         /* no data */
    5124         540 :         if (isnull[natt])
    5125          24 :             continue;
    5126             : 
    5127             :         /* ok, we know we have a toast datum */
    5128         516 :         varlena = (struct varlena *) DatumGetPointer(attrs[natt]);
    5129             : 
    5130             :         /* no need to do anything if the tuple isn't external */
    5131         516 :         if (!VARATT_IS_EXTERNAL(varlena))
    5132         404 :             continue;
    5133             : 
    5134         112 :         VARATT_EXTERNAL_GET_POINTER(toast_pointer, varlena);
    5135             : 
    5136             :         /*
    5137             :          * Check whether the toast tuple changed, replace if so.
    5138             :          */
    5139             :         ent = (ReorderBufferToastEnt *)
    5140         112 :             hash_search(txn->toast_hash,
    5141             :                         &toast_pointer.va_valueid,
    5142             :                         HASH_FIND,
    5143             :                         NULL);
    5144         112 :         if (ent == NULL)
    5145          16 :             continue;
    5146             : 
    5147             :         new_datum =
    5148          96 :             (struct varlena *) palloc0(INDIRECT_POINTER_SIZE);
    5149             : 
    5150          96 :         free[natt] = true;
    5151             : 
    5152          96 :         reconstructed = palloc0(toast_pointer.va_rawsize);
    5153             : 
    5154          96 :         ent->reconstructed = reconstructed;
    5155             : 
    5156             :         /* stitch toast tuple back together from its parts */
    5157        3654 :         dlist_foreach(it, &ent->chunks)
    5158             :         {
    5159             :             bool        cisnull;
    5160             :             ReorderBufferChange *cchange;
    5161             :             HeapTuple   ctup;
    5162             :             Pointer     chunk;
    5163             : 
    5164        3558 :             cchange = dlist_container(ReorderBufferChange, node, it.cur);
    5165        3558 :             ctup = cchange->data.tp.newtuple;
    5166        3558 :             chunk = DatumGetPointer(fastgetattr(ctup, 3, toast_desc, &cisnull));
    5167             : 
    5168             :             Assert(!cisnull);
    5169             :             Assert(!VARATT_IS_EXTERNAL(chunk));
    5170             :             Assert(!VARATT_IS_SHORT(chunk));
    5171             : 
    5172        3558 :             memcpy(VARDATA(reconstructed) + data_done,
    5173        3558 :                    VARDATA(chunk),
    5174        3558 :                    VARSIZE(chunk) - VARHDRSZ);
    5175        3558 :             data_done += VARSIZE(chunk) - VARHDRSZ;
    5176             :         }
    5177             :         Assert(data_done == VARATT_EXTERNAL_GET_EXTSIZE(toast_pointer));
    5178             : 
    5179             :         /* make sure its marked as compressed or not */
    5180          96 :         if (VARATT_EXTERNAL_IS_COMPRESSED(toast_pointer))
    5181          10 :             SET_VARSIZE_COMPRESSED(reconstructed, data_done + VARHDRSZ);
    5182             :         else
    5183          86 :             SET_VARSIZE(reconstructed, data_done + VARHDRSZ);
    5184             : 
    5185          96 :         memset(&redirect_pointer, 0, sizeof(redirect_pointer));
    5186          96 :         redirect_pointer.pointer = reconstructed;
    5187             : 
    5188          96 :         SET_VARTAG_EXTERNAL(new_datum, VARTAG_INDIRECT);
    5189          96 :         memcpy(VARDATA_EXTERNAL(new_datum), &redirect_pointer,
    5190             :                sizeof(redirect_pointer));
    5191             : 
    5192          96 :         attrs[natt] = PointerGetDatum(new_datum);
    5193             :     }
    5194             : 
    5195             :     /*
    5196             :      * Build tuple in separate memory & copy tuple back into the tuplebuf
    5197             :      * passed to the output plugin. We can't directly heap_fill_tuple() into
    5198             :      * the tuplebuf because attrs[] will point back into the current content.
    5199             :      */
    5200         492 :     tmphtup = heap_form_tuple(desc, attrs, isnull);
    5201             :     Assert(newtup->t_len <= MaxHeapTupleSize);
    5202             :     Assert(newtup->t_data == (HeapTupleHeader) ((char *) newtup + HEAPTUPLESIZE));
    5203             : 
    5204         492 :     memcpy(newtup->t_data, tmphtup->t_data, tmphtup->t_len);
    5205         492 :     newtup->t_len = tmphtup->t_len;
    5206             : 
    5207             :     /*
    5208             :      * free resources we won't further need, more persistent stuff will be
    5209             :      * free'd in ReorderBufferToastReset().
    5210             :      */
    5211         492 :     RelationClose(toast_rel);
    5212         492 :     pfree(tmphtup);
    5213        1514 :     for (natt = 0; natt < desc->natts; natt++)
    5214             :     {
    5215        1022 :         if (free[natt])
    5216          96 :             pfree(DatumGetPointer(attrs[natt]));
    5217             :     }
    5218         492 :     pfree(attrs);
    5219         492 :     pfree(free);
    5220         492 :     pfree(isnull);
    5221             : 
    5222         492 :     MemoryContextSwitchTo(oldcontext);
    5223             : 
    5224             :     /* subtract the old change size */
    5225         492 :     ReorderBufferChangeMemoryUpdate(rb, change, NULL, false, old_size);
    5226             :     /* now add the change back, with the correct size */
    5227         492 :     ReorderBufferChangeMemoryUpdate(rb, change, NULL, true,
    5228             :                                     ReorderBufferChangeSize(change));
    5229             : }
    5230             : 
    5231             : /*
    5232             :  * Free all resources allocated for toast reconstruction.
    5233             :  */
    5234             : static void
    5235      680876 : ReorderBufferToastReset(ReorderBuffer *rb, ReorderBufferTXN *txn)
    5236             : {
    5237             :     HASH_SEQ_STATUS hstat;
    5238             :     ReorderBufferToastEnt *ent;
    5239             : 
    5240      680876 :     if (txn->toast_hash == NULL)
    5241      680806 :         return;
    5242             : 
    5243             :     /* sequentially walk over the hash and free everything */
    5244          70 :     hash_seq_init(&hstat, txn->toast_hash);
    5245         168 :     while ((ent = (ReorderBufferToastEnt *) hash_seq_search(&hstat)) != NULL)
    5246             :     {
    5247             :         dlist_mutable_iter it;
    5248             : 
    5249          98 :         if (ent->reconstructed != NULL)
    5250          96 :             pfree(ent->reconstructed);
    5251             : 
    5252        3758 :         dlist_foreach_modify(it, &ent->chunks)
    5253             :         {
    5254        3660 :             ReorderBufferChange *change =
    5255        3660 :                 dlist_container(ReorderBufferChange, node, it.cur);
    5256             : 
    5257        3660 :             dlist_delete(&change->node);
    5258        3660 :             ReorderBufferFreeChange(rb, change, true);
    5259             :         }
    5260             :     }
    5261             : 
    5262          70 :     hash_destroy(txn->toast_hash);
    5263          70 :     txn->toast_hash = NULL;
    5264             : }
    5265             : 
    5266             : 
    5267             : /* ---------------------------------------
    5268             :  * Visibility support for logical decoding
    5269             :  *
    5270             :  *
    5271             :  * Lookup actual cmin/cmax values when using decoding snapshot. We can't
    5272             :  * always rely on stored cmin/cmax values because of two scenarios:
    5273             :  *
    5274             :  * * A tuple got changed multiple times during a single transaction and thus
    5275             :  *   has got a combo CID. Combo CIDs are only valid for the duration of a
    5276             :  *   single transaction.
    5277             :  * * A tuple with a cmin but no cmax (and thus no combo CID) got
    5278             :  *   deleted/updated in another transaction than the one which created it
    5279             :  *   which we are looking at right now. As only one of cmin, cmax or combo CID
    5280             :  *   is actually stored in the heap we don't have access to the value we
    5281             :  *   need anymore.
    5282             :  *
    5283             :  * To resolve those problems we have a per-transaction hash of (cmin,
    5284             :  * cmax) tuples keyed by (relfilelocator, ctid) which contains the actual
    5285             :  * (cmin, cmax) values. That also takes care of combo CIDs by simply
    5286             :  * not caring about them at all. As we have the real cmin/cmax values
    5287             :  * combo CIDs aren't interesting.
    5288             :  *
    5289             :  * As we only care about catalog tuples here the overhead of this
    5290             :  * hashtable should be acceptable.
    5291             :  *
    5292             :  * Heap rewrites complicate this a bit, check rewriteheap.c for
    5293             :  * details.
    5294             :  * -------------------------------------------------------------------------
    5295             :  */
    5296             : 
    5297             : /* struct for sorting mapping files by LSN efficiently */
    5298             : typedef struct RewriteMappingFile
    5299             : {
    5300             :     XLogRecPtr  lsn;
    5301             :     char        fname[MAXPGPATH];
    5302             : } RewriteMappingFile;
    5303             : 
    5304             : #ifdef NOT_USED
    5305             : static void
    5306             : DisplayMapping(HTAB *tuplecid_data)
    5307             : {
    5308             :     HASH_SEQ_STATUS hstat;
    5309             :     ReorderBufferTupleCidEnt *ent;
    5310             : 
    5311             :     hash_seq_init(&hstat, tuplecid_data);
    5312             :     while ((ent = (ReorderBufferTupleCidEnt *) hash_seq_search(&hstat)) != NULL)
    5313             :     {
    5314             :         elog(DEBUG3, "mapping: node: %u/%u/%u tid: %u/%u cmin: %u, cmax: %u",
    5315             :              ent->key.rlocator.dbOid,
    5316             :              ent->key.rlocator.spcOid,
    5317             :              ent->key.rlocator.relNumber,
    5318             :              ItemPointerGetBlockNumber(&ent->key.tid),
    5319             :              ItemPointerGetOffsetNumber(&ent->key.tid),
    5320             :              ent->cmin,
    5321             :              ent->cmax
    5322             :             );
    5323             :     }
    5324             : }
    5325             : #endif
    5326             : 
    5327             : /*
    5328             :  * Apply a single mapping file to tuplecid_data.
    5329             :  *
    5330             :  * The mapping file has to have been verified to be a) committed b) for our
    5331             :  * transaction c) applied in LSN order.
    5332             :  */
    5333             : static void
    5334          54 : ApplyLogicalMappingFile(HTAB *tuplecid_data, Oid relid, const char *fname)
    5335             : {
    5336             :     char        path[MAXPGPATH];
    5337             :     int         fd;
    5338             :     int         readBytes;
    5339             :     LogicalRewriteMappingData map;
    5340             : 
    5341          54 :     sprintf(path, "%s/%s", PG_LOGICAL_MAPPINGS_DIR, fname);
    5342          54 :     fd = OpenTransientFile(path, O_RDONLY | PG_BINARY);
    5343          54 :     if (fd < 0)
    5344           0 :         ereport(ERROR,
    5345             :                 (errcode_for_file_access(),
    5346             :                  errmsg("could not open file \"%s\": %m", path)));
    5347             : 
    5348             :     while (true)
    5349         418 :     {
    5350             :         ReorderBufferTupleCidKey key;
    5351             :         ReorderBufferTupleCidEnt *ent;
    5352             :         ReorderBufferTupleCidEnt *new_ent;
    5353             :         bool        found;
    5354             : 
    5355             :         /* be careful about padding */
    5356         472 :         memset(&key, 0, sizeof(ReorderBufferTupleCidKey));
    5357             : 
    5358             :         /* read all mappings till the end of the file */
    5359         472 :         pgstat_report_wait_start(WAIT_EVENT_REORDER_LOGICAL_MAPPING_READ);
    5360         472 :         readBytes = read(fd, &map, sizeof(LogicalRewriteMappingData));
    5361         472 :         pgstat_report_wait_end();
    5362             : 
    5363         472 :         if (readBytes < 0)
    5364           0 :             ereport(ERROR,
    5365             :                     (errcode_for_file_access(),
    5366             :                      errmsg("could not read file \"%s\": %m",
    5367             :                             path)));
    5368         472 :         else if (readBytes == 0)    /* EOF */
    5369          54 :             break;
    5370         418 :         else if (readBytes != sizeof(LogicalRewriteMappingData))
    5371           0 :             ereport(ERROR,
    5372             :                     (errcode_for_file_access(),
    5373             :                      errmsg("could not read from file \"%s\": read %d instead of %d bytes",
    5374             :                             path, readBytes,
    5375             :                             (int32) sizeof(LogicalRewriteMappingData))));
    5376             : 
    5377         418 :         key.rlocator = map.old_locator;
    5378         418 :         ItemPointerCopy(&map.old_tid,
    5379             :                         &key.tid);
    5380             : 
    5381             : 
    5382             :         ent = (ReorderBufferTupleCidEnt *)
    5383         418 :             hash_search(tuplecid_data, &key, HASH_FIND, NULL);
    5384             : 
    5385             :         /* no existing mapping, no need to update */
    5386         418 :         if (!ent)
    5387           0 :             continue;
    5388             : 
    5389         418 :         key.rlocator = map.new_locator;
    5390         418 :         ItemPointerCopy(&map.new_tid,
    5391             :                         &key.tid);
    5392             : 
    5393             :         new_ent = (ReorderBufferTupleCidEnt *)
    5394         418 :             hash_search(tuplecid_data, &key, HASH_ENTER, &found);
    5395             : 
    5396         418 :         if (found)
    5397             :         {
    5398             :             /*
    5399             :              * Make sure the existing mapping makes sense. We sometime update
    5400             :              * old records that did not yet have a cmax (e.g. pg_class' own
    5401             :              * entry while rewriting it) during rewrites, so allow that.
    5402             :              */
    5403             :             Assert(ent->cmin == InvalidCommandId || ent->cmin == new_ent->cmin);
    5404             :             Assert(ent->cmax == InvalidCommandId || ent->cmax == new_ent->cmax);
    5405             :         }
    5406             :         else
    5407             :         {
    5408             :             /* update mapping */
    5409         406 :             new_ent->cmin = ent->cmin;
    5410         406 :             new_ent->cmax = ent->cmax;
    5411         406 :             new_ent->combocid = ent->combocid;
    5412             :         }
    5413             :     }
    5414             : 
    5415          54 :     if (CloseTransientFile(fd) != 0)
    5416           0 :         ereport(ERROR,
    5417             :                 (errcode_for_file_access(),
    5418             :                  errmsg("could not close file \"%s\": %m", path)));
    5419          54 : }
    5420             : 
    5421             : 
    5422             : /*
    5423             :  * Check whether the TransactionId 'xid' is in the pre-sorted array 'xip'.
    5424             :  */
    5425             : static bool
    5426         696 : TransactionIdInArray(TransactionId xid, TransactionId *xip, Size num)
    5427             : {
    5428         696 :     return bsearch(&xid, xip, num,
    5429         696 :                    sizeof(TransactionId), xidComparator) != NULL;
    5430             : }
    5431             : 
    5432             : /*
    5433             :  * list_sort() comparator for sorting RewriteMappingFiles in LSN order.
    5434             :  */
    5435             : static int
    5436          92 : file_sort_by_lsn(const ListCell *a_p, const ListCell *b_p)
    5437             : {
    5438          92 :     RewriteMappingFile *a = (RewriteMappingFile *) lfirst(a_p);
    5439          92 :     RewriteMappingFile *b = (RewriteMappingFile *) lfirst(b_p);
    5440             : 
    5441          92 :     return pg_cmp_u64(a->lsn, b->lsn);
    5442             : }
    5443             : 
    5444             : /*
    5445             :  * Apply any existing logical remapping files if there are any targeted at our
    5446             :  * transaction for relid.
    5447             :  */
    5448             : static void
    5449          22 : UpdateLogicalMappings(HTAB *tuplecid_data, Oid relid, Snapshot snapshot)
    5450             : {
    5451             :     DIR        *mapping_dir;
    5452             :     struct dirent *mapping_de;
    5453          22 :     List       *files = NIL;
    5454             :     ListCell   *file;
    5455          22 :     Oid         dboid = IsSharedRelation(relid) ? InvalidOid : MyDatabaseId;
    5456             : 
    5457          22 :     mapping_dir = AllocateDir(PG_LOGICAL_MAPPINGS_DIR);
    5458        1146 :     while ((mapping_de = ReadDir(mapping_dir, PG_LOGICAL_MAPPINGS_DIR)) != NULL)
    5459             :     {
    5460             :         Oid         f_dboid;
    5461             :         Oid         f_relid;
    5462             :         TransactionId f_mapped_xid;
    5463             :         TransactionId f_create_xid;
    5464             :         XLogRecPtr  f_lsn;
    5465             :         uint32      f_hi,
    5466             :                     f_lo;
    5467             :         RewriteMappingFile *f;
    5468             : 
    5469        1124 :         if (strcmp(mapping_de->d_name, ".") == 0 ||
    5470        1102 :             strcmp(mapping_de->d_name, "..") == 0)
    5471        1070 :             continue;
    5472             : 
    5473             :         /* Ignore files that aren't ours */
    5474        1080 :         if (strncmp(mapping_de->d_name, "map-", 4) != 0)
    5475           0 :             continue;
    5476             : 
    5477        1080 :         if (sscanf(mapping_de->d_name, LOGICAL_REWRITE_FORMAT,
    5478             :                    &f_dboid, &f_relid, &f_hi, &f_lo,
    5479             :                    &f_mapped_xid, &f_create_xid) != 6)
    5480           0 :             elog(ERROR, "could not parse filename \"%s\"", mapping_de->d_name);
    5481             : 
    5482        1080 :         f_lsn = ((uint64) f_hi) << 32 | f_lo;
    5483             : 
    5484             :         /* mapping for another database */
    5485        1080 :         if (f_dboid != dboid)
    5486           0 :             continue;
    5487             : 
    5488             :         /* mapping for another relation */
    5489        1080 :         if (f_relid != relid)
    5490         120 :             continue;
    5491             : 
    5492             :         /* did the creating transaction abort? */
    5493         960 :         if (!TransactionIdDidCommit(f_create_xid))
    5494         264 :             continue;
    5495             : 
    5496             :         /* not for our transaction */
    5497         696 :         if (!TransactionIdInArray(f_mapped_xid, snapshot->subxip, snapshot->subxcnt))
    5498         642 :             continue;
    5499             : 
    5500             :         /* ok, relevant, queue for apply */
    5501          54 :         f = palloc(sizeof(RewriteMappingFile));
    5502          54 :         f->lsn = f_lsn;
    5503          54 :         strcpy(f->fname, mapping_de->d_name);
    5504          54 :         files = lappend(files, f);
    5505             :     }
    5506          22 :     FreeDir(mapping_dir);
    5507             : 
    5508             :     /* sort files so we apply them in LSN order */
    5509          22 :     list_sort(files, file_sort_by_lsn);
    5510             : 
    5511          76 :     foreach(file, files)
    5512             :     {
    5513          54 :         RewriteMappingFile *f = (RewriteMappingFile *) lfirst(file);
    5514             : 
    5515          54 :         elog(DEBUG1, "applying mapping: \"%s\" in %u", f->fname,
    5516             :              snapshot->subxip[0]);
    5517          54 :         ApplyLogicalMappingFile(tuplecid_data, relid, f->fname);
    5518          54 :         pfree(f);
    5519             :     }
    5520          22 : }
    5521             : 
    5522             : /*
    5523             :  * Lookup cmin/cmax of a tuple, during logical decoding where we can't rely on
    5524             :  * combo CIDs.
    5525             :  */
    5526             : bool
    5527        1550 : ResolveCminCmaxDuringDecoding(HTAB *tuplecid_data,
    5528             :                               Snapshot snapshot,
    5529             :                               HeapTuple htup, Buffer buffer,
    5530             :                               CommandId *cmin, CommandId *cmax)
    5531             : {
    5532             :     ReorderBufferTupleCidKey key;
    5533             :     ReorderBufferTupleCidEnt *ent;
    5534             :     ForkNumber  forkno;
    5535             :     BlockNumber blockno;
    5536        1550 :     bool        updated_mapping = false;
    5537             : 
    5538             :     /*
    5539             :      * Return unresolved if tuplecid_data is not valid.  That's because when
    5540             :      * streaming in-progress transactions we may run into tuples with the CID
    5541             :      * before actually decoding them.  Think e.g. about INSERT followed by
    5542             :      * TRUNCATE, where the TRUNCATE may not be decoded yet when applying the
    5543             :      * INSERT.  So in such cases, we assume the CID is from the future
    5544             :      * command.
    5545             :      */
    5546        1550 :     if (tuplecid_data == NULL)
    5547          22 :         return false;
    5548             : 
    5549             :     /* be careful about padding */
    5550        1528 :     memset(&key, 0, sizeof(key));
    5551             : 
    5552             :     Assert(!BufferIsLocal(buffer));
    5553             : 
    5554             :     /*
    5555             :      * get relfilelocator from the buffer, no convenient way to access it
    5556             :      * other than that.
    5557             :      */
    5558        1528 :     BufferGetTag(buffer, &key.rlocator, &forkno, &blockno);
    5559             : 
    5560             :     /* tuples can only be in the main fork */
    5561             :     Assert(forkno == MAIN_FORKNUM);
    5562             :     Assert(blockno == ItemPointerGetBlockNumber(&htup->t_self));
    5563             : 
    5564        1528 :     ItemPointerCopy(&htup->t_self,
    5565             :                     &key.tid);
    5566             : 
    5567        1550 : restart:
    5568             :     ent = (ReorderBufferTupleCidEnt *)
    5569        1550 :         hash_search(tuplecid_data, &key, HASH_FIND, NULL);
    5570             : 
    5571             :     /*
    5572             :      * failed to find a mapping, check whether the table was rewritten and
    5573             :      * apply mapping if so, but only do that once - there can be no new
    5574             :      * mappings while we are in here since we have to hold a lock on the
    5575             :      * relation.
    5576             :      */
    5577        1550 :     if (ent == NULL && !updated_mapping)
    5578             :     {
    5579          22 :         UpdateLogicalMappings(tuplecid_data, htup->t_tableOid, snapshot);
    5580             :         /* now check but don't update for a mapping again */
    5581          22 :         updated_mapping = true;
    5582          22 :         goto restart;
    5583             :     }
    5584        1528 :     else if (ent == NULL)
    5585          10 :         return false;
    5586             : 
    5587        1518 :     if (cmin)
    5588        1518 :         *cmin = ent->cmin;
    5589        1518 :     if (cmax)
    5590        1518 :         *cmax = ent->cmax;
    5591        1518 :     return true;
    5592             : }
    5593             : 
    5594             : /*
    5595             :  * Count invalidation messages of specified transaction.
    5596             :  *
    5597             :  * Returns number of messages, and msgs is set to the pointer of the linked
    5598             :  * list for the messages.
    5599             :  */
    5600             : uint32
    5601          66 : ReorderBufferGetInvalidations(ReorderBuffer *rb, TransactionId xid,
    5602             :                               SharedInvalidationMessage **msgs)
    5603             : {
    5604             :     ReorderBufferTXN *txn;
    5605             : 
    5606          66 :     txn = ReorderBufferTXNByXid(rb, xid, false, NULL, InvalidXLogRecPtr,
    5607             :                                 false);
    5608             : 
    5609          66 :     if (txn == NULL)
    5610           0 :         return 0;
    5611             : 
    5612          66 :     *msgs = txn->invalidations;
    5613             : 
    5614          66 :     return txn->ninvalidations;
    5615             : }

Generated by: LCOV version 1.16