]> granicus.if.org Git - postgresql/blobdiff - src/backend/replication/logical/reorderbuffer.c
Change extension of spilled ReorderBufferChange data to ".tmp".
[postgresql] / src / backend / replication / logical / reorderbuffer.c
index c72a611a39136e3cb023c21780dbda042905c18f..0d72ac1c791f50a289a06ca432476fda365662a1 100644 (file)
@@ -165,6 +165,8 @@ static void ReorderBufferReturnTXN(ReorderBuffer *rb, ReorderBufferTXN *txn);
 static ReorderBufferTXN *ReorderBufferTXNByXid(ReorderBuffer *rb,
                                          TransactionId xid, bool create, bool *is_new,
                                          XLogRecPtr lsn, bool create_as_top);
+static void ReorderBufferTransferSnapToParent(ReorderBufferTXN *txn,
+                                                                 ReorderBufferTXN *subtxn);
 
 static void AssertTXNLsnOrder(ReorderBuffer *rb);
 
@@ -196,6 +198,9 @@ static Size ReorderBufferRestoreChanges(ReorderBuffer *rb, ReorderBufferTXN *txn
 static void ReorderBufferRestoreChange(ReorderBuffer *rb, ReorderBufferTXN *txn,
                                                   char *change);
 static void ReorderBufferRestoreCleanup(ReorderBuffer *rb, ReorderBufferTXN *txn);
+static void ReorderBufferCleanupSerializedTXNs(const char *slotname);
+static void ReorderBufferSerializedPath(char *path, ReplicationSlot *slot,
+                                                       TransactionId xid, XLogSegNo segno);
 
 static void ReorderBufferFreeSnap(ReorderBuffer *rb, Snapshot snap);
 static Snapshot ReorderBufferCopySnap(ReorderBuffer *rb, Snapshot orig_snap,
@@ -214,7 +219,8 @@ static void ReorderBufferToastAppendChunk(ReorderBuffer *rb, ReorderBufferTXN *t
 
 
 /*
- * Allocate a new ReorderBuffer
+ * Allocate a new ReorderBuffer and clean out any old serialized state from
+ * prior ReorderBuffer instances for the same slot.
  */
 ReorderBuffer *
 ReorderBufferAllocate(void)
@@ -223,6 +229,8 @@ ReorderBufferAllocate(void)
        HASHCTL         hash_ctl;
        MemoryContext new_ctx;
 
+       Assert(MyReplicationSlot != NULL);
+
        /* allocate memory in own context, to have better accountability */
        new_ctx = AllocSetContextCreate(CurrentMemoryContext,
                                                                        "ReorderBuffer",
@@ -237,19 +245,16 @@ ReorderBufferAllocate(void)
 
        buffer->change_context = SlabContextCreate(new_ctx,
                                                                                           "Change",
-                                                                                          0,
                                                                                           SLAB_DEFAULT_BLOCK_SIZE,
                                                                                           sizeof(ReorderBufferChange));
 
        buffer->txn_context = SlabContextCreate(new_ctx,
                                                                                        "TXN",
-                                                                                       0,
                                                                                        SLAB_DEFAULT_BLOCK_SIZE,
                                                                                        sizeof(ReorderBufferTXN));
 
        buffer->tup_context = GenerationContextCreate(new_ctx,
                                                                                                  "Tuples",
-                                                                                                 0,
                                                                                                  SLAB_LARGE_BLOCK_SIZE);
 
        hash_ctl.keysize = sizeof(TransactionId);
@@ -268,6 +273,14 @@ ReorderBufferAllocate(void)
        buffer->current_restart_decoding_lsn = InvalidXLogRecPtr;
 
        dlist_init(&buffer->toplevel_by_lsn);
+       dlist_init(&buffer->txns_by_base_snapshot_lsn);
+
+       /*
+        * Ensure there's no stale data from prior uses of this slot, in case some
+        * prior exit avoided calling ReorderBufferFree. Failure to do this can
+        * produce duplicated txns, and it's very cheap if there's nothing there.
+        */
+       ReorderBufferCleanupSerializedTXNs(NameStr(MyReplicationSlot->data.name));
 
        return buffer;
 }
@@ -285,6 +298,9 @@ ReorderBufferFree(ReorderBuffer *rb)
         * memory context.
         */
        MemoryContextDelete(context);
+
+       /* Free disk space used by unconsumed reorder buffers */
+       ReorderBufferCleanupSerializedTXNs(NameStr(MyReplicationSlot->data.name));
 }
 
 /*
@@ -309,9 +325,6 @@ ReorderBufferGetTXN(ReorderBuffer *rb)
 
 /*
  * Free a ReorderBufferTXN.
- *
- * Deallocation might be delayed for efficiency purposes, for details check
- * the comments above max_cached_changes's definition.
  */
 static void
 ReorderBufferReturnTXN(ReorderBuffer *rb, ReorderBufferTXN *txn)
@@ -341,7 +354,7 @@ ReorderBufferReturnTXN(ReorderBuffer *rb, ReorderBufferTXN *txn)
 }
 
 /*
- * Get an unused, possibly preallocated, ReorderBufferChange.
+ * Get an fresh ReorderBufferChange.
  */
 ReorderBufferChange *
 ReorderBufferGetChange(ReorderBuffer *rb)
@@ -357,9 +370,6 @@ ReorderBufferGetChange(ReorderBuffer *rb)
 
 /*
  * Free an ReorderBufferChange.
- *
- * Deallocation might be delayed for efficiency purposes, for details check
- * the comments above max_cached_changes's definition.
  */
 void
 ReorderBufferReturnChange(ReorderBuffer *rb, ReorderBufferChange *change)
@@ -402,6 +412,7 @@ ReorderBufferReturnChange(ReorderBuffer *rb, ReorderBufferChange *change)
                case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_CONFIRM:
                case REORDER_BUFFER_CHANGE_INTERNAL_COMMAND_ID:
                case REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID:
+               case REORDER_BUFFER_CHANGE_TRUNCATE:
                        break;
        }
 
@@ -409,8 +420,8 @@ ReorderBufferReturnChange(ReorderBuffer *rb, ReorderBufferChange *change)
 }
 
 /*
- * Get an unused, possibly preallocated, ReorderBufferTupleBuf fitting at
- * least a tuple of size tuple_len (excluding header overhead).
+ * Get a fresh ReorderBufferTupleBuf fitting at least a tuple of size
+ * tuple_len (excluding header overhead).
  */
 ReorderBufferTupleBuf *
 ReorderBufferGetTupleBuf(ReorderBuffer *rb, Size tuple_len)
@@ -432,9 +443,6 @@ ReorderBufferGetTupleBuf(ReorderBuffer *rb, Size tuple_len)
 
 /*
  * Free an ReorderBufferTupleBuf.
- *
- * Deallocation might be delayed for efficiency purposes, for details check
- * the comments above max_cached_changes's definition.
  */
 void
 ReorderBufferReturnTupleBuf(ReorderBuffer *rb, ReorderBufferTupleBuf *tuple)
@@ -457,7 +465,6 @@ ReorderBufferTXNByXid(ReorderBuffer *rb, TransactionId xid, bool create,
        bool            found;
 
        Assert(TransactionIdIsValid(xid));
-       Assert(!create || lsn != InvalidXLogRecPtr);
 
        /*
         * Check the one-entry lookup cache first
@@ -501,6 +508,7 @@ ReorderBufferTXNByXid(ReorderBuffer *rb, TransactionId xid, bool create,
        {
                /* initialize the new entry, if creation was requested */
                Assert(ent != NULL);
+               Assert(lsn != InvalidXLogRecPtr);
 
                ent->txn = ReorderBufferGetTXN(rb);
                ent->txn->xid = xid;
@@ -602,43 +610,80 @@ ReorderBufferQueueMessage(ReorderBuffer *rb, TransactionId xid,
        }
 }
 
-
+/*
+ * AssertTXNLsnOrder
+ *             Verify LSN ordering of transaction lists in the reorderbuffer
+ *
+ * Other LSN-related invariants are checked too.
+ *
+ * No-op if assertions are not in use.
+ */
 static void
 AssertTXNLsnOrder(ReorderBuffer *rb)
 {
 #ifdef USE_ASSERT_CHECKING
        dlist_iter      iter;
        XLogRecPtr      prev_first_lsn = InvalidXLogRecPtr;
+       XLogRecPtr      prev_base_snap_lsn = InvalidXLogRecPtr;
 
        dlist_foreach(iter, &rb->toplevel_by_lsn)
        {
-               ReorderBufferTXN *cur_txn;
+               ReorderBufferTXN *cur_txn = dlist_container(ReorderBufferTXN, node,
+                                                                                                       iter.cur);
 
-               cur_txn = dlist_container(ReorderBufferTXN, node, iter.cur);
+               /* start LSN must be set */
                Assert(cur_txn->first_lsn != InvalidXLogRecPtr);
 
+               /* If there is an end LSN, it must be higher than start LSN */
                if (cur_txn->end_lsn != InvalidXLogRecPtr)
                        Assert(cur_txn->first_lsn <= cur_txn->end_lsn);
 
+               /* Current initial LSN must be strictly higher than previous */
                if (prev_first_lsn != InvalidXLogRecPtr)
                        Assert(prev_first_lsn < cur_txn->first_lsn);
 
+               /* known-as-subtxn txns must not be listed */
                Assert(!cur_txn->is_known_as_subxact);
+
                prev_first_lsn = cur_txn->first_lsn;
        }
+
+       dlist_foreach(iter, &rb->txns_by_base_snapshot_lsn)
+       {
+               ReorderBufferTXN *cur_txn = dlist_container(ReorderBufferTXN,
+                                                                                                       base_snapshot_node,
+                                                                                                       iter.cur);
+
+               /* base snapshot (and its LSN) must be set */
+               Assert(cur_txn->base_snapshot != NULL);
+               Assert(cur_txn->base_snapshot_lsn != InvalidXLogRecPtr);
+
+               /* current LSN must be strictly higher than previous */
+               if (prev_base_snap_lsn != InvalidXLogRecPtr)
+                       Assert(prev_base_snap_lsn < cur_txn->base_snapshot_lsn);
+
+               /* known-as-subtxn txns must not be listed */
+               Assert(!cur_txn->is_known_as_subxact);
+
+               prev_base_snap_lsn = cur_txn->base_snapshot_lsn;
+       }
 #endif
 }
 
+/*
+ * ReorderBufferGetOldestTXN
+ *             Return oldest transaction in reorderbuffer
+ */
 ReorderBufferTXN *
 ReorderBufferGetOldestTXN(ReorderBuffer *rb)
 {
        ReorderBufferTXN *txn;
 
+       AssertTXNLsnOrder(rb);
+
        if (dlist_is_empty(&rb->toplevel_by_lsn))
                return NULL;
 
-       AssertTXNLsnOrder(rb);
-
        txn = dlist_head_element(ReorderBufferTXN, node, &rb->toplevel_by_lsn);
 
        Assert(!txn->is_known_as_subxact);
@@ -646,12 +691,44 @@ ReorderBufferGetOldestTXN(ReorderBuffer *rb)
        return txn;
 }
 
+/*
+ * ReorderBufferGetOldestXmin
+ *             Return oldest Xmin in reorderbuffer
+ *
+ * Returns oldest possibly running Xid from the point of view of snapshots
+ * used in the transactions kept by reorderbuffer, or InvalidTransactionId if
+ * there are none.
+ *
+ * Since snapshots are assigned monotonically, this equals the Xmin of the
+ * base snapshot with minimal base_snapshot_lsn.
+ */
+TransactionId
+ReorderBufferGetOldestXmin(ReorderBuffer *rb)
+{
+       ReorderBufferTXN *txn;
+
+       AssertTXNLsnOrder(rb);
+
+       if (dlist_is_empty(&rb->txns_by_base_snapshot_lsn))
+               return InvalidTransactionId;
+
+       txn = dlist_head_element(ReorderBufferTXN, base_snapshot_node,
+                                                        &rb->txns_by_base_snapshot_lsn);
+       return txn->base_snapshot->xmin;
+}
+
 void
 ReorderBufferSetRestartPoint(ReorderBuffer *rb, XLogRecPtr ptr)
 {
        rb->current_restart_decoding_lsn = ptr;
 }
 
+/*
+ * ReorderBufferAssignChild
+ *
+ * Make note that we know that subxid is a subtransaction of xid, seen as of
+ * the given lsn.
+ */
 void
 ReorderBufferAssignChild(ReorderBuffer *rb, TransactionId xid,
                                                 TransactionId subxid, XLogRecPtr lsn)
@@ -664,32 +741,107 @@ ReorderBufferAssignChild(ReorderBuffer *rb, TransactionId xid,
        txn = ReorderBufferTXNByXid(rb, xid, true, &new_top, lsn, true);
        subtxn = ReorderBufferTXNByXid(rb, subxid, true, &new_sub, lsn, false);
 
-       if (new_sub)
+       if (new_top && !new_sub)
+               elog(ERROR, "subtransaction logged without previous top-level txn record");
+
+       if (!new_sub)
        {
-               /*
-                * we assign subtransactions to top level transaction even if we don't
-                * have data for it yet, assignment records frequently reference xids
-                * that have not yet produced any records. Knowing those aren't top
-                * level xids allows us to make processing cheaper in some places.
-                */
-               dlist_push_tail(&txn->subtxns, &subtxn->node);
-               txn->nsubtxns++;
+               if (subtxn->is_known_as_subxact)
+               {
+                       /* already associated, nothing to do */
+                       return;
+               }
+               else
+               {
+                       /*
+                        * We already saw this transaction, but initially added it to the
+                        * list of top-level txns.  Now that we know it's not top-level,
+                        * remove it from there.
+                        */
+                       dlist_delete(&subtxn->node);
+               }
        }
-       else if (!subtxn->is_known_as_subxact)
-       {
-               subtxn->is_known_as_subxact = true;
-               Assert(subtxn->nsubtxns == 0);
 
-               /* remove from lsn order list of top-level transactions */
-               dlist_delete(&subtxn->node);
+       subtxn->is_known_as_subxact = true;
+       subtxn->toplevel_xid = xid;
+       Assert(subtxn->nsubtxns == 0);
 
-               /* add to toplevel transaction */
-               dlist_push_tail(&txn->subtxns, &subtxn->node);
-               txn->nsubtxns++;
-       }
-       else if (new_top)
+       /* add to subtransaction list */
+       dlist_push_tail(&txn->subtxns, &subtxn->node);
+       txn->nsubtxns++;
+
+       /* Possibly transfer the subtxn's snapshot to its top-level txn. */
+       ReorderBufferTransferSnapToParent(txn, subtxn);
+
+       /* Verify LSN-ordering invariant */
+       AssertTXNLsnOrder(rb);
+}
+
+/*
+ * ReorderBufferTransferSnapToParent
+ *             Transfer base snapshot from subtxn to top-level txn, if needed
+ *
+ * This is done if the top-level txn doesn't have a base snapshot, or if the
+ * subtxn's base snapshot has an earlier LSN than the top-level txn's base
+ * snapshot's LSN.  This can happen if there are no changes in the toplevel
+ * txn but there are some in the subtxn, or the first change in subtxn has
+ * earlier LSN than first change in the top-level txn and we learned about
+ * their kinship only now.
+ *
+ * The subtransaction's snapshot is cleared regardless of the transfer
+ * happening, since it's not needed anymore in either case.
+ *
+ * We do this as soon as we become aware of their kinship, to avoid queueing
+ * extra snapshots to txns known-as-subtxns -- only top-level txns will
+ * receive further snapshots.
+ */
+static void
+ReorderBufferTransferSnapToParent(ReorderBufferTXN *txn,
+                                                                 ReorderBufferTXN *subtxn)
+{
+       Assert(subtxn->toplevel_xid == txn->xid);
+
+       if (subtxn->base_snapshot != NULL)
        {
-               elog(ERROR, "existing subxact assigned to unknown toplevel xact");
+               if (txn->base_snapshot == NULL ||
+                       subtxn->base_snapshot_lsn < txn->base_snapshot_lsn)
+               {
+                       /*
+                        * If the toplevel transaction already has a base snapshot but
+                        * it's newer than the subxact's, purge it.
+                        */
+                       if (txn->base_snapshot != NULL)
+                       {
+                               SnapBuildSnapDecRefcount(txn->base_snapshot);
+                               dlist_delete(&txn->base_snapshot_node);
+                       }
+
+                       /*
+                        * The snapshot is now the top transaction's; transfer it, and
+                        * adjust the list position of the top transaction in the list by
+                        * moving it to where the subtransaction is.
+                        */
+                       txn->base_snapshot = subtxn->base_snapshot;
+                       txn->base_snapshot_lsn = subtxn->base_snapshot_lsn;
+                       dlist_insert_before(&subtxn->base_snapshot_node,
+                                                               &txn->base_snapshot_node);
+
+                       /*
+                        * The subtransaction doesn't have a snapshot anymore (so it
+                        * mustn't be in the list.)
+                        */
+                       subtxn->base_snapshot = NULL;
+                       subtxn->base_snapshot_lsn = InvalidXLogRecPtr;
+                       dlist_delete(&subtxn->base_snapshot_node);
+               }
+               else
+               {
+                       /* Base snap of toplevel is fine, so subxact's is not needed */
+                       SnapBuildSnapDecRefcount(subtxn->base_snapshot);
+                       dlist_delete(&subtxn->base_snapshot_node);
+                       subtxn->base_snapshot = NULL;
+                       subtxn->base_snapshot_lsn = InvalidXLogRecPtr;
+               }
        }
 }
 
@@ -702,7 +854,6 @@ ReorderBufferCommitChild(ReorderBuffer *rb, TransactionId xid,
                                                 TransactionId subxid, XLogRecPtr commit_lsn,
                                                 XLogRecPtr end_lsn)
 {
-       ReorderBufferTXN *txn;
        ReorderBufferTXN *subtxn;
 
        subtxn = ReorderBufferTXNByXid(rb, subxid, false, NULL,
@@ -714,42 +865,14 @@ ReorderBufferCommitChild(ReorderBuffer *rb, TransactionId xid,
        if (!subtxn)
                return;
 
-       txn = ReorderBufferTXNByXid(rb, xid, false, NULL, commit_lsn, true);
-
-       if (txn == NULL)
-               elog(ERROR, "subxact logged without previous toplevel record");
-
-       /*
-        * Pass our base snapshot to the parent transaction if it doesn't have
-        * one, or ours is older. That can happen if there are no changes in the
-        * toplevel transaction but in one of the child transactions. This allows
-        * the parent to simply use its base snapshot initially.
-        */
-       if (subtxn->base_snapshot != NULL &&
-               (txn->base_snapshot == NULL ||
-                txn->base_snapshot_lsn > subtxn->base_snapshot_lsn))
-       {
-               txn->base_snapshot = subtxn->base_snapshot;
-               txn->base_snapshot_lsn = subtxn->base_snapshot_lsn;
-               subtxn->base_snapshot = NULL;
-               subtxn->base_snapshot_lsn = InvalidXLogRecPtr;
-       }
-
        subtxn->final_lsn = commit_lsn;
        subtxn->end_lsn = end_lsn;
 
-       if (!subtxn->is_known_as_subxact)
-       {
-               subtxn->is_known_as_subxact = true;
-               Assert(subtxn->nsubtxns == 0);
-
-               /* remove from lsn order list of top-level transactions */
-               dlist_delete(&subtxn->node);
-
-               /* add to subtransaction list */
-               dlist_push_tail(&txn->subtxns, &subtxn->node);
-               txn->nsubtxns++;
-       }
+       /*
+        * Assign this subxact as a child of the toplevel xact (no-op if already
+        * done.)
+        */
+       ReorderBufferAssignChild(rb, xid, subxid, InvalidXLogRecPtr);
 }
 
 
@@ -1073,11 +1196,13 @@ ReorderBufferCleanupTXN(ReorderBuffer *rb, ReorderBufferTXN *txn)
                ReorderBufferReturnChange(rb, change);
        }
 
+       /*
+        * Cleanup the base snapshot, if set.
+        */
        if (txn->base_snapshot != NULL)
        {
                SnapBuildSnapDecRefcount(txn->base_snapshot);
-               txn->base_snapshot = NULL;
-               txn->base_snapshot_lsn = InvalidXLogRecPtr;
+               dlist_delete(&txn->base_snapshot_node);
        }
 
        /*
@@ -1252,17 +1377,17 @@ ReorderBufferFreeSnap(ReorderBuffer *rb, Snapshot snap)
 }
 
 /*
- * Perform the replay of a transaction and it's non-aborted subtransactions.
+ * Perform the replay of a transaction and its non-aborted subtransactions.
  *
  * Subtransactions previously have to be processed by
  * ReorderBufferCommitChild(), even if previously assigned to the toplevel
  * transaction with ReorderBufferAssignChild.
  *
- * We currently can only decode a transaction's contents in when their commit
- * record is read because that's currently the only place where we know about
- * cache invalidations. Thus, once a toplevel commit is read, we iterate over
- * the top and subtransactions (using a k-way merge) and replay the changes in
- * lsn order.
+ * We currently can only decode a transaction's contents when its commit
+ * record is read because that's the only place where we know about cache
+ * invalidations. Thus, once a toplevel commit is read, we iterate over the top
+ * and subtransactions (using a k-way merge) and replay the changes in lsn
+ * order.
  */
 void
 ReorderBufferCommit(ReorderBuffer *rb, TransactionId xid,
@@ -1290,10 +1415,10 @@ ReorderBufferCommit(ReorderBuffer *rb, TransactionId xid,
        txn->origin_lsn = origin_lsn;
 
        /*
-        * If this transaction didn't have any real changes in our database, it's
-        * OK not to have a snapshot. Note that ReorderBufferCommitChild will have
-        * transferred its snapshot to this transaction if it had one and the
-        * toplevel tx didn't.
+        * If this transaction has no snapshot, it didn't make any changes to the
+        * database, so there's nothing to decode.  Note that
+        * ReorderBufferCommitChild will have transferred any snapshots from
+        * subtransactions if there were any.
         */
        if (txn->base_snapshot == NULL)
        {
@@ -1349,6 +1474,8 @@ ReorderBufferCommit(ReorderBuffer *rb, TransactionId xid,
                                         * use as a normal record. It'll be cleaned up at the end
                                         * of INSERT processing.
                                         */
+                                       if (specinsert == NULL)
+                                               elog(ERROR, "invalid ordering of speculative insertion changes");
                                        Assert(specinsert->data.tp.oldtuple == NULL);
                                        change = specinsert;
                                        change->action = REORDER_BUFFER_CHANGE_INSERT;
@@ -1386,6 +1513,13 @@ ReorderBufferCommit(ReorderBuffer *rb, TransactionId xid,
                                        if (!RelationIsLogicallyLogged(relation))
                                                goto change_done;
 
+                                       /*
+                                        * Ignore temporary heaps created during DDL unless the
+                                        * plugin has asked for them.
+                                        */
+                                       if (relation->rd_rel->relrewrite && !rb->output_rewrites)
+                                               goto change_done;
+
                                        /*
                                         * For now ignore sequence changes entirely. Most of the
                                         * time they don't log changes using records we
@@ -1471,6 +1605,38 @@ ReorderBufferCommit(ReorderBuffer *rb, TransactionId xid,
                                        specinsert = change;
                                        break;
 
+                               case REORDER_BUFFER_CHANGE_TRUNCATE:
+                                       {
+                                               int                     i;
+                                               int                     nrelids = change->data.truncate.nrelids;
+                                               int                     nrelations = 0;
+                                               Relation   *relations;
+
+                                               relations = palloc0(nrelids * sizeof(Relation));
+                                               for (i = 0; i < nrelids; i++)
+                                               {
+                                                       Oid                     relid = change->data.truncate.relids[i];
+                                                       Relation        relation;
+
+                                                       relation = RelationIdGetRelation(relid);
+
+                                                       if (relation == NULL)
+                                                               elog(ERROR, "could not open relation with OID %u", relid);
+
+                                                       if (!RelationIsLogicallyLogged(relation))
+                                                               continue;
+
+                                                       relations[nrelations++] = relation;
+                                               }
+
+                                               rb->apply_truncate(rb, txn, nrelations, relations, change);
+
+                                               for (i = 0; i < nrelations; i++)
+                                                       RelationClose(relations[i]);
+
+                                               break;
+                                       }
+
                                case REORDER_BUFFER_CHANGE_MESSAGE:
                                        rb->message(rb, txn, change->lsn, true,
                                                                change->data.msg.prefix,
@@ -1691,7 +1857,7 @@ ReorderBufferAbortOld(ReorderBuffer *rb, TransactionId oldestRunningXid)
                        if (txn->serialized && txn->final_lsn == 0)
                        {
                                ReorderBufferChange *last =
-                                       dlist_tail_element(ReorderBufferChange, node, &txn->changes);
+                               dlist_tail_element(ReorderBufferChange, node, &txn->changes);
 
                                txn->final_lsn = last->lsn;
                        }
@@ -1817,12 +1983,10 @@ ReorderBufferAddSnapshot(ReorderBuffer *rb, TransactionId xid,
 }
 
 /*
- * Setup the base snapshot of a transaction. The base snapshot is the snapshot
- * that is used to decode all changes until either this transaction modifies
- * the catalog or another catalog modifying transaction commits.
+ * Set up the transaction's base snapshot.
  *
- * Needs to be called before any changes are added with
- * ReorderBufferQueueChange().
+ * If we know that xid is a subtransaction, set the base snapshot on the
+ * top-level transaction instead.
  */
 void
 ReorderBufferSetBaseSnapshot(ReorderBuffer *rb, TransactionId xid,
@@ -1831,12 +1995,23 @@ ReorderBufferSetBaseSnapshot(ReorderBuffer *rb, TransactionId xid,
        ReorderBufferTXN *txn;
        bool            is_new;
 
+       AssertArg(snap != NULL);
+
+       /*
+        * Fetch the transaction to operate on.  If we know it's a subtransaction,
+        * operate on its top-level transaction instead.
+        */
        txn = ReorderBufferTXNByXid(rb, xid, true, &is_new, lsn, true);
+       if (txn->is_known_as_subxact)
+               txn = ReorderBufferTXNByXid(rb, txn->toplevel_xid, false,
+                                                                       NULL, InvalidXLogRecPtr, false);
        Assert(txn->base_snapshot == NULL);
-       Assert(snap != NULL);
 
        txn->base_snapshot = snap;
        txn->base_snapshot_lsn = lsn;
+       dlist_push_tail(&rb->txns_by_base_snapshot_lsn, &txn->base_snapshot_node);
+
+       AssertTXNLsnOrder(rb);
 }
 
 /*
@@ -1955,25 +2130,26 @@ ReorderBufferXidHasCatalogChanges(ReorderBuffer *rb, TransactionId xid)
 }
 
 /*
- * Have we already added the first snapshot?
+ * ReorderBufferXidHasBaseSnapshot
+ *             Have we already set the base snapshot for the given txn/subtxn?
  */
 bool
 ReorderBufferXidHasBaseSnapshot(ReorderBuffer *rb, TransactionId xid)
 {
        ReorderBufferTXN *txn;
 
-       txn = ReorderBufferTXNByXid(rb, xid, false, NULL, InvalidXLogRecPtr,
-                                                               false);
+       txn = ReorderBufferTXNByXid(rb, xid, false,
+                                                               NULL, InvalidXLogRecPtr, false);
 
        /* transaction isn't known yet, ergo no snapshot */
        if (txn == NULL)
                return false;
 
-       /*
-        * TODO: It would be a nice improvement if we would check the toplevel
-        * transaction in subtransactions, but we'd need to keep track of a bit
-        * more state.
-        */
+       /* a known subtxn? operate on top-level txn instead */
+       if (txn->is_known_as_subxact)
+               txn = ReorderBufferTXNByXid(rb, txn->toplevel_xid, false,
+                                                                       NULL, InvalidXLogRecPtr, false);
+
        return txn->base_snapshot != NULL;
 }
 
@@ -2030,7 +2206,6 @@ ReorderBufferSerializeTXN(ReorderBuffer *rb, ReorderBufferTXN *txn)
        int                     fd = -1;
        XLogSegNo       curOpenSegNo = 0;
        Size            spilled = 0;
-       char            path[MAXPGPATH];
 
        elog(DEBUG2, "spill %u changes in XID %u to disk",
                 (uint32) txn->nentries_mem, txn->xid);
@@ -2058,21 +2233,19 @@ ReorderBufferSerializeTXN(ReorderBuffer *rb, ReorderBufferTXN *txn)
                if (fd == -1 ||
                        !XLByteInSeg(change->lsn, curOpenSegNo, wal_segment_size))
                {
-                       XLogRecPtr      recptr;
+                       char            path[MAXPGPATH];
 
                        if (fd != -1)
                                CloseTransientFile(fd);
 
                        XLByteToSeg(change->lsn, curOpenSegNo, wal_segment_size);
-                       XLogSegNoOffsetToRecPtr(curOpenSegNo, 0, recptr, wal_segment_size);
 
                        /*
                         * No need to care about TLIs here, only used during a single run,
                         * so each LSN only maps to a specific WAL record.
                         */
-                       sprintf(path, "pg_replslot/%s/xid-%u-lsn-%X-%X.snap",
-                                       NameStr(MyReplicationSlot->data.name), txn->xid,
-                                       (uint32) (recptr >> 32), (uint32) recptr);
+                       ReorderBufferSerializedPath(path, MyReplicationSlot, txn->xid,
+                                                                               curOpenSegNo);
 
                        /* open segment, create it if necessary */
                        fd = OpenTransientFile(path,
@@ -2081,8 +2254,7 @@ ReorderBufferSerializeTXN(ReorderBuffer *rb, ReorderBufferTXN *txn)
                        if (fd < 0)
                                ereport(ERROR,
                                                (errcode_for_file_access(),
-                                                errmsg("could not open file \"%s\": %m",
-                                                               path)));
+                                                errmsg("could not open file \"%s\": %m", path)));
                }
 
                ReorderBufferSerializeChange(rb, txn, fd, change);
@@ -2239,6 +2411,7 @@ ReorderBufferSerializeChange(ReorderBuffer *rb, ReorderBufferTXN *txn,
                                }
                                break;
                        }
+               case REORDER_BUFFER_CHANGE_TRUNCATE:
                case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_CONFIRM:
                case REORDER_BUFFER_CHANGE_INTERNAL_COMMAND_ID:
                case REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID:
@@ -2248,13 +2421,16 @@ ReorderBufferSerializeChange(ReorderBuffer *rb, ReorderBufferTXN *txn,
 
        ondisk->size = sz;
 
+       errno = 0;
        pgstat_report_wait_start(WAIT_EVENT_REORDER_BUFFER_WRITE);
        if (write(fd, rb->outbuf, ondisk->size) != ondisk->size)
        {
                int                     save_errno = errno;
 
                CloseTransientFile(fd);
-               errno = save_errno;
+
+               /* if write didn't set errno, assume problem is no disk space */
+               errno = save_errno ? save_errno : ENOSPC;
                ereport(ERROR,
                                (errcode_for_file_access(),
                                 errmsg("could not write to data file for XID %u: %m",
@@ -2300,25 +2476,20 @@ ReorderBufferRestoreChanges(ReorderBuffer *rb, ReorderBufferTXN *txn,
 
                if (*fd == -1)
                {
-                       XLogRecPtr      recptr;
                        char            path[MAXPGPATH];
 
                        /* first time in */
                        if (*segno == 0)
-                       {
                                XLByteToSeg(txn->first_lsn, *segno, wal_segment_size);
-                       }
 
                        Assert(*segno != 0 || dlist_is_empty(&txn->changes));
-                       XLogSegNoOffsetToRecPtr(*segno, 0, recptr, wal_segment_size);
 
                        /*
                         * No need to care about TLIs here, only used during a single run,
                         * so each LSN only maps to a specific WAL record.
                         */
-                       sprintf(path, "pg_replslot/%s/xid-%u-lsn-%X-%X.snap",
-                                       NameStr(MyReplicationSlot->data.name), txn->xid,
-                                       (uint32) (recptr >> 32), (uint32) recptr);
+                       ReorderBufferSerializedPath(path, MyReplicationSlot, txn->xid,
+                                                                               *segno);
 
                        *fd = OpenTransientFile(path, O_RDONLY | PG_BINARY);
                        if (*fd < 0 && errno == ENOENT)
@@ -2332,7 +2503,6 @@ ReorderBufferRestoreChanges(ReorderBuffer *rb, ReorderBufferTXN *txn,
                                                (errcode_for_file_access(),
                                                 errmsg("could not open file \"%s\": %m",
                                                                path)));
-
                }
 
                /*
@@ -2524,6 +2694,7 @@ ReorderBufferRestoreChange(ReorderBuffer *rb, ReorderBufferTXN *txn,
                                break;
                        }
                        /* the base struct contains all the data, easy peasy */
+               case REORDER_BUFFER_CHANGE_TRUNCATE:
                case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_CONFIRM:
                case REORDER_BUFFER_CHANGE_INTERNAL_COMMAND_ID:
                case REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID:
@@ -2554,13 +2725,8 @@ ReorderBufferRestoreCleanup(ReorderBuffer *rb, ReorderBufferTXN *txn)
        for (cur = first; cur <= last; cur++)
        {
                char            path[MAXPGPATH];
-               XLogRecPtr      recptr;
 
-               XLogSegNoOffsetToRecPtr(cur, 0, recptr, wal_segment_size);
-
-               sprintf(path, "pg_replslot/%s/xid-%u-lsn-%X-%X.snap",
-                               NameStr(MyReplicationSlot->data.name), txn->xid,
-                               (uint32) (recptr >> 32), (uint32) recptr);
+               ReorderBufferSerializedPath(path, MyReplicationSlot, txn->xid, cur);
                if (unlink(path) != 0 && errno != ENOENT)
                        ereport(ERROR,
                                        (errcode_for_file_access(),
@@ -2568,6 +2734,63 @@ ReorderBufferRestoreCleanup(ReorderBuffer *rb, ReorderBufferTXN *txn)
        }
 }
 
+/*
+ * Remove any leftover serialized reorder buffers from a slot directory after a
+ * prior crash or decoding session exit.
+ */
+static void
+ReorderBufferCleanupSerializedTXNs(const char *slotname)
+{
+       DIR                *spill_dir;
+       struct dirent *spill_de;
+       struct stat statbuf;
+       char            path[MAXPGPATH * 2 + 12];
+
+       sprintf(path, "pg_replslot/%s", slotname);
+
+       /* we're only handling directories here, skip if it's not ours */
+       if (lstat(path, &statbuf) == 0 && !S_ISDIR(statbuf.st_mode))
+               return;
+
+       spill_dir = AllocateDir(path);
+       while ((spill_de = ReadDirExtended(spill_dir, path, INFO)) != NULL)
+       {
+               /* only look at names that can be ours */
+               if (strncmp(spill_de->d_name, "xid", 3) == 0)
+               {
+                       snprintf(path, sizeof(path),
+                                        "pg_replslot/%s/%s", slotname,
+                                        spill_de->d_name);
+
+                       if (unlink(path) != 0)
+                               ereport(ERROR,
+                                               (errcode_for_file_access(),
+                                                errmsg("could not remove file \"%s\" during removal of pg_replslot/%s/xid*: %m",
+                                                               path, slotname)));
+               }
+       }
+       FreeDir(spill_dir);
+}
+
+/*
+ * Given a replication slot, transaction ID and segment number, fill in the
+ * corresponding spill file into 'path', which is a caller-owned buffer of size
+ * at least MAXPGPATH.
+ */
+static void
+ReorderBufferSerializedPath(char *path, ReplicationSlot *slot, TransactionId xid,
+                                                       XLogSegNo segno)
+{
+       XLogRecPtr      recptr;
+
+       XLogSegNoOffsetToRecPtr(segno, 0, wal_segment_size, recptr);
+
+       snprintf(path, MAXPGPATH, "pg_replslot/%s/xid-%u-lsn-%X-%X.tmp",
+                        NameStr(MyReplicationSlot->data.name),
+                        xid,
+                        (uint32) (recptr >> 32), (uint32) recptr);
+}
+
 /*
  * Delete all data spilled to disk after we've restarted/crashed. It will be
  * recreated when the respective slots are reused.
@@ -2578,15 +2801,9 @@ StartupReorderBuffer(void)
        DIR                *logical_dir;
        struct dirent *logical_de;
 
-       DIR                *spill_dir;
-       struct dirent *spill_de;
-
        logical_dir = AllocateDir("pg_replslot");
        while ((logical_de = ReadDir(logical_dir, "pg_replslot")) != NULL)
        {
-               struct stat statbuf;
-               char            path[MAXPGPATH * 2 + 12];
-
                if (strcmp(logical_de->d_name, ".") == 0 ||
                        strcmp(logical_de->d_name, "..") == 0)
                        continue;
@@ -2599,33 +2816,7 @@ StartupReorderBuffer(void)
                 * ok, has to be a surviving logical slot, iterate and delete
                 * everything starting with xid-*
                 */
-               sprintf(path, "pg_replslot/%s", logical_de->d_name);
-
-               /* we're only creating directories here, skip if it's not our's */
-               if (lstat(path, &statbuf) == 0 && !S_ISDIR(statbuf.st_mode))
-                       continue;
-
-               spill_dir = AllocateDir(path);
-               while ((spill_de = ReadDir(spill_dir, path)) != NULL)
-               {
-                       if (strcmp(spill_de->d_name, ".") == 0 ||
-                               strcmp(spill_de->d_name, "..") == 0)
-                               continue;
-
-                       /* only look at names that can be ours */
-                       if (strncmp(spill_de->d_name, "xid", 3) == 0)
-                       {
-                               sprintf(path, "pg_replslot/%s/%s", logical_de->d_name,
-                                               spill_de->d_name);
-
-                               if (unlink(path) != 0)
-                                       ereport(PANIC,
-                                                       (errcode_for_file_access(),
-                                                        errmsg("could not remove file \"%s\": %m",
-                                                                       path)));
-                       }
-               }
-               FreeDir(spill_dir);
+               ReorderBufferCleanupSerializedTXNs(logical_de->d_name);
        }
        FreeDir(logical_dir);
 }
@@ -3087,11 +3278,13 @@ ApplyLogicalMappingFile(HTAB *tuplecid_data, Oid relid, const char *fname)
                        new_ent->combocid = ent->combocid;
                }
        }
+
+       CloseTransientFile(fd);
 }
 
 
 /*
- * Check whether the TransactionOId 'xid' is in the pre-sorted array 'xip'.
+ * Check whether the TransactionOid 'xid' is in the pre-sorted array 'xip'.
  */
 static bool
 TransactionIdInArray(TransactionId xid, TransactionId *xip, Size num)