From 479978dcee2fa29f145d7d79fe205cddc4ac5191 Mon Sep 17 00:00:00 2001 From: Zhijie Hou Date: Wed, 2 Sep 2026 17:24:26 +0800 Subject: [PATCH 1/3] Re-initialize conflict slot xmin when a database newly needs retention Since the retain_dead_tuples feature maintains one replication slot for all subscriptions, if two subscriptions are created at different times, the later one may cause slot.xmin to move backwards. For example, consider two subscriptions for databases A and B. The oldest XID in database A is 700, while the oldest XID in database B is 500 (due to a long-running transaction in that database). If subscription A is created first, conflict_detection_slot.xmin advances to 700. When subscription B is later created, it sees that the oldest XID in its own database is 500 ? which is older than the current slot.xmin. This currently causes an Assert failure in the apply worker. If the Assert is removed, it would allow slot.xmin to move backwards. Moving slot.xmin backwards is actually correct behavior for subscription of database B: the long-running transaction in database B is a candidate that could generate dead tuples needed for update_deleted conflict detection, so slot.xmin should not advance beyond that XID. However, instead of letting the worker handle this (which could delay the slot.xmin update), we should have the launcher detect the new subscription and adjust the slot directly. The patch fix this by tracking the set of databases with actively-retaining subscriptions in the launcher, and when a database newly appears in the set, re-initialize the slot's xmin to the cluster-wide safe decoding horizon before launching any workers. The horizon accounts for all running transactions cluster-wide, so it is a safe seed for every database. --- src/backend/replication/logical/launcher.c | 79 ++++++++++++++++----- src/test/subscription/t/035_conflicts.pl | 80 ++++++++++++++++++++++ 2 files changed, 143 insertions(+), 16 deletions(-) diff --git a/src/backend/replication/logical/launcher.c b/src/backend/replication/logical/launcher.c index 313e31ff2e3..6423f1e137c 100644 --- a/src/backend/replication/logical/launcher.c +++ b/src/backend/replication/logical/launcher.c @@ -1204,6 +1204,8 @@ ApplyLauncherWakeup(void) void ApplyLauncherMain(Datum main_arg) { + List *retained_dbids; + ereport(DEBUG1, (errmsg_internal("logical replication launcher started"))); @@ -1222,6 +1224,13 @@ ApplyLauncherMain(Datum main_arg) */ BackgroundWorkerInitializeConnection(NULL, NULL, 0); + /* + * Databases with actively-retaining subscriptions as of the previous + * cycle. Local memory only, so every such database counts as new after a + * launcher restart, re-initializing the slot's xmin once at startup. + */ + retained_dbids = NIL; + /* * Acquire the conflict detection slot at startup to ensure it can be * dropped if no longer needed after a restart. @@ -1239,7 +1248,9 @@ ApplyLauncherMain(Datum main_arg) long wait_time = DEFAULT_NAPTIME_PER_CYCLE; bool can_update_xmin = true; bool retain_dead_tuples = false; + bool reinit_done = false; TransactionId xmin = InvalidTransactionId; + List *current_dbids = NIL; CHECK_FOR_INTERRUPTS(); @@ -1288,6 +1299,29 @@ ApplyLauncherMain(Datum main_arg) if (sub->retentionactive) { + /* Remember the retained databases for the next cycle. */ + current_dbids = lappend_oid(current_dbids, sub->dbid); + + /* + * Initialize the slot's xmin if it is not valid, or + * re-initialize it if this database newly appears among + * the retained databases: the xmin may be newer than the + * new database's oldest active transaction ID, violating + * the per-database invariant checked in + * get_candidate_xid(). The set is keyed on + * subretentionactive, so that a subscription resuming + * retention is also treated as a new arrival. One call + * per cycle is enough, as the horizon is a safe seed for + * every database. + */ + if (!reinit_done && + (!TransactionIdIsValid(MyReplicationSlot->data.xmin) || + !list_member_oid(retained_dbids, sub->dbid))) + { + init_conflict_slot_xmin(); + reinit_done = true; + } + /* * Can't advance xmin of the slot unless all the * subscriptions actively retaining dead tuples are @@ -1299,13 +1333,6 @@ ApplyLauncherMain(Datum main_arg) * retain_dead_tuples option. */ can_update_xmin &= sub->enabled; - - /* - * Initialize the slot once the subscription activates - * retention. - */ - if (!TransactionIdIsValid(MyReplicationSlot->data.xmin)) - init_conflict_slot_xmin(); } } @@ -1414,6 +1441,14 @@ ApplyLauncherMain(Datum main_arg) /* Switch back to original memory context. */ MemoryContextSwitchTo(oldctx); + + /* + * Remember the current set of retained databases for the next cycle, + * in long-lived memory. + */ + list_free(retained_dbids); + retained_dbids = list_copy(current_dbids); + /* Clean the temporary memory. */ MemoryContextDelete(subctx); @@ -1530,28 +1565,40 @@ update_conflict_slot_xmin(TransactionId new_xmin) } /* - * Initialize the xmin for the conflict detection slot. + * Initialize or re-initialize the xmin for the conflict detection slot to + * the cluster-wide safe decoding horizon, which is a safe seed for an + * apply worker in any database. + * + * Re-initialization is needed when a database newly appears among the + * databases with actively-retaining subscriptions; see ApplyLauncherMain(). + * An already-valid xmin is only moved backwards, as advancing it here + * would bypass the advancement protocol; regressing is safe, and the + * workers will advance the xmin again in later cycles. */ static void init_conflict_slot_xmin(void) { TransactionId xmin_horizon; - /* Replication slot must exist but shouldn't be initialized. */ - Assert(MyReplicationSlot && - !TransactionIdIsValid(MyReplicationSlot->data.xmin)); + Assert(MyReplicationSlot); LWLockAcquire(ReplicationSlotControlLock, LW_EXCLUSIVE); LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); xmin_horizon = GetOldestSafeDecodingTransactionId(false); - SpinLockAcquire(&MyReplicationSlot->mutex); - MyReplicationSlot->effective_xmin = xmin_horizon; - MyReplicationSlot->data.xmin = xmin_horizon; - SpinLockRelease(&MyReplicationSlot->mutex); + if (!TransactionIdIsValid(MyReplicationSlot->data.xmin) || + TransactionIdPrecedes(xmin_horizon, MyReplicationSlot->data.xmin)) + { + SpinLockAcquire(&MyReplicationSlot->mutex); + MyReplicationSlot->effective_xmin = xmin_horizon; + MyReplicationSlot->data.xmin = xmin_horizon; + SpinLockRelease(&MyReplicationSlot->mutex); + + elog(DEBUG1, "initialized xmin: %u", MyReplicationSlot->data.xmin); - ReplicationSlotsComputeRequiredXmin(true); + ReplicationSlotsComputeRequiredXmin(true); + } LWLockRelease(ProcArrayLock); LWLockRelease(ReplicationSlotControlLock); diff --git a/src/test/subscription/t/035_conflicts.pl b/src/test/subscription/t/035_conflicts.pl index 3910a49c0aa..e77af772d19 100644 --- a/src/test/subscription/t/035_conflicts.pl +++ b/src/test/subscription/t/035_conflicts.pl @@ -649,6 +649,86 @@ $result = $node_A->safe_psql('postgres', ); is($result, qq(t), 'retention is active'); +############################################################################### +# Check that the conflict detection slot's xmin is re-initialized when a +# database newly appears among the databases with retain_dead_tuples +# subscriptions. +# +# The slot's xmin is advanced according to the per-database horizons of the +# databases seen so far. Without re-initialization, a worker started in a +# newly retaining database whose oldest active transaction ID is older would +# be seeded with a value newer than its database's horizon (which used to +# fire an assertion in get_candidate_xid()). +############################################################################### + +# Create a second database on node B, with the same table. +$node_B->safe_psql('postgres', "CREATE DATABASE dbb"); +$node_B->safe_psql('dbb', "CREATE TABLE tab (a int PRIMARY KEY, b int)"); + +$log_location = -s $node_B->logfile; + +# Hold a transaction with an assigned transaction ID open in dbb, pinning its +# oldest active transaction ID. +my $dbb_session = $node_B->background_psql('dbb'); +$dbb_session->query_until( + qr/starting_bg_psql/, q{ + \echo starting_bg_psql + BEGIN; + SELECT txid_current(); +}); + +# Push the transaction ID counter clearly past the pinned transaction ID and +# wait for the slot's xmin to advance past it. Only the apply worker in the +# postgres database drives the slot's xmin here, and postgres has no old +# transaction running. +$next_xid = $node_B->safe_psql('postgres', "SELECT txid_current() + 1"); +ok( $node_B->poll_query_until( + 'postgres', + "SELECT xmin::text::bigint >= $next_xid FROM pg_replication_slots WHERE slot_name = 'pg_conflict_detection'" + ), + "slot xmin advanced past the transaction ID pinned in dbb"); + +# Create the second retention subscription in dbb. The launcher must +# re-initialize the slot's xmin before launching dbb's apply worker. +my $subname_BA2 = 'tap_sub_b_a2'; +$node_B->safe_psql('dbb', + "CREATE SUBSCRIPTION $subname_BA2 + CONNECTION '$node_A_connstr application_name=$subname_BA2' + PUBLICATION tap_pub_A + WITH (retain_dead_tuples = true, origin = none)"); +$node_B->wait_for_subscription_sync($node_A, $subname_BA2); + +# The slot's xmin must regress to the horizon pinned in dbb. +ok( $node_B->poll_query_until( + 'postgres', + "SELECT xmin::text::bigint < $next_xid FROM pg_replication_slots WHERE slot_name = 'pg_conflict_detection'" + ), + "slot xmin regressed to the horizon pinned in dbb"); + +# No apply worker must have crashed while setting up the second subscription. +$logfile = slurp_file($node_B->logfile(), $log_location); +unlike($logfile, qr/was terminated by signal/, 'no apply worker crash'); + +# Once the pinned transaction commits, the xmin must be able to advance +# again. +$dbb_session->query_until( + qr/committed/, q{ + COMMIT; + \echo committed +}); +ok($dbb_session->quit, 'close pinned session'); + +$next_xid = $node_B->safe_psql('postgres', "SELECT txid_current() + 1"); +ok( $node_B->poll_query_until( + 'postgres', + "SELECT xmin::text::bigint >= $next_xid FROM pg_replication_slots WHERE slot_name = 'pg_conflict_detection'" + ), + "slot xmin advances again after the pinned transaction commits"); + +# Clean up the second database. +$node_B->safe_psql('dbb', "DROP SUBSCRIPTION $subname_BA2"); +$node_B->safe_psql('postgres', "DROP DATABASE dbb"); + ############################################################################### # Check that the replication slot pg_conflict_detection is dropped after # removing all the subscriptions. -- 2.47.3