pg.ddx.io  pgsql-hackers@postgresql.org mailing list archive  
help / color / mirror / Atom feed
Recovery conflict resolution misses backends that import snapshots
8+ messages / 5 participants
[nested] [flat]

* Recovery conflict resolution misses backends that import snapshots
@ 2026-07-25 23:03 Scott Ray <scott@scottray.io>
  2026-07-26 23:49 ` Re: Recovery conflict resolution misses backends that import snapshots Michael Paquier <michael@paquier.xyz>
  0 siblings, 1 reply; 8+ messages in thread

From: Scott Ray @ 2026-07-25 23:03 UTC (permalink / raw)
  To: PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

Hello,

There is a silent bug in standby conflict resolution that can cause
incorrect results.  In ResolveRecoveryConflictWithSnapshot, the standby
calls GetConflictingVirtualXIDs once, then waits for each returned VXID
to disappear.  However, after GetConflictingVirtualXIDs releases the
ProcArrayLock, a backend may import a conflicting snapshot from one of
the backends GetConflictingVirtualXIDs identified as conflicting.  The
resulting VXID conflicts with recovery, but
ResolveRecoveryConflictWithSnapshot doesn't know it has to wait for the
new VXID to disappear before proceeding, so the standby removes tuple
versions or index entries that the importing backend needs.

This problem has existed since PG 10 (6c2003f8a1b), which introduced
standby snapshot export and broke ResolveRecoveryConflictWithSnapshot's
assumption that after GetConflictingVirtualXIDs returns, no new
conflicting VXIDs can be created.

The first attached patch adds a TAP test that fails deterministically
on unpatched master.  The second makes
ResolveRecoveryConflictWithSnapshot call GetConflictingVirtualXIDs
until the result is empty, at which point importing a conflicting
snapshot is impossible: acquiring a conflicting xmin requires a live,
conflicting VXID as a source.

--
Scott Ray

Attachments: download all (3 files, .tar.gz)

v1-0002-Fix-recovery-conflict-resolution-to-account-for-i.patch (application/octet-stream, 4.6K) download From 51ec93006f03dbacb39d033ee6313083f1861c93 Mon Sep 17 00:00:00 2001 From: Scott Ray <scott@scottray.io> Date: Sat, 25 Jul 2026 15:36:49 -0700 Subject: [PATCH v1 2/2] Fix recovery conflict resolution to account for imported snapshots Make ResolveRecoveryConflictWithSnapshot call GetConflictingVirtualXIDs until no conflict remains, fixing a wrong-results bug where, after the first call, a backend could import a conflicting snapshot, creating a new conflict invisible to standby recovery. --- src/backend/storage/ipc/procarray.c | 15 ++++++++++--- src/backend/storage/ipc/standby.c | 35 ++++++++++++++++++++++++----- 2 files changed, 41 insertions(+), 9 deletions(-) diff --git a/src/backend/storage/ipc/procarray.c b/src/backend/storage/ipc/procarray.c index 9299bcebbda..7f9025b9579 100644 --- a/src/backend/storage/ipc/procarray.c +++ b/src/backend/storage/ipc/procarray.c @@ -3351,7 +3351,8 @@ GetCurrentVirtualXIDs(TransactionId limitXmin, bool excludeXmin0, } /* - * GetConflictingVirtualXIDs -- returns an array of currently active VXIDs. + * GetConflictingVirtualXIDs -- returns an array of currently active VXIDs + * considered in conflict with recovery up to limitXmin. * * Usage is limited to conflict resolution during recovery on standby servers. * limitXmin is supplied as either a cutoff with snapshotConflictHorizon @@ -3380,6 +3381,13 @@ GetCurrentVirtualXIDs(TransactionId limitXmin, bool excludeXmin0, * but that would not be true in the case of FATAL errors lagging in array, * but we already know those are bogus anyway, so we skip that test. * + * That reasoning covers snapshots acquired with GetSnapshotData, which yields + * transaction xmins above limitXmin, but it does not cover backends that + * import snapshots using SET TRANSACTION SNAPSHOT, which call + * ProcArrayInstallImportedXmin instead. A backend that imports a snapshot + * from one of the conflicting backends can acquire xmin <= limitXmin, so + * the conflicting VXID set can grow, but only while the set is non-empty. + * * If dbOid is valid we skip backends attached to other databases. * * Be careful to *not* pfree the result from this function. We reuse @@ -3430,8 +3438,9 @@ GetConflictingVirtualXIDs(TransactionId limitXmin, Oid dbOid) * no snapshot currently. We hold a Share lock to avoid contention * with users taking snapshots. That is not a problem because the * current xmin is always at least one higher than the latest - * removed xid, so any new snapshot would never conflict with the - * test here. + * removed xid, so any snapshot acquired with GetSnapshotData + * would never conflict with the test here. See the header + * comment for the caveat about imported snapshots. */ if (!TransactionIdIsValid(limitXmin) || (TransactionIdIsValid(pxmin) && !TransactionIdFollows(pxmin, limitXmin))) diff --git a/src/backend/storage/ipc/standby.c b/src/backend/storage/ipc/standby.c index 29af7733948..5c957b03e6d 100644 --- a/src/backend/storage/ipc/standby.c +++ b/src/backend/storage/ipc/standby.c @@ -489,12 +489,35 @@ ResolveRecoveryConflictWithSnapshot(TransactionId snapshotConflictHorizon, return; Assert(TransactionIdIsNormal(snapshotConflictHorizon)); - backends = GetConflictingVirtualXIDs(snapshotConflictHorizon, - locator.dbOid); - ResolveRecoveryConflictWithVirtualXIDs(backends, - RECOVERY_CONFLICT_SNAPSHOT, - WAIT_EVENT_RECOVERY_CONFLICT_SNAPSHOT, - true); + + /* + * Scan until no conflicting VXID remains. + * + * GetConflictingVirtualXIDs returns the list of conflicting VXIDs that + * existed while it held the ProcArrayLock. While we wait for these VXIDs + * to resolve, a backend may import a conflicting snapshot, creating a + * new, conflicting VXID from one of the VXIDs in the returned list. Any + * new conflict requires a live, conflicting VXID as a source, so we loop + * until GetConflictingVirtualXIDs returns empty, which means no + * conflicting VXID exists and no future VXID will conflict. + * + * The cancellation cutoff is anchored to WAL receipt time + * (GetStandbyLimitTime), not to the start of each wait, so all iterations + * of this loop share a single max_standby_streaming_delay budget. + */ + for (;;) + { + backends = GetConflictingVirtualXIDs(snapshotConflictHorizon, + locator.dbOid); + + if (!VirtualTransactionIdIsValid(backends[0])) + break; + + ResolveRecoveryConflictWithVirtualXIDs(backends, + RECOVERY_CONFLICT_SNAPSHOT, + WAIT_EVENT_RECOVERY_CONFLICT_SNAPSHOT, + true); + } /* * Note that WaitExceedsMaxStandbyDelay() is not taken into account here -- 2.50.1 (Apple Git-155)
v1-0001-Add-TAP-test-for-recovery-conflicts-from-imported.patch (application/octet-stream, 6.9K) download From edec90b93483a15a534a59dc6bdcc31a515f0827 Mon Sep 17 00:00:00 2001 From: Scott Ray <scott@scottray.io> Date: Sat, 25 Jul 2026 15:36:49 -0700 Subject: [PATCH v1 1/2] Add TAP test for recovery conflicts from imported snapshots Add a TAP test verifying that a standby detects conflicts introduced by snapshots imported after its first conflict scan in ResolveRecoveryConflictWithSnapshot. --- src/test/recovery/meson.build | 1 + .../recovery/t/099_conflict_import_race.pl | 151 ++++++++++++++++++ 2 files changed, 152 insertions(+) create mode 100644 src/test/recovery/t/099_conflict_import_race.pl diff --git a/src/test/recovery/meson.build b/src/test/recovery/meson.build index 36d789720a3..afdabe33353 100644 --- a/src/test/recovery/meson.build +++ b/src/test/recovery/meson.build @@ -61,6 +61,7 @@ tests += { 't/050_redo_segment_missing.pl', 't/051_effective_wal_level.pl', 't/052_checkpoint_segment_missing.pl', + 't/099_conflict_import_race.pl', ], }, } diff --git a/src/test/recovery/t/099_conflict_import_race.pl b/src/test/recovery/t/099_conflict_import_race.pl new file mode 100644 index 00000000000..1922daf4c42 --- /dev/null +++ b/src/test/recovery/t/099_conflict_import_race.pl @@ -0,0 +1,151 @@ +# Copyright (c) 2026, PostgreSQL Global Development Group +# +# Verify that a standby does not remove tuple versions visible to backends that +# import snapshots during conflict resolution. During recovery, the standby +# determines which VXIDs conflict with recovery and waits for these VXIDs to +# resolve. If it checks only once for conflicting VXIDs, it may miss a +# conflicting VXID created later by a backend importing a snapshot -- an +# invisible conflict leading to incorrect results for the importing backend. + +use strict; +use warnings FATAL => 'all'; +use PostgreSQL::Test::Cluster; +use PostgreSQL::Test::Utils; +use Test::More; +use Time::HiRes qw(usleep); + +my $node_primary = PostgreSQL::Test::Cluster->new('primary'); +$node_primary->init(allows_streaming => 1); +$node_primary->append_conf( + 'postgresql.conf', qq[ +autovacuum = off +]); +$node_primary->start; + +my $backup_name = 'my_backup'; +$node_primary->backup($backup_name); + +my $node_standby = PostgreSQL::Test::Cluster->new('standby'); +$node_standby->init_from_backup($node_primary, $backup_name, + has_streaming => 1); + +# max_standby_streaming_delay = -1 makes replay wait rather than cancel. The +# conflict reports are not diagnostic: the test reads them to tell which +# backends each scan found. +$node_standby->append_conf( + 'postgresql.conf', qq[ +hot_standby_feedback = off +max_standby_streaming_delay = -1 +log_recovery_conflict_waits = on +deadlock_timeout = 10ms +]); +$node_standby->start; + +$node_primary->safe_psql( + 'postgres', qq[ +CREATE TABLE t (id int); +INSERT INTO t SELECT generate_series(1, 100); +]); +$node_primary->wait_for_replay_catchup($node_standby); + +is($node_standby->safe_psql('postgres', 'SELECT count(*) FROM t'), + 100, 'standby sees 100 rows before conflict'); + +# S1: Register an xmin and export its snapshot. +my $s1 = $node_standby->background_psql('postgres', on_error_stop => 0); +$s1->query_safe(qq[BEGIN TRANSACTION ISOLATION LEVEL REPEATABLE READ;]); +my $s1_count = $s1->query_safe(qq[SELECT count(*) FROM t;]); +like($s1_count, qr/^100$/m, 'S1 sees 100 rows, snapshot registered'); +my $snapid = $s1->query_safe(qq[SELECT pg_export_snapshot();]); +$snapid =~ s/^\s+|\s+$//g; +note("exported snapshot id: $snapid"); + +# S1's backend_xmin as seen on the standby. +my $s1_pid = $s1->query_safe(qq[SELECT pg_backend_pid();]); +$s1_pid =~ s/^\s+|\s+$//g; +my $s1_xmin = $node_standby->safe_psql('postgres', + qq[SELECT backend_xmin FROM pg_stat_activity WHERE pid = $s1_pid;]); +note("S1 pid=$s1_pid backend_xmin=$s1_xmin"); + +# Primary: delete and vacuum so the prune record conflicts with S1. +my $log_offset = -s $node_standby->logfile; +my $lsn_before_vac = + $node_primary->safe_psql('postgres', 'SELECT pg_current_wal_lsn()'); +$node_primary->safe_psql( + 'postgres', qq[ +DELETE FROM t; +VACUUM t; +]); +my $lsn_after_vac = + $node_primary->safe_psql('postgres', 'SELECT pg_current_wal_lsn()'); +note("primary WAL: before vacuum=$lsn_before_vac after=$lsn_after_vac"); + +# The first scan must find exactly S1. +$log_offset = $node_standby->wait_for_log(qr/Conflicting process: $s1_pid\./, + $log_offset); + +my $replay_lsn = + $node_standby->safe_psql('postgres', 'SELECT pg_last_wal_replay_lsn()'); +note("standby replay stalled at $replay_lsn (primary at $lsn_after_vac)"); + +# S2: a new backend imports S1's snapshot +my $s2 = $node_standby->background_psql('postgres', on_error_stop => 0); +$s2->query_safe(qq[BEGIN TRANSACTION ISOLATION LEVEL REPEATABLE READ;]); +$s2->query_safe(qq[SET TRANSACTION SNAPSHOT '$snapid';]); + +my $s2_pid = $s2->query_safe(qq[SELECT pg_backend_pid();]); +$s2_pid =~ s/^\s+|\s+$//g; +my $s2_xmin = $node_standby->safe_psql('postgres', + qq[SELECT backend_xmin FROM pg_stat_activity WHERE pid = $s2_pid;]); +note("S2 pid=$s2_pid backend_xmin=$s2_xmin (S1 xmin was $s1_xmin)"); +is($s2_xmin, $s1_xmin, "S2 adopted S1's xmin"); + +# S1 exits, draining the set the first scan found. +$s1->query_safe(qq[COMMIT;]); +$s1->quit; + +# Wait until the standby commits to one behavior or the other: it either +# rescans and reports S2, or it resumes replay past the prune record. Waiting +# only for the rescan would turn the wrong-results case into a timeout instead +# of a failed assertion. +my $s2_conflict = qr/Conflicting process: $s2_pid\./; +foreach (1 .. 10 * $PostgreSQL::Test::Utils::timeout_default) +{ + last if $node_standby->log_contains($s2_conflict, $log_offset); + my $advanced = $node_standby->safe_psql('postgres', + qq[SELECT pg_last_wal_replay_lsn() >= '$lsn_after_vac'::pg_lsn]); + last if $advanced eq 't'; + usleep(100_000); +} + +ok($node_standby->log_contains($s2_conflict, $log_offset), + 'second scan found S2'); + +# Replay must not have advanced past the prune record. +my $replay_after_s1 = + $node_standby->safe_psql('postgres', 'SELECT pg_last_wal_replay_lsn()'); +note("replay after S1 exit: $replay_after_s1 (primary at $lsn_after_vac)"); +my $stalled = $node_standby->safe_psql('postgres', + qq[SELECT pg_last_wal_replay_lsn() < '$lsn_after_vac'::pg_lsn]); +is($stalled, 't', 'replay stalled while S2 holds the imported snapshot'); + +my $s2_result = $s2->query_safe(qq[SELECT count(*) FROM t;]); +$s2_result =~ s/^\s+|\s+$//g; + +my $s2_alive = $s2->query_safe(qq[SELECT 'alive';]); +like($s2_alive, qr/alive/m, 'S2 not cancelled'); + +is($s2_result, '100', 'S2 sees all rows of its imported snapshot'); + +$s2->query_safe(qq[COMMIT;]); +$s2->quit; + +$node_primary->wait_for_replay_catchup($node_standby); + +is($node_standby->safe_psql('postgres', 'SELECT count(*) FROM t'), + 0, 'standby reflects the pruned table after catchup'); + +$node_standby->stop; +$node_primary->stop; + +done_testing(); -- 2.50.1 (Apple Git-155)
signature.asc (application/pgp-signature, 341B) download ^ permalink raw reply [nested|flat] 8+ messages in thread

* Re: Recovery conflict resolution misses backends that import snapshots
  2026-07-25 23:03 Recovery conflict resolution misses backends that import snapshots Scott Ray <scott@scottray.io>
@ 2026-07-26 23:49 ` Michael Paquier <michael@paquier.xyz>
  2026-07-28 04:44   ` Re: Recovery conflict resolution misses backends that import snapshots Amit Kapila <amit.kapila16@gmail.com>
  0 siblings, 1 reply; 8+ messages in thread

From: Michael Paquier @ 2026-07-26 23:49 UTC (permalink / raw)
  To: Scott Ray <scott@scottray.io>; +Cc: PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>; Masahiko Sawada <sawada.mshk@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Zhijie Hou (Fujitsu) <houzj.fnst@fujitsu.com>; Kuroda, Hayato/黒田 隼人 <kuroda.hayato@fujitsu.com>; Bertrand Drouvot <bertranddrouvot.pg@gmail.com>

On Sat, Jul 25, 2026 at 11:03:52PM +0000, Scott Ray wrote:
> There is a silent bug in standby conflict resolution that can cause
> incorrect results.  In ResolveRecoveryConflictWithSnapshot, the standby
> calls GetConflictingVirtualXIDs once, then waits for each returned VXID
> to disappear.  However, after GetConflictingVirtualXIDs releases the
> ProcArrayLock, a backend may import a conflicting snapshot from one of
> the backends GetConflictingVirtualXIDs identified as conflicting.  The
> resulting VXID conflicts with recovery, but
> ResolveRecoveryConflictWithSnapshot doesn't know it has to wait for the
> new VXID to disappear before proceeding, so the standby removes tuple
> versions or index entries that the importing backend needs.

Hmm.  It looks like you are right here.  I am not the most fluent here
with this area of the code, so adding in CC a couple of folks who
could perhaps comment, being usually interested on these matters.

> The first attached patch adds a TAP test that fails deterministically
> on unpatched master.  The second makes
> ResolveRecoveryConflictWithSnapshot call GetConflictingVirtualXIDs
> until the result is empty, at which point importing a conflicting
> snapshot is impossible: acquiring a conflicting xmin requires a live,
> conflicting VXID as a source.

+	/*
+	 * Scan until no conflicting VXID remains.
[...]
+	for (;;)
+	{

Adding a code pattern that could potentially cause this code path to
loop infinitely is not what I would call a principled approach, I
would call it a risky one.
--
Michael

Attachments:

  signature.asc (application/pgp-signature, 832B) download

^ permalink  raw  reply  [nested|flat] 8+ messages in thread

* Re: Recovery conflict resolution misses backends that import snapshots
  2026-07-25 23:03 Recovery conflict resolution misses backends that import snapshots Scott Ray <scott@scottray.io>
  2026-07-26 23:49 ` Re: Recovery conflict resolution misses backends that import snapshots Michael Paquier <michael@paquier.xyz>
@ 2026-07-28 04:44   ` Amit Kapila <amit.kapila16@gmail.com>
  2026-08-01 22:22     ` Re: Recovery conflict resolution misses backends that import snapshots Scott Ray <scott@scottray.io>
  0 siblings, 1 reply; 8+ messages in thread

From: Amit Kapila @ 2026-07-28 04:44 UTC (permalink / raw)
  To: Michael Paquier <michael@paquier.xyz>; +Cc: Scott Ray <scott@scottray.io>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>; Masahiko Sawada <sawada.mshk@gmail.com>; Zhijie Hou (Fujitsu) <houzj.fnst@fujitsu.com>; Kuroda, Hayato/黒田 隼人 <kuroda.hayato@fujitsu.com>; Bertrand Drouvot <bertranddrouvot.pg@gmail.com>

On Mon, Jul 27, 2026 at 5:19 AM Michael Paquier <michael@paquier.xyz> wrote:
>
> +       /*
> +        * Scan until no conflicting VXID remains.
> [...]
> +       for (;;)
> +       {
>
> Adding a code pattern that could potentially cause this code path to
> loop infinitely is not what I would call a principled approach, I
> would call it a risky one.
>

I think we should at least have CFI in this loop so that it responds
to promotion, shutdown, etc. Currently, it only happens on the waiting
path: ResolveRecoveryConflictWithVirtualXIDs() → inner while
(!VirtualXactLock(*waitlist, false)) → WaitExceedsMaxStandbyDelay(),
which calls CHECK_FOR_INTERRUPTS(). But if a scan returns a non-empty
list and, by the time you call
ResolveRecoveryConflictWithVirtualXIDs(), all those VXIDs have already
ended, VirtualXactLock(..., false) returns true immediately for each
entry, the wait branch is never taken, and that whole call does zero
CFI.

For a finite value of max_standby_streaming_delay, the deadline is
anchored to WAL receipt and does not reset per iteration as mentioned
in the comment in the patch, so once it passes,
ResolveRecoveryConflictWithVirtualXIDs starts cancelling the
conflicting backends (SignalRecoveryConflictWithVirtualXID), not just
waiting. Recovery then makes forward progress by killing sources. A
new importer must find a source that's still alive in a window that
recovery is actively shrinking by terminating everything in it, and
each new importer is itself immediately cancellable on the next pass
(deadline already elapsed → cancel now). So it converges. For
max_standby_streaming_delay = -1, it anyway means "wait forever for
conflicts to clear", so the new behaviour should be acceptable in that
case.

The other way to avoid looping here is to stop the chain from being
extended: past the deadline, refuse new conflicting snapshot imports
on the standby (aka "publish the intended horizon and reject
conflicting imports"). I feel that is over engineering, instead, the
current proposed solution looks reasonable to me but if we still want
to avoid looping then probably we can attempt something like "reject
conflicting imports" in master.

-- 
With Regards,
Amit Kapila.






^ permalink  raw  reply  [nested|flat] 8+ messages in thread

* Re: Recovery conflict resolution misses backends that import snapshots
  2026-07-25 23:03 Recovery conflict resolution misses backends that import snapshots Scott Ray <scott@scottray.io>
  2026-07-26 23:49 ` Re: Recovery conflict resolution misses backends that import snapshots Michael Paquier <michael@paquier.xyz>
  2026-07-28 04:44   ` Re: Recovery conflict resolution misses backends that import snapshots Amit Kapila <amit.kapila16@gmail.com>
@ 2026-08-01 22:22     ` Scott Ray <scott@scottray.io>
  2026-09-11 02:51       ` Re: Recovery conflict resolution misses backends that import snapshots chee.wooson <chee.wooson@gmail.com>
  0 siblings, 1 reply; 8+ messages in thread

From: Scott Ray @ 2026-08-01 22:22 UTC (permalink / raw)
  To: Amit Kapila <amit.kapila16@gmail.com>; +Cc: Michael Paquier <michael@paquier.xyz>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>; Masahiko Sawada <sawada.mshk@gmail.com>; Zhijie Hou (Fujitsu) <houzj.fnst@fujitsu.com>; Kuroda, Hayato/黒田 隼人 <kuroda.hayato@fujitsu.com>; Bertrand Drouvot <bertranddrouvot.pg@gmail.com>

On Monday, July 27th, 2026 at 9:57 PM, Amit Kapila <amit.kapila16@gmail.com> wrote:

> I think we should at least have CFI in this loop so that it responds
> to promotion, shutdown, etc.

If the goal is to make the standby responsive to shutdown, we should
add ProcessStartupProcInterrupts(), which is already called elsewhere
during redo: xlog_redo() -> CheckRequiredParameterValues() ->
RecoveryRequiresIntParameter() -> ProcessStartupProcInterrupts()
in a loop.  CHECK_FOR_INTERRUPTS() doesn't handle shutdown.

If the target is promotion, then we could use CheckForStandbyTrigger().
Conflict resolution occurs while the standby is processing a record,
and from what I can tell, responding to promotion after beginning to
apply the record but before finishing is unprecedented and would force
the standby to decide what to do with the partially-applied record.

The attached v2 calls ProcessStartupProcInterrupts(), and I confirmed
that the standby shuts down promptly when signaled.

On Mon, Jul 27, 2026 at 5:19 AM Michael Paquier
<michael@paquier.xyz> wrote:
>
> Adding a code pattern that could potentially cause this code path to
> loop infinitely is not what I would call a principled approach, I
> would call it a risky one.

I tried to cause an infinite loop using a standby with
max_standby_streaming_delay = 5s, max_connections = 400, and a pool of
clients that relays one old snapshot forward as fast as it can:

t= 1.1s  212 conflicting VXIDs
t= 5.5s  363 population stops growing, no connection slots left
t= 6.6s  277 cutoff has passed, cancellation begins
t= 7.7s  190
t= 8.8s  105
t= 9.9s   16
t=11.0s    0 replay resumes

The standby begins killing VXIDs and kills them too fast for a
sustained relay - at least on my machine with this setup.  The standby
calls pg_usleep(5000) after each signal, which is why the
population remains above 0 for several seconds after the cutoff.

--
Scott Ray

Attachments: download all (3 files, .tar.gz)

v2-0001-Add-TAP-test-for-recovery-conflicts-from-imported.patch (application/octet-stream, 6.9K) download From 0b74385aa349932ecdbd28495da390d6b0dd6f4f Mon Sep 17 00:00:00 2001 From: Scott Ray <scott@scottray.io> Date: Sat, 1 Aug 2026 15:04:54 -0700 Subject: [PATCH v2 1/2] Add TAP test for recovery conflicts from imported snapshots Add a TAP test verifying that a standby detects conflicts introduced by snapshots imported after its first conflict scan in ResolveRecoveryConflictWithSnapshot. --- src/test/recovery/meson.build | 1 + .../recovery/t/099_conflict_import_race.pl | 151 ++++++++++++++++++ 2 files changed, 152 insertions(+) create mode 100644 src/test/recovery/t/099_conflict_import_race.pl diff --git a/src/test/recovery/meson.build b/src/test/recovery/meson.build index 36d789720a3..afdabe33353 100644 --- a/src/test/recovery/meson.build +++ b/src/test/recovery/meson.build @@ -61,6 +61,7 @@ tests += { 't/050_redo_segment_missing.pl', 't/051_effective_wal_level.pl', 't/052_checkpoint_segment_missing.pl', + 't/099_conflict_import_race.pl', ], }, } diff --git a/src/test/recovery/t/099_conflict_import_race.pl b/src/test/recovery/t/099_conflict_import_race.pl new file mode 100644 index 00000000000..1922daf4c42 --- /dev/null +++ b/src/test/recovery/t/099_conflict_import_race.pl @@ -0,0 +1,151 @@ +# Copyright (c) 2026, PostgreSQL Global Development Group +# +# Verify that a standby does not remove tuple versions visible to backends that +# import snapshots during conflict resolution. During recovery, the standby +# determines which VXIDs conflict with recovery and waits for these VXIDs to +# resolve. If it checks only once for conflicting VXIDs, it may miss a +# conflicting VXID created later by a backend importing a snapshot -- an +# invisible conflict leading to incorrect results for the importing backend. + +use strict; +use warnings FATAL => 'all'; +use PostgreSQL::Test::Cluster; +use PostgreSQL::Test::Utils; +use Test::More; +use Time::HiRes qw(usleep); + +my $node_primary = PostgreSQL::Test::Cluster->new('primary'); +$node_primary->init(allows_streaming => 1); +$node_primary->append_conf( + 'postgresql.conf', qq[ +autovacuum = off +]); +$node_primary->start; + +my $backup_name = 'my_backup'; +$node_primary->backup($backup_name); + +my $node_standby = PostgreSQL::Test::Cluster->new('standby'); +$node_standby->init_from_backup($node_primary, $backup_name, + has_streaming => 1); + +# max_standby_streaming_delay = -1 makes replay wait rather than cancel. The +# conflict reports are not diagnostic: the test reads them to tell which +# backends each scan found. +$node_standby->append_conf( + 'postgresql.conf', qq[ +hot_standby_feedback = off +max_standby_streaming_delay = -1 +log_recovery_conflict_waits = on +deadlock_timeout = 10ms +]); +$node_standby->start; + +$node_primary->safe_psql( + 'postgres', qq[ +CREATE TABLE t (id int); +INSERT INTO t SELECT generate_series(1, 100); +]); +$node_primary->wait_for_replay_catchup($node_standby); + +is($node_standby->safe_psql('postgres', 'SELECT count(*) FROM t'), + 100, 'standby sees 100 rows before conflict'); + +# S1: Register an xmin and export its snapshot. +my $s1 = $node_standby->background_psql('postgres', on_error_stop => 0); +$s1->query_safe(qq[BEGIN TRANSACTION ISOLATION LEVEL REPEATABLE READ;]); +my $s1_count = $s1->query_safe(qq[SELECT count(*) FROM t;]); +like($s1_count, qr/^100$/m, 'S1 sees 100 rows, snapshot registered'); +my $snapid = $s1->query_safe(qq[SELECT pg_export_snapshot();]); +$snapid =~ s/^\s+|\s+$//g; +note("exported snapshot id: $snapid"); + +# S1's backend_xmin as seen on the standby. +my $s1_pid = $s1->query_safe(qq[SELECT pg_backend_pid();]); +$s1_pid =~ s/^\s+|\s+$//g; +my $s1_xmin = $node_standby->safe_psql('postgres', + qq[SELECT backend_xmin FROM pg_stat_activity WHERE pid = $s1_pid;]); +note("S1 pid=$s1_pid backend_xmin=$s1_xmin"); + +# Primary: delete and vacuum so the prune record conflicts with S1. +my $log_offset = -s $node_standby->logfile; +my $lsn_before_vac = + $node_primary->safe_psql('postgres', 'SELECT pg_current_wal_lsn()'); +$node_primary->safe_psql( + 'postgres', qq[ +DELETE FROM t; +VACUUM t; +]); +my $lsn_after_vac = + $node_primary->safe_psql('postgres', 'SELECT pg_current_wal_lsn()'); +note("primary WAL: before vacuum=$lsn_before_vac after=$lsn_after_vac"); + +# The first scan must find exactly S1. +$log_offset = $node_standby->wait_for_log(qr/Conflicting process: $s1_pid\./, + $log_offset); + +my $replay_lsn = + $node_standby->safe_psql('postgres', 'SELECT pg_last_wal_replay_lsn()'); +note("standby replay stalled at $replay_lsn (primary at $lsn_after_vac)"); + +# S2: a new backend imports S1's snapshot +my $s2 = $node_standby->background_psql('postgres', on_error_stop => 0); +$s2->query_safe(qq[BEGIN TRANSACTION ISOLATION LEVEL REPEATABLE READ;]); +$s2->query_safe(qq[SET TRANSACTION SNAPSHOT '$snapid';]); + +my $s2_pid = $s2->query_safe(qq[SELECT pg_backend_pid();]); +$s2_pid =~ s/^\s+|\s+$//g; +my $s2_xmin = $node_standby->safe_psql('postgres', + qq[SELECT backend_xmin FROM pg_stat_activity WHERE pid = $s2_pid;]); +note("S2 pid=$s2_pid backend_xmin=$s2_xmin (S1 xmin was $s1_xmin)"); +is($s2_xmin, $s1_xmin, "S2 adopted S1's xmin"); + +# S1 exits, draining the set the first scan found. +$s1->query_safe(qq[COMMIT;]); +$s1->quit; + +# Wait until the standby commits to one behavior or the other: it either +# rescans and reports S2, or it resumes replay past the prune record. Waiting +# only for the rescan would turn the wrong-results case into a timeout instead +# of a failed assertion. +my $s2_conflict = qr/Conflicting process: $s2_pid\./; +foreach (1 .. 10 * $PostgreSQL::Test::Utils::timeout_default) +{ + last if $node_standby->log_contains($s2_conflict, $log_offset); + my $advanced = $node_standby->safe_psql('postgres', + qq[SELECT pg_last_wal_replay_lsn() >= '$lsn_after_vac'::pg_lsn]); + last if $advanced eq 't'; + usleep(100_000); +} + +ok($node_standby->log_contains($s2_conflict, $log_offset), + 'second scan found S2'); + +# Replay must not have advanced past the prune record. +my $replay_after_s1 = + $node_standby->safe_psql('postgres', 'SELECT pg_last_wal_replay_lsn()'); +note("replay after S1 exit: $replay_after_s1 (primary at $lsn_after_vac)"); +my $stalled = $node_standby->safe_psql('postgres', + qq[SELECT pg_last_wal_replay_lsn() < '$lsn_after_vac'::pg_lsn]); +is($stalled, 't', 'replay stalled while S2 holds the imported snapshot'); + +my $s2_result = $s2->query_safe(qq[SELECT count(*) FROM t;]); +$s2_result =~ s/^\s+|\s+$//g; + +my $s2_alive = $s2->query_safe(qq[SELECT 'alive';]); +like($s2_alive, qr/alive/m, 'S2 not cancelled'); + +is($s2_result, '100', 'S2 sees all rows of its imported snapshot'); + +$s2->query_safe(qq[COMMIT;]); +$s2->quit; + +$node_primary->wait_for_replay_catchup($node_standby); + +is($node_standby->safe_psql('postgres', 'SELECT count(*) FROM t'), + 0, 'standby reflects the pruned table after catchup'); + +$node_standby->stop; +$node_primary->stop; + +done_testing(); -- 2.50.1 (Apple Git-155)
v2-0002-Fix-recovery-conflict-resolution-to-account-for-i.patch (application/octet-stream, 4.9K) download From 8159ebea03c60ecacde914581cab3a775589112d Mon Sep 17 00:00:00 2001 From: Scott Ray <scott@scottray.io> Date: Sat, 1 Aug 2026 15:04:54 -0700 Subject: [PATCH v2 2/2] Fix recovery conflict resolution to account for imported snapshots Make ResolveRecoveryConflictWithSnapshot call GetConflictingVirtualXIDs until no conflict remains, fixing a wrong-results bug where, after the first call, a backend could import a conflicting snapshot, creating a new conflict invisible to standby recovery. --- src/backend/storage/ipc/procarray.c | 15 +++++++++--- src/backend/storage/ipc/standby.c | 38 ++++++++++++++++++++++++----- 2 files changed, 44 insertions(+), 9 deletions(-) diff --git a/src/backend/storage/ipc/procarray.c b/src/backend/storage/ipc/procarray.c index 9299bcebbda..7f9025b9579 100644 --- a/src/backend/storage/ipc/procarray.c +++ b/src/backend/storage/ipc/procarray.c @@ -3351,7 +3351,8 @@ GetCurrentVirtualXIDs(TransactionId limitXmin, bool excludeXmin0, } /* - * GetConflictingVirtualXIDs -- returns an array of currently active VXIDs. + * GetConflictingVirtualXIDs -- returns an array of currently active VXIDs + * considered in conflict with recovery up to limitXmin. * * Usage is limited to conflict resolution during recovery on standby servers. * limitXmin is supplied as either a cutoff with snapshotConflictHorizon @@ -3380,6 +3381,13 @@ GetCurrentVirtualXIDs(TransactionId limitXmin, bool excludeXmin0, * but that would not be true in the case of FATAL errors lagging in array, * but we already know those are bogus anyway, so we skip that test. * + * That reasoning covers snapshots acquired with GetSnapshotData, which yields + * transaction xmins above limitXmin, but it does not cover backends that + * import snapshots using SET TRANSACTION SNAPSHOT, which call + * ProcArrayInstallImportedXmin instead. A backend that imports a snapshot + * from one of the conflicting backends can acquire xmin <= limitXmin, so + * the conflicting VXID set can grow, but only while the set is non-empty. + * * If dbOid is valid we skip backends attached to other databases. * * Be careful to *not* pfree the result from this function. We reuse @@ -3430,8 +3438,9 @@ GetConflictingVirtualXIDs(TransactionId limitXmin, Oid dbOid) * no snapshot currently. We hold a Share lock to avoid contention * with users taking snapshots. That is not a problem because the * current xmin is always at least one higher than the latest - * removed xid, so any new snapshot would never conflict with the - * test here. + * removed xid, so any snapshot acquired with GetSnapshotData + * would never conflict with the test here. See the header + * comment for the caveat about imported snapshots. */ if (!TransactionIdIsValid(limitXmin) || (TransactionIdIsValid(pxmin) && !TransactionIdFollows(pxmin, limitXmin))) diff --git a/src/backend/storage/ipc/standby.c b/src/backend/storage/ipc/standby.c index 29af7733948..8c05cbe0702 100644 --- a/src/backend/storage/ipc/standby.c +++ b/src/backend/storage/ipc/standby.c @@ -24,6 +24,7 @@ #include "access/xlogutils.h" #include "miscadmin.h" #include "pgstat.h" +#include "postmaster/startup.h" #include "replication/slot.h" #include "storage/bufmgr.h" #include "storage/proc.h" @@ -489,12 +490,37 @@ ResolveRecoveryConflictWithSnapshot(TransactionId snapshotConflictHorizon, return; Assert(TransactionIdIsNormal(snapshotConflictHorizon)); - backends = GetConflictingVirtualXIDs(snapshotConflictHorizon, - locator.dbOid); - ResolveRecoveryConflictWithVirtualXIDs(backends, - RECOVERY_CONFLICT_SNAPSHOT, - WAIT_EVENT_RECOVERY_CONFLICT_SNAPSHOT, - true); + + /* + * Scan until no conflicting VXID remains. + * + * GetConflictingVirtualXIDs returns the list of conflicting VXIDs that + * existed while it held the ProcArrayLock. While we wait for these VXIDs + * to resolve, a backend may import a conflicting snapshot, creating a + * new, conflicting VXID from one of the VXIDs in the returned list. Any + * new conflict requires a live, conflicting VXID as a source, so we loop + * until GetConflictingVirtualXIDs returns empty, which means no + * conflicting VXID exists and no future VXID will conflict. + * + * The cancellation cutoff is anchored to WAL receipt time + * (GetStandbyLimitTime), not to the start of each wait, so all iterations + * of this loop share a single max_standby_streaming_delay budget. + */ + for (;;) + { + backends = GetConflictingVirtualXIDs(snapshotConflictHorizon, + locator.dbOid); + + if (!VirtualTransactionIdIsValid(backends[0])) + break; + + ResolveRecoveryConflictWithVirtualXIDs(backends, + RECOVERY_CONFLICT_SNAPSHOT, + WAIT_EVENT_RECOVERY_CONFLICT_SNAPSHOT, + true); + /* Respond to shutdown. */ + ProcessStartupProcInterrupts(); + } /* * Note that WaitExceedsMaxStandbyDelay() is not taken into account here -- 2.50.1 (Apple Git-155)
signature.asc (application/pgp-signature, 341B) download ^ permalink raw reply [nested|flat] 8+ messages in thread

* Re: Recovery conflict resolution misses backends that import snapshots
  2026-07-25 23:03 Recovery conflict resolution misses backends that import snapshots Scott Ray <scott@scottray.io>
  2026-07-26 23:49 ` Re: Recovery conflict resolution misses backends that import snapshots Michael Paquier <michael@paquier.xyz>
  2026-07-28 04:44   ` Re: Recovery conflict resolution misses backends that import snapshots Amit Kapila <amit.kapila16@gmail.com>
  2026-08-01 22:22     ` Re: Recovery conflict resolution misses backends that import snapshots Scott Ray <scott@scottray.io>
@ 2026-09-11 02:51       ` chee.wooson <chee.wooson@gmail.com>
  2026-09-12 00:33         ` Re: Recovery conflict resolution misses backends that import snapshots Scott Ray <scott@scottray.io>
  0 siblings, 1 reply; 8+ messages in thread

From: chee.wooson @ 2026-09-11 02:51 UTC (permalink / raw)
  To: Scott Ray <scott@scottray.io>; +Cc: Amit Kapila <amit.kapila16@gmail.com>; Michael Paquier <michael@paquier.xyz>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>; Masahiko Sawada <sawada.mshk@gmail.com>; Zhijie Hou <houzj.fnst@fujitsu.com>; Hayato Kuroda <kuroda.hayato@fujitsu.com>; Bertrand Drouvot <bertranddrouvot.pg@gmail.com>

Hi,

Based on the discussion, I tried an alternative approach for master that
avoids repeatedly rescanning the procarray.

Recovery currently collects a fixed list of VXIDs whose xmins conflict
with a cleanup WAL record.  After ProcArrayLock is released, another
backend can import a listed backend's snapshot and advertise the same
xmin.  The importer is not in recovery's wait list, so recovery can
finish waiting and replay the cleanup while the imported snapshot still
needs the removed data.

The attached v3 uses a separate atomic recoveryConflictTracked field in
PGPROC.  Startup marks each conflicting snapshot source while collecting
the wait list under shared ProcArrayLock.  ProcArrayInstallImportedXmin()
holds ProcArrayLock exclusively and rejects imports from marked sources.

This gives the following ordering:

- An import completed before the scan is visible to the scan and included
  in the wait list.
- An import attempted after the scan observes the source marker and fails.

ResolveRecoveryConflictWithVirtualXIDs() clears each marker immediately
after the corresponding VXID finishes.  The marker is used only for
RECOVERY_CONFLICT_SNAPSHOT.  It is separate from pendingRecoveryConflicts
because the cancellation bits have a different lifetime and are consumed
by backend interrupt processing.

Compared with v2, this prevents the chain of conflicting importers from
growing instead of rescanning until no conflicts remain.  It also retains
the boolean return value of ProcArrayInstallImportedXmin(), and the new
field does not need explicit initialization in ProcGlobalShmemInit, just
as pendingRecoveryConflicts does not.

The attached series is:

- v3-0001 adds a deterministic TAP reproducer and its injection points.
- v3-0002 implements the recoveryConflictTracked protocol.

Patch 0001 is expected to fail without patch 0002 because the conflicting
snapshot import succeeds.

The series is based on master at 9f4bd91a196.  I tested it with assertions,
injection points, and TAP tests enabled.  The build completed successfully,
and recovery tests 056_standby_snapshot_export and
057_snapshot_import_conflict passed.  The series also applies cleanly to
that master commit.

This approach conservatively rejects all snapshot imports from a tracked
source until its tracked VXID finishes.  Feedback on this tradeoff and the
marker lifetime would be appreciated.

Regards,
Chee

Attachments: download all (2 files, .tar.gz)

v3-0001-Add-TAP-test-for-recovery-conflicts-from-imported.patch (text/x-patch, 6.7K) download From e5977336e4fd809960661fe62f461d515738c3b3 Mon Sep 17 00:00:00 2001 From: "chee.wooson" <chee.wooson@gmail.com> Date: Fri, 11 Sep 2026 10:34:32 +0800 Subject: [PATCH v3 1/2] Add TAP test for recovery conflicts from imported snapshots Add injection points around the interval between collecting a snapshot recovery-conflict wait list and finishing the wait for a listed VXID. Use them in a TAP test that attempts to import a conflicting snapshot after the wait list has been collected. Without the accompanying fix, the import succeeds and the test fails because the importer is absent from recovery's fixed wait list. The second half also checks that imports from the source become possible again after its old VXID has been resolved. Reported-by: Scott Ray <scott@scottray.io> Discussion: https://postgr.es/m/QpAansP4iVg_ttSs9x81PFAptL2sqR3AS06u8Jksm3_bHJvUwQjHOocRajbxBc3iiLdf9ZMC6gtXjZsxdxvOmqp98hLZcZuWyBDuQxS6uZc=@scottray.io --- src/backend/storage/ipc/standby.c | 6 + src/test/recovery/meson.build | 1 + .../t/057_snapshot_import_conflict.pl | 116 ++++++++++++++++++ 3 files changed, 123 insertions(+) create mode 100644 src/test/recovery/t/057_snapshot_import_conflict.pl diff --git a/src/backend/storage/ipc/standby.c b/src/backend/storage/ipc/standby.c index 7f011e04990..7065840fc26 100644 --- a/src/backend/storage/ipc/standby.c +++ b/src/backend/storage/ipc/standby.c @@ -439,6 +439,11 @@ ResolveRecoveryConflictWithVirtualXIDs(VirtualTransactionId *waitlist, } } + if (reason == RECOVERY_CONFLICT_SNAPSHOT) + { + INJECTION_POINT("recovery-conflict-snapshot-resolved", NULL); + } + /* The virtual transaction is gone now, wait for the next one */ waitlist++; } @@ -491,6 +496,7 @@ ResolveRecoveryConflictWithSnapshot(TransactionId snapshotConflictHorizon, Assert(TransactionIdIsNormal(snapshotConflictHorizon)); backends = GetConflictingVirtualXIDs(snapshotConflictHorizon, locator.dbOid); + INJECTION_POINT("recovery-conflict-snapshot-scan-complete", NULL); ResolveRecoveryConflictWithVirtualXIDs(backends, RECOVERY_CONFLICT_SNAPSHOT, WAIT_EVENT_RECOVERY_CONFLICT_SNAPSHOT, diff --git a/src/test/recovery/meson.build b/src/test/recovery/meson.build index 72113c5ac6e..4dca2b8acea 100644 --- a/src/test/recovery/meson.build +++ b/src/test/recovery/meson.build @@ -65,6 +65,7 @@ tests += { 't/054_unlogged_sequence_promotion.pl', 't/055_cascade_reconnect.pl', 't/056_standby_snapshot_export.pl', + 't/057_snapshot_import_conflict.pl', ], }, } diff --git a/src/test/recovery/t/057_snapshot_import_conflict.pl b/src/test/recovery/t/057_snapshot_import_conflict.pl new file mode 100644 index 00000000000..bb1ae44525c --- /dev/null +++ b/src/test/recovery/t/057_snapshot_import_conflict.pl @@ -0,0 +1,116 @@ +# Copyright (c) 2026, PostgreSQL Global Development Group +# +# Verify that standby recovery prevents snapshot imports from creating new +# conflicts after it has collected the VXIDs that conflict with a cleanup WAL +# record. + +use strict; +use warnings FATAL => 'all'; +use PostgreSQL::Test::Cluster; +use PostgreSQL::Test::Utils; +use Test::More; + +if ($ENV{enable_injection_points} ne 'yes') +{ + plan skip_all => 'Injection points not supported by this build'; +} + +my $primary = PostgreSQL::Test::Cluster->new('primary'); +$primary->init(allows_streaming => 1); +$primary->append_conf('postgresql.conf', 'autovacuum = off'); +$primary->start; + +if (!$primary->check_extension('injection_points')) +{ + plan skip_all => 'Extension injection_points not installed'; +} + +$primary->safe_psql( + 'postgres', q[ +CREATE EXTENSION injection_points; +CREATE TABLE t AS SELECT generate_series(1, 100) AS id; +]); + +$primary->backup('backup'); +my $standby = PostgreSQL::Test::Cluster->new('standby'); +$standby->init_from_backup($primary, 'backup', has_streaming => 1); +$standby->append_conf('postgresql.conf', + 'max_standby_streaming_delay = -1'); +$standby->start; + +# Register an old xmin and export its snapshot on the standby. +my $exporter = + $standby->background_psql('postgres', on_error_stop => 0); +$exporter->query_safe('BEGIN ISOLATION LEVEL REPEATABLE READ'); +is($exporter->query_safe('SELECT count(*) FROM t'), 100, + 'exporter sees all rows'); +my $old_snapshot = $exporter->query_safe('SELECT pg_export_snapshot()'); + +$standby->safe_psql( + 'postgres', q[ +SELECT injection_points_attach('recovery-conflict-snapshot-scan-complete', 'wait'); +SELECT injection_points_attach('recovery-conflict-snapshot-resolved', 'wait'); +]); + +# Generate a cleanup record whose replay conflicts with the old snapshot. +$primary->safe_psql( + 'postgres', q[ +DELETE FROM t; +VACUUM t; +]); + +# Recovery has completed its conflict scan, but has not started waiting for +# the exporter yet. +$standby->wait_for_event('startup', + 'recovery-conflict-snapshot-scan-complete'); + +my ($stdout, $stderr); +my $result = $standby->psql( + 'postgres', + "BEGIN ISOLATION LEVEL REPEATABLE READ; " + . "SET TRANSACTION SNAPSHOT '$old_snapshot';", + stdout => \$stdout, + stderr => \$stderr); +isnt($result, 0, 'cannot import a snapshot from a tracked source'); + +# Let recovery start waiting, then end the conflicting VXID. Recovery pauses +# after resolving it, before it can replay the cleanup record. +$standby->safe_psql( + 'postgres', q[ +SELECT injection_points_detach('recovery-conflict-snapshot-scan-complete'); +SELECT injection_points_wakeup('recovery-conflict-snapshot-scan-complete'); +]); +$exporter->query_safe('COMMIT'); +$standby->wait_for_event('startup', + 'recovery-conflict-snapshot-resolved'); + +# Reuse the same backend for a new transaction. Snapshot import must be +# allowed again once startup has resolved the old VXID. +$exporter->query_safe('BEGIN ISOLATION LEVEL REPEATABLE READ'); +my $new_snapshot = $exporter->query_safe('SELECT pg_export_snapshot()'); +$result = $standby->psql( + 'postgres', + "BEGIN ISOLATION LEVEL REPEATABLE READ; " + . "SET TRANSACTION SNAPSHOT '$new_snapshot'; SELECT count(*) FROM t;", + stdout => \$stdout, + stderr => \$stderr); +is($result, 0, 'can import from the source after its tracked VXID ends'); +$stdout =~ s/^\s+|\s+$//g; +is($stdout, '0', 'new snapshot sees the replayed delete'); + +$standby->safe_psql( + 'postgres', q[ +SELECT injection_points_detach('recovery-conflict-snapshot-resolved'); +SELECT injection_points_wakeup('recovery-conflict-snapshot-resolved'); +]); +$exporter->query_safe('COMMIT'); +$exporter->quit; + +$primary->wait_for_replay_catchup($standby); +is($standby->safe_psql('postgres', 'SELECT count(*) FROM t'), 0, + 'standby replays the cleanup after the conflict ends'); + +$standby->stop; +$primary->stop; + +done_testing(); -- 2.43.0
v3-0002-Fix-recovery-conflict-resolution-to-account-for-i.patch (text/x-patch, 8.6K) download From 8753d7556c8459a4fd4e2c3a55c92e116a76b115 Mon Sep 17 00:00:00 2001 From: "chee.wooson" <chee.wooson@gmail.com> Date: Fri, 11 Sep 2026 10:34:45 +0800 Subject: [PATCH v3 2/2] Fix recovery conflict resolution to account for imported snapshots Hot standby recovery builds a fixed list of VXIDs whose advertised xmin conflicts with a cleanup WAL record. After that scan, another transaction can import a snapshot from a listed backend and advertise the same xmin. Recovery then misses the importer when the original backend ends. Add a startup-owned recoveryConflictTracked marker to PGPROC. Set it while collecting conflicting VXIDs under ProcArrayLock, reject snapshot imports from marked sources under the importer's exclusive ProcArrayLock, and clear each marker after its tracked VXID ends. Keep this state separate from pending recovery-conflict cancellation reasons. Reported-by: Scott Ray <scott@scottray.io> Discussion: https://postgr.es/m/QpAansP4iVg_ttSs9x81PFAptL2sqR3AS06u8Jksm3_bHJvUwQjHOocRajbxBc3iiLdf9ZMC6gtXjZsxdxvOmqp98hLZcZuWyBDuQxS6uZc=@scottray.io --- src/backend/storage/ipc/procarray.c | 41 ++++++++++++++++++++++++++++- src/backend/storage/ipc/standby.c | 15 ++++++++++- src/backend/storage/lmgr/proc.c | 2 ++ src/include/storage/proc.h | 12 +++++++++ src/include/storage/procarray.h | 4 ++- 5 files changed, 71 insertions(+), 3 deletions(-) diff --git a/src/backend/storage/ipc/procarray.c b/src/backend/storage/ipc/procarray.c index b7e03134ed8..4b2d0e1c20f 100644 --- a/src/backend/storage/ipc/procarray.c +++ b/src/backend/storage/ipc/procarray.c @@ -2473,7 +2473,8 @@ GetSnapshotData(Snapshot snapshot) * check that the source transaction is still running, and we'd better do * that atomically with installing the new xmin. * - * Returns true if successful, false if source xact is no longer running. + * Returns true if successful, false if source xact is no longer running or + * recovery is waiting for it. */ bool ProcArrayInstallImportedXmin(TransactionId xmin, @@ -2534,6 +2535,14 @@ ProcArrayInstallImportedXmin(TransactionId xmin, !TransactionIdPrecedesOrEquals(xid, xmin)) continue; + /* + * Recovery has included this transaction in a fixed wait list. Do + * not let an imported snapshot transfer its conflicting xmin to a + * transaction that is absent from that list. + */ + if (pg_atomic_read_u32(&proc->recoveryConflictTracked) != 0) + break; + /* * We're good. Install the new xmin. As in GetSnapshotData, set * TransactionXmin too. (Note that because snapmgr.c called @@ -2562,6 +2571,10 @@ ProcArrayInstallImportedXmin(TransactionId xmin, * order to avoid the case where MyProc's xmin needs to be skipped for * computing xid horizon. * + * Unlike independent SQL snapshot imports, this is used only by parallel + * workers. A parallel worker cannot outlive the leader VXID that recovery + * tracks, so it need not check recoveryConflictTracked. + * * Returns true if successful, false if source xact is no longer running. */ bool @@ -3374,6 +3387,10 @@ GetCurrentVirtualXIDs(TransactionId limitXmin, bool excludeXmin0, * * If dbOid is valid we skip backends attached to other databases. * + * When limitXmin is valid, mark every returned PGPROC so that it cannot be + * used as the source of an imported snapshot. The caller must clear each + * marker after the corresponding VXID has ended. + * * Be careful to *not* pfree the result from this function. We reuse * this array sufficiently often that we use malloc for the result. */ @@ -3432,7 +3449,11 @@ GetConflictingVirtualXIDs(TransactionId limitXmin, Oid dbOid) GET_VXID_FROM_PGPROC(vxid, *proc); if (VirtualTransactionIdIsValid(vxid)) + { + if (TransactionIdIsValid(limitXmin)) + pg_atomic_write_u32(&proc->recoveryConflictTracked, 1); vxids[count++] = vxid; + } } } } @@ -3446,6 +3467,24 @@ GetConflictingVirtualXIDs(TransactionId limitXmin, Oid dbOid) return vxids; } +/* + * Stop preventing snapshot imports from the PGPROC slot associated with vxid. + * + * The tracked VXID has already ended, so the slot might now belong to another + * process or transaction. Clearing the marker is nevertheless safe: the + * startup process is its only setter and handles one conflict wait list at a + * time. A replacement process also initializes the marker to zero before + * entering the procarray. + */ +void +ProcArrayClearRecoveryConflictTracked(VirtualTransactionId vxid) +{ + PGPROC *proc = ProcNumberGetProc(vxid.procNumber); + + if (proc != NULL) + pg_atomic_write_u32(&proc->recoveryConflictTracked, 0); +} + /* * SignalRecoveryConflict -- signal that a process is blocking recovery * diff --git a/src/backend/storage/ipc/standby.c b/src/backend/storage/ipc/standby.c index 7065840fc26..a78b3aae67b 100644 --- a/src/backend/storage/ipc/standby.c +++ b/src/backend/storage/ipc/standby.c @@ -439,12 +439,17 @@ ResolveRecoveryConflictWithVirtualXIDs(VirtualTransactionId *waitlist, } } + /* + * The virtual transaction is gone now. If this is a snapshot + * conflict, allow snapshot imports from its PGPROC slot again before + * waiting for the next transaction. + */ if (reason == RECOVERY_CONFLICT_SNAPSHOT) { + ProcArrayClearRecoveryConflictTracked(*waitlist); INJECTION_POINT("recovery-conflict-snapshot-resolved", NULL); } - /* The virtual transaction is gone now, wait for the next one */ waitlist++; } @@ -494,6 +499,14 @@ ResolveRecoveryConflictWithSnapshot(TransactionId snapshotConflictHorizon, return; Assert(TransactionIdIsNormal(snapshotConflictHorizon)); + + /* + * Track each conflicting VXID before releasing ProcArrayLock. Snapshot + * import takes ProcArrayLock exclusively, so an import either completes + * before this scan and is included in the wait list, or observes the + * source's marker after the scan and fails. Consequently, no new + * conflicting VXID can appear while the fixed list is being drained. + */ backends = GetConflictingVirtualXIDs(snapshotConflictHorizon, locator.dbOid); INJECTION_POINT("recovery-conflict-snapshot-scan-complete", NULL); diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index ab65a6dbcc9..63954d04769 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -505,6 +505,7 @@ InitProcess(void) } #endif pg_atomic_write_u32(&MyProc->pendingRecoveryConflicts, 0); + pg_atomic_write_u32(&MyProc->recoveryConflictTracked, 0); /* Initialize fields for sync rep */ MyProc->waitLSN = InvalidXLogRecPtr; @@ -705,6 +706,7 @@ InitAuxiliaryProcess(void) } #endif pg_atomic_write_u32(&MyProc->pendingRecoveryConflicts, 0); + pg_atomic_write_u32(&MyProc->recoveryConflictTracked, 0); /* * Acquire ownership of the PGPROC's latch, so that we can use WaitLatch diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h index 4c3f431b4eb..2d2e2a98ebd 100644 --- a/src/include/storage/proc.h +++ b/src/include/storage/proc.h @@ -276,6 +276,18 @@ typedef struct PGPROC */ pg_atomic_uint32 pendingRecoveryConflicts; + /* + * Set by the startup process while it waits for this process's VXID to + * resolve a snapshot conflict. A set value prevents other backends from + * importing this process's snapshot and thereby creating a new conflict + * that is absent from the startup process's wait list. + * + * The startup process is the only process that sets this field. It + * clears the field after the tracked VXID has ended. Atomic access + * permits that cleanup even if the PGPROC slot has since been recycled. + */ + pg_atomic_uint32 recoveryConflictTracked; + /************************************************************************ * LWLock waiting ************************************************************************/ diff --git a/src/include/storage/procarray.h b/src/include/storage/procarray.h index d718a5b542f..6c226e1a26b 100644 --- a/src/include/storage/procarray.h +++ b/src/include/storage/procarray.h @@ -73,7 +73,9 @@ extern bool IsBackendPid(int pid); extern VirtualTransactionId *GetCurrentVirtualXIDs(TransactionId limitXmin, bool excludeXmin0, bool allDbs, int excludeVacuum, int *nvxids); -extern VirtualTransactionId *GetConflictingVirtualXIDs(TransactionId limitXmin, Oid dbOid); +extern VirtualTransactionId *GetConflictingVirtualXIDs(TransactionId limitXmin, + Oid dbOid); +extern void ProcArrayClearRecoveryConflictTracked(VirtualTransactionId vxid); extern bool SignalRecoveryConflict(PGPROC *proc, pid_t pid, RecoveryConflictReason reason); extern bool SignalRecoveryConflictWithVirtualXID(VirtualTransactionId vxid, RecoveryConflictReason reason); -- 2.43.0
^ permalink raw reply [nested|flat] 8+ messages in thread

* Re: Recovery conflict resolution misses backends that import snapshots
  2026-07-25 23:03 Recovery conflict resolution misses backends that import snapshots Scott Ray <scott@scottray.io>
  2026-07-26 23:49 ` Re: Recovery conflict resolution misses backends that import snapshots Michael Paquier <michael@paquier.xyz>
  2026-07-28 04:44   ` Re: Recovery conflict resolution misses backends that import snapshots Amit Kapila <amit.kapila16@gmail.com>
  2026-08-01 22:22     ` Re: Recovery conflict resolution misses backends that import snapshots Scott Ray <scott@scottray.io>
  2026-09-11 02:51       ` Re: Recovery conflict resolution misses backends that import snapshots chee.wooson <chee.wooson@gmail.com>
@ 2026-09-12 00:33         ` Scott Ray <scott@scottray.io>
  2026-09-12 14:16           ` Re: Recovery conflict resolution misses backends that import snapshots Chee Wooson <chee.wooson@gmail.com>
  0 siblings, 1 reply; 8+ messages in thread

From: Scott Ray @ 2026-09-12 00:33 UTC (permalink / raw)
  To: chee.wooson <chee.wooson@gmail.com>; +Cc: Amit Kapila <amit.kapila16@gmail.com>; Michael Paquier <michael@paquier.xyz>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>; Masahiko Sawada <sawada.mshk@gmail.com>; Zhijie Hou <houzj.fnst@fujitsu.com>; Hayato Kuroda <kuroda.hayato@fujitsu.com>; Bertrand Drouvot <bertranddrouvot.pg@gmail.com>

Thanks for posting v3.

1. v3 still exposes snapshot-importing backends to wrong results.
Consider procs Exporter, Recovery, and Importer:

(a) Recovery scans, sets Exporter's recoveryConflictTracked to 1, and
begins to wait for the transaction to end using VirtualXactLock().

(b) Importer calls ProcArrayInstallImportedXmin(), acquires the
ProcArrayLock exclusively, and stalls just before reading
recoveryConflictTracked, for example because the OS preempts it.

(c) Exporter commits and takes the lockless branch of
ProcArrayEndTransaction().

(d) Recovery sees Exporter's transaction end, calls
ProcArrayClearRecoveryConflictTracked(), and resumes replay.

(e) Importer resumes, reads that recoveryConflictTracked contains 0,
and finishes importing the snapshot.

(f) Importer now holds a snapshot that needs tuple versions or index
entries that Recovery has removed.

Holding ProcArrayLock in shared mode while clearing
recoveryConflictTracked would prevent this race.

2. v3 can block importing snapshots even when the snapshots do not
conflict with recovery.  Consider procs Exporter, Recovery, Importer,
and Blocker:

(a) Recovery scans, sets Exporter and Blocker's
recoveryConflictTracked to 1, and begins to wait for Blocker.

(b) Exporter's transaction ends and it begins a new transaction with
a new snapshot that does not conflict.

(c) Importer attempts to import Exporter's new snapshot, but
recoveryConflictTracked is still 1, and so import fails.  The user
receives the false error detail "The source process with PID %d is not
running anymore."

(d) This condition persists until Blocker's transaction completes and
Recovery reaches Exporter's old VXID in the waitlist, at which point
it calls ProcArrayClearRecoveryConflictTracked() and import may
succeed.

GetConflictingVirtualXIDs() could store the lxid of the conflicting
transaction and ProcArrayInstallImportedXmin() could check this value to
determine whether it matches the source of the import.  The false error
detail requires a separate fix.

3. This approach can cause parallel pg_dump failures.

(a) The leader connects, opens a transaction, and exports its
snapshot.  It does not immediately fork workers.  Instead, it
continues preparing, including a full scan of the catalog to find
every table to dump.

(b) GetConflictingVirtualXIDs() sets recoveryConflictTracked to 1 for
the leader.

(c) The leader finishes setting up and forks workers.

(d) Each worker attempts to import the leader's snapshot but fails,
and pg_dump exits with "a worker process died unexpectedly".

The user may set max_standby_streaming_delay to -1 to prioritize
operations on the standby over recovery progress.  Raising an error if
a proc tries to import a conflicting snapshot lets the operation die
instead of delaying recovery, regardless of the user's stated
preference.

4. v3 offers no clear backpatch strategy.  At its current location,
recoveryConflictTracked breaks ABI compatibility by displacing PGPROC
members including lwWaiting.  Also, some of the components v3 uses
postdate affected, supported branches: PG 14 through 16 lack injection
points; and no stable release uses RecoveryConflictReason.

--
Scott Ray

Attachments:

  signature.asc (application/pgp-signature, 341B) download

^ permalink  raw  reply  [nested|flat] 8+ messages in thread

* Re: Recovery conflict resolution misses backends that import snapshots
  2026-07-25 23:03 Recovery conflict resolution misses backends that import snapshots Scott Ray <scott@scottray.io>
  2026-07-26 23:49 ` Re: Recovery conflict resolution misses backends that import snapshots Michael Paquier <michael@paquier.xyz>
  2026-07-28 04:44   ` Re: Recovery conflict resolution misses backends that import snapshots Amit Kapila <amit.kapila16@gmail.com>
  2026-08-01 22:22     ` Re: Recovery conflict resolution misses backends that import snapshots Scott Ray <scott@scottray.io>
  2026-09-11 02:51       ` Re: Recovery conflict resolution misses backends that import snapshots chee.wooson <chee.wooson@gmail.com>
  2026-09-12 00:33         ` Re: Recovery conflict resolution misses backends that import snapshots Scott Ray <scott@scottray.io>
@ 2026-09-12 14:16           ` Chee Wooson <chee.wooson@gmail.com>
  2026-09-27 21:12             ` Re: Recovery conflict resolution misses backends that import snapshots Scott Ray <scott@scottray.io>
  0 siblings, 1 reply; 8+ messages in thread

From: Chee Wooson @ 2026-09-12 14:16 UTC (permalink / raw)
  To: Scott Ray <scott@scottray.io>; +Cc: Amit Kapila <amit.kapila16@gmail.com>; Michael Paquier <michael@paquier.xyz>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>; Masahiko Sawada <sawada.mshk@gmail.com>; Zhijie Hou <houzj.fnst@fujitsu.com>; Hayato Kuroda <kuroda.hayato@fujitsu.com>; Bertrand Drouvot <bertranddrouvot.pg@gmail.com>

Hi,

Thanks for the detailed review. I agree that the implementation in v3
has problems and should not be revised incrementally.

I have also looked again at the rescan approach in v2. I agree that
the deadline is not reset, so a new conflict found by the next scan
will be cancelled without another grace period. However, this only
bounds how long recovery waits for each observed conflict; it does not
bound how many new conflicts can be created.

Until a signalled source actually exits, another backend may still
import its snapshot and subsequently become a source for a snapshot
retaining the same conflicting xmin. The same handoff can then happen
again with the new exporter. I do not see an invariant in v2 that
prevents this chain from continuing, so I am concerned that the outer
rescan loop does not have a strict termination guarantee. Am I missing
such an invariant?

If there is no such invariant, preventing further propagation after
the deadline appears to require some additional shared state, allowing
conflicting imports to be rejected while recovery drains the remaining
conflicts. Such a rejection may be consistent with the semantics of a
finite standby delay, but I do not yet see a sufficiently simple way
to publish and clear this state safely.

I will rethink the approach before posting another version.

Regards,
Chee






^ permalink  raw  reply  [nested|flat] 8+ messages in thread

* Re: Recovery conflict resolution misses backends that import snapshots
  2026-07-25 23:03 Recovery conflict resolution misses backends that import snapshots Scott Ray <scott@scottray.io>
  2026-07-26 23:49 ` Re: Recovery conflict resolution misses backends that import snapshots Michael Paquier <michael@paquier.xyz>
  2026-07-28 04:44   ` Re: Recovery conflict resolution misses backends that import snapshots Amit Kapila <amit.kapila16@gmail.com>
  2026-08-01 22:22     ` Re: Recovery conflict resolution misses backends that import snapshots Scott Ray <scott@scottray.io>
  2026-09-11 02:51       ` Re: Recovery conflict resolution misses backends that import snapshots chee.wooson <chee.wooson@gmail.com>
  2026-09-12 00:33         ` Re: Recovery conflict resolution misses backends that import snapshots Scott Ray <scott@scottray.io>
  2026-09-12 14:16           ` Re: Recovery conflict resolution misses backends that import snapshots Chee Wooson <chee.wooson@gmail.com>
@ 2026-09-27 21:12             ` Scott Ray <scott@scottray.io>
  0 siblings, 0 replies; 8+ messages in thread

From: Scott Ray @ 2026-09-27 21:12 UTC (permalink / raw)
  To: Chee Wooson <chee.wooson@gmail.com>; +Cc: Amit Kapila <amit.kapila16@gmail.com>; Michael Paquier <michael@paquier.xyz>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>; Masahiko Sawada <sawada.mshk@gmail.com>; Zhijie Hou <houzj.fnst@fujitsu.com>; Hayato Kuroda <kuroda.hayato@fujitsu.com>; Bertrand Drouvot <bertranddrouvot.pg@gmail.com>

On Saturday, September 12th, 2026 at 7:19 AM, Chee Wooson <chee.wooson@gmail.com> wrote:

> I do not see an invariant in v2 that
> prevents this chain from continuing, so I am concerned that the outer
> rescan loop does not have a strict termination guarantee. Am I missing
> such an invariant?

No such invariant exists.  I share Amit's concern about overengineering.

On Monday, July 27th, 2026 at 9:44 PM, Amit Kapila <amit.kapila16@gmail.com> wrote:

> The other way to avoid looping here is to stop the chain from being
> extended: past the deadline, refuse new conflicting snapshot imports
> on the standby (aka "publish the intended horizon and reject
> conflicting imports"). I feel that is over engineering, instead, the
> current proposed solution looks reasonable to me

--
Scott Ray

Attachments:

  signature.asc (application/pgp-signature, 341B) download

^ permalink  raw  reply  [nested|flat] 8+ messages in thread


end of thread, other threads:[~2026-09-27 21:12 UTC | newest]

Thread overview: 8+ messages (download: mbox mbox.gz follow: Atom feed)
-- links below jump to the message on this page --
2026-07-25 23:03 Recovery conflict resolution misses backends that import snapshots Scott Ray <scott@scottray.io>
2026-07-26 23:49 ` Michael Paquier <michael@paquier.xyz>
2026-07-28 04:44   ` Amit Kapila <amit.kapila16@gmail.com>
2026-08-01 22:22     ` Scott Ray <scott@scottray.io>
2026-09-11 02:51       ` chee.wooson <chee.wooson@gmail.com>
2026-09-12 00:33         ` Scott Ray <scott@scottray.io>
2026-09-12 14:16           ` Chee Wooson <chee.wooson@gmail.com>
2026-09-27 21:12             ` Scott Ray <scott@scottray.io>

This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox