Race conditions in logical decoding
Race conditions in logical decoding
A stress test [1] for the REPACK patch [1] revealed data corruption. Eventually I found out that the problem is in postgres core. In particular, it can happen that a COMMIT record is decoded, but before the commit could be recorded in CLOG, a snapshot that takes the commit into account is created and even used. Visibility checks then work incorrectly until the CLOG gets updated. In logical replication, the consequences are not only wrong data on the subscriber, but also corrutped table on publisher - this is due to incorrectly set commit hint bits. Attached is a spec file that demonstrates the issue. I did not add it to Makefile because I don't expect the current version to be merged (see the commit message for details. I'm not sure yet how to fix the problem. I tried to call XactLockTableWait() from SnapBuildAddCommittedTxn() (like it happens in SnapBuildWaitSnapshot()), but it made at least one regression test (subscription/t/010_truncate.pl) stuck - probably a deadlock. I can spend more time on it, but maybe someone can come up with a good idea sooner than me. [1] https://www.postgresql.org/message-id/CADzfLwU78as45To9a%3D-Qkr5jEg3tMxc5rUtdKy2MTv4r_SDGng%40mail.gmail.com [2] https://commitfest.postgresql.org/patch/5117/ -- Antonin Houska Web: https://www.cybertec-postgresql.com
Re: Race conditions in logical decoding
Antonin Houska wrote: > I'm not sure yet how to fix the problem. I tried to call XactLockTableWait() > from SnapBuildAddCommittedTxn() (like it happens in SnapBuildWaitSnapshot()), > but it made at least one regression test (subscription/t/010_truncate.pl) > stuck - probably a deadlock. I can spend more time on it, but maybe someone > can come up with a good idea sooner than me. Attached here is what I consider a possible fix - simply wait for the CLOG update before building a new snapshot. Unfortunately I have no idea right now how to test it using the isolation tester. With the fix, the additional waiting makes the current test block. (And if a step is added that unblock the session, it will not reliably catch failure to wait.) -- Antonin Houska Web: https://www.cybertec-postgresql.com
Re: Race conditions in logical decoding
От:
Andres Freund <andres@anarazel.de>
Дата:
Hi, On 2026-01-20 09:30:33 +0100, Antonin Houska wrote: > Antonin Houska wrote: > > > I'm not sure yet how to fix the problem. I tried to call XactLockTableWait() > > from SnapBuildAddCommittedTxn() (like it happens in SnapBuildWaitSnapshot()), > > but it made at least one regression test (subscription/t/010_truncate.pl) > > stuck - probably a deadlock. I can spend more time on it, but maybe someone > > can come up with a good idea sooner than me. > > Attached here is what I consider a possible fix - simply wait for the CLOG > update before building a new snapshot. I don't think that's enough - during non-timetravel visibility semantics, you can only look at the clog if the transaction isn't marked as in-progress in the procarray. ISTM that we need to do that here too? Greetings, Andres
Re: Race conditions in logical decoding
От:
Mihail Nikalayeu <mihailnikalayeu@gmail.com>
Дата:
Hello, Andres.
On Tue, Jan 20, 2026 at 6:50 PM Andres Freund <andres@anarazel.de> wrote:
> I don't think that's enough - during non-timetravel visibility semantics, you
> can only look at the clog if the transaction isn't marked as in-progress in
> the procarray. ISTM that we need to do that here too?
Do you mean replace
> I don't think that's enough - during non-timetravel visibility semantics, you
> can only look at the clog if the transaction isn't marked as in-progress in
> the procarray. ISTM that we need to do that here too?
Do you mean replace
> if (unlikely(!TransactionIdDidCommit(builder->committed.xip[i])))
to
> if (unlikely(TransactionIdIsInProgress(builder->committed.xip[i]) || !TransactionIdDidCommit(builder->committed.xip[i])))
> if (unlikely(TransactionIdIsInProgress(builder->committed.xip[i]) || !TransactionIdDidCommit(builder->committed.xip[i])))
?
If so, yes, it feels correct to me.
Mikhail.
Re: Race conditions in logical decoding
От:
Antonin Houska <ah@cybertec.at>
Дата:
Mihail Nikalayeu wrote: > Hello, Andres. > > On Tue, Jan 20, 2026 at 6:50 PM Andres Freund wrote: > > I don't think that's enough - during non-timetravel visibility semantics, you > > can only look at the clog if the transaction isn't marked as in-progress in > > the procarray. ISTM that we need to do that here too? > > Do you mean replace > > if (unlikely(!TransactionIdDidCommit(builder->committed.xip[i]))) > to > > if (unlikely(TransactionIdIsInProgress(builder->committed.xip[i]) || !TransactionIdDidCommit(builder->committed.xip[i]))) This way the synchronous replication gets stuck, as it did when I tried to use XactLockTableWait(): subscriber cannot confirm replication of certain LSN because publisher is not able to even finalize the commit (due to the waiting for the subscriber's confirmation), and therefore publisher it's not able to decode the data and send it to the subscriber. -- Antonin Houska Web: https://www.cybertec-postgresql.com
Re: Race conditions in logical decoding
От:
Álvaro Herrera <alvherre@kurilemu.de>
Дата:
On 2026-Jan-22, Antonin Houska wrote: > Mihail Nikalayeu wrote: > > > Hello, Andres. > > > > On Tue, Jan 20, 2026 at 6:50 PM Andres Freund wrote: > > > I don't think that's enough - during non-timetravel visibility semantics, you > > > can only look at the clog if the transaction isn't marked as in-progress in > > > the procarray. ISTM that we need to do that here too? > > > > Do you mean replace > > > if (unlikely(!TransactionIdDidCommit(builder->committed.xip[i]))) > > to > > > if (unlikely(TransactionIdIsInProgress(builder->committed.xip[i]) || !TransactionIdDidCommit(builder->committed.xip[i]))) > > This way the synchronous replication gets stuck, as it did when I tried to use > XactLockTableWait(): subscriber cannot confirm replication of certain LSN > because publisher is not able to even finalize the commit (due to the waiting > for the subscriber's confirmation), and therefore publisher it's not able to > decode the data and send it to the subscriber. The layering here is wild, but if I understand it correctly, these XIDs are all added to an array by SnapBuildAddCommittedTxn(), which in turn is only called by SnapBuildCommitTxn(), which is only called by DecodeCommit(), which is only called by xact_decode() when it sees a XLOG_XACT_COMMIT or XLOG_XACT_COMMIT_PREPARED record by reading WAL. Crucially, RecordTransactionCommit() writes the WAL first, then marks everything as committed in CLOG, and finally does the waiting for the synchronous replica to ACK the commit if necessary. However, the transaction is only removed from procarray after RecordTransactionCommit has returned. This means that DecodeCommit() could add a transaction to the SnapBuilder (that needs to be waited for) while that transaction is still shown as running in ProcArray. This sounds problematic in itself, so I'm wondering whether we should do anything (namely, wait) on DecodeCommit() instead of hacking SnapBuildBuildSnapshot() to patch it up by waiting after the fact. -- Álvaro Herrera PostgreSQL Developer — https://www.EnterpriseDB.com/
Re: Race conditions in logical decoding
От:
Álvaro Herrera <alvherre@kurilemu.de>
Дата:
On 2026-Jan-22, Álvaro Herrera wrote: > On 2026-Jan-22, Antonin Houska wrote: > > > Do you mean replace > > > > if (unlikely(!TransactionIdDidCommit(builder->committed.xip[i]))) > > > to > > > > if (unlikely(TransactionIdIsInProgress(builder->committed.xip[i]) || !TransactionIdDidCommit(builder->committed.xip[i]))) > > > > This way the synchronous replication gets stuck, as it did when I tried to use > > XactLockTableWait(): subscriber cannot confirm replication of certain LSN > > because publisher is not able to even finalize the commit (due to the waiting > > for the subscriber's confirmation), and therefore publisher it's not able to > > decode the data and send it to the subscriber. BTW, the reason XactLockTableWait and TransactionIdIsInProgress() cause a deadlock in the same way, is that they are using essentially the same mechanism. The former uses the Lock object on the transaction, which is released (by the ResourceOwnerRelease(RESOURCE_RELEASE_LOCKS) call in CommitTransaction) after RecordTransactionCommit() has returned -- that is, after the wait on a synchronous replica has happened. XactLockTableWait does an _additional_ test for TransactionIdIsInProgress, but that should be pretty much innocuous at that point. One thing that I just realized I don't know, is what exactly are the two pieces that are deadlocking. I mean, one is this side that's decoding commit. But how/why is that other side, the one trying to mark the transaction as committed, waiting on the commit decoding? Maybe there's something that we need to do to _that_ side to prevent the blockage, so that we can use TransactionIdIsInProgress() here. -- Álvaro Herrera PostgreSQL Developer — https://www.EnterpriseDB.com/
Re: Race conditions in logical decoding
От:
Álvaro Herrera <alvherre@kurilemu.de>
Дата:
On 2026-Jan-20, Antonin Houska wrote:
> Antonin Houska wrote:
>
> > I'm not sure yet how to fix the problem. I tried to call XactLockTableWait()
> > from SnapBuildAddCommittedTxn() (like it happens in SnapBuildWaitSnapshot()),
> > but it made at least one regression test (subscription/t/010_truncate.pl)
> > stuck - probably a deadlock. I can spend more time on it, but maybe someone
> > can come up with a good idea sooner than me.
>
> Attached here is what I consider a possible fix - simply wait for the CLOG
> update before building a new snapshot.
>
> Unfortunately I have no idea right now how to test it using the isolation
> tester. With the fix, the additional waiting makes the current test
> block. (And if a step is added that unblock the session, it will not reliably
> catch failure to wait.)
>
> --
> Antonin Houska
> Web: https://www.cybertec-postgresql.com
>
> @@ -400,6 +400,47 @@ SnapBuildBuildSnapshot(SnapBuild *builder)
> snapshot->xmin = builder->xmin;
> snapshot->xmax = builder->xmax;
>
> + /*
> + * Although it's very unlikely, it's possible that a commit WAL record was
> + * decoded but CLOG is not aware of the commit yet. Should the CLOG update
> + * be delayed even more, visibility checks that use this snapshot could
> + * work incorrectly. Therefore we check the CLOG status here.
> + */
> + while (true)
> + {
> + bool found = false;
> +
> + for (int i = 0; i < builder->committed.xcnt; i++)
> + {
> + /*
> + * XXX Is it worth remembering the XIDs that appear to be
> + * committed per CLOG and skipping them in the next iteration of
> + * the outer loop? Not sure it's worth the effort - a single
> + * iteration is enough in most cases.
> + */
> + if (unlikely(!TransactionIdDidCommit(builder->committed.xip[i])))
> + {
> + found = true;
> +
> + /*
> + * Wait a bit before going to the next iteration of the outer
> + * loop. The race conditions we address here is pretty rare,
> + * so we shouldn't need to wait too long.
> + */
> + (void) WaitLatch(MyLatch,
> + WL_LATCH_SET | WL_TIMEOUT | WL_EXIT_ON_PM_DEATH,
> + 10L,
> + WAIT_EVENT_SNAPBUILD_CLOG);
> + ResetLatch(MyLatch);
> +
> + break;
> + }
> + }
> +
> + if (!found)
> + break;
> + }
I think this algorithm is strange -- if you do have to wait more than
once for one transaction, it would lead to doing the
TransactionIdDidCommit again times for _all_ transactions by starting
the inner loop from scratch, which sounds really wasteful. Why not nest
the for() loops the other way around? Something like this perhaps,
for (int i = 0; i < builder->committed.xcnt; i++)
{
for (;;)
{
if (TransactionIdDidCommit(builder->committed.xip[i]))
break;
else
{
(void) WaitLatch(MyLatch,
WL_LATCH_SET, WL_TIMEOUT, WL_EXIT_ON_PM_DEATH,
10L,
WAIT_EVENT_SNAPBUILD_CLOG);
ResetLatch(MyLatch);
}
CHECK_FOR_INTERRUPTS();
}
}
This way you wait repeatedly for one transaction until it is marked
committed; and once it does, you don't test it again.
I also wondered if it would make sense to get rid of the memcpy, given
that we're doing so much work per xid anyway it won't make any visible
difference (I believe), and do the copy per XID there, like
if (TransactionIdDidCommit(builder->committed.xip[i]))
{
snapshot->xip[i] = builder->committed.xip[i];
break;
}
else
...
--
Álvaro Herrera PostgreSQL Developer — https://www.EnterpriseDB.com/
"Sallah, I said NO camels! That's FIVE camels; can't you count?"
(Indiana Jones)
Re: Race conditions in logical decoding
От:
Antonin Houska <ah@cybertec.at>
Дата:
Álvaro Herrera wrote:
> I think this algorithm is strange -- if you do have to wait more than
> once for one transaction, it would lead to doing the
> TransactionIdDidCommit again times for _all_ transactions by starting
> the inner loop from scratch, which sounds really wasteful. Why not nest
> the for() loops the other way around?
I'm quite sure I wanted to iterate through committed.xnt in the outer loop,
but probably got distracted by something else and messed things up.
> Something like this perhaps,
>
> for (int i = 0; i < builder->committed.xcnt; i++)
> {
> for (;;)
> {
> if (TransactionIdDidCommit(builder->committed.xip[i]))
> break;
> else
> {
> (void) WaitLatch(MyLatch,
> WL_LATCH_SET, WL_TIMEOUT, WL_EXIT_ON_PM_DEATH,
> 10L,
> WAIT_EVENT_SNAPBUILD_CLOG);
> ResetLatch(MyLatch);
> }
> CHECK_FOR_INTERRUPTS();
> }
> }
>
> This way you wait repeatedly for one transaction until it is marked
> committed; and once it does, you don't test it again.
Sure, that's much beter. Thanks.
--
Antonin Houska
Web: https://www.cybertec-postgresql.com
Re: Race conditions in logical decoding
От:
Antonin Houska <ah@cybertec.at>
Дата:
Andres Freund wrote: > > Attached here is what I consider a possible fix - simply wait for the CLOG > > update before building a new snapshot. > > I don't think that's enough - during non-timetravel visibility semantics, you > can only look at the clog if the transaction isn't marked as in-progress in > the procarray. ISTM that we need to do that here too? I understand that CLOG must be up-to-date by the time the snapshot is used for visibility checks, but I think that - from the snapshot user POV - what matters is "snapshot->xip vs CLOG" rather than "procarray vs CLOG". For procarray-based snapshots, this consistency is ensured by 1) not removing the XID from procarray until the status is set in CLOG and 2) getting the list of running transactions from procarray. Thus if an MVCC snapshot does not have particular XID in its "xip" array, it implies that it's no longer in procarray and therefore it's been marked in CLOG. As for logical decoding based snapshots (whether HISTORIC_MVCC or those converted eventually to regular MVCC), we currently do not check if CLOG is consistent with the transaction list in snapshot->xip. What I proposed is that we enforce this consistency by checking CLOG (and possibly waiting) before we finalize the snapshot. Thus the snapshot user can safely assume that the snapshot->xip array is consistent with CLOG, as if the snapshot was based on procarray. Or is there another issue with the CLOG itself? I thought about wraparound (i.e. getting the XID status from a CLOG slot which is still being used by old transactions) but I wouldn't expect that (AFAICS, CLOG truncation takes place during XID freezing). Concurrent access to the slot should neither be a problem since only a single byte (which is atomic) needs to be fetched during the XID status check. Another hypothetical problem that occurs to me is memory access ordering, i.e. one backend creates and exports the snapshot and another one imports it before it can see the CLOG update. It's hard to imagine though. Or are there other concerns? -- Antonin Houska Web: https://www.cybertec-postgresql.com
Re: Race conditions in logical decoding
От:
Álvaro Herrera <alvherre@kurilemu.de>
Дата:
On 2026-Jan-23, Antonin Houska wrote:
> > This way you wait repeatedly for one transaction until it is marked
> > committed; and once it does, you don't test it again.
>
> Sure, that's much beter. Thanks.
Actually, I wonder if it would make sense to sleep just once after
testing all the transactions for whether they are marked committed (not
once per transaction); and after sleeping, we only test again those that
were not marked committed in the previous iteration. I think you would
end up doing less tests overall. Something like this
/*
* Although it's very unlikely, it's possible that a commit WAL record was
* decoded but CLOG is not aware of the commit yet. Should the CLOG update
* be delayed even more, visibility checks that use this snapshot could
* work incorrectly. Therefore we check the CLOG status here.
*/
{
TransactionId *stillrunning;
int nstillrunning = builder->committed.xcnt;
stillrunning = palloc(sizeof(TransactionId) * builder->committed.xcnt);
nstillrunning = builder->committed.xcnt;
memcpy(stillrunning, builder->committed.xip, sizeof(TransactionId) * nstillrunning);
for (;;)
{
int next = 0;
if (nstillrunning == 0)
break;
for (int i = 0; i < nstillrunning; i++)
{
if (!TransactionIdDidCommit(stillrunning[i]))
stillrunning[next++] = stillrunning[i];
}
if (next == 0)
break;
nstillrunning = next;
(void) WaitLatch(MyLatch,
WL_LATCH_SET | WL_TIMEOUT | WL_EXIT_ON_PM_DEATH,
10L,
WAIT_EVENT_SNAPBUILD_CLOG);
ResetLatch(MyLatch);
CHECK_FOR_INTERRUPTS();
}
pfree(stillrunning);
}
--
Álvaro Herrera Breisgau, Deutschland — https://www.EnterpriseDB.com/
"Use it up, wear it out, make it do, or do without"
Re: Race conditions in logical decoding
От:
Antonin Houska <ah@cybertec.at>
Дата:
Álvaro Herrera wrote: > On 2026-Jan-23, Antonin Houska wrote: > > > > This way you wait repeatedly for one transaction until it is marked > > > committed; and once it does, you don't test it again. > > > > Sure, that's much beter. Thanks. > > Actually, I wonder if it would make sense to sleep just once after > testing all the transactions for whether they are marked committed (not > once per transaction); and after sleeping, we only test again those that > were not marked committed in the previous iteration. I think you would > end up doing less tests overall. Something like this I suppose that TransactionIdDidCommit() returns false pretty rarely, so one iteration is sufficient in almost all cases. Besides that, I preferred simpler code because it's easier to test (It's not trivial to have debugger reach the conditions.) However it's just my preference - no real objections to your approach. -- Antonin Houska Web: https://www.cybertec-postgresql.com
Re: Race conditions in logical decoding
Hi, I realized that I hadn't posted the patch version I described somewhere downthread. Here it is, as 0001. While thinking about it for posting just now, I wondered if it would work to consider that any transaction whose commit record has been decoded but which nevertheless gets a true return from TransactionIdIsInProgress(), just is not committed yet and so should be omitted from the xip array of the snapshot. That is, if it's still-running, then we just don't copy it into the output snapshot. That's implemented as 0002 here. This seems somehow less controversial, as we don't have to test TransactionIdDidCommit() for a transaction that we haven't seen as not-running per PGPROC; and it should also be faster, because we don't have to wait for anybody to commit. However it gives me pause that perhaps the snapshot would not be fully correct. (Indeed there are a few failing tests in the subscription suite). Failing other ideas, I think we should just go with 0001. We'd need more commentary on why is TransactionIdDidCommit() OK, when we haven't scanned PGPROC for that xid, though. Thanks, -- Álvaro Herrera 48°01'N 7°57'E — https://www.EnterpriseDB.com/ "El que vive para el futuro es un iluso, y el que vive para el pasado, un imbécil" (Luis Adler, "Los tripulantes de la noche")
Re: Race conditions in logical decoding
От:
Antonin Houska <ah@cybertec.at>
Дата:
Álvaro Herrera wrote: > I realized that I hadn't posted the patch version I described somewhere > downthread. Here it is, as 0001. > > While thinking about it for posting just now, I wondered if it would > work to consider that any transaction whose commit record has been > decoded but which nevertheless gets a true return from > TransactionIdIsInProgress(), just is not committed yet and so should be > omitted from the xip array of the snapshot. That is, if it's > still-running, then we just don't copy it into the output snapshot. > That's implemented as 0002 here. This seems somehow less controversial, > as we don't have to test TransactionIdDidCommit() for a transaction that > we haven't seen as not-running per PGPROC; and it should also be faster, > because we don't have to wait for anybody to commit.However it gives > me pause that perhaps the snapshot would not be fully correct. (Indeed > there are a few failing tests in the subscription suite). I recall that in some of the patches for REPACK enhancements (snapshot switching, MVCC-safety, etc.) for v20 I had a problem with TransactionIdIsInProgress(). In particular, I tried to add a flag like PROC_IN_VACUUM, to limit the REPACK's impact on VACUUM xmin horizon. The problem was that TransactionIdIsInProgress() compares the xid to RecentXmin before accessing CLOG. IIRC VACUUM's RecentXmin skipped the xid of REPACK and considered its xid not in progress anymore, but since the transaction wasn't committed yet per CLOG, VACCUM incorrectly considered it aborted (per HeapTupleSatisfiesVacuumHorizon). Thus I imagine that with 0002, transaction having PROC_IN_SAFE_IC set might be added to the snapshot's list of committed transactions although its still in progress. > Failing other ideas, I think we should just go with 0001. We'd need more > commentary on why is TransactionIdDidCommit() OK, when we haven't > scanned PGPROC for that xid, though. Mihail already told me that I should consider adding this patch to the CF. I said that I'm aware of its importance (because REPACK probably exposes the bug more than logical replication does) and that I'll remind you if you happen to forget about it. However I thought that fixes of existing bugs are not subject to feature freeze, so I did not bring it up yet. -- Antonin Houska Web: https://www.cybertec-postgresql.com
Re: Race conditions in logical decoding
От:
Mihail Nikalayeu <mihailnikalayeu@gmail.com>
Дата:
Hello, everyone! Decided to add to CF to ensure we track this properly. https://commitfest.postgresql.org/patch/6840/ Mikhail.
Re: Race conditions in logical decoding
От:
Álvaro Herrera <alvherre@kurilemu.de>
Дата:
Hello, replying to Hou and Houska emails in one. On 2026-Aug-22, Zhijie Hou (Fujitsu) wrote: > I think the cache might be better placed in the SnapBuild struct (at least on > HEAD) rather than in static variables. As currently written, it persists across > decoding sessions in the same backend - a session could build a snapshot, drop > the slot, and later create a new slot and build another snapshot, potentially > consulting stale entries from the first builder. For example, it has a wraparound > concern: after XID wrap, a cached value could refer to a different transaction, > causing us to skip the CLOG wait and reintroduce the inconsistency this patch > aims to fix. Hmm, yeah, there's definitely a problem with that. Now, this bug can affect logical decoding in existing releases as well, so we should backpatch this fix, and I'm not sure about changing SnapBuild in backbranches. Maybe another approach is to use file-level statics (rather than function-level) so that they can be reset by slot drop routines. > Besides, just to confirm one note: IIUC, for exported snapshots by logicalrep, a > transaction could be treated as committed while still in PGPROC, while > concurrent MVCC snapshots still see it as in progress which looks inconsistent. > I understand that waiting for ProcArray removal in the general case could > deadlock against synchronous replication, so it's probably acceptable to leave > it unchanged for internal usage in active replication processes. OK. TBH I'm somewhat unease about this inconsistency; I wondered about doing the CLOG-based test only in sync replication and using XidIsInProgress otherwise, but didn't really try (which is to say: I'm not even sure if it's _possible_ at all.) > However, for cases where the snapshot is exported, would it be possible to > additionally wait for it in SnapBuildInitialSnapshot() (which is used only by > CREATE_REPLICATION_SLOT and REPACK)? Since that runs before START_REPLICATION, > the process isn't streaming or feeding any subscriber, so I believe the deadlock > wouldn't occur there. (I think that the walsender executing > CREATE_REPLICATION_SLOT shouldn't be added to sync_standby_names, otherwise > building the initial snapshot itself would already have a deadlock risk via > SnapBuildWaitSnapshot->XactLockTableWait.) Yeah, we could do that. Do you want to try and write a patch? On 2026-Aug-25, Antonin Houska wrote: > Besides, that, it occurred to me that a sorted array might be appropriate > instead of a list, so that bsearch() can be used, but I'm not sure about that. I think we should absolutely do something like that, because repeated list_member_oid() are unlikely to be great. Maybe as output of each run we end up with an unsorted array; when SnapBuildBuildSnapshot runs next time, the first thing we do is sort the array for bsearch. That way, we don't have to sort unless absolutely necessary. -- Álvaro Herrera Breisgau, Deutschland — https://www.EnterpriseDB.com/ "Para tener más hay que desear menos"
Re: Race conditions in logical decoding
От:
Antonin Houska <ah@cybertec.at>
Дата:
Álvaro Herrera wrote: > Hello, replying to Hou and Houska emails in one. > > On 2026-Aug-22, Zhijie Hou (Fujitsu) wrote: > > > I think the cache might be better placed in the SnapBuild struct (at least on > > HEAD) rather than in static variables. As currently written, it persists across > > decoding sessions in the same backend - a session could build a snapshot, drop > > the slot, and later create a new slot and build another snapshot, potentially > > consulting stale entries from the first builder. For example, it has a wraparound > > concern: after XID wrap, a cached value could refer to a different transaction, > > causing us to skip the CLOG wait and reintroduce the inconsistency this patch > > aims to fix. > > Hmm, yeah, there's definitely a problem with that. Now, this bug can > affect logical decoding in existing releases as well, so we should > backpatch this fix, and I'm not sure about changing SnapBuild in > backbranches. Maybe another approach is to use file-level statics > (rather than function-level) so that they can be reset by slot drop > routines. > > > Besides, just to confirm one note: IIUC, for exported snapshots by logicalrep, a > > transaction could be treated as committed while still in PGPROC, while > > concurrent MVCC snapshots still see it as in progress which looks inconsistent. > > I understand that waiting for ProcArray removal in the general case could > > deadlock against synchronous replication, so it's probably acceptable to leave > > it unchanged for internal usage in active replication processes. > > OK. TBH I'm somewhat unease about this inconsistency; I wondered about > doing the CLOG-based test only in sync replication and using > XidIsInProgress otherwise, but didn't really try (which is to say: I'm > not even sure if it's _possible_ at all.) I'm trying to understand if this kind of inconsistency has the chance to be seen by users. I suspect the concern is about a session having isolation level at least REPEATABLE_READ which scans the table two times using the same snapshot, however another session runs REPACK (CONCURRENTLY) in between. Due to the inconsistency explained above, the snapshot might miss some changes that REPACK already does see. IMO the 2nd scan will not see a different version of the table the table had to be locked before the first scan started, so REPACK won't be able to finish until the whole transaction is finished. Even w/o keeping the lock between the scans, both scans would retrieve the same rows as long as REPACK (CONCURRENTLY) is MVCC-safe (currently it's is not, but should be in the future). Regarding logical replication, yes, this inconsistency can be the reason some data changes are already visible on the replica while some snapshots don't yet see it on the primary. However I think that can happen anyway if the MVCC snapshot for the scan on the primary had been created before the snapshot for the logical replication. Maybe I've just misunderstood something. -- Antonin Houska Web: https://www.cybertec-postgresql.com
Re: Race conditions in logical decoding
On Mon, Jan 19, 2026 at 05:29:25PM +0100, Antonin Houska wrote: > A stress test [1] for the REPACK patch [1] revealed data > corruption. Eventually I found out that the problem is in postgres core. In > particular, it can happen that a COMMIT record is decoded, but before the > commit could be recorded in CLOG, a snapshot that takes the commit into > account is created and even used. Visibility checks then work incorrectly > until the CLOG gets updated. On Fri, Aug 21, 2026 at 08:16:02PM +0200, Álvaro Herrera wrote: > So, what do you think of the attached? I see $SUBJECT lost open item status because released versions have the same defect. However, REPACK (CONCURRENTLY) increases the importance of $SUBJECT and other logical replication data loss causes. In v18, one can recreate the replica or run integrity checks before a cutover. REPACK (CONCURRENTLY) automates the chain: one command starts replication, waits for consistency, and deletes the last known good copy. If v19 ships without a fix for $SUBJECT, I think REPACK (CONCURRENTLY) docs need to warn about the situation. How do you see it?
RE: Race conditions in logical decoding
Hi, On Wednesday, September 9, 2026 6:20 PM Álvaro Herrera wrote: > On 2026-Aug-22, Zhijie Hou (Fujitsu) wrote: > > > > Besides, just to confirm one note: IIUC, for exported snapshots by > > logicalrep, a transaction could be treated as committed while still in > > PGPROC, while concurrent MVCC snapshots still see it as in progress which > looks inconsistent. > > I understand that waiting for ProcArray removal in the general case > > could deadlock against synchronous replication, so it's probably > > acceptable to leave it unchanged for internal usage in active replication processes. > > OK. TBH I'm somewhat unease about this inconsistency; I wondered about > doing the CLOG-based test only in sync replication and using XidIsInProgress > otherwise, but didn't really try (which is to say: I'm not even sure if it's > _possible_ at all.) I experimented with this a bit and confirmed that the inconsistency exists, though it doesn't affect REPACK (CONCURRENTLY), the command takes an exclusive lock on the table when switching the old and new heap, which forces any concurrent transactions on that table to finish first. However, the inconsistency can be observed if a user directly uses the exported snapshot, as shown in the attachment (generated with AI assistance). > > > However, for cases where the snapshot is exported, would it be > > possible to additionally wait for it in SnapBuildInitialSnapshot() > > (which is used only by CREATE_REPLICATION_SLOT and REPACK)? Since > that > > runs before START_REPLICATION, the process isn't streaming or feeding > > any subscriber, so I believe the deadlock wouldn't occur there. (I > > think that the walsender executing CREATE_REPLICATION_SLOT shouldn't > > be added to sync_standby_names, otherwise building the initial > > snapshot itself would already have a deadlock risk via > > SnapBuildWaitSnapshot->XactLockTableWait.) > > Yeah, we could do that. > > Do you want to try and write a patch? I see that Rui Zhao has shared a patch based on this approach [1]. The email is lengthy, but the core idea is to perform the wait inside SnapBuildInitialSnapshot(). [1] https://www.postgresql.org/message-id/CAHWVJhHXyLtS-8mdL9WhEWfsERb%3DFN7JdPD0GYAXgTmCnqbYGw%40mail.gmail.com Best Regards, Zhijie Hou
Re: Race conditions in logical decoding
От:
Antonin Houska <ah@cybertec.at>
Дата:
Rui Zhao wrote:
> 1. The wait belongs in SnapBuildInitialSnapshot() and nowhere else:
> SnapBuildBuildSnapshot() does not need it, and in
> SnapBuildInitialSnapshot() it can be a wait on the transaction lock.
> 0001 does that.
>
> SnapBuildInitialSnapshot() is the only place where the builder's list of
> committed transactions turns into a regular MVCC snapshot, and it is
> HeapTupleSatisfiesMVCC() on that snapshot that asks CLOG about a
> transaction between xmin and xmax. The historic snapshots that
> SnapBuildBuildSnapshot() hands to the reorder buffer never do:
> HeapTupleSatisfiesHistoricMVCC() decides the range [xmin, xmax) by the
> xip array alone and consults CLOG only below xmin, and builder->xmin is
> always the oldestRunningXid of an xl_running_xacts record, so a
> transaction below it had left the procarray, and so updated CLOG, before
> that record was written.
I initially thought that it's silly to rely on such tricky details, but not
consulting CLOG appears to be a design choice - see the header comment in
snapbuild.c.
* ........ Also, our snapshots need to be different in comparison to normal
* MVCC ones because in contrast to those we cannot fully rely on the clog and
* pg_subtrans for information about committed transactions because they might
* commit in the future from the POV of the WAL entry we're currently
* decoding. ...
And regarding snapshot's xmin, I agree that it's controlled by
xl_running_xacts WAL record and that it does not advance until the transaction
has been recorded in CLOG.
Thus I'm not opposed to the idea that it's enough to add the check to
SnapBuildInitialSnapshot().
> + if (!RecoveryInProgress())
> + {
> + RunningTransactions running;
> + int nrunning;
> +
> + running = GetRunningTransactionData();
> + nrunning = running->xcnt + running->subxcnt;
> + LWLockRelease(ProcArrayLock);
> + LWLockRelease(XidGenLock);
> +
> + for (int i = 0; i < nrunning; i++)
> + {
> + TransactionId running_xid = running->xids[i];
> +
> + if (bsearch(&running_xid, snap->xip, snap->xcnt,
> + sizeof(TransactionId), xidComparator) != NULL)
> + XactLockTableWait(running_xid, NULL, NULL, XLTW_None);
> + }
> + }
I don't understand why you check all transactions in procarray, instead of
only those in snap->xip.
--
Antonin Houska
Web: https://www.cybertec-postgresql.com
Re: Race conditions in logical decoding
От:
Antonin Houska <ah@cybertec.at>
Дата:
Zhijie Hou (Fujitsu) wrote: > On Wednesday, September 9, 2026 6:20 PM Álvaro Herrera wrote: > > On 2026-Aug-22, Zhijie Hou (Fujitsu) wrote: > > > > > > Besides, just to confirm one note: IIUC, for exported snapshots by > > > logicalrep, a transaction could be treated as committed while still in > > > PGPROC, while concurrent MVCC snapshots still see it as in progress which > > looks inconsistent. > > > I understand that waiting for ProcArray removal in the general case > > > could deadlock against synchronous replication, so it's probably > > > acceptable to leave it unchanged for internal usage in active replication processes. > > > > OK. TBH I'm somewhat unease about this inconsistency; I wondered about > > doing the CLOG-based test only in sync replication and using XidIsInProgress > > otherwise, but didn't really try (which is to say: I'm not even sure if it's > > _possible_ at all.) > > I experimented with this a bit and confirmed that the inconsistency exists, > though it doesn't affect REPACK (CONCURRENTLY), the command takes an exclusive > lock on the table when switching the old and new heap, which forces any > concurrent transactions on that table to finish first. However, the > inconsistency can be observed if a user directly uses the exported snapshot, as > shown in the attachment (generated with AI assistance). ... > diff --git a/src/test/recovery/t/058_exported_snapshot_pgproc_window.pl b/src/test/recovery/t/058_exported_snapshot_pgproc_window.pl > new file mode 100644 > index 00000000000..4b6d8dd8353 > --- /dev/null > +++ b/src/test/recovery/t/058_exported_snapshot_pgproc_window.pl > @@ -0,0 +1,293 @@ > +# Copyright (c) 2026, PostgreSQL Global Development Group > +# > +# Test that a snapshot exported by CREATE_REPLICATION_SLOT ... (SNAPSHOT > +# 'export') can treat a transaction as committed while that transaction is > +# still in the procarray, so that concurrent MVCC snapshots taken by other > +# backends still see it as in progress. As far as I understand, what you demonstrate here is that different backends can have a different view of the database. Isn't that pretty common situation? What I'd consider a problem would be a single backend (and single transaction) seeing inconsistent data. -- Antonin Houska Web: https://www.cybertec-postgresql.com
RE: Race conditions in logical decoding
От:
"Zhijie Hou (Fujitsu)" <houzj.fnst@fujitsu.com>
Дата:
Hi, On Thursday, September 17, 2026 5:53 PM Antonin Houska wrote: > Zhijie Hou (Fujitsu) wrote: > > > On Wednesday, September 9, 2026 6:20 PM Álvaro Herrera > wrote: > > > OK. TBH I'm somewhat unease about this inconsistency; I wondered > > > about doing the CLOG-based test only in sync replication and using > > > XidIsInProgress otherwise, but didn't really try (which is to say: > > > I'm not even sure if it's _possible_ at all.) > > > > I experimented with this a bit and confirmed that the inconsistency > > exists, though it doesn't affect REPACK (CONCURRENTLY), the command > > takes an exclusive lock on the table when switching the old and new > > heap, which forces any concurrent transactions on that table to finish > > first. However, the inconsistency can be observed if a user directly > > uses the exported snapshot, as shown in the attachment (generated with AI > assistance). > > ... > > --- /dev/null > > +++ b/src/test/recovery/t/058_exported_snapshot_pgproc_window.pl > > @@ -0,0 +1,293 @@ > > +# Copyright (c) 2026, PostgreSQL Global Development Group # # Test > > +that a snapshot exported by CREATE_REPLICATION_SLOT ... (SNAPSHOT # > > +'export') can treat a transaction as committed while that transaction > > +is # still in the procarray, so that concurrent MVCC snapshots taken > > +by other # backends still see it as in progress. > > As far as I understand, what you demonstrate here is that different backends > can have a different view of the database. Isn't that pretty common situation? I'm personally not comfortable with the fact that an MVCC snapshot could ever see changes from a transaction that is still considered in progress from PGPROC's perspective. This situation can only arise when using a snapshot exported by logical decoding. IIUC, any other normal MVCC snapshot follows the same rule: it cannot see changes whose PGPROC entries have not been cleaned, regardless of when the snapshot is created or used, as long as the PGPROC xid has not been cleaned. (I may be missing some cases, please correct me if so.) > What I'd consider a problem would be a single backend (and single > transaction) seeing inconsistent data. Best Regards, Zhijie Hou
Re: Race conditions in logical decoding
От:
Alvaro Herrera <alvherre@kurilemu.de>
Дата:
On 2026-Sep-17, Antonin Houska wrote:
> > + for (int i = 0; i < nrunning; i++)
> > + {
> > + TransactionId running_xid = running->xids[i];
> > +
> > + if (bsearch(&running_xid, snap->xip, snap->xcnt,
> > + sizeof(TransactionId), xidComparator) != NULL)
> > + XactLockTableWait(running_xid, NULL, NULL, XLTW_None);
> > + }
> > + }
>
> I don't understand why you check all transactions in procarray, instead of
> only those in snap->xip.
Hmm, but he does: for all the transactions that are running, only those
that are found by bsearch() in the snap->xip array are waited for. Is
that not what we want?
I guess we could do it the other way around: iterate for each item on
snap->xip and search for those in running->xids. Is that what you
suggest?
We don't know offhand which array is largest; it would be better to
iterate on the smaller one and bsearch the largest. (Or maybe if both
are sorted, scan them simultaneously.) I don't find any reference to
say that running_xid is sorted.
I don't understand these two paragraphs:
* A subtransaction is covered by its top-level transaction, which is in
* snap->xip as well, or was purged from it because it is below xmin and
* thus finished long ago.
*
* Historic snapshots do not need this: between xmin and xmax they rely on
* xip alone, and transactions below xmin had left the procarray by the
* time the xl_running_xacts record that set xmin was written.
--
Álvaro Herrera PostgreSQL Developer — https://www.EnterpriseDB.com/
"After a quick R of TFM, all I can say is HOLY CR** THAT IS COOL! PostgreSQL was
amazing when I first started using it at 7.2, and I'm continually astounded by
learning new features and techniques made available by the continuing work of
the development team."
Berend Tober, http://archives.postgresql.org/pgsql-hackers/2007-08/msg01009.php
Re: Race conditions in logical decoding
От:
Antonin Houska <ah@cybertec.at>
Дата:
Alvaro Herrera wrote:
> On 2026-Sep-17, Antonin Houska wrote:
>
> > > + for (int i = 0; i < nrunning; i++)
> > > + {
> > > + TransactionId running_xid = running->xids[i];
> > > +
> > > + if (bsearch(&running_xid, snap->xip, snap->xcnt,
> > > + sizeof(TransactionId), xidComparator) != NULL)
> > > + XactLockTableWait(running_xid, NULL, NULL, XLTW_None);
> > > + }
> > > + }
> >
> > I don't understand why you check all transactions in procarray, instead of
> > only those in snap->xip.
>
> Hmm, but he does: for all the transactions that are running, only those
> that are found by bsearch() in the snap->xip array are waited for. Is
> that not what we want?
>
> I guess we could do it the other way around: iterate for each item on
> snap->xip and search for those in running->xids. Is that what you
> suggest?
>
> We don't know offhand which array is largest; it would be better to
> iterate on the smaller one and bsearch the largest. (Or maybe if both
> are sorted, scan them simultaneously.) I don't find any reference to
> say that running_xid is sorted.
Maybe I miss the point, but what's wrong about modifying the existing loop
that inverts the meaning of the ->xip array
/*
* snapbuild.c builds transactions in an "inverted" manner, which means it
* stores committed transactions in ->xip, not ones in progress. Build a
* classical snapshot by marking all non-committed transactions as
* in-progress. This can be expensive.
*/
for (xid = snap->xmin; NormalTransactionIdPrecedes(xid, snap->xmax);)
{
...
}
by calling XactLockTableWait() for each XID we find in the array (i.e. each
committed transaction)?
> I don't understand these two paragraphs:
>
> * A subtransaction is covered by its top-level transaction, which is in
> * snap->xip as well, or was purged from it because it is below xmin and
> * thus finished long ago.
Me neither. AFAIU SnapBuildCommitTxn() adds both top-level transaction and
subtransactions to the builder's array of committed transaction.
> * Historic snapshots do not need this: between xmin and xmax they rely on
> * xip alone, and transactions below xmin had left the procarray by the
> * time the xl_running_xacts record that set xmin was written.
I think this is related to the note that HeapTupleSatisfiesHistoricMVCC() does
not really use CLOG in the 3rd paragraph in [1].
[1] https://www.postgresql.org/message-id/CAHWVJhHXyLtS-8mdL9WhEWfsERb%3DFN7JdPD0GYAXgTmCnqbYGw%40mail.gmail.com
--
Antonin Houska
Web: https://www.cybertec-postgresql.com
Re: Race conditions in logical decoding
On 2026-Sep-18, Antonin Houska wrote:
> Maybe I miss the point, but what's wrong about modifying the existing loop
> that inverts the meaning of the ->xip array
>
> /*
> * snapbuild.c builds transactions in an "inverted" manner, which means it
> * stores committed transactions in ->xip, not ones in progress. Build a
> * classical snapshot by marking all non-committed transactions as
> * in-progress. This can be expensive.
> */
> for (xid = snap->xmin; NormalTransactionIdPrecedes(xid, snap->xmax);)
> {
> ...
> }
>
> by calling XactLockTableWait() for each XID we find in the array (i.e. each
> committed transaction)?
Ah, you mean something like the attached quick POC? This does pass the
two tests that Rui wrote, also attached. (I didn't test Zhijie's, which
AFAICT is written to pass with the bug and fail without it.)
--
Álvaro Herrera 48°01'N 7°57'E — https://www.EnterpriseDB.com/
"They proved that being American is not just for some people"
(George Takei)
Re: Race conditions in logical decoding
От:
Antonin Houska <ah@cybertec.at>
Дата:
Alvaro Herrera wrote:
> On 2026-Sep-18, Antonin Houska wrote:
>
> > Maybe I miss the point, but what's wrong about modifying the existing loop
> > that inverts the meaning of the ->xip array
> >
> > /*
> > * snapbuild.c builds transactions in an "inverted" manner, which means it
> > * stores committed transactions in ->xip, not ones in progress. Build a
> > * classical snapshot by marking all non-committed transactions as
> > * in-progress. This can be expensive.
> > */
> > for (xid = snap->xmin; NormalTransactionIdPrecedes(xid, snap->xmax);)
> > {
> > ...
> > }
> >
> > by calling XactLockTableWait() for each XID we find in the array (i.e. each
> > committed transaction)?
>
> Ah, you mean something like the attached quick POC? This does pass the
> two tests that Rui wrote, also attached. (I didn't test Zhijie's, which
> AFAICT is written to pass with the bug and fail without it.)
Yes, I mean checking if those transactions have really ended.
Regarding [1], perhaps the idea is to avoid calling XactLockTableWait() if the
transaction is no longer in procarray. I'm not sure it's a problem to call
that function (possibly many times) for transactions that are no longer
running. (GetRunningTransactionData() is not free either.)
And regarding the deadlock with synchronous replica, my understanding is that
we avoid it by waiting in SnapBuildInitialSnapshot() instead of in
SnapBuildBuildSnapshot().
[1] https://www.postgresql.org/message-id/CAHWVJhHXyLtS-8mdL9WhEWfsERb%3DFN7JdPD0GYAXgTmCnqbYGw%40mail.gmail.com
--
Antonin Houska
Web: https://www.cybertec-postgresql.com
Re: Race conditions in logical decoding
On 2026-Sep-18 at 14:29 UTC, Alvaro Herrera wrote: > This does pass the two tests that Rui wrote, also attached. In v5-0001, newxcnt++ needs to stay in the test == NULL branch. Otherwise committed XIDs increase the count without filling an entry in newxip. The attached v5-0004 applies on top of v5-0001 through v5-0003. It puts the increment back with the assignment in 0001 and adds a snapshot XID check to 0003's test. With 0003's setup, after slot creation finishes, I ran this on the connection holding the slot's snapshot: SELECT pg_current_snapshot(); -- v5: 669:670:0 -- with the correction: 669:670: The original REPACK and TAP tests pass with v5. The added check requires each snapshot XID to lie in [xmin, xmax): it fails with v5 and passes with the correction. Both original tests still pass. On 2026-Sep-17 at 08:37 UTC, Antonin Houska wrote: > I don't understand why you check all transactions in procarray, instead of > only those in snap->xip. I first tried calling XactLockTableWait() for every XID in snap->xip, the same per-XID waiting approach as v5. Even for an already finished XID, that goes through the lock manager and calls TransactionIdIsInProgress(). Unless its RecentXmin or cached-XID checks suffice, that takes ProcArrayLock and scans procarray. In the patch attached to my original mail, I instead read the running-XID list once and used bsearch to wait only for XIDs also in snap->xip. That was to avoid repeating this work for transactions that had already finished. On 2026-Sep-18 at 15:23 UTC, Antonin Houska wrote: > I'm not sure it's a problem to call that function (possibly many times) > for transactions that are no longer running. The case I had in mind was a long-running transaction holding xmin back while many other transactions commit. snap->xip can then be much larger than the running set. GetSnapshotData() uses the same ProcArrayLock and array, so my concern was the extra traffic on shared state used for taking snapshots, not just slot creation time. On 2026-Sep-12 at 17:35 UTC, I wrote: > The two callers, CREATE_REPLICATION_SLOT before START_REPLICATION and > the REPACK worker, stream to nobody, so the synchronous replication > deadlock of the streaming walsender does not apply to them. On 2026-Sep-18 at 15:23 UTC, Antonin Houska wrote: > And regarding the deadlock with synchronous replica, my understanding is > that we avoid it by waiting in SnapBuildInitialSnapshot() instead of in > SnapBuildBuildSnapshot(). Yes, that's right. It is the placement of the wait, not the procarray filtering, that avoids that deadlock. On 2026-Sep-18 at 12:28 UTC, Alvaro Herrera wrote: > I don't understand these two paragraphs: > > * A subtransaction is covered by its top-level transaction, which is in > * snap->xip as well, or was purged from it because it is below xmin and > * thus finished long ago. > * > * Historic snapshots do not need this: between xmin and xmax they rely on > * xip alone, and transactions below xmin had left the procarray by the > * time the xl_running_xacts record that set xmin was written. The first was meant to explain why we don't have to find every subxid in the running-XID list. If any backend's subxid cache has overflowed, GetRunningTransactionData() returns top-level XIDs but no subxids. We still wait for the parent, which covers its children. If the parent was purged from snap->xip because it is below xmin, it has already finished, so no wait is needed. The second was a different question: why wait only in SnapBuildInitialSnapshot(), rather than in SnapBuildBuildSnapshot(), which is also used to build historic snapshots? Here "this" meant waiting for transactions to finish, not handling subtransactions. Historic snapshots use xip for committed-XID checks in [xmin, xmax). They can consult CLOG below xmin, but those transactions had already finished when the running-xacts record supplying xmin was written. So they need no extra wait. The wait is needed when converting to a normal MVCC snapshot, whose visibility checks can consult CLOG for transactions in [xmin, xmax) as well. That is why I put it in SnapBuildInitialSnapshot(). Regards, Rui
Re: Race conditions in logical decoding
От:
Alvaro Herrera <alvherre@kurilemu.de>
Дата:
On 2026-Sep-20, Rui Zhao wrote: > On 2026-Sep-18 at 14:29 UTC, Alvaro Herrera wrote: > > This does pass the two tests that Rui wrote, also attached. > > In v5-0001, newxcnt++ needs to stay in the test == NULL branch. > Otherwise committed XIDs increase the count without filling an entry > in newxip. Eh, yeah. > On 2026-Sep-17 at 08:37 UTC, Antonin Houska wrote: > > I don't understand why you check all transactions in procarray, instead of > > only those in snap->xip. > > I first tried calling XactLockTableWait() for every XID in snap->xip, > the same per-XID waiting approach as v5. Even for an already finished > XID, that goes through the lock manager and calls > TransactionIdIsInProgress(). Unless its RecentXmin or cached-XID > checks suffice, that takes ProcArrayLock and scans procarray. > > In the patch attached to my original mail, I instead read the > running-XID list once and used bsearch to wait only for XIDs also in > snap->xip. That was to avoid repeating this work for transactions > that had already finished. Yeah, maybe this approach isn't great after all. We could turn that around and search for each loop around the snap->xmin..snap->xmax loop that is found in snap->xip in the running->xids array. That reduces the number of times we go through XactLockTableWait() to only running transactions (same as in Rui's original patch [1]). However, the running->xids array is not sorted, so we would have to qsort() it, or do a plain array walk for each element. In the end, I think the code in your (Rui's) first patch is the simplest approach. It's possible that there's a slight performance difference between scanning the running->xids array with bsearch() on snap->xip, versus scanning the snap->xip array with bsearch on running->xids. However, given the amount of code involved in the XactLockTableWait() that we have to do on each item we find still running, I expect the difference to be negligible. And doing it certainly beats ending up with corrupt data anyway. So I'm going to take the code mostly from Rui's original patch[1]. [1] https://postgr.es/m/CAHWVJhHXyLtS-8mdL9WhEWfsERb=FN7JdPD0GYAXgTmCnqbYGw@mail.gmail.com However, the situation with comments is not completely settled for me. I asked: > On 2026-Sep-18 at 12:28 UTC, Alvaro Herrera wrote: > > I don't understand [this comment]: > > > > * A subtransaction is covered by its top-level transaction, which is in > > * snap->xip as well, or was purged from it because it is below xmin and > > * thus finished long ago. and you said: > The first was meant to explain why we don't have to find every > subxid in the running-XID list. If any backend's subxid cache has > overflowed, GetRunningTransactionData() returns top-level XIDs but no > subxids. We still wait for the parent, which covers its children. However, the code scans running->xids with a limit of + nrunning = running->xcnt + running->subxcnt; which means we scan both main Xids as well as subxids, which seems to contradict what you said. I think we should just go up to running->xcnt only; if any subxids are in there, we can ignore that, because we'd still do the XactLockTableWait with the parent xact. (We know, by construction, that the array has the top-level XIDs first, followed by subxids. This doesn't seem documented anywhere though. Perhaps if this is ever broken, SnapBuildWaitSnapshot would be trouble. Maybe worth adding a comment somewhere.) I also asked: > On 2026-Sep-18 at 12:28 UTC, Alvaro Herrera wrote: > > I don't understand [this other comment]: > > > > * Historic snapshots do not need this: between xmin and xmax they rely on > > * xip alone, and transactions below xmin had left the procarray by the > > * time the xl_running_xacts record that set xmin was written. and you replied: > The second was a different question: why wait only in > SnapBuildInitialSnapshot(), rather than in SnapBuildBuildSnapshot(), > which is also used to build historic snapshots? Here "this" meant > waiting for transactions to finish, not handling subtransactions. > > Historic snapshots use xip for committed-XID checks in [xmin, xmax). > They can consult CLOG below xmin, but those transactions had already > finished when the running-xacts record supplying xmin was written. > So they need no extra wait. Ah, I see. It makes sense when explained like that, but I find it difficult to understand in the broader context of the comment being added. I don't disagree that this is worth commenting about, but I'm not sure this is the best place to do it. Rather, maybe we should add something in SnapBuildBuildSnapshot() to explain why we don't do this there. -- Álvaro Herrera 48°01'N 7°57'E — https://www.EnterpriseDB.com/
Re: Race conditions in logical decoding
On 2026-Sep-21, Alvaro Herrera wrote: > Yeah, maybe this approach isn't great after all. We could turn that > around and search for each loop around the snap->xmin..snap->xmax loop > that is found in snap->xip in the running->xids array. That reduces the > number of times we go through XactLockTableWait() to only running > transactions (same as in Rui's original patch [1]). However, the > running->xids array is not sorted, so we would have to qsort() it, or do > a plain array walk for each element. BTW just to make it clear what I'm talking about, attached is the patch for this approach, which I'm now thinking to throw away in favor of Rui's earlier version. (The test contains the change Rui suggested yesterday, and it's passing for me with this patch.) I didn't touch the commit message. -- Álvaro Herrera 48°01'N 7°57'E — https://www.EnterpriseDB.com/ "Las cosas son buenas o malas segun las hace nuestra opinión" (Lisias)
Re: Race conditions in logical decoding
От:
Rui Zhao <zhaorui126@gmail.com>
Дата:
Thanks. Going back to my original loop with the limit changed to running->xcnt makes sense. On 2026-Sep-21 at 15:35 UTC, Alvaro Herrera wrote: > I think we should just go up to running->xcnt > only; Yes, scanning the subxids was unnecessary. My previous explanation addressed overflow, but waiting for the parent covers the children in the non-overflow case too. A note on the top-level-first ordering in RunningTransactionsData would make that dependency explicit. > maybe we should add > something in SnapBuildBuildSnapshot() Agreed. The explanation of why historic snapshots need no wait for transactions to finish belongs there. The comment in SnapBuildInitialSnapshot() can then focus on why the conversion to a normal MVCC snapshot needs the wait. Regards, Rui
Re: Race conditions in logical decoding
От:
Alvaro Herrera <alvherre@kurilemu.de>
Дата:
On 2026-Sep-24, Rui Zhao wrote: > Thanks. Going back to my original loop with the limit changed to > running->xcnt makes sense. OK, I have pushed this to all branches, including the test cases on branches where they work. Thanks all for the work on this issue! I'm going to mark the two pg19 open items (!!) as done. > On 2026-Sep-21 at 15:35 UTC, Alvaro Herrera wrote: > > I think we should just go up to running->xcnt > > only; > > Yes, scanning the subxids was unnecessary. My previous explanation > addressed overflow, but waiting for the parent covers the children in > the non-overflow case too. A note on the top-level-first ordering in > RunningTransactionsData would make that dependency explicit. I didn't add this ... let's consider that as follow-on work, but we don't need it to be backpatched. > > maybe we should add > > something in SnapBuildBuildSnapshot() > > Agreed. The explanation of why historic snapshots need no wait for > transactions to finish belongs there. The comment in > SnapBuildInitialSnapshot() can then focus on why the conversion to a > normal MVCC snapshot needs the wait. Done that way -- I hope the explanations are clear. -- Álvaro Herrera Breisgau, Deutschland — https://www.EnterpriseDB.com/