Patch
Fix loss of unstreamed changes when a subxact aborts concurrently
- Branch
- master
- Risk
- –
- Base commit
- 8e27c9261c9dd6127e16ced998d37ed7a8cb2b7d
To apply it to a checkout of master at the base commit:
curl -s https://ai-annex.j-davis.com/api/v1/patches/01a1d180-d748-7268-9896-15a13eb59a33 | jq -r .body | git am
From 0fe8ee18b26eaed83a007dde144d9d50742fd8a7 Mon Sep 17 00:00:00 2001
From: Grok <grok@x.ai>
Date: Thu, 12 Nov 2026 12:41:26 -0800
Subject: [PATCH] Fix loss of unstreamed changes when a subxact aborts
concurrently.
ReorderBufferResetTXN() discarded the entire toplevel transaction when
streaming detected a concurrent subtransaction abort. Catalog snapshots
distributed to that transaction are only queued in memory, so dropping
them makes later changes fail to map relation filenumbers.
Keep changes that have not been streamed yet, and drop only the aborted
subtransaction plus changes already handed to the output plugin.
---
.../replication/logical/reorderbuffer.c | 419 ++++++++++++++++--
1 file changed, 394 insertions(+), 25 deletions(-)
diff --git a/src/backend/replication/logical/reorderbuffer.c b/src/backend/replication/logical/reorderbuffer.c
index 46843985317..ef0bc72a1a3 100644
--- a/src/backend/replication/logical/reorderbuffer.c
+++ b/src/backend/replication/logical/reorderbuffer.c
@@ -274,6 +274,16 @@ static Size ReorderBufferRestoreChanges(ReorderBuffer *rb, ReorderBufferTXN *txn
static void ReorderBufferRestoreChange(ReorderBuffer *rb, ReorderBufferTXN *txn,
char *data);
static void ReorderBufferRestoreCleanup(ReorderBuffer *rb, ReorderBufferTXN *txn);
+static bool ReorderBufferRestoreSerializedChanges(ReorderBuffer *rb,
+ ReorderBufferTXN *txn,
+ XLogRecPtr min_lsn,
+ bool xact_aborted);
+static void ReorderBufferFreeChangeList(ReorderBuffer *rb,
+ ReorderBufferTXN *txn);
+static bool ReorderBufferDiscardAppliedChanges(ReorderBuffer *rb,
+ ReorderBufferTXN *txn,
+ XLogRecPtr min_lsn,
+ bool xact_aborted);
static void ReorderBufferTruncateTXN(ReorderBuffer *rb, ReorderBufferTXN *txn,
bool txn_prepared);
static void ReorderBufferMaybeMarkTXNStreamed(ReorderBuffer *rb, ReorderBufferTXN *txn);
@@ -2039,11 +2049,15 @@ ReorderBufferStreamCommit(ReorderBuffer *rb, ReorderBufferTXN *txn)
* For detecting the concurrent abort we set CheckXidAlive to the current
* (sub)transaction's xid for which this change belongs to. And, during
* catalog scan we can check the status of the xid and if it is aborted we will
- * report a specific error so that we can stop streaming current transaction
- * and discard the already streamed changes on such an error. We might have
- * already streamed some of the changes for the aborted (sub)transaction, but
- * that is fine because when we decode the abort we will stream abort message
- * to truncate the changes in the subscriber. Similarly, for prepared
+ * report a specific error so that we can stop streaming the aborted
+ * (sub)transaction. Changes already streamed for it are discarded here and
+ * rolled back when its abort record is decoded. Changes that belong to the
+ * toplevel transaction or to other subtransactions and have not been streamed
+ * yet are kept: they were already read from WAL and will not be queued again.
+ * We might have already streamed some of the changes for the aborted
+ * (sub)transaction, but that is fine because when we decode the abort we will
+ * stream an abort message to truncate those changes in the subscriber.
+ * Similarly, for prepared
* transactions, we stop decoding if concurrent abort is detected and then
* rollback the changes when rollback prepared is encountered. See
* DecodePrepare.
@@ -2173,31 +2187,99 @@ ReorderBufferMaybeMarkTXNStreamed(ReorderBuffer *rb, ReorderBufferTXN *txn)
* can be used to stream the remaining data of transaction being processed.
* This can happen when the subtransaction is aborted and we still want to
* continue processing the main or other subtransactions data.
+ *
+ * aborted_txn is the (sub)transaction whose change hit the concurrent abort.
+ * When that is the toplevel transaction, or the toplevel transaction is
+ * itself aborting, every queued change is discarded. When only a
+ * subtransaction is aborting while the toplevel transaction is still in
+ * progress or has already committed, changes that have not been streamed are
+ * kept. Those changes, including snapshots distributed by concurrent
+ * catalog commits, will not be read from WAL again.
*/
static void
ReorderBufferResetTXN(ReorderBuffer *rb, ReorderBufferTXN *txn,
Snapshot snapshot_now,
CommandId command_id,
- XLogRecPtr last_lsn)
+ XLogRecPtr last_lsn,
+ ReorderBufferTXN *aborted_txn)
{
- /* Discard the changes that we just streamed */
- ReorderBufferTruncateTXN(rb, txn, rbtxn_is_prepared(txn));
+ bool preserve_others;
- /* Free all resources allocated for toast reconstruction */
- ReorderBufferToastReset(rb, txn);
+ Assert(aborted_txn != NULL);
+
+ /*
+ * TransactionIdDidCommit() is true when decoding runs behind a toplevel
+ * commit whose aborting subtransaction is already recorded in the clog. A
+ * prepared transaction is neither in progress nor committed; keep the
+ * historical behavior of discarding the whole tree in that case.
+ */
+ preserve_others = aborted_txn != txn &&
+ (TransactionIdIsInProgress(txn->xid) ||
+ TransactionIdDidCommit(txn->xid));
+
+ if (!preserve_others)
+ {
+ /* Discard the changes that we just streamed. */
+ ReorderBufferTruncateTXN(rb, txn, rbtxn_is_prepared(txn));
+
+ /* Free all resources allocated for toast reconstruction */
+ ReorderBufferToastReset(rb, txn);
+
+ /* All changes must be deallocated */
+ Assert(txn->size == 0);
+ }
+ else
+ {
+ dlist_iter iter;
+
+ Assert(XLogRecPtrIsValid(last_lsn));
+
+ ReorderBufferDiscardAppliedChanges(rb, txn, last_lsn, false);
+
+ dlist_foreach(iter, &txn->subtxns)
+ {
+ ReorderBufferTXN *subtxn;
+
+ subtxn = dlist_container(ReorderBufferTXN, node, iter.cur);
+
+ /*
+ * Subtransactions are always associated to the toplevel TXN, even
+ * if they originally were happening inside another subtxn.
+ */
+ Assert(rbtxn_is_known_subxact(subtxn));
+ Assert(subtxn->nsubtxns == 0);
+
+ ReorderBufferDiscardAppliedChanges(rb, subtxn, last_lsn,
+ subtxn == aborted_txn ||
+ rbtxn_is_aborted(subtxn));
+ }
+
+ /*
+ * The next streaming run rebuilds the hash. Leave the tuplecid list
+ * itself in place, as TruncateTXN does for a transaction that is not
+ * being prepared.
+ */
+ if (txn->tuplecid_hash != NULL)
+ {
+ hash_destroy(txn->tuplecid_hash);
+ txn->tuplecid_hash = NULL;
+ }
+
+ /* Free all resources allocated for toast reconstruction */
+ ReorderBufferToastReset(rb, txn);
+ }
/*
* For the streaming case, stop the stream and remember the command ID and
- * snapshot for the streaming run.
+ * snapshot for the streaming run. snapshot_now already reflects every
+ * snapshot change applied before the error. Snapshot changes that were
+ * not reached are still queued and applied on the next run.
*/
if (rbtxn_is_streamed(txn))
{
rb->stream_stop(rb, txn, last_lsn);
ReorderBufferSaveTXNSnapshot(rb, txn, snapshot_now, command_id);
}
-
- /* All changes must be deallocated */
- Assert(txn->size == 0);
}
/*
@@ -2808,7 +2890,7 @@ ReorderBufferProcessTXN(ReorderBuffer *rb, ReorderBufferTXN *txn,
/* Reset the TXN so that it is allowed to stream remaining data. */
ReorderBufferResetTXN(rb, txn, snapshot_now,
- command_id, prev_lsn);
+ command_id, prev_lsn, curtxn);
}
else
{
@@ -4085,6 +4167,12 @@ ReorderBufferCheckMemoryLimit(ReorderBuffer *rb)
continue;
ReorderBufferStreamTXN(rb, txn);
+
+ /*
+ * A concurrent subtransaction abort leaves not-yet-streamed
+ * changes queued. Loop and stream those next. Their bytes are
+ * still charged against the memory limit.
+ */
}
else
{
@@ -4104,14 +4192,14 @@ ReorderBufferCheckMemoryLimit(ReorderBuffer *rb)
continue;
ReorderBufferSerializeTXN(rb, txn);
- }
- /*
- * After eviction, the transaction should have no entries in memory,
- * and should use 0 bytes for changes.
- */
- Assert(txn->size == 0);
- Assert(txn->nentries_mem == 0);
+ /*
+ * After eviction, the transaction should have no entries in
+ * memory, and should use 0 bytes for changes.
+ */
+ Assert(txn->size == 0);
+ Assert(txn->nentries_mem == 0);
+ }
/*
* We've reported the memExceededCount update while streaming or
@@ -4584,9 +4672,11 @@ ReorderBufferStreamTXN(ReorderBuffer *rb, ReorderBufferTXN *txn)
/* update the decoding stats */
UpdateDecodingStats((LogicalDecodingContext *) rb->private_data);
- Assert(dlist_is_empty(&txn->changes));
- Assert(txn->nentries == 0);
- Assert(txn->nentries_mem == 0);
+ /*
+ * Changes that were not streamed, because a subtransaction aborted
+ * concurrently, stay queued. Do not assert that the toplevel change list
+ * is empty: the caller streams whatever remains.
+ */
}
/*
@@ -5013,6 +5103,285 @@ ReorderBufferRestoreCleanup(ReorderBuffer *rb, ReorderBufferTXN *txn)
}
}
+/*
+ * Free every in-memory change of one transaction and account for it once.
+ */
+static void
+ReorderBufferFreeChangeList(ReorderBuffer *rb, ReorderBufferTXN *txn)
+{
+ dlist_mutable_iter iter;
+ Size mem_freed = 0;
+
+ dlist_foreach_modify(iter, &txn->changes)
+ {
+ ReorderBufferChange *change;
+
+ change = dlist_container(ReorderBufferChange, node, iter.cur);
+ Assert(change->txn == txn);
+
+ dlist_delete(&change->node);
+ mem_freed += ReorderBufferChangeSize(change);
+ ReorderBufferFreeChange(rb, change, false);
+ }
+
+ ReorderBufferChangeMemoryUpdate(rb, NULL, txn, false, mem_freed);
+ txn->nentries_mem = 0;
+}
+
+/*
+ * Read every spill file of a serialized transaction.
+ *
+ * When xact_aborted is false, requeue changes whose LSN is at least min_lsn.
+ * There is no max_changes_in_memory cap: the caller deletes the spill files
+ * after this returns, so a partial restore would lose the rest. Returns true
+ * if a change older than min_lsn was stored on disk (it was already streamed).
+ *
+ * The caller must already have freed the in-memory change list.
+ */
+static bool
+ReorderBufferRestoreSerializedChanges(ReorderBuffer *rb, ReorderBufferTXN *txn,
+ XLogRecPtr min_lsn, bool xact_aborted)
+{
+ TXNEntryFile file;
+ XLogSegNo segno = 0;
+ XLogSegNo last_segno;
+ bool sent_earlier = false;
+
+ Assert(rbtxn_is_serialized(txn));
+ Assert(XLogRecPtrIsValid(txn->first_lsn));
+ Assert(XLogRecPtrIsValid(txn->final_lsn));
+ Assert(XLogRecPtrIsValid(min_lsn));
+ Assert(dlist_is_empty(&txn->changes));
+ Assert(txn->nentries_mem == 0);
+
+ file.vfd = -1;
+ file.curOffset = 0;
+
+ XLByteToSeg(txn->final_lsn, last_segno, wal_segment_size);
+
+ for (;;)
+ {
+ ssize_t readBytes;
+ ReorderBufferDiskChange *ondisk;
+ XLogRecPtr change_lsn;
+ Size ondisk_size;
+ bool keep;
+
+ CHECK_FOR_INTERRUPTS();
+
+ if (segno > last_segno && file.vfd == -1)
+ break;
+
+ if (file.vfd == -1)
+ {
+ char path[MAXPGPATH];
+
+ /* first time in */
+ if (segno == 0)
+ XLByteToSeg(txn->first_lsn, segno, wal_segment_size);
+
+ if (segno > last_segno)
+ break;
+
+ ReorderBufferSerializedPath(path, MyReplicationSlot, txn->xid,
+ segno);
+
+ file.vfd = PathNameOpenFile(path, O_RDONLY | PG_BINARY);
+ file.curOffset = 0;
+
+ if (file.vfd < 0 && errno == ENOENT)
+ {
+ file.vfd = -1;
+ segno++;
+ continue;
+ }
+ else if (file.vfd < 0)
+ ereport(ERROR,
+ (errcode_for_file_access(),
+ errmsg("could not open file \"%s\": %m", path)));
+ }
+
+ ReorderBufferSerializeReserve(rb, sizeof(ReorderBufferDiskChange));
+ readBytes = FileRead(file.vfd, rb->outbuf,
+ sizeof(ReorderBufferDiskChange),
+ file.curOffset,
+ WAIT_EVENT_REORDER_BUFFER_READ);
+
+ /* eof */
+ if (readBytes == 0)
+ {
+ FileClose(file.vfd);
+ file.vfd = -1;
+ segno++;
+ continue;
+ }
+ else if (readBytes < 0)
+ ereport(ERROR,
+ (errcode_for_file_access(),
+ errmsg("could not read from reorderbuffer spill file: %m")));
+ else if (readBytes != sizeof(ReorderBufferDiskChange))
+ ereport(ERROR,
+ (errcode_for_file_access(),
+ errmsg("could not read from reorderbuffer spill file: read %zd of %zu",
+ readBytes, sizeof(ReorderBufferDiskChange))));
+
+ file.curOffset += readBytes;
+
+ ondisk = (ReorderBufferDiskChange *) rb->outbuf;
+ change_lsn = ondisk->change.lsn;
+ ondisk_size = ondisk->size;
+
+ if (change_lsn < min_lsn)
+ sent_earlier = true;
+
+ keep = !xact_aborted && change_lsn >= min_lsn;
+
+ if (keep)
+ {
+ /*
+ * SerializeReserve may move outbuf. The header is already there;
+ * read the payload behind it.
+ */
+ ReorderBufferSerializeReserve(rb, ondisk_size);
+ readBytes = FileRead(file.vfd,
+ rb->outbuf + sizeof(ReorderBufferDiskChange),
+ ondisk_size - sizeof(ReorderBufferDiskChange),
+ file.curOffset,
+ WAIT_EVENT_REORDER_BUFFER_READ);
+
+ if (readBytes < 0)
+ ereport(ERROR,
+ (errcode_for_file_access(),
+ errmsg("could not read from reorderbuffer spill file: %m")));
+ else if (readBytes != ondisk_size - sizeof(ReorderBufferDiskChange))
+ ereport(ERROR,
+ (errcode_for_file_access(),
+ errmsg("could not read from reorderbuffer spill file: read %zd of %zu",
+ readBytes,
+ ondisk_size - sizeof(ReorderBufferDiskChange))));
+
+ file.curOffset += readBytes;
+ ReorderBufferRestoreChange(rb, txn, rb->outbuf);
+ }
+ else
+ file.curOffset += ondisk_size - sizeof(ReorderBufferDiskChange);
+ }
+
+ if (file.vfd != -1)
+ FileClose(file.vfd);
+
+ return sent_earlier;
+}
+
+/*
+ * Drop changes that must not be replayed after a concurrent subtransaction
+ * abort during streaming.
+ *
+ * Changes with LSN < min_lsn were applied before the error. The change at
+ * min_lsn is the one that failed, or a not-yet-visited change with that same
+ * LSN; keep the latter unless this transaction aborted. Returns true when a
+ * change older than min_lsn was present.
+ *
+ * A serialized transaction's in-memory list is only a window onto the spill
+ * file, and the spill file is the complete set. Rebuild keepers from the
+ * spill file and remove it. Replaying the spill from the start on the next
+ * stream would otherwise resend changes the output plugin has already seen.
+ */
+static bool
+ReorderBufferDiscardAppliedChanges(ReorderBuffer *rb, ReorderBufferTXN *txn,
+ XLogRecPtr min_lsn, bool xact_aborted)
+{
+ bool sent_earlier = false;
+ dlist_iter iter;
+
+ if (rbtxn_is_serialized(txn))
+ {
+ dlist_foreach(iter, &txn->changes)
+ {
+ ReorderBufferChange *change;
+
+ change = dlist_container(ReorderBufferChange, node, iter.cur);
+ if (change->lsn < min_lsn)
+ sent_earlier = true;
+ }
+
+ ReorderBufferFreeChangeList(rb, txn);
+
+ if (ReorderBufferRestoreSerializedChanges(rb, txn, min_lsn,
+ xact_aborted))
+ sent_earlier = true;
+
+ ReorderBufferRestoreCleanup(rb, txn);
+ txn->txn_flags &= ~RBTXN_IS_SERIALIZED;
+ txn->txn_flags |= RBTXN_IS_SERIALIZED_CLEAR;
+ }
+ else if (xact_aborted)
+ {
+ dlist_foreach(iter, &txn->changes)
+ {
+ ReorderBufferChange *change;
+
+ change = dlist_container(ReorderBufferChange, node, iter.cur);
+ if (change->lsn < min_lsn)
+ sent_earlier = true;
+ }
+
+ ReorderBufferFreeChangeList(rb, txn);
+ }
+ else
+ {
+ dlist_mutable_iter miter;
+ Size mem_freed = 0;
+
+ dlist_foreach_modify(miter, &txn->changes)
+ {
+ ReorderBufferChange *change;
+
+ change = dlist_container(ReorderBufferChange, node, miter.cur);
+ Assert(change->txn == txn);
+
+ if (change->lsn >= min_lsn)
+ continue;
+
+ sent_earlier = true;
+ dlist_delete(&change->node);
+ mem_freed += ReorderBufferChangeSize(change);
+ ReorderBufferFreeChange(rb, change, false);
+ }
+
+ ReorderBufferChangeMemoryUpdate(rb, NULL, txn, false, mem_freed);
+ txn->nentries_mem = 0;
+ }
+
+ /*
+ * nentries counts toast chunks that have been unlinked into the toast
+ * hash as well as changes already freed by the iterator. Neither is on
+ * the list. The iterator treats nentries != nentries_mem as a signal to
+ * read a spill file, so both counters must match the list now that any
+ * spill file is gone.
+ */
+ txn->nentries = 0;
+ dlist_foreach(iter, &txn->changes)
+ txn->nentries++;
+ txn->nentries_mem = txn->nentries;
+
+ if (xact_aborted)
+ Assert(txn->nentries == 0);
+
+ /*
+ * Remember that this subtransaction was streamed when one of its changes
+ * was applied. The toplevel transaction is marked by the caller. Marking
+ * a subtransaction that the downstream has not seen would make us send a
+ * stream abort for an unknown xid.
+ */
+ if (sent_earlier &&
+ rbtxn_is_known_subxact(txn) &&
+ rbtxn_is_streamed(rbtxn_get_toptxn(txn)))
+ txn->txn_flags |= RBTXN_IS_STREAMED;
+
+ return sent_earlier;
+}
+
/*
* Remove any leftover serialized reorder buffers from a slot directory after a
* prior crash or decoding session exit.
base-commit: 8e27c9261c9dd6127e16ced998d37ed7a8cb2b7d
--
2.53.0