Bug in logical decoding with DDL and subtransactions

Поиск
Список
Период
Сортировка
Искать

Bug in logical decoding with DDL and subtransactions

От:
Mark Dilger <mark.dilger@enterprisedb.com>
Дата:
Вложения:
There is a bug in logical decoding with CREATE and subtransactions.  If a CREATE statement creates a row in a catalog during a subtransaction, but that subtransaction gets rolled back to the savepoint, and other things happen which trigger page pruning on the catalog page, and the original transaction (perhaps in a new subtransaction) then does another CREATE operation, a new row can get inserted into the same catalog at the same TID.  During logical decoding, this can trigger an Assertion, and in non-assert builds, could silently corrupt the decoder's catalog visibility, which could cause it to produce incorrect output (wrong column mappings, etc.)

This bug appears to go all the way back to 9.4 where logical replication was introduced.

Arseny Sher hit the cmax variant of this exact bug, and Alvaro fixed the cmax version of it, but appears not to have seen the danger for cmin also existed, rather writing the comment, "if so it must have the same cmin."  (commit 350cdcd5e6d, 2019)

Creating a short deterministic reproducer is difficult, because the catalog table must be set up such that page pruning will happen.  (I have a 24K line reproducer, which seems too big to attach for the list.)  A fuzz tester is attached instead.

The attached patch fixes the problem without fixing the fundamental architectural shortcut the code is taking.  The comment in xl_heap_new_cid ("store toplevel xid so we don't have to merge cids from different transactions") indicates an intentional design choice.  A more complete fix could also be considered, but is not included here.

--

Mark Dilger

Re: Bug in logical decoding with DDL and subtransactions

От:
kid <lucian1412@outlook.com>
Дата:

On 4/30/2026 12:59 PM, Mark Dilger wrote:
> There is a bug in logical decoding with CREATE and subtransactions.  
> If a CREATE statement creates a row in a catalog during a 
> subtransaction, but that subtransaction gets rolled back to the 
> savepoint, and other things happen which trigger page pruning on the 
> catalog page, and the original transaction (perhaps in a new 
> subtransaction) then does another CREATE operation, a new row can get 
> inserted into the same catalog at the same TID.
Hi Mark,

Bug #19555 [1] appears to be another instance of this issue: an
assertion failure in ReorderBufferBuildTupleCidHash
("ent->cmin == change->data.tuplecid.cmin") when DDL runs inside a
savepoint that is then rolled back.  I reproduced it on REL_19_STABLE
(64542957b44) using the script from the bug report, and on current
master (36f7330b8b2) with a slightly different table shape:

     CREATE TABLE zz(data int, pad1 text, pad2 int, pad3 text);
     BEGIN;
     SAVEPOINT a;
     ALTER TABLE zz ALTER COLUMN data TYPE text;
     ROLLBACK TO SAVEPOINT a;
     ALTER TABLE zz ALTER COLUMN data TYPE bigint;
     COMMIT;
     SELECT data FROM pg_logical_slot_get_changes('regression_slot',
         NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');

The crash is layout-dependent: it needs on-access pruning to free the
aborted subtransaction's line pointer and a later catalog insert to
reuse it, so the catalog churn from the bug report's prelude matters.
With the 4-column table above it crashed on the first attempt.

I traced the WAL and can confirm your diagnosis:

- the rolled-back subtransaction's NEW_CID records stay queued under
   the top-level xid, and ReorderBufferAbort() never removes them;
- its HOT-updated catalog tuple becomes a dead heap-only tuple, which
   on-access pruning marks LP_UNUSED (no vacuum needed);
- the next ALTER's catalog insert reuses that TID, producing a second
   NEW_CID for the same (relfilelocator, tid) with a different cmin.

With your patch applied to master, the previously-crashing case passes
(20 iterations, no crash, no "cmin mismatch" warning), and the
test_decoding regression suite passes.

A few review comments:

1. The patch fixes the crashing path, but the mirror case remains: a
    catalog tuple *deleted* only by an aborted subtransaction keeps a
    stale cmax in the hash, so historic snapshots could wrongly treat a
    live tuple as deleted.  Did you consider removing the aborted
    subtransaction's tuplecid entries at ReorderBufferAbort() time,
    instead of resolving conflicts lazily at hash-build time?  That
    would cover both cases and avoid the TransactionIdDidAbort() clog
    lookup during decode.  I'm happy to write that variant if you think
    it is worth comparing.

2. For the "neither subtransaction aborted" branch, would an Assert
    be better than elog(WARNING)?  A warning from the decoding path
    seems odd, and if the case is truly impossible an assertion would
    document that.

3. The patch has no regression test.  The scenario above is the
    smallest reproducer I know of, though its layout dependence makes
    it fragile for the test suite.  Any suggestions for making it
    deterministic?

It would be great to get this fixed for 19: the bug report shows it
is being hit by fuzzers in the wild, and the cmax half of this
problem was already fixed in 8c67d29fd51 back in 2019.

[1] 
https://www.postgresql.org/message-id/19555-3c700f40a13045cd@postgresql.org

Thanks,



Bug in logical decoding with DDL and subtransactions

Hi Mark,

Here is v3.  The only change from v2 is in the regression test: its
scratch database is now named regression_tuplecid instead of
tuplecid_db.  cfbot's autoconf task compiles with
-DENFORCE_REGRESSION_TEST_NAME_RESTRICTIONS, and the old name tripped
the "should have names including regression" WARNING, which broke the
expected output on that task (all other cfbot tasks were green).
No code changes.

Re-verified under that exact flag locally
(CPPFLAGS=-DENFORCE_REGRESSION_TEST_NAME_RESTRICTIONS): the
test_decoding suite passes, 21 regression + 14 isolation tests.

Thanks,
Bingshuai Li

Re: Bug in logical decoding with DDL and subtransactions

От:
Alexander Lakhin <exclusion@gmail.com>
Дата:
Hello hackers,

27.08.2026 10:38, Bingshuai Li wrote:
A brief ping on v4 before PG20-2 starts.  The latest CFBot run is
green on all enabled jobs:

https://github.com/postgres/postgres-cfbot/actions/runs/32910623105/attempts/1
....
PostgreSQL 19 is currently at Beta 3.  Should BUG #19555 also be
tracked as a PostgreSQL 19 open item?

CF entry:
https://commitfest.postgresql.org/patch/7137/

FWIW, buildfarm animal prion produced a couple of failures recently due to
that assertion triggered, [1], [2]:
TRAP: failed Assert("ent->cmin == change->data.tuplecid.cmin"), File: "/home/ec2-user/bf/root/HEAD/pgsql.build/../pgsql/src/backend/replication/logical/reorderbuffer.c", Line: 1890, PID: 1211632
...
2026-09-15 21:58:17.665 UTC [1211335:63] LOG:  00000: client backend (PID 1211632) was terminated by signal 6: Aborted
2026-09-15 21:58:17.665 UTC [1211335:64] DETAIL:  Failed process was running: SELECT data FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');

[1] https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=prion&dt=2026-09-15%2021%3A39%3A57
[2] https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=prion&dt=2026-09-15%2022%3A13%3A04

Best regards,
Alexander

Re: Bug in logical decoding with DDL and subtransactions

От:
Bingshuai Li <lucian1412@outlook.com>
Дата:
Hi Alexander,

Thanks for the data point.  These failures are exactly the assertion
analyzed in this thread, and the failing statement is the decode call
right after the ddl test's own "DDL in aborted subtransactions"
section (contrib/test_decoding/sql/ddl.sql):

    CREATE TABLE tr_sub_ddl(data int);
    BEGIN;
    SAVEPOINT a;
    ALTER TABLE tr_sub_ddl ALTER COLUMN data TYPE text;
    INSERT INTO tr_sub_ddl VALUES ('blah-blah');
    ROLLBACK TO SAVEPOINT a;
    ALTER TABLE tr_sub_ddl ALTER COLUMN data TYPE bigint;
    INSERT INTO tr_sub_ddl VALUES(43);
    COMMIT;

That is the same shape as the BUG #19555 reproducer, and the lines
missing from the ddl.out diff are everything after the backend died.

The failure is inherently layout-dependent: it needs on-access
pruning to free the rolled-back subtransaction's catalog line
pointer and a later catalog insert to reuse that tid.  Presumably
prion's force-release configuration (RELCACHE_FORCE_RELEASE,
CATCACHE_FORCE_RELEASE) makes that far more likely than on other
animals -- two hits in one evening supports that.

The v4 patch posted on 2026-08-15 [1] fixes exactly this path: it
removes the aborted subtransaction's tuplecid entries in
ReorderBufferAbort(), so no stale (relfilelocator, tid) mapping
remains to collide with a reused tid.  The regression test added by
v4 reproduces this crash within a handful of iterations on
unpatched assert builds and always passes with the patch.

I re-checked v4 against current master (be00f041a33) today: it
still applies cleanly, and no upstream commit has touched the
tuplecid code paths since it was posted, so the verification matrix
from the v4 mail (master and REL_19_STABLE, assert and non-assert,
both build systems) still stands.

With the buildfarm now red on HEAD and PostgreSQL 19 GA
approaching, could a committer please take a look at v4?  The two
points where I would most appreciate judgement are unchanged from
my August 27 mail: the restart_lsn invariant (section 2 of the v4
mail), and whether the O(N) abort-time cleanup is acceptable to
backpatch.  I also believe this strengthens the case for tracking
BUG #19555 as a PostgreSQL 19 open item.  I'm happy to prepare a
REL_19_STABLE version of the patch if that would help.

[1] https://www.postgresql.org/message-id/SY8P300MB0570D533D4F6B47B804C7D57C6D92%40SY8P300MB0570.AUSP300.PROD.OUTLOOK.COM

Thanks,
Bingshuai Li

Re: Bug in logical decoding with DDL and subtransactions

От:
"alvherre@kurilemu.de" <alvherre@kurilemu.de>
Дата:
On 2026-Sep-17, Bingshuai Li wrote:

> With the buildfarm now red on HEAD and PostgreSQL 19 GA
> approaching, could a committer please take a look at v4?  The two
> points where I would most appreciate judgement are unchanged from
> my August 27 mail: the restart_lsn invariant (section 2 of the v4
> mail), and whether the O(N) abort-time cleanup is acceptable to
> backpatch.  I also believe this strengthens the case for tracking
> BUG #19555 as a PostgreSQL 19 open item.

What's the reason to consider this as a worse problem in 19 than in
previous releases?  In my mind it's pretty clear that this bug needs to
be fixed in all stable branches.  Moreover, I think the real deadline
here is the next set of minors to be released in November, rather than
the 19.0 release.  The November minors would also include 19.1.

> I'm happy to prepare a REL_19_STABLE version of the patch if that
> would help.

If the proposed patch has any conflicts when applied on any previous
branches, then by all means please do provide backpatches as
appropriate.  However, if the same patch applies cleanly or only has
trivial conflicts, then there's no need.  (I see there's a trivial
conflict in 18's test schedule files for instance, for which IMO you
don't need to provide a patch.  Didn't try further back.)

The patch does change the layout of ReorderBufferChange, which is
apparently an exported struct, so some analysis on whether that can
break anything would also be useful.  It might be innocuous, if there
are no external users, but better make sure ...

--- /tmp/ReorderBufferChange.unpatched  2026-09-17 13:09:09.517276936 +0200
+++ /tmp/ReorderBufferChange.patched    2026-09-17 13:09:35.505580268 +0200
@@ -37,27 +37,29 @@
        CommandId          command_id;           /*    32     4 */
        struct {
            RelFileLocator locator;          /*    32    12 */
            ItemPointerData tid __attribute__((__aligned__(2))); /*    44     6 */
 
            /* XXX 2 bytes hole, try to pack */
 
            CommandId  cmin;                 /*    52     4 */
            CommandId  cmax;                 /*    56     4 */
            CommandId  combocid;             /*    60     4 */
-       } __attribute__((__aligned__(4))) tuplecid __attribute__((__aligned__(4)));  /*    32    32 */
+           /* --- cacheline 1 boundary (64 bytes) --- */
+           TransactionId subxid;            /*    64     4 */
+       } __attribute__((__aligned__(4))) tuplecid __attribute__((__aligned__(4)));  /*    32    36 */
        struct {
            uint32     ninvalidations;       /*    32     4 */
 
            /* XXX 4 bytes hole, try to pack */
 
            SharedInvalidationMessage * invalidations; /*    40     8 */
        } inval;                                 /*    32    16 */
-   } data __attribute__((__aligned__(8)));          /*    32    32 */
-   /* --- cacheline 1 boundary (64 bytes) --- */
-   dlist_node                 node;                 /*    64    16 */
+   } data __attribute__((__aligned__(8)));          /*    32    40 */
+   /* --- cacheline 1 boundary (64 bytes) was 8 bytes ago --- */
+   dlist_node                 node;                 /*    72    16 */
 
-   /* size: 80, cachelines: 2, members: 6 */
-   /* sum members: 70, holes: 2, sum holes: 10 */
+   /* size: 88, cachelines: 2, members: 6 */
+   /* sum members: 78, holes: 2, sum holes: 10 */
    /* forced alignments: 1, forced holes: 1, sum forced holes: 6 */
-   /* last cacheline: 16 bytes */
+   /* last cacheline: 24 bytes */
 } __attribute__((__aligned__(8)));

-- 
Álvaro Herrera               48°01'N 7°57'E  —  https://www.EnterpriseDB.com/
"Debido a que la velocidad de la luz es mucho mayor que la del sonido,
 algunas personas nos parecen brillantes un minuto antes
 de escuchar las pelotudeces que dicen." (Roberto Fontanarrosa)


Re: Bug in logical decoding with DDL and subtransactions

От:
Bingshuai Li <lucian1412@outlook.com>
Дата:
Hi Álvaro,

Thanks for picking this up.

> What's the reason to consider this as a worse problem in 19 than in
> previous releases?

There isn't one -- I asked because 19 GA was approaching and the bug
was reported against 19.  Fixing it in all stable branches for the
November minors sounds right.

> If the proposed patch has any conflicts when applied on any previous
> branches, then by all means please do provide backpatches as
> appropriate.

I ran v4 across all supported branches (--enable-cassert build plus
the full test_decoding suite on each):

  branch  apply                            tests (regress+isolation)
  ------  -------------------------------  -------------------------
  master  clean (be00f041a33)              21+15, CFBot green
  19      clean (a203d201900)              21+15
  18      trivial test-list conflicts      20+14
  17      branch version attached          20+14
  16      branch version attached          20+14
  15      branch version attached          20+14
  14      branch version attached          20+13

(The counts follow each branch's existing test_decoding suite;
tuplecid and tuplecid_restart pass everywhere.)

On 18 the conflicts are exactly the trivial ones you saw: master's
test lists mention repack and parallel_session_origin, which don't
exist there.  All code applies cleanly, so per your advice I have not
prepared an 18 version.

The attached branch versions differ from v4 as follows:

- 17, 16: only the test-list context, plus one rename -- the cleanup
  calls ReorderBufferReturnChange(), the pre-PG18 name of
  ReorderBufferFreeChange() (renamed by ac4494646da; same 3-argument
  signature and body).  The 17 and 16 versions differ from each other
  only in the test-list context, too.
- 15, 14: additionally drop the meson.build hunk (meson arrived in
  16) and use the pre-PG16 names: RelFileNode, xlrec->target_node,
  and txn->toptxn instead of rbtxn_get_toptxn().  The 14 version also
  trims the new test's expected output, because 14's psql prints only
  the last result of a multi-statement string; the decode work is
  unchanged, so the test exercises the bug just the same.

rbtxn_is_known_subxact() exists natively in all of these branches, so
the fix itself is identical everywhere.

> The patch does change the layout of ReorderBufferChange, which is
> apparently an exported struct, so some analysis on whether that can
> break anything would also be useful.

I checked who can observe the layout change:

- the tuplecid variant is only ever accessed from reorderbuffer.c
  itself (no data.tuplecid users anywhere else in tree);
- only reorderbuffer.c touches change->node, and only reorderbuffer.c
  allocates, frees or serializes ReorderBufferChange (the spill files
  embed the struct, but they are transient within a single decoding
  session);
- output plugins (pgoutput, pgrepack, test_decoding, and external
  ones using the same callback API) only read change->action, ->txn,
  ->data.tp.{old,new}tuple and ->data.truncate.*, all at offsets
  unchanged by the patch: the union only grows at the tail of the
  tuplecid variant, and the struct stays within two cachelines, as
  your pahole output shows.

So the layout change is innocuous for any plugin I can think of.

There is one more exported-API change next to it:
ReorderBufferAddNewTupleCids() gains a subxid parameter.  Its only
caller is the NEW_CID decode path in snapbuild.c; output plugins have
no reason to call it.  If you'd rather keep the exported signature
stable on the back branches, I can keep the old one as a wrapper
passing InvalidTransactionId -- it is about five lines.

The part of v4 where I would still most value a second opinion is the
restart_lsn invariant in section 2 of the v4 mail (why the skipped
cleanup on the restart path cannot reach the tuplecid hash); I believe
everything else is covered above.

Thanks,
Bingshuai Li

Re: Bug in logical decoding with DDL and subtransactions

От:
Bingshuai Li <lucian1412@outlook.com>
Дата:
Вложения:
Hi Álvaro,

Apologies -- the branch versions did not make it onto that mail.
Here they are.

Thanks,
Bingshuai Li

Re: Bug in logical decoding with DDL and subtransactions

От:
Bingshuai Li <lucian1412@outlook.com>
Дата:
Вложения:
Hi,

Housekeeping for the commitfest entry: CFBot picked up the
REL_14_STABLE back-branch version from my previous mail and now
reports "needs rebase" against master.  Re-attaching the master
version of v4 (unchanged; still applies cleanly to current master
e1d8f81d496), so the entry points at the right patch again.  The
branch versions from my previous mail are for the back branches
only.

Thanks,
Bingshuai Li

RE: Bug in logical decoding with DDL and subtransactions

От:
"Hayato Kuroda (Fujitsu)" <kuroda.hayato@fujitsu.com>
Дата:
Hi Bingshuai,

Thanks for working on it. Confirmed it's a real issue.

I've read your patch and one comment:
The path you added might be redundant if the top-level transaction is being aborted,
right? Can we export the cleanup part outside ReorderBufferAbort()? It does the
actual task only if needed.

Best regards,
Hayato Kuroda
FUJITSU LIMITED



Re: Bug in logical decoding with DDL and subtransactions

От:
Tom Lane <tgl@sss.pgh.pa.us>
Дата:
Bingshuai Li  writes:
>> What's the reason to consider this as a worse problem in 19 than in
>> previous releases?

> There isn't one -- I asked because 19 GA was approaching and the bug
> was reported against 19.  Fixing it in all stable branches for the
> November minors sounds right.

While it's not any worse for v19 than older branches, it would be sad
if this isn't fixed for v19 GA, since we have that scheduled ahead of
the November minors.

Also, of late the test_decoding/sql/ddl.sql test has been failing
often enough in the buildfarm to be quite annoying.  So I'd like to
see this fixed sooner not later.  (It's not very clear to me why
we are suddenly able to see this old bug in the regression tests.
The part of ddl.sql that's crashing hasn't changed in years, but
BF member "prion" has failed multiple times in the past two weeks.
Do we have a theory about that that's better than hand-wavy
"some change in timing"?)

			regards, tom lane


Re: Bug in logical decoding with DDL and subtransactions

От:
Alexander Lakhin <exclusion@gmail.com>
Дата:
Hello Tom,

29.09.2026 21:31, Tom Lane wrote:
Bingshuai Li <lucian1412@outlook.com> writes:
What's the reason to consider this as a worse problem in 19 than in
previous releases?
There isn't one -- I asked because 19 GA was approaching and the bug
was reported against 19.  Fixing it in all stable branches for the
November minors sounds right.
While it's not any worse for v19 than older branches, it would be sad
if this isn't fixed for v19 GA, since we have that scheduled ahead of
the November minors.

Also, of late the test_decoding/sql/ddl.sql test has been failing
often enough in the buildfarm to be quite annoying.  So I'd like to
see this fixed sooner not later.  (It's not very clear to me why
we are suddenly able to see this old bug in the regression tests.
The part of ddl.sql that's crashing hasn't changed in years, but
BF member "prion" has failed multiple times in the past two weeks.
Do we have a theory about that that's better than hand-wavy
"some change in timing"?)

Besides prion, skink managed to trigger that assert too: [1]. It didn't run
tests from 2026-09-08 to 2026-09-25 [2], and never failed this test before,
so I guess the change which affected the test was on Sep 15: a4b26b8f7
(the very first prion's failure includes this commit [3]). I can reproduce
this failure under Valgrind locally, but not reliably enough to bisect it
quickly.

[1] https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=skink&dt=2026-09-28%2003%3A25%3A19
[2] https://buildfarm.postgresql.org/cgi-bin/show_history.pl?nm=skink&br=master
[3] https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=prion&dt=2026-09-15%2021%3A39%3A57

Best regards,
Alexander

Re: Bug in logical decoding with DDL and subtransactions

От:
Tom Lane <tgl@sss.pgh.pa.us>
Дата:
Alexander Lakhin  writes:
> 29.09.2026 21:31, Tom Lane wrote:
>> Also, of late the test_decoding/sql/ddl.sql test has been failing
>> often enough in the buildfarm to be quite annoying.  So I'd like to
>> see this fixed sooner not later.  (It's not very clear to me why
>> we are suddenly able to see this old bug in the regression tests.
>> The part of ddl.sql that's crashing hasn't changed in years, but
>> BF member "prion" has failed multiple times in the past two weeks.
>> Do we have a theory about that that's better than hand-wavy
>> "some change in timing"?)

> Besides prion, skink managed to trigger that assert too: [1]. It didn't run
> tests from 2026-09-08 to 2026-09-25 [2], and never failed this test before,
> so I guess the change which affected the test was on Sep 15: a4b26b8f7
> (the very first prion's failure includes this commit [3]).

I doubt that theory, because a4b26b8f7 was "Revert UPDATE/DELETE FOR
PORTION OF", so to suppose that it caused this failure you'd have to
explain why we didn't see it before any of that went in.

Assuming that there is an identifiable commit that triggered this,
it must certainly be no later than 862092932 (the latest commit seen
by prion's first failure of this sort).  But it could plausibly have
been anything within several days before that.  ddl.sql itself wasn't
touched for nearly a month before that, so I'm inclined to bet that
the relevant change was somewhere in our code not in the test itself.

Given that the problem is expensive to reproduce, I doubt that
bisecting to identify this still-hypothetical commit is worth the
trouble; I was just curious to know if anyone already understood the
connection.  Now, if it turns out that Bingshuai's patch doesn't make
prion happy, then we'll need to dig deeper.

			regards, tom lane


Re: Bug in logical decoding with DDL and subtransactions

От:
Michael Paquier <michael@paquier.xyz>
Дата:
Вложения:
On Tue, Sep 29, 2026 at 05:17:19PM -0400, Tom Lane wrote:
> Given that the problem is expensive to reproduce, I doubt that
> bisecting to identify this still-hypothetical commit is worth the
> trouble; I was just curious to know if anyone already understood the
> connection.  Now, if it turns out that Bingshuai's patch doesn't make
> prion happy, then we'll need to dig deeper.

It's not that hard to reach.  If I run three check-world builds in
parallel to load my laptop CPU (say HEAD, v19 and v18 with a
worktree), HEAD is able to fail rather reliably like 30%~40% of the
time, on this test.  The problem is very easy to reach for the last
two weeks.
--
Michael

Re: Bug in logical decoding with DDL and subtransactions

От:
Michael Paquier <michael@paquier.xyz>
Дата:
Вложения:
On Wed, Sep 30, 2026 at 12:05:09PM +0900, Michael Paquier wrote:
> On Tue, Sep 29, 2026 at 05:17:19PM -0400, Tom Lane wrote:
>> Given that the problem is expensive to reproduce, I doubt that
>> bisecting to identify this still-hypothetical commit is worth the
>> trouble; I was just curious to know if anyone already understood the
>> connection.  Now, if it turns out that Bingshuai's patch doesn't make
>> prion happy, then we'll need to dig deeper.
> 
> It's not that hard to reach.  If I run three check-world builds in
> parallel to load my laptop CPU (say HEAD, v19 and v18 with a
> worktree), HEAD is able to fail rather reliably like 30%~40% of the
> time, on this test.  The problem is very easy to reach for the last
> two weeks.

There is cheap way to reproduce the issue, as of two
pg_log_standby_snapshot() in ddl.sql:
@@ -231,6 +231,7 @@ ROLLBACK TO SAVEPOINT b;
 INSERT INTO tr_sub(path) VALUES ('3-top-2-#2');
 COMMIT;
 
+SELECT pg_log_standby_snapshot() IS NOT NULL;
 SELECT data FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
 
 -- test whether a known, but not yet logged toplevel xact, followed by a
@@ -250,6 +251,7 @@ INSERT INTO tr_sub(path) VALUES ('5-top-1-#1');
 COMMIT;
 
 
+SELECT pg_log_standby_snapshot() IS NOT NULL;
 SELECT data FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
 
 -- check that DDL in aborted subtransactions handled correctly

See also the attached.  This stuff reproduces quickly the assertion
failure.
--
Michael

RE: Bug in logical decoding with DDL and subtransactions

От:
Bingshuai Li <lucian1412@outlook.com>
Дата:
Вложения:
Hi Hayato, Hi Tom,

Thanks, Hayato, for reviewing and confirming the issue, and Tom for
following up.  Attached is v5, with the cleanup moved out of
ReorderBufferAbort() and a test for nested subtransaction rollback.

1. Hayato's comment

> The path you added might be redundant if the top-level transaction is
> being aborted, right? Can we export the cleanup part outside
> ReorderBufferAbort()? It does the actual task only if needed.

Agreed.  The cleanup loop is now in
ReorderBufferCleanupSubTxnTupleCids(), and ReorderBufferAbort() is back
to its upstream implementation.  DecodeAbort() calls the helper for
each aborted xid before removing its transaction state, passing the
abort record's primary xid as well.

The helper uses the known toplevel of the xid being cleaned.  If that
toplevel's xid equals the primary xid, the whole transaction is being
aborted, so it returns without scanning the tuplecid list;
ReorderBufferCleanupTXN() will free it.  Otherwise it removes the
tuplecid entries written by that subtransaction.

The primary xid's own association cannot be used to decide whether
cleanup is needed.  An outer subtransaction that wrote no WAL of its
own can have no known association when its abort is decoded: the abort
record is written after entering TRANS_ABORT, so
IsSubxactTopXidLogPending() does not attach the toplevel xid.  Released
inner subtransactions listed in that abort record can still have known
associations, and their tuplecids must be removed from the surviving
toplevel's list.

A new isolation test, tuplecid_nested, covers that shape: the toplevel
writes WAL first, an inner subtransaction inserts into a user catalog
table and is RELEASEd, and the outer subtransaction (no WAL of its own)
is then rolled back; using the page-fill and vacuum recipe of
tuplecid_restart, the toplevel's later insert deterministically reuses
the aborted subtransaction's line pointer.  With cleanup gated on the
primary xid's known association, the test dies with the original cmin
assertion; with the attached version it passes.  (The other test files
are unchanged from v4.)

2. Behavior vs v4, scenario by scenario

- Partial rollback, aborted subxact wrote its own WAL (the BUG #19555 /
  ddl.sql shape): cleanup runs, as in v4.  The tuplecid regression test
  still trips the original assertion without the fix and passes with it.
- Partial rollback, aborted outer subxact without own WAL, released
  inner subxact (the nested shape): the inner subxact's entries are
  cleaned, as in v4, even if the outer subxact's association is unknown.
- Toplevel abort: no scan at all (early return), and
  ReorderBufferCleanupTXN() frees the whole list.
- Association of the xid being cleaned unknown (a decoding pass that
  started mid-transaction): cleanup skipped, as in v4; the restart-point
  invariant from my v4 mail still applies unchanged (a pass that
  output-decodes the toplevel commit has replayed the subtransaction's
  first record and knows the association; later passes skip the commit
  entirely), and tuplecid_restart still passes.
- Two-phase aborts and ReorderBufferAbortOld() are untouched.

Compared with v4, this adds one exported helper,
ReorderBufferCleanupSubTxnTupleCids().  ReorderBufferAbort() retains its
existing signature.  The tuplecid subxid field and the additional subxid
argument to ReorderBufferAddNewTupleCids() are unchanged from v4.

3. Verification matrix (all --enable-cassert --enable-debug unless
noted; make check in contrib/test_decoding):

ENFORCE below denotes a build with
ENFORCE_REGRESSION_TEST_NAME_RESTRICTIONS defined.

  branch          base          apply                          regress + isolation
  master          6a93535798a   clean (also non-assert and
                                ENFORCE builds)                 21 + 16
  REL_19_STABLE   ab274a1e966   clean                          21 + 16
  REL_18_STABLE   ea24eadda01   only the known trivial
                                test-list conflicts             20 + 15
  REL_17_STABLE   583b414e511   branch version attached         20 + 15
  REL_16_STABLE   b8d50e14252   branch version attached         20 + 15
  REL_15_STABLE   38e07ce9847   branch version attached         20 + 15
  REL_14_STABLE   42ebc601fec   branch version attached         20 + 14

tuplecid, tuplecid_restart and tuplecid_nested pass everywhere.

4. Tom's question about the recent buildfarm failures

I have some possible leads, but have not isolated the change that made
the failure more frequent.  In the prion history I inspected, the first
failure with this signature was on September 15 at 21:39, at
862092932c9; the preceding green run was at 09:13, at ff39a858b984.
There are seven commits between those revisions.

Alexander's candidate a4b26b8f7 removes 30 lines of ddl.sql before the
tr_sub_ddl section, although the failing section itself is unchanged.
Another commit in that interval, ddce1da5b1b, adds a pg_opclass.dat
entry.  Both could affect catalog layout, on which this bug's TID
collision depends.  That is a possible explanation for why the revert
could matter, but I have not established that either change caused the
increase in failures.

The failures are intermittent on prion and skink.  Locally, 50 runs at
prion's first failing revision with the same configure flags produced
no crashes.  Michael's report of frequent failures under concurrent
check-world builds provides a useful lead about the role of the
environment, but these observations do not rule out a recent code
change as the trigger.

Thanks to Michael for the reproducer.  I also tried it, adding two
pg_log_standby_snapshot() calls to ddl.sql, under CPU load:

- An unfixed tree at 862092932c9, built with cassert and
  RELCACHE_FORCE_RELEASE, CATCACHE_FORCE_RELEASE and
  REALLOCATE_BITMAPSETS, hit the original cmin assertion in all five
  runs, at the tr_sub_ddl get_changes call.
- The attached v5 on 6a93535798a, built with cassert and debug but
  without those three defines, completed ddl.sql without the assertion
  in all five runs.  make check still reported a failure because the
  expected output lacked the two added queries' output; the remaining
  decoded output matched.

Those runs used different baselines and build configurations, so they
do not isolate the patch's effect.  They show that I can reproduce the
reported failure and that the v5 build completes the reproducer.  The
nested test's failure with the association-gated variant and success
with v5 provide separate evidence for the nested rollback fix.

The patch removes the aborted subtransaction's tuplecids before the
surviving toplevel commit is processed.  If prion or skink still hits
the assertion after the fix, I'll follow up with that evidence.

Does this address your comment, Hayato?  Happy to adjust further.

Thanks,
Bingshuai Li

RE: Bug in logical decoding with DDL and subtransactions

От:
Bingshuai Li <lucian1412@outlook.com>
Дата:
Вложения:
For cfbot, reattaching v5 for master only.  The REL_* attachments in my
previous message are alternative backpatch versions, not a patch
series.  Cfbot applied the master patch successfully, then tried to
apply the REL_14_STABLE version on top of it and reported conflicts.

There are no code changes in this attachment.

Thanks,
Bingshuai Li

Re: Bug in logical decoding with DDL and subtransactions

От:
Zhijie Hou <houzhijie22@gmail.com>
Дата:
Hi,

On Wed, Sep 30, 2026 at 5:17 AM Tom Lane  wrote:
>
> Alexander Lakhin  writes:
> > 29.09.2026 21:31, Tom Lane wrote:
> >> Also, of late the test_decoding/sql/ddl.sql test has been failing
> >> often enough in the buildfarm to be quite annoying.  So I'd like to
> >> see this fixed sooner not later.  (It's not very clear to me why
> >> we are suddenly able to see this old bug in the regression tests.
> >> The part of ddl.sql that's crashing hasn't changed in years, but
> >> BF member "prion" has failed multiple times in the past two weeks.
> >> Do we have a theory about that that's better than hand-wavy
> >> "some change in timing"?)
>
> > Besides prion, skink managed to trigger that assert too: [1]. It didn't run
> > tests from 2026-09-08 to 2026-09-25 [2], and never failed this test before,
> > so I guess the change which affected the test was on Sep 15: a4b26b8f7
> > (the very first prion's failure includes this commit [3]).
>
> I doubt that theory, because a4b26b8f7 was "Revert UPDATE/DELETE FOR
> PORTION OF", so to suppose that it caused this failure you'd have to
> explain why we didn't see it before any of that went in.

I experimented with this while reading the patch, and I think Lakhin's instinct
was actually right: the onset commit is a4b26b8f7. The reason being that this
commit changes the layout of the pg_attribute page. For the assert to fire, a
catalog page needs three things to satisfied: (1) the aborted subtransaction's
dead tuple must be prunable to LP_UNUSED, (2) the page must be full enough to
trigger on-access pruning during the second ALTER, and (3) a later catalog
insert in the same top-level transaction must reuse that line pointer with a
different cmin.

Since a4b26b8f7 removed the 36-line FOR PORTION OF section from ddl.sql (a
WITHOUT OVERLAPS pkey table plus DML, pg_attribute page change), the
pg_attribute
page that receives tr_sub_ddl's attribute row now fills past the
on-access-prune threshold during the failing section's own catalog churn, so
the prune fires and the TID is reused for a new row.

As for why it didn't fail before FOR PORTION OF went in: IIUC, it's also due to
the pg_attribute layout, the old layout coincidentally did not satisfy the
condition to trigger the page prune in the test. But the pg_attribute layout
keeps changing, and other related commits (like the new system view
pg_stat_kind_info, the new system catalog row
pg_subscription.subconflictlogrelid, ...) keep shifting it further, which could
be why we're seeing the failure on HEAD now.

As for why it only fails intermittently: Michael's test shows that one factor
in reproducing it is the standby snapshot WAL record, which helps advance the
replication slot's catalog_xmin past the page's pd_prune_xid (pg_attribute's
page in this case), making the TID where the old aborted row lived prunable so
it gets reused by the second ALTER TABLE. While the logging of the standby
snapshot by the bgwriter is timing-dependent.

Best Regards,
Zhijie Hou


RE: Bug in logical decoding with DDL and subtransactions

От:
"Hayato Kuroda (Fujitsu)" <kuroda.hayato@fujitsu.com>
Дата:
Вложения:
Hi,

Thanks for updating the patch.
My idea was to call the cleanup function only once. A cleanup function can accept
a list of sub transactions, and checks them while iterating the tuplecids of the
top transaction. Per my understanding we can use the binary search because the list
of sub transactions are sorted by the logical XID. Attached .txt implements the idea.

> For cfbot, reattaching v5 for master only.  The REL_* attachments in my
> previous message are alternative backpatch versions, not a patch
> series.  Cfbot applied the master patch successfully, then tried to
> apply the REL_14_STABLE version on top of it and reported conflicts.

TIPS: attaching .txt is a known workaround [1].


[1]: https://wiki.postgresql.org/wiki/Cfbot

Best regards,
Hayato Kuroda
FUJITSU LIMITED

Re: Bug in logical decoding with DDL and subtransactions

От:
Zhijie Hou <houzhijie22@gmail.com>
Дата:
Hi,

On Mon, Oct 5, 2026 at 6:13 PM Hayato Kuroda (Fujitsu)
 wrote:
>
> Hi,
>
> Thanks for updating the patch.
> My idea was to call the cleanup function only once. A cleanup function can accept
> a list of sub transactions, and checks them while iterating the tuplecids of the
> top transaction. Per my understanding we can use the binary search because the list
> of sub transactions are sorted by the logical XID. Attached .txt implements the idea.

I personally think your version looks better. But I have few comments for the
diff:

1.

for (int i = 0; i < nsubxacts; i++)
{
txn = ReorderBufferTXNByXid(rb, subxacts[i], false, NULL,
InvalidXLogRecPtr, false);
if (txn != NULL && rbtxn_is_known_subxact(txn))
break;

I'm curious whether the rbtxn_is_known_subxact() check is necessary here, it
gives me the impression that it's possible for an XID in the subxacts array to
be considered as a top-level transaction.

2.

/*
* An abort record's subxacts are children that previously subcommitted
* into the aborting transaction.  AtSubCommit_childXids() preserves their
* logical XID order, so xidLogicalComparator can safely compare them.
*/

I think this comment would be better placed at the caller.

--

And I also reviewed the corresponding part in the original patch, and have a
few comments:

3.

> * Note that we must not try to decide that from the primary xid's
> * own association instead: an abort record is written once the
> * subtransaction is already in TRANS_ABORT, so it never carries
> * the toplevel xid in its header (IsSubxactTopXidLogPending()
> * requires IsTransactionState()), and an outer subtransaction
> * that never wrote WAL of its own -- e.g. a savepoint that only
> * wraps other savepoints -- can therefore have no association at
> * all, while the released inner subtransactions it rolls back do
> * have one and their tuplecids still need to be removed.


As a reader, it wasn't initially clear to me what this comment is trying to
describe, since the association check is inside the cleanup function, so I
think it's better moved there.

It's also not clear to me what "try to decide that" refers to. I think it might
be saying that even if the primary XID's entry doesn't record the toplevel
transaction, we still need to do the cleanup by getting that info from another
subxact entry in the subxacts list. If so, we'd better make that explicit.

4.

 * If this pass does not know the association between the aborting
 * subtransaction and its toplevel, there is nothing we can clean up here, and
 * that's fine: such a pass must have started after the subtransaction's first
 * (toplevel-xid-bearing) WAL record.  A pass that will output-decode the
 * toplevel commit cannot have started that late: a slot's restart point
 * cannot advance past the oldest in-progress transaction
 * (SnapBuildProcessRunningXacts()), so the commit-decoding pass has replayed
 * the record that established the association.  Conversely, once the restart
 * point has advanced past that record, the commit has already been consumed
 * by an earlier pass and is skipped here via SnapBuildXactNeedsSkip(), so
 * stale tuplecid entries left behind in that case are dropped along with the
 * transaction state without ever reaching ReorderBufferBuildTupleCidHash().

It's not clear to me whether the comment is referring to a case that can
actually be hit. It sounds like it can happen and we just skip the cleanup, if
so, could you share an example so I can test it? If it's actually unreachable,
the comment shall explain it from that angle.

Best Regards,
Zhijie Hou


Re: Bug in logical decoding with DDL and subtransactions

От:
"alvherre@kurilemu.de" <alvherre@kurilemu.de>
Дата:
Вложения:
Hi,

Here's v6 of the proposed series, to appease cfbot.  I have not reviewed
it.

Thanks,

-- 
Álvaro Herrera         PostgreSQL Developer  —  https://www.EnterpriseDB.com/
Y una voz del caos me habló y me dijo
"Sonríe y sé feliz, podría ser peor".
Y sonreí. Y fui feliz.
Y fue peor.

Re: Bug in logical decoding with DDL and subtransactions

От:
"alvherre@kurilemu.de" <alvherre@kurilemu.de>
Дата:
Hello

I think the tuplecid.sql test is rather brute-force-ish, and I'm not
sure we need it.  To verify that I ran the tests with it and without it,
and compared the difference in the HTML coverage report.  I see no
additional extra lines marked as covered with the tuplecid.sql left in
place, which I take to mean to support my hypothesis.  I suggest we
throw it away and keep only the two isolation tests.


-- 
Álvaro Herrera         PostgreSQL Developer  —  https://www.EnterpriseDB.com/
"Las cosas son buenas o malas segun las hace nuestra opinión" (Lisias)


RE: Bug in logical decoding with DDL and subtransactions

От:
Bingshuai Li <lucian1412@outlook.com>
Дата:
Hi,

Thanks Álvaro for putting together v6. In cfbot run 37698593816, the two
UBSan jobs, "Linux - Meson (32-bit)" and "Linux - Autoconf", fail with
the same error:

    reorderbuffer.c:3281:9: runtime error: null pointer passed as argument
    2, which is declared to never be null
        #0 TransactionIdInSubxactArray reorderbuffer.c:3281
        #1 ReorderBufferCleanupAbortedSubTxnTupleCids reorderbuffer.c:3258
        #2 DecodeAbort decode.c:912

An abort record without a subxacts block -- for example, ROLLBACK TO a
savepoint with no subcommitted children -- leaves ParseAbortRecord()'s
subxacts == NULL and nsubxacts == 0. In 0002, any tuplecid entry not
matching the primary XID then reaches bsearch(&xid, NULL, 0, ...).
That violates the nonnull contract and aborts the backend under UBSan.
The crashes are in stream and t/019_stream_subxact_ddl_abort.pl; the
backend crash also explains the concurrent regression failures.

The guard belongs in TransactionIdInSubxactArray():

    if (nsubxacts == 0)
        return false;

We still need to remove the primary XID's entries when there are no
children. The isolation tests avoid this UB for different reasons:
tuplecid_restart's entries match the primary XID and short-circuit the
bsearch, whereas tuplecid_nested has a nonempty subxacts array.

With that guard, +1 on 0002: it preserves the cleanup needed before
decoding a commit for output, including finding the toplevel through a
known child when the primary XID is unknown, while scanning the tuplecid
list once. The sortedness precondition holds: AssignTransactionId()
assigns ancestors their XIDs first, AtSubCommit_childXids() relies on
that ordering, and RecordTransactionAbort() logs the array as-is.

On Zhijie's comments:

1. I think the check is needed on a pass that restarts after a child's
first WAL record. Later records can create a ReorderBuffer entry without
replaying the record that established its toplevel association. The
existing catalog_change_snapshot test describes this for NEW_CID records.
I reproduced it with a nested variant on current master plus v6 and the
guard above: at the outer abort, the primary XID was unknown, while a
child in the subxacts array had an entry but was not a known subxact.
The toplevel commit was skipped in that pass. So an entry's presence
does not establish its association; I'd keep rbtxn_is_known_subxact()
and explain that reason in the comment.

2. Agreed, the sortedness comment belongs at the call site.

3. Agreed. 0002 already rewrote the helper's comment. The decode.c
comment could just explain why cleanup precedes the ReorderBufferAbort()
loop, leaving the association reasoning in the helper.

4. Yes, the skipped-cleanup case is reachable on a pass that restarts
after the subtransaction's first, toplevel-XID-bearing WAL record.
Later NEW_CID records can still queue tuplecids on the toplevel without
establishing the writer's association. I reproduced this by consuming
the toplevel commit and then replaying from a checkpoint between the
child's first WAL record and its catalog write. The abort cleanup was
skipped, and so was that already-consumed commit.

For a small example using catalog_change_snapshot.spec, add this step
to session s0 and run only the following permutation:

    step "s0_rollback" { ROLLBACK TO SAVEPOINT sp1; }

    permutation "s0_init" "s0_begin" "s0_savepoint" "s0_insert"
                "s1_checkpoint" "s1_get_changes" "s0_insert2"
                "s0_rollback" "s0_commit" "s0_begin" "s0_insert"
                "s1_checkpoint" "s1_get_changes" "s0_commit"
                "s1_get_changes"

The final get_changes replays the abort without the association and
skips the earlier commit. To exercise (1), nest another savepoint inside
sp1 before the first insert, and release it just before s0_rollback.

The invariant rules out output-decoding that commit in the same pass,
rather than ruling out missing associations: a slot's restart point
cannot advance past the oldest in-progress transaction. The comment
should distinguish those cases. tuplecid_nested covers the separate
case where a known child lets us do the cleanup despite an unknown
primary XID; tuplecid_restart covers replay of the association before
a commit that is decoded for output.

On dropping tuplecid.sql: agreed. The two isolation tests construct the
collision deterministically using a user_catalog_table, page filler,
VACUUM to LP_UNUSED and tid reuse. tuplecid.sql depends on incidental
catalog page layout. Together with your coverage comparison, that seems
like a good reason to keep just the isolation tests.

No attachment here, so cfbot keeps testing the v6 series as posted.
Happy to provide a respin with the guard and comment updates if useful;
otherwise please fold them in as you see fit. The earlier backbranch
versions use v5's per-XID cleanup; I can refresh those once master settles.

Best regards,
Bingshuai Li

RE: Bug in logical decoding with DDL and subtransactions

От:
"Hayato Kuroda (Fujitsu)" <kuroda.hayato@fujitsu.com>
Дата:
Hi Bingshuai,

> Thanks Álvaro for putting together v6. In cfbot run 37698593816, the two
> UBSan jobs, "Linux - Meson (32-bit)" and "Linux - Autoconf", fail with
> the same error:

Embarrassingly, I had not found the cfbot entry. Good catch.
Let me confirm one point, why the test could pass for some platforms?

> The guard belongs in TransactionIdInSubxactArray():
> 
>     if (nsubxacts == 0)
>         return false;

LGTM.

> 1. I think the check is needed on a pass that restarts after a child's
> first WAL record. Later records can create a ReorderBuffer entry without
> replaying the record that established its toplevel association. The
> existing catalog_change_snapshot test describes this for NEW_CID records.
> I reproduced it with a nested variant on current master plus v6 and the
> guard above: at the outer abort, the primary XID was unknown, while a
> child in the subxacts array had an entry but was not a known subxact.
> The toplevel commit was skipped in that pass. So an entry's presence
> does not establish its association; I'd keep rbtxn_is_known_subxact()
> and explain that reason in the comment.

Even though the sub-transactions are not assigned as a child, the code works well
without the rbtxn_is_known_subxact(), right? If so we may not have to keep the
check.

Also, while thinking on it, I started to think whether we have to clean up
Tuplecids even if the transactions will be skipped. In this case transactions are
Not replied thus the issue won't happen, right?

> 3. Agreed. 0002 already rewrote the helper's comment. The decode.c
> comment could just explain why cleanup precedes the ReorderBufferAbort()
> loop, leaving the association reasoning in the helper.

I think the code comment atop the cleanup can be simper like:
```
		/*
		 * Remove tuplecid changes queued by the aborted subtransactions
		 * from the toplevel transaction's list.
		 */
		ReorderBufferCleanupAbortedSubTxnTupleCids(ctx->reorder, xid,
```

Best regards,
Hayato Kuroda
FUJITSU LIMITED

RE: Bug in logical decoding with DDL and subtransactions

От:
Bingshuai Li <lucian1412@outlook.com>
Дата:
Hi Hayato,

On why some platforms passed: the two failing jobs are the only ones in
that run built with UBSan (CFLAGS ... -fno-sanitize-recover=all
-fsanitize=alignment,undefined, UBSAN_OPTIONS with abort_on_error=1).
glibc's  declares bsearch()'s key, base and compar __nonnull,
and UBSan's nonnull-attribute check validates call arguments against
that declaration even when nmemb is zero.  In the glibc build I probed,
the NULL/0 input returns NULL without touching base, so without the
sanitizer the invalid call can go unnoticed; built with those flags,
the same program reports the same "argument 2" error as the cfbot
logs.  With the guard, bsearch() is never reached.

The crash showed up in the stream tests rather than only the new ones:
those tests reach the invalid call while scanning the toplevel's
tuplecid list -- the abort has no subcommitted children, and an entry's
subxid differs from the primary XID.  That shape can occur in savepoint
rollbacks with catalog changes.  tuplecid_restart's entries match the
primary XID (the bsearch is short-circuited) and tuplecid_nested has a
nonempty array, so neither of them trips the NULL base.

On rbtxn_is_known_subxact(): fair point.  My earlier test showed that
an unassociated child entry is reachable, not that the check is
required for correctness.  rbtxn_get_toptxn() returns the transaction
itself when it has no toplevel, and tuplecid changes are always queued
on the entry of the NEW_CID record's top_xid, so an unassociated
child's own list is always empty -- selecting it just walks nothing,
and the worst case is a missed cleanup, not a wrong removal.  I
compared the child-lookup loop with and without the check (leaving the
primary-XID early return unchanged) on current master plus v6 and the
guard, with three schedules including a mixed case that has one
unassociated and one associated child: the output was identical
either way.  In the mixed case, with the check the loop settles on the
associated child and the cleanup does remove its entries; without it
the first child found is selected and nothing is removed -- harmless
in these schedules, because that pass skips the toplevel commit
anyway.  So my earlier example is not a reason to insist on keeping
the child-lookup check; I have no objection to removing it.

On skipped transactions: agreed for the already-consumed transaction
in this example.  DecodeCommit() takes its skip branch, and
ReorderBufferForget() frees the remaining tuplecids through
ReorderBufferCleanupTXN(), without building the tuplecid hash on that
path.  I'd just keep the scope at "this pass will skip the commit":
an abort record can precede start_decoding_at while the later toplevel
commit still needs to be decoded, so the abort record's own skip
decision cannot be used to omit the cleanup.

And yes, your shorter comment is better.  I would only keep one line
saying that the cleanup runs before the ReorderBufferAbort() loop
tears down the transactions and their associations.  The helper's
child-lookup comment should also distinguish missing associations from
an absence of queued tuplecids on the actual toplevel.

No attachment here, so cfbot keeps testing the v6 series as posted;
the guard and the comment updates can go into the next version as
Álvaro prefers.

Best regards,
Bingshuai Li

Re: Bug in logical decoding with DDL and subtransactions

От:
Zhijie Hou <houzhijie22@gmail.com>
Дата:
Вложения:
Hi,

On Thu, Oct 8, 2026 at 5:16 PM Bingshuai Li  wrote:
>
> On Zhijie's comments:
>
> 1. I think the check is needed on a pass that restarts after a child's
> first WAL record. Later records can create a ReorderBuffer entry without
> replaying the record that established its toplevel association. The
> existing catalog_change_snapshot test describes this for NEW_CID records.
> I reproduced it with a nested variant on current master plus v6 and the
> guard above: at the outer abort, the primary XID was unknown, while a
> child in the subxacts array had an entry but was not a known subxact.
> The toplevel commit was skipped in that pass. So an entry's presence
> does not establish its association; I'd keep rbtxn_is_known_subxact()
> and explain that reason in the comment.
>
> 2. Agreed, the sortedness comment belongs at the call site.
>
> 3. Agreed. 0002 already rewrote the helper's comment. The decode.c
> comment could just explain why cleanup precedes the ReorderBufferAbort()
> loop, leaving the association reasoning in the helper.
>
> 4. Yes, the skipped-cleanup case is reachable on a pass that restarts
> after the subtransaction's first, toplevel-XID-bearing WAL record.
> Later NEW_CID records can still queue tuplecids on the toplevel without
> establishing the writer's association. I reproduced this by consuming
> the toplevel commit and then replaying from a checkpoint between the
> child's first WAL record and its catalog write. The abort cleanup was
> skipped, and so was that already-consumed commit.
>
> For a small example using catalog_change_snapshot.spec, add this step
> to session s0 and run only the following permutation:
>
>     step "s0_rollback" { ROLLBACK TO SAVEPOINT sp1; }
>
>     permutation "s0_init" "s0_begin" "s0_savepoint" "s0_insert"
>                 "s1_checkpoint" "s1_get_changes" "s0_insert2"
>                 "s0_rollback" "s0_commit" "s0_begin" "s0_insert"
>                 "s1_checkpoint" "s1_get_changes" "s0_commit"
>                 "s1_get_changes"
>
> The final get_changes replays the abort without the association and
> skips the earlier commit. To exercise (1), nest another savepoint inside
> sp1 before the first insert, and release it just before s0_rollback.

Thanks for the explanation. I re-read the code and comments and have some
suggestions to simplify the code and improve some comments. I think we can
reduce the code in Kuroda-san's patch with a simpler loop:

 txn = ReorderBufferTXNByXid(rb, xid, false, NULL, InvalidXLogRecPtr,
    false);

for (int i = 0; txn == NULL && i < nsubxacts; i++)
    txn = ReorderBufferTXNByXid(rb, subxacts[i], false, NULL,
             InvalidXLogRecPtr, false);

followed by a single early return covering all the skip cases:

if (txn == NULL || !rbtxn_is_known_subxact(txn))
return;

I think this makes the code cleaner and shorter, and also fixes the BF failure
IIUC.

I also rewrote some of the comments above
ReorderBufferCleanupAbortedSubTxnTupleCids(), using wording that's more
consistent with the rest of the codebase and simplifying the explanation of
logic that isn't directly related, hoping it reads better.

I discussed this with Kuroda-san off-list, and have merged the suggested
changes into the original 0002 diff shared by Kuroda-san.

I also moved the tests that Alvaro suggested to remove out of 0001, keeping
them as 0003, so that CFbot can still test them for now, and we can commit
without them later.

0001 is unchanged.

Best Regards,
Zhijie Hou

Re: Bug in logical decoding with DDL and subtransactions

От:
Álvaro Herrera <alvherre@kurilemu.de>
Дата:
On 2026-10-09, Zhijie Hou wrote:

> Thanks for the explanation. I re-read the code and comments and have some
> suggestions to simplify the code and improve some comments. I think we can
> reduce the code in Kuroda-san's patch with a simpler loop:
>
>  txn = ReorderBufferTXNByXid(rb, xid, false, NULL, InvalidXLogRecPtr,
>     false);
>
> for (int i = 0; txn == NULL && i < nsubxacts; i++)
>     txn = ReorderBufferTXNByXid(rb, subxacts[i], false, NULL,
>              InvalidXLogRecPtr, false);
>
> followed by a single early return covering all the skip cases:
>
> if (txn == NULL || !rbtxn_is_known_subxact(txn))
> return;
>
> I think this makes the code cleaner and shorter, and also fixes the BF failure
> IIUC.
>
> I also rewrote some of the comments above
> ReorderBufferCleanupAbortedSubTxnTupleCids(), using wording that's more
> consistent with the rest of the codebase and simplifying the explanation of
> logic that isn't directly related, hoping it reads better.

Hmm I had already made essentially the same changes locally plus a few others. I'll share my patches over the weekend.

-- 
Álvaro Herrera


Re: Bug in logical decoding with DDL and subtransactions

От:
Álvaro Herrera <alvherre@kurilemu.de>
Дата:
Вложения:
On 2026-Oct-09, Álvaro Herrera wrote:

> On 2026-10-09, Zhijie Hou wrote:
> 
> > Thanks for the explanation. I re-read the code and comments and have some
> > suggestions to simplify the code and improve some comments. I think we can
> > reduce the code in Kuroda-san's patch with a simpler loop:
> >
> >  txn = ReorderBufferTXNByXid(rb, xid, false, NULL, InvalidXLogRecPtr,
> >     false);
> >
> > for (int i = 0; txn == NULL && i < nsubxacts; i++)
> >     txn = ReorderBufferTXNByXid(rb, subxacts[i], false, NULL,
> >              InvalidXLogRecPtr, false);
> >
> > followed by a single early return covering all the skip cases:
> >
> > if (txn == NULL || !rbtxn_is_known_subxact(txn))
> > return;
> >
> > I think this makes the code cleaner and shorter, and also fixes the BF failure
> > IIUC.
> >
> > I also rewrote some of the comments above
> > ReorderBufferCleanupAbortedSubTxnTupleCids(), using wording that's more
> > consistent with the rest of the codebase and simplifying the explanation of
> > logic that isn't directly related, hoping it reads better.
> 
> Hmm I had already made essentially the same changes locally plus a few
> others. I'll share my patches over the weekend.

Thanks.  It turned out that the changes I had done were not the same at
all, so I ended up the coding of the new routine essentially the same as
what's in your patch.  But I didn't have time to fully merge my comment
updates with yours, so I kept mine in the function header comment and
mostly yours (but also partly mine) within the function.  You can see I
added an #ifdef block around around the part you found objectionable
(which I also do).  I will give these another read tomorrow to merge
everything in a sane manner.

The new comment in reorderbuffer.h was rewritten.  I think I would like
to add an XXX at that spot, to point out that this is a somewhat silly
arrangement, and that we should instead make tuplecid changes attached
to the subtransaction rather than the top-level transaction, to make the
work at abort time more reasonble.  (That would be a master-only patch,
of course.)  I think XXX comments are effective to motivate people to do
that kind of work.

I renamed the new function to ReorderBufferCleanupAbortedTupleCids, and
moved the new subxid argument to another position.

This patch also renames the tuplecid_data global in snapmgr.c to
HistoricTupleCidHash.  I intend to make this change in master only.  I
think the other name is confusing considering that reorderbuffer.c has a
function parameter using the same name.

-- 
Álvaro Herrera        Breisgau, Deutschland  —  https://www.EnterpriseDB.com/
"Los dioses no protegen a los insensatos.  Éstos reciben protección de
otros insensatos mejor dotados" (Luis Wu, Mundo Anillo)

Re: Bug in logical decoding with DDL and subtransactions

От:
"alvherre@kurilemu.de" <alvherre@kurilemu.de>
Дата:
Okay, I spent some more time trying to rewrite these comments in the new
function so that they explain what we're doing in terms we use elsewhere
in the code, and according to my understanding of how this works.  The
phrasing proposed by Bingshuai contains some terms that we don't use
anywhere else, such as "a decoding pass" and other variations thereof,
referring to the logical decoding "session".  I would appreciate a
review for correctness; if it's wrong, please propose fixes as minimal
as possible (that is, not a complete rewrite).

By the way, the assurance that with this coding we will never call
bsearch() with a NULL subxact array seems a bit too trusting ... I think
we should just add the "return false" if nsubxacts == 0 in
TransactionIdInSubxactArray() just to be on the safe side.  It costs
nothing.  (Well, nothing compared to the cost of doing a hash lookup for
every single aborted subtransaction -- should we instead impose a cost
on ReorderBufferBuildTupleCidHash?)


/*
 * Remove TUPLECID changes from a top-level transaction's tuplecid list.
 *
 * 'xid' is a subtransaction being aborted, and 'subxacts' is the list of
 * its children -- which are, obviously, also being aborted.
 *
 * Unlike other types of changes, tuplecid ones are always queued on the
 * toplevel transaction (see ReorderBufferAddNewTupleCids), so we must search
 * for these changes by subxid.  Because TIDs used by a catalog tuple written
 * by a subtransaction that aborts can be reused later by a future command
 * of the same transaction, we must remove these TUPLECIDs from the array,
 * otherwise the tuplecid hash of the historical snapshot would be corrupt.
 *
 * If the xid being aborted is not known to this reorderbuffer to be a
 * subxact, we return without doing anything, which is correct because there
 * cannot possibly be TUPLECIDs to clean up; the topxid would've been created
 * by ReorderBufferAddNewTupleCids(), and the association between the two is
 * known because we're in SNAPBUILD_FULL_SNAPSHOT mode (otherwise the NEW_CID
 * WAL records aren't decoded.)
 *
 * (This cleanup is pointless when xid is a top-level transaction.  That case
 * is handled instead by ReorderBufferCleanupTXN() clearing the whole list.)
 *
 * XXX this whole exercise is only needed because of keeping the TUPLECID list
 * assigned to the toplevel transaction. Maybe it would be wiser to have a
 * per-subxact list instead.
 */
void
ReorderBufferCleanupAbortedTupleCids(ReorderBuffer *rb,
                                     TransactionId xid,
                                     int nsubxacts,
                                     TransactionId *subxacts)
{
    ReorderBufferTXN *txn;
    ReorderBufferTXN *toptxn;
    dlist_mutable_iter it;

    /*
     * Search the passed-in xids for the first known subtransaction, and use
     * it to find the toplevel transaction.
     */
    txn = ReorderBufferTXNByXid(rb, xid, false, NULL, InvalidXLogRecPtr, false);
    for (int i = 0; txn == NULL && i < nsubxacts; i++)
        txn = ReorderBufferTXNByXid(rb, subxacts[i], false, NULL,
                                    InvalidXLogRecPtr, false);

    /*
     * Skip when nothing usable was found.  No entry at all means no NEW_CID
     * record from these xids was decoded by this snapbuild so nothing was
     * queued, or that we entered FULL_SNAPSHOT after the subxid was assigned
     * as a child.  In the latter case, we won't find the TUPLECIDs, but we
     * don't care.  If this is a top-level xact, this cleanup is not
     * necessary.
     */
    if (txn == NULL || !rbtxn_is_known_subxact(txn))
        return;

    /* Get the top-level transaction whose tuplecid list we're to clean */
    toptxn = rbtxn_get_toptxn(txn);

    dlist_foreach_modify(it, &toptxn->tuplecids)
    {
        ReorderBufferChange *change;

        change = dlist_container(ReorderBufferChange, node, it.cur);

        Assert(change->action == REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID);

        /*
         * Remove the entry if it was recorded on behalf of the aborting
         * subtransaction or one of its subcommitted children.  The subxact
         * array is known sorted in logical order because it comes directly
         * from the xl_xact_abort WAL record, which has them sorted that way
         * by construction (Xid assign order.)
         */
        if (change->data.tuplecid.subxid == xid ||
            TransactionIdInSubxactArray(change->data.tuplecid.subxid,
                                        subxacts, nsubxacts))
        {
            dlist_delete(&change->node);
            ReorderBufferFreeChange(rb, change, false);
            Assert(toptxn->ntuplecids > 0);
            toptxn->ntuplecids--;
        }
    }
}


-- 
Álvaro Herrera         PostgreSQL Developer  —  https://www.EnterpriseDB.com/
"Los dioses no protegen a los insensatos.  Éstos reciben protección de
otros insensatos mejor dotados" (Luis Wu, Mundo Anillo)


RE: Bug in logical decoding with DDL and subtransactions

От:
"Hayato Kuroda (Fujitsu)" <kuroda.hayato@fujitsu.com>
Дата:
Dear Álvaro,

> Okay, I spent some more time trying to rewrite these comments in the new
> function so that they explain what we're doing in terms we use elsewhere
> in the code, and according to my understanding of how this works.  The
> phrasing proposed by Bingshuai contains some terms that we don't use
> anywhere else, such as "a decoding pass" and other variations thereof,
> referring to the logical decoding "session".  I would appreciate a
> review for correctness; if it's wrong, please propose fixes as minimal
> as possible (that is, not a complete rewrite).

I checked your proposal, LGTM.

> By the way, the assurance that with this coding we will never call
> bsearch() with a NULL subxact array seems a bit too trusting ... I think
> we should just add the "return false" if nsubxacts == 0 in
> TransactionIdInSubxactArray() just to be on the safe side.  It costs
> nothing.

The cfbot detected the issue, so +1 to add in TransactionIdInSubxactArray().

[1]: https://github.com/postgres/postgres-cfbot/actions/runs/38178880728/job/114587272272

Best regards,
Hayato Kuroda
FUJITSU LIMITED

Re: Bug in logical decoding with DDL and subtransactions

От:
Zhijie Hou <houzhijie22@gmail.com>
Дата:
Hi,

On Tue, Oct 13, 2026 at 1:15 AM alvherre@kurilemu.de
 wrote:
>
> Okay, I spent some more time trying to rewrite these comments in the new
> function so that they explain what we're doing in terms we use elsewhere
> in the code, and according to my understanding of how this works.  The
> phrasing proposed by Bingshuai contains some terms that we don't use
> anywhere else, such as "a decoding pass" and other variations thereof,
> referring to the logical decoding "session".  I would appreciate a
> review for correctness; if it's wrong, please propose fixes as minimal
> as possible (that is, not a complete rewrite).

Thanks for updating the comments.

They look good to me.

> By the way, the assurance that with this coding we will never call
> bsearch() with a NULL subxact array seems a bit too trusting ... I think
> we should just add the "return false" if nsubxacts == 0 in
> TransactionIdInSubxactArray() just to be on the safe side.  It costs
> nothing.

+1

> (Well, nothing compared to the cost of doing a hash lookup for
> every single aborted subtransaction -- should we instead impose a cost
> on ReorderBufferBuildTupleCidHash?)

I think in most cases the hash lookup only happens once, for the primary XID -
we need to look up the other subxids only when the primary XID has no changes,
which I personally think is rare. And even in that case, we'd find the toplevel
transaction on the second lookup, for one of the subxids, unless many of the
subxids also have no changes. So the cost looks acceptable.

Best Regards,
Zhijie Hou


RE: Bug in logical decoding with DDL and subtransactions

От:
Bingshuai Li <lucian1412@outlook.com>
Дата:
Hi Álvaro,

Agreed on the guard (+1); for the record, I reproduced the cfbot
failure locally on master 36a56229765c plus v8 with the same sanitizer
flags -- the stream test loses its backend and the one-line return
makes the test_decoding and isolation cases pass.

One correction on the comment, though, in the "not known to be a
subxact" paragraph: I don't think "there cannot possibly be TUPLECIDs
to clean up" holds.  The NEW_CID gate is on the snapshot state, but
the association needed by this abort cleanup is established when the
subxact's first WAL record carrying its toplevel XID is replayed
(LogicalDecodingProcessRecord -> ReorderBufferAssignChild).  After a
restart, a saved CONSISTENT snapshot can be restored at a checkpoint
past that record; later NEW_CID records still pass the FULL_SNAPSHOT
gate.  The subxact then gets an entry via ReorderBufferProcessXid with
no association, while its TUPLECIDs are queued on the toplevel.  That
is the state I reported upthread (entry present, not a known subxact,
tuplecids on the toplevel; the toplevel commit skipped).

For this unassociated-subxact case, the early return need not mean an
empty list.  If the toplevel commits, that commit was already consumed
before start_decoding_at; SnapBuildXactNeedsSkip() skips it and
ReorderBufferForget() frees the list, never reaching the tuplecid hash
-- as Zhijie's v7 comment had it.  If the toplevel aborts,
ReorderBufferAbort() frees the list.
The existing parenthetical already covers the top-level abort case.
Minimal suggestion for that paragraph:

    * We return without cleanup if the aborting subxact is not known to
    * this reorderbuffer.  It may still have TUPLECIDs queued on the
    * toplevel if this snapbuild missed its first WAL record carrying
    * the toplevel XID.  A commit that could use them was already
    * consumed: SnapBuildXactNeedsSkip() skips it and ReorderBufferForget()
    * frees the list.  A toplevel abort frees it via ReorderBufferAbort().

Also, in the inner comment, the clause "or that we entered FULL_SNAPSHOT
after the subxid was assigned as a child" doesn't work as an
explanation for finding no entry at all: ReorderBufferProcessXid creates
the entry before the snapshot-state gate, and a later transition to
FULL_SNAPSHOT does not itself remove it.  Dropping that clause (as in
v8's wording) reads correct to me.

And thanks for the terminology fixes; "decoding pass" was indeed not
the codebase's language.

Best regards,
Bingshuai Li

Re: Bug in logical decoding with DDL and subtransactions

От:
"alvherre@kurilemu.de" <alvherre@kurilemu.de>
Дата:
Hello,

Many thanks for the reviews.  I have pushed this to all branches.

On 2026-Oct-14, Bingshuai Li wrote:

> Agreed on the guard (+1); for the record, I reproduced the cfbot
> failure locally on master 36a56229765c plus v8 with the same sanitizer
> flags -- the stream test loses its backend and the one-line return
> makes the test_decoding and isolation cases pass.

Right.

> One correction on the comment, though, in the "not known to be a
> subxact" paragraph: I don't think "there cannot possibly be TUPLECIDs
> to clean up" holds.  The NEW_CID gate is on the snapshot state, but
> the association needed by this abort cleanup is established when the
> subxact's first WAL record carrying its toplevel XID is replayed
> (LogicalDecodingProcessRecord -> ReorderBufferAssignChild).  After a
> restart, a saved CONSISTENT snapshot can be restored at a checkpoint
> past that record; later NEW_CID records still pass the FULL_SNAPSHOT
> gate.  The subxact then gets an entry via ReorderBufferProcessXid with
> no association, while its TUPLECIDs are queued on the toplevel.  That
> is the state I reported upthread (entry present, not a known subxact,
> tuplecids on the toplevel; the toplevel commit skipped).
> 
> For this unassociated-subxact case, the early return need not mean an
> empty list.  If the toplevel commits, that commit was already consumed
> before start_decoding_at; SnapBuildXactNeedsSkip() skips it and
> ReorderBufferForget() frees the list, never reaching the tuplecid hash
> -- as Zhijie's v7 comment had it.  If the toplevel aborts,
> ReorderBufferAbort() frees the list.
> The existing parenthetical already covers the top-level abort case.
> Minimal suggestion for that paragraph:
> 
>     * We return without cleanup if the aborting subxact is not known to
>     * this reorderbuffer.  It may still have TUPLECIDs queued on the
>     * toplevel if this snapbuild missed its first WAL record carrying
>     * the toplevel XID.  A commit that could use them was already
>     * consumed: SnapBuildXactNeedsSkip() skips it and ReorderBufferForget()
>     * frees the list.  A toplevel abort frees it via ReorderBufferAbort().

Okay, I adopted this, but made still more changes to it, mostly because
I don't think we care very much about the memory freeing; we're mostly
concerned with whether the catalog tuple processing is correct.  But I
also changed how we talk about the subxact being "unknown" -- I mean,
it's not that it's really unknown; as I understand it, the problem is
that we don't know that the parent is the parent.  I also think that
talking about SnapBuildXactNeedsSkip() is a bit indirect, so I mentioned
DecodeCommit instead.

There's quite a bit of abstraction leakage in this whole thing, which is
probably unavoidable.  I mean the relationship between reorderbuffer.c
and decode.c and snapbuild.c.  It's probably not surprising that this
patch had to touch all three.  So I don't feel bad that the comment in
reorderbuffer.c needs to mention the function in decode.c.

BTW you mention Zhijie's v7, but I think that comment mostly comes from
your version just prior to that ...

> Also, in the inner comment, the clause "or that we entered FULL_SNAPSHOT
> after the subxid was assigned as a child" doesn't work as an
> explanation for finding no entry at all: ReorderBufferProcessXid creates
> the entry before the snapshot-state gate, and a later transition to
> FULL_SNAPSHOT does not itself remove it.  Dropping that clause (as in
> v8's wording) reads correct to me.

Okay, done that way.

> And thanks for the terminology fixes; "decoding pass" was indeed not
> the codebase's language.

Many thanks for double-checking.

Feel free to propose more wording changes to these comments if something
is still wrong.  At least I think we're better than when we started ...

-- 
Álvaro Herrera               48°01'N 7°57'E  —  https://www.EnterpriseDB.com/
Officer Krupke, what are we to do?
Gee, officer Krupke, Krup you! (West Side Story, "Gee, Officer Krupke")


Re: Bug in logical decoding with DDL and subtransactions

От:
"alvherre@kurilemu.de" <alvherre@kurilemu.de>
Дата:
On 2026-Oct-14, alvherre@kurilemu.de wrote:

> Hello,
> 
> Many thanks for the reviews.  I have pushed this to all branches.

BTW I forgot to mention that this is going to get crake, akepa and baza
worked up about ABI breakage because of the change to
ReorderBufferAddNewTupleCids().  That was unavoidable, I think, but I
checked codesearch.debian.net and a somewhat stale copy of the PGXN
tarballs and found no users of those.


Now I really want to hear whether Mark Dilger's test battery also sees
this bug as fixed ...

-- 
Álvaro Herrera         PostgreSQL Developer  —  https://www.EnterpriseDB.com/
[…] indem ich in meinem Leben oft an euch gedacht, euch glücklich zu machen. Seyd es!
A menudo he pensado en vosotros, en haceros felices. ¡Sedlo, pues!
		Heiligenstädter Testament, L. v. Beethoven, 1802
		https://de.wikisource.org/wiki/Heiligenstädter_Testament


Re: Bug in logical decoding with DDL and subtransactions

От:
"alvherre@kurilemu.de" <alvherre@kurilemu.de>
Дата:
On 2026-Oct-09, Hayato Kuroda (Fujitsu) wrote:

> Also, while thinking on it, I started to think whether we have to clean up
> Tuplecids even if the transactions will be skipped. In this case transactions are
> Not replied thus the issue won't happen, right?

Yeah, I think that's correct.  I was wondering myself if the 2PC case is
correct -- we call ReorderBufferCleanupAbortedTupleCids() only when
two_phase is false.  Do we call DecodeAbort() again for those?  I am not
familiar with the 2PC support here.  The comment for DecodeAbort() could
be better for sure.

-- 
Álvaro Herrera               48°01'N 7°57'E  —  https://www.EnterpriseDB.com/


Re: Bug in logical decoding with DDL and subtransactions

От:
David Rowley <dgrowleyml@gmail.com>
Дата:
On Thu, 15 Oct 2026 at 07:10, alvherre@kurilemu.de  wrote:
> BTW I forgot to mention that this is going to get crake, akepa and baza
> worked up about ABI breakage because of the change to
> ReorderBufferAddNewTupleCids().  That was unavoidable, I think, but I
> checked codesearch.debian.net and a somewhat stale copy of the PGXN
> tarballs and found no users of those.

It's my fault that crake and akepa have been failing the
abi-compliance-check test for the past week or so. I just pushed a
commit to fix that, and akepa is still failing due to 5eae2800a.

Do you need to update .abi-compliance-history?

David


Re: Bug in logical decoding with DDL and subtransactions

От:
Tom Lane <tgl@sss.pgh.pa.us>
Дата:
David Rowley  writes:
> It's my fault that crake and akepa have been failing the
> abi-compliance-check test for the past week or so. I just pushed a
> commit to fix that, and akepa is still failing due to 5eae2800a.

> Do you need to update .abi-compliance-history?

We actually have a bit of a mess here, I think.  Our scheme for
.abi-compliance-history didn't really contemplate overlapping
ABI-breaking patch series.

At this point, to make the buildfarm happy we need v18's
.abi-compliance-history to say that 57193b3a0 is the latest reference
commit.  But it would make very little sense to any future software
archaeologist for the associated text to describe 5eae2800a as the
cause of the ABI break.

I kind of feel like we need to do this as a straight-up reflection
of the actual events: v18's .abi-compliance-history should get three
new entries, citing c7328770b then 5eae2800a then 57193b3a0.

			regards, tom lane


Re: Bug in logical decoding with DDL and subtransactions

От:
David Rowley <dgrowleyml@gmail.com>
Дата:
Вложения:
On Thu, 15 Oct 2026 at 18:25, Tom Lane  wrote:
>
> David Rowley  writes:
> > Do you need to update .abi-compliance-history?
>
> We actually have a bit of a mess here, I think.  Our scheme for
> .abi-compliance-history didn't really contemplate overlapping
> ABI-breaking patch series.
>
> At this point, to make the buildfarm happy we need v18's
> .abi-compliance-history to say that 57193b3a0 is the latest reference
> commit.  But it would make very little sense to any future software
> archaeologist for the associated text to describe 5eae2800a as the
> cause of the ABI break.
>
> I kind of feel like we need to do this as a straight-up reflection
> of the actual events: v18's .abi-compliance-history should get three
> new entries, citing c7328770b then 5eae2800a then 57193b3a0.

That makes sense. I've attached a patch that adds all 3, but I've left
the reason for the middle one for Álvaro to fill in.

Álvaro, happy for you to fill that part in and push to REL_18_STABLE
once you've prepared the 14..17 versions.

David

Re: Bug in logical decoding with DDL and subtransactions

От:
"alvherre@kurilemu.de" <alvherre@kurilemu.de>
Дата:
On 2026-Oct-15, David Rowley wrote:

> That makes sense. I've attached a patch that adds all 3, but I've left
> the reason for the middle one for Álvaro to fill in.
> 
> Álvaro, happy for you to fill that part in and push to REL_18_STABLE
> once you've prepared the 14..17 versions.

Okay, I have pushed the update to branches 14 through 17.  Please grab
the text from there and push the complete update to the other branches.

Thanks!

-- 
Álvaro Herrera        Breisgau, Deutschland  —  https://www.EnterpriseDB.com/
Bob [Floyd] used to say that he was planning to get a Ph.D. by the "green
stamp method," namely by saving envelopes addressed to him as 'Dr. Floyd'.
After collecting 500 such letters, he mused, a university somewhere in
Arizona would probably grant him a degree.              (Don Knuth)


Re: Bug in logical decoding with DDL and subtransactions

От:
Tom Lane <tgl@sss.pgh.pa.us>
Дата:
"alvherre@kurilemu.de"  writes:
> On 2026-Oct-15, David Rowley wrote:
>> That makes sense. I've attached a patch that adds all 3, but I've left
>> the reason for the middle one for Álvaro to fill in.
>> Álvaro, happy for you to fill that part in and push to REL_18_STABLE
>> once you've prepared the 14..17 versions.

> Okay, I have pushed the update to branches 14 through 17.  Please grab
> the text from there and push the complete update to the other branches.

I think it's dead of night in David's time zone, so I'll go fix the
file in v18.

			regards, tom lane


Re: Bug in logical decoding with DDL and subtransactions

От:
Ayush Tiwari <ayushtiwari.slg01@gmail.com>
Дата:
Hi,

I noticed that with beff3cd0098, we scan the whole tuplecid list even
when the aborted subtransaction only did DML.  If there's DDL earlier in
the same transaction, we keep walking the list without removing anything.

Could we skip that scan when none of the aborting xids has catalog changes?
Something like this:

diff --git a/src/backend/replication/logical/reorderbuffer.c
b/src/backend/replication/logical/reorderbuffer.c
index 6c4eadc9972..57a72553d03 100644
--- a/src/backend/replication/logical/reorderbuffer.c
+++ b/src/backend/replication/logical/reorderbuffer.c
@@ -3297,6 +3297,23 @@ ReorderBufferCleanupAbortedTupleCids(ReorderBuffer *rb,
  if (txn == NULL || !rbtxn_is_known_subxact(txn))
  return;

+ /*
+ * SnapBuildProcessNewCid() marks each xid that queues tuplecids as having
+ * catalog changes.  Skip the scan unless an aborting xid has that flag.
+ * Check subcommitted children too, since their parent may not have made
+ * catalog changes itself.
+ */
+ if (!rbtxn_has_catalog_changes(txn))
+ {
+ int subidx;
+
+ for (subidx = 0; subidx < nsubxacts; subidx++)
+ if (ReorderBufferXidHasCatalogChanges(rb, subxacts[subidx]))
+ break;
+ if (subidx == nsubxacts)
+ return;
+ }
+
  /* Get the top-level transaction whose tuplecid list we're to clean */
  toptxn = rbtxn_get_toptxn(txn);

Without the loop over the children, the cmin assertion fails if I add an
insert at the outer savepoint in tuplecid_nested.

This should save some work when a transaction has built up a long tuplecid
list and then hits lots of DML-only subtransaction aborts.  I can prepare a
patch if the direction looks right.

Regards,
Ayush


Re: Bug in logical decoding with DDL and subtransactions

От:
Manu <manuelreyesbravo@gmail.com>
Дата:
Hi Ayush,

> Could we skip that scan when none of the aborting xids has catalog
> changes? [...] I can prepare a patch if the direction looks right.

The direction looks right. I built your guard on current master
(26bd08fb5c, which has beff3cd0098) and measured it:

- Correctness: across 60,000 random transactions (DDL plus DML, nested
  savepoints with RELEASE, and a DML-only savepoint rolled back after the
  DDL), the build with your guard decoded byte-for-byte the same stream as
  master. I also instrumented the skip path to walk the list anyway and
  count what it would have removed: in 50,287 skipped aborts, 0 had any
  tuplecid to remove.

- The loop over the subxacts is necessary, as you noted. Without it, a
  tuplecid_nested permutation with an INSERT at the outer savepoint (the
  outer subxact has no catalog changes of its own; the entries belong to a
  released inner subxact) fails on the cmin Assert, and the same thing
  crashes the differential fuzzer in every shard. With the loop, all of it
  passes. (ReorderBufferBuildTupleCidHash() already gates on
  rbtxn_has_catalog_changes() the same way; the flag is set in
  ReorderBufferXidSetCatalogChanges() and cleared nowhere, so it is a sound
  gate here too.)

- Saving: it grows as (tuplecid list length) x (DML-only aborts). For short
  lists it is in the noise -- around 0.1 ms at 1k tuplecids and 100 aborts.
  It becomes real higher up: 10k/1k is 19 ms -> 3.6 ms, 50k/10k is
  1067 ms -> 18 ms, and 100k/10k is 5213 ms -> 36 ms.

One thing worth documenting: the guard relies on the catalog-changes flag
never being cleared once set. That holds today, but a short comment or an
Assert at the skip would make the dependency explicit for whoever adds a
flag path later.

Happy to share the extra test permutation and the fuzz/benchmark scripts if
they are useful for the patch.

Regards,
Manu


Re: Bug in logical decoding with DDL and subtransactions

От:
"alvherre@kurilemu.de" <alvherre@kurilemu.de>
Дата:
On 2026-Oct-17, Manu wrote:

> - Saving: it grows as (tuplecid list length) x (DML-only aborts). For short
>   lists it is in the noise -- around 0.1 ms at 1k tuplecids and 100 aborts.
>   It becomes real higher up: 10k/1k is 19 ms -> 3.6 ms, 50k/10k is
>   1067 ms -> 18 ms, and 100k/10k is 5213 ms -> 36 ms.

Hmm, so I'm inclined to do this in master only, as I don't think
tuplecid lists are very large generally.

-- 
Álvaro Herrera         PostgreSQL Developer  —  https://www.EnterpriseDB.com/
"Find a bug in a program, and fix it, and the program will work today.
Show the program how to find and fix a bug, and the program
will work forever" (Oliver Silfridge)


Re: Bug in logical decoding with DDL and subtransactions

От:
Rajesh Kumar Thandapani <rajeshkumarth@google.com>
Дата:
Вложения:
On Mon, Nov 23, 2026 at 11:43 AM Alvaro Herrera  wrote:
> Hmm, so I'm inclined to do this in master only, as I don't think
> tuplecid lists are very large generally.

Targeting master only makes sense to me.

Re-attaching the v1 patch here on this thread (my earlier message
accidentally dropped In-Reply-To and started a separate thread). On top
of Ayush's snippet and Manu's feedback, it also returns early when
toptxn->tuplecids is empty, adds an Assert in
ReorderBufferAddNewTupleCids() that subxid has RBTXN_HAS_CATALOG_CHANGES
set, and adds the tuplecid_nested.spec permutation with a regular write
in the outer savepoint.

Regards,
Rajesh Kumar Thandapani
FAQ