pg.ddx.io pgsql-hackers@postgresql.org mailing list archive
help / color / mirror / Atom feedBug in logical decoding with DDL and subtransactions
53+ messages / 15 participants
[nested] [flat]
Commits from this thread:
2026-10-15 96823bfd7c 7792528fd6 72053f183e 46ef0bdd0b Update .abi-compliance-history for changes in reorderbuffer.h
* Bug in logical decoding with DDL and subtransactions
@ 2026-04-30 04:59 Mark Dilger <mark.dilger@enterprisedb.com>
0 siblings, 1 reply; 53+ messages in thread
From: Mark Dilger @ 2026-04-30 04:59 UTC (permalink / raw)
To: pgsql-hackers
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*
Attachments:
fix-tuplecid-cmin-upstream.patch (application/octet-stream, 5.3K) download
diff --git a/src/backend/replication/logical/reorderbuffer.c b/src/backend/replication/logical/reorderbuffer.c
index 11139a910b8..6c0125818cd 100644
--- a/src/backend/replication/logical/reorderbuffer.c
+++ b/src/backend/replication/logical/reorderbuffer.c
@@ -145,6 +145,7 @@ typedef struct ReorderBufferTupleCidEnt
CommandId cmin;
CommandId cmax;
CommandId combocid; /* just for debugging */
+ TransactionId subxid; /* subtransaction that wrote this entry */
} ReorderBufferTupleCidEnt;
/* Virtual file descriptor with file offset tracking */
@@ -1878,16 +1879,60 @@ ReorderBufferBuildTupleCidHash(ReorderBuffer *rb, ReorderBufferTXN *txn)
ent->cmin = change->data.tuplecid.cmin;
ent->cmax = change->data.tuplecid.cmax;
ent->combocid = change->data.tuplecid.combocid;
+ ent->subxid = change->data.tuplecid.subxid;
}
- else
+ else if (ent->cmin != change->data.tuplecid.cmin)
{
/*
- * Maybe we already saw this tuple before in this transaction, but
- * if so it must have the same cmin.
+ * The same TID appears with a different cmin. This happens when
+ * a subtransaction inserts a catalog tuple, then a ROLLBACK TO
+ * SAVEPOINT aborts that subtransaction, and a later operation
+ * reuses the same TID (after page pruning reclaims the dead
+ * tuple's slot). Both xl_heap_new_cid records remain in the WAL
+ * under the top-level xid.
+ *
+ * We resolve this by checking which entry's subtransaction
+ * aborted. The entry from the aborted subtransaction is stale
+ * and should be discarded.
*/
- Assert(ent->cmin == change->data.tuplecid.cmin);
-
+ if (TransactionIdDidAbort(ent->subxid))
+ {
+ /* Existing entry is from an aborted subtxn; replace it. */
+ ent->cmin = change->data.tuplecid.cmin;
+ ent->cmax = change->data.tuplecid.cmax;
+ ent->combocid = change->data.tuplecid.combocid;
+ ent->subxid = change->data.tuplecid.subxid;
+ }
+ else if (TransactionIdDidAbort(change->data.tuplecid.subxid))
+ {
+ /* New entry is from an aborted subtxn; skip it. */
+ }
+ else
+ {
+ /*
+ * Neither subtransaction aborted — this shouldn't happen.
+ * Keep the existing entry but log a warning.
+ */
+ elog(WARNING, "tuplecid cmin mismatch with no aborted "
+ "subtransaction: rel %u/%u/%u tid (%u,%u) "
+ "existing cmin %u (subxid %u) "
+ "new cmin %u (subxid %u)",
+ key.rlocator.spcOid,
+ key.rlocator.dbOid,
+ key.rlocator.relNumber,
+ ItemPointerGetBlockNumber(&key.tid),
+ ItemPointerGetOffsetNumber(&key.tid),
+ ent->cmin, ent->subxid,
+ change->data.tuplecid.cmin,
+ change->data.tuplecid.subxid);
+ }
+ }
+ else
+ {
/*
+ * Same cmin — this is the normal case where the same tuple is
+ * seen multiple times (e.g. insert then update). Update cmax.
+ *
* cmax may be initially invalid, but once set it can only grow,
* and never become invalid again.
*/
@@ -3440,7 +3485,8 @@ void
ReorderBufferAddNewTupleCids(ReorderBuffer *rb, TransactionId xid,
XLogRecPtr lsn, RelFileLocator locator,
ItemPointerData tid, CommandId cmin,
- CommandId cmax, CommandId combocid)
+ CommandId cmax, CommandId combocid,
+ TransactionId subxid)
{
ReorderBufferChange *change = ReorderBufferAllocChange(rb);
ReorderBufferTXN *txn;
@@ -3452,6 +3498,7 @@ ReorderBufferAddNewTupleCids(ReorderBuffer *rb, TransactionId xid,
change->data.tuplecid.cmin = cmin;
change->data.tuplecid.cmax = cmax;
change->data.tuplecid.combocid = combocid;
+ change->data.tuplecid.subxid = subxid;
change->lsn = lsn;
change->txn = txn;
change->action = REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID;
diff --git a/src/backend/replication/logical/snapbuild.c b/src/backend/replication/logical/snapbuild.c
index adf18c397db..3c9eba3dbaa 100644
--- a/src/backend/replication/logical/snapbuild.c
+++ b/src/backend/replication/logical/snapbuild.c
@@ -700,7 +700,7 @@ SnapBuildProcessNewCid(SnapBuild *builder, TransactionId xid,
ReorderBufferAddNewTupleCids(builder->reorder, xlrec->top_xid, lsn,
xlrec->target_locator, xlrec->target_tid,
xlrec->cmin, xlrec->cmax,
- xlrec->combocid);
+ xlrec->combocid, xid);
/* figure out new command id */
if (xlrec->cmin != InvalidCommandId &&
diff --git a/src/include/replication/reorderbuffer.h b/src/include/replication/reorderbuffer.h
index fa0745552f8..0072c7e5aa1 100644
--- a/src/include/replication/reorderbuffer.h
+++ b/src/include/replication/reorderbuffer.h
@@ -146,6 +146,7 @@ typedef struct ReorderBufferChange
CommandId cmin;
CommandId cmax;
CommandId combocid;
+ TransactionId subxid;
} tuplecid;
/* Invalidation. */
@@ -748,7 +749,9 @@ extern void ReorderBufferAddNewCommandId(ReorderBuffer *rb, TransactionId xid,
extern void ReorderBufferAddNewTupleCids(ReorderBuffer *rb, TransactionId xid,
XLogRecPtr lsn, RelFileLocator locator,
ItemPointerData tid,
- CommandId cmin, CommandId cmax, CommandId combocid);
+ CommandId cmin, CommandId cmax,
+ CommandId combocid,
+ TransactionId subxid);
extern void ReorderBufferAddInvalidations(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn,
Size nmsgs, SharedInvalidationMessage *msgs);
extern void ReorderBufferAddDistributedInvalidations(ReorderBuffer *rb, TransactionId xid,
fuzz_cmin.pl (text/x-perl-script, 12.5K) download
#!/usr/bin/env perl
#
# fuzz_cmin.pl — Fuzzer for tuplecid cmin mismatch in logical decoding
#
# Demonstrates a bug in ReorderBufferBuildTupleCidHash where catalog
# TID reuse after savepoint rollback causes an Assert failure (cassert
# builds) or silent catalog visibility corruption (production builds).
#
# WHAT IT DOES
#
# 1. Initializes a fresh PostgreSQL cluster with wal_level=logical.
# 2. Creates a database, a logical replication slot (test_decoding),
# and 30 seed tables to populate catalog pages.
# 3. Runs up to N iterations. Each iteration:
# a. Generates a random transaction with CREATE TABLE, DROP TABLE,
# SAVEPOINT, ROLLBACK TO SAVEPOINT, and ALTER TABLE operations.
# b. Commits the transaction.
# c. Calls pg_logical_slot_get_changes() to trigger logical decoding.
# 4. If the server crashes (Assert or PANIC), reports the iteration
# number and saves the failing SQL to a file.
#
# WHAT TO EXPECT
#
# On an UNPATCHED --enable-cassert build, the fuzzer typically triggers
# within 300-1000 iterations (15-60 seconds) with output like:
#
# !!! CMIN MISMATCH on iteration 389 !!!
# Reproducer: fuzz_cases/case_389.sql
# Panic details:
# TRAP: failed Assert("ent->cmin == change->data.tuplecid.cmin"), ...
#
# On a PATCHED build, it runs to completion with no crashes.
#
# On a production (non-assert) build, the bug is silent — no crash,
# but the logical decoder may produce incorrect output.
#
# REQUIREMENTS
#
# - A PostgreSQL installation (--enable-cassert recommended).
# Set PGINSTALL to the installation prefix, e.g.:
# export PGINSTALL=/usr/local/pgsql
# The directory must contain bin/initdb, bin/pg_ctl, bin/psql.
# - The test_decoding contrib module must be installed.
# - No other PostgreSQL instance using port 54329 (or set PGPORT).
#
# USAGE
#
# perl fuzz_cmin.pl [max_iterations]
#
# Default is 100000 iterations. The fuzzer stops early on crash.
# Data directory and test cases are written to fuzz_data/ and
# fuzz_cases/ in the current directory.
#
# ENVIRONMENT VARIABLES
#
# PGINSTALL PostgreSQL installation prefix (default: /usr/local/pgsql)
# PGPORT Port number (default: 54329)
#
use strict;
use warnings;
use File::Path qw(rmtree);
use POSIX qw(WIFEXITED WEXITSTATUS);
# ---------------------------------------------------------------------------
# Configuration
# ---------------------------------------------------------------------------
my $max_iterations = $ARGV[0] || 100_000;
my $pg_install = $ENV{PGINSTALL} || '/usr/local/pgsql';
my $port = $ENV{PGPORT} || 54329;
my $base_dir = 'fuzz_data';
my $cases_dir = 'fuzz_cases';
my $dbname = 'fuzzdb';
my $slot_name = 'fuzz_slot';
my $pg_ctl = "$pg_install/bin/pg_ctl";
my $initdb = "$pg_install/bin/initdb";
my $psql = "$pg_install/bin/psql";
die "PGINSTALL=$pg_install does not contain bin/initdb\n"
unless -x $initdb;
# Tunable ranges for test case generation
my $min_ops_per_txn = 10;
my $max_ops_per_txn = 80;
my $min_cols_per_table = 5;
my $max_cols_per_table = 25;
my $max_live_tables = 30;
my $savepoint_prob = 0.15;
my $rollback_prob = 0.40;
my $alter_add_prob = 0.10;
my $alter_drop_prob = 0.05;
my @col_types = (
('integer') x 5,
('bigint') x 3,
('text') x 4,
('boolean') x 3,
('real') x 2,
'double precision',
'numeric',
'date',
'timestamp',
'bytea',
'varchar(100)',
'char(10)',
'smallint',
'oid',
'name',
);
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
sub pick { return $_[int(rand(@_))] }
sub run_psql {
my ($db, $sql, %opts) = @_;
my $timeout = $opts{timeout} || 30;
my $tmpfile = "/tmp/fuzz_cmin_$$.sql";
open(my $fh, '>', $tmpfile) or die "Cannot write $tmpfile: $!\n";
print $fh $sql;
close($fh);
my $cmd = "$psql -X -h /tmp -p $port -d $db -f $tmpfile 2>&1";
my $output;
eval {
local $SIG{ALRM} = sub { die "timeout\n" };
alarm($timeout);
$output = `$cmd`;
alarm(0);
};
my $exit_status = $?;
alarm(0);
unlink($tmpfile);
if ($@ && $@ eq "timeout\n") {
return (undef, "TIMEOUT after ${timeout}s");
}
my $ok = WIFEXITED($exit_status) && WEXITSTATUS($exit_status) == 0;
return ($ok, $output);
}
sub server_alive {
my ($ok) = run_psql('postgres', "SELECT 1;", timeout => 10);
return $ok;
}
sub start_server {
print "Starting server on port $port...\n";
system("$pg_ctl -D $base_dir -l $base_dir/logfile -w start "
. "-o '-p $port -k /tmp' >/dev/null 2>&1");
die "Failed to start server\n" unless server_alive();
print "Server running.\n";
}
sub stop_server {
system("$pg_ctl -D $base_dir -m fast stop >/dev/null 2>&1");
}
sub check_log_for_panic {
open(my $fh, '<', "$base_dir/logfile") or return "";
my @matches;
while (<$fh>) {
push @matches, $_ if /tuplecid cmin mismatch|matching entry #|PANIC|TRAP/;
}
close($fh);
return join("", @matches);
}
# ---------------------------------------------------------------------------
# Setup
# ---------------------------------------------------------------------------
print "=== cmin mismatch fuzzer ===\n";
print "PG install: $pg_install\n";
print "Data dir: $base_dir\n";
print "Port: $port\n\n";
# Clean up any previous run
stop_server();
if (-d $base_dir) {
rmtree($base_dir) or die "Cannot remove $base_dir: $!\n";
}
mkdir($cases_dir) unless -d $cases_dir;
# Initialize cluster
print "Initializing cluster...\n";
system("$initdb -D $base_dir --no-locale -A trust >/dev/null 2>&1") == 0
or die "initdb failed\n";
# Configure for logical decoding
open(my $conf, '>>', "$base_dir/postgresql.conf") or die $!;
print $conf <<'CONF';
wal_level = logical
max_replication_slots = 4
max_wal_senders = 4
shared_buffers = '64MB'
log_min_messages = warning
log_line_prefix = '%m [%p] '
CONF
close($conf);
start_server();
# Create database and logical replication slot
print "Creating database and replication slot...\n";
run_psql('postgres', "CREATE DATABASE $dbname;");
run_psql($dbname,
"SELECT pg_create_logical_replication_slot('$slot_name', 'test_decoding');");
# Pre-seed: create tables to populate catalog pages so that subsequent
# CREATE/DROP cycles within a transaction can trigger page pruning and
# TID reuse on catalog pages.
print "Pre-seeding catalog pages (30 tables)...\n";
for my $i (1..30) {
my @cols = map { "c$_ integer" } 1..20;
run_psql($dbname, "CREATE TABLE seed_$i (" . join(', ', @cols) . ");");
}
# Consume the seeding WAL
run_psql($dbname,
"SELECT count(*) FROM pg_logical_slot_get_changes('$slot_name', NULL, NULL);");
print "Setup complete. Starting fuzzer.\n\n";
# ---------------------------------------------------------------------------
# Test case generator
# ---------------------------------------------------------------------------
sub generate_test_case {
my $sql = "";
my @live_tables;
my @savepoints;
my %sp_tables;
my $table_counter = 0;
my $sp_counter = 0;
my $col_counter = 0;
my $num_ops = $min_ops_per_txn +
int(rand($max_ops_per_txn - $min_ops_per_txn));
$sql .= "BEGIN;\n";
for my $op_num (1..$num_ops) {
# Maybe create a savepoint
if (rand() < $savepoint_prob && @savepoints < 3) {
$sp_counter++;
my $sp = "sp_$sp_counter";
push @savepoints, $sp;
$sp_tables{$sp} = [];
$sql .= "SAVEPOINT $sp;\n";
next;
}
# Maybe rollback to savepoint
if (rand() < $rollback_prob && @savepoints > 0) {
my $sp = $savepoints[-1];
for my $t (@{$sp_tables{$sp}}) {
@live_tables = grep { $_ ne $t } @live_tables;
}
$sql .= "ROLLBACK TO SAVEPOINT $sp;\n";
$sp_tables{$sp} = [];
next;
}
# Maybe ALTER TABLE ADD COLUMN
if (rand() < $alter_add_prob && @live_tables > 0) {
my $tbl = pick(@live_tables);
$col_counter++;
my $typ = pick(@col_types);
$sql .= "ALTER TABLE $tbl ADD COLUMN extra_$col_counter $typ;\n";
next;
}
# Maybe ALTER TABLE DROP COLUMN
if (rand() < $alter_drop_prob && @live_tables > 0) {
my $tbl = pick(@live_tables);
if ($col_counter > 0) {
my $c = 1 + int(rand($col_counter));
$sql .= "DO \$\$ BEGIN "
. "ALTER TABLE $tbl DROP COLUMN IF EXISTS extra_$c; "
. "EXCEPTION WHEN OTHERS THEN NULL; "
. "END \$\$;\n";
}
next;
}
# Main choice: CREATE or DROP
my $do_create = (@live_tables < 3) ? 1 :
(@live_tables >= $max_live_tables) ? 0 :
(rand() < 0.55) ? 1 : 0;
if ($do_create) {
$table_counter++;
my $tbl = "fuzz_t$table_counter";
my $ncols = $min_cols_per_table +
int(rand($max_cols_per_table - $min_cols_per_table));
my @cols;
for my $c (1..$ncols) {
push @cols, "c$c " . pick(@col_types);
}
$sql .= "CREATE TABLE $tbl (" . join(', ', @cols) . ");\n";
push @live_tables, $tbl;
if (@savepoints) {
push @{$sp_tables{$savepoints[-1]}}, $tbl;
}
}
else {
my $idx = int(rand(@live_tables));
my $tbl = splice(@live_tables, $idx, 1);
$sql .= "DROP TABLE $tbl;\n";
}
}
$sql .= "COMMIT;\n";
return $sql;
}
# ---------------------------------------------------------------------------
# Main fuzzer loop
# ---------------------------------------------------------------------------
my $start_time = time();
for my $iter (1..$max_iterations) {
my $test_sql = generate_test_case();
# Save to file before executing (in case server crashes hard)
my $case_file = "$cases_dir/case_$iter.sql";
open(my $fh, '>', $case_file) or die "Cannot write $case_file: $!\n";
print $fh $test_sql;
close($fh);
# Execute the transaction
my ($txn_ok, $txn_out) = run_psql($dbname, $test_sql, timeout => 60);
if (!$txn_ok) {
if (!server_alive()) {
my $panic = check_log_for_panic();
print "\n!!! SERVER CRASHED on iteration $iter !!!\n";
print "Reproducer: $case_file\n";
print "Server log extract:\n$panic\n" if $panic;
last;
}
# Server alive, txn just failed — consume WAL and continue
run_psql($dbname,
"SELECT count(*) FROM pg_logical_slot_get_changes("
. "'$slot_name', NULL, NULL);", timeout => 30);
next;
}
# Transaction committed — trigger logical decoding
my ($dec_ok, $dec_out) = run_psql($dbname,
"SELECT count(*) FROM pg_logical_slot_get_changes("
. "'$slot_name', NULL, NULL);", timeout => 120);
if (!$dec_ok) {
sleep(2);
my $panic = check_log_for_panic();
if ($panic =~ /tuplecid cmin mismatch|TRAP.*Assert/) {
print "\n!!! CMIN MISMATCH on iteration $iter !!!\n";
print "Reproducer: $case_file\n";
print "Server log extract:\n$panic\n";
last;
}
if (!server_alive()) {
print "\n!!! SERVER CRASHED during decode, iteration $iter !!!\n";
print "Reproducer: $case_file\n";
print "Server log extract:\n$panic\n" if $panic;
last;
}
}
# Periodic cleanup: drop fuzz_ tables to prevent unbounded catalog growth
if ($iter % 50 == 0) {
run_psql($dbname, <<'CLEANUP');
DO $$ DECLARE r record;
BEGIN
FOR r IN SELECT schemaname || '.' || tablename AS t
FROM pg_tables WHERE tablename LIKE 'fuzz_%'
LOOP
EXECUTE 'DROP TABLE IF EXISTS ' || r.t || ' CASCADE';
END LOOP;
END $$;
CLEANUP
run_psql($dbname,
"SELECT count(*) FROM pg_logical_slot_get_changes("
. "'$slot_name', NULL, NULL);", timeout => 30);
}
# Progress
if ($iter % 100 == 0) {
my $elapsed = time() - $start_time;
printf " [%d iterations, %ds elapsed, %.1f iter/s]\n",
$iter, $elapsed, $iter / ($elapsed || 1);
}
}
my $elapsed = time() - $start_time;
print "\nFuzzer finished after $elapsed seconds.\n";
# Cleanup
stop_server();
^ permalink raw reply [nested|flat] 53+ messages in thread
* Re: Bug in logical decoding with DDL and subtransactions
@ 2026-08-04 02:33 kid <lucian1412@outlook.com>
parent: Mark Dilger <mark.dilger@enterprisedb.com>
0 siblings, 1 reply; 53+ messages in thread
From: kid @ 2026-08-04 02:33 UTC (permalink / raw)
To: pgsql-hackers; +Cc: Mark Dilger <mark.dilger@enterprisedb.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,
<Bingshuai Li>
^ permalink raw reply [nested|flat] 53+ messages in thread
* Bug in logical decoding with DDL and subtransactions
@ 2026-08-11 11:00 Bingshuai Li <lucian1412@outlook.com>
parent: kid <lucian1412@outlook.com>
0 siblings, 1 reply; 53+ messages in thread
From: Bingshuai Li @ 2026-08-11 11:00 UTC (permalink / raw)
To: pgsql-hackers@lists.postgresql.org <pgsql-hackers@lists.postgresql.org>; +Cc: mark.dilger@enterprisedb.com <mark.dilger@enterprisedb.com>
Hi Mark,
There has been no feedback so far, so I went ahead and wrote the
abort-time cleanup variant I offered in my first mail, so that both
approaches can be compared concretely. Patch attached (including a
regression test, more on that below).
The variant shares your approach of tagging each tuplecid record with
the writing subtransaction's xid, but instead of resolving conflicts
lazily at hash-build time via TransactionIdDidAbort(), it removes the
aborted subtransaction's entries in ReorderBufferAbort(). Compared
to your patch:
- ReorderBufferBuildTupleCidHash() is left untouched: with the stale
entries removed at abort time, the "same tid => same cmin"
assumption holds again, so the original Assert can stay (and no
WARNING needs to be raised from the decoding path).
- No clog lookups during decode: the abort is known from the WAL
stream itself.
- The mirror case is covered too: a catalog tuple *deleted* only by
an aborted subtransaction no longer leaves a stale cmax behind, so
historic snapshots cannot wrongly treat a still-live tuple as
deleted.
One implementation note: no extra work is needed to learn the
sub->top association. Any subtransaction with tuplecid entries must
have written WAL (the xl_heap_new_cid record itself), and records
written inside a subtransaction carry the top-level xid, which
LogicalDecodingProcessRecord() uses to assign the subtransaction to
its top-level transaction before dispatching the record. So
ReorderBufferAbort() can simply walk the toplevel transaction's
tuplecids list and drop the entries tagged with the aborted xid.
Testing (master 36f7330b8b2, --enable-cassert):
- A/B with my earlier reproducer in a loop: unpatched master dies at
the 4th iteration (the original Assert at reorderbuffer.c:1890);
with the patch, 300 iterations without a crash.
- contrib/test_decoding "make check" passes, including the new test
(21 regression + 14 isolation tests).
- Same results on REL_19_STABLE (64542957b44): the reporter's
original script crashes unpatched and passes with the patch.
About the regression test: since the collision depends on the
physical layout of catalog pages, I initially doubted a usable test
was possible. What worked was running the trigger shape in a
*freshly created database* (so prior tests cannot have changed the
catalog layout), with some catalog churn first and the
savepoint-DDL/rollback/DDL/decode shape repeated 25 times via \gexec.
Without the fix, the test dies in ReorderBufferBuildTupleCidHash()
within a handful of iterations on every fresh cluster I tried; with
the fix it always passes. It is still probabilistic in principle --
an unusual initial catalog layout could in theory dodge all 25
iterations -- and on non-assert builds it cannot observe the silent
corruption at all, but it is a good deal smaller than a fully
deterministic reproducer.
I'm not attached to either approach; the goal is to get this fixed
for 19. If you prefer your variant, the test should serve it as
well, since it exercises the crash that both patches fix.
Thanks,
Bingshuai Li
Attachments:
v1-0001-Fix-stale-tuplecid-records-left-behind-by-aborted-su.patch (application/octet-stream, 24.2K) download
From 616fadcf2e4112a654b96ee8b1a303c734294bf8 Mon Sep 17 00:00:00 2001
From: Bingshuai Li <lucian1412@outlook.com>
Date: Tue, 11 Aug 2026 14:19:47 +0800
Subject: [PATCH] Fix stale tuplecid records left behind by aborted
subtransactions
Tuplecid changes are always queued on the toplevel transaction, so
unlike regular changes they are not dropped when the subtransaction
that wrote them aborts. The stale mappings corrupt
ReorderBufferBuildTupleCidHash() at commit time: if a later catalog
insert reuses the aborted subtransaction's line pointer (made
LP_UNUSED by on-access pruning), the fresh record collides with the
stale one with a different cmin, tripping the cmin equality
assertion; where nothing reuses the tid, a stale cmax makes a
still-live catalog tuple look deleted on historic snapshots.
Remove the aborted subtransaction's tuplecid entries in
ReorderBufferAbort(). The sub->top association is always known
there, because any subtransaction with tuplecid entries must have
written WAL (the xl_heap_new_cid record itself), and
LogicalDecodingProcessRecord() assigns records carrying a top-level
xid to their top-level transaction before dispatching them.
Bug: #19555
Reported-by: Alexander Kozhemyakin <a.kozhemyakin@postgrespro.ru>
Discussion: https://postgr.es/m/CAHgHdKu5e3XY5e90Tuaxq_R4WrKxSV734Q%2BLwo5y39Omp2A-Gg@mail.gmail.com
---
contrib/test_decoding/Makefile | 3 +-
contrib/test_decoding/expected/tuplecid.out | 481 ++++++++++++++++++
contrib/test_decoding/sql/tuplecid.sql | 70 +++
.../replication/logical/reorderbuffer.c | 48 +-
src/backend/replication/logical/snapbuild.c | 2 +-
src/include/replication/reorderbuffer.h | 9 +-
6 files changed, 609 insertions(+), 4 deletions(-)
create mode 100644 contrib/test_decoding/expected/tuplecid.out
create mode 100644 contrib/test_decoding/sql/tuplecid.sql
diff --git a/contrib/test_decoding/Makefile b/contrib/test_decoding/Makefile
index 0111124399a..46db0eb3b75 100644
--- a/contrib/test_decoding/Makefile
+++ b/contrib/test_decoding/Makefile
@@ -5,7 +5,8 @@ PGFILEDESC = "test_decoding - example of a logical decoding output plugin"
REGRESS = ddl xact rewrite toast permissions decoding_in_xact \
decoding_into_rel binary prepared replorigin time messages \
- repack spill slot truncate stream stats twophase twophase_stream
+ repack spill slot truncate stream stats twophase twophase_stream \
+ tuplecid
ISOLATION = mxact delayed_startup ondisk_startup concurrent_ddl_dml \
oldest_xmin snapshot_transfer subxact_without_top concurrent_stream \
twophase_snapshot slot_creation_error catalog_change_snapshot \
diff --git a/contrib/test_decoding/expected/tuplecid.out b/contrib/test_decoding/expected/tuplecid.out
new file mode 100644
index 00000000000..4d7f2e10802
--- /dev/null
+++ b/contrib/test_decoding/expected/tuplecid.out
@@ -0,0 +1,481 @@
+-- Tests for decoding of transactions in which a catalog-modifying
+-- subtransaction was rolled back (BUG #19555).
+--
+-- When a subtransaction modifies catalog tuples and is then rolled back,
+-- its dead heap-only line pointers can be marked LP_UNUSED by on-access
+-- pruning and reused by later catalog inserts of the same top-level
+-- transaction. The aborted subtransaction's xl_heap_new_cid records must
+-- not be consulted when building the historic snapshot used to decode the
+-- transaction; on unfixed builds they collide with the records of the
+-- reused line pointer and decoding dies with
+-- TRAP: failed Assert("ent->cmin == change->data.tuplecid.cmin")
+-- (or, on non-assert builds, silently uses wrong cmin/cmax mappings).
+--
+-- Whether the collision triggers depends on the physical layout of the
+-- catalog pages, so run in a fresh database where prior tests cannot have
+-- changed it, and loop enough times to leave headroom for layout
+-- differences across versions.
+CREATE DATABASE tuplecid_db;
+\c tuplecid_db
+-- predictability
+SET synchronous_commit = on;
+SELECT 'init' FROM pg_create_logical_replication_slot('regression_slot', 'test_decoding');
+ ?column?
+----------
+ init
+(1 row)
+
+-- Catalog churn to push the catalog pages into a state where on-access
+-- pruning frees the aborted subtransaction's line pointer and the second
+-- ALTER's catalog insert reuses it.
+CREATE TABLE tpc_filler1(f1 char(4));
+CREATE TABLE tpc_filler2(data text);
+INSERT INTO tpc_filler2 VALUES ('before-test');
+CREATE TYPE tpc_complex AS (r float8, i float8);
+CREATE TABLE tpc_filler3 (a int PRIMARY KEY, b text DEFAULT 'Unspecified');
+CREATE TABLE tpc_filler4 (id serial, t text);
+CREATE TABLE tpc_filler5(data text);
+INSERT INTO tpc_filler5 SELECT repeat('a', 2000) || g.i FROM generate_series(1, 1) g(i);
+TRUNCATE table tpc_filler5;
+CHECKPOINT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+ count
+-------
+ 9
+(1 row)
+
+-- Each iteration runs the trigger shape: catalog DDL inside a rolled-back
+-- subtransaction, then the same DDL again, then decode. Unfixed builds
+-- typically die within a handful of iterations.
+SELECT format($fmt$
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+$fmt$)
+FROM generate_series(1, 25) \gexec
+
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+
+ count
+-------
+ 0
+(1 row)
+
+
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+
+ count
+-------
+ 0
+(1 row)
+
+
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+
+ count
+-------
+ 0
+(1 row)
+
+
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+
+ count
+-------
+ 0
+(1 row)
+
+
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+
+ count
+-------
+ 0
+(1 row)
+
+
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+
+ count
+-------
+ 0
+(1 row)
+
+
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+
+ count
+-------
+ 0
+(1 row)
+
+
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+
+ count
+-------
+ 0
+(1 row)
+
+
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+
+ count
+-------
+ 0
+(1 row)
+
+
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+
+ count
+-------
+ 0
+(1 row)
+
+
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+
+ count
+-------
+ 0
+(1 row)
+
+
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+
+ count
+-------
+ 0
+(1 row)
+
+
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+
+ count
+-------
+ 0
+(1 row)
+
+
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+
+ count
+-------
+ 0
+(1 row)
+
+
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+
+ count
+-------
+ 0
+(1 row)
+
+
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+
+ count
+-------
+ 0
+(1 row)
+
+
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+
+ count
+-------
+ 0
+(1 row)
+
+
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+
+ count
+-------
+ 0
+(1 row)
+
+
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+
+ count
+-------
+ 0
+(1 row)
+
+
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+
+ count
+-------
+ 0
+(1 row)
+
+
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+
+ count
+-------
+ 0
+(1 row)
+
+
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+
+ count
+-------
+ 0
+(1 row)
+
+
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+
+ count
+-------
+ 0
+(1 row)
+
+
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+
+ count
+-------
+ 0
+(1 row)
+
+
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+
+ count
+-------
+ 0
+(1 row)
+
+DROP TABLE tpc_filler1;
+DROP TABLE tpc_filler2;
+DROP TYPE tpc_complex;
+DROP TABLE tpc_filler3;
+DROP TABLE tpc_filler4;
+DROP TABLE tpc_filler5;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+ count
+-------
+ 0
+(1 row)
+
+SELECT pg_drop_replication_slot('regression_slot');
+ pg_drop_replication_slot
+--------------------------
+
+(1 row)
+
+\c contrib_regression
+DROP DATABASE tuplecid_db;
diff --git a/contrib/test_decoding/sql/tuplecid.sql b/contrib/test_decoding/sql/tuplecid.sql
new file mode 100644
index 00000000000..657c56439b8
--- /dev/null
+++ b/contrib/test_decoding/sql/tuplecid.sql
@@ -0,0 +1,70 @@
+-- Tests for decoding of transactions in which a catalog-modifying
+-- subtransaction was rolled back (BUG #19555).
+--
+-- When a subtransaction modifies catalog tuples and is then rolled back,
+-- its dead heap-only line pointers can be marked LP_UNUSED by on-access
+-- pruning and reused by later catalog inserts of the same top-level
+-- transaction. The aborted subtransaction's xl_heap_new_cid records must
+-- not be consulted when building the historic snapshot used to decode the
+-- transaction; on unfixed builds they collide with the records of the
+-- reused line pointer and decoding dies with
+-- TRAP: failed Assert("ent->cmin == change->data.tuplecid.cmin")
+-- (or, on non-assert builds, silently uses wrong cmin/cmax mappings).
+--
+-- Whether the collision triggers depends on the physical layout of the
+-- catalog pages, so run in a fresh database where prior tests cannot have
+-- changed it, and loop enough times to leave headroom for layout
+-- differences across versions.
+CREATE DATABASE tuplecid_db;
+\c tuplecid_db
+
+-- predictability
+SET synchronous_commit = on;
+
+SELECT 'init' FROM pg_create_logical_replication_slot('regression_slot', 'test_decoding');
+
+-- Catalog churn to push the catalog pages into a state where on-access
+-- pruning frees the aborted subtransaction's line pointer and the second
+-- ALTER's catalog insert reuses it.
+CREATE TABLE tpc_filler1(f1 char(4));
+CREATE TABLE tpc_filler2(data text);
+INSERT INTO tpc_filler2 VALUES ('before-test');
+CREATE TYPE tpc_complex AS (r float8, i float8);
+CREATE TABLE tpc_filler3 (a int PRIMARY KEY, b text DEFAULT 'Unspecified');
+CREATE TABLE tpc_filler4 (id serial, t text);
+CREATE TABLE tpc_filler5(data text);
+INSERT INTO tpc_filler5 SELECT repeat('a', 2000) || g.i FROM generate_series(1, 1) g(i);
+TRUNCATE table tpc_filler5;
+CHECKPOINT;
+
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+
+-- Each iteration runs the trigger shape: catalog DDL inside a rolled-back
+-- subtransaction, then the same DDL again, then decode. Unfixed builds
+-- typically die within a handful of iterations.
+SELECT format($fmt$
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+$fmt$)
+FROM generate_series(1, 25) \gexec
+
+DROP TABLE tpc_filler1;
+DROP TABLE tpc_filler2;
+DROP TYPE tpc_complex;
+DROP TABLE tpc_filler3;
+DROP TABLE tpc_filler4;
+DROP TABLE tpc_filler5;
+
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+
+SELECT pg_drop_replication_slot('regression_slot');
+
+\c contrib_regression
+DROP DATABASE tuplecid_db;
diff --git a/src/backend/replication/logical/reorderbuffer.c b/src/backend/replication/logical/reorderbuffer.c
index 6aed6346366..1f6c0ac0b33 100644
--- a/src/backend/replication/logical/reorderbuffer.c
+++ b/src/backend/replication/logical/reorderbuffer.c
@@ -3140,6 +3140,50 @@ ReorderBufferAbort(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn,
/* cosmetic... */
txn->final_lsn = lsn;
+ /*
+ * If this is a subtransaction, remove any tuplecid changes it added to
+ * the toplevel transaction's list. Unlike regular changes, tuplecid
+ * changes are always queued on the toplevel transaction (see
+ * ReorderBufferAddNewTupleCids), so they would otherwise survive the
+ * abort of the subtransaction that wrote them. That's wrong: they
+ * describe catalog tuple versions created or killed by the aborted
+ * subtransaction, which never became visible, and keeping them can
+ * corrupt ReorderBufferBuildTupleCidHash() at commit time -- both when
+ * the toplevel transaction later reuses the same tid (the stale entry
+ * collides with the fresh one, breaking the cmin equality assumption)
+ * and when nothing touches the tid again (a stale cmax would make a
+ * still-live tuple look deleted on historic snapshots).
+ *
+ * The association between the subtransaction and its toplevel is
+ * guaranteed to be known here: the subtransaction must have written at
+ * least one WAL record (the xl_heap_new_cid record itself) for any
+ * tuplecid change to exist, and records written inside a subtransaction
+ * carry the toplevel xid, which LogicalDecodingProcessRecord() uses to
+ * assign the subtransaction to its toplevel before dispatching the
+ * record.
+ */
+ if (rbtxn_is_known_subxact(txn))
+ {
+ ReorderBufferTXN *toptxn = rbtxn_get_toptxn(txn);
+ dlist_mutable_iter it;
+
+ dlist_foreach_modify(it, &toptxn->tuplecids)
+ {
+ ReorderBufferChange *change;
+
+ change = dlist_container(ReorderBufferChange, node, it.cur);
+
+ Assert(change->action == REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID);
+
+ if (change->data.tuplecid.subxid == xid)
+ {
+ dlist_delete(&change->node);
+ ReorderBufferFreeChange(rb, change, false);
+ toptxn->ntuplecids--;
+ }
+ }
+ }
+
/* remove potential on-disk data, and deallocate */
ReorderBufferCleanupTXN(rb, txn);
}
@@ -3477,7 +3521,8 @@ void
ReorderBufferAddNewTupleCids(ReorderBuffer *rb, TransactionId xid,
XLogRecPtr lsn, RelFileLocator locator,
ItemPointerData tid, CommandId cmin,
- CommandId cmax, CommandId combocid)
+ CommandId cmax, CommandId combocid,
+ TransactionId subxid)
{
ReorderBufferChange *change = ReorderBufferAllocChange(rb);
ReorderBufferTXN *txn;
@@ -3489,6 +3534,7 @@ ReorderBufferAddNewTupleCids(ReorderBuffer *rb, TransactionId xid,
change->data.tuplecid.cmin = cmin;
change->data.tuplecid.cmax = cmax;
change->data.tuplecid.combocid = combocid;
+ change->data.tuplecid.subxid = subxid;
change->lsn = lsn;
change->txn = txn;
change->action = REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID;
diff --git a/src/backend/replication/logical/snapbuild.c b/src/backend/replication/logical/snapbuild.c
index f60bcf09605..11cc3c08ffd 100644
--- a/src/backend/replication/logical/snapbuild.c
+++ b/src/backend/replication/logical/snapbuild.c
@@ -703,7 +703,7 @@ SnapBuildProcessNewCid(SnapBuild *builder, TransactionId xid,
ReorderBufferAddNewTupleCids(builder->reorder, xlrec->top_xid, lsn,
xlrec->target_locator, xlrec->target_tid,
xlrec->cmin, xlrec->cmax,
- xlrec->combocid);
+ xlrec->combocid, xid);
/* figure out new command id */
if (xlrec->cmin != InvalidCommandId &&
diff --git a/src/include/replication/reorderbuffer.h b/src/include/replication/reorderbuffer.h
index ff825e4b7b2..9d4f01e1d77 100644
--- a/src/include/replication/reorderbuffer.h
+++ b/src/include/replication/reorderbuffer.h
@@ -146,6 +146,11 @@ typedef struct ReorderBufferChange
CommandId cmin;
CommandId cmax;
CommandId combocid;
+ TransactionId subxid; /* xid that wrote the tuplecid record;
+ * differs from the xid of the txn this
+ * change is queued on (always the
+ * toplevel xid) when a subtransaction
+ * modified the catalog */
} tuplecid;
/* Invalidation. */
@@ -751,7 +756,9 @@ extern void ReorderBufferAddNewCommandId(ReorderBuffer *rb, TransactionId xid,
extern void ReorderBufferAddNewTupleCids(ReorderBuffer *rb, TransactionId xid,
XLogRecPtr lsn, RelFileLocator locator,
ItemPointerData tid,
- CommandId cmin, CommandId cmax, CommandId combocid);
+ CommandId cmin, CommandId cmax,
+ CommandId combocid,
+ TransactionId subxid);
extern void ReorderBufferAddInvalidations(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn,
Size nmsgs, SharedInvalidationMessage *msgs);
extern void ReorderBufferAddDistributedInvalidations(ReorderBuffer *rb, TransactionId xid,
--
2.43.0
^ permalink raw reply [nested|flat] 53+ messages in thread
* Bug in logical decoding with DDL and subtransactions
@ 2026-08-12 03:39 Bingshuai Li <lucian1412@outlook.com>
parent: Bingshuai Li <lucian1412@outlook.com>
0 siblings, 1 reply; 53+ messages in thread
From: Bingshuai Li @ 2026-08-12 03:39 UTC (permalink / raw)
To: pgsql-hackers@lists.postgresql.org <pgsql-hackers@lists.postgresql.org>; +Cc: mark.dilger@enterprisedb.com <mark.dilger@enterprisedb.com>
Hi Mark,
Here is a v2 of the abort-time cleanup patch. The code changes are
identical to v1; there are two test-related fixes:
- the new regression test is now also registered in
contrib/test_decoding/meson.build -- v1 added it to the Makefile
only, so Meson builds would not have run it;
- the test no longer hardcodes the regression database name when
reconnecting to drop its scratch database (make and Meson use
different names, which broke the test's final reconnect under
Meson).
Re-verified on master (36f7330b8b2, --enable-cassert): the
test_decoding suite (21 regression + 14 isolation tests, including
tuplecid) passes under both build systems, and the core regression
suite passes (245/245).
One trade-off worth stating explicitly: ReorderBufferAbort() now
scans the toplevel transaction's tuplecids list, an O(N) walk per
aborted subtransaction. I believe that is acceptable for a
backpatchable fix -- catalog-modifying subtransaction aborts are
rare, and each removal shortens the list. The cleaner long-term
design (queue tuplecids on the writing subtransaction and merge at
commit) is a much larger change and should not block this fix.
The test considerations from my previous mail still apply: it is
probabilistic in principle, and it cannot observe the silent
corruption on non-assert builds. And as before, I'm not attached to
either approach -- the goal is to get this fixed for 19.
Thanks,
Bingshuai Li
Attachments:
v2-0001-Fix-stale-tuplecid-records-left-behind-by-aborted.patch (application/octet-stream, 24.9K) download
From 89b9e046b6f0c3022b6fdec521b934919259c614 Mon Sep 17 00:00:00 2001
From: Bingshuai Li <lucian1412@outlook.com>
Date: Wed, 12 Aug 2026 10:17:04 +0800
Subject: [PATCH v2] Fix stale tuplecid records left behind by aborted
subtransactions
Tuplecid changes are always queued on the toplevel transaction, so unlike regular changes they are not dropped when the subtransaction that wrote them aborts. The stale mappings corrupt ReorderBufferBuildTupleCidHash() at commit time: if a later catalog insert reuses the aborted subtransaction's line pointer (made LP_UNUSED by on-access pruning), the fresh record collides with the stale one with a different cmin, tripping the cmin equality assertion; where nothing reuses the tid, a stale cmax makes a still-live catalog tuple look deleted on historic snapshots.
Remove the aborted subtransaction's tuplecid entries in ReorderBufferAbort(). The sub->top association is always known there, because any subtransaction with tuplecid entries must have written WAL (the xl_heap_new_cid record itself), and LogicalDecodingProcessRecord() assigns records carrying a top-level xid to their top-level transaction before dispatching them.
Bug: #19555
Reported-by: Alexander Kozhemyakin <a.kozhemyakin@postgrespro.ru>
Discussion: https://postgr.es/m/CAHgHdKu5e3XY5e90Tuaxq_R4WrKxSV734Q%2BLwo5y39Omp2A-Gg@mail.gmail.com
---
contrib/test_decoding/Makefile | 3 +-
contrib/test_decoding/expected/tuplecid.out | 484 ++++++++++++++++++
contrib/test_decoding/meson.build | 1 +
contrib/test_decoding/sql/tuplecid.sql | 73 +++
.../replication/logical/reorderbuffer.c | 48 +-
src/backend/replication/logical/snapbuild.c | 2 +-
src/include/replication/reorderbuffer.h | 9 +-
7 files changed, 616 insertions(+), 4 deletions(-)
create mode 100644 contrib/test_decoding/expected/tuplecid.out
create mode 100644 contrib/test_decoding/sql/tuplecid.sql
diff --git a/contrib/test_decoding/Makefile b/contrib/test_decoding/Makefile
index 0111124399a..46db0eb3b75 100644
--- a/contrib/test_decoding/Makefile
+++ b/contrib/test_decoding/Makefile
@@ -5,7 +5,8 @@ PGFILEDESC = "test_decoding - example of a logical decoding output plugin"
REGRESS = ddl xact rewrite toast permissions decoding_in_xact \
decoding_into_rel binary prepared replorigin time messages \
- repack spill slot truncate stream stats twophase twophase_stream
+ repack spill slot truncate stream stats twophase twophase_stream \
+ tuplecid
ISOLATION = mxact delayed_startup ondisk_startup concurrent_ddl_dml \
oldest_xmin snapshot_transfer subxact_without_top concurrent_stream \
twophase_snapshot slot_creation_error catalog_change_snapshot \
diff --git a/contrib/test_decoding/expected/tuplecid.out b/contrib/test_decoding/expected/tuplecid.out
new file mode 100644
index 00000000000..83228134106
--- /dev/null
+++ b/contrib/test_decoding/expected/tuplecid.out
@@ -0,0 +1,484 @@
+-- Tests for decoding of transactions in which a catalog-modifying
+-- subtransaction was rolled back (BUG #19555).
+--
+-- When a subtransaction modifies catalog tuples and is then rolled back,
+-- its dead heap-only line pointers can be marked LP_UNUSED by on-access
+-- pruning and reused by later catalog inserts of the same top-level
+-- transaction. The aborted subtransaction's xl_heap_new_cid records must
+-- not be consulted when building the historic snapshot used to decode the
+-- transaction; on unfixed builds they collide with the records of the
+-- reused line pointer and decoding dies with
+-- TRAP: failed Assert("ent->cmin == change->data.tuplecid.cmin")
+-- (or, on non-assert builds, silently uses wrong cmin/cmax mappings).
+--
+-- Whether the collision triggers depends on the physical layout of the
+-- catalog pages, so run in a fresh database where prior tests cannot have
+-- changed it, and loop enough times to leave headroom for layout
+-- differences across versions.
+CREATE DATABASE tuplecid_db;
+-- snapshot the original database name (make and meson use different
+-- names for it) so we can switch back before dropping the test database
+\set prevdb :DBNAME
+\c tuplecid_db
+-- predictability
+SET synchronous_commit = on;
+SELECT 'init' FROM pg_create_logical_replication_slot('regression_slot', 'test_decoding');
+ ?column?
+----------
+ init
+(1 row)
+
+-- Catalog churn to push the catalog pages into a state where on-access
+-- pruning frees the aborted subtransaction's line pointer and the second
+-- ALTER's catalog insert reuses it.
+CREATE TABLE tpc_filler1(f1 char(4));
+CREATE TABLE tpc_filler2(data text);
+INSERT INTO tpc_filler2 VALUES ('before-test');
+CREATE TYPE tpc_complex AS (r float8, i float8);
+CREATE TABLE tpc_filler3 (a int PRIMARY KEY, b text DEFAULT 'Unspecified');
+CREATE TABLE tpc_filler4 (id serial, t text);
+CREATE TABLE tpc_filler5(data text);
+INSERT INTO tpc_filler5 SELECT repeat('a', 2000) || g.i FROM generate_series(1, 1) g(i);
+TRUNCATE table tpc_filler5;
+CHECKPOINT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+ count
+-------
+ 9
+(1 row)
+
+-- Each iteration runs the trigger shape: catalog DDL inside a rolled-back
+-- subtransaction, then the same DDL again, then decode. Unfixed builds
+-- typically die within a handful of iterations.
+SELECT format($fmt$
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+$fmt$)
+FROM generate_series(1, 25) \gexec
+
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+
+ count
+-------
+ 0
+(1 row)
+
+
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+
+ count
+-------
+ 0
+(1 row)
+
+
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+
+ count
+-------
+ 0
+(1 row)
+
+
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+
+ count
+-------
+ 0
+(1 row)
+
+
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+
+ count
+-------
+ 0
+(1 row)
+
+
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+
+ count
+-------
+ 0
+(1 row)
+
+
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+
+ count
+-------
+ 0
+(1 row)
+
+
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+
+ count
+-------
+ 0
+(1 row)
+
+
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+
+ count
+-------
+ 0
+(1 row)
+
+
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+
+ count
+-------
+ 0
+(1 row)
+
+
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+
+ count
+-------
+ 0
+(1 row)
+
+
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+
+ count
+-------
+ 0
+(1 row)
+
+
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+
+ count
+-------
+ 0
+(1 row)
+
+
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+
+ count
+-------
+ 0
+(1 row)
+
+
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+
+ count
+-------
+ 0
+(1 row)
+
+
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+
+ count
+-------
+ 0
+(1 row)
+
+
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+
+ count
+-------
+ 0
+(1 row)
+
+
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+
+ count
+-------
+ 0
+(1 row)
+
+
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+
+ count
+-------
+ 0
+(1 row)
+
+
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+
+ count
+-------
+ 0
+(1 row)
+
+
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+
+ count
+-------
+ 0
+(1 row)
+
+
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+
+ count
+-------
+ 0
+(1 row)
+
+
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+
+ count
+-------
+ 0
+(1 row)
+
+
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+
+ count
+-------
+ 0
+(1 row)
+
+
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+
+ count
+-------
+ 0
+(1 row)
+
+DROP TABLE tpc_filler1;
+DROP TABLE tpc_filler2;
+DROP TYPE tpc_complex;
+DROP TABLE tpc_filler3;
+DROP TABLE tpc_filler4;
+DROP TABLE tpc_filler5;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+ count
+-------
+ 0
+(1 row)
+
+SELECT pg_drop_replication_slot('regression_slot');
+ pg_drop_replication_slot
+--------------------------
+
+(1 row)
+
+\c :prevdb
+DROP DATABASE tuplecid_db;
diff --git a/contrib/test_decoding/meson.build b/contrib/test_decoding/meson.build
index ac655853d26..ac8f13c12ac 100644
--- a/contrib/test_decoding/meson.build
+++ b/contrib/test_decoding/meson.build
@@ -42,6 +42,7 @@ tests += {
'stats',
'twophase',
'twophase_stream',
+ 'tuplecid',
],
'regress_args': [
'--temp-config', files('logical.conf'),
diff --git a/contrib/test_decoding/sql/tuplecid.sql b/contrib/test_decoding/sql/tuplecid.sql
new file mode 100644
index 00000000000..d04dbec790f
--- /dev/null
+++ b/contrib/test_decoding/sql/tuplecid.sql
@@ -0,0 +1,73 @@
+-- Tests for decoding of transactions in which a catalog-modifying
+-- subtransaction was rolled back (BUG #19555).
+--
+-- When a subtransaction modifies catalog tuples and is then rolled back,
+-- its dead heap-only line pointers can be marked LP_UNUSED by on-access
+-- pruning and reused by later catalog inserts of the same top-level
+-- transaction. The aborted subtransaction's xl_heap_new_cid records must
+-- not be consulted when building the historic snapshot used to decode the
+-- transaction; on unfixed builds they collide with the records of the
+-- reused line pointer and decoding dies with
+-- TRAP: failed Assert("ent->cmin == change->data.tuplecid.cmin")
+-- (or, on non-assert builds, silently uses wrong cmin/cmax mappings).
+--
+-- Whether the collision triggers depends on the physical layout of the
+-- catalog pages, so run in a fresh database where prior tests cannot have
+-- changed it, and loop enough times to leave headroom for layout
+-- differences across versions.
+CREATE DATABASE tuplecid_db;
+-- snapshot the original database name (make and meson use different
+-- names for it) so we can switch back before dropping the test database
+\set prevdb :DBNAME
+\c tuplecid_db
+
+-- predictability
+SET synchronous_commit = on;
+
+SELECT 'init' FROM pg_create_logical_replication_slot('regression_slot', 'test_decoding');
+
+-- Catalog churn to push the catalog pages into a state where on-access
+-- pruning frees the aborted subtransaction's line pointer and the second
+-- ALTER's catalog insert reuses it.
+CREATE TABLE tpc_filler1(f1 char(4));
+CREATE TABLE tpc_filler2(data text);
+INSERT INTO tpc_filler2 VALUES ('before-test');
+CREATE TYPE tpc_complex AS (r float8, i float8);
+CREATE TABLE tpc_filler3 (a int PRIMARY KEY, b text DEFAULT 'Unspecified');
+CREATE TABLE tpc_filler4 (id serial, t text);
+CREATE TABLE tpc_filler5(data text);
+INSERT INTO tpc_filler5 SELECT repeat('a', 2000) || g.i FROM generate_series(1, 1) g(i);
+TRUNCATE table tpc_filler5;
+CHECKPOINT;
+
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+
+-- Each iteration runs the trigger shape: catalog DDL inside a rolled-back
+-- subtransaction, then the same DDL again, then decode. Unfixed builds
+-- typically die within a handful of iterations.
+SELECT format($fmt$
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+$fmt$)
+FROM generate_series(1, 25) \gexec
+
+DROP TABLE tpc_filler1;
+DROP TABLE tpc_filler2;
+DROP TYPE tpc_complex;
+DROP TABLE tpc_filler3;
+DROP TABLE tpc_filler4;
+DROP TABLE tpc_filler5;
+
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+
+SELECT pg_drop_replication_slot('regression_slot');
+
+\c :prevdb
+DROP DATABASE tuplecid_db;
diff --git a/src/backend/replication/logical/reorderbuffer.c b/src/backend/replication/logical/reorderbuffer.c
index 6aed6346366..1f6c0ac0b33 100644
--- a/src/backend/replication/logical/reorderbuffer.c
+++ b/src/backend/replication/logical/reorderbuffer.c
@@ -3140,6 +3140,50 @@ ReorderBufferAbort(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn,
/* cosmetic... */
txn->final_lsn = lsn;
+ /*
+ * If this is a subtransaction, remove any tuplecid changes it added to
+ * the toplevel transaction's list. Unlike regular changes, tuplecid
+ * changes are always queued on the toplevel transaction (see
+ * ReorderBufferAddNewTupleCids), so they would otherwise survive the
+ * abort of the subtransaction that wrote them. That's wrong: they
+ * describe catalog tuple versions created or killed by the aborted
+ * subtransaction, which never became visible, and keeping them can
+ * corrupt ReorderBufferBuildTupleCidHash() at commit time -- both when
+ * the toplevel transaction later reuses the same tid (the stale entry
+ * collides with the fresh one, breaking the cmin equality assumption)
+ * and when nothing touches the tid again (a stale cmax would make a
+ * still-live tuple look deleted on historic snapshots).
+ *
+ * The association between the subtransaction and its toplevel is
+ * guaranteed to be known here: the subtransaction must have written at
+ * least one WAL record (the xl_heap_new_cid record itself) for any
+ * tuplecid change to exist, and records written inside a subtransaction
+ * carry the toplevel xid, which LogicalDecodingProcessRecord() uses to
+ * assign the subtransaction to its toplevel before dispatching the
+ * record.
+ */
+ if (rbtxn_is_known_subxact(txn))
+ {
+ ReorderBufferTXN *toptxn = rbtxn_get_toptxn(txn);
+ dlist_mutable_iter it;
+
+ dlist_foreach_modify(it, &toptxn->tuplecids)
+ {
+ ReorderBufferChange *change;
+
+ change = dlist_container(ReorderBufferChange, node, it.cur);
+
+ Assert(change->action == REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID);
+
+ if (change->data.tuplecid.subxid == xid)
+ {
+ dlist_delete(&change->node);
+ ReorderBufferFreeChange(rb, change, false);
+ toptxn->ntuplecids--;
+ }
+ }
+ }
+
/* remove potential on-disk data, and deallocate */
ReorderBufferCleanupTXN(rb, txn);
}
@@ -3477,7 +3521,8 @@ void
ReorderBufferAddNewTupleCids(ReorderBuffer *rb, TransactionId xid,
XLogRecPtr lsn, RelFileLocator locator,
ItemPointerData tid, CommandId cmin,
- CommandId cmax, CommandId combocid)
+ CommandId cmax, CommandId combocid,
+ TransactionId subxid)
{
ReorderBufferChange *change = ReorderBufferAllocChange(rb);
ReorderBufferTXN *txn;
@@ -3489,6 +3534,7 @@ ReorderBufferAddNewTupleCids(ReorderBuffer *rb, TransactionId xid,
change->data.tuplecid.cmin = cmin;
change->data.tuplecid.cmax = cmax;
change->data.tuplecid.combocid = combocid;
+ change->data.tuplecid.subxid = subxid;
change->lsn = lsn;
change->txn = txn;
change->action = REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID;
diff --git a/src/backend/replication/logical/snapbuild.c b/src/backend/replication/logical/snapbuild.c
index f60bcf09605..11cc3c08ffd 100644
--- a/src/backend/replication/logical/snapbuild.c
+++ b/src/backend/replication/logical/snapbuild.c
@@ -703,7 +703,7 @@ SnapBuildProcessNewCid(SnapBuild *builder, TransactionId xid,
ReorderBufferAddNewTupleCids(builder->reorder, xlrec->top_xid, lsn,
xlrec->target_locator, xlrec->target_tid,
xlrec->cmin, xlrec->cmax,
- xlrec->combocid);
+ xlrec->combocid, xid);
/* figure out new command id */
if (xlrec->cmin != InvalidCommandId &&
diff --git a/src/include/replication/reorderbuffer.h b/src/include/replication/reorderbuffer.h
index ff825e4b7b2..9d4f01e1d77 100644
--- a/src/include/replication/reorderbuffer.h
+++ b/src/include/replication/reorderbuffer.h
@@ -146,6 +146,11 @@ typedef struct ReorderBufferChange
CommandId cmin;
CommandId cmax;
CommandId combocid;
+ TransactionId subxid; /* xid that wrote the tuplecid record;
+ * differs from the xid of the txn this
+ * change is queued on (always the
+ * toplevel xid) when a subtransaction
+ * modified the catalog */
} tuplecid;
/* Invalidation. */
@@ -751,7 +756,9 @@ extern void ReorderBufferAddNewCommandId(ReorderBuffer *rb, TransactionId xid,
extern void ReorderBufferAddNewTupleCids(ReorderBuffer *rb, TransactionId xid,
XLogRecPtr lsn, RelFileLocator locator,
ItemPointerData tid,
- CommandId cmin, CommandId cmax, CommandId combocid);
+ CommandId cmin, CommandId cmax,
+ CommandId combocid,
+ TransactionId subxid);
extern void ReorderBufferAddInvalidations(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn,
Size nmsgs, SharedInvalidationMessage *msgs);
extern void ReorderBufferAddDistributedInvalidations(ReorderBuffer *rb, TransactionId xid,
--
2.43.0
^ permalink raw reply [nested|flat] 53+ messages in thread
* Bug in logical decoding with DDL and subtransactions
@ 2026-08-13 02:18 Bingshuai Li <lucian1412@outlook.com>
parent: Bingshuai Li <lucian1412@outlook.com>
0 siblings, 1 reply; 53+ messages in thread
From: Bingshuai Li @ 2026-08-13 02:18 UTC (permalink / raw)
To: pgsql-hackers@lists.postgresql.org <pgsql-hackers@lists.postgresql.org>; +Cc: mark.dilger@enterprisedb.com <mark.dilger@enterprisedb.com>
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
Attachments:
v3-0001-Fix-stale-tuplecid-records-left-behind-by-aborted.patch (application/octet-stream, 25.0K) download
From c72d2fa9a5bbc195d1a92a75d35952940e707287 Mon Sep 17 00:00:00 2001
From: Bingshuai Li <lucian1412@outlook.com>
Date: Thu, 13 Aug 2026 09:36:22 +0800
Subject: [PATCH v3] Fix stale tuplecid records left behind by aborted
subtransactions
Tuplecid changes are always queued on the toplevel transaction, so unlike regular changes they are not dropped when the subtransaction that wrote them aborts. The stale mappings corrupt ReorderBufferBuildTupleCidHash() at commit time: if a later catalog insert reuses the aborted subtransaction's line pointer (made LP_UNUSED by on-access pruning), the fresh record collides with the stale one with a different cmin, tripping the cmin equality assertion; where nothing reuses the tid, a stale cmax makes a still-live catalog tuple look deleted on historic snapshots.
Remove the aborted subtransaction's tuplecid entries in ReorderBufferAbort(). The sub->top association is always known there, because any subtransaction with tuplecid entries must have written WAL (the xl_heap_new_cid record itself), and LogicalDecodingProcessRecord() assigns records carrying a top-level xid to their top-level transaction before dispatching them.
Bug: #19555
Reported-by: Alexander Kozhemyakin <a.kozhemyakin@postgrespro.ru>
Discussion: https://postgr.es/m/CAHgHdKu5e3XY5e90Tuaxq_R4WrKxSV734Q%2BLwo5y39Omp2A-Gg@mail.gmail.com
---
contrib/test_decoding/Makefile | 3 +-
contrib/test_decoding/expected/tuplecid.out | 484 ++++++++++++++++++
contrib/test_decoding/meson.build | 1 +
contrib/test_decoding/sql/tuplecid.sql | 73 +++
.../replication/logical/reorderbuffer.c | 48 +-
src/backend/replication/logical/snapbuild.c | 2 +-
src/include/replication/reorderbuffer.h | 9 +-
7 files changed, 616 insertions(+), 4 deletions(-)
create mode 100644 contrib/test_decoding/expected/tuplecid.out
create mode 100644 contrib/test_decoding/sql/tuplecid.sql
diff --git a/contrib/test_decoding/Makefile b/contrib/test_decoding/Makefile
index 0111124399a..46db0eb3b75 100644
--- a/contrib/test_decoding/Makefile
+++ b/contrib/test_decoding/Makefile
@@ -5,7 +5,8 @@ PGFILEDESC = "test_decoding - example of a logical decoding output plugin"
REGRESS = ddl xact rewrite toast permissions decoding_in_xact \
decoding_into_rel binary prepared replorigin time messages \
- repack spill slot truncate stream stats twophase twophase_stream
+ repack spill slot truncate stream stats twophase twophase_stream \
+ tuplecid
ISOLATION = mxact delayed_startup ondisk_startup concurrent_ddl_dml \
oldest_xmin snapshot_transfer subxact_without_top concurrent_stream \
twophase_snapshot slot_creation_error catalog_change_snapshot \
diff --git a/contrib/test_decoding/expected/tuplecid.out b/contrib/test_decoding/expected/tuplecid.out
new file mode 100644
index 00000000000..b333f3db0c8
--- /dev/null
+++ b/contrib/test_decoding/expected/tuplecid.out
@@ -0,0 +1,484 @@
+-- Tests for decoding of transactions in which a catalog-modifying
+-- subtransaction was rolled back (BUG #19555).
+--
+-- When a subtransaction modifies catalog tuples and is then rolled back,
+-- its dead heap-only line pointers can be marked LP_UNUSED by on-access
+-- pruning and reused by later catalog inserts of the same top-level
+-- transaction. The aborted subtransaction's xl_heap_new_cid records must
+-- not be consulted when building the historic snapshot used to decode the
+-- transaction; on unfixed builds they collide with the records of the
+-- reused line pointer and decoding dies with
+-- TRAP: failed Assert("ent->cmin == change->data.tuplecid.cmin")
+-- (or, on non-assert builds, silently uses wrong cmin/cmax mappings).
+--
+-- Whether the collision triggers depends on the physical layout of the
+-- catalog pages, so run in a fresh database where prior tests cannot have
+-- changed it, and loop enough times to leave headroom for layout
+-- differences across versions.
+CREATE DATABASE regression_tuplecid;
+-- snapshot the original database name (make and meson use different
+-- names for it) so we can switch back before dropping the test database
+\set prevdb :DBNAME
+\c regression_tuplecid
+-- predictability
+SET synchronous_commit = on;
+SELECT 'init' FROM pg_create_logical_replication_slot('regression_slot', 'test_decoding');
+ ?column?
+----------
+ init
+(1 row)
+
+-- Catalog churn to push the catalog pages into a state where on-access
+-- pruning frees the aborted subtransaction's line pointer and the second
+-- ALTER's catalog insert reuses it.
+CREATE TABLE tpc_filler1(f1 char(4));
+CREATE TABLE tpc_filler2(data text);
+INSERT INTO tpc_filler2 VALUES ('before-test');
+CREATE TYPE tpc_complex AS (r float8, i float8);
+CREATE TABLE tpc_filler3 (a int PRIMARY KEY, b text DEFAULT 'Unspecified');
+CREATE TABLE tpc_filler4 (id serial, t text);
+CREATE TABLE tpc_filler5(data text);
+INSERT INTO tpc_filler5 SELECT repeat('a', 2000) || g.i FROM generate_series(1, 1) g(i);
+TRUNCATE table tpc_filler5;
+CHECKPOINT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+ count
+-------
+ 9
+(1 row)
+
+-- Each iteration runs the trigger shape: catalog DDL inside a rolled-back
+-- subtransaction, then the same DDL again, then decode. Unfixed builds
+-- typically die within a handful of iterations.
+SELECT format($fmt$
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+$fmt$)
+FROM generate_series(1, 25) \gexec
+
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+
+ count
+-------
+ 0
+(1 row)
+
+
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+
+ count
+-------
+ 0
+(1 row)
+
+
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+
+ count
+-------
+ 0
+(1 row)
+
+
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+
+ count
+-------
+ 0
+(1 row)
+
+
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+
+ count
+-------
+ 0
+(1 row)
+
+
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+
+ count
+-------
+ 0
+(1 row)
+
+
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+
+ count
+-------
+ 0
+(1 row)
+
+
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+
+ count
+-------
+ 0
+(1 row)
+
+
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+
+ count
+-------
+ 0
+(1 row)
+
+
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+
+ count
+-------
+ 0
+(1 row)
+
+
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+
+ count
+-------
+ 0
+(1 row)
+
+
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+
+ count
+-------
+ 0
+(1 row)
+
+
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+
+ count
+-------
+ 0
+(1 row)
+
+
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+
+ count
+-------
+ 0
+(1 row)
+
+
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+
+ count
+-------
+ 0
+(1 row)
+
+
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+
+ count
+-------
+ 0
+(1 row)
+
+
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+
+ count
+-------
+ 0
+(1 row)
+
+
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+
+ count
+-------
+ 0
+(1 row)
+
+
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+
+ count
+-------
+ 0
+(1 row)
+
+
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+
+ count
+-------
+ 0
+(1 row)
+
+
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+
+ count
+-------
+ 0
+(1 row)
+
+
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+
+ count
+-------
+ 0
+(1 row)
+
+
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+
+ count
+-------
+ 0
+(1 row)
+
+
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+
+ count
+-------
+ 0
+(1 row)
+
+
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+
+ count
+-------
+ 0
+(1 row)
+
+DROP TABLE tpc_filler1;
+DROP TABLE tpc_filler2;
+DROP TYPE tpc_complex;
+DROP TABLE tpc_filler3;
+DROP TABLE tpc_filler4;
+DROP TABLE tpc_filler5;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+ count
+-------
+ 0
+(1 row)
+
+SELECT pg_drop_replication_slot('regression_slot');
+ pg_drop_replication_slot
+--------------------------
+
+(1 row)
+
+\c :prevdb
+DROP DATABASE regression_tuplecid;
diff --git a/contrib/test_decoding/meson.build b/contrib/test_decoding/meson.build
index ac655853d26..ac8f13c12ac 100644
--- a/contrib/test_decoding/meson.build
+++ b/contrib/test_decoding/meson.build
@@ -42,6 +42,7 @@ tests += {
'stats',
'twophase',
'twophase_stream',
+ 'tuplecid',
],
'regress_args': [
'--temp-config', files('logical.conf'),
diff --git a/contrib/test_decoding/sql/tuplecid.sql b/contrib/test_decoding/sql/tuplecid.sql
new file mode 100644
index 00000000000..b3e97f42b91
--- /dev/null
+++ b/contrib/test_decoding/sql/tuplecid.sql
@@ -0,0 +1,73 @@
+-- Tests for decoding of transactions in which a catalog-modifying
+-- subtransaction was rolled back (BUG #19555).
+--
+-- When a subtransaction modifies catalog tuples and is then rolled back,
+-- its dead heap-only line pointers can be marked LP_UNUSED by on-access
+-- pruning and reused by later catalog inserts of the same top-level
+-- transaction. The aborted subtransaction's xl_heap_new_cid records must
+-- not be consulted when building the historic snapshot used to decode the
+-- transaction; on unfixed builds they collide with the records of the
+-- reused line pointer and decoding dies with
+-- TRAP: failed Assert("ent->cmin == change->data.tuplecid.cmin")
+-- (or, on non-assert builds, silently uses wrong cmin/cmax mappings).
+--
+-- Whether the collision triggers depends on the physical layout of the
+-- catalog pages, so run in a fresh database where prior tests cannot have
+-- changed it, and loop enough times to leave headroom for layout
+-- differences across versions.
+CREATE DATABASE regression_tuplecid;
+-- snapshot the original database name (make and meson use different
+-- names for it) so we can switch back before dropping the test database
+\set prevdb :DBNAME
+\c regression_tuplecid
+
+-- predictability
+SET synchronous_commit = on;
+
+SELECT 'init' FROM pg_create_logical_replication_slot('regression_slot', 'test_decoding');
+
+-- Catalog churn to push the catalog pages into a state where on-access
+-- pruning frees the aborted subtransaction's line pointer and the second
+-- ALTER's catalog insert reuses it.
+CREATE TABLE tpc_filler1(f1 char(4));
+CREATE TABLE tpc_filler2(data text);
+INSERT INTO tpc_filler2 VALUES ('before-test');
+CREATE TYPE tpc_complex AS (r float8, i float8);
+CREATE TABLE tpc_filler3 (a int PRIMARY KEY, b text DEFAULT 'Unspecified');
+CREATE TABLE tpc_filler4 (id serial, t text);
+CREATE TABLE tpc_filler5(data text);
+INSERT INTO tpc_filler5 SELECT repeat('a', 2000) || g.i FROM generate_series(1, 1) g(i);
+TRUNCATE table tpc_filler5;
+CHECKPOINT;
+
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+
+-- Each iteration runs the trigger shape: catalog DDL inside a rolled-back
+-- subtransaction, then the same DDL again, then decode. Unfixed builds
+-- typically die within a handful of iterations.
+SELECT format($fmt$
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+$fmt$)
+FROM generate_series(1, 25) \gexec
+
+DROP TABLE tpc_filler1;
+DROP TABLE tpc_filler2;
+DROP TYPE tpc_complex;
+DROP TABLE tpc_filler3;
+DROP TABLE tpc_filler4;
+DROP TABLE tpc_filler5;
+
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+
+SELECT pg_drop_replication_slot('regression_slot');
+
+\c :prevdb
+DROP DATABASE regression_tuplecid;
diff --git a/src/backend/replication/logical/reorderbuffer.c b/src/backend/replication/logical/reorderbuffer.c
index 6aed6346366..1f6c0ac0b33 100644
--- a/src/backend/replication/logical/reorderbuffer.c
+++ b/src/backend/replication/logical/reorderbuffer.c
@@ -3140,6 +3140,50 @@ ReorderBufferAbort(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn,
/* cosmetic... */
txn->final_lsn = lsn;
+ /*
+ * If this is a subtransaction, remove any tuplecid changes it added to
+ * the toplevel transaction's list. Unlike regular changes, tuplecid
+ * changes are always queued on the toplevel transaction (see
+ * ReorderBufferAddNewTupleCids), so they would otherwise survive the
+ * abort of the subtransaction that wrote them. That's wrong: they
+ * describe catalog tuple versions created or killed by the aborted
+ * subtransaction, which never became visible, and keeping them can
+ * corrupt ReorderBufferBuildTupleCidHash() at commit time -- both when
+ * the toplevel transaction later reuses the same tid (the stale entry
+ * collides with the fresh one, breaking the cmin equality assumption)
+ * and when nothing touches the tid again (a stale cmax would make a
+ * still-live tuple look deleted on historic snapshots).
+ *
+ * The association between the subtransaction and its toplevel is
+ * guaranteed to be known here: the subtransaction must have written at
+ * least one WAL record (the xl_heap_new_cid record itself) for any
+ * tuplecid change to exist, and records written inside a subtransaction
+ * carry the toplevel xid, which LogicalDecodingProcessRecord() uses to
+ * assign the subtransaction to its toplevel before dispatching the
+ * record.
+ */
+ if (rbtxn_is_known_subxact(txn))
+ {
+ ReorderBufferTXN *toptxn = rbtxn_get_toptxn(txn);
+ dlist_mutable_iter it;
+
+ dlist_foreach_modify(it, &toptxn->tuplecids)
+ {
+ ReorderBufferChange *change;
+
+ change = dlist_container(ReorderBufferChange, node, it.cur);
+
+ Assert(change->action == REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID);
+
+ if (change->data.tuplecid.subxid == xid)
+ {
+ dlist_delete(&change->node);
+ ReorderBufferFreeChange(rb, change, false);
+ toptxn->ntuplecids--;
+ }
+ }
+ }
+
/* remove potential on-disk data, and deallocate */
ReorderBufferCleanupTXN(rb, txn);
}
@@ -3477,7 +3521,8 @@ void
ReorderBufferAddNewTupleCids(ReorderBuffer *rb, TransactionId xid,
XLogRecPtr lsn, RelFileLocator locator,
ItemPointerData tid, CommandId cmin,
- CommandId cmax, CommandId combocid)
+ CommandId cmax, CommandId combocid,
+ TransactionId subxid)
{
ReorderBufferChange *change = ReorderBufferAllocChange(rb);
ReorderBufferTXN *txn;
@@ -3489,6 +3534,7 @@ ReorderBufferAddNewTupleCids(ReorderBuffer *rb, TransactionId xid,
change->data.tuplecid.cmin = cmin;
change->data.tuplecid.cmax = cmax;
change->data.tuplecid.combocid = combocid;
+ change->data.tuplecid.subxid = subxid;
change->lsn = lsn;
change->txn = txn;
change->action = REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID;
diff --git a/src/backend/replication/logical/snapbuild.c b/src/backend/replication/logical/snapbuild.c
index f60bcf09605..11cc3c08ffd 100644
--- a/src/backend/replication/logical/snapbuild.c
+++ b/src/backend/replication/logical/snapbuild.c
@@ -703,7 +703,7 @@ SnapBuildProcessNewCid(SnapBuild *builder, TransactionId xid,
ReorderBufferAddNewTupleCids(builder->reorder, xlrec->top_xid, lsn,
xlrec->target_locator, xlrec->target_tid,
xlrec->cmin, xlrec->cmax,
- xlrec->combocid);
+ xlrec->combocid, xid);
/* figure out new command id */
if (xlrec->cmin != InvalidCommandId &&
diff --git a/src/include/replication/reorderbuffer.h b/src/include/replication/reorderbuffer.h
index ff825e4b7b2..9d4f01e1d77 100644
--- a/src/include/replication/reorderbuffer.h
+++ b/src/include/replication/reorderbuffer.h
@@ -146,6 +146,11 @@ typedef struct ReorderBufferChange
CommandId cmin;
CommandId cmax;
CommandId combocid;
+ TransactionId subxid; /* xid that wrote the tuplecid record;
+ * differs from the xid of the txn this
+ * change is queued on (always the
+ * toplevel xid) when a subtransaction
+ * modified the catalog */
} tuplecid;
/* Invalidation. */
@@ -751,7 +756,9 @@ extern void ReorderBufferAddNewCommandId(ReorderBuffer *rb, TransactionId xid,
extern void ReorderBufferAddNewTupleCids(ReorderBuffer *rb, TransactionId xid,
XLogRecPtr lsn, RelFileLocator locator,
ItemPointerData tid,
- CommandId cmin, CommandId cmax, CommandId combocid);
+ CommandId cmin, CommandId cmax,
+ CommandId combocid,
+ TransactionId subxid);
extern void ReorderBufferAddInvalidations(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn,
Size nmsgs, SharedInvalidationMessage *msgs);
extern void ReorderBufferAddDistributedInvalidations(ReorderBuffer *rb, TransactionId xid,
--
2.43.0
^ permalink raw reply [nested|flat] 53+ messages in thread
* Bug in logical decoding with DDL and subtransactions
@ 2026-08-15 08:17 Bingshuai Li <lucian1412@outlook.com>
parent: Bingshuai Li <lucian1412@outlook.com>
0 siblings, 1 reply; 53+ messages in thread
From: Bingshuai Li @ 2026-08-15 08:17 UTC (permalink / raw)
To: pgsql-hackers@lists.postgresql.org <pgsql-hackers@lists.postgresql.org>; +Cc: mark.dilger@enterprisedb.com <mark.dilger@enterprisedb.com>; amit.kapila16@gmail.com <amit.kapila16@gmail.com>; sawada.mshk@gmail.com <sawada.mshk@gmail.com>
Hi Mark,
A follow-up on the v3 patch. While re-reviewing it I found a flaw in
the reasoning I gave for the abort-time cleanup. The v4 patch below
fixes the explanation and adds test coverage for the case in point;
the code logic is identical to v3.
1. The flaw in v3's reasoning
v3 claimed the sub->top association is always known in
ReorderBufferAbort(), because any subtransaction with tuplecid entries
must have written WAL, and records written inside a subtransaction
carry the toplevel xid. That argument misses one case: the toplevel
xid is included in a subtransaction's WAL records only once (the
one-time topxid mechanism), and an abort record never carries it. A
decoding pass that starts after the subtransaction's first record --
e.g. when decoding restarts in the middle of a transaction -- never
learns the association, so the v3 cleanup is indeed skipped there. I
confirmed this at runtime with temporary instrumentation:
ReorderBufferAbort() runs with known_subxact = false and the stale
tuplecid entries survive that pass.
2. Why the skipped cleanup stays unobservable
The surviving stale entries still cannot reach
ReorderBufferBuildTupleCidHash(), because of how a slot's restart
point advances:
- SnapBuildProcessRunningXacts() cannot move the restart point past
the oldest in-progress transaction, so a pass that output-decodes
the toplevel commit must have replayed the subtransaction's first
(toplevel-xid-bearing) record; hence it knows the association and
runs the cleanup.
- Conversely, once the restart point has advanced past that record,
the commit was necessarily consumed by an earlier pass. Later
passes skip it via SnapBuildXactNeedsSkip(), and the transaction
state, stale tuplecids included, is dropped without ever building
the hash.
- Starting to decode mid-transaction is unreachable via slot creation
as well: creation waits for a consistent point, which an open
transaction blocks until it ends.
I verified both arms at runtime (cleanup skipped with the commit not
decoded, and association rebuilt with the cleanup running before the
commit decode), and the new test in 3. locks the behavior in. I also
considered recording the tuplecid owner's toplevel xid on the writing
subtransaction's reorder-buffer entry, so the cleanup could always
run; given the invariant above it is not needed, so I left it out to
keep the patch minimal for backpatching.
3. What v4 changes
- reorderbuffer.c: the cleanup itself is byte-for-byte v3; the comment
now states the invariant from 2. instead of the incorrect "always
known" claim.
- New isolation test tuplecid_restart: a transaction with a
rolled-back catalog-modifying subtransaction stays open across two
checkpoints; a concurrent VACUUM deterministically reclaims the
aborted row's line pointer, so the toplevel's later catalog insert
reuses the same tid with a different cmin; the final
pg_logical_slot_get_changes() both replays the transaction across a
restart and output-decodes its commit. On unfixed assert builds it
dies deterministically with the original BUG #19555 assertion in
ReorderBufferBuildTupleCidHash(); with the fix it passes. A second
permutation locks in that slot creation cannot start decoding in the
middle of a transaction.
- The tuplecid regression test is unchanged in behavior; its expected
output is de-noised by hiding the \gexec loop behind
\set ECHO none/all (in-tree convention), 484 -> 199 lines.
Tested on current master (7e6e294e4e4) and REL_19_STABLE
(16742849a3d): contrib/test_decoding passes 21 regression + 15
isolation tests under both make and meson, with asserts on and off,
and with ENFORCE_REGRESSION_TEST_NAME_RESTRICTIONS; the core
regression suite passes (245 tests).
PG19 is still in beta, and I'd like to see this fixed there. Review
would be much appreciated -- in particular of the invariant in 2.,
since that is the piece v3 argued incorrectly (even though the skipped
cleanup turns out to be unobservable).
I've Cc'd Amit and Sawada: section 2 leans on the NEW_CID restart
semantics from 64ff0fe4e8c, so your eyes on it would be especially
valuable.
Thanks,
Bingshuai Li
Attachments:
v4-0001-Fix-stale-tuplecid-records-left-behind-by-aborted.patch (application/octet-stream, 25.0K) download
From b1ab73ebb6668a8e41d0e5d796ebc97dc691946b Mon Sep 17 00:00:00 2001
From: Bingshuai Li <lucian1412@outlook.com>
Date: Sat, 15 Aug 2026 15:41:56 +0800
Subject: [PATCH v4] Fix stale tuplecid records left behind by aborted
subtransactions
Tuplecid changes are always queued on the toplevel transaction, so
unlike regular changes they are not dropped when the subtransaction
that wrote them aborts. The stale mappings corrupt
ReorderBufferBuildTupleCidHash() at commit time: if a later catalog
insert reuses the aborted subtransaction's line pointer (made
LP_UNUSED by on-access pruning or by vacuum), the fresh record
collides with the stale one with a different cmin, tripping the cmin
equality assertion; where nothing reuses the tid, a stale cmax makes
a still-live catalog tuple look deleted on historic snapshots. On
non-assert builds there is no crash, but the stale mappings risk
misjudging historic catalog visibility, which could produce
incorrect decoding output.
Remove the aborted subtransaction's tuplecid entries in
ReorderBufferAbort() when the sub->top association is known. The
association can be unknown in a decoding pass that started after the
subtransaction's first (toplevel-xid-bearing) WAL record, e.g. when
decoding restarted in the middle of the transaction: tuplecid
records are dispatched on the writing subtransaction without
establishing the association, and abort records never carry the
toplevel xid. Skipping the cleanup in that case is safe because of
how a slot's restart point advances: SnapBuildProcessRunningXacts()
cannot move the restart point past the oldest in-progress
transaction, so any pass that output-decodes the toplevel commit
must have replayed the subtransaction's first record and therefore
knows 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 via SnapBuildXactNeedsSkip(), so any
stale tuplecid entries left behind are dropped along with the
transaction state and never reach ReorderBufferBuildTupleCidHash().
Add an isolation test for the restart shape: the transaction stays
open across checkpoints, the aborted subtransaction's catalog insert
is vacuumed away by another session so that the toplevel's later
insert deterministically reuses the same line pointer, and the final
get_changes both replays the transaction across a restart and
output-decodes its commit. On unfixed assert builds the test dies
deterministically with the cmin assertion in
ReorderBufferBuildTupleCidHash(); with the fix it passes. The
existing regression test keeps covering the continuous (no restart)
shape.
Bug: #19555
Reported-by: Alexander Kozhemyakin <a.kozhemyakin@postgrespro.ru>
Based-on-patch-by: Mark Dilger
Discussion: https://postgr.es/m/CAHgHdKu5e3XY5e90Tuaxq_R4WrKxSV734Q%2BLwo5y39Omp2A-Gg@mail.gmail.com
---
contrib/test_decoding/Makefile | 6 +-
contrib/test_decoding/expected/tuplecid.out | 199 ++++++++++++++++++
.../expected/tuplecid_restart.out | 68 ++++++
contrib/test_decoding/meson.build | 2 +
.../test_decoding/specs/tuplecid_restart.spec | 75 +++++++
contrib/test_decoding/sql/tuplecid.sql | 76 +++++++
.../replication/logical/reorderbuffer.c | 55 ++++-
src/backend/replication/logical/snapbuild.c | 2 +-
src/include/replication/reorderbuffer.h | 9 +-
9 files changed, 487 insertions(+), 5 deletions(-)
create mode 100644 contrib/test_decoding/expected/tuplecid.out
create mode 100644 contrib/test_decoding/expected/tuplecid_restart.out
create mode 100644 contrib/test_decoding/specs/tuplecid_restart.spec
create mode 100644 contrib/test_decoding/sql/tuplecid.sql
diff --git a/contrib/test_decoding/Makefile b/contrib/test_decoding/Makefile
index 0111124399a..5876d8d739e 100644
--- a/contrib/test_decoding/Makefile
+++ b/contrib/test_decoding/Makefile
@@ -5,11 +5,13 @@ PGFILEDESC = "test_decoding - example of a logical decoding output plugin"
REGRESS = ddl xact rewrite toast permissions decoding_in_xact \
decoding_into_rel binary prepared replorigin time messages \
- repack spill slot truncate stream stats twophase twophase_stream
+ repack spill slot truncate stream stats twophase twophase_stream \
+ tuplecid
ISOLATION = mxact delayed_startup ondisk_startup concurrent_ddl_dml \
oldest_xmin snapshot_transfer subxact_without_top concurrent_stream \
twophase_snapshot slot_creation_error catalog_change_snapshot \
- skip_snapshot_restore invalidation_distribution parallel_session_origin
+ skip_snapshot_restore invalidation_distribution parallel_session_origin \
+ tuplecid_restart
REGRESS_OPTS = --temp-config $(top_srcdir)/contrib/test_decoding/logical.conf
ISOLATION_OPTS = --temp-config $(top_srcdir)/contrib/test_decoding/logical.conf
diff --git a/contrib/test_decoding/expected/tuplecid.out b/contrib/test_decoding/expected/tuplecid.out
new file mode 100644
index 00000000000..b559dd21bd4
--- /dev/null
+++ b/contrib/test_decoding/expected/tuplecid.out
@@ -0,0 +1,199 @@
+-- Tests for decoding of transactions in which a catalog-modifying
+-- subtransaction was rolled back (BUG #19555).
+--
+-- When a subtransaction modifies catalog tuples and is then rolled back,
+-- its dead heap-only line pointers can be marked LP_UNUSED by on-access
+-- pruning and reused by later catalog inserts of the same top-level
+-- transaction. The aborted subtransaction's xl_heap_new_cid records must
+-- not be consulted when building the historic snapshot used to decode the
+-- transaction; on unfixed builds they collide with the records of the
+-- reused line pointer and decoding dies with
+-- TRAP: failed Assert("ent->cmin == change->data.tuplecid.cmin")
+-- (or, on non-assert builds, silently uses wrong cmin/cmax mappings).
+--
+-- Whether the collision triggers depends on the physical layout of the
+-- catalog pages, so run in a fresh database where prior tests cannot have
+-- changed it, and loop enough times to leave headroom for layout
+-- differences across versions.
+CREATE DATABASE regression_tuplecid;
+-- snapshot the original database name (make and meson use different
+-- names for it) so we can switch back before dropping the test database
+\set prevdb :DBNAME
+\c regression_tuplecid
+-- predictability
+SET synchronous_commit = on;
+SELECT 'init' FROM pg_create_logical_replication_slot('regression_slot', 'test_decoding');
+ ?column?
+----------
+ init
+(1 row)
+
+-- Catalog churn to push the catalog pages into a state where on-access
+-- pruning frees the aborted subtransaction's line pointer and the second
+-- ALTER's catalog insert reuses it.
+CREATE TABLE tpc_filler1(f1 char(4));
+CREATE TABLE tpc_filler2(data text);
+INSERT INTO tpc_filler2 VALUES ('before-test');
+CREATE TYPE tpc_complex AS (r float8, i float8);
+CREATE TABLE tpc_filler3 (a int PRIMARY KEY, b text DEFAULT 'Unspecified');
+CREATE TABLE tpc_filler4 (id serial, t text);
+CREATE TABLE tpc_filler5(data text);
+INSERT INTO tpc_filler5 SELECT repeat('a', 2000) || g.i FROM generate_series(1, 1) g(i);
+TRUNCATE table tpc_filler5;
+CHECKPOINT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+ count
+-------
+ 9
+(1 row)
+
+-- Each iteration runs the trigger shape: catalog DDL inside a rolled-back
+-- subtransaction, then the same DDL again, then decode. Unfixed builds
+-- typically die within a handful of iterations.
+-- (temporarily hide the queries, to avoid flooding the expected output)
+\set ECHO none
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+DROP TABLE tpc_filler1;
+DROP TABLE tpc_filler2;
+DROP TYPE tpc_complex;
+DROP TABLE tpc_filler3;
+DROP TABLE tpc_filler4;
+DROP TABLE tpc_filler5;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+ count
+-------
+ 0
+(1 row)
+
+SELECT pg_drop_replication_slot('regression_slot');
+ pg_drop_replication_slot
+--------------------------
+
+(1 row)
+
+\c :prevdb
+DROP DATABASE regression_tuplecid;
diff --git a/contrib/test_decoding/expected/tuplecid_restart.out b/contrib/test_decoding/expected/tuplecid_restart.out
new file mode 100644
index 00000000000..e5b4bc2543d
--- /dev/null
+++ b/contrib/test_decoding/expected/tuplecid_restart.out
@@ -0,0 +1,68 @@
+Parsed test spec with 3 sessions
+
+starting permutation: s0_init s0_begin s0_savepoint s0_insert s1_checkpoint s1_get_changes s0_catinsert1 s0_rollback s2_vacuum s0_catinsert2 s1_checkpoint s1_get_changes s0_commit s1_get_changes
+step s0_init: SELECT 'init' FROM pg_create_logical_replication_slot('isolation_slot', 'test_decoding');
+?column?
+--------
+init
+(1 row)
+
+step s0_begin: BEGIN;
+step s0_savepoint: SAVEPOINT sp1;
+step s0_insert: INSERT INTO tbl1 VALUES (1);
+step s1_checkpoint: CHECKPOINT;
+step s1_get_changes: SELECT data FROM pg_logical_slot_get_changes('isolation_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%';
+data
+----
+(0 rows)
+
+step s0_catinsert1: INSERT INTO user_cat VALUES (5, 'e');
+step s0_rollback: ROLLBACK TO SAVEPOINT sp1;
+step s2_vacuum: VACUUM user_cat;
+step s0_catinsert2: INSERT INTO user_cat VALUES (6, 'f');
+step s1_checkpoint: CHECKPOINT;
+step s1_get_changes: SELECT data FROM pg_logical_slot_get_changes('isolation_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%';
+data
+----
+(0 rows)
+
+step s0_commit: COMMIT;
+step s1_get_changes: SELECT data FROM pg_logical_slot_get_changes('isolation_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%';
+data
+------
+BEGIN
+COMMIT
+(2 rows)
+
+?column?
+--------
+stop
+(1 row)
+
+
+starting permutation: s0_begin s0_savepoint s0_insert s1_init s0_catinsert1 s0_rollback s2_vacuum s0_catinsert2 s0_commit s1_get_changes
+step s0_begin: BEGIN;
+step s0_savepoint: SAVEPOINT sp1;
+step s0_insert: INSERT INTO tbl1 VALUES (1);
+step s1_init: SELECT 'init' FROM pg_create_logical_replication_slot('isolation_slot', 'test_decoding'); <waiting ...>
+step s0_catinsert1: INSERT INTO user_cat VALUES (5, 'e');
+step s0_rollback: ROLLBACK TO SAVEPOINT sp1;
+step s2_vacuum: VACUUM user_cat;
+step s0_catinsert2: INSERT INTO user_cat VALUES (6, 'f');
+step s0_commit: COMMIT;
+step s1_init: <... completed>
+?column?
+--------
+init
+(1 row)
+
+step s1_get_changes: SELECT data FROM pg_logical_slot_get_changes('isolation_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%';
+data
+----
+(0 rows)
+
+?column?
+--------
+stop
+(1 row)
+
diff --git a/contrib/test_decoding/meson.build b/contrib/test_decoding/meson.build
index ac655853d26..a78024587dc 100644
--- a/contrib/test_decoding/meson.build
+++ b/contrib/test_decoding/meson.build
@@ -42,6 +42,7 @@ tests += {
'stats',
'twophase',
'twophase_stream',
+ 'tuplecid',
],
'regress_args': [
'--temp-config', files('logical.conf'),
@@ -66,6 +67,7 @@ tests += {
'skip_snapshot_restore',
'invalidation_distribution',
'parallel_session_origin',
+ 'tuplecid_restart',
],
'regress_args': [
'--temp-config', files('logical.conf'),
diff --git a/contrib/test_decoding/specs/tuplecid_restart.spec b/contrib/test_decoding/specs/tuplecid_restart.spec
new file mode 100644
index 00000000000..58da414e8b7
--- /dev/null
+++ b/contrib/test_decoding/specs/tuplecid_restart.spec
@@ -0,0 +1,75 @@
+# Test decoding of a transaction in which a catalog-modifying subtransaction
+# was rolled back, where the transaction spans a logical decoding restart
+# point (BUG #19555 restart shape).
+#
+# The tuplecid records written by the aborted subtransaction are queued on the
+# toplevel transaction and must be removed when the subtransaction's abort is
+# decoded; otherwise they collide with the records of the line pointer that
+# gets reused by the toplevel transaction's later catalog insert, failing
+# Assert(ent->cmin == change->data.tuplecid.cmin) in
+# ReorderBufferBuildTupleCidHash() when the commit is decoded.
+#
+# - s0_insert runs in a subtransaction and produces its first WAL record.
+# - s0_catinsert1 generates an xl_heap_new_cid record in that subtransaction.
+# - s0_rollback aborts the subtransaction.
+# - s2_vacuum reclaims the aborted row's line pointer (dead inserts are
+# removed regardless of the xid horizon, so this is deterministic even
+# while the toplevel transaction is still open); s0_catinsert2 then reuses
+# the same tid with a different cmin.
+# - The transaction stays open across both checkpoints, so the final
+# s1_get_changes replays the transaction's records from the first
+# checkpoint and decodes its commit for output, building the tuplecid
+# hash. On unfixed builds the stale tuplecid of the aborted
+# subtransaction collides there with the fresh one.
+setup
+{
+ DROP TABLE IF EXISTS tbl1;
+ DROP TABLE IF EXISTS user_cat;
+ CREATE TABLE tbl1 (val1 integer);
+ -- Four rows of ~1.5kB fill the first heap page to within a few hundred
+ -- bytes, so that vacuuming away the aborted fifth row leaves exactly one
+ -- line pointer for the next insert to reuse.
+ CREATE TABLE user_cat (c1 int, filler char(1500)) WITH (user_catalog_table = true);
+ INSERT INTO user_cat VALUES (1, 'a'), (2, 'b'), (3, 'c'), (4, 'd');
+}
+
+teardown
+{
+ DROP TABLE tbl1;
+ DROP TABLE user_cat;
+ SELECT 'stop' FROM pg_drop_replication_slot('isolation_slot');
+}
+
+session "s0"
+setup { SET synchronous_commit=on; }
+step "s0_init" { SELECT 'init' FROM pg_create_logical_replication_slot('isolation_slot', 'test_decoding'); }
+step "s0_begin" { BEGIN; }
+step "s0_savepoint" { SAVEPOINT sp1; }
+step "s0_insert" { INSERT INTO tbl1 VALUES (1); }
+step "s0_catinsert1" { INSERT INTO user_cat VALUES (5, 'e'); }
+step "s0_rollback" { ROLLBACK TO SAVEPOINT sp1; }
+step "s0_catinsert2" { INSERT INTO user_cat VALUES (6, 'f'); }
+step "s0_commit" { COMMIT; }
+
+session "s1"
+setup { SET synchronous_commit=on; }
+step "s1_init" { SELECT 'init' FROM pg_create_logical_replication_slot('isolation_slot', 'test_decoding'); }
+step "s1_checkpoint" { CHECKPOINT; }
+# The user_cat rows carry ~1.5kB filler values which would flood the expected
+# output; filter them out (decoding still processes them server-side).
+step "s1_get_changes" { SELECT data FROM pg_logical_slot_get_changes('isolation_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%'; }
+
+session "s2"
+setup { SET synchronous_commit=on; }
+step "s2_vacuum" { VACUUM user_cat; }
+
+# The transaction commits only after the second s1_get_changes, so the last
+# s1_get_changes both replays the transaction from the first checkpoint and
+# decodes its commit for output.
+permutation "s0_init" "s0_begin" "s0_savepoint" "s0_insert" "s1_checkpoint" "s1_get_changes" "s0_catinsert1" "s0_rollback" "s2_vacuum" "s0_catinsert2" "s1_checkpoint" "s1_get_changes" "s0_commit" "s1_get_changes"
+
+# Variant with the slot created while the transaction is already open: slot
+# creation waits for a consistent point past the open transaction, so the
+# transaction is never decoded by this slot at all (no output). This locks in
+# the behavior that decoding cannot start in the middle of a transaction.
+permutation "s0_begin" "s0_savepoint" "s0_insert" "s1_init" "s0_catinsert1" "s0_rollback" "s2_vacuum" "s0_catinsert2" "s0_commit" "s1_get_changes"
diff --git a/contrib/test_decoding/sql/tuplecid.sql b/contrib/test_decoding/sql/tuplecid.sql
new file mode 100644
index 00000000000..335fb6d1591
--- /dev/null
+++ b/contrib/test_decoding/sql/tuplecid.sql
@@ -0,0 +1,76 @@
+-- Tests for decoding of transactions in which a catalog-modifying
+-- subtransaction was rolled back (BUG #19555).
+--
+-- When a subtransaction modifies catalog tuples and is then rolled back,
+-- its dead heap-only line pointers can be marked LP_UNUSED by on-access
+-- pruning and reused by later catalog inserts of the same top-level
+-- transaction. The aborted subtransaction's xl_heap_new_cid records must
+-- not be consulted when building the historic snapshot used to decode the
+-- transaction; on unfixed builds they collide with the records of the
+-- reused line pointer and decoding dies with
+-- TRAP: failed Assert("ent->cmin == change->data.tuplecid.cmin")
+-- (or, on non-assert builds, silently uses wrong cmin/cmax mappings).
+--
+-- Whether the collision triggers depends on the physical layout of the
+-- catalog pages, so run in a fresh database where prior tests cannot have
+-- changed it, and loop enough times to leave headroom for layout
+-- differences across versions.
+CREATE DATABASE regression_tuplecid;
+-- snapshot the original database name (make and meson use different
+-- names for it) so we can switch back before dropping the test database
+\set prevdb :DBNAME
+\c regression_tuplecid
+
+-- predictability
+SET synchronous_commit = on;
+
+SELECT 'init' FROM pg_create_logical_replication_slot('regression_slot', 'test_decoding');
+
+-- Catalog churn to push the catalog pages into a state where on-access
+-- pruning frees the aborted subtransaction's line pointer and the second
+-- ALTER's catalog insert reuses it.
+CREATE TABLE tpc_filler1(f1 char(4));
+CREATE TABLE tpc_filler2(data text);
+INSERT INTO tpc_filler2 VALUES ('before-test');
+CREATE TYPE tpc_complex AS (r float8, i float8);
+CREATE TABLE tpc_filler3 (a int PRIMARY KEY, b text DEFAULT 'Unspecified');
+CREATE TABLE tpc_filler4 (id serial, t text);
+CREATE TABLE tpc_filler5(data text);
+INSERT INTO tpc_filler5 SELECT repeat('a', 2000) || g.i FROM generate_series(1, 1) g(i);
+TRUNCATE table tpc_filler5;
+CHECKPOINT;
+
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+
+-- Each iteration runs the trigger shape: catalog DDL inside a rolled-back
+-- subtransaction, then the same DDL again, then decode. Unfixed builds
+-- typically die within a handful of iterations.
+-- (temporarily hide the queries, to avoid flooding the expected output)
+\set ECHO none
+SELECT format($fmt$
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+$fmt$)
+FROM generate_series(1, 25) \gexec
+\set ECHO all
+
+DROP TABLE tpc_filler1;
+DROP TABLE tpc_filler2;
+DROP TYPE tpc_complex;
+DROP TABLE tpc_filler3;
+DROP TABLE tpc_filler4;
+DROP TABLE tpc_filler5;
+
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+
+SELECT pg_drop_replication_slot('regression_slot');
+
+\c :prevdb
+DROP DATABASE regression_tuplecid;
diff --git a/src/backend/replication/logical/reorderbuffer.c b/src/backend/replication/logical/reorderbuffer.c
index 6aed6346366..27dc6a40efc 100644
--- a/src/backend/replication/logical/reorderbuffer.c
+++ b/src/backend/replication/logical/reorderbuffer.c
@@ -3140,6 +3140,57 @@ ReorderBufferAbort(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn,
/* cosmetic... */
txn->final_lsn = lsn;
+ /*
+ * If this is a subtransaction, remove any tuplecid changes it added to
+ * the toplevel transaction's list. Unlike regular changes, tuplecid
+ * changes are always queued on the toplevel transaction (see
+ * ReorderBufferAddNewTupleCids), so they would otherwise survive the
+ * abort of the subtransaction that wrote them. That's wrong: they
+ * describe catalog tuple versions created or killed by the aborted
+ * subtransaction, which never became visible, and keeping them can
+ * corrupt ReorderBufferBuildTupleCidHash() at commit time -- both when
+ * the toplevel transaction later reuses the same tid (the stale entry
+ * collides with the fresh one, breaking the cmin equality assumption)
+ * and when nothing touches the tid again (a stale cmax would make a
+ * still-live tuple look deleted on historic snapshots).
+ *
+ * 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().
+ */
+ if (rbtxn_is_known_subxact(txn))
+ {
+ ReorderBufferTXN *toptxn = rbtxn_get_toptxn(txn);
+ dlist_mutable_iter it;
+
+ dlist_foreach_modify(it, &toptxn->tuplecids)
+ {
+ ReorderBufferChange *change;
+
+ change = dlist_container(ReorderBufferChange, node, it.cur);
+
+ Assert(change->action == REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID);
+
+ if (change->data.tuplecid.subxid == xid)
+ {
+ dlist_delete(&change->node);
+ ReorderBufferFreeChange(rb, change, false);
+ toptxn->ntuplecids--;
+ }
+ }
+ }
+
/* remove potential on-disk data, and deallocate */
ReorderBufferCleanupTXN(rb, txn);
}
@@ -3477,7 +3528,8 @@ void
ReorderBufferAddNewTupleCids(ReorderBuffer *rb, TransactionId xid,
XLogRecPtr lsn, RelFileLocator locator,
ItemPointerData tid, CommandId cmin,
- CommandId cmax, CommandId combocid)
+ CommandId cmax, CommandId combocid,
+ TransactionId subxid)
{
ReorderBufferChange *change = ReorderBufferAllocChange(rb);
ReorderBufferTXN *txn;
@@ -3489,6 +3541,7 @@ ReorderBufferAddNewTupleCids(ReorderBuffer *rb, TransactionId xid,
change->data.tuplecid.cmin = cmin;
change->data.tuplecid.cmax = cmax;
change->data.tuplecid.combocid = combocid;
+ change->data.tuplecid.subxid = subxid;
change->lsn = lsn;
change->txn = txn;
change->action = REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID;
diff --git a/src/backend/replication/logical/snapbuild.c b/src/backend/replication/logical/snapbuild.c
index f60bcf09605..11cc3c08ffd 100644
--- a/src/backend/replication/logical/snapbuild.c
+++ b/src/backend/replication/logical/snapbuild.c
@@ -703,7 +703,7 @@ SnapBuildProcessNewCid(SnapBuild *builder, TransactionId xid,
ReorderBufferAddNewTupleCids(builder->reorder, xlrec->top_xid, lsn,
xlrec->target_locator, xlrec->target_tid,
xlrec->cmin, xlrec->cmax,
- xlrec->combocid);
+ xlrec->combocid, xid);
/* figure out new command id */
if (xlrec->cmin != InvalidCommandId &&
diff --git a/src/include/replication/reorderbuffer.h b/src/include/replication/reorderbuffer.h
index ff825e4b7b2..9d4f01e1d77 100644
--- a/src/include/replication/reorderbuffer.h
+++ b/src/include/replication/reorderbuffer.h
@@ -146,6 +146,11 @@ typedef struct ReorderBufferChange
CommandId cmin;
CommandId cmax;
CommandId combocid;
+ TransactionId subxid; /* xid that wrote the tuplecid record;
+ * differs from the xid of the txn this
+ * change is queued on (always the
+ * toplevel xid) when a subtransaction
+ * modified the catalog */
} tuplecid;
/* Invalidation. */
@@ -751,7 +756,9 @@ extern void ReorderBufferAddNewCommandId(ReorderBuffer *rb, TransactionId xid,
extern void ReorderBufferAddNewTupleCids(ReorderBuffer *rb, TransactionId xid,
XLogRecPtr lsn, RelFileLocator locator,
ItemPointerData tid,
- CommandId cmin, CommandId cmax, CommandId combocid);
+ CommandId cmin, CommandId cmax,
+ CommandId combocid,
+ TransactionId subxid);
extern void ReorderBufferAddInvalidations(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn,
Size nmsgs, SharedInvalidationMessage *msgs);
extern void ReorderBufferAddDistributedInvalidations(ReorderBuffer *rb, TransactionId xid,
--
2.43.0
^ permalink raw reply [nested|flat] 53+ messages in thread
* Re: Bug in logical decoding with DDL and subtransactions
@ 2026-08-27 07:38 Bingshuai Li <lucian1412@outlook.com>
parent: Bingshuai Li <lucian1412@outlook.com>
0 siblings, 1 reply; 53+ messages in thread
From: Bingshuai Li @ 2026-08-27 07:38 UTC (permalink / raw)
To: pgsql-hackers@lists.postgresql.org <pgsql-hackers@lists.postgresql.org>; +Cc: mark.dilger@enterprisedb.com <mark.dilger@enterprisedb.com>; Amit Kapila <amit.kapila16@gmail.com>; Masahiko Sawada <sawada.mshk@gmail.com>; alvherre@kurilemu.de <alvherre@kurilemu.de>
Hi,
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
The point on which I would especially appreciate review is the
restart_lsn invariant described in section 2 of v4: a decoding pass
that does not know the subtransaction's parent cannot output-decode
that transaction's commit, so tuplecid entries left by the skipped
cleanup cannot reach ReorderBufferBuildTupleCidHash().
Could someone comment on whether that reasoning is sound, and whether
the O(N) abort-time cleanup is an acceptable backpatchable fix?
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/
Thanks,
Bingshuai Li
^ permalink raw reply [nested|flat] 53+ messages in thread
* Re: Bug in logical decoding with DDL and subtransactions
@ 2026-09-17 06:00 Alexander Lakhin <exclusion@gmail.com>
parent: Bingshuai Li <lucian1412@outlook.com>
0 siblings, 1 reply; 53+ messages in thread
From: Alexander Lakhin @ 2026-09-17 06:00 UTC (permalink / raw)
To: Bingshuai Li <lucian1412@outlook.com>; pgsql-hackers@lists.postgresql.org <pgsql-hackers@lists.postgresql.org>; +Cc: mark.dilger@enterprisedb.com <mark.dilger@enterprisedb.com>; Amit Kapila <amit.kapila16@gmail.com>; Masahiko Sawada <sawada.mshk@gmail.com>; alvherre@kurilemu.de <alvherre@kurilemu.de>; Andrey Rachitskiy <pl0h0yp1@gmail.com>; a.kozhemyakin@postgrespro.ru
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
^ permalink raw reply [nested|flat] 53+ messages in thread
* Re: Bug in logical decoding with DDL and subtransactions
@ 2026-09-17 08:33 Bingshuai Li <lucian1412@outlook.com>
parent: Alexander Lakhin <exclusion@gmail.com>
0 siblings, 1 reply; 53+ messages in thread
From: Bingshuai Li @ 2026-09-17 08:33 UTC (permalink / raw)
To: pgsql-hackers@lists.postgresql.org <pgsql-hackers@lists.postgresql.org>; +Cc: mark.dilger@enterprisedb.com <mark.dilger@enterprisedb.com>; Amit Kapila <amit.kapila16@gmail.com>; Masahiko Sawada <sawada.mshk@gmail.com>; alvherre@kurilemu.de <alvherre@kurilemu.de>; Alexander Lakhin <exclusion@gmail.com>; Andrey Rachitskiy <pl0h0yp1@gmail.com>; a.kozhemyakin@postgrespro.ru <a.kozhemyakin@postgrespro.ru>
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...
Thanks,
Bingshuai Li
^ permalink raw reply [nested|flat] 53+ messages in thread
* Re: Bug in logical decoding with DDL and subtransactions
@ 2026-09-17 11:16 alvherre@kurilemu.de <alvherre@kurilemu.de>
parent: Bingshuai Li <lucian1412@outlook.com>
0 siblings, 1 reply; 53+ messages in thread
From: alvherre@kurilemu.de @ 2026-09-17 11:16 UTC (permalink / raw)
To: Bingshuai Li <lucian1412@outlook.com>; +Cc: pgsql-hackers@lists.postgresql.org <pgsql-hackers@lists.postgresql.org>; mark.dilger@enterprisedb.com <mark.dilger@enterprisedb.com>; Amit Kapila <amit.kapila16@gmail.com>; Masahiko Sawada <sawada.mshk@gmail.com>; Alexander Lakhin <exclusion@gmail.com>; Andrey Rachitskiy <pl0h0yp1@gmail.com>; a.kozhemyakin@postgrespro.ru <a.kozhemyakin@postgrespro.ru>
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 ...
inline patch 1: /tmp/ReorderBufferChange.patched (+9/-7 lines) download inline-1.patch
--- /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)
^ permalink raw reply [nested|flat] 53+ messages in thread
* Re: Bug in logical decoding with DDL and subtransactions
@ 2026-09-17 16:42 Bingshuai Li <lucian1412@outlook.com>
parent: alvherre@kurilemu.de <alvherre@kurilemu.de>
0 siblings, 2 replies; 53+ messages in thread
From: Bingshuai Li @ 2026-09-17 16:42 UTC (permalink / raw)
To: alvherre@kurilemu.de <alvherre@kurilemu.de>; pgsql-hackers@lists.postgresql.org <pgsql-hackers@lists.postgresql.org>; +Cc: mark.dilger@enterprisedb.com <mark.dilger@enterprisedb.com>; Amit Kapila <amit.kapila16@gmail.com>; Masahiko Sawada <sawada.mshk@gmail.com>; Alexander Lakhin <exclusion@gmail.com>; Andrey Rachitskiy <pl0h0yp1@gmail.com>; a.kozhemyakin@postgrespro.ru <a.kozhemyakin@postgrespro.ru>
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
^ permalink raw reply [nested|flat] 53+ messages in thread
* Re: Bug in logical decoding with DDL and subtransactions
@ 2026-09-18 01:39 Bingshuai Li <lucian1412@outlook.com>
parent: Bingshuai Li <lucian1412@outlook.com>
1 sibling, 1 reply; 53+ messages in thread
From: Bingshuai Li @ 2026-09-18 01:39 UTC (permalink / raw)
To: alvherre@kurilemu.de <alvherre@kurilemu.de>; pgsql-hackers@lists.postgresql.org <pgsql-hackers@lists.postgresql.org>; +Cc: mark.dilger@enterprisedb.com <mark.dilger@enterprisedb.com>; Amit Kapila <amit.kapila16@gmail.com>; Masahiko Sawada <sawada.mshk@gmail.com>; Alexander Lakhin <exclusion@gmail.com>; Andrey Rachitskiy <pl0h0yp1@gmail.com>; a.kozhemyakin@postgrespro.ru <a.kozhemyakin@postgrespro.ru>
Hi Álvaro,
Apologies -- the branch versions did not make it onto that mail.
Here they are.
Thanks,
Bingshuai Li=
Attachments: download all (4 files, .tar.gz)
v4-REL_14_STABLE-0001-Fix-stale-tuplecid-records-left-behind-by-aborted.patch (application/octet-stream, 23.3K) download
From 31658194ac3bb33521e806cbc0893df221a48b95 Mon Sep 17 00:00:00 2001
From: Bingshuai Li <lucian1412@outlook.com>
Date: Fri, 18 Sep 2026 00:32:51 +0800
Subject: [PATCH] Fix stale tuplecid records left behind by aborted
subtransactions
Tuplecid changes are always queued on the toplevel transaction, so
unlike regular changes they are not dropped when the subtransaction
that wrote them aborts. The stale mappings corrupt
ReorderBufferBuildTupleCidHash() at commit time: if a later catalog
insert reuses the aborted subtransaction's line pointer (made
LP_UNUSED by on-access pruning or by vacuum), the fresh record
collides with the stale one with a different cmin, tripping the cmin
equality assertion; where nothing reuses the tid, a stale cmax makes
a still-live catalog tuple look deleted on historic snapshots. On
non-assert builds there is no crash, but the stale mappings risk
misjudging historic catalog visibility, which could produce
incorrect decoding output.
Remove the aborted subtransaction's tuplecid entries in
ReorderBufferAbort() when the sub->top association is known. The
association can be unknown in a decoding pass that started after the
subtransaction's first (toplevel-xid-bearing) WAL record, e.g. when
decoding restarted in the middle of the transaction: tuplecid
records are dispatched on the writing subtransaction without
establishing the association, and abort records never carry the
toplevel xid. Skipping the cleanup in that case is safe because of
how a slot's restart point advances: SnapBuildProcessRunningXacts()
cannot move the restart point past the oldest in-progress
transaction, so any pass that output-decodes the toplevel commit
must have replayed the subtransaction's first record and therefore
knows 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 via SnapBuildXactNeedsSkip(), so any
stale tuplecid entries left behind are dropped along with the
transaction state and never reach ReorderBufferBuildTupleCidHash().
Add an isolation test for the restart shape: the transaction stays
open across checkpoints, the aborted subtransaction's catalog insert
is vacuumed away by another session so that the toplevel's later
insert deterministically reuses the same line pointer, and the final
get_changes both replays the transaction across a restart and
output-decodes its commit. On unfixed assert builds the test dies
deterministically with the cmin assertion in
ReorderBufferBuildTupleCidHash(); with the fix it passes. The
existing regression test keeps covering the continuous (no restart)
shape.
Bug: #19555
Reported-by: Alexander Kozhemyakin <a.kozhemyakin@postgrespro.ru>
Based-on-patch-by: Mark Dilger
Discussion: https://postgr.es/m/CAHgHdKu5e3XY5e90Tuaxq_R4WrKxSV734Q%2BLwo5y39Omp2A-Gg@mail.gmail.com
---
contrib/test_decoding/Makefile | 5 +-
contrib/test_decoding/expected/tuplecid.out | 74 ++++++++++++++++++
.../expected/tuplecid_restart.out | 68 +++++++++++++++++
.../test_decoding/specs/tuplecid_restart.spec | 75 ++++++++++++++++++
contrib/test_decoding/sql/tuplecid.sql | 76 +++++++++++++++++++
.../replication/logical/reorderbuffer.c | 55 +++++++++++++-
src/backend/replication/logical/snapbuild.c | 2 +-
src/include/replication/reorderbuffer.h | 8 +-
8 files changed, 358 insertions(+), 5 deletions(-)
create mode 100644 contrib/test_decoding/expected/tuplecid.out
create mode 100644 contrib/test_decoding/expected/tuplecid_restart.out
create mode 100644 contrib/test_decoding/specs/tuplecid_restart.spec
create mode 100644 contrib/test_decoding/sql/tuplecid.sql
diff --git a/contrib/test_decoding/Makefile b/contrib/test_decoding/Makefile
index 1e5f4f6b1cd..92f0effc0bf 100644
--- a/contrib/test_decoding/Makefile
+++ b/contrib/test_decoding/Makefile
@@ -5,11 +5,12 @@ PGFILEDESC = "test_decoding - example of a logical decoding output plugin"
REGRESS = ddl xact rewrite toast permissions decoding_in_xact \
decoding_into_rel binary prepared replorigin time messages \
- spill slot truncate stream stats twophase twophase_stream
+ spill slot truncate stream stats twophase twophase_stream \
+ tuplecid
ISOLATION = mxact delayed_startup ondisk_startup concurrent_ddl_dml \
oldest_xmin snapshot_transfer subxact_without_top concurrent_stream \
twophase_snapshot catalog_change_snapshot skip_snapshot_restore \
- invalidation_distribution
+ invalidation_distribution tuplecid_restart
REGRESS_OPTS = --temp-config $(top_srcdir)/contrib/test_decoding/logical.conf
ISOLATION_OPTS = --temp-config $(top_srcdir)/contrib/test_decoding/logical.conf
diff --git a/contrib/test_decoding/expected/tuplecid.out b/contrib/test_decoding/expected/tuplecid.out
new file mode 100644
index 00000000000..0105bbb674d
--- /dev/null
+++ b/contrib/test_decoding/expected/tuplecid.out
@@ -0,0 +1,74 @@
+-- Tests for decoding of transactions in which a catalog-modifying
+-- subtransaction was rolled back (BUG #19555).
+--
+-- When a subtransaction modifies catalog tuples and is then rolled back,
+-- its dead heap-only line pointers can be marked LP_UNUSED by on-access
+-- pruning and reused by later catalog inserts of the same top-level
+-- transaction. The aborted subtransaction's xl_heap_new_cid records must
+-- not be consulted when building the historic snapshot used to decode the
+-- transaction; on unfixed builds they collide with the records of the
+-- reused line pointer and decoding dies with
+-- TRAP: failed Assert("ent->cmin == change->data.tuplecid.cmin")
+-- (or, on non-assert builds, silently uses wrong cmin/cmax mappings).
+--
+-- Whether the collision triggers depends on the physical layout of the
+-- catalog pages, so run in a fresh database where prior tests cannot have
+-- changed it, and loop enough times to leave headroom for layout
+-- differences across versions.
+CREATE DATABASE regression_tuplecid;
+-- snapshot the original database name (make and meson use different
+-- names for it) so we can switch back before dropping the test database
+\set prevdb :DBNAME
+\c regression_tuplecid
+-- predictability
+SET synchronous_commit = on;
+SELECT 'init' FROM pg_create_logical_replication_slot('regression_slot', 'test_decoding');
+ ?column?
+----------
+ init
+(1 row)
+
+-- Catalog churn to push the catalog pages into a state where on-access
+-- pruning frees the aborted subtransaction's line pointer and the second
+-- ALTER's catalog insert reuses it.
+CREATE TABLE tpc_filler1(f1 char(4));
+CREATE TABLE tpc_filler2(data text);
+INSERT INTO tpc_filler2 VALUES ('before-test');
+CREATE TYPE tpc_complex AS (r float8, i float8);
+CREATE TABLE tpc_filler3 (a int PRIMARY KEY, b text DEFAULT 'Unspecified');
+CREATE TABLE tpc_filler4 (id serial, t text);
+CREATE TABLE tpc_filler5(data text);
+INSERT INTO tpc_filler5 SELECT repeat('a', 2000) || g.i FROM generate_series(1, 1) g(i);
+TRUNCATE table tpc_filler5;
+CHECKPOINT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+ count
+-------
+ 9
+(1 row)
+
+-- Each iteration runs the trigger shape: catalog DDL inside a rolled-back
+-- subtransaction, then the same DDL again, then decode. Unfixed builds
+-- typically die within a handful of iterations.
+-- (temporarily hide the queries, to avoid flooding the expected output)
+\set ECHO none
+DROP TABLE tpc_filler1;
+DROP TABLE tpc_filler2;
+DROP TYPE tpc_complex;
+DROP TABLE tpc_filler3;
+DROP TABLE tpc_filler4;
+DROP TABLE tpc_filler5;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+ count
+-------
+ 0
+(1 row)
+
+SELECT pg_drop_replication_slot('regression_slot');
+ pg_drop_replication_slot
+--------------------------
+
+(1 row)
+
+\c :prevdb
+DROP DATABASE regression_tuplecid;
diff --git a/contrib/test_decoding/expected/tuplecid_restart.out b/contrib/test_decoding/expected/tuplecid_restart.out
new file mode 100644
index 00000000000..e5b4bc2543d
--- /dev/null
+++ b/contrib/test_decoding/expected/tuplecid_restart.out
@@ -0,0 +1,68 @@
+Parsed test spec with 3 sessions
+
+starting permutation: s0_init s0_begin s0_savepoint s0_insert s1_checkpoint s1_get_changes s0_catinsert1 s0_rollback s2_vacuum s0_catinsert2 s1_checkpoint s1_get_changes s0_commit s1_get_changes
+step s0_init: SELECT 'init' FROM pg_create_logical_replication_slot('isolation_slot', 'test_decoding');
+?column?
+--------
+init
+(1 row)
+
+step s0_begin: BEGIN;
+step s0_savepoint: SAVEPOINT sp1;
+step s0_insert: INSERT INTO tbl1 VALUES (1);
+step s1_checkpoint: CHECKPOINT;
+step s1_get_changes: SELECT data FROM pg_logical_slot_get_changes('isolation_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%';
+data
+----
+(0 rows)
+
+step s0_catinsert1: INSERT INTO user_cat VALUES (5, 'e');
+step s0_rollback: ROLLBACK TO SAVEPOINT sp1;
+step s2_vacuum: VACUUM user_cat;
+step s0_catinsert2: INSERT INTO user_cat VALUES (6, 'f');
+step s1_checkpoint: CHECKPOINT;
+step s1_get_changes: SELECT data FROM pg_logical_slot_get_changes('isolation_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%';
+data
+----
+(0 rows)
+
+step s0_commit: COMMIT;
+step s1_get_changes: SELECT data FROM pg_logical_slot_get_changes('isolation_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%';
+data
+------
+BEGIN
+COMMIT
+(2 rows)
+
+?column?
+--------
+stop
+(1 row)
+
+
+starting permutation: s0_begin s0_savepoint s0_insert s1_init s0_catinsert1 s0_rollback s2_vacuum s0_catinsert2 s0_commit s1_get_changes
+step s0_begin: BEGIN;
+step s0_savepoint: SAVEPOINT sp1;
+step s0_insert: INSERT INTO tbl1 VALUES (1);
+step s1_init: SELECT 'init' FROM pg_create_logical_replication_slot('isolation_slot', 'test_decoding'); <waiting ...>
+step s0_catinsert1: INSERT INTO user_cat VALUES (5, 'e');
+step s0_rollback: ROLLBACK TO SAVEPOINT sp1;
+step s2_vacuum: VACUUM user_cat;
+step s0_catinsert2: INSERT INTO user_cat VALUES (6, 'f');
+step s0_commit: COMMIT;
+step s1_init: <... completed>
+?column?
+--------
+init
+(1 row)
+
+step s1_get_changes: SELECT data FROM pg_logical_slot_get_changes('isolation_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%';
+data
+----
+(0 rows)
+
+?column?
+--------
+stop
+(1 row)
+
diff --git a/contrib/test_decoding/specs/tuplecid_restart.spec b/contrib/test_decoding/specs/tuplecid_restart.spec
new file mode 100644
index 00000000000..58da414e8b7
--- /dev/null
+++ b/contrib/test_decoding/specs/tuplecid_restart.spec
@@ -0,0 +1,75 @@
+# Test decoding of a transaction in which a catalog-modifying subtransaction
+# was rolled back, where the transaction spans a logical decoding restart
+# point (BUG #19555 restart shape).
+#
+# The tuplecid records written by the aborted subtransaction are queued on the
+# toplevel transaction and must be removed when the subtransaction's abort is
+# decoded; otherwise they collide with the records of the line pointer that
+# gets reused by the toplevel transaction's later catalog insert, failing
+# Assert(ent->cmin == change->data.tuplecid.cmin) in
+# ReorderBufferBuildTupleCidHash() when the commit is decoded.
+#
+# - s0_insert runs in a subtransaction and produces its first WAL record.
+# - s0_catinsert1 generates an xl_heap_new_cid record in that subtransaction.
+# - s0_rollback aborts the subtransaction.
+# - s2_vacuum reclaims the aborted row's line pointer (dead inserts are
+# removed regardless of the xid horizon, so this is deterministic even
+# while the toplevel transaction is still open); s0_catinsert2 then reuses
+# the same tid with a different cmin.
+# - The transaction stays open across both checkpoints, so the final
+# s1_get_changes replays the transaction's records from the first
+# checkpoint and decodes its commit for output, building the tuplecid
+# hash. On unfixed builds the stale tuplecid of the aborted
+# subtransaction collides there with the fresh one.
+setup
+{
+ DROP TABLE IF EXISTS tbl1;
+ DROP TABLE IF EXISTS user_cat;
+ CREATE TABLE tbl1 (val1 integer);
+ -- Four rows of ~1.5kB fill the first heap page to within a few hundred
+ -- bytes, so that vacuuming away the aborted fifth row leaves exactly one
+ -- line pointer for the next insert to reuse.
+ CREATE TABLE user_cat (c1 int, filler char(1500)) WITH (user_catalog_table = true);
+ INSERT INTO user_cat VALUES (1, 'a'), (2, 'b'), (3, 'c'), (4, 'd');
+}
+
+teardown
+{
+ DROP TABLE tbl1;
+ DROP TABLE user_cat;
+ SELECT 'stop' FROM pg_drop_replication_slot('isolation_slot');
+}
+
+session "s0"
+setup { SET synchronous_commit=on; }
+step "s0_init" { SELECT 'init' FROM pg_create_logical_replication_slot('isolation_slot', 'test_decoding'); }
+step "s0_begin" { BEGIN; }
+step "s0_savepoint" { SAVEPOINT sp1; }
+step "s0_insert" { INSERT INTO tbl1 VALUES (1); }
+step "s0_catinsert1" { INSERT INTO user_cat VALUES (5, 'e'); }
+step "s0_rollback" { ROLLBACK TO SAVEPOINT sp1; }
+step "s0_catinsert2" { INSERT INTO user_cat VALUES (6, 'f'); }
+step "s0_commit" { COMMIT; }
+
+session "s1"
+setup { SET synchronous_commit=on; }
+step "s1_init" { SELECT 'init' FROM pg_create_logical_replication_slot('isolation_slot', 'test_decoding'); }
+step "s1_checkpoint" { CHECKPOINT; }
+# The user_cat rows carry ~1.5kB filler values which would flood the expected
+# output; filter them out (decoding still processes them server-side).
+step "s1_get_changes" { SELECT data FROM pg_logical_slot_get_changes('isolation_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%'; }
+
+session "s2"
+setup { SET synchronous_commit=on; }
+step "s2_vacuum" { VACUUM user_cat; }
+
+# The transaction commits only after the second s1_get_changes, so the last
+# s1_get_changes both replays the transaction from the first checkpoint and
+# decodes its commit for output.
+permutation "s0_init" "s0_begin" "s0_savepoint" "s0_insert" "s1_checkpoint" "s1_get_changes" "s0_catinsert1" "s0_rollback" "s2_vacuum" "s0_catinsert2" "s1_checkpoint" "s1_get_changes" "s0_commit" "s1_get_changes"
+
+# Variant with the slot created while the transaction is already open: slot
+# creation waits for a consistent point past the open transaction, so the
+# transaction is never decoded by this slot at all (no output). This locks in
+# the behavior that decoding cannot start in the middle of a transaction.
+permutation "s0_begin" "s0_savepoint" "s0_insert" "s1_init" "s0_catinsert1" "s0_rollback" "s2_vacuum" "s0_catinsert2" "s0_commit" "s1_get_changes"
diff --git a/contrib/test_decoding/sql/tuplecid.sql b/contrib/test_decoding/sql/tuplecid.sql
new file mode 100644
index 00000000000..335fb6d1591
--- /dev/null
+++ b/contrib/test_decoding/sql/tuplecid.sql
@@ -0,0 +1,76 @@
+-- Tests for decoding of transactions in which a catalog-modifying
+-- subtransaction was rolled back (BUG #19555).
+--
+-- When a subtransaction modifies catalog tuples and is then rolled back,
+-- its dead heap-only line pointers can be marked LP_UNUSED by on-access
+-- pruning and reused by later catalog inserts of the same top-level
+-- transaction. The aborted subtransaction's xl_heap_new_cid records must
+-- not be consulted when building the historic snapshot used to decode the
+-- transaction; on unfixed builds they collide with the records of the
+-- reused line pointer and decoding dies with
+-- TRAP: failed Assert("ent->cmin == change->data.tuplecid.cmin")
+-- (or, on non-assert builds, silently uses wrong cmin/cmax mappings).
+--
+-- Whether the collision triggers depends on the physical layout of the
+-- catalog pages, so run in a fresh database where prior tests cannot have
+-- changed it, and loop enough times to leave headroom for layout
+-- differences across versions.
+CREATE DATABASE regression_tuplecid;
+-- snapshot the original database name (make and meson use different
+-- names for it) so we can switch back before dropping the test database
+\set prevdb :DBNAME
+\c regression_tuplecid
+
+-- predictability
+SET synchronous_commit = on;
+
+SELECT 'init' FROM pg_create_logical_replication_slot('regression_slot', 'test_decoding');
+
+-- Catalog churn to push the catalog pages into a state where on-access
+-- pruning frees the aborted subtransaction's line pointer and the second
+-- ALTER's catalog insert reuses it.
+CREATE TABLE tpc_filler1(f1 char(4));
+CREATE TABLE tpc_filler2(data text);
+INSERT INTO tpc_filler2 VALUES ('before-test');
+CREATE TYPE tpc_complex AS (r float8, i float8);
+CREATE TABLE tpc_filler3 (a int PRIMARY KEY, b text DEFAULT 'Unspecified');
+CREATE TABLE tpc_filler4 (id serial, t text);
+CREATE TABLE tpc_filler5(data text);
+INSERT INTO tpc_filler5 SELECT repeat('a', 2000) || g.i FROM generate_series(1, 1) g(i);
+TRUNCATE table tpc_filler5;
+CHECKPOINT;
+
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+
+-- Each iteration runs the trigger shape: catalog DDL inside a rolled-back
+-- subtransaction, then the same DDL again, then decode. Unfixed builds
+-- typically die within a handful of iterations.
+-- (temporarily hide the queries, to avoid flooding the expected output)
+\set ECHO none
+SELECT format($fmt$
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+$fmt$)
+FROM generate_series(1, 25) \gexec
+\set ECHO all
+
+DROP TABLE tpc_filler1;
+DROP TABLE tpc_filler2;
+DROP TYPE tpc_complex;
+DROP TABLE tpc_filler3;
+DROP TABLE tpc_filler4;
+DROP TABLE tpc_filler5;
+
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+
+SELECT pg_drop_replication_slot('regression_slot');
+
+\c :prevdb
+DROP DATABASE regression_tuplecid;
diff --git a/src/backend/replication/logical/reorderbuffer.c b/src/backend/replication/logical/reorderbuffer.c
index 0a84443208f..ea38ce5142f 100644
--- a/src/backend/replication/logical/reorderbuffer.c
+++ b/src/backend/replication/logical/reorderbuffer.c
@@ -2943,6 +2943,57 @@ ReorderBufferAbort(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn)
/* cosmetic... */
txn->final_lsn = lsn;
+ /*
+ * If this is a subtransaction, remove any tuplecid changes it added to
+ * the toplevel transaction's list. Unlike regular changes, tuplecid
+ * changes are always queued on the toplevel transaction (see
+ * ReorderBufferAddNewTupleCids), so they would otherwise survive the
+ * abort of the subtransaction that wrote them. That's wrong: they
+ * describe catalog tuple versions created or killed by the aborted
+ * subtransaction, which never became visible, and keeping them can
+ * corrupt ReorderBufferBuildTupleCidHash() at commit time -- both when
+ * the toplevel transaction later reuses the same tid (the stale entry
+ * collides with the fresh one, breaking the cmin equality assumption)
+ * and when nothing touches the tid again (a stale cmax would make a
+ * still-live tuple look deleted on historic snapshots).
+ *
+ * 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().
+ */
+ if (rbtxn_is_known_subxact(txn))
+ {
+ ReorderBufferTXN *toptxn = txn->toptxn;
+ dlist_mutable_iter it;
+
+ dlist_foreach_modify(it, &toptxn->tuplecids)
+ {
+ ReorderBufferChange *change;
+
+ change = dlist_container(ReorderBufferChange, node, it.cur);
+
+ Assert(change->action == REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID);
+
+ if (change->data.tuplecid.subxid == xid)
+ {
+ dlist_delete(&change->node);
+ ReorderBufferReturnChange(rb, change, false);
+ toptxn->ntuplecids--;
+ }
+ }
+ }
+
/* remove potential on-disk data, and deallocate */
ReorderBufferCleanupTXN(rb, txn);
}
@@ -3259,7 +3310,8 @@ void
ReorderBufferAddNewTupleCids(ReorderBuffer *rb, TransactionId xid,
XLogRecPtr lsn, RelFileNode node,
ItemPointerData tid, CommandId cmin,
- CommandId cmax, CommandId combocid)
+ CommandId cmax, CommandId combocid,
+ TransactionId subxid)
{
ReorderBufferChange *change = ReorderBufferGetChange(rb);
ReorderBufferTXN *txn;
@@ -3271,6 +3323,7 @@ ReorderBufferAddNewTupleCids(ReorderBuffer *rb, TransactionId xid,
change->data.tuplecid.cmin = cmin;
change->data.tuplecid.cmax = cmax;
change->data.tuplecid.combocid = combocid;
+ change->data.tuplecid.subxid = subxid;
change->lsn = lsn;
change->txn = txn;
change->action = REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID;
diff --git a/src/backend/replication/logical/snapbuild.c b/src/backend/replication/logical/snapbuild.c
index 67f0b9e089a..53999e62535 100644
--- a/src/backend/replication/logical/snapbuild.c
+++ b/src/backend/replication/logical/snapbuild.c
@@ -823,7 +823,7 @@ SnapBuildProcessNewCid(SnapBuild *builder, TransactionId xid,
ReorderBufferAddNewTupleCids(builder->reorder, xlrec->top_xid, lsn,
xlrec->target_node, xlrec->target_tid,
xlrec->cmin, xlrec->cmax,
- xlrec->combocid);
+ xlrec->combocid, xid);
/* figure out new command id */
if (xlrec->cmin != InvalidCommandId &&
diff --git a/src/include/replication/reorderbuffer.h b/src/include/replication/reorderbuffer.h
index cb633315d04..79498217faf 100644
--- a/src/include/replication/reorderbuffer.h
+++ b/src/include/replication/reorderbuffer.h
@@ -150,6 +150,11 @@ typedef struct ReorderBufferChange
CommandId cmin;
CommandId cmax;
CommandId combocid;
+ TransactionId subxid; /* xid that wrote the tuplecid record;
+ * differs from the xid of the txn this
+ * change is queued on (always the
+ * toplevel xid) when a subtransaction
+ * modified the catalog */
} tuplecid;
/* Invalidation. */
@@ -667,7 +672,8 @@ void ReorderBufferAddNewCommandId(ReorderBuffer *, TransactionId, XLogRecPtr ls
CommandId cid);
void ReorderBufferAddNewTupleCids(ReorderBuffer *, TransactionId, XLogRecPtr lsn,
RelFileNode node, ItemPointerData pt,
- CommandId cmin, CommandId cmax, CommandId combocid);
+ CommandId cmin, CommandId cmax,
+ CommandId combocid, TransactionId subxid);
void ReorderBufferAddInvalidations(ReorderBuffer *, TransactionId, XLogRecPtr lsn,
Size nmsgs, SharedInvalidationMessage *msgs);
void ReorderBufferAddDistributedInvalidations(ReorderBuffer *rb, TransactionId xid,
--
2.43.0
v4-REL_15_STABLE-0001-Fix-stale-tuplecid-records-left-behind-by-aborted.patch (application/octet-stream, 24.2K) download
From 849ba6ef6ca1e881131a93e5a0eb3aca791eef58 Mon Sep 17 00:00:00 2001
From: Bingshuai Li <lucian1412@outlook.com>
Date: Fri, 18 Sep 2026 00:28:40 +0800
Subject: [PATCH] Fix stale tuplecid records left behind by aborted
subtransactions
Tuplecid changes are always queued on the toplevel transaction, so
unlike regular changes they are not dropped when the subtransaction
that wrote them aborts. The stale mappings corrupt
ReorderBufferBuildTupleCidHash() at commit time: if a later catalog
insert reuses the aborted subtransaction's line pointer (made
LP_UNUSED by on-access pruning or by vacuum), the fresh record
collides with the stale one with a different cmin, tripping the cmin
equality assertion; where nothing reuses the tid, a stale cmax makes
a still-live catalog tuple look deleted on historic snapshots. On
non-assert builds there is no crash, but the stale mappings risk
misjudging historic catalog visibility, which could produce
incorrect decoding output.
Remove the aborted subtransaction's tuplecid entries in
ReorderBufferAbort() when the sub->top association is known. The
association can be unknown in a decoding pass that started after the
subtransaction's first (toplevel-xid-bearing) WAL record, e.g. when
decoding restarted in the middle of the transaction: tuplecid
records are dispatched on the writing subtransaction without
establishing the association, and abort records never carry the
toplevel xid. Skipping the cleanup in that case is safe because of
how a slot's restart point advances: SnapBuildProcessRunningXacts()
cannot move the restart point past the oldest in-progress
transaction, so any pass that output-decodes the toplevel commit
must have replayed the subtransaction's first record and therefore
knows 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 via SnapBuildXactNeedsSkip(), so any
stale tuplecid entries left behind are dropped along with the
transaction state and never reach ReorderBufferBuildTupleCidHash().
Add an isolation test for the restart shape: the transaction stays
open across checkpoints, the aborted subtransaction's catalog insert
is vacuumed away by another session so that the toplevel's later
insert deterministically reuses the same line pointer, and the final
get_changes both replays the transaction across a restart and
output-decodes its commit. On unfixed assert builds the test dies
deterministically with the cmin assertion in
ReorderBufferBuildTupleCidHash(); with the fix it passes. The
existing regression test keeps covering the continuous (no restart)
shape.
Bug: #19555
Reported-by: Alexander Kozhemyakin <a.kozhemyakin@postgrespro.ru>
Based-on-patch-by: Mark Dilger
Discussion: https://postgr.es/m/CAHgHdKu5e3XY5e90Tuaxq_R4WrKxSV734Q%2BLwo5y39Omp2A-Gg@mail.gmail.com
---
contrib/test_decoding/Makefile | 5 +-
contrib/test_decoding/expected/tuplecid.out | 199 ++++++++++++++++++
.../expected/tuplecid_restart.out | 68 ++++++
.../test_decoding/specs/tuplecid_restart.spec | 75 +++++++
contrib/test_decoding/sql/tuplecid.sql | 76 +++++++
.../replication/logical/reorderbuffer.c | 55 ++++-
src/backend/replication/logical/snapbuild.c | 2 +-
src/include/replication/reorderbuffer.h | 8 +-
8 files changed, 483 insertions(+), 5 deletions(-)
create mode 100644 contrib/test_decoding/expected/tuplecid.out
create mode 100644 contrib/test_decoding/expected/tuplecid_restart.out
create mode 100644 contrib/test_decoding/specs/tuplecid_restart.spec
create mode 100644 contrib/test_decoding/sql/tuplecid.sql
diff --git a/contrib/test_decoding/Makefile b/contrib/test_decoding/Makefile
index 02e961f4d31..59173fbb2c9 100644
--- a/contrib/test_decoding/Makefile
+++ b/contrib/test_decoding/Makefile
@@ -5,11 +5,12 @@ PGFILEDESC = "test_decoding - example of a logical decoding output plugin"
REGRESS = ddl xact rewrite toast permissions decoding_in_xact \
decoding_into_rel binary prepared replorigin time messages \
- spill slot truncate stream stats twophase twophase_stream
+ spill slot truncate stream stats twophase twophase_stream \
+ tuplecid
ISOLATION = mxact delayed_startup ondisk_startup concurrent_ddl_dml \
oldest_xmin snapshot_transfer subxact_without_top concurrent_stream \
twophase_snapshot slot_creation_error catalog_change_snapshot \
- skip_snapshot_restore invalidation_distribution
+ skip_snapshot_restore invalidation_distribution tuplecid_restart
REGRESS_OPTS = --temp-config $(top_srcdir)/contrib/test_decoding/logical.conf
ISOLATION_OPTS = --temp-config $(top_srcdir)/contrib/test_decoding/logical.conf
diff --git a/contrib/test_decoding/expected/tuplecid.out b/contrib/test_decoding/expected/tuplecid.out
new file mode 100644
index 00000000000..b559dd21bd4
--- /dev/null
+++ b/contrib/test_decoding/expected/tuplecid.out
@@ -0,0 +1,199 @@
+-- Tests for decoding of transactions in which a catalog-modifying
+-- subtransaction was rolled back (BUG #19555).
+--
+-- When a subtransaction modifies catalog tuples and is then rolled back,
+-- its dead heap-only line pointers can be marked LP_UNUSED by on-access
+-- pruning and reused by later catalog inserts of the same top-level
+-- transaction. The aborted subtransaction's xl_heap_new_cid records must
+-- not be consulted when building the historic snapshot used to decode the
+-- transaction; on unfixed builds they collide with the records of the
+-- reused line pointer and decoding dies with
+-- TRAP: failed Assert("ent->cmin == change->data.tuplecid.cmin")
+-- (or, on non-assert builds, silently uses wrong cmin/cmax mappings).
+--
+-- Whether the collision triggers depends on the physical layout of the
+-- catalog pages, so run in a fresh database where prior tests cannot have
+-- changed it, and loop enough times to leave headroom for layout
+-- differences across versions.
+CREATE DATABASE regression_tuplecid;
+-- snapshot the original database name (make and meson use different
+-- names for it) so we can switch back before dropping the test database
+\set prevdb :DBNAME
+\c regression_tuplecid
+-- predictability
+SET synchronous_commit = on;
+SELECT 'init' FROM pg_create_logical_replication_slot('regression_slot', 'test_decoding');
+ ?column?
+----------
+ init
+(1 row)
+
+-- Catalog churn to push the catalog pages into a state where on-access
+-- pruning frees the aborted subtransaction's line pointer and the second
+-- ALTER's catalog insert reuses it.
+CREATE TABLE tpc_filler1(f1 char(4));
+CREATE TABLE tpc_filler2(data text);
+INSERT INTO tpc_filler2 VALUES ('before-test');
+CREATE TYPE tpc_complex AS (r float8, i float8);
+CREATE TABLE tpc_filler3 (a int PRIMARY KEY, b text DEFAULT 'Unspecified');
+CREATE TABLE tpc_filler4 (id serial, t text);
+CREATE TABLE tpc_filler5(data text);
+INSERT INTO tpc_filler5 SELECT repeat('a', 2000) || g.i FROM generate_series(1, 1) g(i);
+TRUNCATE table tpc_filler5;
+CHECKPOINT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+ count
+-------
+ 9
+(1 row)
+
+-- Each iteration runs the trigger shape: catalog DDL inside a rolled-back
+-- subtransaction, then the same DDL again, then decode. Unfixed builds
+-- typically die within a handful of iterations.
+-- (temporarily hide the queries, to avoid flooding the expected output)
+\set ECHO none
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+DROP TABLE tpc_filler1;
+DROP TABLE tpc_filler2;
+DROP TYPE tpc_complex;
+DROP TABLE tpc_filler3;
+DROP TABLE tpc_filler4;
+DROP TABLE tpc_filler5;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+ count
+-------
+ 0
+(1 row)
+
+SELECT pg_drop_replication_slot('regression_slot');
+ pg_drop_replication_slot
+--------------------------
+
+(1 row)
+
+\c :prevdb
+DROP DATABASE regression_tuplecid;
diff --git a/contrib/test_decoding/expected/tuplecid_restart.out b/contrib/test_decoding/expected/tuplecid_restart.out
new file mode 100644
index 00000000000..e5b4bc2543d
--- /dev/null
+++ b/contrib/test_decoding/expected/tuplecid_restart.out
@@ -0,0 +1,68 @@
+Parsed test spec with 3 sessions
+
+starting permutation: s0_init s0_begin s0_savepoint s0_insert s1_checkpoint s1_get_changes s0_catinsert1 s0_rollback s2_vacuum s0_catinsert2 s1_checkpoint s1_get_changes s0_commit s1_get_changes
+step s0_init: SELECT 'init' FROM pg_create_logical_replication_slot('isolation_slot', 'test_decoding');
+?column?
+--------
+init
+(1 row)
+
+step s0_begin: BEGIN;
+step s0_savepoint: SAVEPOINT sp1;
+step s0_insert: INSERT INTO tbl1 VALUES (1);
+step s1_checkpoint: CHECKPOINT;
+step s1_get_changes: SELECT data FROM pg_logical_slot_get_changes('isolation_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%';
+data
+----
+(0 rows)
+
+step s0_catinsert1: INSERT INTO user_cat VALUES (5, 'e');
+step s0_rollback: ROLLBACK TO SAVEPOINT sp1;
+step s2_vacuum: VACUUM user_cat;
+step s0_catinsert2: INSERT INTO user_cat VALUES (6, 'f');
+step s1_checkpoint: CHECKPOINT;
+step s1_get_changes: SELECT data FROM pg_logical_slot_get_changes('isolation_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%';
+data
+----
+(0 rows)
+
+step s0_commit: COMMIT;
+step s1_get_changes: SELECT data FROM pg_logical_slot_get_changes('isolation_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%';
+data
+------
+BEGIN
+COMMIT
+(2 rows)
+
+?column?
+--------
+stop
+(1 row)
+
+
+starting permutation: s0_begin s0_savepoint s0_insert s1_init s0_catinsert1 s0_rollback s2_vacuum s0_catinsert2 s0_commit s1_get_changes
+step s0_begin: BEGIN;
+step s0_savepoint: SAVEPOINT sp1;
+step s0_insert: INSERT INTO tbl1 VALUES (1);
+step s1_init: SELECT 'init' FROM pg_create_logical_replication_slot('isolation_slot', 'test_decoding'); <waiting ...>
+step s0_catinsert1: INSERT INTO user_cat VALUES (5, 'e');
+step s0_rollback: ROLLBACK TO SAVEPOINT sp1;
+step s2_vacuum: VACUUM user_cat;
+step s0_catinsert2: INSERT INTO user_cat VALUES (6, 'f');
+step s0_commit: COMMIT;
+step s1_init: <... completed>
+?column?
+--------
+init
+(1 row)
+
+step s1_get_changes: SELECT data FROM pg_logical_slot_get_changes('isolation_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%';
+data
+----
+(0 rows)
+
+?column?
+--------
+stop
+(1 row)
+
diff --git a/contrib/test_decoding/specs/tuplecid_restart.spec b/contrib/test_decoding/specs/tuplecid_restart.spec
new file mode 100644
index 00000000000..58da414e8b7
--- /dev/null
+++ b/contrib/test_decoding/specs/tuplecid_restart.spec
@@ -0,0 +1,75 @@
+# Test decoding of a transaction in which a catalog-modifying subtransaction
+# was rolled back, where the transaction spans a logical decoding restart
+# point (BUG #19555 restart shape).
+#
+# The tuplecid records written by the aborted subtransaction are queued on the
+# toplevel transaction and must be removed when the subtransaction's abort is
+# decoded; otherwise they collide with the records of the line pointer that
+# gets reused by the toplevel transaction's later catalog insert, failing
+# Assert(ent->cmin == change->data.tuplecid.cmin) in
+# ReorderBufferBuildTupleCidHash() when the commit is decoded.
+#
+# - s0_insert runs in a subtransaction and produces its first WAL record.
+# - s0_catinsert1 generates an xl_heap_new_cid record in that subtransaction.
+# - s0_rollback aborts the subtransaction.
+# - s2_vacuum reclaims the aborted row's line pointer (dead inserts are
+# removed regardless of the xid horizon, so this is deterministic even
+# while the toplevel transaction is still open); s0_catinsert2 then reuses
+# the same tid with a different cmin.
+# - The transaction stays open across both checkpoints, so the final
+# s1_get_changes replays the transaction's records from the first
+# checkpoint and decodes its commit for output, building the tuplecid
+# hash. On unfixed builds the stale tuplecid of the aborted
+# subtransaction collides there with the fresh one.
+setup
+{
+ DROP TABLE IF EXISTS tbl1;
+ DROP TABLE IF EXISTS user_cat;
+ CREATE TABLE tbl1 (val1 integer);
+ -- Four rows of ~1.5kB fill the first heap page to within a few hundred
+ -- bytes, so that vacuuming away the aborted fifth row leaves exactly one
+ -- line pointer for the next insert to reuse.
+ CREATE TABLE user_cat (c1 int, filler char(1500)) WITH (user_catalog_table = true);
+ INSERT INTO user_cat VALUES (1, 'a'), (2, 'b'), (3, 'c'), (4, 'd');
+}
+
+teardown
+{
+ DROP TABLE tbl1;
+ DROP TABLE user_cat;
+ SELECT 'stop' FROM pg_drop_replication_slot('isolation_slot');
+}
+
+session "s0"
+setup { SET synchronous_commit=on; }
+step "s0_init" { SELECT 'init' FROM pg_create_logical_replication_slot('isolation_slot', 'test_decoding'); }
+step "s0_begin" { BEGIN; }
+step "s0_savepoint" { SAVEPOINT sp1; }
+step "s0_insert" { INSERT INTO tbl1 VALUES (1); }
+step "s0_catinsert1" { INSERT INTO user_cat VALUES (5, 'e'); }
+step "s0_rollback" { ROLLBACK TO SAVEPOINT sp1; }
+step "s0_catinsert2" { INSERT INTO user_cat VALUES (6, 'f'); }
+step "s0_commit" { COMMIT; }
+
+session "s1"
+setup { SET synchronous_commit=on; }
+step "s1_init" { SELECT 'init' FROM pg_create_logical_replication_slot('isolation_slot', 'test_decoding'); }
+step "s1_checkpoint" { CHECKPOINT; }
+# The user_cat rows carry ~1.5kB filler values which would flood the expected
+# output; filter them out (decoding still processes them server-side).
+step "s1_get_changes" { SELECT data FROM pg_logical_slot_get_changes('isolation_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%'; }
+
+session "s2"
+setup { SET synchronous_commit=on; }
+step "s2_vacuum" { VACUUM user_cat; }
+
+# The transaction commits only after the second s1_get_changes, so the last
+# s1_get_changes both replays the transaction from the first checkpoint and
+# decodes its commit for output.
+permutation "s0_init" "s0_begin" "s0_savepoint" "s0_insert" "s1_checkpoint" "s1_get_changes" "s0_catinsert1" "s0_rollback" "s2_vacuum" "s0_catinsert2" "s1_checkpoint" "s1_get_changes" "s0_commit" "s1_get_changes"
+
+# Variant with the slot created while the transaction is already open: slot
+# creation waits for a consistent point past the open transaction, so the
+# transaction is never decoded by this slot at all (no output). This locks in
+# the behavior that decoding cannot start in the middle of a transaction.
+permutation "s0_begin" "s0_savepoint" "s0_insert" "s1_init" "s0_catinsert1" "s0_rollback" "s2_vacuum" "s0_catinsert2" "s0_commit" "s1_get_changes"
diff --git a/contrib/test_decoding/sql/tuplecid.sql b/contrib/test_decoding/sql/tuplecid.sql
new file mode 100644
index 00000000000..335fb6d1591
--- /dev/null
+++ b/contrib/test_decoding/sql/tuplecid.sql
@@ -0,0 +1,76 @@
+-- Tests for decoding of transactions in which a catalog-modifying
+-- subtransaction was rolled back (BUG #19555).
+--
+-- When a subtransaction modifies catalog tuples and is then rolled back,
+-- its dead heap-only line pointers can be marked LP_UNUSED by on-access
+-- pruning and reused by later catalog inserts of the same top-level
+-- transaction. The aborted subtransaction's xl_heap_new_cid records must
+-- not be consulted when building the historic snapshot used to decode the
+-- transaction; on unfixed builds they collide with the records of the
+-- reused line pointer and decoding dies with
+-- TRAP: failed Assert("ent->cmin == change->data.tuplecid.cmin")
+-- (or, on non-assert builds, silently uses wrong cmin/cmax mappings).
+--
+-- Whether the collision triggers depends on the physical layout of the
+-- catalog pages, so run in a fresh database where prior tests cannot have
+-- changed it, and loop enough times to leave headroom for layout
+-- differences across versions.
+CREATE DATABASE regression_tuplecid;
+-- snapshot the original database name (make and meson use different
+-- names for it) so we can switch back before dropping the test database
+\set prevdb :DBNAME
+\c regression_tuplecid
+
+-- predictability
+SET synchronous_commit = on;
+
+SELECT 'init' FROM pg_create_logical_replication_slot('regression_slot', 'test_decoding');
+
+-- Catalog churn to push the catalog pages into a state where on-access
+-- pruning frees the aborted subtransaction's line pointer and the second
+-- ALTER's catalog insert reuses it.
+CREATE TABLE tpc_filler1(f1 char(4));
+CREATE TABLE tpc_filler2(data text);
+INSERT INTO tpc_filler2 VALUES ('before-test');
+CREATE TYPE tpc_complex AS (r float8, i float8);
+CREATE TABLE tpc_filler3 (a int PRIMARY KEY, b text DEFAULT 'Unspecified');
+CREATE TABLE tpc_filler4 (id serial, t text);
+CREATE TABLE tpc_filler5(data text);
+INSERT INTO tpc_filler5 SELECT repeat('a', 2000) || g.i FROM generate_series(1, 1) g(i);
+TRUNCATE table tpc_filler5;
+CHECKPOINT;
+
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+
+-- Each iteration runs the trigger shape: catalog DDL inside a rolled-back
+-- subtransaction, then the same DDL again, then decode. Unfixed builds
+-- typically die within a handful of iterations.
+-- (temporarily hide the queries, to avoid flooding the expected output)
+\set ECHO none
+SELECT format($fmt$
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+$fmt$)
+FROM generate_series(1, 25) \gexec
+\set ECHO all
+
+DROP TABLE tpc_filler1;
+DROP TABLE tpc_filler2;
+DROP TYPE tpc_complex;
+DROP TABLE tpc_filler3;
+DROP TABLE tpc_filler4;
+DROP TABLE tpc_filler5;
+
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+
+SELECT pg_drop_replication_slot('regression_slot');
+
+\c :prevdb
+DROP DATABASE regression_tuplecid;
diff --git a/src/backend/replication/logical/reorderbuffer.c b/src/backend/replication/logical/reorderbuffer.c
index ca2b5f117c2..f1a546ae826 100644
--- a/src/backend/replication/logical/reorderbuffer.c
+++ b/src/backend/replication/logical/reorderbuffer.c
@@ -2947,6 +2947,57 @@ ReorderBufferAbort(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn)
/* cosmetic... */
txn->final_lsn = lsn;
+ /*
+ * If this is a subtransaction, remove any tuplecid changes it added to
+ * the toplevel transaction's list. Unlike regular changes, tuplecid
+ * changes are always queued on the toplevel transaction (see
+ * ReorderBufferAddNewTupleCids), so they would otherwise survive the
+ * abort of the subtransaction that wrote them. That's wrong: they
+ * describe catalog tuple versions created or killed by the aborted
+ * subtransaction, which never became visible, and keeping them can
+ * corrupt ReorderBufferBuildTupleCidHash() at commit time -- both when
+ * the toplevel transaction later reuses the same tid (the stale entry
+ * collides with the fresh one, breaking the cmin equality assumption)
+ * and when nothing touches the tid again (a stale cmax would make a
+ * still-live tuple look deleted on historic snapshots).
+ *
+ * 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().
+ */
+ if (rbtxn_is_known_subxact(txn))
+ {
+ ReorderBufferTXN *toptxn = txn->toptxn;
+ dlist_mutable_iter it;
+
+ dlist_foreach_modify(it, &toptxn->tuplecids)
+ {
+ ReorderBufferChange *change;
+
+ change = dlist_container(ReorderBufferChange, node, it.cur);
+
+ Assert(change->action == REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID);
+
+ if (change->data.tuplecid.subxid == xid)
+ {
+ dlist_delete(&change->node);
+ ReorderBufferReturnChange(rb, change, false);
+ toptxn->ntuplecids--;
+ }
+ }
+ }
+
/* remove potential on-disk data, and deallocate */
ReorderBufferCleanupTXN(rb, txn);
}
@@ -3263,7 +3314,8 @@ void
ReorderBufferAddNewTupleCids(ReorderBuffer *rb, TransactionId xid,
XLogRecPtr lsn, RelFileNode node,
ItemPointerData tid, CommandId cmin,
- CommandId cmax, CommandId combocid)
+ CommandId cmax, CommandId combocid,
+ TransactionId subxid)
{
ReorderBufferChange *change = ReorderBufferGetChange(rb);
ReorderBufferTXN *txn;
@@ -3275,6 +3327,7 @@ ReorderBufferAddNewTupleCids(ReorderBuffer *rb, TransactionId xid,
change->data.tuplecid.cmin = cmin;
change->data.tuplecid.cmax = cmax;
change->data.tuplecid.combocid = combocid;
+ change->data.tuplecid.subxid = subxid;
change->lsn = lsn;
change->txn = txn;
change->action = REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID;
diff --git a/src/backend/replication/logical/snapbuild.c b/src/backend/replication/logical/snapbuild.c
index 2dd4782f086..f6c00b63de9 100644
--- a/src/backend/replication/logical/snapbuild.c
+++ b/src/backend/replication/logical/snapbuild.c
@@ -832,7 +832,7 @@ SnapBuildProcessNewCid(SnapBuild *builder, TransactionId xid,
ReorderBufferAddNewTupleCids(builder->reorder, xlrec->top_xid, lsn,
xlrec->target_node, xlrec->target_tid,
xlrec->cmin, xlrec->cmax,
- xlrec->combocid);
+ xlrec->combocid, xid);
/* figure out new command id */
if (xlrec->cmin != InvalidCommandId &&
diff --git a/src/include/replication/reorderbuffer.h b/src/include/replication/reorderbuffer.h
index af154587618..22594f9034e 100644
--- a/src/include/replication/reorderbuffer.h
+++ b/src/include/replication/reorderbuffer.h
@@ -150,6 +150,11 @@ typedef struct ReorderBufferChange
CommandId cmin;
CommandId cmax;
CommandId combocid;
+ TransactionId subxid; /* xid that wrote the tuplecid record;
+ * differs from the xid of the txn this
+ * change is queued on (always the
+ * toplevel xid) when a subtransaction
+ * modified the catalog */
} tuplecid;
/* Invalidation. */
@@ -671,7 +676,8 @@ extern void ReorderBufferAddNewCommandId(ReorderBuffer *, TransactionId, XLogRec
CommandId cid);
extern void ReorderBufferAddNewTupleCids(ReorderBuffer *, TransactionId, XLogRecPtr lsn,
RelFileNode node, ItemPointerData pt,
- CommandId cmin, CommandId cmax, CommandId combocid);
+ CommandId cmin, CommandId cmax,
+ CommandId combocid, TransactionId subxid);
extern void ReorderBufferAddInvalidations(ReorderBuffer *, TransactionId, XLogRecPtr lsn,
Size nmsgs, SharedInvalidationMessage *msgs);
extern void ReorderBufferAddDistributedInvalidations(ReorderBuffer *rb, TransactionId xid,
--
2.43.0
v4-REL_16_STABLE-0001-Fix-stale-tuplecid-records-left-behind-by-aborted.patch (application/octet-stream, 24.9K) download
From 92b4de87e60fa4d48f17c55ffab4a0909c8f8d96 Mon Sep 17 00:00:00 2001
From: Bingshuai Li <lucian1412@outlook.com>
Date: Fri, 18 Sep 2026 00:16:25 +0800
Subject: [PATCH] Fix stale tuplecid records left behind by aborted
subtransactions
Tuplecid changes are always queued on the toplevel transaction, so
unlike regular changes they are not dropped when the subtransaction
that wrote them aborts. The stale mappings corrupt
ReorderBufferBuildTupleCidHash() at commit time: if a later catalog
insert reuses the aborted subtransaction's line pointer (made
LP_UNUSED by on-access pruning or by vacuum), the fresh record
collides with the stale one with a different cmin, tripping the cmin
equality assertion; where nothing reuses the tid, a stale cmax makes
a still-live catalog tuple look deleted on historic snapshots. On
non-assert builds there is no crash, but the stale mappings risk
misjudging historic catalog visibility, which could produce
incorrect decoding output.
Remove the aborted subtransaction's tuplecid entries in
ReorderBufferAbort() when the sub->top association is known. The
association can be unknown in a decoding pass that started after the
subtransaction's first (toplevel-xid-bearing) WAL record, e.g. when
decoding restarted in the middle of the transaction: tuplecid
records are dispatched on the writing subtransaction without
establishing the association, and abort records never carry the
toplevel xid. Skipping the cleanup in that case is safe because of
how a slot's restart point advances: SnapBuildProcessRunningXacts()
cannot move the restart point past the oldest in-progress
transaction, so any pass that output-decodes the toplevel commit
must have replayed the subtransaction's first record and therefore
knows 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 via SnapBuildXactNeedsSkip(), so any
stale tuplecid entries left behind are dropped along with the
transaction state and never reach ReorderBufferBuildTupleCidHash().
Add an isolation test for the restart shape: the transaction stays
open across checkpoints, the aborted subtransaction's catalog insert
is vacuumed away by another session so that the toplevel's later
insert deterministically reuses the same line pointer, and the final
get_changes both replays the transaction across a restart and
output-decodes its commit. On unfixed assert builds the test dies
deterministically with the cmin assertion in
ReorderBufferBuildTupleCidHash(); with the fix it passes. The
existing regression test keeps covering the continuous (no restart)
shape.
Bug: #19555
Reported-by: Alexander Kozhemyakin <a.kozhemyakin@postgrespro.ru>
Based-on-patch-by: Mark Dilger
Discussion: https://postgr.es/m/CAHgHdKu5e3XY5e90Tuaxq_R4WrKxSV734Q%2BLwo5y39Omp2A-Gg@mail.gmail.com
---
contrib/test_decoding/Makefile | 6 +-
contrib/test_decoding/expected/tuplecid.out | 199 ++++++++++++++++++
.../expected/tuplecid_restart.out | 68 ++++++
contrib/test_decoding/meson.build | 2 +
.../test_decoding/specs/tuplecid_restart.spec | 75 +++++++
contrib/test_decoding/sql/tuplecid.sql | 76 +++++++
.../replication/logical/reorderbuffer.c | 55 ++++-
src/backend/replication/logical/snapbuild.c | 2 +-
src/include/replication/reorderbuffer.h | 9 +-
9 files changed, 487 insertions(+), 5 deletions(-)
create mode 100644 contrib/test_decoding/expected/tuplecid.out
create mode 100644 contrib/test_decoding/expected/tuplecid_restart.out
create mode 100644 contrib/test_decoding/specs/tuplecid_restart.spec
create mode 100644 contrib/test_decoding/sql/tuplecid.sql
diff --git a/contrib/test_decoding/Makefile b/contrib/test_decoding/Makefile
index 02e961f4d31..06fa37178ae 100644
--- a/contrib/test_decoding/Makefile
+++ b/contrib/test_decoding/Makefile
@@ -5,11 +5,13 @@ PGFILEDESC = "test_decoding - example of a logical decoding output plugin"
REGRESS = ddl xact rewrite toast permissions decoding_in_xact \
decoding_into_rel binary prepared replorigin time messages \
- spill slot truncate stream stats twophase twophase_stream
+ spill slot truncate stream stats twophase twophase_stream \
+ tuplecid
ISOLATION = mxact delayed_startup ondisk_startup concurrent_ddl_dml \
oldest_xmin snapshot_transfer subxact_without_top concurrent_stream \
twophase_snapshot slot_creation_error catalog_change_snapshot \
- skip_snapshot_restore invalidation_distribution
+ skip_snapshot_restore invalidation_distribution \
+ tuplecid_restart
REGRESS_OPTS = --temp-config $(top_srcdir)/contrib/test_decoding/logical.conf
ISOLATION_OPTS = --temp-config $(top_srcdir)/contrib/test_decoding/logical.conf
diff --git a/contrib/test_decoding/expected/tuplecid.out b/contrib/test_decoding/expected/tuplecid.out
new file mode 100644
index 00000000000..b559dd21bd4
--- /dev/null
+++ b/contrib/test_decoding/expected/tuplecid.out
@@ -0,0 +1,199 @@
+-- Tests for decoding of transactions in which a catalog-modifying
+-- subtransaction was rolled back (BUG #19555).
+--
+-- When a subtransaction modifies catalog tuples and is then rolled back,
+-- its dead heap-only line pointers can be marked LP_UNUSED by on-access
+-- pruning and reused by later catalog inserts of the same top-level
+-- transaction. The aborted subtransaction's xl_heap_new_cid records must
+-- not be consulted when building the historic snapshot used to decode the
+-- transaction; on unfixed builds they collide with the records of the
+-- reused line pointer and decoding dies with
+-- TRAP: failed Assert("ent->cmin == change->data.tuplecid.cmin")
+-- (or, on non-assert builds, silently uses wrong cmin/cmax mappings).
+--
+-- Whether the collision triggers depends on the physical layout of the
+-- catalog pages, so run in a fresh database where prior tests cannot have
+-- changed it, and loop enough times to leave headroom for layout
+-- differences across versions.
+CREATE DATABASE regression_tuplecid;
+-- snapshot the original database name (make and meson use different
+-- names for it) so we can switch back before dropping the test database
+\set prevdb :DBNAME
+\c regression_tuplecid
+-- predictability
+SET synchronous_commit = on;
+SELECT 'init' FROM pg_create_logical_replication_slot('regression_slot', 'test_decoding');
+ ?column?
+----------
+ init
+(1 row)
+
+-- Catalog churn to push the catalog pages into a state where on-access
+-- pruning frees the aborted subtransaction's line pointer and the second
+-- ALTER's catalog insert reuses it.
+CREATE TABLE tpc_filler1(f1 char(4));
+CREATE TABLE tpc_filler2(data text);
+INSERT INTO tpc_filler2 VALUES ('before-test');
+CREATE TYPE tpc_complex AS (r float8, i float8);
+CREATE TABLE tpc_filler3 (a int PRIMARY KEY, b text DEFAULT 'Unspecified');
+CREATE TABLE tpc_filler4 (id serial, t text);
+CREATE TABLE tpc_filler5(data text);
+INSERT INTO tpc_filler5 SELECT repeat('a', 2000) || g.i FROM generate_series(1, 1) g(i);
+TRUNCATE table tpc_filler5;
+CHECKPOINT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+ count
+-------
+ 9
+(1 row)
+
+-- Each iteration runs the trigger shape: catalog DDL inside a rolled-back
+-- subtransaction, then the same DDL again, then decode. Unfixed builds
+-- typically die within a handful of iterations.
+-- (temporarily hide the queries, to avoid flooding the expected output)
+\set ECHO none
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+DROP TABLE tpc_filler1;
+DROP TABLE tpc_filler2;
+DROP TYPE tpc_complex;
+DROP TABLE tpc_filler3;
+DROP TABLE tpc_filler4;
+DROP TABLE tpc_filler5;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+ count
+-------
+ 0
+(1 row)
+
+SELECT pg_drop_replication_slot('regression_slot');
+ pg_drop_replication_slot
+--------------------------
+
+(1 row)
+
+\c :prevdb
+DROP DATABASE regression_tuplecid;
diff --git a/contrib/test_decoding/expected/tuplecid_restart.out b/contrib/test_decoding/expected/tuplecid_restart.out
new file mode 100644
index 00000000000..e5b4bc2543d
--- /dev/null
+++ b/contrib/test_decoding/expected/tuplecid_restart.out
@@ -0,0 +1,68 @@
+Parsed test spec with 3 sessions
+
+starting permutation: s0_init s0_begin s0_savepoint s0_insert s1_checkpoint s1_get_changes s0_catinsert1 s0_rollback s2_vacuum s0_catinsert2 s1_checkpoint s1_get_changes s0_commit s1_get_changes
+step s0_init: SELECT 'init' FROM pg_create_logical_replication_slot('isolation_slot', 'test_decoding');
+?column?
+--------
+init
+(1 row)
+
+step s0_begin: BEGIN;
+step s0_savepoint: SAVEPOINT sp1;
+step s0_insert: INSERT INTO tbl1 VALUES (1);
+step s1_checkpoint: CHECKPOINT;
+step s1_get_changes: SELECT data FROM pg_logical_slot_get_changes('isolation_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%';
+data
+----
+(0 rows)
+
+step s0_catinsert1: INSERT INTO user_cat VALUES (5, 'e');
+step s0_rollback: ROLLBACK TO SAVEPOINT sp1;
+step s2_vacuum: VACUUM user_cat;
+step s0_catinsert2: INSERT INTO user_cat VALUES (6, 'f');
+step s1_checkpoint: CHECKPOINT;
+step s1_get_changes: SELECT data FROM pg_logical_slot_get_changes('isolation_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%';
+data
+----
+(0 rows)
+
+step s0_commit: COMMIT;
+step s1_get_changes: SELECT data FROM pg_logical_slot_get_changes('isolation_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%';
+data
+------
+BEGIN
+COMMIT
+(2 rows)
+
+?column?
+--------
+stop
+(1 row)
+
+
+starting permutation: s0_begin s0_savepoint s0_insert s1_init s0_catinsert1 s0_rollback s2_vacuum s0_catinsert2 s0_commit s1_get_changes
+step s0_begin: BEGIN;
+step s0_savepoint: SAVEPOINT sp1;
+step s0_insert: INSERT INTO tbl1 VALUES (1);
+step s1_init: SELECT 'init' FROM pg_create_logical_replication_slot('isolation_slot', 'test_decoding'); <waiting ...>
+step s0_catinsert1: INSERT INTO user_cat VALUES (5, 'e');
+step s0_rollback: ROLLBACK TO SAVEPOINT sp1;
+step s2_vacuum: VACUUM user_cat;
+step s0_catinsert2: INSERT INTO user_cat VALUES (6, 'f');
+step s0_commit: COMMIT;
+step s1_init: <... completed>
+?column?
+--------
+init
+(1 row)
+
+step s1_get_changes: SELECT data FROM pg_logical_slot_get_changes('isolation_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%';
+data
+----
+(0 rows)
+
+?column?
+--------
+stop
+(1 row)
+
diff --git a/contrib/test_decoding/meson.build b/contrib/test_decoding/meson.build
index 3c99ba472c0..c92067035ee 100644
--- a/contrib/test_decoding/meson.build
+++ b/contrib/test_decoding/meson.build
@@ -41,6 +41,7 @@ tests += {
'stats',
'twophase',
'twophase_stream',
+ 'tuplecid',
],
'regress_args': [
'--temp-config', files('logical.conf'),
@@ -64,6 +65,7 @@ tests += {
'slot_creation_error',
'skip_snapshot_restore',
'invalidation_distribution',
+ 'tuplecid_restart',
],
'regress_args': [
'--temp-config', files('logical.conf'),
diff --git a/contrib/test_decoding/specs/tuplecid_restart.spec b/contrib/test_decoding/specs/tuplecid_restart.spec
new file mode 100644
index 00000000000..58da414e8b7
--- /dev/null
+++ b/contrib/test_decoding/specs/tuplecid_restart.spec
@@ -0,0 +1,75 @@
+# Test decoding of a transaction in which a catalog-modifying subtransaction
+# was rolled back, where the transaction spans a logical decoding restart
+# point (BUG #19555 restart shape).
+#
+# The tuplecid records written by the aborted subtransaction are queued on the
+# toplevel transaction and must be removed when the subtransaction's abort is
+# decoded; otherwise they collide with the records of the line pointer that
+# gets reused by the toplevel transaction's later catalog insert, failing
+# Assert(ent->cmin == change->data.tuplecid.cmin) in
+# ReorderBufferBuildTupleCidHash() when the commit is decoded.
+#
+# - s0_insert runs in a subtransaction and produces its first WAL record.
+# - s0_catinsert1 generates an xl_heap_new_cid record in that subtransaction.
+# - s0_rollback aborts the subtransaction.
+# - s2_vacuum reclaims the aborted row's line pointer (dead inserts are
+# removed regardless of the xid horizon, so this is deterministic even
+# while the toplevel transaction is still open); s0_catinsert2 then reuses
+# the same tid with a different cmin.
+# - The transaction stays open across both checkpoints, so the final
+# s1_get_changes replays the transaction's records from the first
+# checkpoint and decodes its commit for output, building the tuplecid
+# hash. On unfixed builds the stale tuplecid of the aborted
+# subtransaction collides there with the fresh one.
+setup
+{
+ DROP TABLE IF EXISTS tbl1;
+ DROP TABLE IF EXISTS user_cat;
+ CREATE TABLE tbl1 (val1 integer);
+ -- Four rows of ~1.5kB fill the first heap page to within a few hundred
+ -- bytes, so that vacuuming away the aborted fifth row leaves exactly one
+ -- line pointer for the next insert to reuse.
+ CREATE TABLE user_cat (c1 int, filler char(1500)) WITH (user_catalog_table = true);
+ INSERT INTO user_cat VALUES (1, 'a'), (2, 'b'), (3, 'c'), (4, 'd');
+}
+
+teardown
+{
+ DROP TABLE tbl1;
+ DROP TABLE user_cat;
+ SELECT 'stop' FROM pg_drop_replication_slot('isolation_slot');
+}
+
+session "s0"
+setup { SET synchronous_commit=on; }
+step "s0_init" { SELECT 'init' FROM pg_create_logical_replication_slot('isolation_slot', 'test_decoding'); }
+step "s0_begin" { BEGIN; }
+step "s0_savepoint" { SAVEPOINT sp1; }
+step "s0_insert" { INSERT INTO tbl1 VALUES (1); }
+step "s0_catinsert1" { INSERT INTO user_cat VALUES (5, 'e'); }
+step "s0_rollback" { ROLLBACK TO SAVEPOINT sp1; }
+step "s0_catinsert2" { INSERT INTO user_cat VALUES (6, 'f'); }
+step "s0_commit" { COMMIT; }
+
+session "s1"
+setup { SET synchronous_commit=on; }
+step "s1_init" { SELECT 'init' FROM pg_create_logical_replication_slot('isolation_slot', 'test_decoding'); }
+step "s1_checkpoint" { CHECKPOINT; }
+# The user_cat rows carry ~1.5kB filler values which would flood the expected
+# output; filter them out (decoding still processes them server-side).
+step "s1_get_changes" { SELECT data FROM pg_logical_slot_get_changes('isolation_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%'; }
+
+session "s2"
+setup { SET synchronous_commit=on; }
+step "s2_vacuum" { VACUUM user_cat; }
+
+# The transaction commits only after the second s1_get_changes, so the last
+# s1_get_changes both replays the transaction from the first checkpoint and
+# decodes its commit for output.
+permutation "s0_init" "s0_begin" "s0_savepoint" "s0_insert" "s1_checkpoint" "s1_get_changes" "s0_catinsert1" "s0_rollback" "s2_vacuum" "s0_catinsert2" "s1_checkpoint" "s1_get_changes" "s0_commit" "s1_get_changes"
+
+# Variant with the slot created while the transaction is already open: slot
+# creation waits for a consistent point past the open transaction, so the
+# transaction is never decoded by this slot at all (no output). This locks in
+# the behavior that decoding cannot start in the middle of a transaction.
+permutation "s0_begin" "s0_savepoint" "s0_insert" "s1_init" "s0_catinsert1" "s0_rollback" "s2_vacuum" "s0_catinsert2" "s0_commit" "s1_get_changes"
diff --git a/contrib/test_decoding/sql/tuplecid.sql b/contrib/test_decoding/sql/tuplecid.sql
new file mode 100644
index 00000000000..335fb6d1591
--- /dev/null
+++ b/contrib/test_decoding/sql/tuplecid.sql
@@ -0,0 +1,76 @@
+-- Tests for decoding of transactions in which a catalog-modifying
+-- subtransaction was rolled back (BUG #19555).
+--
+-- When a subtransaction modifies catalog tuples and is then rolled back,
+-- its dead heap-only line pointers can be marked LP_UNUSED by on-access
+-- pruning and reused by later catalog inserts of the same top-level
+-- transaction. The aborted subtransaction's xl_heap_new_cid records must
+-- not be consulted when building the historic snapshot used to decode the
+-- transaction; on unfixed builds they collide with the records of the
+-- reused line pointer and decoding dies with
+-- TRAP: failed Assert("ent->cmin == change->data.tuplecid.cmin")
+-- (or, on non-assert builds, silently uses wrong cmin/cmax mappings).
+--
+-- Whether the collision triggers depends on the physical layout of the
+-- catalog pages, so run in a fresh database where prior tests cannot have
+-- changed it, and loop enough times to leave headroom for layout
+-- differences across versions.
+CREATE DATABASE regression_tuplecid;
+-- snapshot the original database name (make and meson use different
+-- names for it) so we can switch back before dropping the test database
+\set prevdb :DBNAME
+\c regression_tuplecid
+
+-- predictability
+SET synchronous_commit = on;
+
+SELECT 'init' FROM pg_create_logical_replication_slot('regression_slot', 'test_decoding');
+
+-- Catalog churn to push the catalog pages into a state where on-access
+-- pruning frees the aborted subtransaction's line pointer and the second
+-- ALTER's catalog insert reuses it.
+CREATE TABLE tpc_filler1(f1 char(4));
+CREATE TABLE tpc_filler2(data text);
+INSERT INTO tpc_filler2 VALUES ('before-test');
+CREATE TYPE tpc_complex AS (r float8, i float8);
+CREATE TABLE tpc_filler3 (a int PRIMARY KEY, b text DEFAULT 'Unspecified');
+CREATE TABLE tpc_filler4 (id serial, t text);
+CREATE TABLE tpc_filler5(data text);
+INSERT INTO tpc_filler5 SELECT repeat('a', 2000) || g.i FROM generate_series(1, 1) g(i);
+TRUNCATE table tpc_filler5;
+CHECKPOINT;
+
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+
+-- Each iteration runs the trigger shape: catalog DDL inside a rolled-back
+-- subtransaction, then the same DDL again, then decode. Unfixed builds
+-- typically die within a handful of iterations.
+-- (temporarily hide the queries, to avoid flooding the expected output)
+\set ECHO none
+SELECT format($fmt$
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+$fmt$)
+FROM generate_series(1, 25) \gexec
+\set ECHO all
+
+DROP TABLE tpc_filler1;
+DROP TABLE tpc_filler2;
+DROP TYPE tpc_complex;
+DROP TABLE tpc_filler3;
+DROP TABLE tpc_filler4;
+DROP TABLE tpc_filler5;
+
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+
+SELECT pg_drop_replication_slot('regression_slot');
+
+\c :prevdb
+DROP DATABASE regression_tuplecid;
diff --git a/src/backend/replication/logical/reorderbuffer.c b/src/backend/replication/logical/reorderbuffer.c
index cd0e83284ac..e43cd16db3b 100644
--- a/src/backend/replication/logical/reorderbuffer.c
+++ b/src/backend/replication/logical/reorderbuffer.c
@@ -2985,6 +2985,57 @@ ReorderBufferAbort(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn,
/* cosmetic... */
txn->final_lsn = lsn;
+ /*
+ * If this is a subtransaction, remove any tuplecid changes it added to
+ * the toplevel transaction's list. Unlike regular changes, tuplecid
+ * changes are always queued on the toplevel transaction (see
+ * ReorderBufferAddNewTupleCids), so they would otherwise survive the
+ * abort of the subtransaction that wrote them. That's wrong: they
+ * describe catalog tuple versions created or killed by the aborted
+ * subtransaction, which never became visible, and keeping them can
+ * corrupt ReorderBufferBuildTupleCidHash() at commit time -- both when
+ * the toplevel transaction later reuses the same tid (the stale entry
+ * collides with the fresh one, breaking the cmin equality assumption)
+ * and when nothing touches the tid again (a stale cmax would make a
+ * still-live tuple look deleted on historic snapshots).
+ *
+ * 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().
+ */
+ if (rbtxn_is_known_subxact(txn))
+ {
+ ReorderBufferTXN *toptxn = rbtxn_get_toptxn(txn);
+ dlist_mutable_iter it;
+
+ dlist_foreach_modify(it, &toptxn->tuplecids)
+ {
+ ReorderBufferChange *change;
+
+ change = dlist_container(ReorderBufferChange, node, it.cur);
+
+ Assert(change->action == REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID);
+
+ if (change->data.tuplecid.subxid == xid)
+ {
+ dlist_delete(&change->node);
+ ReorderBufferReturnChange(rb, change, false);
+ toptxn->ntuplecids--;
+ }
+ }
+ }
+
/* remove potential on-disk data, and deallocate */
ReorderBufferCleanupTXN(rb, txn);
}
@@ -3297,7 +3348,8 @@ void
ReorderBufferAddNewTupleCids(ReorderBuffer *rb, TransactionId xid,
XLogRecPtr lsn, RelFileLocator locator,
ItemPointerData tid, CommandId cmin,
- CommandId cmax, CommandId combocid)
+ CommandId cmax, CommandId combocid,
+ TransactionId subxid)
{
ReorderBufferChange *change = ReorderBufferGetChange(rb);
ReorderBufferTXN *txn;
@@ -3309,6 +3361,7 @@ ReorderBufferAddNewTupleCids(ReorderBuffer *rb, TransactionId xid,
change->data.tuplecid.cmin = cmin;
change->data.tuplecid.cmax = cmax;
change->data.tuplecid.combocid = combocid;
+ change->data.tuplecid.subxid = subxid;
change->lsn = lsn;
change->txn = txn;
change->action = REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID;
diff --git a/src/backend/replication/logical/snapbuild.c b/src/backend/replication/logical/snapbuild.c
index 6c49dda75b6..c91ff8f8af1 100644
--- a/src/backend/replication/logical/snapbuild.c
+++ b/src/backend/replication/logical/snapbuild.c
@@ -825,7 +825,7 @@ SnapBuildProcessNewCid(SnapBuild *builder, TransactionId xid,
ReorderBufferAddNewTupleCids(builder->reorder, xlrec->top_xid, lsn,
xlrec->target_locator, xlrec->target_tid,
xlrec->cmin, xlrec->cmax,
- xlrec->combocid);
+ xlrec->combocid, xid);
/* figure out new command id */
if (xlrec->cmin != InvalidCommandId &&
diff --git a/src/include/replication/reorderbuffer.h b/src/include/replication/reorderbuffer.h
index 1606e0ea007..613198e4ebb 100644
--- a/src/include/replication/reorderbuffer.h
+++ b/src/include/replication/reorderbuffer.h
@@ -159,6 +159,11 @@ typedef struct ReorderBufferChange
CommandId cmin;
CommandId cmax;
CommandId combocid;
+ TransactionId subxid; /* xid that wrote the tuplecid record;
+ * differs from the xid of the txn this
+ * change is queued on (always the
+ * toplevel xid) when a subtransaction
+ * modified the catalog */
} tuplecid;
/* Invalidation. */
@@ -738,7 +743,9 @@ extern void ReorderBufferAddNewCommandId(ReorderBuffer *rb, TransactionId xid,
extern void ReorderBufferAddNewTupleCids(ReorderBuffer *rb, TransactionId xid,
XLogRecPtr lsn, RelFileLocator locator,
ItemPointerData tid,
- CommandId cmin, CommandId cmax, CommandId combocid);
+ CommandId cmin, CommandId cmax,
+ CommandId combocid,
+ TransactionId subxid);
extern void ReorderBufferAddInvalidations(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn,
Size nmsgs, SharedInvalidationMessage *msgs);
extern void ReorderBufferAddDistributedInvalidations(ReorderBuffer *rb, TransactionId xid,
--
2.43.0
v4-REL_17_STABLE-0001-Fix-stale-tuplecid-records-left-behind-by-aborted.patch (application/octet-stream, 24.9K) download
From 9ed920de2526896e187ff91cdb4a89afa164f2f5 Mon Sep 17 00:00:00 2001
From: Bingshuai Li <lucian1412@outlook.com>
Date: Fri, 18 Sep 2026 00:15:24 +0800
Subject: [PATCH] Fix stale tuplecid records left behind by aborted
subtransactions
Tuplecid changes are always queued on the toplevel transaction, so
unlike regular changes they are not dropped when the subtransaction
that wrote them aborts. The stale mappings corrupt
ReorderBufferBuildTupleCidHash() at commit time: if a later catalog
insert reuses the aborted subtransaction's line pointer (made
LP_UNUSED by on-access pruning or by vacuum), the fresh record
collides with the stale one with a different cmin, tripping the cmin
equality assertion; where nothing reuses the tid, a stale cmax makes
a still-live catalog tuple look deleted on historic snapshots. On
non-assert builds there is no crash, but the stale mappings risk
misjudging historic catalog visibility, which could produce
incorrect decoding output.
Remove the aborted subtransaction's tuplecid entries in
ReorderBufferAbort() when the sub->top association is known. The
association can be unknown in a decoding pass that started after the
subtransaction's first (toplevel-xid-bearing) WAL record, e.g. when
decoding restarted in the middle of the transaction: tuplecid
records are dispatched on the writing subtransaction without
establishing the association, and abort records never carry the
toplevel xid. Skipping the cleanup in that case is safe because of
how a slot's restart point advances: SnapBuildProcessRunningXacts()
cannot move the restart point past the oldest in-progress
transaction, so any pass that output-decodes the toplevel commit
must have replayed the subtransaction's first record and therefore
knows 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 via SnapBuildXactNeedsSkip(), so any
stale tuplecid entries left behind are dropped along with the
transaction state and never reach ReorderBufferBuildTupleCidHash().
Add an isolation test for the restart shape: the transaction stays
open across checkpoints, the aborted subtransaction's catalog insert
is vacuumed away by another session so that the toplevel's later
insert deterministically reuses the same line pointer, and the final
get_changes both replays the transaction across a restart and
output-decodes its commit. On unfixed assert builds the test dies
deterministically with the cmin assertion in
ReorderBufferBuildTupleCidHash(); with the fix it passes. The
existing regression test keeps covering the continuous (no restart)
shape.
Bug: #19555
Reported-by: Alexander Kozhemyakin <a.kozhemyakin@postgrespro.ru>
Based-on-patch-by: Mark Dilger
Discussion: https://postgr.es/m/CAHgHdKu5e3XY5e90Tuaxq_R4WrKxSV734Q%2BLwo5y39Omp2A-Gg@mail.gmail.com
---
contrib/test_decoding/Makefile | 6 +-
contrib/test_decoding/expected/tuplecid.out | 199 ++++++++++++++++++
.../expected/tuplecid_restart.out | 68 ++++++
contrib/test_decoding/meson.build | 2 +
.../test_decoding/specs/tuplecid_restart.spec | 75 +++++++
contrib/test_decoding/sql/tuplecid.sql | 76 +++++++
.../replication/logical/reorderbuffer.c | 55 ++++-
src/backend/replication/logical/snapbuild.c | 2 +-
src/include/replication/reorderbuffer.h | 9 +-
9 files changed, 487 insertions(+), 5 deletions(-)
create mode 100644 contrib/test_decoding/expected/tuplecid.out
create mode 100644 contrib/test_decoding/expected/tuplecid_restart.out
create mode 100644 contrib/test_decoding/specs/tuplecid_restart.spec
create mode 100644 contrib/test_decoding/sql/tuplecid.sql
diff --git a/contrib/test_decoding/Makefile b/contrib/test_decoding/Makefile
index 02e961f4d31..06fa37178ae 100644
--- a/contrib/test_decoding/Makefile
+++ b/contrib/test_decoding/Makefile
@@ -5,11 +5,13 @@ PGFILEDESC = "test_decoding - example of a logical decoding output plugin"
REGRESS = ddl xact rewrite toast permissions decoding_in_xact \
decoding_into_rel binary prepared replorigin time messages \
- spill slot truncate stream stats twophase twophase_stream
+ spill slot truncate stream stats twophase twophase_stream \
+ tuplecid
ISOLATION = mxact delayed_startup ondisk_startup concurrent_ddl_dml \
oldest_xmin snapshot_transfer subxact_without_top concurrent_stream \
twophase_snapshot slot_creation_error catalog_change_snapshot \
- skip_snapshot_restore invalidation_distribution
+ skip_snapshot_restore invalidation_distribution \
+ tuplecid_restart
REGRESS_OPTS = --temp-config $(top_srcdir)/contrib/test_decoding/logical.conf
ISOLATION_OPTS = --temp-config $(top_srcdir)/contrib/test_decoding/logical.conf
diff --git a/contrib/test_decoding/expected/tuplecid.out b/contrib/test_decoding/expected/tuplecid.out
new file mode 100644
index 00000000000..b559dd21bd4
--- /dev/null
+++ b/contrib/test_decoding/expected/tuplecid.out
@@ -0,0 +1,199 @@
+-- Tests for decoding of transactions in which a catalog-modifying
+-- subtransaction was rolled back (BUG #19555).
+--
+-- When a subtransaction modifies catalog tuples and is then rolled back,
+-- its dead heap-only line pointers can be marked LP_UNUSED by on-access
+-- pruning and reused by later catalog inserts of the same top-level
+-- transaction. The aborted subtransaction's xl_heap_new_cid records must
+-- not be consulted when building the historic snapshot used to decode the
+-- transaction; on unfixed builds they collide with the records of the
+-- reused line pointer and decoding dies with
+-- TRAP: failed Assert("ent->cmin == change->data.tuplecid.cmin")
+-- (or, on non-assert builds, silently uses wrong cmin/cmax mappings).
+--
+-- Whether the collision triggers depends on the physical layout of the
+-- catalog pages, so run in a fresh database where prior tests cannot have
+-- changed it, and loop enough times to leave headroom for layout
+-- differences across versions.
+CREATE DATABASE regression_tuplecid;
+-- snapshot the original database name (make and meson use different
+-- names for it) so we can switch back before dropping the test database
+\set prevdb :DBNAME
+\c regression_tuplecid
+-- predictability
+SET synchronous_commit = on;
+SELECT 'init' FROM pg_create_logical_replication_slot('regression_slot', 'test_decoding');
+ ?column?
+----------
+ init
+(1 row)
+
+-- Catalog churn to push the catalog pages into a state where on-access
+-- pruning frees the aborted subtransaction's line pointer and the second
+-- ALTER's catalog insert reuses it.
+CREATE TABLE tpc_filler1(f1 char(4));
+CREATE TABLE tpc_filler2(data text);
+INSERT INTO tpc_filler2 VALUES ('before-test');
+CREATE TYPE tpc_complex AS (r float8, i float8);
+CREATE TABLE tpc_filler3 (a int PRIMARY KEY, b text DEFAULT 'Unspecified');
+CREATE TABLE tpc_filler4 (id serial, t text);
+CREATE TABLE tpc_filler5(data text);
+INSERT INTO tpc_filler5 SELECT repeat('a', 2000) || g.i FROM generate_series(1, 1) g(i);
+TRUNCATE table tpc_filler5;
+CHECKPOINT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+ count
+-------
+ 9
+(1 row)
+
+-- Each iteration runs the trigger shape: catalog DDL inside a rolled-back
+-- subtransaction, then the same DDL again, then decode. Unfixed builds
+-- typically die within a handful of iterations.
+-- (temporarily hide the queries, to avoid flooding the expected output)
+\set ECHO none
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+DROP TABLE tpc_filler1;
+DROP TABLE tpc_filler2;
+DROP TYPE tpc_complex;
+DROP TABLE tpc_filler3;
+DROP TABLE tpc_filler4;
+DROP TABLE tpc_filler5;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+ count
+-------
+ 0
+(1 row)
+
+SELECT pg_drop_replication_slot('regression_slot');
+ pg_drop_replication_slot
+--------------------------
+
+(1 row)
+
+\c :prevdb
+DROP DATABASE regression_tuplecid;
diff --git a/contrib/test_decoding/expected/tuplecid_restart.out b/contrib/test_decoding/expected/tuplecid_restart.out
new file mode 100644
index 00000000000..e5b4bc2543d
--- /dev/null
+++ b/contrib/test_decoding/expected/tuplecid_restart.out
@@ -0,0 +1,68 @@
+Parsed test spec with 3 sessions
+
+starting permutation: s0_init s0_begin s0_savepoint s0_insert s1_checkpoint s1_get_changes s0_catinsert1 s0_rollback s2_vacuum s0_catinsert2 s1_checkpoint s1_get_changes s0_commit s1_get_changes
+step s0_init: SELECT 'init' FROM pg_create_logical_replication_slot('isolation_slot', 'test_decoding');
+?column?
+--------
+init
+(1 row)
+
+step s0_begin: BEGIN;
+step s0_savepoint: SAVEPOINT sp1;
+step s0_insert: INSERT INTO tbl1 VALUES (1);
+step s1_checkpoint: CHECKPOINT;
+step s1_get_changes: SELECT data FROM pg_logical_slot_get_changes('isolation_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%';
+data
+----
+(0 rows)
+
+step s0_catinsert1: INSERT INTO user_cat VALUES (5, 'e');
+step s0_rollback: ROLLBACK TO SAVEPOINT sp1;
+step s2_vacuum: VACUUM user_cat;
+step s0_catinsert2: INSERT INTO user_cat VALUES (6, 'f');
+step s1_checkpoint: CHECKPOINT;
+step s1_get_changes: SELECT data FROM pg_logical_slot_get_changes('isolation_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%';
+data
+----
+(0 rows)
+
+step s0_commit: COMMIT;
+step s1_get_changes: SELECT data FROM pg_logical_slot_get_changes('isolation_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%';
+data
+------
+BEGIN
+COMMIT
+(2 rows)
+
+?column?
+--------
+stop
+(1 row)
+
+
+starting permutation: s0_begin s0_savepoint s0_insert s1_init s0_catinsert1 s0_rollback s2_vacuum s0_catinsert2 s0_commit s1_get_changes
+step s0_begin: BEGIN;
+step s0_savepoint: SAVEPOINT sp1;
+step s0_insert: INSERT INTO tbl1 VALUES (1);
+step s1_init: SELECT 'init' FROM pg_create_logical_replication_slot('isolation_slot', 'test_decoding'); <waiting ...>
+step s0_catinsert1: INSERT INTO user_cat VALUES (5, 'e');
+step s0_rollback: ROLLBACK TO SAVEPOINT sp1;
+step s2_vacuum: VACUUM user_cat;
+step s0_catinsert2: INSERT INTO user_cat VALUES (6, 'f');
+step s0_commit: COMMIT;
+step s1_init: <... completed>
+?column?
+--------
+init
+(1 row)
+
+step s1_get_changes: SELECT data FROM pg_logical_slot_get_changes('isolation_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%';
+data
+----
+(0 rows)
+
+?column?
+--------
+stop
+(1 row)
+
diff --git a/contrib/test_decoding/meson.build b/contrib/test_decoding/meson.build
index 03dd80b7f19..b05b17eb991 100644
--- a/contrib/test_decoding/meson.build
+++ b/contrib/test_decoding/meson.build
@@ -41,6 +41,7 @@ tests += {
'stats',
'twophase',
'twophase_stream',
+ 'tuplecid',
],
'regress_args': [
'--temp-config', files('logical.conf'),
@@ -64,6 +65,7 @@ tests += {
'slot_creation_error',
'skip_snapshot_restore',
'invalidation_distribution',
+ 'tuplecid_restart',
],
'regress_args': [
'--temp-config', files('logical.conf'),
diff --git a/contrib/test_decoding/specs/tuplecid_restart.spec b/contrib/test_decoding/specs/tuplecid_restart.spec
new file mode 100644
index 00000000000..58da414e8b7
--- /dev/null
+++ b/contrib/test_decoding/specs/tuplecid_restart.spec
@@ -0,0 +1,75 @@
+# Test decoding of a transaction in which a catalog-modifying subtransaction
+# was rolled back, where the transaction spans a logical decoding restart
+# point (BUG #19555 restart shape).
+#
+# The tuplecid records written by the aborted subtransaction are queued on the
+# toplevel transaction and must be removed when the subtransaction's abort is
+# decoded; otherwise they collide with the records of the line pointer that
+# gets reused by the toplevel transaction's later catalog insert, failing
+# Assert(ent->cmin == change->data.tuplecid.cmin) in
+# ReorderBufferBuildTupleCidHash() when the commit is decoded.
+#
+# - s0_insert runs in a subtransaction and produces its first WAL record.
+# - s0_catinsert1 generates an xl_heap_new_cid record in that subtransaction.
+# - s0_rollback aborts the subtransaction.
+# - s2_vacuum reclaims the aborted row's line pointer (dead inserts are
+# removed regardless of the xid horizon, so this is deterministic even
+# while the toplevel transaction is still open); s0_catinsert2 then reuses
+# the same tid with a different cmin.
+# - The transaction stays open across both checkpoints, so the final
+# s1_get_changes replays the transaction's records from the first
+# checkpoint and decodes its commit for output, building the tuplecid
+# hash. On unfixed builds the stale tuplecid of the aborted
+# subtransaction collides there with the fresh one.
+setup
+{
+ DROP TABLE IF EXISTS tbl1;
+ DROP TABLE IF EXISTS user_cat;
+ CREATE TABLE tbl1 (val1 integer);
+ -- Four rows of ~1.5kB fill the first heap page to within a few hundred
+ -- bytes, so that vacuuming away the aborted fifth row leaves exactly one
+ -- line pointer for the next insert to reuse.
+ CREATE TABLE user_cat (c1 int, filler char(1500)) WITH (user_catalog_table = true);
+ INSERT INTO user_cat VALUES (1, 'a'), (2, 'b'), (3, 'c'), (4, 'd');
+}
+
+teardown
+{
+ DROP TABLE tbl1;
+ DROP TABLE user_cat;
+ SELECT 'stop' FROM pg_drop_replication_slot('isolation_slot');
+}
+
+session "s0"
+setup { SET synchronous_commit=on; }
+step "s0_init" { SELECT 'init' FROM pg_create_logical_replication_slot('isolation_slot', 'test_decoding'); }
+step "s0_begin" { BEGIN; }
+step "s0_savepoint" { SAVEPOINT sp1; }
+step "s0_insert" { INSERT INTO tbl1 VALUES (1); }
+step "s0_catinsert1" { INSERT INTO user_cat VALUES (5, 'e'); }
+step "s0_rollback" { ROLLBACK TO SAVEPOINT sp1; }
+step "s0_catinsert2" { INSERT INTO user_cat VALUES (6, 'f'); }
+step "s0_commit" { COMMIT; }
+
+session "s1"
+setup { SET synchronous_commit=on; }
+step "s1_init" { SELECT 'init' FROM pg_create_logical_replication_slot('isolation_slot', 'test_decoding'); }
+step "s1_checkpoint" { CHECKPOINT; }
+# The user_cat rows carry ~1.5kB filler values which would flood the expected
+# output; filter them out (decoding still processes them server-side).
+step "s1_get_changes" { SELECT data FROM pg_logical_slot_get_changes('isolation_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%'; }
+
+session "s2"
+setup { SET synchronous_commit=on; }
+step "s2_vacuum" { VACUUM user_cat; }
+
+# The transaction commits only after the second s1_get_changes, so the last
+# s1_get_changes both replays the transaction from the first checkpoint and
+# decodes its commit for output.
+permutation "s0_init" "s0_begin" "s0_savepoint" "s0_insert" "s1_checkpoint" "s1_get_changes" "s0_catinsert1" "s0_rollback" "s2_vacuum" "s0_catinsert2" "s1_checkpoint" "s1_get_changes" "s0_commit" "s1_get_changes"
+
+# Variant with the slot created while the transaction is already open: slot
+# creation waits for a consistent point past the open transaction, so the
+# transaction is never decoded by this slot at all (no output). This locks in
+# the behavior that decoding cannot start in the middle of a transaction.
+permutation "s0_begin" "s0_savepoint" "s0_insert" "s1_init" "s0_catinsert1" "s0_rollback" "s2_vacuum" "s0_catinsert2" "s0_commit" "s1_get_changes"
diff --git a/contrib/test_decoding/sql/tuplecid.sql b/contrib/test_decoding/sql/tuplecid.sql
new file mode 100644
index 00000000000..335fb6d1591
--- /dev/null
+++ b/contrib/test_decoding/sql/tuplecid.sql
@@ -0,0 +1,76 @@
+-- Tests for decoding of transactions in which a catalog-modifying
+-- subtransaction was rolled back (BUG #19555).
+--
+-- When a subtransaction modifies catalog tuples and is then rolled back,
+-- its dead heap-only line pointers can be marked LP_UNUSED by on-access
+-- pruning and reused by later catalog inserts of the same top-level
+-- transaction. The aborted subtransaction's xl_heap_new_cid records must
+-- not be consulted when building the historic snapshot used to decode the
+-- transaction; on unfixed builds they collide with the records of the
+-- reused line pointer and decoding dies with
+-- TRAP: failed Assert("ent->cmin == change->data.tuplecid.cmin")
+-- (or, on non-assert builds, silently uses wrong cmin/cmax mappings).
+--
+-- Whether the collision triggers depends on the physical layout of the
+-- catalog pages, so run in a fresh database where prior tests cannot have
+-- changed it, and loop enough times to leave headroom for layout
+-- differences across versions.
+CREATE DATABASE regression_tuplecid;
+-- snapshot the original database name (make and meson use different
+-- names for it) so we can switch back before dropping the test database
+\set prevdb :DBNAME
+\c regression_tuplecid
+
+-- predictability
+SET synchronous_commit = on;
+
+SELECT 'init' FROM pg_create_logical_replication_slot('regression_slot', 'test_decoding');
+
+-- Catalog churn to push the catalog pages into a state where on-access
+-- pruning frees the aborted subtransaction's line pointer and the second
+-- ALTER's catalog insert reuses it.
+CREATE TABLE tpc_filler1(f1 char(4));
+CREATE TABLE tpc_filler2(data text);
+INSERT INTO tpc_filler2 VALUES ('before-test');
+CREATE TYPE tpc_complex AS (r float8, i float8);
+CREATE TABLE tpc_filler3 (a int PRIMARY KEY, b text DEFAULT 'Unspecified');
+CREATE TABLE tpc_filler4 (id serial, t text);
+CREATE TABLE tpc_filler5(data text);
+INSERT INTO tpc_filler5 SELECT repeat('a', 2000) || g.i FROM generate_series(1, 1) g(i);
+TRUNCATE table tpc_filler5;
+CHECKPOINT;
+
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+
+-- Each iteration runs the trigger shape: catalog DDL inside a rolled-back
+-- subtransaction, then the same DDL again, then decode. Unfixed builds
+-- typically die within a handful of iterations.
+-- (temporarily hide the queries, to avoid flooding the expected output)
+\set ECHO none
+SELECT format($fmt$
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+$fmt$)
+FROM generate_series(1, 25) \gexec
+\set ECHO all
+
+DROP TABLE tpc_filler1;
+DROP TABLE tpc_filler2;
+DROP TYPE tpc_complex;
+DROP TABLE tpc_filler3;
+DROP TABLE tpc_filler4;
+DROP TABLE tpc_filler5;
+
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+
+SELECT pg_drop_replication_slot('regression_slot');
+
+\c :prevdb
+DROP DATABASE regression_tuplecid;
diff --git a/src/backend/replication/logical/reorderbuffer.c b/src/backend/replication/logical/reorderbuffer.c
index 149a1c0d0f0..f5944950db2 100644
--- a/src/backend/replication/logical/reorderbuffer.c
+++ b/src/backend/replication/logical/reorderbuffer.c
@@ -3018,6 +3018,57 @@ ReorderBufferAbort(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn,
/* cosmetic... */
txn->final_lsn = lsn;
+ /*
+ * If this is a subtransaction, remove any tuplecid changes it added to
+ * the toplevel transaction's list. Unlike regular changes, tuplecid
+ * changes are always queued on the toplevel transaction (see
+ * ReorderBufferAddNewTupleCids), so they would otherwise survive the
+ * abort of the subtransaction that wrote them. That's wrong: they
+ * describe catalog tuple versions created or killed by the aborted
+ * subtransaction, which never became visible, and keeping them can
+ * corrupt ReorderBufferBuildTupleCidHash() at commit time -- both when
+ * the toplevel transaction later reuses the same tid (the stale entry
+ * collides with the fresh one, breaking the cmin equality assumption)
+ * and when nothing touches the tid again (a stale cmax would make a
+ * still-live tuple look deleted on historic snapshots).
+ *
+ * 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().
+ */
+ if (rbtxn_is_known_subxact(txn))
+ {
+ ReorderBufferTXN *toptxn = rbtxn_get_toptxn(txn);
+ dlist_mutable_iter it;
+
+ dlist_foreach_modify(it, &toptxn->tuplecids)
+ {
+ ReorderBufferChange *change;
+
+ change = dlist_container(ReorderBufferChange, node, it.cur);
+
+ Assert(change->action == REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID);
+
+ if (change->data.tuplecid.subxid == xid)
+ {
+ dlist_delete(&change->node);
+ ReorderBufferReturnChange(rb, change, false);
+ toptxn->ntuplecids--;
+ }
+ }
+ }
+
/* remove potential on-disk data, and deallocate */
ReorderBufferCleanupTXN(rb, txn);
}
@@ -3350,7 +3401,8 @@ void
ReorderBufferAddNewTupleCids(ReorderBuffer *rb, TransactionId xid,
XLogRecPtr lsn, RelFileLocator locator,
ItemPointerData tid, CommandId cmin,
- CommandId cmax, CommandId combocid)
+ CommandId cmax, CommandId combocid,
+ TransactionId subxid)
{
ReorderBufferChange *change = ReorderBufferGetChange(rb);
ReorderBufferTXN *txn;
@@ -3362,6 +3414,7 @@ ReorderBufferAddNewTupleCids(ReorderBuffer *rb, TransactionId xid,
change->data.tuplecid.cmin = cmin;
change->data.tuplecid.cmax = cmax;
change->data.tuplecid.combocid = combocid;
+ change->data.tuplecid.subxid = subxid;
change->lsn = lsn;
change->txn = txn;
change->action = REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID;
diff --git a/src/backend/replication/logical/snapbuild.c b/src/backend/replication/logical/snapbuild.c
index 5c3bbf0e93f..cf933504229 100644
--- a/src/backend/replication/logical/snapbuild.c
+++ b/src/backend/replication/logical/snapbuild.c
@@ -839,7 +839,7 @@ SnapBuildProcessNewCid(SnapBuild *builder, TransactionId xid,
ReorderBufferAddNewTupleCids(builder->reorder, xlrec->top_xid, lsn,
xlrec->target_locator, xlrec->target_tid,
xlrec->cmin, xlrec->cmax,
- xlrec->combocid);
+ xlrec->combocid, xid);
/* figure out new command id */
if (xlrec->cmin != InvalidCommandId &&
diff --git a/src/include/replication/reorderbuffer.h b/src/include/replication/reorderbuffer.h
index 0cfa9005141..710d1e22aa2 100644
--- a/src/include/replication/reorderbuffer.h
+++ b/src/include/replication/reorderbuffer.h
@@ -141,6 +141,11 @@ typedef struct ReorderBufferChange
CommandId cmin;
CommandId cmax;
CommandId combocid;
+ TransactionId subxid; /* xid that wrote the tuplecid record;
+ * differs from the xid of the txn this
+ * change is queued on (always the
+ * toplevel xid) when a subtransaction
+ * modified the catalog */
} tuplecid;
/* Invalidation. */
@@ -719,7 +724,9 @@ extern void ReorderBufferAddNewCommandId(ReorderBuffer *rb, TransactionId xid,
extern void ReorderBufferAddNewTupleCids(ReorderBuffer *rb, TransactionId xid,
XLogRecPtr lsn, RelFileLocator locator,
ItemPointerData tid,
- CommandId cmin, CommandId cmax, CommandId combocid);
+ CommandId cmin, CommandId cmax,
+ CommandId combocid,
+ TransactionId subxid);
extern void ReorderBufferAddInvalidations(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn,
Size nmsgs, SharedInvalidationMessage *msgs);
extern void ReorderBufferAddDistributedInvalidations(ReorderBuffer *rb, TransactionId xid,
--
2.43.0
^ permalink raw reply [nested|flat] 53+ messages in thread
* Re: Bug in logical decoding with DDL and subtransactions
@ 2026-09-18 02:19 Bingshuai Li <lucian1412@outlook.com>
parent: Bingshuai Li <lucian1412@outlook.com>
0 siblings, 1 reply; 53+ messages in thread
From: Bingshuai Li @ 2026-09-18 02:19 UTC (permalink / raw)
To: alvherre@kurilemu.de <alvherre@kurilemu.de>; pgsql-hackers@lists.postgresql.org <pgsql-hackers@lists.postgresql.org>; +Cc: mark.dilger@enterprisedb.com <mark.dilger@enterprisedb.com>; Amit Kapila <amit.kapila16@gmail.com>; Masahiko Sawada <sawada.mshk@gmail.com>; Alexander Lakhin <exclusion@gmail.com>; Andrey Rachitskiy <pl0h0yp1@gmail.com>; a.kozhemyakin@postgrespro.ru <a.kozhemyakin@postgrespro.ru>
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
Attachments:
v4-0001-Fix-stale-tuplecid-records-left-behind-by-aborted.patch (application/octet-stream, 25.0K) download
From b1ab73ebb6668a8e41d0e5d796ebc97dc691946b Mon Sep 17 00:00:00 2001
From: Bingshuai Li <lucian1412@outlook.com>
Date: Sat, 15 Aug 2026 15:41:56 +0800
Subject: [PATCH v4] Fix stale tuplecid records left behind by aborted
subtransactions
Tuplecid changes are always queued on the toplevel transaction, so
unlike regular changes they are not dropped when the subtransaction
that wrote them aborts. The stale mappings corrupt
ReorderBufferBuildTupleCidHash() at commit time: if a later catalog
insert reuses the aborted subtransaction's line pointer (made
LP_UNUSED by on-access pruning or by vacuum), the fresh record
collides with the stale one with a different cmin, tripping the cmin
equality assertion; where nothing reuses the tid, a stale cmax makes
a still-live catalog tuple look deleted on historic snapshots. On
non-assert builds there is no crash, but the stale mappings risk
misjudging historic catalog visibility, which could produce
incorrect decoding output.
Remove the aborted subtransaction's tuplecid entries in
ReorderBufferAbort() when the sub->top association is known. The
association can be unknown in a decoding pass that started after the
subtransaction's first (toplevel-xid-bearing) WAL record, e.g. when
decoding restarted in the middle of the transaction: tuplecid
records are dispatched on the writing subtransaction without
establishing the association, and abort records never carry the
toplevel xid. Skipping the cleanup in that case is safe because of
how a slot's restart point advances: SnapBuildProcessRunningXacts()
cannot move the restart point past the oldest in-progress
transaction, so any pass that output-decodes the toplevel commit
must have replayed the subtransaction's first record and therefore
knows 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 via SnapBuildXactNeedsSkip(), so any
stale tuplecid entries left behind are dropped along with the
transaction state and never reach ReorderBufferBuildTupleCidHash().
Add an isolation test for the restart shape: the transaction stays
open across checkpoints, the aborted subtransaction's catalog insert
is vacuumed away by another session so that the toplevel's later
insert deterministically reuses the same line pointer, and the final
get_changes both replays the transaction across a restart and
output-decodes its commit. On unfixed assert builds the test dies
deterministically with the cmin assertion in
ReorderBufferBuildTupleCidHash(); with the fix it passes. The
existing regression test keeps covering the continuous (no restart)
shape.
Bug: #19555
Reported-by: Alexander Kozhemyakin <a.kozhemyakin@postgrespro.ru>
Based-on-patch-by: Mark Dilger
Discussion: https://postgr.es/m/CAHgHdKu5e3XY5e90Tuaxq_R4WrKxSV734Q%2BLwo5y39Omp2A-Gg@mail.gmail.com
---
contrib/test_decoding/Makefile | 6 +-
contrib/test_decoding/expected/tuplecid.out | 199 ++++++++++++++++++
.../expected/tuplecid_restart.out | 68 ++++++
contrib/test_decoding/meson.build | 2 +
.../test_decoding/specs/tuplecid_restart.spec | 75 +++++++
contrib/test_decoding/sql/tuplecid.sql | 76 +++++++
.../replication/logical/reorderbuffer.c | 55 ++++-
src/backend/replication/logical/snapbuild.c | 2 +-
src/include/replication/reorderbuffer.h | 9 +-
9 files changed, 487 insertions(+), 5 deletions(-)
create mode 100644 contrib/test_decoding/expected/tuplecid.out
create mode 100644 contrib/test_decoding/expected/tuplecid_restart.out
create mode 100644 contrib/test_decoding/specs/tuplecid_restart.spec
create mode 100644 contrib/test_decoding/sql/tuplecid.sql
diff --git a/contrib/test_decoding/Makefile b/contrib/test_decoding/Makefile
index 0111124399a..5876d8d739e 100644
--- a/contrib/test_decoding/Makefile
+++ b/contrib/test_decoding/Makefile
@@ -5,11 +5,13 @@ PGFILEDESC = "test_decoding - example of a logical decoding output plugin"
REGRESS = ddl xact rewrite toast permissions decoding_in_xact \
decoding_into_rel binary prepared replorigin time messages \
- repack spill slot truncate stream stats twophase twophase_stream
+ repack spill slot truncate stream stats twophase twophase_stream \
+ tuplecid
ISOLATION = mxact delayed_startup ondisk_startup concurrent_ddl_dml \
oldest_xmin snapshot_transfer subxact_without_top concurrent_stream \
twophase_snapshot slot_creation_error catalog_change_snapshot \
- skip_snapshot_restore invalidation_distribution parallel_session_origin
+ skip_snapshot_restore invalidation_distribution parallel_session_origin \
+ tuplecid_restart
REGRESS_OPTS = --temp-config $(top_srcdir)/contrib/test_decoding/logical.conf
ISOLATION_OPTS = --temp-config $(top_srcdir)/contrib/test_decoding/logical.conf
diff --git a/contrib/test_decoding/expected/tuplecid.out b/contrib/test_decoding/expected/tuplecid.out
new file mode 100644
index 00000000000..b559dd21bd4
--- /dev/null
+++ b/contrib/test_decoding/expected/tuplecid.out
@@ -0,0 +1,199 @@
+-- Tests for decoding of transactions in which a catalog-modifying
+-- subtransaction was rolled back (BUG #19555).
+--
+-- When a subtransaction modifies catalog tuples and is then rolled back,
+-- its dead heap-only line pointers can be marked LP_UNUSED by on-access
+-- pruning and reused by later catalog inserts of the same top-level
+-- transaction. The aborted subtransaction's xl_heap_new_cid records must
+-- not be consulted when building the historic snapshot used to decode the
+-- transaction; on unfixed builds they collide with the records of the
+-- reused line pointer and decoding dies with
+-- TRAP: failed Assert("ent->cmin == change->data.tuplecid.cmin")
+-- (or, on non-assert builds, silently uses wrong cmin/cmax mappings).
+--
+-- Whether the collision triggers depends on the physical layout of the
+-- catalog pages, so run in a fresh database where prior tests cannot have
+-- changed it, and loop enough times to leave headroom for layout
+-- differences across versions.
+CREATE DATABASE regression_tuplecid;
+-- snapshot the original database name (make and meson use different
+-- names for it) so we can switch back before dropping the test database
+\set prevdb :DBNAME
+\c regression_tuplecid
+-- predictability
+SET synchronous_commit = on;
+SELECT 'init' FROM pg_create_logical_replication_slot('regression_slot', 'test_decoding');
+ ?column?
+----------
+ init
+(1 row)
+
+-- Catalog churn to push the catalog pages into a state where on-access
+-- pruning frees the aborted subtransaction's line pointer and the second
+-- ALTER's catalog insert reuses it.
+CREATE TABLE tpc_filler1(f1 char(4));
+CREATE TABLE tpc_filler2(data text);
+INSERT INTO tpc_filler2 VALUES ('before-test');
+CREATE TYPE tpc_complex AS (r float8, i float8);
+CREATE TABLE tpc_filler3 (a int PRIMARY KEY, b text DEFAULT 'Unspecified');
+CREATE TABLE tpc_filler4 (id serial, t text);
+CREATE TABLE tpc_filler5(data text);
+INSERT INTO tpc_filler5 SELECT repeat('a', 2000) || g.i FROM generate_series(1, 1) g(i);
+TRUNCATE table tpc_filler5;
+CHECKPOINT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+ count
+-------
+ 9
+(1 row)
+
+-- Each iteration runs the trigger shape: catalog DDL inside a rolled-back
+-- subtransaction, then the same DDL again, then decode. Unfixed builds
+-- typically die within a handful of iterations.
+-- (temporarily hide the queries, to avoid flooding the expected output)
+\set ECHO none
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+DROP TABLE tpc_filler1;
+DROP TABLE tpc_filler2;
+DROP TYPE tpc_complex;
+DROP TABLE tpc_filler3;
+DROP TABLE tpc_filler4;
+DROP TABLE tpc_filler5;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+ count
+-------
+ 0
+(1 row)
+
+SELECT pg_drop_replication_slot('regression_slot');
+ pg_drop_replication_slot
+--------------------------
+
+(1 row)
+
+\c :prevdb
+DROP DATABASE regression_tuplecid;
diff --git a/contrib/test_decoding/expected/tuplecid_restart.out b/contrib/test_decoding/expected/tuplecid_restart.out
new file mode 100644
index 00000000000..e5b4bc2543d
--- /dev/null
+++ b/contrib/test_decoding/expected/tuplecid_restart.out
@@ -0,0 +1,68 @@
+Parsed test spec with 3 sessions
+
+starting permutation: s0_init s0_begin s0_savepoint s0_insert s1_checkpoint s1_get_changes s0_catinsert1 s0_rollback s2_vacuum s0_catinsert2 s1_checkpoint s1_get_changes s0_commit s1_get_changes
+step s0_init: SELECT 'init' FROM pg_create_logical_replication_slot('isolation_slot', 'test_decoding');
+?column?
+--------
+init
+(1 row)
+
+step s0_begin: BEGIN;
+step s0_savepoint: SAVEPOINT sp1;
+step s0_insert: INSERT INTO tbl1 VALUES (1);
+step s1_checkpoint: CHECKPOINT;
+step s1_get_changes: SELECT data FROM pg_logical_slot_get_changes('isolation_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%';
+data
+----
+(0 rows)
+
+step s0_catinsert1: INSERT INTO user_cat VALUES (5, 'e');
+step s0_rollback: ROLLBACK TO SAVEPOINT sp1;
+step s2_vacuum: VACUUM user_cat;
+step s0_catinsert2: INSERT INTO user_cat VALUES (6, 'f');
+step s1_checkpoint: CHECKPOINT;
+step s1_get_changes: SELECT data FROM pg_logical_slot_get_changes('isolation_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%';
+data
+----
+(0 rows)
+
+step s0_commit: COMMIT;
+step s1_get_changes: SELECT data FROM pg_logical_slot_get_changes('isolation_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%';
+data
+------
+BEGIN
+COMMIT
+(2 rows)
+
+?column?
+--------
+stop
+(1 row)
+
+
+starting permutation: s0_begin s0_savepoint s0_insert s1_init s0_catinsert1 s0_rollback s2_vacuum s0_catinsert2 s0_commit s1_get_changes
+step s0_begin: BEGIN;
+step s0_savepoint: SAVEPOINT sp1;
+step s0_insert: INSERT INTO tbl1 VALUES (1);
+step s1_init: SELECT 'init' FROM pg_create_logical_replication_slot('isolation_slot', 'test_decoding'); <waiting ...>
+step s0_catinsert1: INSERT INTO user_cat VALUES (5, 'e');
+step s0_rollback: ROLLBACK TO SAVEPOINT sp1;
+step s2_vacuum: VACUUM user_cat;
+step s0_catinsert2: INSERT INTO user_cat VALUES (6, 'f');
+step s0_commit: COMMIT;
+step s1_init: <... completed>
+?column?
+--------
+init
+(1 row)
+
+step s1_get_changes: SELECT data FROM pg_logical_slot_get_changes('isolation_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%';
+data
+----
+(0 rows)
+
+?column?
+--------
+stop
+(1 row)
+
diff --git a/contrib/test_decoding/meson.build b/contrib/test_decoding/meson.build
index ac655853d26..a78024587dc 100644
--- a/contrib/test_decoding/meson.build
+++ b/contrib/test_decoding/meson.build
@@ -42,6 +42,7 @@ tests += {
'stats',
'twophase',
'twophase_stream',
+ 'tuplecid',
],
'regress_args': [
'--temp-config', files('logical.conf'),
@@ -66,6 +67,7 @@ tests += {
'skip_snapshot_restore',
'invalidation_distribution',
'parallel_session_origin',
+ 'tuplecid_restart',
],
'regress_args': [
'--temp-config', files('logical.conf'),
diff --git a/contrib/test_decoding/specs/tuplecid_restart.spec b/contrib/test_decoding/specs/tuplecid_restart.spec
new file mode 100644
index 00000000000..58da414e8b7
--- /dev/null
+++ b/contrib/test_decoding/specs/tuplecid_restart.spec
@@ -0,0 +1,75 @@
+# Test decoding of a transaction in which a catalog-modifying subtransaction
+# was rolled back, where the transaction spans a logical decoding restart
+# point (BUG #19555 restart shape).
+#
+# The tuplecid records written by the aborted subtransaction are queued on the
+# toplevel transaction and must be removed when the subtransaction's abort is
+# decoded; otherwise they collide with the records of the line pointer that
+# gets reused by the toplevel transaction's later catalog insert, failing
+# Assert(ent->cmin == change->data.tuplecid.cmin) in
+# ReorderBufferBuildTupleCidHash() when the commit is decoded.
+#
+# - s0_insert runs in a subtransaction and produces its first WAL record.
+# - s0_catinsert1 generates an xl_heap_new_cid record in that subtransaction.
+# - s0_rollback aborts the subtransaction.
+# - s2_vacuum reclaims the aborted row's line pointer (dead inserts are
+# removed regardless of the xid horizon, so this is deterministic even
+# while the toplevel transaction is still open); s0_catinsert2 then reuses
+# the same tid with a different cmin.
+# - The transaction stays open across both checkpoints, so the final
+# s1_get_changes replays the transaction's records from the first
+# checkpoint and decodes its commit for output, building the tuplecid
+# hash. On unfixed builds the stale tuplecid of the aborted
+# subtransaction collides there with the fresh one.
+setup
+{
+ DROP TABLE IF EXISTS tbl1;
+ DROP TABLE IF EXISTS user_cat;
+ CREATE TABLE tbl1 (val1 integer);
+ -- Four rows of ~1.5kB fill the first heap page to within a few hundred
+ -- bytes, so that vacuuming away the aborted fifth row leaves exactly one
+ -- line pointer for the next insert to reuse.
+ CREATE TABLE user_cat (c1 int, filler char(1500)) WITH (user_catalog_table = true);
+ INSERT INTO user_cat VALUES (1, 'a'), (2, 'b'), (3, 'c'), (4, 'd');
+}
+
+teardown
+{
+ DROP TABLE tbl1;
+ DROP TABLE user_cat;
+ SELECT 'stop' FROM pg_drop_replication_slot('isolation_slot');
+}
+
+session "s0"
+setup { SET synchronous_commit=on; }
+step "s0_init" { SELECT 'init' FROM pg_create_logical_replication_slot('isolation_slot', 'test_decoding'); }
+step "s0_begin" { BEGIN; }
+step "s0_savepoint" { SAVEPOINT sp1; }
+step "s0_insert" { INSERT INTO tbl1 VALUES (1); }
+step "s0_catinsert1" { INSERT INTO user_cat VALUES (5, 'e'); }
+step "s0_rollback" { ROLLBACK TO SAVEPOINT sp1; }
+step "s0_catinsert2" { INSERT INTO user_cat VALUES (6, 'f'); }
+step "s0_commit" { COMMIT; }
+
+session "s1"
+setup { SET synchronous_commit=on; }
+step "s1_init" { SELECT 'init' FROM pg_create_logical_replication_slot('isolation_slot', 'test_decoding'); }
+step "s1_checkpoint" { CHECKPOINT; }
+# The user_cat rows carry ~1.5kB filler values which would flood the expected
+# output; filter them out (decoding still processes them server-side).
+step "s1_get_changes" { SELECT data FROM pg_logical_slot_get_changes('isolation_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%'; }
+
+session "s2"
+setup { SET synchronous_commit=on; }
+step "s2_vacuum" { VACUUM user_cat; }
+
+# The transaction commits only after the second s1_get_changes, so the last
+# s1_get_changes both replays the transaction from the first checkpoint and
+# decodes its commit for output.
+permutation "s0_init" "s0_begin" "s0_savepoint" "s0_insert" "s1_checkpoint" "s1_get_changes" "s0_catinsert1" "s0_rollback" "s2_vacuum" "s0_catinsert2" "s1_checkpoint" "s1_get_changes" "s0_commit" "s1_get_changes"
+
+# Variant with the slot created while the transaction is already open: slot
+# creation waits for a consistent point past the open transaction, so the
+# transaction is never decoded by this slot at all (no output). This locks in
+# the behavior that decoding cannot start in the middle of a transaction.
+permutation "s0_begin" "s0_savepoint" "s0_insert" "s1_init" "s0_catinsert1" "s0_rollback" "s2_vacuum" "s0_catinsert2" "s0_commit" "s1_get_changes"
diff --git a/contrib/test_decoding/sql/tuplecid.sql b/contrib/test_decoding/sql/tuplecid.sql
new file mode 100644
index 00000000000..335fb6d1591
--- /dev/null
+++ b/contrib/test_decoding/sql/tuplecid.sql
@@ -0,0 +1,76 @@
+-- Tests for decoding of transactions in which a catalog-modifying
+-- subtransaction was rolled back (BUG #19555).
+--
+-- When a subtransaction modifies catalog tuples and is then rolled back,
+-- its dead heap-only line pointers can be marked LP_UNUSED by on-access
+-- pruning and reused by later catalog inserts of the same top-level
+-- transaction. The aborted subtransaction's xl_heap_new_cid records must
+-- not be consulted when building the historic snapshot used to decode the
+-- transaction; on unfixed builds they collide with the records of the
+-- reused line pointer and decoding dies with
+-- TRAP: failed Assert("ent->cmin == change->data.tuplecid.cmin")
+-- (or, on non-assert builds, silently uses wrong cmin/cmax mappings).
+--
+-- Whether the collision triggers depends on the physical layout of the
+-- catalog pages, so run in a fresh database where prior tests cannot have
+-- changed it, and loop enough times to leave headroom for layout
+-- differences across versions.
+CREATE DATABASE regression_tuplecid;
+-- snapshot the original database name (make and meson use different
+-- names for it) so we can switch back before dropping the test database
+\set prevdb :DBNAME
+\c regression_tuplecid
+
+-- predictability
+SET synchronous_commit = on;
+
+SELECT 'init' FROM pg_create_logical_replication_slot('regression_slot', 'test_decoding');
+
+-- Catalog churn to push the catalog pages into a state where on-access
+-- pruning frees the aborted subtransaction's line pointer and the second
+-- ALTER's catalog insert reuses it.
+CREATE TABLE tpc_filler1(f1 char(4));
+CREATE TABLE tpc_filler2(data text);
+INSERT INTO tpc_filler2 VALUES ('before-test');
+CREATE TYPE tpc_complex AS (r float8, i float8);
+CREATE TABLE tpc_filler3 (a int PRIMARY KEY, b text DEFAULT 'Unspecified');
+CREATE TABLE tpc_filler4 (id serial, t text);
+CREATE TABLE tpc_filler5(data text);
+INSERT INTO tpc_filler5 SELECT repeat('a', 2000) || g.i FROM generate_series(1, 1) g(i);
+TRUNCATE table tpc_filler5;
+CHECKPOINT;
+
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+
+-- Each iteration runs the trigger shape: catalog DDL inside a rolled-back
+-- subtransaction, then the same DDL again, then decode. Unfixed builds
+-- typically die within a handful of iterations.
+-- (temporarily hide the queries, to avoid flooding the expected output)
+\set ECHO none
+SELECT format($fmt$
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+$fmt$)
+FROM generate_series(1, 25) \gexec
+\set ECHO all
+
+DROP TABLE tpc_filler1;
+DROP TABLE tpc_filler2;
+DROP TYPE tpc_complex;
+DROP TABLE tpc_filler3;
+DROP TABLE tpc_filler4;
+DROP TABLE tpc_filler5;
+
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+
+SELECT pg_drop_replication_slot('regression_slot');
+
+\c :prevdb
+DROP DATABASE regression_tuplecid;
diff --git a/src/backend/replication/logical/reorderbuffer.c b/src/backend/replication/logical/reorderbuffer.c
index 6aed6346366..27dc6a40efc 100644
--- a/src/backend/replication/logical/reorderbuffer.c
+++ b/src/backend/replication/logical/reorderbuffer.c
@@ -3140,6 +3140,57 @@ ReorderBufferAbort(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn,
/* cosmetic... */
txn->final_lsn = lsn;
+ /*
+ * If this is a subtransaction, remove any tuplecid changes it added to
+ * the toplevel transaction's list. Unlike regular changes, tuplecid
+ * changes are always queued on the toplevel transaction (see
+ * ReorderBufferAddNewTupleCids), so they would otherwise survive the
+ * abort of the subtransaction that wrote them. That's wrong: they
+ * describe catalog tuple versions created or killed by the aborted
+ * subtransaction, which never became visible, and keeping them can
+ * corrupt ReorderBufferBuildTupleCidHash() at commit time -- both when
+ * the toplevel transaction later reuses the same tid (the stale entry
+ * collides with the fresh one, breaking the cmin equality assumption)
+ * and when nothing touches the tid again (a stale cmax would make a
+ * still-live tuple look deleted on historic snapshots).
+ *
+ * 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().
+ */
+ if (rbtxn_is_known_subxact(txn))
+ {
+ ReorderBufferTXN *toptxn = rbtxn_get_toptxn(txn);
+ dlist_mutable_iter it;
+
+ dlist_foreach_modify(it, &toptxn->tuplecids)
+ {
+ ReorderBufferChange *change;
+
+ change = dlist_container(ReorderBufferChange, node, it.cur);
+
+ Assert(change->action == REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID);
+
+ if (change->data.tuplecid.subxid == xid)
+ {
+ dlist_delete(&change->node);
+ ReorderBufferFreeChange(rb, change, false);
+ toptxn->ntuplecids--;
+ }
+ }
+ }
+
/* remove potential on-disk data, and deallocate */
ReorderBufferCleanupTXN(rb, txn);
}
@@ -3477,7 +3528,8 @@ void
ReorderBufferAddNewTupleCids(ReorderBuffer *rb, TransactionId xid,
XLogRecPtr lsn, RelFileLocator locator,
ItemPointerData tid, CommandId cmin,
- CommandId cmax, CommandId combocid)
+ CommandId cmax, CommandId combocid,
+ TransactionId subxid)
{
ReorderBufferChange *change = ReorderBufferAllocChange(rb);
ReorderBufferTXN *txn;
@@ -3489,6 +3541,7 @@ ReorderBufferAddNewTupleCids(ReorderBuffer *rb, TransactionId xid,
change->data.tuplecid.cmin = cmin;
change->data.tuplecid.cmax = cmax;
change->data.tuplecid.combocid = combocid;
+ change->data.tuplecid.subxid = subxid;
change->lsn = lsn;
change->txn = txn;
change->action = REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID;
diff --git a/src/backend/replication/logical/snapbuild.c b/src/backend/replication/logical/snapbuild.c
index f60bcf09605..11cc3c08ffd 100644
--- a/src/backend/replication/logical/snapbuild.c
+++ b/src/backend/replication/logical/snapbuild.c
@@ -703,7 +703,7 @@ SnapBuildProcessNewCid(SnapBuild *builder, TransactionId xid,
ReorderBufferAddNewTupleCids(builder->reorder, xlrec->top_xid, lsn,
xlrec->target_locator, xlrec->target_tid,
xlrec->cmin, xlrec->cmax,
- xlrec->combocid);
+ xlrec->combocid, xid);
/* figure out new command id */
if (xlrec->cmin != InvalidCommandId &&
diff --git a/src/include/replication/reorderbuffer.h b/src/include/replication/reorderbuffer.h
index ff825e4b7b2..9d4f01e1d77 100644
--- a/src/include/replication/reorderbuffer.h
+++ b/src/include/replication/reorderbuffer.h
@@ -146,6 +146,11 @@ typedef struct ReorderBufferChange
CommandId cmin;
CommandId cmax;
CommandId combocid;
+ TransactionId subxid; /* xid that wrote the tuplecid record;
+ * differs from the xid of the txn this
+ * change is queued on (always the
+ * toplevel xid) when a subtransaction
+ * modified the catalog */
} tuplecid;
/* Invalidation. */
@@ -751,7 +756,9 @@ extern void ReorderBufferAddNewCommandId(ReorderBuffer *rb, TransactionId xid,
extern void ReorderBufferAddNewTupleCids(ReorderBuffer *rb, TransactionId xid,
XLogRecPtr lsn, RelFileLocator locator,
ItemPointerData tid,
- CommandId cmin, CommandId cmax, CommandId combocid);
+ CommandId cmin, CommandId cmax,
+ CommandId combocid,
+ TransactionId subxid);
extern void ReorderBufferAddInvalidations(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn,
Size nmsgs, SharedInvalidationMessage *msgs);
extern void ReorderBufferAddDistributedInvalidations(ReorderBuffer *rb, TransactionId xid,
--
2.43.0
^ permalink raw reply [nested|flat] 53+ messages in thread
* RE: Bug in logical decoding with DDL and subtransactions
@ 2026-09-28 05:18 Hayato Kuroda (Fujitsu) <kuroda.hayato@fujitsu.com>
parent: Bingshuai Li <lucian1412@outlook.com>
0 siblings, 0 replies; 53+ messages in thread
From: Hayato Kuroda (Fujitsu) @ 2026-09-28 05:18 UTC (permalink / raw)
To: Bingshuai Li <lucian1412@outlook.com>; alvherre@kurilemu.de <alvherre@kurilemu.de>; pgsql-hackers@lists.postgresql.org <pgsql-hackers@lists.postgresql.org>; +Cc: mark.dilger@enterprisedb.com <mark.dilger@enterprisedb.com>; Amit Kapila <amit.kapila16@gmail.com>; Masahiko Sawada <sawada.mshk@gmail.com>; Alexander Lakhin <exclusion@gmail.com>; Andrey Rachitskiy <pl0h0yp1@gmail.com>; a.kozhemyakin@postgrespro.ru <a.kozhemyakin@postgrespro.ru>
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
^ permalink raw reply [nested|flat] 53+ messages in thread
* Re: Bug in logical decoding with DDL and subtransactions
@ 2026-09-29 18:31 Tom Lane <tgl@sss.pgh.pa.us>
parent: Bingshuai Li <lucian1412@outlook.com>
1 sibling, 1 reply; 53+ messages in thread
From: Tom Lane @ 2026-09-29 18:31 UTC (permalink / raw)
To: Bingshuai Li <lucian1412@outlook.com>; +Cc: alvherre@kurilemu.de <alvherre@kurilemu.de>; pgsql-hackers@lists.postgresql.org <pgsql-hackers@lists.postgresql.org>; mark.dilger@enterprisedb.com <mark.dilger@enterprisedb.com>; Amit Kapila <amit.kapila16@gmail.com>; Masahiko Sawada <sawada.mshk@gmail.com>; Alexander Lakhin <exclusion@gmail.com>; Andrey Rachitskiy <pl0h0yp1@gmail.com>; a.kozhemyakin@postgrespro.ru <a.kozhemyakin@postgrespro.ru>
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"?)
regards, tom lane
^ permalink raw reply [nested|flat] 53+ messages in thread
* Re: Bug in logical decoding with DDL and subtransactions
@ 2026-09-29 21:00 Alexander Lakhin <exclusion@gmail.com>
parent: Tom Lane <tgl@sss.pgh.pa.us>
0 siblings, 1 reply; 53+ messages in thread
From: Alexander Lakhin @ 2026-09-29 21:00 UTC (permalink / raw)
To: Tom Lane <tgl@sss.pgh.pa.us>; Bingshuai Li <lucian1412@outlook.com>; +Cc: alvherre@kurilemu.de <alvherre@kurilemu.de>; pgsql-hackers@lists.postgresql.org <pgsql-hackers@lists.postgresql.org>; mark.dilger@enterprisedb.com <mark.dilger@enterprisedb.com>; Amit Kapila <amit.kapila16@gmail.com>; Masahiko Sawada <sawada.mshk@gmail.com>; Andrey Rachitskiy <pl0h0yp1@gmail.com>; a.kozhemyakin@postgrespro.ru <a.kozhemyakin@postgrespro.ru>
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
^ permalink raw reply [nested|flat] 53+ messages in thread
* Re: Bug in logical decoding with DDL and subtransactions
@ 2026-09-29 21:17 Tom Lane <tgl@sss.pgh.pa.us>
parent: Alexander Lakhin <exclusion@gmail.com>
0 siblings, 2 replies; 53+ messages in thread
From: Tom Lane @ 2026-09-29 21:17 UTC (permalink / raw)
To: Alexander Lakhin <exclusion@gmail.com>; +Cc: Bingshuai Li <lucian1412@outlook.com>; alvherre@kurilemu.de <alvherre@kurilemu.de>; pgsql-hackers@lists.postgresql.org <pgsql-hackers@lists.postgresql.org>; mark.dilger@enterprisedb.com <mark.dilger@enterprisedb.com>; Amit Kapila <amit.kapila16@gmail.com>; Masahiko Sawada <sawada.mshk@gmail.com>; Andrey Rachitskiy <pl0h0yp1@gmail.com>; a.kozhemyakin@postgrespro.ru <a.kozhemyakin@postgrespro.ru>
Alexander Lakhin <exclusion@gmail.com> 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
^ permalink raw reply [nested|flat] 53+ messages in thread
* Re: Bug in logical decoding with DDL and subtransactions
@ 2026-09-30 03:05 Michael Paquier <michael@paquier.xyz>
parent: Tom Lane <tgl@sss.pgh.pa.us>
1 sibling, 1 reply; 53+ messages in thread
From: Michael Paquier @ 2026-09-30 03:05 UTC (permalink / raw)
To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Alexander Lakhin <exclusion@gmail.com>; Bingshuai Li <lucian1412@outlook.com>; alvherre@kurilemu.de <alvherre@kurilemu.de>; pgsql-hackers@lists.postgresql.org <pgsql-hackers@lists.postgresql.org>; mark.dilger@enterprisedb.com <mark.dilger@enterprisedb.com>; Amit Kapila <amit.kapila16@gmail.com>; Masahiko Sawada <sawada.mshk@gmail.com>; Andrey Rachitskiy <pl0h0yp1@gmail.com>; a.kozhemyakin@postgrespro.ru <a.kozhemyakin@postgrespro.ru>
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
Attachments:
signature.asc (application/pgp-signature, 832B) download
^ permalink raw reply [nested|flat] 53+ messages in thread
* Re: Bug in logical decoding with DDL and subtransactions
@ 2026-09-30 05:07 Michael Paquier <michael@paquier.xyz>
parent: Michael Paquier <michael@paquier.xyz>
0 siblings, 1 reply; 53+ messages in thread
From: Michael Paquier @ 2026-09-30 05:07 UTC (permalink / raw)
To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Alexander Lakhin <exclusion@gmail.com>; Bingshuai Li <lucian1412@outlook.com>; alvherre@kurilemu.de <alvherre@kurilemu.de>; pgsql-hackers@lists.postgresql.org <pgsql-hackers@lists.postgresql.org>; mark.dilger@enterprisedb.com <mark.dilger@enterprisedb.com>; Amit Kapila <amit.kapila16@gmail.com>; Masahiko Sawada <sawada.mshk@gmail.com>; Andrey Rachitskiy <pl0h0yp1@gmail.com>; a.kozhemyakin@postgrespro.ru <a.kozhemyakin@postgrespro.ru>
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
Attachments:
ddl.diff.txt (text/plain, 872B) download
diff --git a/contrib/test_decoding/sql/ddl.sql b/contrib/test_decoding/sql/ddl.sql
index 8c5b150079e7..afc264312334 100644
--- a/contrib/test_decoding/sql/ddl.sql
+++ b/contrib/test_decoding/sql/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
signature.asc (application/pgp-signature, 832B) download
^ permalink raw reply [nested|flat] 53+ messages in thread
* RE: Bug in logical decoding with DDL and subtransactions
@ 2026-09-30 09:12 Bingshuai Li <lucian1412@outlook.com>
parent: Michael Paquier <michael@paquier.xyz>
0 siblings, 1 reply; 53+ messages in thread
From: Bingshuai Li @ 2026-09-30 09:12 UTC (permalink / raw)
To: Michael Paquier <michael@paquier.xyz>; Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Alexander Lakhin <exclusion@gmail.com>; alvherre@kurilemu.de <alvherre@kurilemu.de>; pgsql-hackers@lists.postgresql.org <pgsql-hackers@lists.postgresql.org>; mark.dilger@enterprisedb.com <mark.dilger@enterprisedb.com>; Amit Kapila <amit.kapila16@gmail.com>; Masahiko Sawada <sawada.mshk@gmail.com>; Andrey Rachitskiy <pl0h0yp1@gmail.com>; a.kozhemyakin@postgrespro.ru <a.kozhemyakin@postgrespro.ru>; Michael Paquier <michael@paquier.xyz>
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
Attachments: download all (5 files, .tar.gz)
v5-0001-Fix-stale-tuplecid-records-left-behind-by-aborted.patch (application/octet-stream, 35.5K) download
From ff518e4ecb51b8e62c1596f6229cf9aa4704fef2 Mon Sep 17 00:00:00 2001
From: Bingshuai Li <lucian1412@outlook.com>
Date: Wed, 30 Sep 2026 11:52:16 +0800
Subject: [PATCH] Fix stale tuplecid records left behind by aborted
subtransactions
Tuplecid changes are always queued on the toplevel transaction, so
unlike regular changes they are not dropped when the subtransaction
that wrote them aborts. The stale mappings corrupt
ReorderBufferBuildTupleCidHash() at commit time: if a later catalog
insert reuses the aborted subtransaction's line pointer (made
LP_UNUSED by on-access pruning or by vacuum), the fresh record
collides with the stale one with a different cmin, tripping the cmin
equality assertion; where nothing reuses the tid, a stale cmax makes
a still-live catalog tuple look deleted on historic snapshots. On
non-assert builds there is no crash, but the stale mappings risk
misjudging historic catalog visibility, which could produce
incorrect decoding output.
Remove the aborted subtransaction's tuplecid entries when its abort
is decoded. The cleanup is not needed when the whole toplevel
transaction is being aborted, because ReorderBufferCleanupTXN()
frees the whole list anyway; to avoid scanning the list once per
aborted subxid in that case, DecodeAbort() passes the abort record's
primary xid to the new ReorderBufferCleanupSubTxnTupleCids(), which
skips the scan when that xid is the toplevel of the xid being
cleaned.
The decision cannot be based on whether the primary xid's own
association with its toplevel is known: abort records are written
after the subtransaction has entered TRANS_ABORT, so they never
carry the toplevel xid in their header, and an outer subtransaction
that never wrote WAL of its own -- for example a savepoint that only
wraps other savepoints -- can never get its association established
at all. When such an outer subtransaction is rolled back, the
released inner subtransactions listed in its abort record do have
known associations, and their tuplecids must be removed from the
surviving toplevel's list. The existing tuplecid and tuplecid_restart
tests only cover aborts of subtransactions that wrote WAL themselves,
which is why this shape needs its own test.
Skipping the cleanup when the association of the xid being cleaned
is unknown is safe because of how a slot's restart point advances:
SnapBuildProcessRunningXacts() cannot move the restart point past
the oldest in-progress transaction, so any pass that output-decodes
the toplevel commit must have replayed the subtransaction's first
record and therefore knows 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 via
SnapBuildXactNeedsSkip(), so any stale tuplecid entries left behind
are dropped along with the transaction state and never reach
ReorderBufferBuildTupleCidHash().
Add an isolation test for the nested shape: the toplevel writes WAL
first, an inner subtransaction modifies a user catalog table and is
released, and the outer subtransaction -- which produces no WAL of
its own -- is then rolled back; with the page-fill and vacuum recipe
of tuplecid_restart, the toplevel's later insert deterministically
reuses the aborted subtransaction's line pointer. On unfixed assert
builds the final get_changes dies with the original cmin assertion
in ReorderBufferBuildTupleCidHash(); with the fix it passes. The
existing tests keep covering the simple savepoint and the restart
shapes.
Bug: #19555
Reported-by: Alexander Kozhemyakin <a.kozhemyakin@postgrespro.ru>
Based-on-patch-by: Mark Dilger
Discussion: https://postgr.es/m/CAHgHdKu5e3XY5e90Tuaxq_R4WrKxSV734Q%2BLwo5y39Omp2A-Gg@mail.gmail.com
---
contrib/test_decoding/Makefile | 6 +-
contrib/test_decoding/expected/tuplecid.out | 199 ++++++++++++++++++
.../expected/tuplecid_nested.out | 32 +++
.../expected/tuplecid_restart.out | 68 ++++++
contrib/test_decoding/meson.build | 3 +
.../test_decoding/specs/tuplecid_nested.spec | 77 +++++++
.../test_decoding/specs/tuplecid_restart.spec | 75 +++++++
contrib/test_decoding/sql/tuplecid.sql | 76 +++++++
src/backend/replication/logical/decode.c | 21 ++
.../replication/logical/reorderbuffer.c | 86 +++++++-
src/backend/replication/logical/snapbuild.c | 2 +-
src/include/replication/reorderbuffer.h | 11 +-
12 files changed, 651 insertions(+), 5 deletions(-)
create mode 100644 contrib/test_decoding/expected/tuplecid.out
create mode 100644 contrib/test_decoding/expected/tuplecid_nested.out
create mode 100644 contrib/test_decoding/expected/tuplecid_restart.out
create mode 100644 contrib/test_decoding/specs/tuplecid_nested.spec
create mode 100644 contrib/test_decoding/specs/tuplecid_restart.spec
create mode 100644 contrib/test_decoding/sql/tuplecid.sql
diff --git a/contrib/test_decoding/Makefile b/contrib/test_decoding/Makefile
index 0111124399a..e00d75316e8 100644
--- a/contrib/test_decoding/Makefile
+++ b/contrib/test_decoding/Makefile
@@ -5,11 +5,13 @@ PGFILEDESC = "test_decoding - example of a logical decoding output plugin"
REGRESS = ddl xact rewrite toast permissions decoding_in_xact \
decoding_into_rel binary prepared replorigin time messages \
- repack spill slot truncate stream stats twophase twophase_stream
+ repack spill slot truncate stream stats twophase twophase_stream \
+ tuplecid
ISOLATION = mxact delayed_startup ondisk_startup concurrent_ddl_dml \
oldest_xmin snapshot_transfer subxact_without_top concurrent_stream \
twophase_snapshot slot_creation_error catalog_change_snapshot \
- skip_snapshot_restore invalidation_distribution parallel_session_origin
+ skip_snapshot_restore invalidation_distribution parallel_session_origin \
+ tuplecid_restart tuplecid_nested
REGRESS_OPTS = --temp-config $(top_srcdir)/contrib/test_decoding/logical.conf
ISOLATION_OPTS = --temp-config $(top_srcdir)/contrib/test_decoding/logical.conf
diff --git a/contrib/test_decoding/expected/tuplecid.out b/contrib/test_decoding/expected/tuplecid.out
new file mode 100644
index 00000000000..b559dd21bd4
--- /dev/null
+++ b/contrib/test_decoding/expected/tuplecid.out
@@ -0,0 +1,199 @@
+-- Tests for decoding of transactions in which a catalog-modifying
+-- subtransaction was rolled back (BUG #19555).
+--
+-- When a subtransaction modifies catalog tuples and is then rolled back,
+-- its dead heap-only line pointers can be marked LP_UNUSED by on-access
+-- pruning and reused by later catalog inserts of the same top-level
+-- transaction. The aborted subtransaction's xl_heap_new_cid records must
+-- not be consulted when building the historic snapshot used to decode the
+-- transaction; on unfixed builds they collide with the records of the
+-- reused line pointer and decoding dies with
+-- TRAP: failed Assert("ent->cmin == change->data.tuplecid.cmin")
+-- (or, on non-assert builds, silently uses wrong cmin/cmax mappings).
+--
+-- Whether the collision triggers depends on the physical layout of the
+-- catalog pages, so run in a fresh database where prior tests cannot have
+-- changed it, and loop enough times to leave headroom for layout
+-- differences across versions.
+CREATE DATABASE regression_tuplecid;
+-- snapshot the original database name (make and meson use different
+-- names for it) so we can switch back before dropping the test database
+\set prevdb :DBNAME
+\c regression_tuplecid
+-- predictability
+SET synchronous_commit = on;
+SELECT 'init' FROM pg_create_logical_replication_slot('regression_slot', 'test_decoding');
+ ?column?
+----------
+ init
+(1 row)
+
+-- Catalog churn to push the catalog pages into a state where on-access
+-- pruning frees the aborted subtransaction's line pointer and the second
+-- ALTER's catalog insert reuses it.
+CREATE TABLE tpc_filler1(f1 char(4));
+CREATE TABLE tpc_filler2(data text);
+INSERT INTO tpc_filler2 VALUES ('before-test');
+CREATE TYPE tpc_complex AS (r float8, i float8);
+CREATE TABLE tpc_filler3 (a int PRIMARY KEY, b text DEFAULT 'Unspecified');
+CREATE TABLE tpc_filler4 (id serial, t text);
+CREATE TABLE tpc_filler5(data text);
+INSERT INTO tpc_filler5 SELECT repeat('a', 2000) || g.i FROM generate_series(1, 1) g(i);
+TRUNCATE table tpc_filler5;
+CHECKPOINT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+ count
+-------
+ 9
+(1 row)
+
+-- Each iteration runs the trigger shape: catalog DDL inside a rolled-back
+-- subtransaction, then the same DDL again, then decode. Unfixed builds
+-- typically die within a handful of iterations.
+-- (temporarily hide the queries, to avoid flooding the expected output)
+\set ECHO none
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+DROP TABLE tpc_filler1;
+DROP TABLE tpc_filler2;
+DROP TYPE tpc_complex;
+DROP TABLE tpc_filler3;
+DROP TABLE tpc_filler4;
+DROP TABLE tpc_filler5;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+ count
+-------
+ 0
+(1 row)
+
+SELECT pg_drop_replication_slot('regression_slot');
+ pg_drop_replication_slot
+--------------------------
+
+(1 row)
+
+\c :prevdb
+DROP DATABASE regression_tuplecid;
diff --git a/contrib/test_decoding/expected/tuplecid_nested.out b/contrib/test_decoding/expected/tuplecid_nested.out
new file mode 100644
index 00000000000..5d816374fbc
--- /dev/null
+++ b/contrib/test_decoding/expected/tuplecid_nested.out
@@ -0,0 +1,32 @@
+Parsed test spec with 3 sessions
+
+starting permutation: s1_init s0_begin s0_topwrite s0_outer s0_inner s0_catinsert1 s0_release_inner s0_rollback_outer s2_vacuum s0_catinsert2 s0_commit s1_get_changes
+step s1_init: SELECT 'init' FROM pg_create_logical_replication_slot('tuplecid_nested_slot', 'test_decoding');
+?column?
+--------
+init
+(1 row)
+
+step s0_begin: BEGIN;
+step s0_topwrite: INSERT INTO tbl1 VALUES (0);
+step s0_outer: SAVEPOINT outer_sp;
+step s0_inner: SAVEPOINT inner_sp;
+step s0_catinsert1: INSERT INTO user_cat VALUES (5, 'e');
+step s0_release_inner: RELEASE SAVEPOINT inner_sp;
+step s0_rollback_outer: ROLLBACK TO SAVEPOINT outer_sp;
+step s2_vacuum: VACUUM user_cat;
+step s0_catinsert2: INSERT INTO user_cat VALUES (6, 'f');
+step s0_commit: COMMIT;
+step s1_get_changes: SELECT data FROM pg_logical_slot_get_changes('tuplecid_nested_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%';
+data
+------------------------------------------
+BEGIN
+table public.tbl1: INSERT: val1[integer]:0
+COMMIT
+(3 rows)
+
+?column?
+--------
+stop
+(1 row)
+
diff --git a/contrib/test_decoding/expected/tuplecid_restart.out b/contrib/test_decoding/expected/tuplecid_restart.out
new file mode 100644
index 00000000000..e5b4bc2543d
--- /dev/null
+++ b/contrib/test_decoding/expected/tuplecid_restart.out
@@ -0,0 +1,68 @@
+Parsed test spec with 3 sessions
+
+starting permutation: s0_init s0_begin s0_savepoint s0_insert s1_checkpoint s1_get_changes s0_catinsert1 s0_rollback s2_vacuum s0_catinsert2 s1_checkpoint s1_get_changes s0_commit s1_get_changes
+step s0_init: SELECT 'init' FROM pg_create_logical_replication_slot('isolation_slot', 'test_decoding');
+?column?
+--------
+init
+(1 row)
+
+step s0_begin: BEGIN;
+step s0_savepoint: SAVEPOINT sp1;
+step s0_insert: INSERT INTO tbl1 VALUES (1);
+step s1_checkpoint: CHECKPOINT;
+step s1_get_changes: SELECT data FROM pg_logical_slot_get_changes('isolation_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%';
+data
+----
+(0 rows)
+
+step s0_catinsert1: INSERT INTO user_cat VALUES (5, 'e');
+step s0_rollback: ROLLBACK TO SAVEPOINT sp1;
+step s2_vacuum: VACUUM user_cat;
+step s0_catinsert2: INSERT INTO user_cat VALUES (6, 'f');
+step s1_checkpoint: CHECKPOINT;
+step s1_get_changes: SELECT data FROM pg_logical_slot_get_changes('isolation_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%';
+data
+----
+(0 rows)
+
+step s0_commit: COMMIT;
+step s1_get_changes: SELECT data FROM pg_logical_slot_get_changes('isolation_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%';
+data
+------
+BEGIN
+COMMIT
+(2 rows)
+
+?column?
+--------
+stop
+(1 row)
+
+
+starting permutation: s0_begin s0_savepoint s0_insert s1_init s0_catinsert1 s0_rollback s2_vacuum s0_catinsert2 s0_commit s1_get_changes
+step s0_begin: BEGIN;
+step s0_savepoint: SAVEPOINT sp1;
+step s0_insert: INSERT INTO tbl1 VALUES (1);
+step s1_init: SELECT 'init' FROM pg_create_logical_replication_slot('isolation_slot', 'test_decoding'); <waiting ...>
+step s0_catinsert1: INSERT INTO user_cat VALUES (5, 'e');
+step s0_rollback: ROLLBACK TO SAVEPOINT sp1;
+step s2_vacuum: VACUUM user_cat;
+step s0_catinsert2: INSERT INTO user_cat VALUES (6, 'f');
+step s0_commit: COMMIT;
+step s1_init: <... completed>
+?column?
+--------
+init
+(1 row)
+
+step s1_get_changes: SELECT data FROM pg_logical_slot_get_changes('isolation_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%';
+data
+----
+(0 rows)
+
+?column?
+--------
+stop
+(1 row)
+
diff --git a/contrib/test_decoding/meson.build b/contrib/test_decoding/meson.build
index ac655853d26..32143732212 100644
--- a/contrib/test_decoding/meson.build
+++ b/contrib/test_decoding/meson.build
@@ -42,6 +42,7 @@ tests += {
'stats',
'twophase',
'twophase_stream',
+ 'tuplecid',
],
'regress_args': [
'--temp-config', files('logical.conf'),
@@ -66,6 +67,8 @@ tests += {
'skip_snapshot_restore',
'invalidation_distribution',
'parallel_session_origin',
+ 'tuplecid_restart',
+ 'tuplecid_nested',
],
'regress_args': [
'--temp-config', files('logical.conf'),
diff --git a/contrib/test_decoding/specs/tuplecid_nested.spec b/contrib/test_decoding/specs/tuplecid_nested.spec
new file mode 100644
index 00000000000..52c80eb55eb
--- /dev/null
+++ b/contrib/test_decoding/specs/tuplecid_nested.spec
@@ -0,0 +1,77 @@
+# Test decoding of a partially rolled back transaction where the aborted part
+# is nested: the aborting outer subtransaction never produced any WAL of its
+# own, so decoding cannot know its toplevel transaction, while an inner
+# subtransaction it rolls back did produce WAL and its tuplecid records still
+# have to be removed (BUG #19555 nested shape).
+#
+# The tuplecid records written by the aborted inner subtransaction are queued
+# on the toplevel transaction and must be removed when the outer
+# subtransaction's abort is decoded; otherwise they collide with the records
+# of the line pointer that gets reused by the toplevel transaction's later
+# catalog insert, failing Assert(ent->cmin == change->data.tuplecid.cmin) in
+# ReorderBufferBuildTupleCidHash() when the commit is decoded.
+#
+# - s0_topwrite makes the toplevel transaction produce its first WAL record
+# before any subtransaction exists.
+# - s0_outer establishes the outer savepoint, which never gets a WAL record
+# of its own.
+# - s0_catinsert1 generates an xl_heap_new_cid record in the inner
+# subtransaction, which is then released.
+# - s0_rollback_outer rolls the outer savepoint back. Its abort record is
+# written once the backend is already in TRANS_ABORT, so it carries no
+# toplevel xid in its header and the outer subtransaction's association
+# with the toplevel can never be established. The released inner
+# subtransaction is listed in the same abort record, though, and its
+# tuplecid records still must be removed from the toplevel's list.
+# - s2_vacuum reclaims the aborted row's line pointer (dead inserts are
+# removed regardless of the xid horizon, so this is deterministic even
+# while the toplevel transaction is still open); s0_catinsert2 then reuses
+# the same tid with a different cmin.
+# - s1_get_changes then decodes the toplevel commit and builds the tuplecid
+# hash; on unfixed builds the stale tuplecid of the aborted inner
+# subtransaction collides there with the fresh one.
+setup
+{
+ DROP TABLE IF EXISTS tbl1;
+ DROP TABLE IF EXISTS user_cat;
+ CREATE TABLE tbl1 (val1 integer);
+ -- Four rows of ~1.5kB fill the first heap page to within a few hundred
+ -- bytes, so that vacuuming away the aborted fifth row leaves exactly one
+ -- line pointer for the next insert to reuse.
+ CREATE TABLE user_cat (c1 int, filler char(1500)) WITH (user_catalog_table = true);
+ INSERT INTO user_cat VALUES (1, 'a'), (2, 'b'), (3, 'c'), (4, 'd');
+}
+
+teardown
+{
+ DROP TABLE tbl1;
+ DROP TABLE user_cat;
+ SELECT 'stop' FROM pg_drop_replication_slot('tuplecid_nested_slot');
+}
+
+session "s0"
+setup { SET synchronous_commit=on; }
+step "s0_begin" { BEGIN; }
+step "s0_topwrite" { INSERT INTO tbl1 VALUES (0); }
+step "s0_outer" { SAVEPOINT outer_sp; }
+step "s0_inner" { SAVEPOINT inner_sp; }
+step "s0_catinsert1" { INSERT INTO user_cat VALUES (5, 'e'); }
+step "s0_release_inner" { RELEASE SAVEPOINT inner_sp; }
+step "s0_rollback_outer" { ROLLBACK TO SAVEPOINT outer_sp; }
+step "s0_catinsert2" { INSERT INTO user_cat VALUES (6, 'f'); }
+step "s0_commit" { COMMIT; }
+
+session "s1"
+setup { SET synchronous_commit=on; }
+step "s1_init" { SELECT 'init' FROM pg_create_logical_replication_slot('tuplecid_nested_slot', 'test_decoding'); }
+# The user_cat rows carry ~1.5kB filler values which would flood the expected
+# output; filter them out (decoding still processes them server-side).
+step "s1_get_changes" { SELECT data FROM pg_logical_slot_get_changes('tuplecid_nested_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%'; }
+
+session "s2"
+setup { SET synchronous_commit=on; }
+step "s2_vacuum" { VACUUM user_cat; }
+
+# The slot is created before the transaction begins, so the final
+# s1_get_changes decodes the whole transaction through its commit.
+permutation "s1_init" "s0_begin" "s0_topwrite" "s0_outer" "s0_inner" "s0_catinsert1" "s0_release_inner" "s0_rollback_outer" "s2_vacuum" "s0_catinsert2" "s0_commit" "s1_get_changes"
diff --git a/contrib/test_decoding/specs/tuplecid_restart.spec b/contrib/test_decoding/specs/tuplecid_restart.spec
new file mode 100644
index 00000000000..58da414e8b7
--- /dev/null
+++ b/contrib/test_decoding/specs/tuplecid_restart.spec
@@ -0,0 +1,75 @@
+# Test decoding of a transaction in which a catalog-modifying subtransaction
+# was rolled back, where the transaction spans a logical decoding restart
+# point (BUG #19555 restart shape).
+#
+# The tuplecid records written by the aborted subtransaction are queued on the
+# toplevel transaction and must be removed when the subtransaction's abort is
+# decoded; otherwise they collide with the records of the line pointer that
+# gets reused by the toplevel transaction's later catalog insert, failing
+# Assert(ent->cmin == change->data.tuplecid.cmin) in
+# ReorderBufferBuildTupleCidHash() when the commit is decoded.
+#
+# - s0_insert runs in a subtransaction and produces its first WAL record.
+# - s0_catinsert1 generates an xl_heap_new_cid record in that subtransaction.
+# - s0_rollback aborts the subtransaction.
+# - s2_vacuum reclaims the aborted row's line pointer (dead inserts are
+# removed regardless of the xid horizon, so this is deterministic even
+# while the toplevel transaction is still open); s0_catinsert2 then reuses
+# the same tid with a different cmin.
+# - The transaction stays open across both checkpoints, so the final
+# s1_get_changes replays the transaction's records from the first
+# checkpoint and decodes its commit for output, building the tuplecid
+# hash. On unfixed builds the stale tuplecid of the aborted
+# subtransaction collides there with the fresh one.
+setup
+{
+ DROP TABLE IF EXISTS tbl1;
+ DROP TABLE IF EXISTS user_cat;
+ CREATE TABLE tbl1 (val1 integer);
+ -- Four rows of ~1.5kB fill the first heap page to within a few hundred
+ -- bytes, so that vacuuming away the aborted fifth row leaves exactly one
+ -- line pointer for the next insert to reuse.
+ CREATE TABLE user_cat (c1 int, filler char(1500)) WITH (user_catalog_table = true);
+ INSERT INTO user_cat VALUES (1, 'a'), (2, 'b'), (3, 'c'), (4, 'd');
+}
+
+teardown
+{
+ DROP TABLE tbl1;
+ DROP TABLE user_cat;
+ SELECT 'stop' FROM pg_drop_replication_slot('isolation_slot');
+}
+
+session "s0"
+setup { SET synchronous_commit=on; }
+step "s0_init" { SELECT 'init' FROM pg_create_logical_replication_slot('isolation_slot', 'test_decoding'); }
+step "s0_begin" { BEGIN; }
+step "s0_savepoint" { SAVEPOINT sp1; }
+step "s0_insert" { INSERT INTO tbl1 VALUES (1); }
+step "s0_catinsert1" { INSERT INTO user_cat VALUES (5, 'e'); }
+step "s0_rollback" { ROLLBACK TO SAVEPOINT sp1; }
+step "s0_catinsert2" { INSERT INTO user_cat VALUES (6, 'f'); }
+step "s0_commit" { COMMIT; }
+
+session "s1"
+setup { SET synchronous_commit=on; }
+step "s1_init" { SELECT 'init' FROM pg_create_logical_replication_slot('isolation_slot', 'test_decoding'); }
+step "s1_checkpoint" { CHECKPOINT; }
+# The user_cat rows carry ~1.5kB filler values which would flood the expected
+# output; filter them out (decoding still processes them server-side).
+step "s1_get_changes" { SELECT data FROM pg_logical_slot_get_changes('isolation_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%'; }
+
+session "s2"
+setup { SET synchronous_commit=on; }
+step "s2_vacuum" { VACUUM user_cat; }
+
+# The transaction commits only after the second s1_get_changes, so the last
+# s1_get_changes both replays the transaction from the first checkpoint and
+# decodes its commit for output.
+permutation "s0_init" "s0_begin" "s0_savepoint" "s0_insert" "s1_checkpoint" "s1_get_changes" "s0_catinsert1" "s0_rollback" "s2_vacuum" "s0_catinsert2" "s1_checkpoint" "s1_get_changes" "s0_commit" "s1_get_changes"
+
+# Variant with the slot created while the transaction is already open: slot
+# creation waits for a consistent point past the open transaction, so the
+# transaction is never decoded by this slot at all (no output). This locks in
+# the behavior that decoding cannot start in the middle of a transaction.
+permutation "s0_begin" "s0_savepoint" "s0_insert" "s1_init" "s0_catinsert1" "s0_rollback" "s2_vacuum" "s0_catinsert2" "s0_commit" "s1_get_changes"
diff --git a/contrib/test_decoding/sql/tuplecid.sql b/contrib/test_decoding/sql/tuplecid.sql
new file mode 100644
index 00000000000..335fb6d1591
--- /dev/null
+++ b/contrib/test_decoding/sql/tuplecid.sql
@@ -0,0 +1,76 @@
+-- Tests for decoding of transactions in which a catalog-modifying
+-- subtransaction was rolled back (BUG #19555).
+--
+-- When a subtransaction modifies catalog tuples and is then rolled back,
+-- its dead heap-only line pointers can be marked LP_UNUSED by on-access
+-- pruning and reused by later catalog inserts of the same top-level
+-- transaction. The aborted subtransaction's xl_heap_new_cid records must
+-- not be consulted when building the historic snapshot used to decode the
+-- transaction; on unfixed builds they collide with the records of the
+-- reused line pointer and decoding dies with
+-- TRAP: failed Assert("ent->cmin == change->data.tuplecid.cmin")
+-- (or, on non-assert builds, silently uses wrong cmin/cmax mappings).
+--
+-- Whether the collision triggers depends on the physical layout of the
+-- catalog pages, so run in a fresh database where prior tests cannot have
+-- changed it, and loop enough times to leave headroom for layout
+-- differences across versions.
+CREATE DATABASE regression_tuplecid;
+-- snapshot the original database name (make and meson use different
+-- names for it) so we can switch back before dropping the test database
+\set prevdb :DBNAME
+\c regression_tuplecid
+
+-- predictability
+SET synchronous_commit = on;
+
+SELECT 'init' FROM pg_create_logical_replication_slot('regression_slot', 'test_decoding');
+
+-- Catalog churn to push the catalog pages into a state where on-access
+-- pruning frees the aborted subtransaction's line pointer and the second
+-- ALTER's catalog insert reuses it.
+CREATE TABLE tpc_filler1(f1 char(4));
+CREATE TABLE tpc_filler2(data text);
+INSERT INTO tpc_filler2 VALUES ('before-test');
+CREATE TYPE tpc_complex AS (r float8, i float8);
+CREATE TABLE tpc_filler3 (a int PRIMARY KEY, b text DEFAULT 'Unspecified');
+CREATE TABLE tpc_filler4 (id serial, t text);
+CREATE TABLE tpc_filler5(data text);
+INSERT INTO tpc_filler5 SELECT repeat('a', 2000) || g.i FROM generate_series(1, 1) g(i);
+TRUNCATE table tpc_filler5;
+CHECKPOINT;
+
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+
+-- Each iteration runs the trigger shape: catalog DDL inside a rolled-back
+-- subtransaction, then the same DDL again, then decode. Unfixed builds
+-- typically die within a handful of iterations.
+-- (temporarily hide the queries, to avoid flooding the expected output)
+\set ECHO none
+SELECT format($fmt$
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+$fmt$)
+FROM generate_series(1, 25) \gexec
+\set ECHO all
+
+DROP TABLE tpc_filler1;
+DROP TABLE tpc_filler2;
+DROP TYPE tpc_complex;
+DROP TABLE tpc_filler3;
+DROP TABLE tpc_filler4;
+DROP TABLE tpc_filler5;
+
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+
+SELECT pg_drop_replication_slot('regression_slot');
+
+\c :prevdb
+DROP DATABASE regression_tuplecid;
diff --git a/src/backend/replication/logical/decode.c b/src/backend/replication/logical/decode.c
index 4a739230264..0e7d4840a8e 100644
--- a/src/backend/replication/logical/decode.c
+++ b/src/backend/replication/logical/decode.c
@@ -892,12 +892,33 @@ DecodeAbort(LogicalDecodingContext *ctx, XLogRecordBuffer *buf,
}
else
{
+ /*
+ * Remove tuplecid changes queued by the aborted (sub)transactions
+ * from the toplevel's list, before the transactions are torn down.
+ * The abort record's primary xid tells
+ * ReorderBufferCleanupSubTxnTupleCids() whether the whole toplevel
+ * is going away, in which case scanning the list is pointless.
+ *
+ * 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.
+ */
for (i = 0; i < parsed->nsubxacts; i++)
{
+ ReorderBufferCleanupSubTxnTupleCids(ctx->reorder,
+ parsed->subxacts[i],
+ xid);
ReorderBufferAbort(ctx->reorder, parsed->subxacts[i],
buf->record->EndRecPtr, abort_time);
}
+ ReorderBufferCleanupSubTxnTupleCids(ctx->reorder, xid, xid);
ReorderBufferAbort(ctx->reorder, xid, buf->record->EndRecPtr,
abort_time);
}
diff --git a/src/backend/replication/logical/reorderbuffer.c b/src/backend/replication/logical/reorderbuffer.c
index 94112c30501..e1c6a7c4d32 100644
--- a/src/backend/replication/logical/reorderbuffer.c
+++ b/src/backend/replication/logical/reorderbuffer.c
@@ -3157,6 +3157,88 @@ ReorderBufferAbort(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn,
ReorderBufferCleanupTXN(rb, txn);
}
+/*
+ * Remove tuplecid changes queued by subtransaction xid from its toplevel
+ * transaction's list.
+ *
+ * Unlike regular changes, tuplecid changes are always queued on the toplevel
+ * transaction (see ReorderBufferAddNewTupleCids), so they would otherwise
+ * survive the abort of the subtransaction that wrote them. That's wrong:
+ * they describe catalog tuple versions created or killed by the aborted
+ * subtransaction, which never became visible, and keeping them can corrupt
+ * ReorderBufferBuildTupleCidHash() at commit time -- both when the toplevel
+ * transaction later reuses the same tid (the stale entry collides with the
+ * fresh one, breaking the cmin equality assumption) and when nothing touches
+ * the tid again (a stale cmax would make a still-live tuple look deleted on
+ * historic snapshots).
+ *
+ * The cleanup is pointless when the whole toplevel transaction is
+ * being aborted, since ReorderBufferCleanupTXN() frees the whole list
+ * anyway; the caller passes the abort record's primary xid and we skip
+ * the scan when it is xid's toplevel. Note that the opposite decision
+ * -- cleaning only when the primary xid's own association is known --
+ * would be wrong: abort records are written once the subtransaction is
+ * already in TRANS_ABORT, so they carry no toplevel xid in their
+ * header, and an outer subtransaction that never wrote WAL of its own
+ * never gets an association at all. When such an outer subtransaction
+ * rolls back, released inner subtransactions listed in its abort record
+ * do have known associations and are cleaned here.
+ *
+ * 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().
+ */
+void
+ReorderBufferCleanupSubTxnTupleCids(ReorderBuffer *rb, TransactionId xid,
+ TransactionId primary_xid)
+{
+ ReorderBufferTXN *txn;
+ ReorderBufferTXN *toptxn;
+ dlist_mutable_iter it;
+
+ txn = ReorderBufferTXNByXid(rb, xid, false, NULL, InvalidXLogRecPtr,
+ false);
+
+ /* unknown transaction, or unknown association: nothing to remove */
+ if (txn == NULL || !rbtxn_is_known_subxact(txn))
+ return;
+
+ toptxn = rbtxn_get_toptxn(txn);
+
+ /*
+ * The whole toplevel transaction is being aborted (the abort record's
+ * primary xid is xid's toplevel): ReorderBufferCleanupTXN() will free
+ * the whole list shortly, don't scan it once per aborted subxid.
+ */
+ if (toptxn->xid == primary_xid)
+ return;
+
+ dlist_foreach_modify(it, &toptxn->tuplecids)
+ {
+ ReorderBufferChange *change;
+
+ change = dlist_container(ReorderBufferChange, node, it.cur);
+
+ Assert(change->action == REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID);
+
+ if (change->data.tuplecid.subxid == xid)
+ {
+ dlist_delete(&change->node);
+ ReorderBufferFreeChange(rb, change, false);
+ toptxn->ntuplecids--;
+ }
+ }
+}
+
/*
* Abort all transactions that aren't actually running anymore because the
* server restarted.
@@ -3490,7 +3572,8 @@ void
ReorderBufferAddNewTupleCids(ReorderBuffer *rb, TransactionId xid,
XLogRecPtr lsn, RelFileLocator locator,
ItemPointerData tid, CommandId cmin,
- CommandId cmax, CommandId combocid)
+ CommandId cmax, CommandId combocid,
+ TransactionId subxid)
{
ReorderBufferChange *change = ReorderBufferAllocChange(rb);
ReorderBufferTXN *txn;
@@ -3502,6 +3585,7 @@ ReorderBufferAddNewTupleCids(ReorderBuffer *rb, TransactionId xid,
change->data.tuplecid.cmin = cmin;
change->data.tuplecid.cmax = cmax;
change->data.tuplecid.combocid = combocid;
+ change->data.tuplecid.subxid = subxid;
change->lsn = lsn;
change->txn = txn;
change->action = REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID;
diff --git a/src/backend/replication/logical/snapbuild.c b/src/backend/replication/logical/snapbuild.c
index 69caf5b02e7..451b2b89286 100644
--- a/src/backend/replication/logical/snapbuild.c
+++ b/src/backend/replication/logical/snapbuild.c
@@ -743,7 +743,7 @@ SnapBuildProcessNewCid(SnapBuild *builder, TransactionId xid,
ReorderBufferAddNewTupleCids(builder->reorder, xlrec->top_xid, lsn,
xlrec->target_locator, xlrec->target_tid,
xlrec->cmin, xlrec->cmax,
- xlrec->combocid);
+ xlrec->combocid, xid);
/* figure out new command id */
if (xlrec->cmin != InvalidCommandId &&
diff --git a/src/include/replication/reorderbuffer.h b/src/include/replication/reorderbuffer.h
index ff825e4b7b2..23c447c4953 100644
--- a/src/include/replication/reorderbuffer.h
+++ b/src/include/replication/reorderbuffer.h
@@ -146,6 +146,11 @@ typedef struct ReorderBufferChange
CommandId cmin;
CommandId cmax;
CommandId combocid;
+ TransactionId subxid; /* xid that wrote the tuplecid record;
+ * differs from the xid of the txn this
+ * change is queued on (always the
+ * toplevel xid) when a subtransaction
+ * modified the catalog */
} tuplecid;
/* Invalidation. */
@@ -738,6 +743,8 @@ extern void ReorderBufferCommitChild(ReorderBuffer *rb, TransactionId xid,
XLogRecPtr end_lsn);
extern void ReorderBufferAbort(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn,
TimestampTz abort_time);
+extern void ReorderBufferCleanupSubTxnTupleCids(ReorderBuffer *rb, TransactionId xid,
+ TransactionId primary_xid);
extern void ReorderBufferAbortOld(ReorderBuffer *rb, TransactionId oldestRunningXid);
extern void ReorderBufferForget(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn);
extern void ReorderBufferInvalidate(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn);
@@ -751,7 +758,9 @@ extern void ReorderBufferAddNewCommandId(ReorderBuffer *rb, TransactionId xid,
extern void ReorderBufferAddNewTupleCids(ReorderBuffer *rb, TransactionId xid,
XLogRecPtr lsn, RelFileLocator locator,
ItemPointerData tid,
- CommandId cmin, CommandId cmax, CommandId combocid);
+ CommandId cmin, CommandId cmax,
+ CommandId combocid,
+ TransactionId subxid);
extern void ReorderBufferAddInvalidations(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn,
Size nmsgs, SharedInvalidationMessage *msgs);
extern void ReorderBufferAddDistributedInvalidations(ReorderBuffer *rb, TransactionId xid,
--
2.43.0
v5-REL_14_STABLE-0001-Fix-stale-tuplecid-records-left-behind-by-aborted.patch (application/octet-stream, 33.7K) download
From d5aca2292c7b45e5b398a9c9840d117016aa4d92 Mon Sep 17 00:00:00 2001
From: Bingshuai Li <lucian1412@outlook.com>
Date: Wed, 30 Sep 2026 12:09:23 +0800
Subject: [PATCH] Fix stale tuplecid records left behind by aborted
subtransactions
Tuplecid changes are always queued on the toplevel transaction, so
unlike regular changes they are not dropped when the subtransaction
that wrote them aborts. The stale mappings corrupt
ReorderBufferBuildTupleCidHash() at commit time: if a later catalog
insert reuses the aborted subtransaction's line pointer (made
LP_UNUSED by on-access pruning or by vacuum), the fresh record
collides with the stale one with a different cmin, tripping the cmin
equality assertion; where nothing reuses the tid, a stale cmax makes
a still-live catalog tuple look deleted on historic snapshots. On
non-assert builds there is no crash, but the stale mappings risk
misjudging historic catalog visibility, which could produce
incorrect decoding output.
Remove the aborted subtransaction's tuplecid entries when its abort
is decoded. The cleanup is not needed when the whole toplevel
transaction is being aborted, because ReorderBufferCleanupTXN()
frees the whole list anyway; to avoid scanning the list once per
aborted subxid in that case, DecodeAbort() passes the abort record's
primary xid to the new ReorderBufferCleanupSubTxnTupleCids(), which
skips the scan when that xid is the toplevel of the xid being
cleaned.
The decision cannot be based on whether the primary xid's own
association with its toplevel is known: abort records are written
after the subtransaction has entered TRANS_ABORT, so they never
carry the toplevel xid in their header, and an outer subtransaction
that never wrote WAL of its own -- for example a savepoint that only
wraps other savepoints -- can never get its association established
at all. When such an outer subtransaction is rolled back, the
released inner subtransactions listed in its abort record do have
known associations, and their tuplecids must be removed from the
surviving toplevel's list. The existing tuplecid and tuplecid_restart
tests only cover aborts of subtransactions that wrote WAL themselves,
which is why this shape needs its own test.
Skipping the cleanup when the association of the xid being cleaned
is unknown is safe because of how a slot's restart point advances:
SnapBuildProcessRunningXacts() cannot move the restart point past
the oldest in-progress transaction, so any pass that output-decodes
the toplevel commit must have replayed the subtransaction's first
record and therefore knows 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 via
SnapBuildXactNeedsSkip(), so any stale tuplecid entries left behind
are dropped along with the transaction state and never reach
ReorderBufferBuildTupleCidHash().
Add an isolation test for the nested shape: the toplevel writes WAL
first, an inner subtransaction modifies a user catalog table and is
released, and the outer subtransaction -- which produces no WAL of
its own -- is then rolled back; with the page-fill and vacuum recipe
of tuplecid_restart, the toplevel's later insert deterministically
reuses the aborted subtransaction's line pointer. On unfixed assert
builds the final get_changes dies with the original cmin assertion
in ReorderBufferBuildTupleCidHash(); with the fix it passes. The
existing tests keep covering the simple savepoint and the restart
shapes.
Bug: #19555
Reported-by: Alexander Kozhemyakin <a.kozhemyakin@postgrespro.ru>
Based-on-patch-by: Mark Dilger
Discussion: https://postgr.es/m/CAHgHdKu5e3XY5e90Tuaxq_R4WrKxSV734Q%2BLwo5y39Omp2A-Gg@mail.gmail.com
---
contrib/test_decoding/Makefile | 5 +-
contrib/test_decoding/expected/tuplecid.out | 74 ++++++++++++++++
.../expected/tuplecid_nested.out | 32 +++++++
.../expected/tuplecid_restart.out | 68 +++++++++++++++
.../test_decoding/specs/tuplecid_nested.spec | 77 +++++++++++++++++
.../test_decoding/specs/tuplecid_restart.spec | 75 ++++++++++++++++
contrib/test_decoding/sql/tuplecid.sql | 76 ++++++++++++++++
src/backend/replication/logical/decode.c | 21 +++++
.../replication/logical/reorderbuffer.c | 86 ++++++++++++++++++-
src/backend/replication/logical/snapbuild.c | 2 +-
src/include/replication/reorderbuffer.h | 10 ++-
11 files changed, 521 insertions(+), 5 deletions(-)
create mode 100644 contrib/test_decoding/expected/tuplecid.out
create mode 100644 contrib/test_decoding/expected/tuplecid_nested.out
create mode 100644 contrib/test_decoding/expected/tuplecid_restart.out
create mode 100644 contrib/test_decoding/specs/tuplecid_nested.spec
create mode 100644 contrib/test_decoding/specs/tuplecid_restart.spec
create mode 100644 contrib/test_decoding/sql/tuplecid.sql
diff --git a/contrib/test_decoding/Makefile b/contrib/test_decoding/Makefile
index 1e5f4f6b1cd..9fb90b80299 100644
--- a/contrib/test_decoding/Makefile
+++ b/contrib/test_decoding/Makefile
@@ -5,11 +5,12 @@ PGFILEDESC = "test_decoding - example of a logical decoding output plugin"
REGRESS = ddl xact rewrite toast permissions decoding_in_xact \
decoding_into_rel binary prepared replorigin time messages \
- spill slot truncate stream stats twophase twophase_stream
+ spill slot truncate stream stats twophase twophase_stream \
+ tuplecid
ISOLATION = mxact delayed_startup ondisk_startup concurrent_ddl_dml \
oldest_xmin snapshot_transfer subxact_without_top concurrent_stream \
twophase_snapshot catalog_change_snapshot skip_snapshot_restore \
- invalidation_distribution
+ invalidation_distribution tuplecid_restart tuplecid_nested
REGRESS_OPTS = --temp-config $(top_srcdir)/contrib/test_decoding/logical.conf
ISOLATION_OPTS = --temp-config $(top_srcdir)/contrib/test_decoding/logical.conf
diff --git a/contrib/test_decoding/expected/tuplecid.out b/contrib/test_decoding/expected/tuplecid.out
new file mode 100644
index 00000000000..0105bbb674d
--- /dev/null
+++ b/contrib/test_decoding/expected/tuplecid.out
@@ -0,0 +1,74 @@
+-- Tests for decoding of transactions in which a catalog-modifying
+-- subtransaction was rolled back (BUG #19555).
+--
+-- When a subtransaction modifies catalog tuples and is then rolled back,
+-- its dead heap-only line pointers can be marked LP_UNUSED by on-access
+-- pruning and reused by later catalog inserts of the same top-level
+-- transaction. The aborted subtransaction's xl_heap_new_cid records must
+-- not be consulted when building the historic snapshot used to decode the
+-- transaction; on unfixed builds they collide with the records of the
+-- reused line pointer and decoding dies with
+-- TRAP: failed Assert("ent->cmin == change->data.tuplecid.cmin")
+-- (or, on non-assert builds, silently uses wrong cmin/cmax mappings).
+--
+-- Whether the collision triggers depends on the physical layout of the
+-- catalog pages, so run in a fresh database where prior tests cannot have
+-- changed it, and loop enough times to leave headroom for layout
+-- differences across versions.
+CREATE DATABASE regression_tuplecid;
+-- snapshot the original database name (make and meson use different
+-- names for it) so we can switch back before dropping the test database
+\set prevdb :DBNAME
+\c regression_tuplecid
+-- predictability
+SET synchronous_commit = on;
+SELECT 'init' FROM pg_create_logical_replication_slot('regression_slot', 'test_decoding');
+ ?column?
+----------
+ init
+(1 row)
+
+-- Catalog churn to push the catalog pages into a state where on-access
+-- pruning frees the aborted subtransaction's line pointer and the second
+-- ALTER's catalog insert reuses it.
+CREATE TABLE tpc_filler1(f1 char(4));
+CREATE TABLE tpc_filler2(data text);
+INSERT INTO tpc_filler2 VALUES ('before-test');
+CREATE TYPE tpc_complex AS (r float8, i float8);
+CREATE TABLE tpc_filler3 (a int PRIMARY KEY, b text DEFAULT 'Unspecified');
+CREATE TABLE tpc_filler4 (id serial, t text);
+CREATE TABLE tpc_filler5(data text);
+INSERT INTO tpc_filler5 SELECT repeat('a', 2000) || g.i FROM generate_series(1, 1) g(i);
+TRUNCATE table tpc_filler5;
+CHECKPOINT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+ count
+-------
+ 9
+(1 row)
+
+-- Each iteration runs the trigger shape: catalog DDL inside a rolled-back
+-- subtransaction, then the same DDL again, then decode. Unfixed builds
+-- typically die within a handful of iterations.
+-- (temporarily hide the queries, to avoid flooding the expected output)
+\set ECHO none
+DROP TABLE tpc_filler1;
+DROP TABLE tpc_filler2;
+DROP TYPE tpc_complex;
+DROP TABLE tpc_filler3;
+DROP TABLE tpc_filler4;
+DROP TABLE tpc_filler5;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+ count
+-------
+ 0
+(1 row)
+
+SELECT pg_drop_replication_slot('regression_slot');
+ pg_drop_replication_slot
+--------------------------
+
+(1 row)
+
+\c :prevdb
+DROP DATABASE regression_tuplecid;
diff --git a/contrib/test_decoding/expected/tuplecid_nested.out b/contrib/test_decoding/expected/tuplecid_nested.out
new file mode 100644
index 00000000000..5d816374fbc
--- /dev/null
+++ b/contrib/test_decoding/expected/tuplecid_nested.out
@@ -0,0 +1,32 @@
+Parsed test spec with 3 sessions
+
+starting permutation: s1_init s0_begin s0_topwrite s0_outer s0_inner s0_catinsert1 s0_release_inner s0_rollback_outer s2_vacuum s0_catinsert2 s0_commit s1_get_changes
+step s1_init: SELECT 'init' FROM pg_create_logical_replication_slot('tuplecid_nested_slot', 'test_decoding');
+?column?
+--------
+init
+(1 row)
+
+step s0_begin: BEGIN;
+step s0_topwrite: INSERT INTO tbl1 VALUES (0);
+step s0_outer: SAVEPOINT outer_sp;
+step s0_inner: SAVEPOINT inner_sp;
+step s0_catinsert1: INSERT INTO user_cat VALUES (5, 'e');
+step s0_release_inner: RELEASE SAVEPOINT inner_sp;
+step s0_rollback_outer: ROLLBACK TO SAVEPOINT outer_sp;
+step s2_vacuum: VACUUM user_cat;
+step s0_catinsert2: INSERT INTO user_cat VALUES (6, 'f');
+step s0_commit: COMMIT;
+step s1_get_changes: SELECT data FROM pg_logical_slot_get_changes('tuplecid_nested_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%';
+data
+------------------------------------------
+BEGIN
+table public.tbl1: INSERT: val1[integer]:0
+COMMIT
+(3 rows)
+
+?column?
+--------
+stop
+(1 row)
+
diff --git a/contrib/test_decoding/expected/tuplecid_restart.out b/contrib/test_decoding/expected/tuplecid_restart.out
new file mode 100644
index 00000000000..e5b4bc2543d
--- /dev/null
+++ b/contrib/test_decoding/expected/tuplecid_restart.out
@@ -0,0 +1,68 @@
+Parsed test spec with 3 sessions
+
+starting permutation: s0_init s0_begin s0_savepoint s0_insert s1_checkpoint s1_get_changes s0_catinsert1 s0_rollback s2_vacuum s0_catinsert2 s1_checkpoint s1_get_changes s0_commit s1_get_changes
+step s0_init: SELECT 'init' FROM pg_create_logical_replication_slot('isolation_slot', 'test_decoding');
+?column?
+--------
+init
+(1 row)
+
+step s0_begin: BEGIN;
+step s0_savepoint: SAVEPOINT sp1;
+step s0_insert: INSERT INTO tbl1 VALUES (1);
+step s1_checkpoint: CHECKPOINT;
+step s1_get_changes: SELECT data FROM pg_logical_slot_get_changes('isolation_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%';
+data
+----
+(0 rows)
+
+step s0_catinsert1: INSERT INTO user_cat VALUES (5, 'e');
+step s0_rollback: ROLLBACK TO SAVEPOINT sp1;
+step s2_vacuum: VACUUM user_cat;
+step s0_catinsert2: INSERT INTO user_cat VALUES (6, 'f');
+step s1_checkpoint: CHECKPOINT;
+step s1_get_changes: SELECT data FROM pg_logical_slot_get_changes('isolation_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%';
+data
+----
+(0 rows)
+
+step s0_commit: COMMIT;
+step s1_get_changes: SELECT data FROM pg_logical_slot_get_changes('isolation_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%';
+data
+------
+BEGIN
+COMMIT
+(2 rows)
+
+?column?
+--------
+stop
+(1 row)
+
+
+starting permutation: s0_begin s0_savepoint s0_insert s1_init s0_catinsert1 s0_rollback s2_vacuum s0_catinsert2 s0_commit s1_get_changes
+step s0_begin: BEGIN;
+step s0_savepoint: SAVEPOINT sp1;
+step s0_insert: INSERT INTO tbl1 VALUES (1);
+step s1_init: SELECT 'init' FROM pg_create_logical_replication_slot('isolation_slot', 'test_decoding'); <waiting ...>
+step s0_catinsert1: INSERT INTO user_cat VALUES (5, 'e');
+step s0_rollback: ROLLBACK TO SAVEPOINT sp1;
+step s2_vacuum: VACUUM user_cat;
+step s0_catinsert2: INSERT INTO user_cat VALUES (6, 'f');
+step s0_commit: COMMIT;
+step s1_init: <... completed>
+?column?
+--------
+init
+(1 row)
+
+step s1_get_changes: SELECT data FROM pg_logical_slot_get_changes('isolation_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%';
+data
+----
+(0 rows)
+
+?column?
+--------
+stop
+(1 row)
+
diff --git a/contrib/test_decoding/specs/tuplecid_nested.spec b/contrib/test_decoding/specs/tuplecid_nested.spec
new file mode 100644
index 00000000000..52c80eb55eb
--- /dev/null
+++ b/contrib/test_decoding/specs/tuplecid_nested.spec
@@ -0,0 +1,77 @@
+# Test decoding of a partially rolled back transaction where the aborted part
+# is nested: the aborting outer subtransaction never produced any WAL of its
+# own, so decoding cannot know its toplevel transaction, while an inner
+# subtransaction it rolls back did produce WAL and its tuplecid records still
+# have to be removed (BUG #19555 nested shape).
+#
+# The tuplecid records written by the aborted inner subtransaction are queued
+# on the toplevel transaction and must be removed when the outer
+# subtransaction's abort is decoded; otherwise they collide with the records
+# of the line pointer that gets reused by the toplevel transaction's later
+# catalog insert, failing Assert(ent->cmin == change->data.tuplecid.cmin) in
+# ReorderBufferBuildTupleCidHash() when the commit is decoded.
+#
+# - s0_topwrite makes the toplevel transaction produce its first WAL record
+# before any subtransaction exists.
+# - s0_outer establishes the outer savepoint, which never gets a WAL record
+# of its own.
+# - s0_catinsert1 generates an xl_heap_new_cid record in the inner
+# subtransaction, which is then released.
+# - s0_rollback_outer rolls the outer savepoint back. Its abort record is
+# written once the backend is already in TRANS_ABORT, so it carries no
+# toplevel xid in its header and the outer subtransaction's association
+# with the toplevel can never be established. The released inner
+# subtransaction is listed in the same abort record, though, and its
+# tuplecid records still must be removed from the toplevel's list.
+# - s2_vacuum reclaims the aborted row's line pointer (dead inserts are
+# removed regardless of the xid horizon, so this is deterministic even
+# while the toplevel transaction is still open); s0_catinsert2 then reuses
+# the same tid with a different cmin.
+# - s1_get_changes then decodes the toplevel commit and builds the tuplecid
+# hash; on unfixed builds the stale tuplecid of the aborted inner
+# subtransaction collides there with the fresh one.
+setup
+{
+ DROP TABLE IF EXISTS tbl1;
+ DROP TABLE IF EXISTS user_cat;
+ CREATE TABLE tbl1 (val1 integer);
+ -- Four rows of ~1.5kB fill the first heap page to within a few hundred
+ -- bytes, so that vacuuming away the aborted fifth row leaves exactly one
+ -- line pointer for the next insert to reuse.
+ CREATE TABLE user_cat (c1 int, filler char(1500)) WITH (user_catalog_table = true);
+ INSERT INTO user_cat VALUES (1, 'a'), (2, 'b'), (3, 'c'), (4, 'd');
+}
+
+teardown
+{
+ DROP TABLE tbl1;
+ DROP TABLE user_cat;
+ SELECT 'stop' FROM pg_drop_replication_slot('tuplecid_nested_slot');
+}
+
+session "s0"
+setup { SET synchronous_commit=on; }
+step "s0_begin" { BEGIN; }
+step "s0_topwrite" { INSERT INTO tbl1 VALUES (0); }
+step "s0_outer" { SAVEPOINT outer_sp; }
+step "s0_inner" { SAVEPOINT inner_sp; }
+step "s0_catinsert1" { INSERT INTO user_cat VALUES (5, 'e'); }
+step "s0_release_inner" { RELEASE SAVEPOINT inner_sp; }
+step "s0_rollback_outer" { ROLLBACK TO SAVEPOINT outer_sp; }
+step "s0_catinsert2" { INSERT INTO user_cat VALUES (6, 'f'); }
+step "s0_commit" { COMMIT; }
+
+session "s1"
+setup { SET synchronous_commit=on; }
+step "s1_init" { SELECT 'init' FROM pg_create_logical_replication_slot('tuplecid_nested_slot', 'test_decoding'); }
+# The user_cat rows carry ~1.5kB filler values which would flood the expected
+# output; filter them out (decoding still processes them server-side).
+step "s1_get_changes" { SELECT data FROM pg_logical_slot_get_changes('tuplecid_nested_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%'; }
+
+session "s2"
+setup { SET synchronous_commit=on; }
+step "s2_vacuum" { VACUUM user_cat; }
+
+# The slot is created before the transaction begins, so the final
+# s1_get_changes decodes the whole transaction through its commit.
+permutation "s1_init" "s0_begin" "s0_topwrite" "s0_outer" "s0_inner" "s0_catinsert1" "s0_release_inner" "s0_rollback_outer" "s2_vacuum" "s0_catinsert2" "s0_commit" "s1_get_changes"
diff --git a/contrib/test_decoding/specs/tuplecid_restart.spec b/contrib/test_decoding/specs/tuplecid_restart.spec
new file mode 100644
index 00000000000..58da414e8b7
--- /dev/null
+++ b/contrib/test_decoding/specs/tuplecid_restart.spec
@@ -0,0 +1,75 @@
+# Test decoding of a transaction in which a catalog-modifying subtransaction
+# was rolled back, where the transaction spans a logical decoding restart
+# point (BUG #19555 restart shape).
+#
+# The tuplecid records written by the aborted subtransaction are queued on the
+# toplevel transaction and must be removed when the subtransaction's abort is
+# decoded; otherwise they collide with the records of the line pointer that
+# gets reused by the toplevel transaction's later catalog insert, failing
+# Assert(ent->cmin == change->data.tuplecid.cmin) in
+# ReorderBufferBuildTupleCidHash() when the commit is decoded.
+#
+# - s0_insert runs in a subtransaction and produces its first WAL record.
+# - s0_catinsert1 generates an xl_heap_new_cid record in that subtransaction.
+# - s0_rollback aborts the subtransaction.
+# - s2_vacuum reclaims the aborted row's line pointer (dead inserts are
+# removed regardless of the xid horizon, so this is deterministic even
+# while the toplevel transaction is still open); s0_catinsert2 then reuses
+# the same tid with a different cmin.
+# - The transaction stays open across both checkpoints, so the final
+# s1_get_changes replays the transaction's records from the first
+# checkpoint and decodes its commit for output, building the tuplecid
+# hash. On unfixed builds the stale tuplecid of the aborted
+# subtransaction collides there with the fresh one.
+setup
+{
+ DROP TABLE IF EXISTS tbl1;
+ DROP TABLE IF EXISTS user_cat;
+ CREATE TABLE tbl1 (val1 integer);
+ -- Four rows of ~1.5kB fill the first heap page to within a few hundred
+ -- bytes, so that vacuuming away the aborted fifth row leaves exactly one
+ -- line pointer for the next insert to reuse.
+ CREATE TABLE user_cat (c1 int, filler char(1500)) WITH (user_catalog_table = true);
+ INSERT INTO user_cat VALUES (1, 'a'), (2, 'b'), (3, 'c'), (4, 'd');
+}
+
+teardown
+{
+ DROP TABLE tbl1;
+ DROP TABLE user_cat;
+ SELECT 'stop' FROM pg_drop_replication_slot('isolation_slot');
+}
+
+session "s0"
+setup { SET synchronous_commit=on; }
+step "s0_init" { SELECT 'init' FROM pg_create_logical_replication_slot('isolation_slot', 'test_decoding'); }
+step "s0_begin" { BEGIN; }
+step "s0_savepoint" { SAVEPOINT sp1; }
+step "s0_insert" { INSERT INTO tbl1 VALUES (1); }
+step "s0_catinsert1" { INSERT INTO user_cat VALUES (5, 'e'); }
+step "s0_rollback" { ROLLBACK TO SAVEPOINT sp1; }
+step "s0_catinsert2" { INSERT INTO user_cat VALUES (6, 'f'); }
+step "s0_commit" { COMMIT; }
+
+session "s1"
+setup { SET synchronous_commit=on; }
+step "s1_init" { SELECT 'init' FROM pg_create_logical_replication_slot('isolation_slot', 'test_decoding'); }
+step "s1_checkpoint" { CHECKPOINT; }
+# The user_cat rows carry ~1.5kB filler values which would flood the expected
+# output; filter them out (decoding still processes them server-side).
+step "s1_get_changes" { SELECT data FROM pg_logical_slot_get_changes('isolation_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%'; }
+
+session "s2"
+setup { SET synchronous_commit=on; }
+step "s2_vacuum" { VACUUM user_cat; }
+
+# The transaction commits only after the second s1_get_changes, so the last
+# s1_get_changes both replays the transaction from the first checkpoint and
+# decodes its commit for output.
+permutation "s0_init" "s0_begin" "s0_savepoint" "s0_insert" "s1_checkpoint" "s1_get_changes" "s0_catinsert1" "s0_rollback" "s2_vacuum" "s0_catinsert2" "s1_checkpoint" "s1_get_changes" "s0_commit" "s1_get_changes"
+
+# Variant with the slot created while the transaction is already open: slot
+# creation waits for a consistent point past the open transaction, so the
+# transaction is never decoded by this slot at all (no output). This locks in
+# the behavior that decoding cannot start in the middle of a transaction.
+permutation "s0_begin" "s0_savepoint" "s0_insert" "s1_init" "s0_catinsert1" "s0_rollback" "s2_vacuum" "s0_catinsert2" "s0_commit" "s1_get_changes"
diff --git a/contrib/test_decoding/sql/tuplecid.sql b/contrib/test_decoding/sql/tuplecid.sql
new file mode 100644
index 00000000000..335fb6d1591
--- /dev/null
+++ b/contrib/test_decoding/sql/tuplecid.sql
@@ -0,0 +1,76 @@
+-- Tests for decoding of transactions in which a catalog-modifying
+-- subtransaction was rolled back (BUG #19555).
+--
+-- When a subtransaction modifies catalog tuples and is then rolled back,
+-- its dead heap-only line pointers can be marked LP_UNUSED by on-access
+-- pruning and reused by later catalog inserts of the same top-level
+-- transaction. The aborted subtransaction's xl_heap_new_cid records must
+-- not be consulted when building the historic snapshot used to decode the
+-- transaction; on unfixed builds they collide with the records of the
+-- reused line pointer and decoding dies with
+-- TRAP: failed Assert("ent->cmin == change->data.tuplecid.cmin")
+-- (or, on non-assert builds, silently uses wrong cmin/cmax mappings).
+--
+-- Whether the collision triggers depends on the physical layout of the
+-- catalog pages, so run in a fresh database where prior tests cannot have
+-- changed it, and loop enough times to leave headroom for layout
+-- differences across versions.
+CREATE DATABASE regression_tuplecid;
+-- snapshot the original database name (make and meson use different
+-- names for it) so we can switch back before dropping the test database
+\set prevdb :DBNAME
+\c regression_tuplecid
+
+-- predictability
+SET synchronous_commit = on;
+
+SELECT 'init' FROM pg_create_logical_replication_slot('regression_slot', 'test_decoding');
+
+-- Catalog churn to push the catalog pages into a state where on-access
+-- pruning frees the aborted subtransaction's line pointer and the second
+-- ALTER's catalog insert reuses it.
+CREATE TABLE tpc_filler1(f1 char(4));
+CREATE TABLE tpc_filler2(data text);
+INSERT INTO tpc_filler2 VALUES ('before-test');
+CREATE TYPE tpc_complex AS (r float8, i float8);
+CREATE TABLE tpc_filler3 (a int PRIMARY KEY, b text DEFAULT 'Unspecified');
+CREATE TABLE tpc_filler4 (id serial, t text);
+CREATE TABLE tpc_filler5(data text);
+INSERT INTO tpc_filler5 SELECT repeat('a', 2000) || g.i FROM generate_series(1, 1) g(i);
+TRUNCATE table tpc_filler5;
+CHECKPOINT;
+
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+
+-- Each iteration runs the trigger shape: catalog DDL inside a rolled-back
+-- subtransaction, then the same DDL again, then decode. Unfixed builds
+-- typically die within a handful of iterations.
+-- (temporarily hide the queries, to avoid flooding the expected output)
+\set ECHO none
+SELECT format($fmt$
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+$fmt$)
+FROM generate_series(1, 25) \gexec
+\set ECHO all
+
+DROP TABLE tpc_filler1;
+DROP TABLE tpc_filler2;
+DROP TYPE tpc_complex;
+DROP TABLE tpc_filler3;
+DROP TABLE tpc_filler4;
+DROP TABLE tpc_filler5;
+
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+
+SELECT pg_drop_replication_slot('regression_slot');
+
+\c :prevdb
+DROP DATABASE regression_tuplecid;
diff --git a/src/backend/replication/logical/decode.c b/src/backend/replication/logical/decode.c
index c6858da9b0b..e9f2fced3ff 100644
--- a/src/backend/replication/logical/decode.c
+++ b/src/backend/replication/logical/decode.c
@@ -912,12 +912,33 @@ DecodeAbort(LogicalDecodingContext *ctx, XLogRecordBuffer *buf,
}
else
{
+ /*
+ * Remove tuplecid changes queued by the aborted (sub)transactions
+ * from the toplevel's list, before the transactions are torn down.
+ * The abort record's primary xid tells
+ * ReorderBufferCleanupSubTxnTupleCids() whether the whole toplevel
+ * is going away, in which case scanning the list is pointless.
+ *
+ * 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.
+ */
for (i = 0; i < parsed->nsubxacts; i++)
{
+ ReorderBufferCleanupSubTxnTupleCids(ctx->reorder,
+ parsed->subxacts[i],
+ xid);
ReorderBufferAbort(ctx->reorder, parsed->subxacts[i],
buf->record->EndRecPtr);
}
+ ReorderBufferCleanupSubTxnTupleCids(ctx->reorder, xid, xid);
ReorderBufferAbort(ctx->reorder, xid, buf->record->EndRecPtr);
}
diff --git a/src/backend/replication/logical/reorderbuffer.c b/src/backend/replication/logical/reorderbuffer.c
index 0a84443208f..f08137b862f 100644
--- a/src/backend/replication/logical/reorderbuffer.c
+++ b/src/backend/replication/logical/reorderbuffer.c
@@ -2947,6 +2947,88 @@ ReorderBufferAbort(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn)
ReorderBufferCleanupTXN(rb, txn);
}
+/*
+ * Remove tuplecid changes queued by subtransaction xid from its toplevel
+ * transaction's list.
+ *
+ * Unlike regular changes, tuplecid changes are always queued on the toplevel
+ * transaction (see ReorderBufferAddNewTupleCids), so they would otherwise
+ * survive the abort of the subtransaction that wrote them. That's wrong:
+ * they describe catalog tuple versions created or killed by the aborted
+ * subtransaction, which never became visible, and keeping them can corrupt
+ * ReorderBufferBuildTupleCidHash() at commit time -- both when the toplevel
+ * transaction later reuses the same tid (the stale entry collides with the
+ * fresh one, breaking the cmin equality assumption) and when nothing touches
+ * the tid again (a stale cmax would make a still-live tuple look deleted on
+ * historic snapshots).
+ *
+ * The cleanup is pointless when the whole toplevel transaction is
+ * being aborted, since ReorderBufferCleanupTXN() frees the whole list
+ * anyway; the caller passes the abort record's primary xid and we skip
+ * the scan when it is xid's toplevel. Note that the opposite decision
+ * -- cleaning only when the primary xid's own association is known --
+ * would be wrong: abort records are written once the subtransaction is
+ * already in TRANS_ABORT, so they carry no toplevel xid in their
+ * header, and an outer subtransaction that never wrote WAL of its own
+ * never gets an association at all. When such an outer subtransaction
+ * rolls back, released inner subtransactions listed in its abort record
+ * do have known associations and are cleaned here.
+ *
+ * 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().
+ */
+void
+ReorderBufferCleanupSubTxnTupleCids(ReorderBuffer *rb, TransactionId xid,
+ TransactionId primary_xid)
+{
+ ReorderBufferTXN *txn;
+ ReorderBufferTXN *toptxn;
+ dlist_mutable_iter it;
+
+ txn = ReorderBufferTXNByXid(rb, xid, false, NULL, InvalidXLogRecPtr,
+ false);
+
+ /* unknown transaction, or unknown association: nothing to remove */
+ if (txn == NULL || !rbtxn_is_known_subxact(txn))
+ return;
+
+ toptxn = txn->toptxn;
+
+ /*
+ * The whole toplevel transaction is being aborted (the abort record's
+ * primary xid is xid's toplevel): ReorderBufferCleanupTXN() will free
+ * the whole list shortly, don't scan it once per aborted subxid.
+ */
+ if (toptxn->xid == primary_xid)
+ return;
+
+ dlist_foreach_modify(it, &toptxn->tuplecids)
+ {
+ ReorderBufferChange *change;
+
+ change = dlist_container(ReorderBufferChange, node, it.cur);
+
+ Assert(change->action == REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID);
+
+ if (change->data.tuplecid.subxid == xid)
+ {
+ dlist_delete(&change->node);
+ ReorderBufferReturnChange(rb, change, false);
+ toptxn->ntuplecids--;
+ }
+ }
+}
+
/*
* Abort all transactions that aren't actually running anymore because the
* server restarted.
@@ -3259,7 +3341,8 @@ void
ReorderBufferAddNewTupleCids(ReorderBuffer *rb, TransactionId xid,
XLogRecPtr lsn, RelFileNode node,
ItemPointerData tid, CommandId cmin,
- CommandId cmax, CommandId combocid)
+ CommandId cmax, CommandId combocid,
+ TransactionId subxid)
{
ReorderBufferChange *change = ReorderBufferGetChange(rb);
ReorderBufferTXN *txn;
@@ -3271,6 +3354,7 @@ ReorderBufferAddNewTupleCids(ReorderBuffer *rb, TransactionId xid,
change->data.tuplecid.cmin = cmin;
change->data.tuplecid.cmax = cmax;
change->data.tuplecid.combocid = combocid;
+ change->data.tuplecid.subxid = subxid;
change->lsn = lsn;
change->txn = txn;
change->action = REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID;
diff --git a/src/backend/replication/logical/snapbuild.c b/src/backend/replication/logical/snapbuild.c
index bcee0896500..ddf7a50a088 100644
--- a/src/backend/replication/logical/snapbuild.c
+++ b/src/backend/replication/logical/snapbuild.c
@@ -867,7 +867,7 @@ SnapBuildProcessNewCid(SnapBuild *builder, TransactionId xid,
ReorderBufferAddNewTupleCids(builder->reorder, xlrec->top_xid, lsn,
xlrec->target_node, xlrec->target_tid,
xlrec->cmin, xlrec->cmax,
- xlrec->combocid);
+ xlrec->combocid, xid);
/* figure out new command id */
if (xlrec->cmin != InvalidCommandId &&
diff --git a/src/include/replication/reorderbuffer.h b/src/include/replication/reorderbuffer.h
index cb633315d04..d59ea121b4f 100644
--- a/src/include/replication/reorderbuffer.h
+++ b/src/include/replication/reorderbuffer.h
@@ -150,6 +150,11 @@ typedef struct ReorderBufferChange
CommandId cmin;
CommandId cmax;
CommandId combocid;
+ TransactionId subxid; /* xid that wrote the tuplecid record;
+ * differs from the xid of the txn this
+ * change is queued on (always the
+ * toplevel xid) when a subtransaction
+ * modified the catalog */
} tuplecid;
/* Invalidation. */
@@ -657,6 +662,8 @@ void ReorderBufferAssignChild(ReorderBuffer *, TransactionId, TransactionId, XL
void ReorderBufferCommitChild(ReorderBuffer *, TransactionId, TransactionId,
XLogRecPtr commit_lsn, XLogRecPtr end_lsn);
void ReorderBufferAbort(ReorderBuffer *, TransactionId, XLogRecPtr lsn);
+extern void ReorderBufferCleanupSubTxnTupleCids(ReorderBuffer *rb, TransactionId xid,
+ TransactionId primary_xid);
void ReorderBufferAbortOld(ReorderBuffer *, TransactionId xid);
void ReorderBufferForget(ReorderBuffer *, TransactionId, XLogRecPtr lsn);
void ReorderBufferInvalidate(ReorderBuffer *, TransactionId, XLogRecPtr lsn);
@@ -667,7 +674,8 @@ void ReorderBufferAddNewCommandId(ReorderBuffer *, TransactionId, XLogRecPtr ls
CommandId cid);
void ReorderBufferAddNewTupleCids(ReorderBuffer *, TransactionId, XLogRecPtr lsn,
RelFileNode node, ItemPointerData pt,
- CommandId cmin, CommandId cmax, CommandId combocid);
+ CommandId cmin, CommandId cmax,
+ CommandId combocid, TransactionId subxid);
void ReorderBufferAddInvalidations(ReorderBuffer *, TransactionId, XLogRecPtr lsn,
Size nmsgs, SharedInvalidationMessage *msgs);
void ReorderBufferAddDistributedInvalidations(ReorderBuffer *rb, TransactionId xid,
--
2.43.0
v5-REL_15_STABLE-0001-Fix-stale-tuplecid-records-left-behind-by-aborted.patch (application/octet-stream, 34.7K) download
From 263488269c2ff8f7c5fe390e8a3ded04599edece Mon Sep 17 00:00:00 2001
From: Bingshuai Li <lucian1412@outlook.com>
Date: Wed, 30 Sep 2026 11:30:00 +0800
Subject: [PATCH] Fix stale tuplecid records left behind by aborted
subtransactions
Tuplecid changes are always queued on the toplevel transaction, so
unlike regular changes they are not dropped when the subtransaction
that wrote them aborts. The stale mappings corrupt
ReorderBufferBuildTupleCidHash() at commit time: if a later catalog
insert reuses the aborted subtransaction's line pointer (made
LP_UNUSED by on-access pruning or by vacuum), the fresh record
collides with the stale one with a different cmin, tripping the cmin
equality assertion; where nothing reuses the tid, a stale cmax makes
a still-live catalog tuple look deleted on historic snapshots. On
non-assert builds there is no crash, but the stale mappings risk
misjudging historic catalog visibility, which could produce
incorrect decoding output.
Remove the aborted subtransaction's tuplecid entries when its abort
is decoded. The cleanup is not needed when the whole toplevel
transaction is being aborted, because ReorderBufferCleanupTXN()
frees the whole list anyway; to avoid scanning the list once per
aborted subxid in that case, DecodeAbort() passes the abort record's
primary xid to the new ReorderBufferCleanupSubTxnTupleCids(), which
skips the scan when that xid is the toplevel of the xid being
cleaned.
The decision cannot be based on whether the primary xid's own
association with its toplevel is known: abort records are written
after the subtransaction has entered TRANS_ABORT, so they never
carry the toplevel xid in their header, and an outer subtransaction
that never wrote WAL of its own -- for example a savepoint that only
wraps other savepoints -- can never get its association established
at all. When such an outer subtransaction is rolled back, the
released inner subtransactions listed in its abort record do have
known associations, and their tuplecids must be removed from the
surviving toplevel's list. The existing tuplecid and tuplecid_restart
tests only cover aborts of subtransactions that wrote WAL themselves,
which is why this shape needs its own test.
Skipping the cleanup when the association of the xid being cleaned
is unknown is safe because of how a slot's restart point advances:
SnapBuildProcessRunningXacts() cannot move the restart point past
the oldest in-progress transaction, so any pass that output-decodes
the toplevel commit must have replayed the subtransaction's first
record and therefore knows 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 via
SnapBuildXactNeedsSkip(), so any stale tuplecid entries left behind
are dropped along with the transaction state and never reach
ReorderBufferBuildTupleCidHash().
Add an isolation test for the nested shape: the toplevel writes WAL
first, an inner subtransaction modifies a user catalog table and is
released, and the outer subtransaction -- which produces no WAL of
its own -- is then rolled back; with the page-fill and vacuum recipe
of tuplecid_restart, the toplevel's later insert deterministically
reuses the aborted subtransaction's line pointer. On unfixed assert
builds the final get_changes dies with the original cmin assertion
in ReorderBufferBuildTupleCidHash(); with the fix it passes. The
existing tests keep covering the simple savepoint and the restart
shapes.
Bug: #19555
Reported-by: Alexander Kozhemyakin <a.kozhemyakin@postgrespro.ru>
Based-on-patch-by: Mark Dilger
Discussion: https://postgr.es/m/CAHgHdKu5e3XY5e90Tuaxq_R4WrKxSV734Q%2BLwo5y39Omp2A-Gg@mail.gmail.com
---
contrib/test_decoding/Makefile | 6 +-
contrib/test_decoding/expected/tuplecid.out | 199 ++++++++++++++++++
.../expected/tuplecid_nested.out | 32 +++
.../expected/tuplecid_restart.out | 68 ++++++
.../test_decoding/specs/tuplecid_nested.spec | 77 +++++++
.../test_decoding/specs/tuplecid_restart.spec | 75 +++++++
contrib/test_decoding/sql/tuplecid.sql | 76 +++++++
src/backend/replication/logical/decode.c | 21 ++
.../replication/logical/reorderbuffer.c | 86 +++++++-
src/backend/replication/logical/snapbuild.c | 2 +-
src/include/replication/reorderbuffer.h | 10 +-
11 files changed, 647 insertions(+), 5 deletions(-)
create mode 100644 contrib/test_decoding/expected/tuplecid.out
create mode 100644 contrib/test_decoding/expected/tuplecid_nested.out
create mode 100644 contrib/test_decoding/expected/tuplecid_restart.out
create mode 100644 contrib/test_decoding/specs/tuplecid_nested.spec
create mode 100644 contrib/test_decoding/specs/tuplecid_restart.spec
create mode 100644 contrib/test_decoding/sql/tuplecid.sql
diff --git a/contrib/test_decoding/Makefile b/contrib/test_decoding/Makefile
index 02e961f4d31..123424724df 100644
--- a/contrib/test_decoding/Makefile
+++ b/contrib/test_decoding/Makefile
@@ -5,11 +5,13 @@ PGFILEDESC = "test_decoding - example of a logical decoding output plugin"
REGRESS = ddl xact rewrite toast permissions decoding_in_xact \
decoding_into_rel binary prepared replorigin time messages \
- spill slot truncate stream stats twophase twophase_stream
+ spill slot truncate stream stats twophase twophase_stream \
+ tuplecid
ISOLATION = mxact delayed_startup ondisk_startup concurrent_ddl_dml \
oldest_xmin snapshot_transfer subxact_without_top concurrent_stream \
twophase_snapshot slot_creation_error catalog_change_snapshot \
- skip_snapshot_restore invalidation_distribution
+ skip_snapshot_restore invalidation_distribution tuplecid_restart \
+ tuplecid_nested
REGRESS_OPTS = --temp-config $(top_srcdir)/contrib/test_decoding/logical.conf
ISOLATION_OPTS = --temp-config $(top_srcdir)/contrib/test_decoding/logical.conf
diff --git a/contrib/test_decoding/expected/tuplecid.out b/contrib/test_decoding/expected/tuplecid.out
new file mode 100644
index 00000000000..b559dd21bd4
--- /dev/null
+++ b/contrib/test_decoding/expected/tuplecid.out
@@ -0,0 +1,199 @@
+-- Tests for decoding of transactions in which a catalog-modifying
+-- subtransaction was rolled back (BUG #19555).
+--
+-- When a subtransaction modifies catalog tuples and is then rolled back,
+-- its dead heap-only line pointers can be marked LP_UNUSED by on-access
+-- pruning and reused by later catalog inserts of the same top-level
+-- transaction. The aborted subtransaction's xl_heap_new_cid records must
+-- not be consulted when building the historic snapshot used to decode the
+-- transaction; on unfixed builds they collide with the records of the
+-- reused line pointer and decoding dies with
+-- TRAP: failed Assert("ent->cmin == change->data.tuplecid.cmin")
+-- (or, on non-assert builds, silently uses wrong cmin/cmax mappings).
+--
+-- Whether the collision triggers depends on the physical layout of the
+-- catalog pages, so run in a fresh database where prior tests cannot have
+-- changed it, and loop enough times to leave headroom for layout
+-- differences across versions.
+CREATE DATABASE regression_tuplecid;
+-- snapshot the original database name (make and meson use different
+-- names for it) so we can switch back before dropping the test database
+\set prevdb :DBNAME
+\c regression_tuplecid
+-- predictability
+SET synchronous_commit = on;
+SELECT 'init' FROM pg_create_logical_replication_slot('regression_slot', 'test_decoding');
+ ?column?
+----------
+ init
+(1 row)
+
+-- Catalog churn to push the catalog pages into a state where on-access
+-- pruning frees the aborted subtransaction's line pointer and the second
+-- ALTER's catalog insert reuses it.
+CREATE TABLE tpc_filler1(f1 char(4));
+CREATE TABLE tpc_filler2(data text);
+INSERT INTO tpc_filler2 VALUES ('before-test');
+CREATE TYPE tpc_complex AS (r float8, i float8);
+CREATE TABLE tpc_filler3 (a int PRIMARY KEY, b text DEFAULT 'Unspecified');
+CREATE TABLE tpc_filler4 (id serial, t text);
+CREATE TABLE tpc_filler5(data text);
+INSERT INTO tpc_filler5 SELECT repeat('a', 2000) || g.i FROM generate_series(1, 1) g(i);
+TRUNCATE table tpc_filler5;
+CHECKPOINT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+ count
+-------
+ 9
+(1 row)
+
+-- Each iteration runs the trigger shape: catalog DDL inside a rolled-back
+-- subtransaction, then the same DDL again, then decode. Unfixed builds
+-- typically die within a handful of iterations.
+-- (temporarily hide the queries, to avoid flooding the expected output)
+\set ECHO none
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+DROP TABLE tpc_filler1;
+DROP TABLE tpc_filler2;
+DROP TYPE tpc_complex;
+DROP TABLE tpc_filler3;
+DROP TABLE tpc_filler4;
+DROP TABLE tpc_filler5;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+ count
+-------
+ 0
+(1 row)
+
+SELECT pg_drop_replication_slot('regression_slot');
+ pg_drop_replication_slot
+--------------------------
+
+(1 row)
+
+\c :prevdb
+DROP DATABASE regression_tuplecid;
diff --git a/contrib/test_decoding/expected/tuplecid_nested.out b/contrib/test_decoding/expected/tuplecid_nested.out
new file mode 100644
index 00000000000..5d816374fbc
--- /dev/null
+++ b/contrib/test_decoding/expected/tuplecid_nested.out
@@ -0,0 +1,32 @@
+Parsed test spec with 3 sessions
+
+starting permutation: s1_init s0_begin s0_topwrite s0_outer s0_inner s0_catinsert1 s0_release_inner s0_rollback_outer s2_vacuum s0_catinsert2 s0_commit s1_get_changes
+step s1_init: SELECT 'init' FROM pg_create_logical_replication_slot('tuplecid_nested_slot', 'test_decoding');
+?column?
+--------
+init
+(1 row)
+
+step s0_begin: BEGIN;
+step s0_topwrite: INSERT INTO tbl1 VALUES (0);
+step s0_outer: SAVEPOINT outer_sp;
+step s0_inner: SAVEPOINT inner_sp;
+step s0_catinsert1: INSERT INTO user_cat VALUES (5, 'e');
+step s0_release_inner: RELEASE SAVEPOINT inner_sp;
+step s0_rollback_outer: ROLLBACK TO SAVEPOINT outer_sp;
+step s2_vacuum: VACUUM user_cat;
+step s0_catinsert2: INSERT INTO user_cat VALUES (6, 'f');
+step s0_commit: COMMIT;
+step s1_get_changes: SELECT data FROM pg_logical_slot_get_changes('tuplecid_nested_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%';
+data
+------------------------------------------
+BEGIN
+table public.tbl1: INSERT: val1[integer]:0
+COMMIT
+(3 rows)
+
+?column?
+--------
+stop
+(1 row)
+
diff --git a/contrib/test_decoding/expected/tuplecid_restart.out b/contrib/test_decoding/expected/tuplecid_restart.out
new file mode 100644
index 00000000000..e5b4bc2543d
--- /dev/null
+++ b/contrib/test_decoding/expected/tuplecid_restart.out
@@ -0,0 +1,68 @@
+Parsed test spec with 3 sessions
+
+starting permutation: s0_init s0_begin s0_savepoint s0_insert s1_checkpoint s1_get_changes s0_catinsert1 s0_rollback s2_vacuum s0_catinsert2 s1_checkpoint s1_get_changes s0_commit s1_get_changes
+step s0_init: SELECT 'init' FROM pg_create_logical_replication_slot('isolation_slot', 'test_decoding');
+?column?
+--------
+init
+(1 row)
+
+step s0_begin: BEGIN;
+step s0_savepoint: SAVEPOINT sp1;
+step s0_insert: INSERT INTO tbl1 VALUES (1);
+step s1_checkpoint: CHECKPOINT;
+step s1_get_changes: SELECT data FROM pg_logical_slot_get_changes('isolation_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%';
+data
+----
+(0 rows)
+
+step s0_catinsert1: INSERT INTO user_cat VALUES (5, 'e');
+step s0_rollback: ROLLBACK TO SAVEPOINT sp1;
+step s2_vacuum: VACUUM user_cat;
+step s0_catinsert2: INSERT INTO user_cat VALUES (6, 'f');
+step s1_checkpoint: CHECKPOINT;
+step s1_get_changes: SELECT data FROM pg_logical_slot_get_changes('isolation_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%';
+data
+----
+(0 rows)
+
+step s0_commit: COMMIT;
+step s1_get_changes: SELECT data FROM pg_logical_slot_get_changes('isolation_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%';
+data
+------
+BEGIN
+COMMIT
+(2 rows)
+
+?column?
+--------
+stop
+(1 row)
+
+
+starting permutation: s0_begin s0_savepoint s0_insert s1_init s0_catinsert1 s0_rollback s2_vacuum s0_catinsert2 s0_commit s1_get_changes
+step s0_begin: BEGIN;
+step s0_savepoint: SAVEPOINT sp1;
+step s0_insert: INSERT INTO tbl1 VALUES (1);
+step s1_init: SELECT 'init' FROM pg_create_logical_replication_slot('isolation_slot', 'test_decoding'); <waiting ...>
+step s0_catinsert1: INSERT INTO user_cat VALUES (5, 'e');
+step s0_rollback: ROLLBACK TO SAVEPOINT sp1;
+step s2_vacuum: VACUUM user_cat;
+step s0_catinsert2: INSERT INTO user_cat VALUES (6, 'f');
+step s0_commit: COMMIT;
+step s1_init: <... completed>
+?column?
+--------
+init
+(1 row)
+
+step s1_get_changes: SELECT data FROM pg_logical_slot_get_changes('isolation_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%';
+data
+----
+(0 rows)
+
+?column?
+--------
+stop
+(1 row)
+
diff --git a/contrib/test_decoding/specs/tuplecid_nested.spec b/contrib/test_decoding/specs/tuplecid_nested.spec
new file mode 100644
index 00000000000..52c80eb55eb
--- /dev/null
+++ b/contrib/test_decoding/specs/tuplecid_nested.spec
@@ -0,0 +1,77 @@
+# Test decoding of a partially rolled back transaction where the aborted part
+# is nested: the aborting outer subtransaction never produced any WAL of its
+# own, so decoding cannot know its toplevel transaction, while an inner
+# subtransaction it rolls back did produce WAL and its tuplecid records still
+# have to be removed (BUG #19555 nested shape).
+#
+# The tuplecid records written by the aborted inner subtransaction are queued
+# on the toplevel transaction and must be removed when the outer
+# subtransaction's abort is decoded; otherwise they collide with the records
+# of the line pointer that gets reused by the toplevel transaction's later
+# catalog insert, failing Assert(ent->cmin == change->data.tuplecid.cmin) in
+# ReorderBufferBuildTupleCidHash() when the commit is decoded.
+#
+# - s0_topwrite makes the toplevel transaction produce its first WAL record
+# before any subtransaction exists.
+# - s0_outer establishes the outer savepoint, which never gets a WAL record
+# of its own.
+# - s0_catinsert1 generates an xl_heap_new_cid record in the inner
+# subtransaction, which is then released.
+# - s0_rollback_outer rolls the outer savepoint back. Its abort record is
+# written once the backend is already in TRANS_ABORT, so it carries no
+# toplevel xid in its header and the outer subtransaction's association
+# with the toplevel can never be established. The released inner
+# subtransaction is listed in the same abort record, though, and its
+# tuplecid records still must be removed from the toplevel's list.
+# - s2_vacuum reclaims the aborted row's line pointer (dead inserts are
+# removed regardless of the xid horizon, so this is deterministic even
+# while the toplevel transaction is still open); s0_catinsert2 then reuses
+# the same tid with a different cmin.
+# - s1_get_changes then decodes the toplevel commit and builds the tuplecid
+# hash; on unfixed builds the stale tuplecid of the aborted inner
+# subtransaction collides there with the fresh one.
+setup
+{
+ DROP TABLE IF EXISTS tbl1;
+ DROP TABLE IF EXISTS user_cat;
+ CREATE TABLE tbl1 (val1 integer);
+ -- Four rows of ~1.5kB fill the first heap page to within a few hundred
+ -- bytes, so that vacuuming away the aborted fifth row leaves exactly one
+ -- line pointer for the next insert to reuse.
+ CREATE TABLE user_cat (c1 int, filler char(1500)) WITH (user_catalog_table = true);
+ INSERT INTO user_cat VALUES (1, 'a'), (2, 'b'), (3, 'c'), (4, 'd');
+}
+
+teardown
+{
+ DROP TABLE tbl1;
+ DROP TABLE user_cat;
+ SELECT 'stop' FROM pg_drop_replication_slot('tuplecid_nested_slot');
+}
+
+session "s0"
+setup { SET synchronous_commit=on; }
+step "s0_begin" { BEGIN; }
+step "s0_topwrite" { INSERT INTO tbl1 VALUES (0); }
+step "s0_outer" { SAVEPOINT outer_sp; }
+step "s0_inner" { SAVEPOINT inner_sp; }
+step "s0_catinsert1" { INSERT INTO user_cat VALUES (5, 'e'); }
+step "s0_release_inner" { RELEASE SAVEPOINT inner_sp; }
+step "s0_rollback_outer" { ROLLBACK TO SAVEPOINT outer_sp; }
+step "s0_catinsert2" { INSERT INTO user_cat VALUES (6, 'f'); }
+step "s0_commit" { COMMIT; }
+
+session "s1"
+setup { SET synchronous_commit=on; }
+step "s1_init" { SELECT 'init' FROM pg_create_logical_replication_slot('tuplecid_nested_slot', 'test_decoding'); }
+# The user_cat rows carry ~1.5kB filler values which would flood the expected
+# output; filter them out (decoding still processes them server-side).
+step "s1_get_changes" { SELECT data FROM pg_logical_slot_get_changes('tuplecid_nested_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%'; }
+
+session "s2"
+setup { SET synchronous_commit=on; }
+step "s2_vacuum" { VACUUM user_cat; }
+
+# The slot is created before the transaction begins, so the final
+# s1_get_changes decodes the whole transaction through its commit.
+permutation "s1_init" "s0_begin" "s0_topwrite" "s0_outer" "s0_inner" "s0_catinsert1" "s0_release_inner" "s0_rollback_outer" "s2_vacuum" "s0_catinsert2" "s0_commit" "s1_get_changes"
diff --git a/contrib/test_decoding/specs/tuplecid_restart.spec b/contrib/test_decoding/specs/tuplecid_restart.spec
new file mode 100644
index 00000000000..58da414e8b7
--- /dev/null
+++ b/contrib/test_decoding/specs/tuplecid_restart.spec
@@ -0,0 +1,75 @@
+# Test decoding of a transaction in which a catalog-modifying subtransaction
+# was rolled back, where the transaction spans a logical decoding restart
+# point (BUG #19555 restart shape).
+#
+# The tuplecid records written by the aborted subtransaction are queued on the
+# toplevel transaction and must be removed when the subtransaction's abort is
+# decoded; otherwise they collide with the records of the line pointer that
+# gets reused by the toplevel transaction's later catalog insert, failing
+# Assert(ent->cmin == change->data.tuplecid.cmin) in
+# ReorderBufferBuildTupleCidHash() when the commit is decoded.
+#
+# - s0_insert runs in a subtransaction and produces its first WAL record.
+# - s0_catinsert1 generates an xl_heap_new_cid record in that subtransaction.
+# - s0_rollback aborts the subtransaction.
+# - s2_vacuum reclaims the aborted row's line pointer (dead inserts are
+# removed regardless of the xid horizon, so this is deterministic even
+# while the toplevel transaction is still open); s0_catinsert2 then reuses
+# the same tid with a different cmin.
+# - The transaction stays open across both checkpoints, so the final
+# s1_get_changes replays the transaction's records from the first
+# checkpoint and decodes its commit for output, building the tuplecid
+# hash. On unfixed builds the stale tuplecid of the aborted
+# subtransaction collides there with the fresh one.
+setup
+{
+ DROP TABLE IF EXISTS tbl1;
+ DROP TABLE IF EXISTS user_cat;
+ CREATE TABLE tbl1 (val1 integer);
+ -- Four rows of ~1.5kB fill the first heap page to within a few hundred
+ -- bytes, so that vacuuming away the aborted fifth row leaves exactly one
+ -- line pointer for the next insert to reuse.
+ CREATE TABLE user_cat (c1 int, filler char(1500)) WITH (user_catalog_table = true);
+ INSERT INTO user_cat VALUES (1, 'a'), (2, 'b'), (3, 'c'), (4, 'd');
+}
+
+teardown
+{
+ DROP TABLE tbl1;
+ DROP TABLE user_cat;
+ SELECT 'stop' FROM pg_drop_replication_slot('isolation_slot');
+}
+
+session "s0"
+setup { SET synchronous_commit=on; }
+step "s0_init" { SELECT 'init' FROM pg_create_logical_replication_slot('isolation_slot', 'test_decoding'); }
+step "s0_begin" { BEGIN; }
+step "s0_savepoint" { SAVEPOINT sp1; }
+step "s0_insert" { INSERT INTO tbl1 VALUES (1); }
+step "s0_catinsert1" { INSERT INTO user_cat VALUES (5, 'e'); }
+step "s0_rollback" { ROLLBACK TO SAVEPOINT sp1; }
+step "s0_catinsert2" { INSERT INTO user_cat VALUES (6, 'f'); }
+step "s0_commit" { COMMIT; }
+
+session "s1"
+setup { SET synchronous_commit=on; }
+step "s1_init" { SELECT 'init' FROM pg_create_logical_replication_slot('isolation_slot', 'test_decoding'); }
+step "s1_checkpoint" { CHECKPOINT; }
+# The user_cat rows carry ~1.5kB filler values which would flood the expected
+# output; filter them out (decoding still processes them server-side).
+step "s1_get_changes" { SELECT data FROM pg_logical_slot_get_changes('isolation_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%'; }
+
+session "s2"
+setup { SET synchronous_commit=on; }
+step "s2_vacuum" { VACUUM user_cat; }
+
+# The transaction commits only after the second s1_get_changes, so the last
+# s1_get_changes both replays the transaction from the first checkpoint and
+# decodes its commit for output.
+permutation "s0_init" "s0_begin" "s0_savepoint" "s0_insert" "s1_checkpoint" "s1_get_changes" "s0_catinsert1" "s0_rollback" "s2_vacuum" "s0_catinsert2" "s1_checkpoint" "s1_get_changes" "s0_commit" "s1_get_changes"
+
+# Variant with the slot created while the transaction is already open: slot
+# creation waits for a consistent point past the open transaction, so the
+# transaction is never decoded by this slot at all (no output). This locks in
+# the behavior that decoding cannot start in the middle of a transaction.
+permutation "s0_begin" "s0_savepoint" "s0_insert" "s1_init" "s0_catinsert1" "s0_rollback" "s2_vacuum" "s0_catinsert2" "s0_commit" "s1_get_changes"
diff --git a/contrib/test_decoding/sql/tuplecid.sql b/contrib/test_decoding/sql/tuplecid.sql
new file mode 100644
index 00000000000..335fb6d1591
--- /dev/null
+++ b/contrib/test_decoding/sql/tuplecid.sql
@@ -0,0 +1,76 @@
+-- Tests for decoding of transactions in which a catalog-modifying
+-- subtransaction was rolled back (BUG #19555).
+--
+-- When a subtransaction modifies catalog tuples and is then rolled back,
+-- its dead heap-only line pointers can be marked LP_UNUSED by on-access
+-- pruning and reused by later catalog inserts of the same top-level
+-- transaction. The aborted subtransaction's xl_heap_new_cid records must
+-- not be consulted when building the historic snapshot used to decode the
+-- transaction; on unfixed builds they collide with the records of the
+-- reused line pointer and decoding dies with
+-- TRAP: failed Assert("ent->cmin == change->data.tuplecid.cmin")
+-- (or, on non-assert builds, silently uses wrong cmin/cmax mappings).
+--
+-- Whether the collision triggers depends on the physical layout of the
+-- catalog pages, so run in a fresh database where prior tests cannot have
+-- changed it, and loop enough times to leave headroom for layout
+-- differences across versions.
+CREATE DATABASE regression_tuplecid;
+-- snapshot the original database name (make and meson use different
+-- names for it) so we can switch back before dropping the test database
+\set prevdb :DBNAME
+\c regression_tuplecid
+
+-- predictability
+SET synchronous_commit = on;
+
+SELECT 'init' FROM pg_create_logical_replication_slot('regression_slot', 'test_decoding');
+
+-- Catalog churn to push the catalog pages into a state where on-access
+-- pruning frees the aborted subtransaction's line pointer and the second
+-- ALTER's catalog insert reuses it.
+CREATE TABLE tpc_filler1(f1 char(4));
+CREATE TABLE tpc_filler2(data text);
+INSERT INTO tpc_filler2 VALUES ('before-test');
+CREATE TYPE tpc_complex AS (r float8, i float8);
+CREATE TABLE tpc_filler3 (a int PRIMARY KEY, b text DEFAULT 'Unspecified');
+CREATE TABLE tpc_filler4 (id serial, t text);
+CREATE TABLE tpc_filler5(data text);
+INSERT INTO tpc_filler5 SELECT repeat('a', 2000) || g.i FROM generate_series(1, 1) g(i);
+TRUNCATE table tpc_filler5;
+CHECKPOINT;
+
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+
+-- Each iteration runs the trigger shape: catalog DDL inside a rolled-back
+-- subtransaction, then the same DDL again, then decode. Unfixed builds
+-- typically die within a handful of iterations.
+-- (temporarily hide the queries, to avoid flooding the expected output)
+\set ECHO none
+SELECT format($fmt$
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+$fmt$)
+FROM generate_series(1, 25) \gexec
+\set ECHO all
+
+DROP TABLE tpc_filler1;
+DROP TABLE tpc_filler2;
+DROP TYPE tpc_complex;
+DROP TABLE tpc_filler3;
+DROP TABLE tpc_filler4;
+DROP TABLE tpc_filler5;
+
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+
+SELECT pg_drop_replication_slot('regression_slot');
+
+\c :prevdb
+DROP DATABASE regression_tuplecid;
diff --git a/src/backend/replication/logical/decode.c b/src/backend/replication/logical/decode.c
index 466fb37719e..f22fbb62440 100644
--- a/src/backend/replication/logical/decode.c
+++ b/src/backend/replication/logical/decode.c
@@ -848,12 +848,33 @@ DecodeAbort(LogicalDecodingContext *ctx, XLogRecordBuffer *buf,
}
else
{
+ /*
+ * Remove tuplecid changes queued by the aborted (sub)transactions
+ * from the toplevel's list, before the transactions are torn down.
+ * The abort record's primary xid tells
+ * ReorderBufferCleanupSubTxnTupleCids() whether the whole toplevel
+ * is going away, in which case scanning the list is pointless.
+ *
+ * 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.
+ */
for (i = 0; i < parsed->nsubxacts; i++)
{
+ ReorderBufferCleanupSubTxnTupleCids(ctx->reorder,
+ parsed->subxacts[i],
+ xid);
ReorderBufferAbort(ctx->reorder, parsed->subxacts[i],
buf->record->EndRecPtr);
}
+ ReorderBufferCleanupSubTxnTupleCids(ctx->reorder, xid, xid);
ReorderBufferAbort(ctx->reorder, xid, buf->record->EndRecPtr);
}
diff --git a/src/backend/replication/logical/reorderbuffer.c b/src/backend/replication/logical/reorderbuffer.c
index ca2b5f117c2..270d371f362 100644
--- a/src/backend/replication/logical/reorderbuffer.c
+++ b/src/backend/replication/logical/reorderbuffer.c
@@ -2951,6 +2951,88 @@ ReorderBufferAbort(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn)
ReorderBufferCleanupTXN(rb, txn);
}
+/*
+ * Remove tuplecid changes queued by subtransaction xid from its toplevel
+ * transaction's list.
+ *
+ * Unlike regular changes, tuplecid changes are always queued on the toplevel
+ * transaction (see ReorderBufferAddNewTupleCids), so they would otherwise
+ * survive the abort of the subtransaction that wrote them. That's wrong:
+ * they describe catalog tuple versions created or killed by the aborted
+ * subtransaction, which never became visible, and keeping them can corrupt
+ * ReorderBufferBuildTupleCidHash() at commit time -- both when the toplevel
+ * transaction later reuses the same tid (the stale entry collides with the
+ * fresh one, breaking the cmin equality assumption) and when nothing touches
+ * the tid again (a stale cmax would make a still-live tuple look deleted on
+ * historic snapshots).
+ *
+ * The cleanup is pointless when the whole toplevel transaction is
+ * being aborted, since ReorderBufferCleanupTXN() frees the whole list
+ * anyway; the caller passes the abort record's primary xid and we skip
+ * the scan when it is xid's toplevel. Note that the opposite decision
+ * -- cleaning only when the primary xid's own association is known --
+ * would be wrong: abort records are written once the subtransaction is
+ * already in TRANS_ABORT, so they carry no toplevel xid in their
+ * header, and an outer subtransaction that never wrote WAL of its own
+ * never gets an association at all. When such an outer subtransaction
+ * rolls back, released inner subtransactions listed in its abort record
+ * do have known associations and are cleaned here.
+ *
+ * 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().
+ */
+void
+ReorderBufferCleanupSubTxnTupleCids(ReorderBuffer *rb, TransactionId xid,
+ TransactionId primary_xid)
+{
+ ReorderBufferTXN *txn;
+ ReorderBufferTXN *toptxn;
+ dlist_mutable_iter it;
+
+ txn = ReorderBufferTXNByXid(rb, xid, false, NULL, InvalidXLogRecPtr,
+ false);
+
+ /* unknown transaction, or unknown association: nothing to remove */
+ if (txn == NULL || !rbtxn_is_known_subxact(txn))
+ return;
+
+ toptxn = txn->toptxn;
+
+ /*
+ * The whole toplevel transaction is being aborted (the abort record's
+ * primary xid is xid's toplevel): ReorderBufferCleanupTXN() will free
+ * the whole list shortly, don't scan it once per aborted subxid.
+ */
+ if (toptxn->xid == primary_xid)
+ return;
+
+ dlist_foreach_modify(it, &toptxn->tuplecids)
+ {
+ ReorderBufferChange *change;
+
+ change = dlist_container(ReorderBufferChange, node, it.cur);
+
+ Assert(change->action == REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID);
+
+ if (change->data.tuplecid.subxid == xid)
+ {
+ dlist_delete(&change->node);
+ ReorderBufferReturnChange(rb, change, false);
+ toptxn->ntuplecids--;
+ }
+ }
+}
+
/*
* Abort all transactions that aren't actually running anymore because the
* server restarted.
@@ -3263,7 +3345,8 @@ void
ReorderBufferAddNewTupleCids(ReorderBuffer *rb, TransactionId xid,
XLogRecPtr lsn, RelFileNode node,
ItemPointerData tid, CommandId cmin,
- CommandId cmax, CommandId combocid)
+ CommandId cmax, CommandId combocid,
+ TransactionId subxid)
{
ReorderBufferChange *change = ReorderBufferGetChange(rb);
ReorderBufferTXN *txn;
@@ -3275,6 +3358,7 @@ ReorderBufferAddNewTupleCids(ReorderBuffer *rb, TransactionId xid,
change->data.tuplecid.cmin = cmin;
change->data.tuplecid.cmax = cmax;
change->data.tuplecid.combocid = combocid;
+ change->data.tuplecid.subxid = subxid;
change->lsn = lsn;
change->txn = txn;
change->action = REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID;
diff --git a/src/backend/replication/logical/snapbuild.c b/src/backend/replication/logical/snapbuild.c
index 122c7838d8c..5e34a2daa2f 100644
--- a/src/backend/replication/logical/snapbuild.c
+++ b/src/backend/replication/logical/snapbuild.c
@@ -876,7 +876,7 @@ SnapBuildProcessNewCid(SnapBuild *builder, TransactionId xid,
ReorderBufferAddNewTupleCids(builder->reorder, xlrec->top_xid, lsn,
xlrec->target_node, xlrec->target_tid,
xlrec->cmin, xlrec->cmax,
- xlrec->combocid);
+ xlrec->combocid, xid);
/* figure out new command id */
if (xlrec->cmin != InvalidCommandId &&
diff --git a/src/include/replication/reorderbuffer.h b/src/include/replication/reorderbuffer.h
index af154587618..e45033c6bab 100644
--- a/src/include/replication/reorderbuffer.h
+++ b/src/include/replication/reorderbuffer.h
@@ -150,6 +150,11 @@ typedef struct ReorderBufferChange
CommandId cmin;
CommandId cmax;
CommandId combocid;
+ TransactionId subxid; /* xid that wrote the tuplecid record;
+ * differs from the xid of the txn this
+ * change is queued on (always the
+ * toplevel xid) when a subtransaction
+ * modified the catalog */
} tuplecid;
/* Invalidation. */
@@ -661,6 +666,8 @@ extern void ReorderBufferAssignChild(ReorderBuffer *, TransactionId, Transaction
extern void ReorderBufferCommitChild(ReorderBuffer *, TransactionId, TransactionId,
XLogRecPtr commit_lsn, XLogRecPtr end_lsn);
extern void ReorderBufferAbort(ReorderBuffer *, TransactionId, XLogRecPtr lsn);
+extern void ReorderBufferCleanupSubTxnTupleCids(ReorderBuffer *rb, TransactionId xid,
+ TransactionId primary_xid);
extern void ReorderBufferAbortOld(ReorderBuffer *, TransactionId xid);
extern void ReorderBufferForget(ReorderBuffer *, TransactionId, XLogRecPtr lsn);
extern void ReorderBufferInvalidate(ReorderBuffer *, TransactionId, XLogRecPtr lsn);
@@ -671,7 +678,8 @@ extern void ReorderBufferAddNewCommandId(ReorderBuffer *, TransactionId, XLogRec
CommandId cid);
extern void ReorderBufferAddNewTupleCids(ReorderBuffer *, TransactionId, XLogRecPtr lsn,
RelFileNode node, ItemPointerData pt,
- CommandId cmin, CommandId cmax, CommandId combocid);
+ CommandId cmin, CommandId cmax,
+ CommandId combocid, TransactionId subxid);
extern void ReorderBufferAddInvalidations(ReorderBuffer *, TransactionId, XLogRecPtr lsn,
Size nmsgs, SharedInvalidationMessage *msgs);
extern void ReorderBufferAddDistributedInvalidations(ReorderBuffer *rb, TransactionId xid,
--
2.43.0
v5-REL_16_STABLE-0001-Fix-stale-tuplecid-records-left-behind-by-aborted.patch (application/octet-stream, 35.4K) download
From cd2342acec3c3c2b56e1e535e5333ad461a5cfcc Mon Sep 17 00:00:00 2001
From: Bingshuai Li <lucian1412@outlook.com>
Date: Wed, 30 Sep 2026 12:07:54 +0800
Subject: [PATCH] Fix stale tuplecid records left behind by aborted
subtransactions
Tuplecid changes are always queued on the toplevel transaction, so
unlike regular changes they are not dropped when the subtransaction
that wrote them aborts. The stale mappings corrupt
ReorderBufferBuildTupleCidHash() at commit time: if a later catalog
insert reuses the aborted subtransaction's line pointer (made
LP_UNUSED by on-access pruning or by vacuum), the fresh record
collides with the stale one with a different cmin, tripping the cmin
equality assertion; where nothing reuses the tid, a stale cmax makes
a still-live catalog tuple look deleted on historic snapshots. On
non-assert builds there is no crash, but the stale mappings risk
misjudging historic catalog visibility, which could produce
incorrect decoding output.
Remove the aborted subtransaction's tuplecid entries when its abort
is decoded. The cleanup is not needed when the whole toplevel
transaction is being aborted, because ReorderBufferCleanupTXN()
frees the whole list anyway; to avoid scanning the list once per
aborted subxid in that case, DecodeAbort() passes the abort record's
primary xid to the new ReorderBufferCleanupSubTxnTupleCids(), which
skips the scan when that xid is the toplevel of the xid being
cleaned.
The decision cannot be based on whether the primary xid's own
association with its toplevel is known: abort records are written
after the subtransaction has entered TRANS_ABORT, so they never
carry the toplevel xid in their header, and an outer subtransaction
that never wrote WAL of its own -- for example a savepoint that only
wraps other savepoints -- can never get its association established
at all. When such an outer subtransaction is rolled back, the
released inner subtransactions listed in its abort record do have
known associations, and their tuplecids must be removed from the
surviving toplevel's list. The existing tuplecid and tuplecid_restart
tests only cover aborts of subtransactions that wrote WAL themselves,
which is why this shape needs its own test.
Skipping the cleanup when the association of the xid being cleaned
is unknown is safe because of how a slot's restart point advances:
SnapBuildProcessRunningXacts() cannot move the restart point past
the oldest in-progress transaction, so any pass that output-decodes
the toplevel commit must have replayed the subtransaction's first
record and therefore knows 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 via
SnapBuildXactNeedsSkip(), so any stale tuplecid entries left behind
are dropped along with the transaction state and never reach
ReorderBufferBuildTupleCidHash().
Add an isolation test for the nested shape: the toplevel writes WAL
first, an inner subtransaction modifies a user catalog table and is
released, and the outer subtransaction -- which produces no WAL of
its own -- is then rolled back; with the page-fill and vacuum recipe
of tuplecid_restart, the toplevel's later insert deterministically
reuses the aborted subtransaction's line pointer. On unfixed assert
builds the final get_changes dies with the original cmin assertion
in ReorderBufferBuildTupleCidHash(); with the fix it passes. The
existing tests keep covering the simple savepoint and the restart
shapes.
Bug: #19555
Reported-by: Alexander Kozhemyakin <a.kozhemyakin@postgrespro.ru>
Based-on-patch-by: Mark Dilger
Discussion: https://postgr.es/m/CAHgHdKu5e3XY5e90Tuaxq_R4WrKxSV734Q%2BLwo5y39Omp2A-Gg@mail.gmail.com
---
contrib/test_decoding/Makefile | 6 +-
contrib/test_decoding/expected/tuplecid.out | 199 ++++++++++++++++++
.../expected/tuplecid_nested.out | 32 +++
.../expected/tuplecid_restart.out | 68 ++++++
contrib/test_decoding/meson.build | 3 +
.../test_decoding/specs/tuplecid_nested.spec | 77 +++++++
.../test_decoding/specs/tuplecid_restart.spec | 75 +++++++
contrib/test_decoding/sql/tuplecid.sql | 76 +++++++
src/backend/replication/logical/decode.c | 21 ++
.../replication/logical/reorderbuffer.c | 86 +++++++-
src/backend/replication/logical/snapbuild.c | 2 +-
src/include/replication/reorderbuffer.h | 11 +-
12 files changed, 651 insertions(+), 5 deletions(-)
create mode 100644 contrib/test_decoding/expected/tuplecid.out
create mode 100644 contrib/test_decoding/expected/tuplecid_nested.out
create mode 100644 contrib/test_decoding/expected/tuplecid_restart.out
create mode 100644 contrib/test_decoding/specs/tuplecid_nested.spec
create mode 100644 contrib/test_decoding/specs/tuplecid_restart.spec
create mode 100644 contrib/test_decoding/sql/tuplecid.sql
diff --git a/contrib/test_decoding/Makefile b/contrib/test_decoding/Makefile
index 02e961f4d31..0583786f9f5 100644
--- a/contrib/test_decoding/Makefile
+++ b/contrib/test_decoding/Makefile
@@ -5,11 +5,13 @@ PGFILEDESC = "test_decoding - example of a logical decoding output plugin"
REGRESS = ddl xact rewrite toast permissions decoding_in_xact \
decoding_into_rel binary prepared replorigin time messages \
- spill slot truncate stream stats twophase twophase_stream
+ spill slot truncate stream stats twophase twophase_stream \
+ tuplecid
ISOLATION = mxact delayed_startup ondisk_startup concurrent_ddl_dml \
oldest_xmin snapshot_transfer subxact_without_top concurrent_stream \
twophase_snapshot slot_creation_error catalog_change_snapshot \
- skip_snapshot_restore invalidation_distribution
+ skip_snapshot_restore invalidation_distribution \
+ tuplecid_restart tuplecid_nested
REGRESS_OPTS = --temp-config $(top_srcdir)/contrib/test_decoding/logical.conf
ISOLATION_OPTS = --temp-config $(top_srcdir)/contrib/test_decoding/logical.conf
diff --git a/contrib/test_decoding/expected/tuplecid.out b/contrib/test_decoding/expected/tuplecid.out
new file mode 100644
index 00000000000..b559dd21bd4
--- /dev/null
+++ b/contrib/test_decoding/expected/tuplecid.out
@@ -0,0 +1,199 @@
+-- Tests for decoding of transactions in which a catalog-modifying
+-- subtransaction was rolled back (BUG #19555).
+--
+-- When a subtransaction modifies catalog tuples and is then rolled back,
+-- its dead heap-only line pointers can be marked LP_UNUSED by on-access
+-- pruning and reused by later catalog inserts of the same top-level
+-- transaction. The aborted subtransaction's xl_heap_new_cid records must
+-- not be consulted when building the historic snapshot used to decode the
+-- transaction; on unfixed builds they collide with the records of the
+-- reused line pointer and decoding dies with
+-- TRAP: failed Assert("ent->cmin == change->data.tuplecid.cmin")
+-- (or, on non-assert builds, silently uses wrong cmin/cmax mappings).
+--
+-- Whether the collision triggers depends on the physical layout of the
+-- catalog pages, so run in a fresh database where prior tests cannot have
+-- changed it, and loop enough times to leave headroom for layout
+-- differences across versions.
+CREATE DATABASE regression_tuplecid;
+-- snapshot the original database name (make and meson use different
+-- names for it) so we can switch back before dropping the test database
+\set prevdb :DBNAME
+\c regression_tuplecid
+-- predictability
+SET synchronous_commit = on;
+SELECT 'init' FROM pg_create_logical_replication_slot('regression_slot', 'test_decoding');
+ ?column?
+----------
+ init
+(1 row)
+
+-- Catalog churn to push the catalog pages into a state where on-access
+-- pruning frees the aborted subtransaction's line pointer and the second
+-- ALTER's catalog insert reuses it.
+CREATE TABLE tpc_filler1(f1 char(4));
+CREATE TABLE tpc_filler2(data text);
+INSERT INTO tpc_filler2 VALUES ('before-test');
+CREATE TYPE tpc_complex AS (r float8, i float8);
+CREATE TABLE tpc_filler3 (a int PRIMARY KEY, b text DEFAULT 'Unspecified');
+CREATE TABLE tpc_filler4 (id serial, t text);
+CREATE TABLE tpc_filler5(data text);
+INSERT INTO tpc_filler5 SELECT repeat('a', 2000) || g.i FROM generate_series(1, 1) g(i);
+TRUNCATE table tpc_filler5;
+CHECKPOINT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+ count
+-------
+ 9
+(1 row)
+
+-- Each iteration runs the trigger shape: catalog DDL inside a rolled-back
+-- subtransaction, then the same DDL again, then decode. Unfixed builds
+-- typically die within a handful of iterations.
+-- (temporarily hide the queries, to avoid flooding the expected output)
+\set ECHO none
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+DROP TABLE tpc_filler1;
+DROP TABLE tpc_filler2;
+DROP TYPE tpc_complex;
+DROP TABLE tpc_filler3;
+DROP TABLE tpc_filler4;
+DROP TABLE tpc_filler5;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+ count
+-------
+ 0
+(1 row)
+
+SELECT pg_drop_replication_slot('regression_slot');
+ pg_drop_replication_slot
+--------------------------
+
+(1 row)
+
+\c :prevdb
+DROP DATABASE regression_tuplecid;
diff --git a/contrib/test_decoding/expected/tuplecid_nested.out b/contrib/test_decoding/expected/tuplecid_nested.out
new file mode 100644
index 00000000000..5d816374fbc
--- /dev/null
+++ b/contrib/test_decoding/expected/tuplecid_nested.out
@@ -0,0 +1,32 @@
+Parsed test spec with 3 sessions
+
+starting permutation: s1_init s0_begin s0_topwrite s0_outer s0_inner s0_catinsert1 s0_release_inner s0_rollback_outer s2_vacuum s0_catinsert2 s0_commit s1_get_changes
+step s1_init: SELECT 'init' FROM pg_create_logical_replication_slot('tuplecid_nested_slot', 'test_decoding');
+?column?
+--------
+init
+(1 row)
+
+step s0_begin: BEGIN;
+step s0_topwrite: INSERT INTO tbl1 VALUES (0);
+step s0_outer: SAVEPOINT outer_sp;
+step s0_inner: SAVEPOINT inner_sp;
+step s0_catinsert1: INSERT INTO user_cat VALUES (5, 'e');
+step s0_release_inner: RELEASE SAVEPOINT inner_sp;
+step s0_rollback_outer: ROLLBACK TO SAVEPOINT outer_sp;
+step s2_vacuum: VACUUM user_cat;
+step s0_catinsert2: INSERT INTO user_cat VALUES (6, 'f');
+step s0_commit: COMMIT;
+step s1_get_changes: SELECT data FROM pg_logical_slot_get_changes('tuplecid_nested_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%';
+data
+------------------------------------------
+BEGIN
+table public.tbl1: INSERT: val1[integer]:0
+COMMIT
+(3 rows)
+
+?column?
+--------
+stop
+(1 row)
+
diff --git a/contrib/test_decoding/expected/tuplecid_restart.out b/contrib/test_decoding/expected/tuplecid_restart.out
new file mode 100644
index 00000000000..e5b4bc2543d
--- /dev/null
+++ b/contrib/test_decoding/expected/tuplecid_restart.out
@@ -0,0 +1,68 @@
+Parsed test spec with 3 sessions
+
+starting permutation: s0_init s0_begin s0_savepoint s0_insert s1_checkpoint s1_get_changes s0_catinsert1 s0_rollback s2_vacuum s0_catinsert2 s1_checkpoint s1_get_changes s0_commit s1_get_changes
+step s0_init: SELECT 'init' FROM pg_create_logical_replication_slot('isolation_slot', 'test_decoding');
+?column?
+--------
+init
+(1 row)
+
+step s0_begin: BEGIN;
+step s0_savepoint: SAVEPOINT sp1;
+step s0_insert: INSERT INTO tbl1 VALUES (1);
+step s1_checkpoint: CHECKPOINT;
+step s1_get_changes: SELECT data FROM pg_logical_slot_get_changes('isolation_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%';
+data
+----
+(0 rows)
+
+step s0_catinsert1: INSERT INTO user_cat VALUES (5, 'e');
+step s0_rollback: ROLLBACK TO SAVEPOINT sp1;
+step s2_vacuum: VACUUM user_cat;
+step s0_catinsert2: INSERT INTO user_cat VALUES (6, 'f');
+step s1_checkpoint: CHECKPOINT;
+step s1_get_changes: SELECT data FROM pg_logical_slot_get_changes('isolation_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%';
+data
+----
+(0 rows)
+
+step s0_commit: COMMIT;
+step s1_get_changes: SELECT data FROM pg_logical_slot_get_changes('isolation_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%';
+data
+------
+BEGIN
+COMMIT
+(2 rows)
+
+?column?
+--------
+stop
+(1 row)
+
+
+starting permutation: s0_begin s0_savepoint s0_insert s1_init s0_catinsert1 s0_rollback s2_vacuum s0_catinsert2 s0_commit s1_get_changes
+step s0_begin: BEGIN;
+step s0_savepoint: SAVEPOINT sp1;
+step s0_insert: INSERT INTO tbl1 VALUES (1);
+step s1_init: SELECT 'init' FROM pg_create_logical_replication_slot('isolation_slot', 'test_decoding'); <waiting ...>
+step s0_catinsert1: INSERT INTO user_cat VALUES (5, 'e');
+step s0_rollback: ROLLBACK TO SAVEPOINT sp1;
+step s2_vacuum: VACUUM user_cat;
+step s0_catinsert2: INSERT INTO user_cat VALUES (6, 'f');
+step s0_commit: COMMIT;
+step s1_init: <... completed>
+?column?
+--------
+init
+(1 row)
+
+step s1_get_changes: SELECT data FROM pg_logical_slot_get_changes('isolation_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%';
+data
+----
+(0 rows)
+
+?column?
+--------
+stop
+(1 row)
+
diff --git a/contrib/test_decoding/meson.build b/contrib/test_decoding/meson.build
index 3c99ba472c0..d0d7a93a1f9 100644
--- a/contrib/test_decoding/meson.build
+++ b/contrib/test_decoding/meson.build
@@ -41,6 +41,7 @@ tests += {
'stats',
'twophase',
'twophase_stream',
+ 'tuplecid',
],
'regress_args': [
'--temp-config', files('logical.conf'),
@@ -64,6 +65,8 @@ tests += {
'slot_creation_error',
'skip_snapshot_restore',
'invalidation_distribution',
+ 'tuplecid_restart',
+ 'tuplecid_nested',
],
'regress_args': [
'--temp-config', files('logical.conf'),
diff --git a/contrib/test_decoding/specs/tuplecid_nested.spec b/contrib/test_decoding/specs/tuplecid_nested.spec
new file mode 100644
index 00000000000..52c80eb55eb
--- /dev/null
+++ b/contrib/test_decoding/specs/tuplecid_nested.spec
@@ -0,0 +1,77 @@
+# Test decoding of a partially rolled back transaction where the aborted part
+# is nested: the aborting outer subtransaction never produced any WAL of its
+# own, so decoding cannot know its toplevel transaction, while an inner
+# subtransaction it rolls back did produce WAL and its tuplecid records still
+# have to be removed (BUG #19555 nested shape).
+#
+# The tuplecid records written by the aborted inner subtransaction are queued
+# on the toplevel transaction and must be removed when the outer
+# subtransaction's abort is decoded; otherwise they collide with the records
+# of the line pointer that gets reused by the toplevel transaction's later
+# catalog insert, failing Assert(ent->cmin == change->data.tuplecid.cmin) in
+# ReorderBufferBuildTupleCidHash() when the commit is decoded.
+#
+# - s0_topwrite makes the toplevel transaction produce its first WAL record
+# before any subtransaction exists.
+# - s0_outer establishes the outer savepoint, which never gets a WAL record
+# of its own.
+# - s0_catinsert1 generates an xl_heap_new_cid record in the inner
+# subtransaction, which is then released.
+# - s0_rollback_outer rolls the outer savepoint back. Its abort record is
+# written once the backend is already in TRANS_ABORT, so it carries no
+# toplevel xid in its header and the outer subtransaction's association
+# with the toplevel can never be established. The released inner
+# subtransaction is listed in the same abort record, though, and its
+# tuplecid records still must be removed from the toplevel's list.
+# - s2_vacuum reclaims the aborted row's line pointer (dead inserts are
+# removed regardless of the xid horizon, so this is deterministic even
+# while the toplevel transaction is still open); s0_catinsert2 then reuses
+# the same tid with a different cmin.
+# - s1_get_changes then decodes the toplevel commit and builds the tuplecid
+# hash; on unfixed builds the stale tuplecid of the aborted inner
+# subtransaction collides there with the fresh one.
+setup
+{
+ DROP TABLE IF EXISTS tbl1;
+ DROP TABLE IF EXISTS user_cat;
+ CREATE TABLE tbl1 (val1 integer);
+ -- Four rows of ~1.5kB fill the first heap page to within a few hundred
+ -- bytes, so that vacuuming away the aborted fifth row leaves exactly one
+ -- line pointer for the next insert to reuse.
+ CREATE TABLE user_cat (c1 int, filler char(1500)) WITH (user_catalog_table = true);
+ INSERT INTO user_cat VALUES (1, 'a'), (2, 'b'), (3, 'c'), (4, 'd');
+}
+
+teardown
+{
+ DROP TABLE tbl1;
+ DROP TABLE user_cat;
+ SELECT 'stop' FROM pg_drop_replication_slot('tuplecid_nested_slot');
+}
+
+session "s0"
+setup { SET synchronous_commit=on; }
+step "s0_begin" { BEGIN; }
+step "s0_topwrite" { INSERT INTO tbl1 VALUES (0); }
+step "s0_outer" { SAVEPOINT outer_sp; }
+step "s0_inner" { SAVEPOINT inner_sp; }
+step "s0_catinsert1" { INSERT INTO user_cat VALUES (5, 'e'); }
+step "s0_release_inner" { RELEASE SAVEPOINT inner_sp; }
+step "s0_rollback_outer" { ROLLBACK TO SAVEPOINT outer_sp; }
+step "s0_catinsert2" { INSERT INTO user_cat VALUES (6, 'f'); }
+step "s0_commit" { COMMIT; }
+
+session "s1"
+setup { SET synchronous_commit=on; }
+step "s1_init" { SELECT 'init' FROM pg_create_logical_replication_slot('tuplecid_nested_slot', 'test_decoding'); }
+# The user_cat rows carry ~1.5kB filler values which would flood the expected
+# output; filter them out (decoding still processes them server-side).
+step "s1_get_changes" { SELECT data FROM pg_logical_slot_get_changes('tuplecid_nested_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%'; }
+
+session "s2"
+setup { SET synchronous_commit=on; }
+step "s2_vacuum" { VACUUM user_cat; }
+
+# The slot is created before the transaction begins, so the final
+# s1_get_changes decodes the whole transaction through its commit.
+permutation "s1_init" "s0_begin" "s0_topwrite" "s0_outer" "s0_inner" "s0_catinsert1" "s0_release_inner" "s0_rollback_outer" "s2_vacuum" "s0_catinsert2" "s0_commit" "s1_get_changes"
diff --git a/contrib/test_decoding/specs/tuplecid_restart.spec b/contrib/test_decoding/specs/tuplecid_restart.spec
new file mode 100644
index 00000000000..58da414e8b7
--- /dev/null
+++ b/contrib/test_decoding/specs/tuplecid_restart.spec
@@ -0,0 +1,75 @@
+# Test decoding of a transaction in which a catalog-modifying subtransaction
+# was rolled back, where the transaction spans a logical decoding restart
+# point (BUG #19555 restart shape).
+#
+# The tuplecid records written by the aborted subtransaction are queued on the
+# toplevel transaction and must be removed when the subtransaction's abort is
+# decoded; otherwise they collide with the records of the line pointer that
+# gets reused by the toplevel transaction's later catalog insert, failing
+# Assert(ent->cmin == change->data.tuplecid.cmin) in
+# ReorderBufferBuildTupleCidHash() when the commit is decoded.
+#
+# - s0_insert runs in a subtransaction and produces its first WAL record.
+# - s0_catinsert1 generates an xl_heap_new_cid record in that subtransaction.
+# - s0_rollback aborts the subtransaction.
+# - s2_vacuum reclaims the aborted row's line pointer (dead inserts are
+# removed regardless of the xid horizon, so this is deterministic even
+# while the toplevel transaction is still open); s0_catinsert2 then reuses
+# the same tid with a different cmin.
+# - The transaction stays open across both checkpoints, so the final
+# s1_get_changes replays the transaction's records from the first
+# checkpoint and decodes its commit for output, building the tuplecid
+# hash. On unfixed builds the stale tuplecid of the aborted
+# subtransaction collides there with the fresh one.
+setup
+{
+ DROP TABLE IF EXISTS tbl1;
+ DROP TABLE IF EXISTS user_cat;
+ CREATE TABLE tbl1 (val1 integer);
+ -- Four rows of ~1.5kB fill the first heap page to within a few hundred
+ -- bytes, so that vacuuming away the aborted fifth row leaves exactly one
+ -- line pointer for the next insert to reuse.
+ CREATE TABLE user_cat (c1 int, filler char(1500)) WITH (user_catalog_table = true);
+ INSERT INTO user_cat VALUES (1, 'a'), (2, 'b'), (3, 'c'), (4, 'd');
+}
+
+teardown
+{
+ DROP TABLE tbl1;
+ DROP TABLE user_cat;
+ SELECT 'stop' FROM pg_drop_replication_slot('isolation_slot');
+}
+
+session "s0"
+setup { SET synchronous_commit=on; }
+step "s0_init" { SELECT 'init' FROM pg_create_logical_replication_slot('isolation_slot', 'test_decoding'); }
+step "s0_begin" { BEGIN; }
+step "s0_savepoint" { SAVEPOINT sp1; }
+step "s0_insert" { INSERT INTO tbl1 VALUES (1); }
+step "s0_catinsert1" { INSERT INTO user_cat VALUES (5, 'e'); }
+step "s0_rollback" { ROLLBACK TO SAVEPOINT sp1; }
+step "s0_catinsert2" { INSERT INTO user_cat VALUES (6, 'f'); }
+step "s0_commit" { COMMIT; }
+
+session "s1"
+setup { SET synchronous_commit=on; }
+step "s1_init" { SELECT 'init' FROM pg_create_logical_replication_slot('isolation_slot', 'test_decoding'); }
+step "s1_checkpoint" { CHECKPOINT; }
+# The user_cat rows carry ~1.5kB filler values which would flood the expected
+# output; filter them out (decoding still processes them server-side).
+step "s1_get_changes" { SELECT data FROM pg_logical_slot_get_changes('isolation_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%'; }
+
+session "s2"
+setup { SET synchronous_commit=on; }
+step "s2_vacuum" { VACUUM user_cat; }
+
+# The transaction commits only after the second s1_get_changes, so the last
+# s1_get_changes both replays the transaction from the first checkpoint and
+# decodes its commit for output.
+permutation "s0_init" "s0_begin" "s0_savepoint" "s0_insert" "s1_checkpoint" "s1_get_changes" "s0_catinsert1" "s0_rollback" "s2_vacuum" "s0_catinsert2" "s1_checkpoint" "s1_get_changes" "s0_commit" "s1_get_changes"
+
+# Variant with the slot created while the transaction is already open: slot
+# creation waits for a consistent point past the open transaction, so the
+# transaction is never decoded by this slot at all (no output). This locks in
+# the behavior that decoding cannot start in the middle of a transaction.
+permutation "s0_begin" "s0_savepoint" "s0_insert" "s1_init" "s0_catinsert1" "s0_rollback" "s2_vacuum" "s0_catinsert2" "s0_commit" "s1_get_changes"
diff --git a/contrib/test_decoding/sql/tuplecid.sql b/contrib/test_decoding/sql/tuplecid.sql
new file mode 100644
index 00000000000..335fb6d1591
--- /dev/null
+++ b/contrib/test_decoding/sql/tuplecid.sql
@@ -0,0 +1,76 @@
+-- Tests for decoding of transactions in which a catalog-modifying
+-- subtransaction was rolled back (BUG #19555).
+--
+-- When a subtransaction modifies catalog tuples and is then rolled back,
+-- its dead heap-only line pointers can be marked LP_UNUSED by on-access
+-- pruning and reused by later catalog inserts of the same top-level
+-- transaction. The aborted subtransaction's xl_heap_new_cid records must
+-- not be consulted when building the historic snapshot used to decode the
+-- transaction; on unfixed builds they collide with the records of the
+-- reused line pointer and decoding dies with
+-- TRAP: failed Assert("ent->cmin == change->data.tuplecid.cmin")
+-- (or, on non-assert builds, silently uses wrong cmin/cmax mappings).
+--
+-- Whether the collision triggers depends on the physical layout of the
+-- catalog pages, so run in a fresh database where prior tests cannot have
+-- changed it, and loop enough times to leave headroom for layout
+-- differences across versions.
+CREATE DATABASE regression_tuplecid;
+-- snapshot the original database name (make and meson use different
+-- names for it) so we can switch back before dropping the test database
+\set prevdb :DBNAME
+\c regression_tuplecid
+
+-- predictability
+SET synchronous_commit = on;
+
+SELECT 'init' FROM pg_create_logical_replication_slot('regression_slot', 'test_decoding');
+
+-- Catalog churn to push the catalog pages into a state where on-access
+-- pruning frees the aborted subtransaction's line pointer and the second
+-- ALTER's catalog insert reuses it.
+CREATE TABLE tpc_filler1(f1 char(4));
+CREATE TABLE tpc_filler2(data text);
+INSERT INTO tpc_filler2 VALUES ('before-test');
+CREATE TYPE tpc_complex AS (r float8, i float8);
+CREATE TABLE tpc_filler3 (a int PRIMARY KEY, b text DEFAULT 'Unspecified');
+CREATE TABLE tpc_filler4 (id serial, t text);
+CREATE TABLE tpc_filler5(data text);
+INSERT INTO tpc_filler5 SELECT repeat('a', 2000) || g.i FROM generate_series(1, 1) g(i);
+TRUNCATE table tpc_filler5;
+CHECKPOINT;
+
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+
+-- Each iteration runs the trigger shape: catalog DDL inside a rolled-back
+-- subtransaction, then the same DDL again, then decode. Unfixed builds
+-- typically die within a handful of iterations.
+-- (temporarily hide the queries, to avoid flooding the expected output)
+\set ECHO none
+SELECT format($fmt$
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+$fmt$)
+FROM generate_series(1, 25) \gexec
+\set ECHO all
+
+DROP TABLE tpc_filler1;
+DROP TABLE tpc_filler2;
+DROP TYPE tpc_complex;
+DROP TABLE tpc_filler3;
+DROP TABLE tpc_filler4;
+DROP TABLE tpc_filler5;
+
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+
+SELECT pg_drop_replication_slot('regression_slot');
+
+\c :prevdb
+DROP DATABASE regression_tuplecid;
diff --git a/src/backend/replication/logical/decode.c b/src/backend/replication/logical/decode.c
index a591bf08e1f..a5b4b997175 100644
--- a/src/backend/replication/logical/decode.c
+++ b/src/backend/replication/logical/decode.c
@@ -862,12 +862,33 @@ DecodeAbort(LogicalDecodingContext *ctx, XLogRecordBuffer *buf,
}
else
{
+ /*
+ * Remove tuplecid changes queued by the aborted (sub)transactions
+ * from the toplevel's list, before the transactions are torn down.
+ * The abort record's primary xid tells
+ * ReorderBufferCleanupSubTxnTupleCids() whether the whole toplevel
+ * is going away, in which case scanning the list is pointless.
+ *
+ * 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.
+ */
for (i = 0; i < parsed->nsubxacts; i++)
{
+ ReorderBufferCleanupSubTxnTupleCids(ctx->reorder,
+ parsed->subxacts[i],
+ xid);
ReorderBufferAbort(ctx->reorder, parsed->subxacts[i],
buf->record->EndRecPtr, abort_time);
}
+ ReorderBufferCleanupSubTxnTupleCids(ctx->reorder, xid, xid);
ReorderBufferAbort(ctx->reorder, xid, buf->record->EndRecPtr,
abort_time);
}
diff --git a/src/backend/replication/logical/reorderbuffer.c b/src/backend/replication/logical/reorderbuffer.c
index cd0e83284ac..e5b0c535723 100644
--- a/src/backend/replication/logical/reorderbuffer.c
+++ b/src/backend/replication/logical/reorderbuffer.c
@@ -2989,6 +2989,88 @@ ReorderBufferAbort(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn,
ReorderBufferCleanupTXN(rb, txn);
}
+/*
+ * Remove tuplecid changes queued by subtransaction xid from its toplevel
+ * transaction's list.
+ *
+ * Unlike regular changes, tuplecid changes are always queued on the toplevel
+ * transaction (see ReorderBufferAddNewTupleCids), so they would otherwise
+ * survive the abort of the subtransaction that wrote them. That's wrong:
+ * they describe catalog tuple versions created or killed by the aborted
+ * subtransaction, which never became visible, and keeping them can corrupt
+ * ReorderBufferBuildTupleCidHash() at commit time -- both when the toplevel
+ * transaction later reuses the same tid (the stale entry collides with the
+ * fresh one, breaking the cmin equality assumption) and when nothing touches
+ * the tid again (a stale cmax would make a still-live tuple look deleted on
+ * historic snapshots).
+ *
+ * The cleanup is pointless when the whole toplevel transaction is
+ * being aborted, since ReorderBufferCleanupTXN() frees the whole list
+ * anyway; the caller passes the abort record's primary xid and we skip
+ * the scan when it is xid's toplevel. Note that the opposite decision
+ * -- cleaning only when the primary xid's own association is known --
+ * would be wrong: abort records are written once the subtransaction is
+ * already in TRANS_ABORT, so they carry no toplevel xid in their
+ * header, and an outer subtransaction that never wrote WAL of its own
+ * never gets an association at all. When such an outer subtransaction
+ * rolls back, released inner subtransactions listed in its abort record
+ * do have known associations and are cleaned here.
+ *
+ * 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().
+ */
+void
+ReorderBufferCleanupSubTxnTupleCids(ReorderBuffer *rb, TransactionId xid,
+ TransactionId primary_xid)
+{
+ ReorderBufferTXN *txn;
+ ReorderBufferTXN *toptxn;
+ dlist_mutable_iter it;
+
+ txn = ReorderBufferTXNByXid(rb, xid, false, NULL, InvalidXLogRecPtr,
+ false);
+
+ /* unknown transaction, or unknown association: nothing to remove */
+ if (txn == NULL || !rbtxn_is_known_subxact(txn))
+ return;
+
+ toptxn = rbtxn_get_toptxn(txn);
+
+ /*
+ * The whole toplevel transaction is being aborted (the abort record's
+ * primary xid is xid's toplevel): ReorderBufferCleanupTXN() will free
+ * the whole list shortly, don't scan it once per aborted subxid.
+ */
+ if (toptxn->xid == primary_xid)
+ return;
+
+ dlist_foreach_modify(it, &toptxn->tuplecids)
+ {
+ ReorderBufferChange *change;
+
+ change = dlist_container(ReorderBufferChange, node, it.cur);
+
+ Assert(change->action == REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID);
+
+ if (change->data.tuplecid.subxid == xid)
+ {
+ dlist_delete(&change->node);
+ ReorderBufferReturnChange(rb, change, false);
+ toptxn->ntuplecids--;
+ }
+ }
+}
+
/*
* Abort all transactions that aren't actually running anymore because the
* server restarted.
@@ -3297,7 +3379,8 @@ void
ReorderBufferAddNewTupleCids(ReorderBuffer *rb, TransactionId xid,
XLogRecPtr lsn, RelFileLocator locator,
ItemPointerData tid, CommandId cmin,
- CommandId cmax, CommandId combocid)
+ CommandId cmax, CommandId combocid,
+ TransactionId subxid)
{
ReorderBufferChange *change = ReorderBufferGetChange(rb);
ReorderBufferTXN *txn;
@@ -3309,6 +3392,7 @@ ReorderBufferAddNewTupleCids(ReorderBuffer *rb, TransactionId xid,
change->data.tuplecid.cmin = cmin;
change->data.tuplecid.cmax = cmax;
change->data.tuplecid.combocid = combocid;
+ change->data.tuplecid.subxid = subxid;
change->lsn = lsn;
change->txn = txn;
change->action = REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID;
diff --git a/src/backend/replication/logical/snapbuild.c b/src/backend/replication/logical/snapbuild.c
index 8cc8a10ccad..1a388cfa08c 100644
--- a/src/backend/replication/logical/snapbuild.c
+++ b/src/backend/replication/logical/snapbuild.c
@@ -865,7 +865,7 @@ SnapBuildProcessNewCid(SnapBuild *builder, TransactionId xid,
ReorderBufferAddNewTupleCids(builder->reorder, xlrec->top_xid, lsn,
xlrec->target_locator, xlrec->target_tid,
xlrec->cmin, xlrec->cmax,
- xlrec->combocid);
+ xlrec->combocid, xid);
/* figure out new command id */
if (xlrec->cmin != InvalidCommandId &&
diff --git a/src/include/replication/reorderbuffer.h b/src/include/replication/reorderbuffer.h
index 1606e0ea007..3006ec802a8 100644
--- a/src/include/replication/reorderbuffer.h
+++ b/src/include/replication/reorderbuffer.h
@@ -159,6 +159,11 @@ typedef struct ReorderBufferChange
CommandId cmin;
CommandId cmax;
CommandId combocid;
+ TransactionId subxid; /* xid that wrote the tuplecid record;
+ * differs from the xid of the txn this
+ * change is queued on (always the
+ * toplevel xid) when a subtransaction
+ * modified the catalog */
} tuplecid;
/* Invalidation. */
@@ -725,6 +730,8 @@ extern void ReorderBufferCommitChild(ReorderBuffer *rb, TransactionId xid,
XLogRecPtr end_lsn);
extern void ReorderBufferAbort(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn,
TimestampTz abort_time);
+extern void ReorderBufferCleanupSubTxnTupleCids(ReorderBuffer *rb, TransactionId xid,
+ TransactionId primary_xid);
extern void ReorderBufferAbortOld(ReorderBuffer *rb, TransactionId oldestRunningXid);
extern void ReorderBufferForget(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn);
extern void ReorderBufferInvalidate(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn);
@@ -738,7 +745,9 @@ extern void ReorderBufferAddNewCommandId(ReorderBuffer *rb, TransactionId xid,
extern void ReorderBufferAddNewTupleCids(ReorderBuffer *rb, TransactionId xid,
XLogRecPtr lsn, RelFileLocator locator,
ItemPointerData tid,
- CommandId cmin, CommandId cmax, CommandId combocid);
+ CommandId cmin, CommandId cmax,
+ CommandId combocid,
+ TransactionId subxid);
extern void ReorderBufferAddInvalidations(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn,
Size nmsgs, SharedInvalidationMessage *msgs);
extern void ReorderBufferAddDistributedInvalidations(ReorderBuffer *rb, TransactionId xid,
--
2.43.0
v5-REL_17_STABLE-0001-Fix-stale-tuplecid-records-left-behind-by-aborted.patch (application/octet-stream, 35.4K) download
From 1651df02b1c2076a5207a337833c652e070dcec6 Mon Sep 17 00:00:00 2001
From: Bingshuai Li <lucian1412@outlook.com>
Date: Wed, 30 Sep 2026 12:05:32 +0800
Subject: [PATCH] Fix stale tuplecid records left behind by aborted
subtransactions
Tuplecid changes are always queued on the toplevel transaction, so
unlike regular changes they are not dropped when the subtransaction
that wrote them aborts. The stale mappings corrupt
ReorderBufferBuildTupleCidHash() at commit time: if a later catalog
insert reuses the aborted subtransaction's line pointer (made
LP_UNUSED by on-access pruning or by vacuum), the fresh record
collides with the stale one with a different cmin, tripping the cmin
equality assertion; where nothing reuses the tid, a stale cmax makes
a still-live catalog tuple look deleted on historic snapshots. On
non-assert builds there is no crash, but the stale mappings risk
misjudging historic catalog visibility, which could produce
incorrect decoding output.
Remove the aborted subtransaction's tuplecid entries when its abort
is decoded. The cleanup is not needed when the whole toplevel
transaction is being aborted, because ReorderBufferCleanupTXN()
frees the whole list anyway; to avoid scanning the list once per
aborted subxid in that case, DecodeAbort() passes the abort record's
primary xid to the new ReorderBufferCleanupSubTxnTupleCids(), which
skips the scan when that xid is the toplevel of the xid being
cleaned.
The decision cannot be based on whether the primary xid's own
association with its toplevel is known: abort records are written
after the subtransaction has entered TRANS_ABORT, so they never
carry the toplevel xid in their header, and an outer subtransaction
that never wrote WAL of its own -- for example a savepoint that only
wraps other savepoints -- can never get its association established
at all. When such an outer subtransaction is rolled back, the
released inner subtransactions listed in its abort record do have
known associations, and their tuplecids must be removed from the
surviving toplevel's list. The existing tuplecid and tuplecid_restart
tests only cover aborts of subtransactions that wrote WAL themselves,
which is why this shape needs its own test.
Skipping the cleanup when the association of the xid being cleaned
is unknown is safe because of how a slot's restart point advances:
SnapBuildProcessRunningXacts() cannot move the restart point past
the oldest in-progress transaction, so any pass that output-decodes
the toplevel commit must have replayed the subtransaction's first
record and therefore knows 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 via
SnapBuildXactNeedsSkip(), so any stale tuplecid entries left behind
are dropped along with the transaction state and never reach
ReorderBufferBuildTupleCidHash().
Add an isolation test for the nested shape: the toplevel writes WAL
first, an inner subtransaction modifies a user catalog table and is
released, and the outer subtransaction -- which produces no WAL of
its own -- is then rolled back; with the page-fill and vacuum recipe
of tuplecid_restart, the toplevel's later insert deterministically
reuses the aborted subtransaction's line pointer. On unfixed assert
builds the final get_changes dies with the original cmin assertion
in ReorderBufferBuildTupleCidHash(); with the fix it passes. The
existing tests keep covering the simple savepoint and the restart
shapes.
Bug: #19555
Reported-by: Alexander Kozhemyakin <a.kozhemyakin@postgrespro.ru>
Based-on-patch-by: Mark Dilger
Discussion: https://postgr.es/m/CAHgHdKu5e3XY5e90Tuaxq_R4WrKxSV734Q%2BLwo5y39Omp2A-Gg@mail.gmail.com
---
contrib/test_decoding/Makefile | 6 +-
contrib/test_decoding/expected/tuplecid.out | 199 ++++++++++++++++++
.../expected/tuplecid_nested.out | 32 +++
.../expected/tuplecid_restart.out | 68 ++++++
contrib/test_decoding/meson.build | 3 +
.../test_decoding/specs/tuplecid_nested.spec | 77 +++++++
.../test_decoding/specs/tuplecid_restart.spec | 75 +++++++
contrib/test_decoding/sql/tuplecid.sql | 76 +++++++
src/backend/replication/logical/decode.c | 21 ++
.../replication/logical/reorderbuffer.c | 86 +++++++-
src/backend/replication/logical/snapbuild.c | 2 +-
src/include/replication/reorderbuffer.h | 11 +-
12 files changed, 651 insertions(+), 5 deletions(-)
create mode 100644 contrib/test_decoding/expected/tuplecid.out
create mode 100644 contrib/test_decoding/expected/tuplecid_nested.out
create mode 100644 contrib/test_decoding/expected/tuplecid_restart.out
create mode 100644 contrib/test_decoding/specs/tuplecid_nested.spec
create mode 100644 contrib/test_decoding/specs/tuplecid_restart.spec
create mode 100644 contrib/test_decoding/sql/tuplecid.sql
diff --git a/contrib/test_decoding/Makefile b/contrib/test_decoding/Makefile
index 02e961f4d31..0583786f9f5 100644
--- a/contrib/test_decoding/Makefile
+++ b/contrib/test_decoding/Makefile
@@ -5,11 +5,13 @@ PGFILEDESC = "test_decoding - example of a logical decoding output plugin"
REGRESS = ddl xact rewrite toast permissions decoding_in_xact \
decoding_into_rel binary prepared replorigin time messages \
- spill slot truncate stream stats twophase twophase_stream
+ spill slot truncate stream stats twophase twophase_stream \
+ tuplecid
ISOLATION = mxact delayed_startup ondisk_startup concurrent_ddl_dml \
oldest_xmin snapshot_transfer subxact_without_top concurrent_stream \
twophase_snapshot slot_creation_error catalog_change_snapshot \
- skip_snapshot_restore invalidation_distribution
+ skip_snapshot_restore invalidation_distribution \
+ tuplecid_restart tuplecid_nested
REGRESS_OPTS = --temp-config $(top_srcdir)/contrib/test_decoding/logical.conf
ISOLATION_OPTS = --temp-config $(top_srcdir)/contrib/test_decoding/logical.conf
diff --git a/contrib/test_decoding/expected/tuplecid.out b/contrib/test_decoding/expected/tuplecid.out
new file mode 100644
index 00000000000..b559dd21bd4
--- /dev/null
+++ b/contrib/test_decoding/expected/tuplecid.out
@@ -0,0 +1,199 @@
+-- Tests for decoding of transactions in which a catalog-modifying
+-- subtransaction was rolled back (BUG #19555).
+--
+-- When a subtransaction modifies catalog tuples and is then rolled back,
+-- its dead heap-only line pointers can be marked LP_UNUSED by on-access
+-- pruning and reused by later catalog inserts of the same top-level
+-- transaction. The aborted subtransaction's xl_heap_new_cid records must
+-- not be consulted when building the historic snapshot used to decode the
+-- transaction; on unfixed builds they collide with the records of the
+-- reused line pointer and decoding dies with
+-- TRAP: failed Assert("ent->cmin == change->data.tuplecid.cmin")
+-- (or, on non-assert builds, silently uses wrong cmin/cmax mappings).
+--
+-- Whether the collision triggers depends on the physical layout of the
+-- catalog pages, so run in a fresh database where prior tests cannot have
+-- changed it, and loop enough times to leave headroom for layout
+-- differences across versions.
+CREATE DATABASE regression_tuplecid;
+-- snapshot the original database name (make and meson use different
+-- names for it) so we can switch back before dropping the test database
+\set prevdb :DBNAME
+\c regression_tuplecid
+-- predictability
+SET synchronous_commit = on;
+SELECT 'init' FROM pg_create_logical_replication_slot('regression_slot', 'test_decoding');
+ ?column?
+----------
+ init
+(1 row)
+
+-- Catalog churn to push the catalog pages into a state where on-access
+-- pruning frees the aborted subtransaction's line pointer and the second
+-- ALTER's catalog insert reuses it.
+CREATE TABLE tpc_filler1(f1 char(4));
+CREATE TABLE tpc_filler2(data text);
+INSERT INTO tpc_filler2 VALUES ('before-test');
+CREATE TYPE tpc_complex AS (r float8, i float8);
+CREATE TABLE tpc_filler3 (a int PRIMARY KEY, b text DEFAULT 'Unspecified');
+CREATE TABLE tpc_filler4 (id serial, t text);
+CREATE TABLE tpc_filler5(data text);
+INSERT INTO tpc_filler5 SELECT repeat('a', 2000) || g.i FROM generate_series(1, 1) g(i);
+TRUNCATE table tpc_filler5;
+CHECKPOINT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+ count
+-------
+ 9
+(1 row)
+
+-- Each iteration runs the trigger shape: catalog DDL inside a rolled-back
+-- subtransaction, then the same DDL again, then decode. Unfixed builds
+-- typically die within a handful of iterations.
+-- (temporarily hide the queries, to avoid flooding the expected output)
+\set ECHO none
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+DROP TABLE tpc_filler1;
+DROP TABLE tpc_filler2;
+DROP TYPE tpc_complex;
+DROP TABLE tpc_filler3;
+DROP TABLE tpc_filler4;
+DROP TABLE tpc_filler5;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+ count
+-------
+ 0
+(1 row)
+
+SELECT pg_drop_replication_slot('regression_slot');
+ pg_drop_replication_slot
+--------------------------
+
+(1 row)
+
+\c :prevdb
+DROP DATABASE regression_tuplecid;
diff --git a/contrib/test_decoding/expected/tuplecid_nested.out b/contrib/test_decoding/expected/tuplecid_nested.out
new file mode 100644
index 00000000000..5d816374fbc
--- /dev/null
+++ b/contrib/test_decoding/expected/tuplecid_nested.out
@@ -0,0 +1,32 @@
+Parsed test spec with 3 sessions
+
+starting permutation: s1_init s0_begin s0_topwrite s0_outer s0_inner s0_catinsert1 s0_release_inner s0_rollback_outer s2_vacuum s0_catinsert2 s0_commit s1_get_changes
+step s1_init: SELECT 'init' FROM pg_create_logical_replication_slot('tuplecid_nested_slot', 'test_decoding');
+?column?
+--------
+init
+(1 row)
+
+step s0_begin: BEGIN;
+step s0_topwrite: INSERT INTO tbl1 VALUES (0);
+step s0_outer: SAVEPOINT outer_sp;
+step s0_inner: SAVEPOINT inner_sp;
+step s0_catinsert1: INSERT INTO user_cat VALUES (5, 'e');
+step s0_release_inner: RELEASE SAVEPOINT inner_sp;
+step s0_rollback_outer: ROLLBACK TO SAVEPOINT outer_sp;
+step s2_vacuum: VACUUM user_cat;
+step s0_catinsert2: INSERT INTO user_cat VALUES (6, 'f');
+step s0_commit: COMMIT;
+step s1_get_changes: SELECT data FROM pg_logical_slot_get_changes('tuplecid_nested_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%';
+data
+------------------------------------------
+BEGIN
+table public.tbl1: INSERT: val1[integer]:0
+COMMIT
+(3 rows)
+
+?column?
+--------
+stop
+(1 row)
+
diff --git a/contrib/test_decoding/expected/tuplecid_restart.out b/contrib/test_decoding/expected/tuplecid_restart.out
new file mode 100644
index 00000000000..e5b4bc2543d
--- /dev/null
+++ b/contrib/test_decoding/expected/tuplecid_restart.out
@@ -0,0 +1,68 @@
+Parsed test spec with 3 sessions
+
+starting permutation: s0_init s0_begin s0_savepoint s0_insert s1_checkpoint s1_get_changes s0_catinsert1 s0_rollback s2_vacuum s0_catinsert2 s1_checkpoint s1_get_changes s0_commit s1_get_changes
+step s0_init: SELECT 'init' FROM pg_create_logical_replication_slot('isolation_slot', 'test_decoding');
+?column?
+--------
+init
+(1 row)
+
+step s0_begin: BEGIN;
+step s0_savepoint: SAVEPOINT sp1;
+step s0_insert: INSERT INTO tbl1 VALUES (1);
+step s1_checkpoint: CHECKPOINT;
+step s1_get_changes: SELECT data FROM pg_logical_slot_get_changes('isolation_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%';
+data
+----
+(0 rows)
+
+step s0_catinsert1: INSERT INTO user_cat VALUES (5, 'e');
+step s0_rollback: ROLLBACK TO SAVEPOINT sp1;
+step s2_vacuum: VACUUM user_cat;
+step s0_catinsert2: INSERT INTO user_cat VALUES (6, 'f');
+step s1_checkpoint: CHECKPOINT;
+step s1_get_changes: SELECT data FROM pg_logical_slot_get_changes('isolation_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%';
+data
+----
+(0 rows)
+
+step s0_commit: COMMIT;
+step s1_get_changes: SELECT data FROM pg_logical_slot_get_changes('isolation_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%';
+data
+------
+BEGIN
+COMMIT
+(2 rows)
+
+?column?
+--------
+stop
+(1 row)
+
+
+starting permutation: s0_begin s0_savepoint s0_insert s1_init s0_catinsert1 s0_rollback s2_vacuum s0_catinsert2 s0_commit s1_get_changes
+step s0_begin: BEGIN;
+step s0_savepoint: SAVEPOINT sp1;
+step s0_insert: INSERT INTO tbl1 VALUES (1);
+step s1_init: SELECT 'init' FROM pg_create_logical_replication_slot('isolation_slot', 'test_decoding'); <waiting ...>
+step s0_catinsert1: INSERT INTO user_cat VALUES (5, 'e');
+step s0_rollback: ROLLBACK TO SAVEPOINT sp1;
+step s2_vacuum: VACUUM user_cat;
+step s0_catinsert2: INSERT INTO user_cat VALUES (6, 'f');
+step s0_commit: COMMIT;
+step s1_init: <... completed>
+?column?
+--------
+init
+(1 row)
+
+step s1_get_changes: SELECT data FROM pg_logical_slot_get_changes('isolation_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%';
+data
+----
+(0 rows)
+
+?column?
+--------
+stop
+(1 row)
+
diff --git a/contrib/test_decoding/meson.build b/contrib/test_decoding/meson.build
index 03dd80b7f19..40b2ed34338 100644
--- a/contrib/test_decoding/meson.build
+++ b/contrib/test_decoding/meson.build
@@ -41,6 +41,7 @@ tests += {
'stats',
'twophase',
'twophase_stream',
+ 'tuplecid',
],
'regress_args': [
'--temp-config', files('logical.conf'),
@@ -64,6 +65,8 @@ tests += {
'slot_creation_error',
'skip_snapshot_restore',
'invalidation_distribution',
+ 'tuplecid_restart',
+ 'tuplecid_nested',
],
'regress_args': [
'--temp-config', files('logical.conf'),
diff --git a/contrib/test_decoding/specs/tuplecid_nested.spec b/contrib/test_decoding/specs/tuplecid_nested.spec
new file mode 100644
index 00000000000..52c80eb55eb
--- /dev/null
+++ b/contrib/test_decoding/specs/tuplecid_nested.spec
@@ -0,0 +1,77 @@
+# Test decoding of a partially rolled back transaction where the aborted part
+# is nested: the aborting outer subtransaction never produced any WAL of its
+# own, so decoding cannot know its toplevel transaction, while an inner
+# subtransaction it rolls back did produce WAL and its tuplecid records still
+# have to be removed (BUG #19555 nested shape).
+#
+# The tuplecid records written by the aborted inner subtransaction are queued
+# on the toplevel transaction and must be removed when the outer
+# subtransaction's abort is decoded; otherwise they collide with the records
+# of the line pointer that gets reused by the toplevel transaction's later
+# catalog insert, failing Assert(ent->cmin == change->data.tuplecid.cmin) in
+# ReorderBufferBuildTupleCidHash() when the commit is decoded.
+#
+# - s0_topwrite makes the toplevel transaction produce its first WAL record
+# before any subtransaction exists.
+# - s0_outer establishes the outer savepoint, which never gets a WAL record
+# of its own.
+# - s0_catinsert1 generates an xl_heap_new_cid record in the inner
+# subtransaction, which is then released.
+# - s0_rollback_outer rolls the outer savepoint back. Its abort record is
+# written once the backend is already in TRANS_ABORT, so it carries no
+# toplevel xid in its header and the outer subtransaction's association
+# with the toplevel can never be established. The released inner
+# subtransaction is listed in the same abort record, though, and its
+# tuplecid records still must be removed from the toplevel's list.
+# - s2_vacuum reclaims the aborted row's line pointer (dead inserts are
+# removed regardless of the xid horizon, so this is deterministic even
+# while the toplevel transaction is still open); s0_catinsert2 then reuses
+# the same tid with a different cmin.
+# - s1_get_changes then decodes the toplevel commit and builds the tuplecid
+# hash; on unfixed builds the stale tuplecid of the aborted inner
+# subtransaction collides there with the fresh one.
+setup
+{
+ DROP TABLE IF EXISTS tbl1;
+ DROP TABLE IF EXISTS user_cat;
+ CREATE TABLE tbl1 (val1 integer);
+ -- Four rows of ~1.5kB fill the first heap page to within a few hundred
+ -- bytes, so that vacuuming away the aborted fifth row leaves exactly one
+ -- line pointer for the next insert to reuse.
+ CREATE TABLE user_cat (c1 int, filler char(1500)) WITH (user_catalog_table = true);
+ INSERT INTO user_cat VALUES (1, 'a'), (2, 'b'), (3, 'c'), (4, 'd');
+}
+
+teardown
+{
+ DROP TABLE tbl1;
+ DROP TABLE user_cat;
+ SELECT 'stop' FROM pg_drop_replication_slot('tuplecid_nested_slot');
+}
+
+session "s0"
+setup { SET synchronous_commit=on; }
+step "s0_begin" { BEGIN; }
+step "s0_topwrite" { INSERT INTO tbl1 VALUES (0); }
+step "s0_outer" { SAVEPOINT outer_sp; }
+step "s0_inner" { SAVEPOINT inner_sp; }
+step "s0_catinsert1" { INSERT INTO user_cat VALUES (5, 'e'); }
+step "s0_release_inner" { RELEASE SAVEPOINT inner_sp; }
+step "s0_rollback_outer" { ROLLBACK TO SAVEPOINT outer_sp; }
+step "s0_catinsert2" { INSERT INTO user_cat VALUES (6, 'f'); }
+step "s0_commit" { COMMIT; }
+
+session "s1"
+setup { SET synchronous_commit=on; }
+step "s1_init" { SELECT 'init' FROM pg_create_logical_replication_slot('tuplecid_nested_slot', 'test_decoding'); }
+# The user_cat rows carry ~1.5kB filler values which would flood the expected
+# output; filter them out (decoding still processes them server-side).
+step "s1_get_changes" { SELECT data FROM pg_logical_slot_get_changes('tuplecid_nested_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%'; }
+
+session "s2"
+setup { SET synchronous_commit=on; }
+step "s2_vacuum" { VACUUM user_cat; }
+
+# The slot is created before the transaction begins, so the final
+# s1_get_changes decodes the whole transaction through its commit.
+permutation "s1_init" "s0_begin" "s0_topwrite" "s0_outer" "s0_inner" "s0_catinsert1" "s0_release_inner" "s0_rollback_outer" "s2_vacuum" "s0_catinsert2" "s0_commit" "s1_get_changes"
diff --git a/contrib/test_decoding/specs/tuplecid_restart.spec b/contrib/test_decoding/specs/tuplecid_restart.spec
new file mode 100644
index 00000000000..58da414e8b7
--- /dev/null
+++ b/contrib/test_decoding/specs/tuplecid_restart.spec
@@ -0,0 +1,75 @@
+# Test decoding of a transaction in which a catalog-modifying subtransaction
+# was rolled back, where the transaction spans a logical decoding restart
+# point (BUG #19555 restart shape).
+#
+# The tuplecid records written by the aborted subtransaction are queued on the
+# toplevel transaction and must be removed when the subtransaction's abort is
+# decoded; otherwise they collide with the records of the line pointer that
+# gets reused by the toplevel transaction's later catalog insert, failing
+# Assert(ent->cmin == change->data.tuplecid.cmin) in
+# ReorderBufferBuildTupleCidHash() when the commit is decoded.
+#
+# - s0_insert runs in a subtransaction and produces its first WAL record.
+# - s0_catinsert1 generates an xl_heap_new_cid record in that subtransaction.
+# - s0_rollback aborts the subtransaction.
+# - s2_vacuum reclaims the aborted row's line pointer (dead inserts are
+# removed regardless of the xid horizon, so this is deterministic even
+# while the toplevel transaction is still open); s0_catinsert2 then reuses
+# the same tid with a different cmin.
+# - The transaction stays open across both checkpoints, so the final
+# s1_get_changes replays the transaction's records from the first
+# checkpoint and decodes its commit for output, building the tuplecid
+# hash. On unfixed builds the stale tuplecid of the aborted
+# subtransaction collides there with the fresh one.
+setup
+{
+ DROP TABLE IF EXISTS tbl1;
+ DROP TABLE IF EXISTS user_cat;
+ CREATE TABLE tbl1 (val1 integer);
+ -- Four rows of ~1.5kB fill the first heap page to within a few hundred
+ -- bytes, so that vacuuming away the aborted fifth row leaves exactly one
+ -- line pointer for the next insert to reuse.
+ CREATE TABLE user_cat (c1 int, filler char(1500)) WITH (user_catalog_table = true);
+ INSERT INTO user_cat VALUES (1, 'a'), (2, 'b'), (3, 'c'), (4, 'd');
+}
+
+teardown
+{
+ DROP TABLE tbl1;
+ DROP TABLE user_cat;
+ SELECT 'stop' FROM pg_drop_replication_slot('isolation_slot');
+}
+
+session "s0"
+setup { SET synchronous_commit=on; }
+step "s0_init" { SELECT 'init' FROM pg_create_logical_replication_slot('isolation_slot', 'test_decoding'); }
+step "s0_begin" { BEGIN; }
+step "s0_savepoint" { SAVEPOINT sp1; }
+step "s0_insert" { INSERT INTO tbl1 VALUES (1); }
+step "s0_catinsert1" { INSERT INTO user_cat VALUES (5, 'e'); }
+step "s0_rollback" { ROLLBACK TO SAVEPOINT sp1; }
+step "s0_catinsert2" { INSERT INTO user_cat VALUES (6, 'f'); }
+step "s0_commit" { COMMIT; }
+
+session "s1"
+setup { SET synchronous_commit=on; }
+step "s1_init" { SELECT 'init' FROM pg_create_logical_replication_slot('isolation_slot', 'test_decoding'); }
+step "s1_checkpoint" { CHECKPOINT; }
+# The user_cat rows carry ~1.5kB filler values which would flood the expected
+# output; filter them out (decoding still processes them server-side).
+step "s1_get_changes" { SELECT data FROM pg_logical_slot_get_changes('isolation_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%'; }
+
+session "s2"
+setup { SET synchronous_commit=on; }
+step "s2_vacuum" { VACUUM user_cat; }
+
+# The transaction commits only after the second s1_get_changes, so the last
+# s1_get_changes both replays the transaction from the first checkpoint and
+# decodes its commit for output.
+permutation "s0_init" "s0_begin" "s0_savepoint" "s0_insert" "s1_checkpoint" "s1_get_changes" "s0_catinsert1" "s0_rollback" "s2_vacuum" "s0_catinsert2" "s1_checkpoint" "s1_get_changes" "s0_commit" "s1_get_changes"
+
+# Variant with the slot created while the transaction is already open: slot
+# creation waits for a consistent point past the open transaction, so the
+# transaction is never decoded by this slot at all (no output). This locks in
+# the behavior that decoding cannot start in the middle of a transaction.
+permutation "s0_begin" "s0_savepoint" "s0_insert" "s1_init" "s0_catinsert1" "s0_rollback" "s2_vacuum" "s0_catinsert2" "s0_commit" "s1_get_changes"
diff --git a/contrib/test_decoding/sql/tuplecid.sql b/contrib/test_decoding/sql/tuplecid.sql
new file mode 100644
index 00000000000..335fb6d1591
--- /dev/null
+++ b/contrib/test_decoding/sql/tuplecid.sql
@@ -0,0 +1,76 @@
+-- Tests for decoding of transactions in which a catalog-modifying
+-- subtransaction was rolled back (BUG #19555).
+--
+-- When a subtransaction modifies catalog tuples and is then rolled back,
+-- its dead heap-only line pointers can be marked LP_UNUSED by on-access
+-- pruning and reused by later catalog inserts of the same top-level
+-- transaction. The aborted subtransaction's xl_heap_new_cid records must
+-- not be consulted when building the historic snapshot used to decode the
+-- transaction; on unfixed builds they collide with the records of the
+-- reused line pointer and decoding dies with
+-- TRAP: failed Assert("ent->cmin == change->data.tuplecid.cmin")
+-- (or, on non-assert builds, silently uses wrong cmin/cmax mappings).
+--
+-- Whether the collision triggers depends on the physical layout of the
+-- catalog pages, so run in a fresh database where prior tests cannot have
+-- changed it, and loop enough times to leave headroom for layout
+-- differences across versions.
+CREATE DATABASE regression_tuplecid;
+-- snapshot the original database name (make and meson use different
+-- names for it) so we can switch back before dropping the test database
+\set prevdb :DBNAME
+\c regression_tuplecid
+
+-- predictability
+SET synchronous_commit = on;
+
+SELECT 'init' FROM pg_create_logical_replication_slot('regression_slot', 'test_decoding');
+
+-- Catalog churn to push the catalog pages into a state where on-access
+-- pruning frees the aborted subtransaction's line pointer and the second
+-- ALTER's catalog insert reuses it.
+CREATE TABLE tpc_filler1(f1 char(4));
+CREATE TABLE tpc_filler2(data text);
+INSERT INTO tpc_filler2 VALUES ('before-test');
+CREATE TYPE tpc_complex AS (r float8, i float8);
+CREATE TABLE tpc_filler3 (a int PRIMARY KEY, b text DEFAULT 'Unspecified');
+CREATE TABLE tpc_filler4 (id serial, t text);
+CREATE TABLE tpc_filler5(data text);
+INSERT INTO tpc_filler5 SELECT repeat('a', 2000) || g.i FROM generate_series(1, 1) g(i);
+TRUNCATE table tpc_filler5;
+CHECKPOINT;
+
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+
+-- Each iteration runs the trigger shape: catalog DDL inside a rolled-back
+-- subtransaction, then the same DDL again, then decode. Unfixed builds
+-- typically die within a handful of iterations.
+-- (temporarily hide the queries, to avoid flooding the expected output)
+\set ECHO none
+SELECT format($fmt$
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+$fmt$)
+FROM generate_series(1, 25) \gexec
+\set ECHO all
+
+DROP TABLE tpc_filler1;
+DROP TABLE tpc_filler2;
+DROP TYPE tpc_complex;
+DROP TABLE tpc_filler3;
+DROP TABLE tpc_filler4;
+DROP TABLE tpc_filler5;
+
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+
+SELECT pg_drop_replication_slot('regression_slot');
+
+\c :prevdb
+DROP DATABASE regression_tuplecid;
diff --git a/src/backend/replication/logical/decode.c b/src/backend/replication/logical/decode.c
index 02d4e4fd8ee..985b2ce415a 100644
--- a/src/backend/replication/logical/decode.c
+++ b/src/backend/replication/logical/decode.c
@@ -876,12 +876,33 @@ DecodeAbort(LogicalDecodingContext *ctx, XLogRecordBuffer *buf,
}
else
{
+ /*
+ * Remove tuplecid changes queued by the aborted (sub)transactions
+ * from the toplevel's list, before the transactions are torn down.
+ * The abort record's primary xid tells
+ * ReorderBufferCleanupSubTxnTupleCids() whether the whole toplevel
+ * is going away, in which case scanning the list is pointless.
+ *
+ * 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.
+ */
for (i = 0; i < parsed->nsubxacts; i++)
{
+ ReorderBufferCleanupSubTxnTupleCids(ctx->reorder,
+ parsed->subxacts[i],
+ xid);
ReorderBufferAbort(ctx->reorder, parsed->subxacts[i],
buf->record->EndRecPtr, abort_time);
}
+ ReorderBufferCleanupSubTxnTupleCids(ctx->reorder, xid, xid);
ReorderBufferAbort(ctx->reorder, xid, buf->record->EndRecPtr,
abort_time);
}
diff --git a/src/backend/replication/logical/reorderbuffer.c b/src/backend/replication/logical/reorderbuffer.c
index 149a1c0d0f0..733e33e3d0f 100644
--- a/src/backend/replication/logical/reorderbuffer.c
+++ b/src/backend/replication/logical/reorderbuffer.c
@@ -3022,6 +3022,88 @@ ReorderBufferAbort(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn,
ReorderBufferCleanupTXN(rb, txn);
}
+/*
+ * Remove tuplecid changes queued by subtransaction xid from its toplevel
+ * transaction's list.
+ *
+ * Unlike regular changes, tuplecid changes are always queued on the toplevel
+ * transaction (see ReorderBufferAddNewTupleCids), so they would otherwise
+ * survive the abort of the subtransaction that wrote them. That's wrong:
+ * they describe catalog tuple versions created or killed by the aborted
+ * subtransaction, which never became visible, and keeping them can corrupt
+ * ReorderBufferBuildTupleCidHash() at commit time -- both when the toplevel
+ * transaction later reuses the same tid (the stale entry collides with the
+ * fresh one, breaking the cmin equality assumption) and when nothing touches
+ * the tid again (a stale cmax would make a still-live tuple look deleted on
+ * historic snapshots).
+ *
+ * The cleanup is pointless when the whole toplevel transaction is
+ * being aborted, since ReorderBufferCleanupTXN() frees the whole list
+ * anyway; the caller passes the abort record's primary xid and we skip
+ * the scan when it is xid's toplevel. Note that the opposite decision
+ * -- cleaning only when the primary xid's own association is known --
+ * would be wrong: abort records are written once the subtransaction is
+ * already in TRANS_ABORT, so they carry no toplevel xid in their
+ * header, and an outer subtransaction that never wrote WAL of its own
+ * never gets an association at all. When such an outer subtransaction
+ * rolls back, released inner subtransactions listed in its abort record
+ * do have known associations and are cleaned here.
+ *
+ * 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().
+ */
+void
+ReorderBufferCleanupSubTxnTupleCids(ReorderBuffer *rb, TransactionId xid,
+ TransactionId primary_xid)
+{
+ ReorderBufferTXN *txn;
+ ReorderBufferTXN *toptxn;
+ dlist_mutable_iter it;
+
+ txn = ReorderBufferTXNByXid(rb, xid, false, NULL, InvalidXLogRecPtr,
+ false);
+
+ /* unknown transaction, or unknown association: nothing to remove */
+ if (txn == NULL || !rbtxn_is_known_subxact(txn))
+ return;
+
+ toptxn = rbtxn_get_toptxn(txn);
+
+ /*
+ * The whole toplevel transaction is being aborted (the abort record's
+ * primary xid is xid's toplevel): ReorderBufferCleanupTXN() will free
+ * the whole list shortly, don't scan it once per aborted subxid.
+ */
+ if (toptxn->xid == primary_xid)
+ return;
+
+ dlist_foreach_modify(it, &toptxn->tuplecids)
+ {
+ ReorderBufferChange *change;
+
+ change = dlist_container(ReorderBufferChange, node, it.cur);
+
+ Assert(change->action == REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID);
+
+ if (change->data.tuplecid.subxid == xid)
+ {
+ dlist_delete(&change->node);
+ ReorderBufferReturnChange(rb, change, false);
+ toptxn->ntuplecids--;
+ }
+ }
+}
+
/*
* Abort all transactions that aren't actually running anymore because the
* server restarted.
@@ -3350,7 +3432,8 @@ void
ReorderBufferAddNewTupleCids(ReorderBuffer *rb, TransactionId xid,
XLogRecPtr lsn, RelFileLocator locator,
ItemPointerData tid, CommandId cmin,
- CommandId cmax, CommandId combocid)
+ CommandId cmax, CommandId combocid,
+ TransactionId subxid)
{
ReorderBufferChange *change = ReorderBufferGetChange(rb);
ReorderBufferTXN *txn;
@@ -3362,6 +3445,7 @@ ReorderBufferAddNewTupleCids(ReorderBuffer *rb, TransactionId xid,
change->data.tuplecid.cmin = cmin;
change->data.tuplecid.cmax = cmax;
change->data.tuplecid.combocid = combocid;
+ change->data.tuplecid.subxid = subxid;
change->lsn = lsn;
change->txn = txn;
change->action = REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID;
diff --git a/src/backend/replication/logical/snapbuild.c b/src/backend/replication/logical/snapbuild.c
index f862836b7eb..707aab5d110 100644
--- a/src/backend/replication/logical/snapbuild.c
+++ b/src/backend/replication/logical/snapbuild.c
@@ -879,7 +879,7 @@ SnapBuildProcessNewCid(SnapBuild *builder, TransactionId xid,
ReorderBufferAddNewTupleCids(builder->reorder, xlrec->top_xid, lsn,
xlrec->target_locator, xlrec->target_tid,
xlrec->cmin, xlrec->cmax,
- xlrec->combocid);
+ xlrec->combocid, xid);
/* figure out new command id */
if (xlrec->cmin != InvalidCommandId &&
diff --git a/src/include/replication/reorderbuffer.h b/src/include/replication/reorderbuffer.h
index 0cfa9005141..2bc40162a94 100644
--- a/src/include/replication/reorderbuffer.h
+++ b/src/include/replication/reorderbuffer.h
@@ -141,6 +141,11 @@ typedef struct ReorderBufferChange
CommandId cmin;
CommandId cmax;
CommandId combocid;
+ TransactionId subxid; /* xid that wrote the tuplecid record;
+ * differs from the xid of the txn this
+ * change is queued on (always the
+ * toplevel xid) when a subtransaction
+ * modified the catalog */
} tuplecid;
/* Invalidation. */
@@ -706,6 +711,8 @@ extern void ReorderBufferCommitChild(ReorderBuffer *rb, TransactionId xid,
XLogRecPtr end_lsn);
extern void ReorderBufferAbort(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn,
TimestampTz abort_time);
+extern void ReorderBufferCleanupSubTxnTupleCids(ReorderBuffer *rb, TransactionId xid,
+ TransactionId primary_xid);
extern void ReorderBufferAbortOld(ReorderBuffer *rb, TransactionId oldestRunningXid);
extern void ReorderBufferForget(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn);
extern void ReorderBufferInvalidate(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn);
@@ -719,7 +726,9 @@ extern void ReorderBufferAddNewCommandId(ReorderBuffer *rb, TransactionId xid,
extern void ReorderBufferAddNewTupleCids(ReorderBuffer *rb, TransactionId xid,
XLogRecPtr lsn, RelFileLocator locator,
ItemPointerData tid,
- CommandId cmin, CommandId cmax, CommandId combocid);
+ CommandId cmin, CommandId cmax,
+ CommandId combocid,
+ TransactionId subxid);
extern void ReorderBufferAddInvalidations(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn,
Size nmsgs, SharedInvalidationMessage *msgs);
extern void ReorderBufferAddDistributedInvalidations(ReorderBuffer *rb, TransactionId xid,
--
2.43.0
^ permalink raw reply [nested|flat] 53+ messages in thread
* RE: Bug in logical decoding with DDL and subtransactions
@ 2026-09-30 09:58 Bingshuai Li <lucian1412@outlook.com>
parent: Bingshuai Li <lucian1412@outlook.com>
0 siblings, 1 reply; 53+ messages in thread
From: Bingshuai Li @ 2026-09-30 09:58 UTC (permalink / raw)
To: Michael Paquier <michael@paquier.xyz>; Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Alexander Lakhin <exclusion@gmail.com>; alvherre@kurilemu.de <alvherre@kurilemu.de>; pgsql-hackers@lists.postgresql.org <pgsql-hackers@lists.postgresql.org>; mark.dilger@enterprisedb.com <mark.dilger@enterprisedb.com>; Amit Kapila <amit.kapila16@gmail.com>; Masahiko Sawada <sawada.mshk@gmail.com>; Andrey Rachitskiy <pl0h0yp1@gmail.com>; a.kozhemyakin@postgrespro.ru <a.kozhemyakin@postgrespro.ru>; kuroda.hayato@fujitsu.com <kuroda.hayato@fujitsu.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
Attachments:
v5-0001-Fix-stale-tuplecid-records-left-behind-by-aborted.patch (application/octet-stream, 35.5K) download
From ff518e4ecb51b8e62c1596f6229cf9aa4704fef2 Mon Sep 17 00:00:00 2001
From: Bingshuai Li <lucian1412@outlook.com>
Date: Wed, 30 Sep 2026 11:52:16 +0800
Subject: [PATCH] Fix stale tuplecid records left behind by aborted
subtransactions
Tuplecid changes are always queued on the toplevel transaction, so
unlike regular changes they are not dropped when the subtransaction
that wrote them aborts. The stale mappings corrupt
ReorderBufferBuildTupleCidHash() at commit time: if a later catalog
insert reuses the aborted subtransaction's line pointer (made
LP_UNUSED by on-access pruning or by vacuum), the fresh record
collides with the stale one with a different cmin, tripping the cmin
equality assertion; where nothing reuses the tid, a stale cmax makes
a still-live catalog tuple look deleted on historic snapshots. On
non-assert builds there is no crash, but the stale mappings risk
misjudging historic catalog visibility, which could produce
incorrect decoding output.
Remove the aborted subtransaction's tuplecid entries when its abort
is decoded. The cleanup is not needed when the whole toplevel
transaction is being aborted, because ReorderBufferCleanupTXN()
frees the whole list anyway; to avoid scanning the list once per
aborted subxid in that case, DecodeAbort() passes the abort record's
primary xid to the new ReorderBufferCleanupSubTxnTupleCids(), which
skips the scan when that xid is the toplevel of the xid being
cleaned.
The decision cannot be based on whether the primary xid's own
association with its toplevel is known: abort records are written
after the subtransaction has entered TRANS_ABORT, so they never
carry the toplevel xid in their header, and an outer subtransaction
that never wrote WAL of its own -- for example a savepoint that only
wraps other savepoints -- can never get its association established
at all. When such an outer subtransaction is rolled back, the
released inner subtransactions listed in its abort record do have
known associations, and their tuplecids must be removed from the
surviving toplevel's list. The existing tuplecid and tuplecid_restart
tests only cover aborts of subtransactions that wrote WAL themselves,
which is why this shape needs its own test.
Skipping the cleanup when the association of the xid being cleaned
is unknown is safe because of how a slot's restart point advances:
SnapBuildProcessRunningXacts() cannot move the restart point past
the oldest in-progress transaction, so any pass that output-decodes
the toplevel commit must have replayed the subtransaction's first
record and therefore knows 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 via
SnapBuildXactNeedsSkip(), so any stale tuplecid entries left behind
are dropped along with the transaction state and never reach
ReorderBufferBuildTupleCidHash().
Add an isolation test for the nested shape: the toplevel writes WAL
first, an inner subtransaction modifies a user catalog table and is
released, and the outer subtransaction -- which produces no WAL of
its own -- is then rolled back; with the page-fill and vacuum recipe
of tuplecid_restart, the toplevel's later insert deterministically
reuses the aborted subtransaction's line pointer. On unfixed assert
builds the final get_changes dies with the original cmin assertion
in ReorderBufferBuildTupleCidHash(); with the fix it passes. The
existing tests keep covering the simple savepoint and the restart
shapes.
Bug: #19555
Reported-by: Alexander Kozhemyakin <a.kozhemyakin@postgrespro.ru>
Based-on-patch-by: Mark Dilger
Discussion: https://postgr.es/m/CAHgHdKu5e3XY5e90Tuaxq_R4WrKxSV734Q%2BLwo5y39Omp2A-Gg@mail.gmail.com
---
contrib/test_decoding/Makefile | 6 +-
contrib/test_decoding/expected/tuplecid.out | 199 ++++++++++++++++++
.../expected/tuplecid_nested.out | 32 +++
.../expected/tuplecid_restart.out | 68 ++++++
contrib/test_decoding/meson.build | 3 +
.../test_decoding/specs/tuplecid_nested.spec | 77 +++++++
.../test_decoding/specs/tuplecid_restart.spec | 75 +++++++
contrib/test_decoding/sql/tuplecid.sql | 76 +++++++
src/backend/replication/logical/decode.c | 21 ++
.../replication/logical/reorderbuffer.c | 86 +++++++-
src/backend/replication/logical/snapbuild.c | 2 +-
src/include/replication/reorderbuffer.h | 11 +-
12 files changed, 651 insertions(+), 5 deletions(-)
create mode 100644 contrib/test_decoding/expected/tuplecid.out
create mode 100644 contrib/test_decoding/expected/tuplecid_nested.out
create mode 100644 contrib/test_decoding/expected/tuplecid_restart.out
create mode 100644 contrib/test_decoding/specs/tuplecid_nested.spec
create mode 100644 contrib/test_decoding/specs/tuplecid_restart.spec
create mode 100644 contrib/test_decoding/sql/tuplecid.sql
diff --git a/contrib/test_decoding/Makefile b/contrib/test_decoding/Makefile
index 0111124399a..e00d75316e8 100644
--- a/contrib/test_decoding/Makefile
+++ b/contrib/test_decoding/Makefile
@@ -5,11 +5,13 @@ PGFILEDESC = "test_decoding - example of a logical decoding output plugin"
REGRESS = ddl xact rewrite toast permissions decoding_in_xact \
decoding_into_rel binary prepared replorigin time messages \
- repack spill slot truncate stream stats twophase twophase_stream
+ repack spill slot truncate stream stats twophase twophase_stream \
+ tuplecid
ISOLATION = mxact delayed_startup ondisk_startup concurrent_ddl_dml \
oldest_xmin snapshot_transfer subxact_without_top concurrent_stream \
twophase_snapshot slot_creation_error catalog_change_snapshot \
- skip_snapshot_restore invalidation_distribution parallel_session_origin
+ skip_snapshot_restore invalidation_distribution parallel_session_origin \
+ tuplecid_restart tuplecid_nested
REGRESS_OPTS = --temp-config $(top_srcdir)/contrib/test_decoding/logical.conf
ISOLATION_OPTS = --temp-config $(top_srcdir)/contrib/test_decoding/logical.conf
diff --git a/contrib/test_decoding/expected/tuplecid.out b/contrib/test_decoding/expected/tuplecid.out
new file mode 100644
index 00000000000..b559dd21bd4
--- /dev/null
+++ b/contrib/test_decoding/expected/tuplecid.out
@@ -0,0 +1,199 @@
+-- Tests for decoding of transactions in which a catalog-modifying
+-- subtransaction was rolled back (BUG #19555).
+--
+-- When a subtransaction modifies catalog tuples and is then rolled back,
+-- its dead heap-only line pointers can be marked LP_UNUSED by on-access
+-- pruning and reused by later catalog inserts of the same top-level
+-- transaction. The aborted subtransaction's xl_heap_new_cid records must
+-- not be consulted when building the historic snapshot used to decode the
+-- transaction; on unfixed builds they collide with the records of the
+-- reused line pointer and decoding dies with
+-- TRAP: failed Assert("ent->cmin == change->data.tuplecid.cmin")
+-- (or, on non-assert builds, silently uses wrong cmin/cmax mappings).
+--
+-- Whether the collision triggers depends on the physical layout of the
+-- catalog pages, so run in a fresh database where prior tests cannot have
+-- changed it, and loop enough times to leave headroom for layout
+-- differences across versions.
+CREATE DATABASE regression_tuplecid;
+-- snapshot the original database name (make and meson use different
+-- names for it) so we can switch back before dropping the test database
+\set prevdb :DBNAME
+\c regression_tuplecid
+-- predictability
+SET synchronous_commit = on;
+SELECT 'init' FROM pg_create_logical_replication_slot('regression_slot', 'test_decoding');
+ ?column?
+----------
+ init
+(1 row)
+
+-- Catalog churn to push the catalog pages into a state where on-access
+-- pruning frees the aborted subtransaction's line pointer and the second
+-- ALTER's catalog insert reuses it.
+CREATE TABLE tpc_filler1(f1 char(4));
+CREATE TABLE tpc_filler2(data text);
+INSERT INTO tpc_filler2 VALUES ('before-test');
+CREATE TYPE tpc_complex AS (r float8, i float8);
+CREATE TABLE tpc_filler3 (a int PRIMARY KEY, b text DEFAULT 'Unspecified');
+CREATE TABLE tpc_filler4 (id serial, t text);
+CREATE TABLE tpc_filler5(data text);
+INSERT INTO tpc_filler5 SELECT repeat('a', 2000) || g.i FROM generate_series(1, 1) g(i);
+TRUNCATE table tpc_filler5;
+CHECKPOINT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+ count
+-------
+ 9
+(1 row)
+
+-- Each iteration runs the trigger shape: catalog DDL inside a rolled-back
+-- subtransaction, then the same DDL again, then decode. Unfixed builds
+-- typically die within a handful of iterations.
+-- (temporarily hide the queries, to avoid flooding the expected output)
+\set ECHO none
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+DROP TABLE tpc_filler1;
+DROP TABLE tpc_filler2;
+DROP TYPE tpc_complex;
+DROP TABLE tpc_filler3;
+DROP TABLE tpc_filler4;
+DROP TABLE tpc_filler5;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+ count
+-------
+ 0
+(1 row)
+
+SELECT pg_drop_replication_slot('regression_slot');
+ pg_drop_replication_slot
+--------------------------
+
+(1 row)
+
+\c :prevdb
+DROP DATABASE regression_tuplecid;
diff --git a/contrib/test_decoding/expected/tuplecid_nested.out b/contrib/test_decoding/expected/tuplecid_nested.out
new file mode 100644
index 00000000000..5d816374fbc
--- /dev/null
+++ b/contrib/test_decoding/expected/tuplecid_nested.out
@@ -0,0 +1,32 @@
+Parsed test spec with 3 sessions
+
+starting permutation: s1_init s0_begin s0_topwrite s0_outer s0_inner s0_catinsert1 s0_release_inner s0_rollback_outer s2_vacuum s0_catinsert2 s0_commit s1_get_changes
+step s1_init: SELECT 'init' FROM pg_create_logical_replication_slot('tuplecid_nested_slot', 'test_decoding');
+?column?
+--------
+init
+(1 row)
+
+step s0_begin: BEGIN;
+step s0_topwrite: INSERT INTO tbl1 VALUES (0);
+step s0_outer: SAVEPOINT outer_sp;
+step s0_inner: SAVEPOINT inner_sp;
+step s0_catinsert1: INSERT INTO user_cat VALUES (5, 'e');
+step s0_release_inner: RELEASE SAVEPOINT inner_sp;
+step s0_rollback_outer: ROLLBACK TO SAVEPOINT outer_sp;
+step s2_vacuum: VACUUM user_cat;
+step s0_catinsert2: INSERT INTO user_cat VALUES (6, 'f');
+step s0_commit: COMMIT;
+step s1_get_changes: SELECT data FROM pg_logical_slot_get_changes('tuplecid_nested_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%';
+data
+------------------------------------------
+BEGIN
+table public.tbl1: INSERT: val1[integer]:0
+COMMIT
+(3 rows)
+
+?column?
+--------
+stop
+(1 row)
+
diff --git a/contrib/test_decoding/expected/tuplecid_restart.out b/contrib/test_decoding/expected/tuplecid_restart.out
new file mode 100644
index 00000000000..e5b4bc2543d
--- /dev/null
+++ b/contrib/test_decoding/expected/tuplecid_restart.out
@@ -0,0 +1,68 @@
+Parsed test spec with 3 sessions
+
+starting permutation: s0_init s0_begin s0_savepoint s0_insert s1_checkpoint s1_get_changes s0_catinsert1 s0_rollback s2_vacuum s0_catinsert2 s1_checkpoint s1_get_changes s0_commit s1_get_changes
+step s0_init: SELECT 'init' FROM pg_create_logical_replication_slot('isolation_slot', 'test_decoding');
+?column?
+--------
+init
+(1 row)
+
+step s0_begin: BEGIN;
+step s0_savepoint: SAVEPOINT sp1;
+step s0_insert: INSERT INTO tbl1 VALUES (1);
+step s1_checkpoint: CHECKPOINT;
+step s1_get_changes: SELECT data FROM pg_logical_slot_get_changes('isolation_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%';
+data
+----
+(0 rows)
+
+step s0_catinsert1: INSERT INTO user_cat VALUES (5, 'e');
+step s0_rollback: ROLLBACK TO SAVEPOINT sp1;
+step s2_vacuum: VACUUM user_cat;
+step s0_catinsert2: INSERT INTO user_cat VALUES (6, 'f');
+step s1_checkpoint: CHECKPOINT;
+step s1_get_changes: SELECT data FROM pg_logical_slot_get_changes('isolation_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%';
+data
+----
+(0 rows)
+
+step s0_commit: COMMIT;
+step s1_get_changes: SELECT data FROM pg_logical_slot_get_changes('isolation_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%';
+data
+------
+BEGIN
+COMMIT
+(2 rows)
+
+?column?
+--------
+stop
+(1 row)
+
+
+starting permutation: s0_begin s0_savepoint s0_insert s1_init s0_catinsert1 s0_rollback s2_vacuum s0_catinsert2 s0_commit s1_get_changes
+step s0_begin: BEGIN;
+step s0_savepoint: SAVEPOINT sp1;
+step s0_insert: INSERT INTO tbl1 VALUES (1);
+step s1_init: SELECT 'init' FROM pg_create_logical_replication_slot('isolation_slot', 'test_decoding'); <waiting ...>
+step s0_catinsert1: INSERT INTO user_cat VALUES (5, 'e');
+step s0_rollback: ROLLBACK TO SAVEPOINT sp1;
+step s2_vacuum: VACUUM user_cat;
+step s0_catinsert2: INSERT INTO user_cat VALUES (6, 'f');
+step s0_commit: COMMIT;
+step s1_init: <... completed>
+?column?
+--------
+init
+(1 row)
+
+step s1_get_changes: SELECT data FROM pg_logical_slot_get_changes('isolation_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%';
+data
+----
+(0 rows)
+
+?column?
+--------
+stop
+(1 row)
+
diff --git a/contrib/test_decoding/meson.build b/contrib/test_decoding/meson.build
index ac655853d26..32143732212 100644
--- a/contrib/test_decoding/meson.build
+++ b/contrib/test_decoding/meson.build
@@ -42,6 +42,7 @@ tests += {
'stats',
'twophase',
'twophase_stream',
+ 'tuplecid',
],
'regress_args': [
'--temp-config', files('logical.conf'),
@@ -66,6 +67,8 @@ tests += {
'skip_snapshot_restore',
'invalidation_distribution',
'parallel_session_origin',
+ 'tuplecid_restart',
+ 'tuplecid_nested',
],
'regress_args': [
'--temp-config', files('logical.conf'),
diff --git a/contrib/test_decoding/specs/tuplecid_nested.spec b/contrib/test_decoding/specs/tuplecid_nested.spec
new file mode 100644
index 00000000000..52c80eb55eb
--- /dev/null
+++ b/contrib/test_decoding/specs/tuplecid_nested.spec
@@ -0,0 +1,77 @@
+# Test decoding of a partially rolled back transaction where the aborted part
+# is nested: the aborting outer subtransaction never produced any WAL of its
+# own, so decoding cannot know its toplevel transaction, while an inner
+# subtransaction it rolls back did produce WAL and its tuplecid records still
+# have to be removed (BUG #19555 nested shape).
+#
+# The tuplecid records written by the aborted inner subtransaction are queued
+# on the toplevel transaction and must be removed when the outer
+# subtransaction's abort is decoded; otherwise they collide with the records
+# of the line pointer that gets reused by the toplevel transaction's later
+# catalog insert, failing Assert(ent->cmin == change->data.tuplecid.cmin) in
+# ReorderBufferBuildTupleCidHash() when the commit is decoded.
+#
+# - s0_topwrite makes the toplevel transaction produce its first WAL record
+# before any subtransaction exists.
+# - s0_outer establishes the outer savepoint, which never gets a WAL record
+# of its own.
+# - s0_catinsert1 generates an xl_heap_new_cid record in the inner
+# subtransaction, which is then released.
+# - s0_rollback_outer rolls the outer savepoint back. Its abort record is
+# written once the backend is already in TRANS_ABORT, so it carries no
+# toplevel xid in its header and the outer subtransaction's association
+# with the toplevel can never be established. The released inner
+# subtransaction is listed in the same abort record, though, and its
+# tuplecid records still must be removed from the toplevel's list.
+# - s2_vacuum reclaims the aborted row's line pointer (dead inserts are
+# removed regardless of the xid horizon, so this is deterministic even
+# while the toplevel transaction is still open); s0_catinsert2 then reuses
+# the same tid with a different cmin.
+# - s1_get_changes then decodes the toplevel commit and builds the tuplecid
+# hash; on unfixed builds the stale tuplecid of the aborted inner
+# subtransaction collides there with the fresh one.
+setup
+{
+ DROP TABLE IF EXISTS tbl1;
+ DROP TABLE IF EXISTS user_cat;
+ CREATE TABLE tbl1 (val1 integer);
+ -- Four rows of ~1.5kB fill the first heap page to within a few hundred
+ -- bytes, so that vacuuming away the aborted fifth row leaves exactly one
+ -- line pointer for the next insert to reuse.
+ CREATE TABLE user_cat (c1 int, filler char(1500)) WITH (user_catalog_table = true);
+ INSERT INTO user_cat VALUES (1, 'a'), (2, 'b'), (3, 'c'), (4, 'd');
+}
+
+teardown
+{
+ DROP TABLE tbl1;
+ DROP TABLE user_cat;
+ SELECT 'stop' FROM pg_drop_replication_slot('tuplecid_nested_slot');
+}
+
+session "s0"
+setup { SET synchronous_commit=on; }
+step "s0_begin" { BEGIN; }
+step "s0_topwrite" { INSERT INTO tbl1 VALUES (0); }
+step "s0_outer" { SAVEPOINT outer_sp; }
+step "s0_inner" { SAVEPOINT inner_sp; }
+step "s0_catinsert1" { INSERT INTO user_cat VALUES (5, 'e'); }
+step "s0_release_inner" { RELEASE SAVEPOINT inner_sp; }
+step "s0_rollback_outer" { ROLLBACK TO SAVEPOINT outer_sp; }
+step "s0_catinsert2" { INSERT INTO user_cat VALUES (6, 'f'); }
+step "s0_commit" { COMMIT; }
+
+session "s1"
+setup { SET synchronous_commit=on; }
+step "s1_init" { SELECT 'init' FROM pg_create_logical_replication_slot('tuplecid_nested_slot', 'test_decoding'); }
+# The user_cat rows carry ~1.5kB filler values which would flood the expected
+# output; filter them out (decoding still processes them server-side).
+step "s1_get_changes" { SELECT data FROM pg_logical_slot_get_changes('tuplecid_nested_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%'; }
+
+session "s2"
+setup { SET synchronous_commit=on; }
+step "s2_vacuum" { VACUUM user_cat; }
+
+# The slot is created before the transaction begins, so the final
+# s1_get_changes decodes the whole transaction through its commit.
+permutation "s1_init" "s0_begin" "s0_topwrite" "s0_outer" "s0_inner" "s0_catinsert1" "s0_release_inner" "s0_rollback_outer" "s2_vacuum" "s0_catinsert2" "s0_commit" "s1_get_changes"
diff --git a/contrib/test_decoding/specs/tuplecid_restart.spec b/contrib/test_decoding/specs/tuplecid_restart.spec
new file mode 100644
index 00000000000..58da414e8b7
--- /dev/null
+++ b/contrib/test_decoding/specs/tuplecid_restart.spec
@@ -0,0 +1,75 @@
+# Test decoding of a transaction in which a catalog-modifying subtransaction
+# was rolled back, where the transaction spans a logical decoding restart
+# point (BUG #19555 restart shape).
+#
+# The tuplecid records written by the aborted subtransaction are queued on the
+# toplevel transaction and must be removed when the subtransaction's abort is
+# decoded; otherwise they collide with the records of the line pointer that
+# gets reused by the toplevel transaction's later catalog insert, failing
+# Assert(ent->cmin == change->data.tuplecid.cmin) in
+# ReorderBufferBuildTupleCidHash() when the commit is decoded.
+#
+# - s0_insert runs in a subtransaction and produces its first WAL record.
+# - s0_catinsert1 generates an xl_heap_new_cid record in that subtransaction.
+# - s0_rollback aborts the subtransaction.
+# - s2_vacuum reclaims the aborted row's line pointer (dead inserts are
+# removed regardless of the xid horizon, so this is deterministic even
+# while the toplevel transaction is still open); s0_catinsert2 then reuses
+# the same tid with a different cmin.
+# - The transaction stays open across both checkpoints, so the final
+# s1_get_changes replays the transaction's records from the first
+# checkpoint and decodes its commit for output, building the tuplecid
+# hash. On unfixed builds the stale tuplecid of the aborted
+# subtransaction collides there with the fresh one.
+setup
+{
+ DROP TABLE IF EXISTS tbl1;
+ DROP TABLE IF EXISTS user_cat;
+ CREATE TABLE tbl1 (val1 integer);
+ -- Four rows of ~1.5kB fill the first heap page to within a few hundred
+ -- bytes, so that vacuuming away the aborted fifth row leaves exactly one
+ -- line pointer for the next insert to reuse.
+ CREATE TABLE user_cat (c1 int, filler char(1500)) WITH (user_catalog_table = true);
+ INSERT INTO user_cat VALUES (1, 'a'), (2, 'b'), (3, 'c'), (4, 'd');
+}
+
+teardown
+{
+ DROP TABLE tbl1;
+ DROP TABLE user_cat;
+ SELECT 'stop' FROM pg_drop_replication_slot('isolation_slot');
+}
+
+session "s0"
+setup { SET synchronous_commit=on; }
+step "s0_init" { SELECT 'init' FROM pg_create_logical_replication_slot('isolation_slot', 'test_decoding'); }
+step "s0_begin" { BEGIN; }
+step "s0_savepoint" { SAVEPOINT sp1; }
+step "s0_insert" { INSERT INTO tbl1 VALUES (1); }
+step "s0_catinsert1" { INSERT INTO user_cat VALUES (5, 'e'); }
+step "s0_rollback" { ROLLBACK TO SAVEPOINT sp1; }
+step "s0_catinsert2" { INSERT INTO user_cat VALUES (6, 'f'); }
+step "s0_commit" { COMMIT; }
+
+session "s1"
+setup { SET synchronous_commit=on; }
+step "s1_init" { SELECT 'init' FROM pg_create_logical_replication_slot('isolation_slot', 'test_decoding'); }
+step "s1_checkpoint" { CHECKPOINT; }
+# The user_cat rows carry ~1.5kB filler values which would flood the expected
+# output; filter them out (decoding still processes them server-side).
+step "s1_get_changes" { SELECT data FROM pg_logical_slot_get_changes('isolation_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%'; }
+
+session "s2"
+setup { SET synchronous_commit=on; }
+step "s2_vacuum" { VACUUM user_cat; }
+
+# The transaction commits only after the second s1_get_changes, so the last
+# s1_get_changes both replays the transaction from the first checkpoint and
+# decodes its commit for output.
+permutation "s0_init" "s0_begin" "s0_savepoint" "s0_insert" "s1_checkpoint" "s1_get_changes" "s0_catinsert1" "s0_rollback" "s2_vacuum" "s0_catinsert2" "s1_checkpoint" "s1_get_changes" "s0_commit" "s1_get_changes"
+
+# Variant with the slot created while the transaction is already open: slot
+# creation waits for a consistent point past the open transaction, so the
+# transaction is never decoded by this slot at all (no output). This locks in
+# the behavior that decoding cannot start in the middle of a transaction.
+permutation "s0_begin" "s0_savepoint" "s0_insert" "s1_init" "s0_catinsert1" "s0_rollback" "s2_vacuum" "s0_catinsert2" "s0_commit" "s1_get_changes"
diff --git a/contrib/test_decoding/sql/tuplecid.sql b/contrib/test_decoding/sql/tuplecid.sql
new file mode 100644
index 00000000000..335fb6d1591
--- /dev/null
+++ b/contrib/test_decoding/sql/tuplecid.sql
@@ -0,0 +1,76 @@
+-- Tests for decoding of transactions in which a catalog-modifying
+-- subtransaction was rolled back (BUG #19555).
+--
+-- When a subtransaction modifies catalog tuples and is then rolled back,
+-- its dead heap-only line pointers can be marked LP_UNUSED by on-access
+-- pruning and reused by later catalog inserts of the same top-level
+-- transaction. The aborted subtransaction's xl_heap_new_cid records must
+-- not be consulted when building the historic snapshot used to decode the
+-- transaction; on unfixed builds they collide with the records of the
+-- reused line pointer and decoding dies with
+-- TRAP: failed Assert("ent->cmin == change->data.tuplecid.cmin")
+-- (or, on non-assert builds, silently uses wrong cmin/cmax mappings).
+--
+-- Whether the collision triggers depends on the physical layout of the
+-- catalog pages, so run in a fresh database where prior tests cannot have
+-- changed it, and loop enough times to leave headroom for layout
+-- differences across versions.
+CREATE DATABASE regression_tuplecid;
+-- snapshot the original database name (make and meson use different
+-- names for it) so we can switch back before dropping the test database
+\set prevdb :DBNAME
+\c regression_tuplecid
+
+-- predictability
+SET synchronous_commit = on;
+
+SELECT 'init' FROM pg_create_logical_replication_slot('regression_slot', 'test_decoding');
+
+-- Catalog churn to push the catalog pages into a state where on-access
+-- pruning frees the aborted subtransaction's line pointer and the second
+-- ALTER's catalog insert reuses it.
+CREATE TABLE tpc_filler1(f1 char(4));
+CREATE TABLE tpc_filler2(data text);
+INSERT INTO tpc_filler2 VALUES ('before-test');
+CREATE TYPE tpc_complex AS (r float8, i float8);
+CREATE TABLE tpc_filler3 (a int PRIMARY KEY, b text DEFAULT 'Unspecified');
+CREATE TABLE tpc_filler4 (id serial, t text);
+CREATE TABLE tpc_filler5(data text);
+INSERT INTO tpc_filler5 SELECT repeat('a', 2000) || g.i FROM generate_series(1, 1) g(i);
+TRUNCATE table tpc_filler5;
+CHECKPOINT;
+
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+
+-- Each iteration runs the trigger shape: catalog DDL inside a rolled-back
+-- subtransaction, then the same DDL again, then decode. Unfixed builds
+-- typically die within a handful of iterations.
+-- (temporarily hide the queries, to avoid flooding the expected output)
+\set ECHO none
+SELECT format($fmt$
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+$fmt$)
+FROM generate_series(1, 25) \gexec
+\set ECHO all
+
+DROP TABLE tpc_filler1;
+DROP TABLE tpc_filler2;
+DROP TYPE tpc_complex;
+DROP TABLE tpc_filler3;
+DROP TABLE tpc_filler4;
+DROP TABLE tpc_filler5;
+
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+
+SELECT pg_drop_replication_slot('regression_slot');
+
+\c :prevdb
+DROP DATABASE regression_tuplecid;
diff --git a/src/backend/replication/logical/decode.c b/src/backend/replication/logical/decode.c
index 4a739230264..0e7d4840a8e 100644
--- a/src/backend/replication/logical/decode.c
+++ b/src/backend/replication/logical/decode.c
@@ -892,12 +892,33 @@ DecodeAbort(LogicalDecodingContext *ctx, XLogRecordBuffer *buf,
}
else
{
+ /*
+ * Remove tuplecid changes queued by the aborted (sub)transactions
+ * from the toplevel's list, before the transactions are torn down.
+ * The abort record's primary xid tells
+ * ReorderBufferCleanupSubTxnTupleCids() whether the whole toplevel
+ * is going away, in which case scanning the list is pointless.
+ *
+ * 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.
+ */
for (i = 0; i < parsed->nsubxacts; i++)
{
+ ReorderBufferCleanupSubTxnTupleCids(ctx->reorder,
+ parsed->subxacts[i],
+ xid);
ReorderBufferAbort(ctx->reorder, parsed->subxacts[i],
buf->record->EndRecPtr, abort_time);
}
+ ReorderBufferCleanupSubTxnTupleCids(ctx->reorder, xid, xid);
ReorderBufferAbort(ctx->reorder, xid, buf->record->EndRecPtr,
abort_time);
}
diff --git a/src/backend/replication/logical/reorderbuffer.c b/src/backend/replication/logical/reorderbuffer.c
index 94112c30501..e1c6a7c4d32 100644
--- a/src/backend/replication/logical/reorderbuffer.c
+++ b/src/backend/replication/logical/reorderbuffer.c
@@ -3157,6 +3157,88 @@ ReorderBufferAbort(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn,
ReorderBufferCleanupTXN(rb, txn);
}
+/*
+ * Remove tuplecid changes queued by subtransaction xid from its toplevel
+ * transaction's list.
+ *
+ * Unlike regular changes, tuplecid changes are always queued on the toplevel
+ * transaction (see ReorderBufferAddNewTupleCids), so they would otherwise
+ * survive the abort of the subtransaction that wrote them. That's wrong:
+ * they describe catalog tuple versions created or killed by the aborted
+ * subtransaction, which never became visible, and keeping them can corrupt
+ * ReorderBufferBuildTupleCidHash() at commit time -- both when the toplevel
+ * transaction later reuses the same tid (the stale entry collides with the
+ * fresh one, breaking the cmin equality assumption) and when nothing touches
+ * the tid again (a stale cmax would make a still-live tuple look deleted on
+ * historic snapshots).
+ *
+ * The cleanup is pointless when the whole toplevel transaction is
+ * being aborted, since ReorderBufferCleanupTXN() frees the whole list
+ * anyway; the caller passes the abort record's primary xid and we skip
+ * the scan when it is xid's toplevel. Note that the opposite decision
+ * -- cleaning only when the primary xid's own association is known --
+ * would be wrong: abort records are written once the subtransaction is
+ * already in TRANS_ABORT, so they carry no toplevel xid in their
+ * header, and an outer subtransaction that never wrote WAL of its own
+ * never gets an association at all. When such an outer subtransaction
+ * rolls back, released inner subtransactions listed in its abort record
+ * do have known associations and are cleaned here.
+ *
+ * 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().
+ */
+void
+ReorderBufferCleanupSubTxnTupleCids(ReorderBuffer *rb, TransactionId xid,
+ TransactionId primary_xid)
+{
+ ReorderBufferTXN *txn;
+ ReorderBufferTXN *toptxn;
+ dlist_mutable_iter it;
+
+ txn = ReorderBufferTXNByXid(rb, xid, false, NULL, InvalidXLogRecPtr,
+ false);
+
+ /* unknown transaction, or unknown association: nothing to remove */
+ if (txn == NULL || !rbtxn_is_known_subxact(txn))
+ return;
+
+ toptxn = rbtxn_get_toptxn(txn);
+
+ /*
+ * The whole toplevel transaction is being aborted (the abort record's
+ * primary xid is xid's toplevel): ReorderBufferCleanupTXN() will free
+ * the whole list shortly, don't scan it once per aborted subxid.
+ */
+ if (toptxn->xid == primary_xid)
+ return;
+
+ dlist_foreach_modify(it, &toptxn->tuplecids)
+ {
+ ReorderBufferChange *change;
+
+ change = dlist_container(ReorderBufferChange, node, it.cur);
+
+ Assert(change->action == REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID);
+
+ if (change->data.tuplecid.subxid == xid)
+ {
+ dlist_delete(&change->node);
+ ReorderBufferFreeChange(rb, change, false);
+ toptxn->ntuplecids--;
+ }
+ }
+}
+
/*
* Abort all transactions that aren't actually running anymore because the
* server restarted.
@@ -3490,7 +3572,8 @@ void
ReorderBufferAddNewTupleCids(ReorderBuffer *rb, TransactionId xid,
XLogRecPtr lsn, RelFileLocator locator,
ItemPointerData tid, CommandId cmin,
- CommandId cmax, CommandId combocid)
+ CommandId cmax, CommandId combocid,
+ TransactionId subxid)
{
ReorderBufferChange *change = ReorderBufferAllocChange(rb);
ReorderBufferTXN *txn;
@@ -3502,6 +3585,7 @@ ReorderBufferAddNewTupleCids(ReorderBuffer *rb, TransactionId xid,
change->data.tuplecid.cmin = cmin;
change->data.tuplecid.cmax = cmax;
change->data.tuplecid.combocid = combocid;
+ change->data.tuplecid.subxid = subxid;
change->lsn = lsn;
change->txn = txn;
change->action = REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID;
diff --git a/src/backend/replication/logical/snapbuild.c b/src/backend/replication/logical/snapbuild.c
index 69caf5b02e7..451b2b89286 100644
--- a/src/backend/replication/logical/snapbuild.c
+++ b/src/backend/replication/logical/snapbuild.c
@@ -743,7 +743,7 @@ SnapBuildProcessNewCid(SnapBuild *builder, TransactionId xid,
ReorderBufferAddNewTupleCids(builder->reorder, xlrec->top_xid, lsn,
xlrec->target_locator, xlrec->target_tid,
xlrec->cmin, xlrec->cmax,
- xlrec->combocid);
+ xlrec->combocid, xid);
/* figure out new command id */
if (xlrec->cmin != InvalidCommandId &&
diff --git a/src/include/replication/reorderbuffer.h b/src/include/replication/reorderbuffer.h
index ff825e4b7b2..23c447c4953 100644
--- a/src/include/replication/reorderbuffer.h
+++ b/src/include/replication/reorderbuffer.h
@@ -146,6 +146,11 @@ typedef struct ReorderBufferChange
CommandId cmin;
CommandId cmax;
CommandId combocid;
+ TransactionId subxid; /* xid that wrote the tuplecid record;
+ * differs from the xid of the txn this
+ * change is queued on (always the
+ * toplevel xid) when a subtransaction
+ * modified the catalog */
} tuplecid;
/* Invalidation. */
@@ -738,6 +743,8 @@ extern void ReorderBufferCommitChild(ReorderBuffer *rb, TransactionId xid,
XLogRecPtr end_lsn);
extern void ReorderBufferAbort(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn,
TimestampTz abort_time);
+extern void ReorderBufferCleanupSubTxnTupleCids(ReorderBuffer *rb, TransactionId xid,
+ TransactionId primary_xid);
extern void ReorderBufferAbortOld(ReorderBuffer *rb, TransactionId oldestRunningXid);
extern void ReorderBufferForget(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn);
extern void ReorderBufferInvalidate(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn);
@@ -751,7 +758,9 @@ extern void ReorderBufferAddNewCommandId(ReorderBuffer *rb, TransactionId xid,
extern void ReorderBufferAddNewTupleCids(ReorderBuffer *rb, TransactionId xid,
XLogRecPtr lsn, RelFileLocator locator,
ItemPointerData tid,
- CommandId cmin, CommandId cmax, CommandId combocid);
+ CommandId cmin, CommandId cmax,
+ CommandId combocid,
+ TransactionId subxid);
extern void ReorderBufferAddInvalidations(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn,
Size nmsgs, SharedInvalidationMessage *msgs);
extern void ReorderBufferAddDistributedInvalidations(ReorderBuffer *rb, TransactionId xid,
--
2.43.0
^ permalink raw reply [nested|flat] 53+ messages in thread
* Re: Bug in logical decoding with DDL and subtransactions
@ 2026-09-30 16:33 Zhijie Hou <houzhijie22@gmail.com>
parent: Tom Lane <tgl@sss.pgh.pa.us>
1 sibling, 0 replies; 53+ messages in thread
From: Zhijie Hou @ 2026-09-30 16:33 UTC (permalink / raw)
To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Alexander Lakhin <exclusion@gmail.com>; Bingshuai Li <lucian1412@outlook.com>; alvherre@kurilemu.de <alvherre@kurilemu.de>; pgsql-hackers@lists.postgresql.org <pgsql-hackers@lists.postgresql.org>; mark.dilger@enterprisedb.com <mark.dilger@enterprisedb.com>; Amit Kapila <amit.kapila16@gmail.com>; Masahiko Sawada <sawada.mshk@gmail.com>; Andrey Rachitskiy <pl0h0yp1@gmail.com>; a.kozhemyakin@postgrespro.ru <a.kozhemyakin@postgrespro.ru>
Hi,
On Wed, Sep 30, 2026 at 5:17 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:
>
> Alexander Lakhin <exclusion@gmail.com> 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
^ permalink raw reply [nested|flat] 53+ messages in thread
* RE: Bug in logical decoding with DDL and subtransactions
@ 2026-10-05 10:13 Hayato Kuroda (Fujitsu) <kuroda.hayato@fujitsu.com>
parent: Bingshuai Li <lucian1412@outlook.com>
0 siblings, 1 reply; 53+ messages in thread
From: Hayato Kuroda (Fujitsu) @ 2026-10-05 10:13 UTC (permalink / raw)
To: Bingshuai Li <lucian1412@outlook.com>; Michael Paquier <michael@paquier.xyz>; Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Alexander Lakhin <exclusion@gmail.com>; alvherre@kurilemu.de <alvherre@kurilemu.de>; pgsql-hackers@lists.postgresql.org <pgsql-hackers@lists.postgresql.org>; mark.dilger@enterprisedb.com <mark.dilger@enterprisedb.com>; Amit Kapila <amit.kapila16@gmail.com>; Masahiko Sawada <sawada.mshk@gmail.com>; Andrey Rachitskiy <pl0h0yp1@gmail.com>; a.kozhemyakin@postgrespro.ru <a.kozhemyakin@postgrespro.ru>
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
Attachments:
atop_v5_kuroda.txt (text/plain, 8.5K) download
diff --git a/src/backend/replication/logical/decode.c b/src/backend/replication/logical/decode.c
index 0e7d4840a8e..c45edae853a 100644
--- a/src/backend/replication/logical/decode.c
+++ b/src/backend/replication/logical/decode.c
@@ -895,9 +895,9 @@ DecodeAbort(LogicalDecodingContext *ctx, XLogRecordBuffer *buf,
/*
* Remove tuplecid changes queued by the aborted (sub)transactions
* from the toplevel's list, before the transactions are torn down.
- * The abort record's primary xid tells
- * ReorderBufferCleanupSubTxnTupleCids() whether the whole toplevel
- * is going away, in which case scanning the list is pointless.
+ * The abort record's primary xid tells the cleanup function whether
+ * the whole toplevel is going away, in which case scanning the list is
+ * pointless.
*
* Note that we must not try to decide that from the primary xid's
* own association instead: an abort record is written once the
@@ -909,16 +909,16 @@ DecodeAbort(LogicalDecodingContext *ctx, XLogRecordBuffer *buf,
* all, while the released inner subtransactions it rolls back do
* have one and their tuplecids still need to be removed.
*/
+ ReorderBufferCleanupAbortedSubTxnTupleCids(ctx->reorder, xid,
+ parsed->nsubxacts,
+ parsed->subxacts);
+
for (i = 0; i < parsed->nsubxacts; i++)
{
- ReorderBufferCleanupSubTxnTupleCids(ctx->reorder,
- parsed->subxacts[i],
- xid);
ReorderBufferAbort(ctx->reorder, parsed->subxacts[i],
buf->record->EndRecPtr, abort_time);
}
- ReorderBufferCleanupSubTxnTupleCids(ctx->reorder, xid, xid);
ReorderBufferAbort(ctx->reorder, xid, buf->record->EndRecPtr,
abort_time);
}
diff --git a/src/backend/replication/logical/reorderbuffer.c b/src/backend/replication/logical/reorderbuffer.c
index e1c6a7c4d32..ccbdbde7335 100644
--- a/src/backend/replication/logical/reorderbuffer.c
+++ b/src/backend/replication/logical/reorderbuffer.c
@@ -240,6 +240,9 @@ static ReorderBufferTXN *ReorderBufferTXNByXid(ReorderBuffer *rb,
XLogRecPtr lsn, bool create_as_top);
static void ReorderBufferTransferSnapToParent(ReorderBufferTXN *txn,
ReorderBufferTXN *subtxn);
+static bool TransactionIdInSubxactArray(TransactionId xid,
+ TransactionId *subxacts,
+ int nsubxacts);
static void AssertTXNLsnOrder(ReorderBuffer *rb);
@@ -3158,8 +3161,8 @@ ReorderBufferAbort(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn,
}
/*
- * Remove tuplecid changes queued by subtransaction xid from its toplevel
- * transaction's list.
+ * Remove tuplecid changes queued by aborted subtransactions from their
+ * toplevel transaction's list.
*
* Unlike regular changes, tuplecid changes are always queued on the toplevel
* transaction (see ReorderBufferAddNewTupleCids), so they would otherwise
@@ -3174,15 +3177,10 @@ ReorderBufferAbort(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn,
*
* The cleanup is pointless when the whole toplevel transaction is
* being aborted, since ReorderBufferCleanupTXN() frees the whole list
- * anyway; the caller passes the abort record's primary xid and we skip
- * the scan when it is xid's toplevel. Note that the opposite decision
- * -- cleaning only when the primary xid's own association is known --
- * would be wrong: abort records are written once the subtransaction is
- * already in TRANS_ABORT, so they carry no toplevel xid in their
- * header, and an outer subtransaction that never wrote WAL of its own
- * never gets an association at all. When such an outer subtransaction
- * rolls back, released inner subtransactions listed in its abort record
- * do have known associations and are cleaned here.
+ * anyway. If the primary xid is unknown, search its aborted children for a known
+ * association. An outer subtransaction that never wrote WAL of its own can
+ * have no association, while released inner subtransactions listed in its
+ * abort record do have one and their tuplecids still need to be removed.
*
* If this pass does not know the association between the aborting
* subtransaction and its toplevel, there is nothing we can clean up here, and
@@ -3198,8 +3196,10 @@ ReorderBufferAbort(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn,
* transaction state without ever reaching ReorderBufferBuildTupleCidHash().
*/
void
-ReorderBufferCleanupSubTxnTupleCids(ReorderBuffer *rb, TransactionId xid,
- TransactionId primary_xid)
+ReorderBufferCleanupAbortedSubTxnTupleCids(ReorderBuffer *rb,
+ TransactionId xid,
+ int nsubxacts,
+ TransactionId *subxacts)
{
ReorderBufferTXN *txn;
ReorderBufferTXN *toptxn;
@@ -3208,19 +3208,39 @@ ReorderBufferCleanupSubTxnTupleCids(ReorderBuffer *rb, TransactionId xid,
txn = ReorderBufferTXNByXid(rb, xid, false, NULL, InvalidXLogRecPtr,
false);
- /* unknown transaction, or unknown association: nothing to remove */
- if (txn == NULL || !rbtxn_is_known_subxact(txn))
+ /*
+ * If xid is a known toplevel transaction, the whole transaction is being
+ * aborted and ReorderBufferCleanupTXN() will free the tuplecid list.
+ */
+ if (txn != NULL && !rbtxn_is_known_subxact(txn))
return;
- toptxn = rbtxn_get_toptxn(txn);
-
/*
- * The whole toplevel transaction is being aborted (the abort record's
- * primary xid is xid's toplevel): ReorderBufferCleanupTXN() will free
- * the whole list shortly, don't scan it once per aborted subxid.
+ * If the aborting subtransaction is unknown, try to find the toplevel
+ * transaction through one of its children. There may be any number of
+ * unknown children, but they cannot have queued tuplecid changes: decoding
+ * a WAL record that queues such a change first associates its xid with the
+ * toplevel transaction. Therefore, if all children are unknown, there is
+ * nothing to remove.
*/
- if (toptxn->xid == primary_xid)
- return;
+ if (txn == NULL)
+ {
+ 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;
+
+ txn = NULL;
+ }
+
+ if (txn == NULL)
+ return;
+ }
+
+ /* Get the top-level transaction to clean up its tuplecid list */
+ toptxn = rbtxn_get_toptxn(txn);
dlist_foreach_modify(it, &toptxn->tuplecids)
{
@@ -3230,15 +3250,38 @@ ReorderBufferCleanupSubTxnTupleCids(ReorderBuffer *rb, TransactionId xid,
Assert(change->action == REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID);
- if (change->data.tuplecid.subxid == xid)
+ /*
+ * Remove the entry if it's part of the aborting subtransaction or one
+ * of its children.
+ */
+ 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--;
}
}
}
+/*
+ * Check whether xid is in an array sorted in logical XID order.
+ */
+static bool
+TransactionIdInSubxactArray(TransactionId xid, TransactionId *subxacts,
+ int nsubxacts)
+{
+ /*
+ * 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.
+ */
+ return bsearch(&xid, subxacts, nsubxacts,
+ sizeof(TransactionId), xidLogicalComparator) != NULL;
+}
+
/*
* Abort all transactions that aren't actually running anymore because the
* server restarted.
diff --git a/src/include/replication/reorderbuffer.h b/src/include/replication/reorderbuffer.h
index 23c447c4953..7cfa43ad163 100644
--- a/src/include/replication/reorderbuffer.h
+++ b/src/include/replication/reorderbuffer.h
@@ -743,8 +743,10 @@ extern void ReorderBufferCommitChild(ReorderBuffer *rb, TransactionId xid,
XLogRecPtr end_lsn);
extern void ReorderBufferAbort(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn,
TimestampTz abort_time);
-extern void ReorderBufferCleanupSubTxnTupleCids(ReorderBuffer *rb, TransactionId xid,
- TransactionId primary_xid);
+extern void ReorderBufferCleanupAbortedSubTxnTupleCids(ReorderBuffer *rb,
+ TransactionId xid,
+ int nsubxacts,
+ TransactionId *subxacts);
extern void ReorderBufferAbortOld(ReorderBuffer *rb, TransactionId oldestRunningXid);
extern void ReorderBufferForget(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn);
extern void ReorderBufferInvalidate(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn);
^ permalink raw reply [nested|flat] 53+ messages in thread
* Re: Bug in logical decoding with DDL and subtransactions
@ 2026-10-07 09:55 Zhijie Hou <houzhijie22@gmail.com>
parent: Hayato Kuroda (Fujitsu) <kuroda.hayato@fujitsu.com>
0 siblings, 1 reply; 53+ messages in thread
From: Zhijie Hou @ 2026-10-07 09:55 UTC (permalink / raw)
To: Hayato Kuroda (Fujitsu) <kuroda.hayato@fujitsu.com>; +Cc: Bingshuai Li <lucian1412@outlook.com>; Michael Paquier <michael@paquier.xyz>; Tom Lane <tgl@sss.pgh.pa.us>; Alexander Lakhin <exclusion@gmail.com>; alvherre@kurilemu.de <alvherre@kurilemu.de>; pgsql-hackers@lists.postgresql.org <pgsql-hackers@lists.postgresql.org>; mark.dilger@enterprisedb.com <mark.dilger@enterprisedb.com>; Amit Kapila <amit.kapila16@gmail.com>; Masahiko Sawada <sawada.mshk@gmail.com>; Andrey Rachitskiy <pl0h0yp1@gmail.com>; a.kozhemyakin@postgrespro.ru <a.kozhemyakin@postgrespro.ru>
Hi,
On Mon, Oct 5, 2026 at 6:13 PM Hayato Kuroda (Fujitsu)
<kuroda.hayato@fujitsu.com> 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
^ permalink raw reply [nested|flat] 53+ messages in thread
* Re: Bug in logical decoding with DDL and subtransactions
@ 2026-10-07 10:48 alvherre@kurilemu.de <alvherre@kurilemu.de>
parent: Zhijie Hou <houzhijie22@gmail.com>
0 siblings, 1 reply; 53+ messages in thread
From: alvherre@kurilemu.de @ 2026-10-07 10:48 UTC (permalink / raw)
To: Zhijie Hou <houzhijie22@gmail.com>; +Cc: Hayato Kuroda (Fujitsu) <kuroda.hayato@fujitsu.com>; Bingshuai Li <lucian1412@outlook.com>; Michael Paquier <michael@paquier.xyz>; Tom Lane <tgl@sss.pgh.pa.us>; Alexander Lakhin <exclusion@gmail.com>; pgsql-hackers@lists.postgresql.org <pgsql-hackers@lists.postgresql.org>; mark.dilger@enterprisedb.com <mark.dilger@enterprisedb.com>; Amit Kapila <amit.kapila16@gmail.com>; Masahiko Sawada <sawada.mshk@gmail.com>; Andrey Rachitskiy <pl0h0yp1@gmail.com>; a.kozhemyakin@postgrespro.ru <a.kozhemyakin@postgrespro.ru>
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.
Attachments: download all (3 files, .tar.gz)
v6-0001-Fix-stale-tuplecid-records-left-behind-by-aborted.patch (text/x-diff, 35.7K) download
From c0bc82f4a84a63d221cd47dcc34e65027a46832c Mon Sep 17 00:00:00 2001
From: Bingshuai Li <lucian1412@outlook.com>
Date: Wed, 30 Sep 2026 11:52:16 +0800
Subject: [PATCH v6 1/3] Fix stale tuplecid records left behind by aborted
subtransactions
Tuplecid changes are always queued on the toplevel transaction, so
unlike regular changes they are not dropped when the subtransaction
that wrote them aborts. The stale mappings corrupt
ReorderBufferBuildTupleCidHash() at commit time: if a later catalog
insert reuses the aborted subtransaction's line pointer (made
LP_UNUSED by on-access pruning or by vacuum), the fresh record
collides with the stale one with a different cmin, tripping the cmin
equality assertion; where nothing reuses the tid, a stale cmax makes
a still-live catalog tuple look deleted on historic snapshots. On
non-assert builds there is no crash, but the stale mappings risk
misjudging historic catalog visibility, which could produce
incorrect decoding output.
Remove the aborted subtransaction's tuplecid entries when its abort
is decoded. The cleanup is not needed when the whole toplevel
transaction is being aborted, because ReorderBufferCleanupTXN()
frees the whole list anyway; to avoid scanning the list once per
aborted subxid in that case, DecodeAbort() passes the abort record's
primary xid to the new ReorderBufferCleanupSubTxnTupleCids(), which
skips the scan when that xid is the toplevel of the xid being
cleaned.
The decision cannot be based on whether the primary xid's own
association with its toplevel is known: abort records are written
after the subtransaction has entered TRANS_ABORT, so they never
carry the toplevel xid in their header, and an outer subtransaction
that never wrote WAL of its own -- for example a savepoint that only
wraps other savepoints -- can never get its association established
at all. When such an outer subtransaction is rolled back, the
released inner subtransactions listed in its abort record do have
known associations, and their tuplecids must be removed from the
surviving toplevel's list. The existing tuplecid and tuplecid_restart
tests only cover aborts of subtransactions that wrote WAL themselves,
which is why this shape needs its own test.
Skipping the cleanup when the association of the xid being cleaned
is unknown is safe because of how a slot's restart point advances:
SnapBuildProcessRunningXacts() cannot move the restart point past
the oldest in-progress transaction, so any pass that output-decodes
the toplevel commit must have replayed the subtransaction's first
record and therefore knows 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 via
SnapBuildXactNeedsSkip(), so any stale tuplecid entries left behind
are dropped along with the transaction state and never reach
ReorderBufferBuildTupleCidHash().
Add an isolation test for the nested shape: the toplevel writes WAL
first, an inner subtransaction modifies a user catalog table and is
released, and the outer subtransaction -- which produces no WAL of
its own -- is then rolled back; with the page-fill and vacuum recipe
of tuplecid_restart, the toplevel's later insert deterministically
reuses the aborted subtransaction's line pointer. On unfixed assert
builds the final get_changes dies with the original cmin assertion
in ReorderBufferBuildTupleCidHash(); with the fix it passes. The
existing tests keep covering the simple savepoint and the restart
shapes.
Bug: #19555
Reported-by: Alexander Kozhemyakin <a.kozhemyakin@postgrespro.ru>
Based-on-patch-by: Mark Dilger
Discussion: https://postgr.es/m/CAHgHdKu5e3XY5e90Tuaxq_R4WrKxSV734Q%2BLwo5y39Omp2A-Gg@mail.gmail.com
---
contrib/test_decoding/Makefile | 5 +-
contrib/test_decoding/expected/tuplecid.out | 199 ++++++++++++++++++
.../expected/tuplecid_nested.out | 32 +++
.../expected/tuplecid_restart.out | 68 ++++++
contrib/test_decoding/meson.build | 3 +
.../test_decoding/specs/tuplecid_nested.spec | 77 +++++++
.../test_decoding/specs/tuplecid_restart.spec | 75 +++++++
contrib/test_decoding/sql/tuplecid.sql | 76 +++++++
src/backend/replication/logical/decode.c | 21 ++
.../replication/logical/reorderbuffer.c | 86 +++++++-
src/backend/replication/logical/snapbuild.c | 2 +-
src/include/replication/reorderbuffer.h | 11 +-
12 files changed, 650 insertions(+), 5 deletions(-)
create mode 100644 contrib/test_decoding/expected/tuplecid.out
create mode 100644 contrib/test_decoding/expected/tuplecid_nested.out
create mode 100644 contrib/test_decoding/expected/tuplecid_restart.out
create mode 100644 contrib/test_decoding/specs/tuplecid_nested.spec
create mode 100644 contrib/test_decoding/specs/tuplecid_restart.spec
create mode 100644 contrib/test_decoding/sql/tuplecid.sql
diff --git a/contrib/test_decoding/Makefile b/contrib/test_decoding/Makefile
index a7f7b7ae789..d84bf3603dd 100644
--- a/contrib/test_decoding/Makefile
+++ b/contrib/test_decoding/Makefile
@@ -5,7 +5,7 @@ PGFILEDESC = "test_decoding - example of a logical decoding output plugin"
REGRESS = ddl xact rewrite toast permissions decoding_in_xact \
decoding_into_rel binary prepared replorigin time messages \
- repack spill slot truncate stream stats twophase twophase_stream
+ repack spill slot truncate stream stats tuplecid twophase twophase_stream
# slot_creation_error terminates another backend, whose FATAL message can be
# lost on Windows, making the test unstable there.
@@ -15,7 +15,8 @@ SLOT_CREATION_TST = $(if $(filter win32,$(PORTNAME)),,slot_creation_error)
ISOLATION = mxact delayed_startup ondisk_startup concurrent_ddl_dml \
oldest_xmin snapshot_transfer subxact_without_top concurrent_stream \
twophase_snapshot $(SLOT_CREATION_TST) catalog_change_snapshot \
- skip_snapshot_restore invalidation_distribution parallel_session_origin
+ skip_snapshot_restore invalidation_distribution parallel_session_origin \
+ tuplecid_restart tuplecid_nested
REGRESS_OPTS = --temp-config $(top_srcdir)/contrib/test_decoding/logical.conf
ISOLATION_OPTS = --temp-config $(top_srcdir)/contrib/test_decoding/logical.conf
diff --git a/contrib/test_decoding/expected/tuplecid.out b/contrib/test_decoding/expected/tuplecid.out
new file mode 100644
index 00000000000..b559dd21bd4
--- /dev/null
+++ b/contrib/test_decoding/expected/tuplecid.out
@@ -0,0 +1,199 @@
+-- Tests for decoding of transactions in which a catalog-modifying
+-- subtransaction was rolled back (BUG #19555).
+--
+-- When a subtransaction modifies catalog tuples and is then rolled back,
+-- its dead heap-only line pointers can be marked LP_UNUSED by on-access
+-- pruning and reused by later catalog inserts of the same top-level
+-- transaction. The aborted subtransaction's xl_heap_new_cid records must
+-- not be consulted when building the historic snapshot used to decode the
+-- transaction; on unfixed builds they collide with the records of the
+-- reused line pointer and decoding dies with
+-- TRAP: failed Assert("ent->cmin == change->data.tuplecid.cmin")
+-- (or, on non-assert builds, silently uses wrong cmin/cmax mappings).
+--
+-- Whether the collision triggers depends on the physical layout of the
+-- catalog pages, so run in a fresh database where prior tests cannot have
+-- changed it, and loop enough times to leave headroom for layout
+-- differences across versions.
+CREATE DATABASE regression_tuplecid;
+-- snapshot the original database name (make and meson use different
+-- names for it) so we can switch back before dropping the test database
+\set prevdb :DBNAME
+\c regression_tuplecid
+-- predictability
+SET synchronous_commit = on;
+SELECT 'init' FROM pg_create_logical_replication_slot('regression_slot', 'test_decoding');
+ ?column?
+----------
+ init
+(1 row)
+
+-- Catalog churn to push the catalog pages into a state where on-access
+-- pruning frees the aborted subtransaction's line pointer and the second
+-- ALTER's catalog insert reuses it.
+CREATE TABLE tpc_filler1(f1 char(4));
+CREATE TABLE tpc_filler2(data text);
+INSERT INTO tpc_filler2 VALUES ('before-test');
+CREATE TYPE tpc_complex AS (r float8, i float8);
+CREATE TABLE tpc_filler3 (a int PRIMARY KEY, b text DEFAULT 'Unspecified');
+CREATE TABLE tpc_filler4 (id serial, t text);
+CREATE TABLE tpc_filler5(data text);
+INSERT INTO tpc_filler5 SELECT repeat('a', 2000) || g.i FROM generate_series(1, 1) g(i);
+TRUNCATE table tpc_filler5;
+CHECKPOINT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+ count
+-------
+ 9
+(1 row)
+
+-- Each iteration runs the trigger shape: catalog DDL inside a rolled-back
+-- subtransaction, then the same DDL again, then decode. Unfixed builds
+-- typically die within a handful of iterations.
+-- (temporarily hide the queries, to avoid flooding the expected output)
+\set ECHO none
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+DROP TABLE tpc_filler1;
+DROP TABLE tpc_filler2;
+DROP TYPE tpc_complex;
+DROP TABLE tpc_filler3;
+DROP TABLE tpc_filler4;
+DROP TABLE tpc_filler5;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+ count
+-------
+ 0
+(1 row)
+
+SELECT pg_drop_replication_slot('regression_slot');
+ pg_drop_replication_slot
+--------------------------
+
+(1 row)
+
+\c :prevdb
+DROP DATABASE regression_tuplecid;
diff --git a/contrib/test_decoding/expected/tuplecid_nested.out b/contrib/test_decoding/expected/tuplecid_nested.out
new file mode 100644
index 00000000000..5d816374fbc
--- /dev/null
+++ b/contrib/test_decoding/expected/tuplecid_nested.out
@@ -0,0 +1,32 @@
+Parsed test spec with 3 sessions
+
+starting permutation: s1_init s0_begin s0_topwrite s0_outer s0_inner s0_catinsert1 s0_release_inner s0_rollback_outer s2_vacuum s0_catinsert2 s0_commit s1_get_changes
+step s1_init: SELECT 'init' FROM pg_create_logical_replication_slot('tuplecid_nested_slot', 'test_decoding');
+?column?
+--------
+init
+(1 row)
+
+step s0_begin: BEGIN;
+step s0_topwrite: INSERT INTO tbl1 VALUES (0);
+step s0_outer: SAVEPOINT outer_sp;
+step s0_inner: SAVEPOINT inner_sp;
+step s0_catinsert1: INSERT INTO user_cat VALUES (5, 'e');
+step s0_release_inner: RELEASE SAVEPOINT inner_sp;
+step s0_rollback_outer: ROLLBACK TO SAVEPOINT outer_sp;
+step s2_vacuum: VACUUM user_cat;
+step s0_catinsert2: INSERT INTO user_cat VALUES (6, 'f');
+step s0_commit: COMMIT;
+step s1_get_changes: SELECT data FROM pg_logical_slot_get_changes('tuplecid_nested_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%';
+data
+------------------------------------------
+BEGIN
+table public.tbl1: INSERT: val1[integer]:0
+COMMIT
+(3 rows)
+
+?column?
+--------
+stop
+(1 row)
+
diff --git a/contrib/test_decoding/expected/tuplecid_restart.out b/contrib/test_decoding/expected/tuplecid_restart.out
new file mode 100644
index 00000000000..e5b4bc2543d
--- /dev/null
+++ b/contrib/test_decoding/expected/tuplecid_restart.out
@@ -0,0 +1,68 @@
+Parsed test spec with 3 sessions
+
+starting permutation: s0_init s0_begin s0_savepoint s0_insert s1_checkpoint s1_get_changes s0_catinsert1 s0_rollback s2_vacuum s0_catinsert2 s1_checkpoint s1_get_changes s0_commit s1_get_changes
+step s0_init: SELECT 'init' FROM pg_create_logical_replication_slot('isolation_slot', 'test_decoding');
+?column?
+--------
+init
+(1 row)
+
+step s0_begin: BEGIN;
+step s0_savepoint: SAVEPOINT sp1;
+step s0_insert: INSERT INTO tbl1 VALUES (1);
+step s1_checkpoint: CHECKPOINT;
+step s1_get_changes: SELECT data FROM pg_logical_slot_get_changes('isolation_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%';
+data
+----
+(0 rows)
+
+step s0_catinsert1: INSERT INTO user_cat VALUES (5, 'e');
+step s0_rollback: ROLLBACK TO SAVEPOINT sp1;
+step s2_vacuum: VACUUM user_cat;
+step s0_catinsert2: INSERT INTO user_cat VALUES (6, 'f');
+step s1_checkpoint: CHECKPOINT;
+step s1_get_changes: SELECT data FROM pg_logical_slot_get_changes('isolation_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%';
+data
+----
+(0 rows)
+
+step s0_commit: COMMIT;
+step s1_get_changes: SELECT data FROM pg_logical_slot_get_changes('isolation_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%';
+data
+------
+BEGIN
+COMMIT
+(2 rows)
+
+?column?
+--------
+stop
+(1 row)
+
+
+starting permutation: s0_begin s0_savepoint s0_insert s1_init s0_catinsert1 s0_rollback s2_vacuum s0_catinsert2 s0_commit s1_get_changes
+step s0_begin: BEGIN;
+step s0_savepoint: SAVEPOINT sp1;
+step s0_insert: INSERT INTO tbl1 VALUES (1);
+step s1_init: SELECT 'init' FROM pg_create_logical_replication_slot('isolation_slot', 'test_decoding'); <waiting ...>
+step s0_catinsert1: INSERT INTO user_cat VALUES (5, 'e');
+step s0_rollback: ROLLBACK TO SAVEPOINT sp1;
+step s2_vacuum: VACUUM user_cat;
+step s0_catinsert2: INSERT INTO user_cat VALUES (6, 'f');
+step s0_commit: COMMIT;
+step s1_init: <... completed>
+?column?
+--------
+init
+(1 row)
+
+step s1_get_changes: SELECT data FROM pg_logical_slot_get_changes('isolation_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%';
+data
+----
+(0 rows)
+
+?column?
+--------
+stop
+(1 row)
+
diff --git a/contrib/test_decoding/meson.build b/contrib/test_decoding/meson.build
index dbc0ef0f63e..b0d3ce66649 100644
--- a/contrib/test_decoding/meson.build
+++ b/contrib/test_decoding/meson.build
@@ -30,6 +30,8 @@ test_decoding_isolation = [
'skip_snapshot_restore',
'invalidation_distribution',
'parallel_session_origin',
+ 'tuplecid_nested',
+ 'tuplecid_restart',
]
# slot_creation_error terminates another backend, whose FATAL message can be
@@ -65,6 +67,7 @@ tests += {
'stats',
'twophase',
'twophase_stream',
+ 'tuplecid',
],
'regress_args': [
'--temp-config', files('logical.conf'),
diff --git a/contrib/test_decoding/specs/tuplecid_nested.spec b/contrib/test_decoding/specs/tuplecid_nested.spec
new file mode 100644
index 00000000000..52c80eb55eb
--- /dev/null
+++ b/contrib/test_decoding/specs/tuplecid_nested.spec
@@ -0,0 +1,77 @@
+# Test decoding of a partially rolled back transaction where the aborted part
+# is nested: the aborting outer subtransaction never produced any WAL of its
+# own, so decoding cannot know its toplevel transaction, while an inner
+# subtransaction it rolls back did produce WAL and its tuplecid records still
+# have to be removed (BUG #19555 nested shape).
+#
+# The tuplecid records written by the aborted inner subtransaction are queued
+# on the toplevel transaction and must be removed when the outer
+# subtransaction's abort is decoded; otherwise they collide with the records
+# of the line pointer that gets reused by the toplevel transaction's later
+# catalog insert, failing Assert(ent->cmin == change->data.tuplecid.cmin) in
+# ReorderBufferBuildTupleCidHash() when the commit is decoded.
+#
+# - s0_topwrite makes the toplevel transaction produce its first WAL record
+# before any subtransaction exists.
+# - s0_outer establishes the outer savepoint, which never gets a WAL record
+# of its own.
+# - s0_catinsert1 generates an xl_heap_new_cid record in the inner
+# subtransaction, which is then released.
+# - s0_rollback_outer rolls the outer savepoint back. Its abort record is
+# written once the backend is already in TRANS_ABORT, so it carries no
+# toplevel xid in its header and the outer subtransaction's association
+# with the toplevel can never be established. The released inner
+# subtransaction is listed in the same abort record, though, and its
+# tuplecid records still must be removed from the toplevel's list.
+# - s2_vacuum reclaims the aborted row's line pointer (dead inserts are
+# removed regardless of the xid horizon, so this is deterministic even
+# while the toplevel transaction is still open); s0_catinsert2 then reuses
+# the same tid with a different cmin.
+# - s1_get_changes then decodes the toplevel commit and builds the tuplecid
+# hash; on unfixed builds the stale tuplecid of the aborted inner
+# subtransaction collides there with the fresh one.
+setup
+{
+ DROP TABLE IF EXISTS tbl1;
+ DROP TABLE IF EXISTS user_cat;
+ CREATE TABLE tbl1 (val1 integer);
+ -- Four rows of ~1.5kB fill the first heap page to within a few hundred
+ -- bytes, so that vacuuming away the aborted fifth row leaves exactly one
+ -- line pointer for the next insert to reuse.
+ CREATE TABLE user_cat (c1 int, filler char(1500)) WITH (user_catalog_table = true);
+ INSERT INTO user_cat VALUES (1, 'a'), (2, 'b'), (3, 'c'), (4, 'd');
+}
+
+teardown
+{
+ DROP TABLE tbl1;
+ DROP TABLE user_cat;
+ SELECT 'stop' FROM pg_drop_replication_slot('tuplecid_nested_slot');
+}
+
+session "s0"
+setup { SET synchronous_commit=on; }
+step "s0_begin" { BEGIN; }
+step "s0_topwrite" { INSERT INTO tbl1 VALUES (0); }
+step "s0_outer" { SAVEPOINT outer_sp; }
+step "s0_inner" { SAVEPOINT inner_sp; }
+step "s0_catinsert1" { INSERT INTO user_cat VALUES (5, 'e'); }
+step "s0_release_inner" { RELEASE SAVEPOINT inner_sp; }
+step "s0_rollback_outer" { ROLLBACK TO SAVEPOINT outer_sp; }
+step "s0_catinsert2" { INSERT INTO user_cat VALUES (6, 'f'); }
+step "s0_commit" { COMMIT; }
+
+session "s1"
+setup { SET synchronous_commit=on; }
+step "s1_init" { SELECT 'init' FROM pg_create_logical_replication_slot('tuplecid_nested_slot', 'test_decoding'); }
+# The user_cat rows carry ~1.5kB filler values which would flood the expected
+# output; filter them out (decoding still processes them server-side).
+step "s1_get_changes" { SELECT data FROM pg_logical_slot_get_changes('tuplecid_nested_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%'; }
+
+session "s2"
+setup { SET synchronous_commit=on; }
+step "s2_vacuum" { VACUUM user_cat; }
+
+# The slot is created before the transaction begins, so the final
+# s1_get_changes decodes the whole transaction through its commit.
+permutation "s1_init" "s0_begin" "s0_topwrite" "s0_outer" "s0_inner" "s0_catinsert1" "s0_release_inner" "s0_rollback_outer" "s2_vacuum" "s0_catinsert2" "s0_commit" "s1_get_changes"
diff --git a/contrib/test_decoding/specs/tuplecid_restart.spec b/contrib/test_decoding/specs/tuplecid_restart.spec
new file mode 100644
index 00000000000..58da414e8b7
--- /dev/null
+++ b/contrib/test_decoding/specs/tuplecid_restart.spec
@@ -0,0 +1,75 @@
+# Test decoding of a transaction in which a catalog-modifying subtransaction
+# was rolled back, where the transaction spans a logical decoding restart
+# point (BUG #19555 restart shape).
+#
+# The tuplecid records written by the aborted subtransaction are queued on the
+# toplevel transaction and must be removed when the subtransaction's abort is
+# decoded; otherwise they collide with the records of the line pointer that
+# gets reused by the toplevel transaction's later catalog insert, failing
+# Assert(ent->cmin == change->data.tuplecid.cmin) in
+# ReorderBufferBuildTupleCidHash() when the commit is decoded.
+#
+# - s0_insert runs in a subtransaction and produces its first WAL record.
+# - s0_catinsert1 generates an xl_heap_new_cid record in that subtransaction.
+# - s0_rollback aborts the subtransaction.
+# - s2_vacuum reclaims the aborted row's line pointer (dead inserts are
+# removed regardless of the xid horizon, so this is deterministic even
+# while the toplevel transaction is still open); s0_catinsert2 then reuses
+# the same tid with a different cmin.
+# - The transaction stays open across both checkpoints, so the final
+# s1_get_changes replays the transaction's records from the first
+# checkpoint and decodes its commit for output, building the tuplecid
+# hash. On unfixed builds the stale tuplecid of the aborted
+# subtransaction collides there with the fresh one.
+setup
+{
+ DROP TABLE IF EXISTS tbl1;
+ DROP TABLE IF EXISTS user_cat;
+ CREATE TABLE tbl1 (val1 integer);
+ -- Four rows of ~1.5kB fill the first heap page to within a few hundred
+ -- bytes, so that vacuuming away the aborted fifth row leaves exactly one
+ -- line pointer for the next insert to reuse.
+ CREATE TABLE user_cat (c1 int, filler char(1500)) WITH (user_catalog_table = true);
+ INSERT INTO user_cat VALUES (1, 'a'), (2, 'b'), (3, 'c'), (4, 'd');
+}
+
+teardown
+{
+ DROP TABLE tbl1;
+ DROP TABLE user_cat;
+ SELECT 'stop' FROM pg_drop_replication_slot('isolation_slot');
+}
+
+session "s0"
+setup { SET synchronous_commit=on; }
+step "s0_init" { SELECT 'init' FROM pg_create_logical_replication_slot('isolation_slot', 'test_decoding'); }
+step "s0_begin" { BEGIN; }
+step "s0_savepoint" { SAVEPOINT sp1; }
+step "s0_insert" { INSERT INTO tbl1 VALUES (1); }
+step "s0_catinsert1" { INSERT INTO user_cat VALUES (5, 'e'); }
+step "s0_rollback" { ROLLBACK TO SAVEPOINT sp1; }
+step "s0_catinsert2" { INSERT INTO user_cat VALUES (6, 'f'); }
+step "s0_commit" { COMMIT; }
+
+session "s1"
+setup { SET synchronous_commit=on; }
+step "s1_init" { SELECT 'init' FROM pg_create_logical_replication_slot('isolation_slot', 'test_decoding'); }
+step "s1_checkpoint" { CHECKPOINT; }
+# The user_cat rows carry ~1.5kB filler values which would flood the expected
+# output; filter them out (decoding still processes them server-side).
+step "s1_get_changes" { SELECT data FROM pg_logical_slot_get_changes('isolation_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%'; }
+
+session "s2"
+setup { SET synchronous_commit=on; }
+step "s2_vacuum" { VACUUM user_cat; }
+
+# The transaction commits only after the second s1_get_changes, so the last
+# s1_get_changes both replays the transaction from the first checkpoint and
+# decodes its commit for output.
+permutation "s0_init" "s0_begin" "s0_savepoint" "s0_insert" "s1_checkpoint" "s1_get_changes" "s0_catinsert1" "s0_rollback" "s2_vacuum" "s0_catinsert2" "s1_checkpoint" "s1_get_changes" "s0_commit" "s1_get_changes"
+
+# Variant with the slot created while the transaction is already open: slot
+# creation waits for a consistent point past the open transaction, so the
+# transaction is never decoded by this slot at all (no output). This locks in
+# the behavior that decoding cannot start in the middle of a transaction.
+permutation "s0_begin" "s0_savepoint" "s0_insert" "s1_init" "s0_catinsert1" "s0_rollback" "s2_vacuum" "s0_catinsert2" "s0_commit" "s1_get_changes"
diff --git a/contrib/test_decoding/sql/tuplecid.sql b/contrib/test_decoding/sql/tuplecid.sql
new file mode 100644
index 00000000000..335fb6d1591
--- /dev/null
+++ b/contrib/test_decoding/sql/tuplecid.sql
@@ -0,0 +1,76 @@
+-- Tests for decoding of transactions in which a catalog-modifying
+-- subtransaction was rolled back (BUG #19555).
+--
+-- When a subtransaction modifies catalog tuples and is then rolled back,
+-- its dead heap-only line pointers can be marked LP_UNUSED by on-access
+-- pruning and reused by later catalog inserts of the same top-level
+-- transaction. The aborted subtransaction's xl_heap_new_cid records must
+-- not be consulted when building the historic snapshot used to decode the
+-- transaction; on unfixed builds they collide with the records of the
+-- reused line pointer and decoding dies with
+-- TRAP: failed Assert("ent->cmin == change->data.tuplecid.cmin")
+-- (or, on non-assert builds, silently uses wrong cmin/cmax mappings).
+--
+-- Whether the collision triggers depends on the physical layout of the
+-- catalog pages, so run in a fresh database where prior tests cannot have
+-- changed it, and loop enough times to leave headroom for layout
+-- differences across versions.
+CREATE DATABASE regression_tuplecid;
+-- snapshot the original database name (make and meson use different
+-- names for it) so we can switch back before dropping the test database
+\set prevdb :DBNAME
+\c regression_tuplecid
+
+-- predictability
+SET synchronous_commit = on;
+
+SELECT 'init' FROM pg_create_logical_replication_slot('regression_slot', 'test_decoding');
+
+-- Catalog churn to push the catalog pages into a state where on-access
+-- pruning frees the aborted subtransaction's line pointer and the second
+-- ALTER's catalog insert reuses it.
+CREATE TABLE tpc_filler1(f1 char(4));
+CREATE TABLE tpc_filler2(data text);
+INSERT INTO tpc_filler2 VALUES ('before-test');
+CREATE TYPE tpc_complex AS (r float8, i float8);
+CREATE TABLE tpc_filler3 (a int PRIMARY KEY, b text DEFAULT 'Unspecified');
+CREATE TABLE tpc_filler4 (id serial, t text);
+CREATE TABLE tpc_filler5(data text);
+INSERT INTO tpc_filler5 SELECT repeat('a', 2000) || g.i FROM generate_series(1, 1) g(i);
+TRUNCATE table tpc_filler5;
+CHECKPOINT;
+
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+
+-- Each iteration runs the trigger shape: catalog DDL inside a rolled-back
+-- subtransaction, then the same DDL again, then decode. Unfixed builds
+-- typically die within a handful of iterations.
+-- (temporarily hide the queries, to avoid flooding the expected output)
+\set ECHO none
+SELECT format($fmt$
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+$fmt$)
+FROM generate_series(1, 25) \gexec
+\set ECHO all
+
+DROP TABLE tpc_filler1;
+DROP TABLE tpc_filler2;
+DROP TYPE tpc_complex;
+DROP TABLE tpc_filler3;
+DROP TABLE tpc_filler4;
+DROP TABLE tpc_filler5;
+
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+
+SELECT pg_drop_replication_slot('regression_slot');
+
+\c :prevdb
+DROP DATABASE regression_tuplecid;
diff --git a/src/backend/replication/logical/decode.c b/src/backend/replication/logical/decode.c
index 4a739230264..0e7d4840a8e 100644
--- a/src/backend/replication/logical/decode.c
+++ b/src/backend/replication/logical/decode.c
@@ -892,12 +892,33 @@ DecodeAbort(LogicalDecodingContext *ctx, XLogRecordBuffer *buf,
}
else
{
+ /*
+ * Remove tuplecid changes queued by the aborted (sub)transactions
+ * from the toplevel's list, before the transactions are torn down.
+ * The abort record's primary xid tells
+ * ReorderBufferCleanupSubTxnTupleCids() whether the whole toplevel
+ * is going away, in which case scanning the list is pointless.
+ *
+ * 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.
+ */
for (i = 0; i < parsed->nsubxacts; i++)
{
+ ReorderBufferCleanupSubTxnTupleCids(ctx->reorder,
+ parsed->subxacts[i],
+ xid);
ReorderBufferAbort(ctx->reorder, parsed->subxacts[i],
buf->record->EndRecPtr, abort_time);
}
+ ReorderBufferCleanupSubTxnTupleCids(ctx->reorder, xid, xid);
ReorderBufferAbort(ctx->reorder, xid, buf->record->EndRecPtr,
abort_time);
}
diff --git a/src/backend/replication/logical/reorderbuffer.c b/src/backend/replication/logical/reorderbuffer.c
index 94112c30501..e1c6a7c4d32 100644
--- a/src/backend/replication/logical/reorderbuffer.c
+++ b/src/backend/replication/logical/reorderbuffer.c
@@ -3157,6 +3157,88 @@ ReorderBufferAbort(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn,
ReorderBufferCleanupTXN(rb, txn);
}
+/*
+ * Remove tuplecid changes queued by subtransaction xid from its toplevel
+ * transaction's list.
+ *
+ * Unlike regular changes, tuplecid changes are always queued on the toplevel
+ * transaction (see ReorderBufferAddNewTupleCids), so they would otherwise
+ * survive the abort of the subtransaction that wrote them. That's wrong:
+ * they describe catalog tuple versions created or killed by the aborted
+ * subtransaction, which never became visible, and keeping them can corrupt
+ * ReorderBufferBuildTupleCidHash() at commit time -- both when the toplevel
+ * transaction later reuses the same tid (the stale entry collides with the
+ * fresh one, breaking the cmin equality assumption) and when nothing touches
+ * the tid again (a stale cmax would make a still-live tuple look deleted on
+ * historic snapshots).
+ *
+ * The cleanup is pointless when the whole toplevel transaction is
+ * being aborted, since ReorderBufferCleanupTXN() frees the whole list
+ * anyway; the caller passes the abort record's primary xid and we skip
+ * the scan when it is xid's toplevel. Note that the opposite decision
+ * -- cleaning only when the primary xid's own association is known --
+ * would be wrong: abort records are written once the subtransaction is
+ * already in TRANS_ABORT, so they carry no toplevel xid in their
+ * header, and an outer subtransaction that never wrote WAL of its own
+ * never gets an association at all. When such an outer subtransaction
+ * rolls back, released inner subtransactions listed in its abort record
+ * do have known associations and are cleaned here.
+ *
+ * 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().
+ */
+void
+ReorderBufferCleanupSubTxnTupleCids(ReorderBuffer *rb, TransactionId xid,
+ TransactionId primary_xid)
+{
+ ReorderBufferTXN *txn;
+ ReorderBufferTXN *toptxn;
+ dlist_mutable_iter it;
+
+ txn = ReorderBufferTXNByXid(rb, xid, false, NULL, InvalidXLogRecPtr,
+ false);
+
+ /* unknown transaction, or unknown association: nothing to remove */
+ if (txn == NULL || !rbtxn_is_known_subxact(txn))
+ return;
+
+ toptxn = rbtxn_get_toptxn(txn);
+
+ /*
+ * The whole toplevel transaction is being aborted (the abort record's
+ * primary xid is xid's toplevel): ReorderBufferCleanupTXN() will free
+ * the whole list shortly, don't scan it once per aborted subxid.
+ */
+ if (toptxn->xid == primary_xid)
+ return;
+
+ dlist_foreach_modify(it, &toptxn->tuplecids)
+ {
+ ReorderBufferChange *change;
+
+ change = dlist_container(ReorderBufferChange, node, it.cur);
+
+ Assert(change->action == REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID);
+
+ if (change->data.tuplecid.subxid == xid)
+ {
+ dlist_delete(&change->node);
+ ReorderBufferFreeChange(rb, change, false);
+ toptxn->ntuplecids--;
+ }
+ }
+}
+
/*
* Abort all transactions that aren't actually running anymore because the
* server restarted.
@@ -3490,7 +3572,8 @@ void
ReorderBufferAddNewTupleCids(ReorderBuffer *rb, TransactionId xid,
XLogRecPtr lsn, RelFileLocator locator,
ItemPointerData tid, CommandId cmin,
- CommandId cmax, CommandId combocid)
+ CommandId cmax, CommandId combocid,
+ TransactionId subxid)
{
ReorderBufferChange *change = ReorderBufferAllocChange(rb);
ReorderBufferTXN *txn;
@@ -3502,6 +3585,7 @@ ReorderBufferAddNewTupleCids(ReorderBuffer *rb, TransactionId xid,
change->data.tuplecid.cmin = cmin;
change->data.tuplecid.cmax = cmax;
change->data.tuplecid.combocid = combocid;
+ change->data.tuplecid.subxid = subxid;
change->lsn = lsn;
change->txn = txn;
change->action = REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID;
diff --git a/src/backend/replication/logical/snapbuild.c b/src/backend/replication/logical/snapbuild.c
index 69caf5b02e7..451b2b89286 100644
--- a/src/backend/replication/logical/snapbuild.c
+++ b/src/backend/replication/logical/snapbuild.c
@@ -743,7 +743,7 @@ SnapBuildProcessNewCid(SnapBuild *builder, TransactionId xid,
ReorderBufferAddNewTupleCids(builder->reorder, xlrec->top_xid, lsn,
xlrec->target_locator, xlrec->target_tid,
xlrec->cmin, xlrec->cmax,
- xlrec->combocid);
+ xlrec->combocid, xid);
/* figure out new command id */
if (xlrec->cmin != InvalidCommandId &&
diff --git a/src/include/replication/reorderbuffer.h b/src/include/replication/reorderbuffer.h
index ff825e4b7b2..23c447c4953 100644
--- a/src/include/replication/reorderbuffer.h
+++ b/src/include/replication/reorderbuffer.h
@@ -146,6 +146,11 @@ typedef struct ReorderBufferChange
CommandId cmin;
CommandId cmax;
CommandId combocid;
+ TransactionId subxid; /* xid that wrote the tuplecid record;
+ * differs from the xid of the txn this
+ * change is queued on (always the
+ * toplevel xid) when a subtransaction
+ * modified the catalog */
} tuplecid;
/* Invalidation. */
@@ -738,6 +743,8 @@ extern void ReorderBufferCommitChild(ReorderBuffer *rb, TransactionId xid,
XLogRecPtr end_lsn);
extern void ReorderBufferAbort(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn,
TimestampTz abort_time);
+extern void ReorderBufferCleanupSubTxnTupleCids(ReorderBuffer *rb, TransactionId xid,
+ TransactionId primary_xid);
extern void ReorderBufferAbortOld(ReorderBuffer *rb, TransactionId oldestRunningXid);
extern void ReorderBufferForget(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn);
extern void ReorderBufferInvalidate(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn);
@@ -751,7 +758,9 @@ extern void ReorderBufferAddNewCommandId(ReorderBuffer *rb, TransactionId xid,
extern void ReorderBufferAddNewTupleCids(ReorderBuffer *rb, TransactionId xid,
XLogRecPtr lsn, RelFileLocator locator,
ItemPointerData tid,
- CommandId cmin, CommandId cmax, CommandId combocid);
+ CommandId cmin, CommandId cmax,
+ CommandId combocid,
+ TransactionId subxid);
extern void ReorderBufferAddInvalidations(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn,
Size nmsgs, SharedInvalidationMessage *msgs);
extern void ReorderBufferAddDistributedInvalidations(ReorderBuffer *rb, TransactionId xid,
--
2.47.3
v6-0002-Kuroda.patch (text/x-diff, 9.0K) download
From f98f7002d15712392d4a4a861f66e3e728023cc5 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=C3=81lvaro=20Herrera?= <alvherre@kurilemu.de>
Date: Wed, 7 Oct 2026 12:42:01 +0200
Subject: [PATCH v6 2/3] Kuroda
---
src/backend/replication/logical/decode.c | 14 +--
.../replication/logical/reorderbuffer.c | 89 ++++++++++++++-----
src/include/replication/reorderbuffer.h | 6 +-
3 files changed, 77 insertions(+), 32 deletions(-)
diff --git a/src/backend/replication/logical/decode.c b/src/backend/replication/logical/decode.c
index 0e7d4840a8e..c45edae853a 100644
--- a/src/backend/replication/logical/decode.c
+++ b/src/backend/replication/logical/decode.c
@@ -895,9 +895,9 @@ DecodeAbort(LogicalDecodingContext *ctx, XLogRecordBuffer *buf,
/*
* Remove tuplecid changes queued by the aborted (sub)transactions
* from the toplevel's list, before the transactions are torn down.
- * The abort record's primary xid tells
- * ReorderBufferCleanupSubTxnTupleCids() whether the whole toplevel
- * is going away, in which case scanning the list is pointless.
+ * The abort record's primary xid tells the cleanup function whether
+ * the whole toplevel is going away, in which case scanning the list is
+ * pointless.
*
* Note that we must not try to decide that from the primary xid's
* own association instead: an abort record is written once the
@@ -909,16 +909,16 @@ DecodeAbort(LogicalDecodingContext *ctx, XLogRecordBuffer *buf,
* all, while the released inner subtransactions it rolls back do
* have one and their tuplecids still need to be removed.
*/
+ ReorderBufferCleanupAbortedSubTxnTupleCids(ctx->reorder, xid,
+ parsed->nsubxacts,
+ parsed->subxacts);
+
for (i = 0; i < parsed->nsubxacts; i++)
{
- ReorderBufferCleanupSubTxnTupleCids(ctx->reorder,
- parsed->subxacts[i],
- xid);
ReorderBufferAbort(ctx->reorder, parsed->subxacts[i],
buf->record->EndRecPtr, abort_time);
}
- ReorderBufferCleanupSubTxnTupleCids(ctx->reorder, xid, xid);
ReorderBufferAbort(ctx->reorder, xid, buf->record->EndRecPtr,
abort_time);
}
diff --git a/src/backend/replication/logical/reorderbuffer.c b/src/backend/replication/logical/reorderbuffer.c
index e1c6a7c4d32..ccbdbde7335 100644
--- a/src/backend/replication/logical/reorderbuffer.c
+++ b/src/backend/replication/logical/reorderbuffer.c
@@ -240,6 +240,9 @@ static ReorderBufferTXN *ReorderBufferTXNByXid(ReorderBuffer *rb,
XLogRecPtr lsn, bool create_as_top);
static void ReorderBufferTransferSnapToParent(ReorderBufferTXN *txn,
ReorderBufferTXN *subtxn);
+static bool TransactionIdInSubxactArray(TransactionId xid,
+ TransactionId *subxacts,
+ int nsubxacts);
static void AssertTXNLsnOrder(ReorderBuffer *rb);
@@ -3158,8 +3161,8 @@ ReorderBufferAbort(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn,
}
/*
- * Remove tuplecid changes queued by subtransaction xid from its toplevel
- * transaction's list.
+ * Remove tuplecid changes queued by aborted subtransactions from their
+ * toplevel transaction's list.
*
* Unlike regular changes, tuplecid changes are always queued on the toplevel
* transaction (see ReorderBufferAddNewTupleCids), so they would otherwise
@@ -3174,15 +3177,10 @@ ReorderBufferAbort(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn,
*
* The cleanup is pointless when the whole toplevel transaction is
* being aborted, since ReorderBufferCleanupTXN() frees the whole list
- * anyway; the caller passes the abort record's primary xid and we skip
- * the scan when it is xid's toplevel. Note that the opposite decision
- * -- cleaning only when the primary xid's own association is known --
- * would be wrong: abort records are written once the subtransaction is
- * already in TRANS_ABORT, so they carry no toplevel xid in their
- * header, and an outer subtransaction that never wrote WAL of its own
- * never gets an association at all. When such an outer subtransaction
- * rolls back, released inner subtransactions listed in its abort record
- * do have known associations and are cleaned here.
+ * anyway. If the primary xid is unknown, search its aborted children for a known
+ * association. An outer subtransaction that never wrote WAL of its own can
+ * have no association, while released inner subtransactions listed in its
+ * abort record do have one and their tuplecids still need to be removed.
*
* If this pass does not know the association between the aborting
* subtransaction and its toplevel, there is nothing we can clean up here, and
@@ -3198,8 +3196,10 @@ ReorderBufferAbort(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn,
* transaction state without ever reaching ReorderBufferBuildTupleCidHash().
*/
void
-ReorderBufferCleanupSubTxnTupleCids(ReorderBuffer *rb, TransactionId xid,
- TransactionId primary_xid)
+ReorderBufferCleanupAbortedSubTxnTupleCids(ReorderBuffer *rb,
+ TransactionId xid,
+ int nsubxacts,
+ TransactionId *subxacts)
{
ReorderBufferTXN *txn;
ReorderBufferTXN *toptxn;
@@ -3208,19 +3208,39 @@ ReorderBufferCleanupSubTxnTupleCids(ReorderBuffer *rb, TransactionId xid,
txn = ReorderBufferTXNByXid(rb, xid, false, NULL, InvalidXLogRecPtr,
false);
- /* unknown transaction, or unknown association: nothing to remove */
- if (txn == NULL || !rbtxn_is_known_subxact(txn))
+ /*
+ * If xid is a known toplevel transaction, the whole transaction is being
+ * aborted and ReorderBufferCleanupTXN() will free the tuplecid list.
+ */
+ if (txn != NULL && !rbtxn_is_known_subxact(txn))
return;
- toptxn = rbtxn_get_toptxn(txn);
-
/*
- * The whole toplevel transaction is being aborted (the abort record's
- * primary xid is xid's toplevel): ReorderBufferCleanupTXN() will free
- * the whole list shortly, don't scan it once per aborted subxid.
+ * If the aborting subtransaction is unknown, try to find the toplevel
+ * transaction through one of its children. There may be any number of
+ * unknown children, but they cannot have queued tuplecid changes: decoding
+ * a WAL record that queues such a change first associates its xid with the
+ * toplevel transaction. Therefore, if all children are unknown, there is
+ * nothing to remove.
*/
- if (toptxn->xid == primary_xid)
- return;
+ if (txn == NULL)
+ {
+ 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;
+
+ txn = NULL;
+ }
+
+ if (txn == NULL)
+ return;
+ }
+
+ /* Get the top-level transaction to clean up its tuplecid list */
+ toptxn = rbtxn_get_toptxn(txn);
dlist_foreach_modify(it, &toptxn->tuplecids)
{
@@ -3230,15 +3250,38 @@ ReorderBufferCleanupSubTxnTupleCids(ReorderBuffer *rb, TransactionId xid,
Assert(change->action == REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID);
- if (change->data.tuplecid.subxid == xid)
+ /*
+ * Remove the entry if it's part of the aborting subtransaction or one
+ * of its children.
+ */
+ 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--;
}
}
}
+/*
+ * Check whether xid is in an array sorted in logical XID order.
+ */
+static bool
+TransactionIdInSubxactArray(TransactionId xid, TransactionId *subxacts,
+ int nsubxacts)
+{
+ /*
+ * 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.
+ */
+ return bsearch(&xid, subxacts, nsubxacts,
+ sizeof(TransactionId), xidLogicalComparator) != NULL;
+}
+
/*
* Abort all transactions that aren't actually running anymore because the
* server restarted.
diff --git a/src/include/replication/reorderbuffer.h b/src/include/replication/reorderbuffer.h
index 23c447c4953..7cfa43ad163 100644
--- a/src/include/replication/reorderbuffer.h
+++ b/src/include/replication/reorderbuffer.h
@@ -743,8 +743,10 @@ extern void ReorderBufferCommitChild(ReorderBuffer *rb, TransactionId xid,
XLogRecPtr end_lsn);
extern void ReorderBufferAbort(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn,
TimestampTz abort_time);
-extern void ReorderBufferCleanupSubTxnTupleCids(ReorderBuffer *rb, TransactionId xid,
- TransactionId primary_xid);
+extern void ReorderBufferCleanupAbortedSubTxnTupleCids(ReorderBuffer *rb,
+ TransactionId xid,
+ int nsubxacts,
+ TransactionId *subxacts);
extern void ReorderBufferAbortOld(ReorderBuffer *rb, TransactionId oldestRunningXid);
extern void ReorderBufferForget(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn);
extern void ReorderBufferInvalidate(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn);
--
2.47.3
v6-0003-pgindent.patch (text/x-diff, 3.4K) download
From 7f4f3755b2b41fbefa7b4db3e8cf099aa45d3013 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=C3=81lvaro=20Herrera?= <alvherre@kurilemu.de>
Date: Wed, 7 Oct 2026 12:42:20 +0200
Subject: [PATCH v6 3/3] pgindent
---
src/backend/replication/logical/decode.c | 22 +++++++++----------
.../replication/logical/reorderbuffer.c | 8 +++----
2 files changed, 15 insertions(+), 15 deletions(-)
diff --git a/src/backend/replication/logical/decode.c b/src/backend/replication/logical/decode.c
index c45edae853a..357bf697a90 100644
--- a/src/backend/replication/logical/decode.c
+++ b/src/backend/replication/logical/decode.c
@@ -896,18 +896,18 @@ DecodeAbort(LogicalDecodingContext *ctx, XLogRecordBuffer *buf,
* Remove tuplecid changes queued by the aborted (sub)transactions
* from the toplevel's list, before the transactions are torn down.
* The abort record's primary xid tells the cleanup function whether
- * the whole toplevel is going away, in which case scanning the list is
- * pointless.
+ * the whole toplevel is going away, in which case scanning the list
+ * is pointless.
*
- * 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.
+ * 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.
*/
ReorderBufferCleanupAbortedSubTxnTupleCids(ctx->reorder, xid,
parsed->nsubxacts,
diff --git a/src/backend/replication/logical/reorderbuffer.c b/src/backend/replication/logical/reorderbuffer.c
index ccbdbde7335..db2a7a9f7fd 100644
--- a/src/backend/replication/logical/reorderbuffer.c
+++ b/src/backend/replication/logical/reorderbuffer.c
@@ -3218,10 +3218,10 @@ ReorderBufferCleanupAbortedSubTxnTupleCids(ReorderBuffer *rb,
/*
* If the aborting subtransaction is unknown, try to find the toplevel
* transaction through one of its children. There may be any number of
- * unknown children, but they cannot have queued tuplecid changes: decoding
- * a WAL record that queues such a change first associates its xid with the
- * toplevel transaction. Therefore, if all children are unknown, there is
- * nothing to remove.
+ * unknown children, but they cannot have queued tuplecid changes:
+ * decoding a WAL record that queues such a change first associates its
+ * xid with the toplevel transaction. Therefore, if all children are
+ * unknown, there is nothing to remove.
*/
if (txn == NULL)
{
--
2.47.3
^ permalink raw reply [nested|flat] 53+ messages in thread
* Re: Bug in logical decoding with DDL and subtransactions
@ 2026-10-07 14:25 alvherre@kurilemu.de <alvherre@kurilemu.de>
parent: alvherre@kurilemu.de <alvherre@kurilemu.de>
0 siblings, 1 reply; 53+ messages in thread
From: alvherre@kurilemu.de @ 2026-10-07 14:25 UTC (permalink / raw)
To: Zhijie Hou <houzhijie22@gmail.com>; +Cc: Hayato Kuroda (Fujitsu) <kuroda.hayato@fujitsu.com>; Bingshuai Li <lucian1412@outlook.com>; Michael Paquier <michael@paquier.xyz>; Tom Lane <tgl@sss.pgh.pa.us>; Alexander Lakhin <exclusion@gmail.com>; pgsql-hackers@lists.postgresql.org <pgsql-hackers@lists.postgresql.org>; mark.dilger@enterprisedb.com <mark.dilger@enterprisedb.com>; Amit Kapila <amit.kapila16@gmail.com>; Masahiko Sawada <sawada.mshk@gmail.com>; Andrey Rachitskiy <pl0h0yp1@gmail.com>; a.kozhemyakin@postgrespro.ru <a.kozhemyakin@postgrespro.ru>
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)
^ permalink raw reply [nested|flat] 53+ messages in thread
* RE: Bug in logical decoding with DDL and subtransactions
@ 2026-10-08 09:16 Bingshuai Li <lucian1412@outlook.com>
parent: alvherre@kurilemu.de <alvherre@kurilemu.de>
0 siblings, 2 replies; 53+ messages in thread
From: Bingshuai Li @ 2026-10-08 09:16 UTC (permalink / raw)
To: alvherre@kurilemu.de <alvherre@kurilemu.de>; Zhijie Hou <houzhijie22@gmail.com>; +Cc: Hayato Kuroda (Fujitsu) <kuroda.hayato@fujitsu.com>; Michael Paquier <michael@paquier.xyz>; Tom Lane <tgl@sss.pgh.pa.us>; Alexander Lakhin <exclusion@gmail.com>; pgsql-hackers@lists.postgresql.org <pgsql-hackers@lists.postgresql.org>; mark.dilger@enterprisedb.com <mark.dilger@enterprisedb.com>; Amit Kapila <amit.kapila16@gmail.com>; Masahiko Sawada <sawada.mshk@gmail.com>; Andrey Rachitskiy <pl0h0yp1@gmail.com>; a.kozhemyakin@postgrespro.ru <a.kozhemyakin@postgrespro.ru>
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
^ permalink raw reply [nested|flat] 53+ messages in thread
* RE: Bug in logical decoding with DDL and subtransactions
@ 2026-10-09 03:13 Hayato Kuroda (Fujitsu) <kuroda.hayato@fujitsu.com>
parent: Bingshuai Li <lucian1412@outlook.com>
1 sibling, 2 replies; 53+ messages in thread
From: Hayato Kuroda (Fujitsu) @ 2026-10-09 03:13 UTC (permalink / raw)
To: Bingshuai Li <lucian1412@outlook.com>; alvherre@kurilemu.de <alvherre@kurilemu.de>; Zhijie Hou <houzhijie22@gmail.com>; +Cc: Michael Paquier <michael@paquier.xyz>; Tom Lane <tgl@sss.pgh.pa.us>; Alexander Lakhin <exclusion@gmail.com>; pgsql-hackers@lists.postgresql.org <pgsql-hackers@lists.postgresql.org>; mark.dilger@enterprisedb.com <mark.dilger@enterprisedb.com>; Amit Kapila <amit.kapila16@gmail.com>; Masahiko Sawada <sawada.mshk@gmail.com>; Andrey Rachitskiy <pl0h0yp1@gmail.com>; a.kozhemyakin@postgrespro.ru <a.kozhemyakin@postgrespro.ru>
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
^ permalink raw reply [nested|flat] 53+ messages in thread
* RE: Bug in logical decoding with DDL and subtransactions
@ 2026-10-09 09:18 Bingshuai Li <lucian1412@outlook.com>
parent: Hayato Kuroda (Fujitsu) <kuroda.hayato@fujitsu.com>
1 sibling, 0 replies; 53+ messages in thread
From: Bingshuai Li @ 2026-10-09 09:18 UTC (permalink / raw)
To: Hayato Kuroda (Fujitsu) <kuroda.hayato@fujitsu.com>; alvherre@kurilemu.de <alvherre@kurilemu.de>; Zhijie Hou <houzhijie22@gmail.com>; +Cc: Michael Paquier <michael@paquier.xyz>; Tom Lane <tgl@sss.pgh.pa.us>; Alexander Lakhin <exclusion@gmail.com>; pgsql-hackers@lists.postgresql.org <pgsql-hackers@lists.postgresql.org>; mark.dilger@enterprisedb.com <mark.dilger@enterprisedb.com>; Amit Kapila <amit.kapila16@gmail.com>; Masahiko Sawada <sawada.mshk@gmail.com>; Andrey Rachitskiy <pl0h0yp1@gmail.com>; a.kozhemyakin@postgrespro.ru <a.kozhemyakin@postgrespro.ru>
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 <stdlib.h> 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
^ permalink raw reply [nested|flat] 53+ messages in thread
* Re: Bug in logical decoding with DDL and subtransactions
@ 2026-10-09 15:28 Zhijie Hou <houzhijie22@gmail.com>
parent: Bingshuai Li <lucian1412@outlook.com>
1 sibling, 2 replies; 53+ messages in thread
From: Zhijie Hou @ 2026-10-09 15:28 UTC (permalink / raw)
To: Bingshuai Li <lucian1412@outlook.com>; +Cc: alvherre@kurilemu.de <alvherre@kurilemu.de>; Hayato Kuroda (Fujitsu) <kuroda.hayato@fujitsu.com>; Michael Paquier <michael@paquier.xyz>; Tom Lane <tgl@sss.pgh.pa.us>; Alexander Lakhin <exclusion@gmail.com>; pgsql-hackers@lists.postgresql.org <pgsql-hackers@lists.postgresql.org>; mark.dilger@enterprisedb.com <mark.dilger@enterprisedb.com>; Amit Kapila <amit.kapila16@gmail.com>; Masahiko Sawada <sawada.mshk@gmail.com>; Andrey Rachitskiy <pl0h0yp1@gmail.com>; a.kozhemyakin@postgrespro.ru <a.kozhemyakin@postgrespro.ru>
Hi,
On Thu, Oct 8, 2026 at 5:16 PM Bingshuai Li <lucian1412@outlook.com> 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
Attachments: download all (3 files, .tar.gz)
v7-0001-Fix-stale-tuplecid-records-left-behind-by-aborted.patch (application/octet-stream, 27.3K) download
From c70d013f05215ede5b44dd9400849e640b169ea3 Mon Sep 17 00:00:00 2001
From: Bingshuai Li <lucian1412@outlook.com>
Date: Wed, 30 Sep 2026 11:52:16 +0800
Subject: [PATCH v7 1/3] Fix stale tuplecid records left behind by aborted
subtransactions
Tuplecid changes are always queued on the toplevel transaction, so
unlike regular changes they are not dropped when the subtransaction
that wrote them aborts. The stale mappings corrupt
ReorderBufferBuildTupleCidHash() at commit time: if a later catalog
insert reuses the aborted subtransaction's line pointer (made
LP_UNUSED by on-access pruning or by vacuum), the fresh record
collides with the stale one with a different cmin, tripping the cmin
equality assertion; where nothing reuses the tid, a stale cmax makes
a still-live catalog tuple look deleted on historic snapshots. On
non-assert builds there is no crash, but the stale mappings risk
misjudging historic catalog visibility, which could produce
incorrect decoding output.
Remove the aborted subtransaction's tuplecid entries when its abort
is decoded. The cleanup is not needed when the whole toplevel
transaction is being aborted, because ReorderBufferCleanupTXN()
frees the whole list anyway; to avoid scanning the list once per
aborted subxid in that case, DecodeAbort() passes the abort record's
primary xid to the new ReorderBufferCleanupSubTxnTupleCids(), which
skips the scan when that xid is the toplevel of the xid being
cleaned.
The decision cannot be based on whether the primary xid's own
association with its toplevel is known: abort records are written
after the subtransaction has entered TRANS_ABORT, so they never
carry the toplevel xid in their header, and an outer subtransaction
that never wrote WAL of its own -- for example a savepoint that only
wraps other savepoints -- can never get its association established
at all. When such an outer subtransaction is rolled back, the
released inner subtransactions listed in its abort record do have
known associations, and their tuplecids must be removed from the
surviving toplevel's list. The existing tuplecid and tuplecid_restart
tests only cover aborts of subtransactions that wrote WAL themselves,
which is why this shape needs its own test.
Skipping the cleanup when the association of the xid being cleaned
is unknown is safe because of how a slot's restart point advances:
SnapBuildProcessRunningXacts() cannot move the restart point past
the oldest in-progress transaction, so any pass that output-decodes
the toplevel commit must have replayed the subtransaction's first
record and therefore knows 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 via
SnapBuildXactNeedsSkip(), so any stale tuplecid entries left behind
are dropped along with the transaction state and never reach
ReorderBufferBuildTupleCidHash().
Add an isolation test for the nested shape: the toplevel writes WAL
first, an inner subtransaction modifies a user catalog table and is
released, and the outer subtransaction -- which produces no WAL of
its own -- is then rolled back; with the page-fill and vacuum recipe
of tuplecid_restart, the toplevel's later insert deterministically
reuses the aborted subtransaction's line pointer. On unfixed assert
builds the final get_changes dies with the original cmin assertion
in ReorderBufferBuildTupleCidHash(); with the fix it passes. The
existing tests keep covering the simple savepoint and the restart
shapes.
Bug: #19555
Reported-by: Alexander Kozhemyakin <a.kozhemyakin@postgrespro.ru>
Based-on-patch-by: Mark Dilger
Discussion: https://postgr.es/m/CAHgHdKu5e3XY5e90Tuaxq_R4WrKxSV734Q%2BLwo5y39Omp2A-Gg@mail.gmail.com
---
contrib/test_decoding/Makefile | 3 +-
.../expected/tuplecid_nested.out | 32 +++++++
.../expected/tuplecid_restart.out | 68 +++++++++++++++
contrib/test_decoding/meson.build | 2 +
.../test_decoding/specs/tuplecid_nested.spec | 77 +++++++++++++++++
.../test_decoding/specs/tuplecid_restart.spec | 75 ++++++++++++++++
src/backend/replication/logical/decode.c | 21 +++++
.../replication/logical/reorderbuffer.c | 86 ++++++++++++++++++-
src/backend/replication/logical/snapbuild.c | 2 +-
src/include/replication/reorderbuffer.h | 11 ++-
10 files changed, 373 insertions(+), 4 deletions(-)
create mode 100644 contrib/test_decoding/expected/tuplecid_nested.out
create mode 100644 contrib/test_decoding/expected/tuplecid_restart.out
create mode 100644 contrib/test_decoding/specs/tuplecid_nested.spec
create mode 100644 contrib/test_decoding/specs/tuplecid_restart.spec
diff --git a/contrib/test_decoding/Makefile b/contrib/test_decoding/Makefile
index a7f7b7ae789..a33e6295d8c 100644
--- a/contrib/test_decoding/Makefile
+++ b/contrib/test_decoding/Makefile
@@ -15,7 +15,8 @@ SLOT_CREATION_TST = $(if $(filter win32,$(PORTNAME)),,slot_creation_error)
ISOLATION = mxact delayed_startup ondisk_startup concurrent_ddl_dml \
oldest_xmin snapshot_transfer subxact_without_top concurrent_stream \
twophase_snapshot $(SLOT_CREATION_TST) catalog_change_snapshot \
- skip_snapshot_restore invalidation_distribution parallel_session_origin
+ skip_snapshot_restore invalidation_distribution parallel_session_origin \
+ tuplecid_restart tuplecid_nested
REGRESS_OPTS = --temp-config $(top_srcdir)/contrib/test_decoding/logical.conf
ISOLATION_OPTS = --temp-config $(top_srcdir)/contrib/test_decoding/logical.conf
diff --git a/contrib/test_decoding/expected/tuplecid_nested.out b/contrib/test_decoding/expected/tuplecid_nested.out
new file mode 100644
index 00000000000..5d816374fbc
--- /dev/null
+++ b/contrib/test_decoding/expected/tuplecid_nested.out
@@ -0,0 +1,32 @@
+Parsed test spec with 3 sessions
+
+starting permutation: s1_init s0_begin s0_topwrite s0_outer s0_inner s0_catinsert1 s0_release_inner s0_rollback_outer s2_vacuum s0_catinsert2 s0_commit s1_get_changes
+step s1_init: SELECT 'init' FROM pg_create_logical_replication_slot('tuplecid_nested_slot', 'test_decoding');
+?column?
+--------
+init
+(1 row)
+
+step s0_begin: BEGIN;
+step s0_topwrite: INSERT INTO tbl1 VALUES (0);
+step s0_outer: SAVEPOINT outer_sp;
+step s0_inner: SAVEPOINT inner_sp;
+step s0_catinsert1: INSERT INTO user_cat VALUES (5, 'e');
+step s0_release_inner: RELEASE SAVEPOINT inner_sp;
+step s0_rollback_outer: ROLLBACK TO SAVEPOINT outer_sp;
+step s2_vacuum: VACUUM user_cat;
+step s0_catinsert2: INSERT INTO user_cat VALUES (6, 'f');
+step s0_commit: COMMIT;
+step s1_get_changes: SELECT data FROM pg_logical_slot_get_changes('tuplecid_nested_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%';
+data
+------------------------------------------
+BEGIN
+table public.tbl1: INSERT: val1[integer]:0
+COMMIT
+(3 rows)
+
+?column?
+--------
+stop
+(1 row)
+
diff --git a/contrib/test_decoding/expected/tuplecid_restart.out b/contrib/test_decoding/expected/tuplecid_restart.out
new file mode 100644
index 00000000000..e5b4bc2543d
--- /dev/null
+++ b/contrib/test_decoding/expected/tuplecid_restart.out
@@ -0,0 +1,68 @@
+Parsed test spec with 3 sessions
+
+starting permutation: s0_init s0_begin s0_savepoint s0_insert s1_checkpoint s1_get_changes s0_catinsert1 s0_rollback s2_vacuum s0_catinsert2 s1_checkpoint s1_get_changes s0_commit s1_get_changes
+step s0_init: SELECT 'init' FROM pg_create_logical_replication_slot('isolation_slot', 'test_decoding');
+?column?
+--------
+init
+(1 row)
+
+step s0_begin: BEGIN;
+step s0_savepoint: SAVEPOINT sp1;
+step s0_insert: INSERT INTO tbl1 VALUES (1);
+step s1_checkpoint: CHECKPOINT;
+step s1_get_changes: SELECT data FROM pg_logical_slot_get_changes('isolation_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%';
+data
+----
+(0 rows)
+
+step s0_catinsert1: INSERT INTO user_cat VALUES (5, 'e');
+step s0_rollback: ROLLBACK TO SAVEPOINT sp1;
+step s2_vacuum: VACUUM user_cat;
+step s0_catinsert2: INSERT INTO user_cat VALUES (6, 'f');
+step s1_checkpoint: CHECKPOINT;
+step s1_get_changes: SELECT data FROM pg_logical_slot_get_changes('isolation_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%';
+data
+----
+(0 rows)
+
+step s0_commit: COMMIT;
+step s1_get_changes: SELECT data FROM pg_logical_slot_get_changes('isolation_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%';
+data
+------
+BEGIN
+COMMIT
+(2 rows)
+
+?column?
+--------
+stop
+(1 row)
+
+
+starting permutation: s0_begin s0_savepoint s0_insert s1_init s0_catinsert1 s0_rollback s2_vacuum s0_catinsert2 s0_commit s1_get_changes
+step s0_begin: BEGIN;
+step s0_savepoint: SAVEPOINT sp1;
+step s0_insert: INSERT INTO tbl1 VALUES (1);
+step s1_init: SELECT 'init' FROM pg_create_logical_replication_slot('isolation_slot', 'test_decoding'); <waiting ...>
+step s0_catinsert1: INSERT INTO user_cat VALUES (5, 'e');
+step s0_rollback: ROLLBACK TO SAVEPOINT sp1;
+step s2_vacuum: VACUUM user_cat;
+step s0_catinsert2: INSERT INTO user_cat VALUES (6, 'f');
+step s0_commit: COMMIT;
+step s1_init: <... completed>
+?column?
+--------
+init
+(1 row)
+
+step s1_get_changes: SELECT data FROM pg_logical_slot_get_changes('isolation_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%';
+data
+----
+(0 rows)
+
+?column?
+--------
+stop
+(1 row)
+
diff --git a/contrib/test_decoding/meson.build b/contrib/test_decoding/meson.build
index dbc0ef0f63e..667ea76518f 100644
--- a/contrib/test_decoding/meson.build
+++ b/contrib/test_decoding/meson.build
@@ -30,6 +30,8 @@ test_decoding_isolation = [
'skip_snapshot_restore',
'invalidation_distribution',
'parallel_session_origin',
+ 'tuplecid_nested',
+ 'tuplecid_restart',
]
# slot_creation_error terminates another backend, whose FATAL message can be
diff --git a/contrib/test_decoding/specs/tuplecid_nested.spec b/contrib/test_decoding/specs/tuplecid_nested.spec
new file mode 100644
index 00000000000..52c80eb55eb
--- /dev/null
+++ b/contrib/test_decoding/specs/tuplecid_nested.spec
@@ -0,0 +1,77 @@
+# Test decoding of a partially rolled back transaction where the aborted part
+# is nested: the aborting outer subtransaction never produced any WAL of its
+# own, so decoding cannot know its toplevel transaction, while an inner
+# subtransaction it rolls back did produce WAL and its tuplecid records still
+# have to be removed (BUG #19555 nested shape).
+#
+# The tuplecid records written by the aborted inner subtransaction are queued
+# on the toplevel transaction and must be removed when the outer
+# subtransaction's abort is decoded; otherwise they collide with the records
+# of the line pointer that gets reused by the toplevel transaction's later
+# catalog insert, failing Assert(ent->cmin == change->data.tuplecid.cmin) in
+# ReorderBufferBuildTupleCidHash() when the commit is decoded.
+#
+# - s0_topwrite makes the toplevel transaction produce its first WAL record
+# before any subtransaction exists.
+# - s0_outer establishes the outer savepoint, which never gets a WAL record
+# of its own.
+# - s0_catinsert1 generates an xl_heap_new_cid record in the inner
+# subtransaction, which is then released.
+# - s0_rollback_outer rolls the outer savepoint back. Its abort record is
+# written once the backend is already in TRANS_ABORT, so it carries no
+# toplevel xid in its header and the outer subtransaction's association
+# with the toplevel can never be established. The released inner
+# subtransaction is listed in the same abort record, though, and its
+# tuplecid records still must be removed from the toplevel's list.
+# - s2_vacuum reclaims the aborted row's line pointer (dead inserts are
+# removed regardless of the xid horizon, so this is deterministic even
+# while the toplevel transaction is still open); s0_catinsert2 then reuses
+# the same tid with a different cmin.
+# - s1_get_changes then decodes the toplevel commit and builds the tuplecid
+# hash; on unfixed builds the stale tuplecid of the aborted inner
+# subtransaction collides there with the fresh one.
+setup
+{
+ DROP TABLE IF EXISTS tbl1;
+ DROP TABLE IF EXISTS user_cat;
+ CREATE TABLE tbl1 (val1 integer);
+ -- Four rows of ~1.5kB fill the first heap page to within a few hundred
+ -- bytes, so that vacuuming away the aborted fifth row leaves exactly one
+ -- line pointer for the next insert to reuse.
+ CREATE TABLE user_cat (c1 int, filler char(1500)) WITH (user_catalog_table = true);
+ INSERT INTO user_cat VALUES (1, 'a'), (2, 'b'), (3, 'c'), (4, 'd');
+}
+
+teardown
+{
+ DROP TABLE tbl1;
+ DROP TABLE user_cat;
+ SELECT 'stop' FROM pg_drop_replication_slot('tuplecid_nested_slot');
+}
+
+session "s0"
+setup { SET synchronous_commit=on; }
+step "s0_begin" { BEGIN; }
+step "s0_topwrite" { INSERT INTO tbl1 VALUES (0); }
+step "s0_outer" { SAVEPOINT outer_sp; }
+step "s0_inner" { SAVEPOINT inner_sp; }
+step "s0_catinsert1" { INSERT INTO user_cat VALUES (5, 'e'); }
+step "s0_release_inner" { RELEASE SAVEPOINT inner_sp; }
+step "s0_rollback_outer" { ROLLBACK TO SAVEPOINT outer_sp; }
+step "s0_catinsert2" { INSERT INTO user_cat VALUES (6, 'f'); }
+step "s0_commit" { COMMIT; }
+
+session "s1"
+setup { SET synchronous_commit=on; }
+step "s1_init" { SELECT 'init' FROM pg_create_logical_replication_slot('tuplecid_nested_slot', 'test_decoding'); }
+# The user_cat rows carry ~1.5kB filler values which would flood the expected
+# output; filter them out (decoding still processes them server-side).
+step "s1_get_changes" { SELECT data FROM pg_logical_slot_get_changes('tuplecid_nested_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%'; }
+
+session "s2"
+setup { SET synchronous_commit=on; }
+step "s2_vacuum" { VACUUM user_cat; }
+
+# The slot is created before the transaction begins, so the final
+# s1_get_changes decodes the whole transaction through its commit.
+permutation "s1_init" "s0_begin" "s0_topwrite" "s0_outer" "s0_inner" "s0_catinsert1" "s0_release_inner" "s0_rollback_outer" "s2_vacuum" "s0_catinsert2" "s0_commit" "s1_get_changes"
diff --git a/contrib/test_decoding/specs/tuplecid_restart.spec b/contrib/test_decoding/specs/tuplecid_restart.spec
new file mode 100644
index 00000000000..58da414e8b7
--- /dev/null
+++ b/contrib/test_decoding/specs/tuplecid_restart.spec
@@ -0,0 +1,75 @@
+# Test decoding of a transaction in which a catalog-modifying subtransaction
+# was rolled back, where the transaction spans a logical decoding restart
+# point (BUG #19555 restart shape).
+#
+# The tuplecid records written by the aborted subtransaction are queued on the
+# toplevel transaction and must be removed when the subtransaction's abort is
+# decoded; otherwise they collide with the records of the line pointer that
+# gets reused by the toplevel transaction's later catalog insert, failing
+# Assert(ent->cmin == change->data.tuplecid.cmin) in
+# ReorderBufferBuildTupleCidHash() when the commit is decoded.
+#
+# - s0_insert runs in a subtransaction and produces its first WAL record.
+# - s0_catinsert1 generates an xl_heap_new_cid record in that subtransaction.
+# - s0_rollback aborts the subtransaction.
+# - s2_vacuum reclaims the aborted row's line pointer (dead inserts are
+# removed regardless of the xid horizon, so this is deterministic even
+# while the toplevel transaction is still open); s0_catinsert2 then reuses
+# the same tid with a different cmin.
+# - The transaction stays open across both checkpoints, so the final
+# s1_get_changes replays the transaction's records from the first
+# checkpoint and decodes its commit for output, building the tuplecid
+# hash. On unfixed builds the stale tuplecid of the aborted
+# subtransaction collides there with the fresh one.
+setup
+{
+ DROP TABLE IF EXISTS tbl1;
+ DROP TABLE IF EXISTS user_cat;
+ CREATE TABLE tbl1 (val1 integer);
+ -- Four rows of ~1.5kB fill the first heap page to within a few hundred
+ -- bytes, so that vacuuming away the aborted fifth row leaves exactly one
+ -- line pointer for the next insert to reuse.
+ CREATE TABLE user_cat (c1 int, filler char(1500)) WITH (user_catalog_table = true);
+ INSERT INTO user_cat VALUES (1, 'a'), (2, 'b'), (3, 'c'), (4, 'd');
+}
+
+teardown
+{
+ DROP TABLE tbl1;
+ DROP TABLE user_cat;
+ SELECT 'stop' FROM pg_drop_replication_slot('isolation_slot');
+}
+
+session "s0"
+setup { SET synchronous_commit=on; }
+step "s0_init" { SELECT 'init' FROM pg_create_logical_replication_slot('isolation_slot', 'test_decoding'); }
+step "s0_begin" { BEGIN; }
+step "s0_savepoint" { SAVEPOINT sp1; }
+step "s0_insert" { INSERT INTO tbl1 VALUES (1); }
+step "s0_catinsert1" { INSERT INTO user_cat VALUES (5, 'e'); }
+step "s0_rollback" { ROLLBACK TO SAVEPOINT sp1; }
+step "s0_catinsert2" { INSERT INTO user_cat VALUES (6, 'f'); }
+step "s0_commit" { COMMIT; }
+
+session "s1"
+setup { SET synchronous_commit=on; }
+step "s1_init" { SELECT 'init' FROM pg_create_logical_replication_slot('isolation_slot', 'test_decoding'); }
+step "s1_checkpoint" { CHECKPOINT; }
+# The user_cat rows carry ~1.5kB filler values which would flood the expected
+# output; filter them out (decoding still processes them server-side).
+step "s1_get_changes" { SELECT data FROM pg_logical_slot_get_changes('isolation_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%'; }
+
+session "s2"
+setup { SET synchronous_commit=on; }
+step "s2_vacuum" { VACUUM user_cat; }
+
+# The transaction commits only after the second s1_get_changes, so the last
+# s1_get_changes both replays the transaction from the first checkpoint and
+# decodes its commit for output.
+permutation "s0_init" "s0_begin" "s0_savepoint" "s0_insert" "s1_checkpoint" "s1_get_changes" "s0_catinsert1" "s0_rollback" "s2_vacuum" "s0_catinsert2" "s1_checkpoint" "s1_get_changes" "s0_commit" "s1_get_changes"
+
+# Variant with the slot created while the transaction is already open: slot
+# creation waits for a consistent point past the open transaction, so the
+# transaction is never decoded by this slot at all (no output). This locks in
+# the behavior that decoding cannot start in the middle of a transaction.
+permutation "s0_begin" "s0_savepoint" "s0_insert" "s1_init" "s0_catinsert1" "s0_rollback" "s2_vacuum" "s0_catinsert2" "s0_commit" "s1_get_changes"
diff --git a/src/backend/replication/logical/decode.c b/src/backend/replication/logical/decode.c
index 4a739230264..0e7d4840a8e 100644
--- a/src/backend/replication/logical/decode.c
+++ b/src/backend/replication/logical/decode.c
@@ -892,12 +892,33 @@ DecodeAbort(LogicalDecodingContext *ctx, XLogRecordBuffer *buf,
}
else
{
+ /*
+ * Remove tuplecid changes queued by the aborted (sub)transactions
+ * from the toplevel's list, before the transactions are torn down.
+ * The abort record's primary xid tells
+ * ReorderBufferCleanupSubTxnTupleCids() whether the whole toplevel
+ * is going away, in which case scanning the list is pointless.
+ *
+ * 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.
+ */
for (i = 0; i < parsed->nsubxacts; i++)
{
+ ReorderBufferCleanupSubTxnTupleCids(ctx->reorder,
+ parsed->subxacts[i],
+ xid);
ReorderBufferAbort(ctx->reorder, parsed->subxacts[i],
buf->record->EndRecPtr, abort_time);
}
+ ReorderBufferCleanupSubTxnTupleCids(ctx->reorder, xid, xid);
ReorderBufferAbort(ctx->reorder, xid, buf->record->EndRecPtr,
abort_time);
}
diff --git a/src/backend/replication/logical/reorderbuffer.c b/src/backend/replication/logical/reorderbuffer.c
index 94112c30501..e1c6a7c4d32 100644
--- a/src/backend/replication/logical/reorderbuffer.c
+++ b/src/backend/replication/logical/reorderbuffer.c
@@ -3157,6 +3157,88 @@ ReorderBufferAbort(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn,
ReorderBufferCleanupTXN(rb, txn);
}
+/*
+ * Remove tuplecid changes queued by subtransaction xid from its toplevel
+ * transaction's list.
+ *
+ * Unlike regular changes, tuplecid changes are always queued on the toplevel
+ * transaction (see ReorderBufferAddNewTupleCids), so they would otherwise
+ * survive the abort of the subtransaction that wrote them. That's wrong:
+ * they describe catalog tuple versions created or killed by the aborted
+ * subtransaction, which never became visible, and keeping them can corrupt
+ * ReorderBufferBuildTupleCidHash() at commit time -- both when the toplevel
+ * transaction later reuses the same tid (the stale entry collides with the
+ * fresh one, breaking the cmin equality assumption) and when nothing touches
+ * the tid again (a stale cmax would make a still-live tuple look deleted on
+ * historic snapshots).
+ *
+ * The cleanup is pointless when the whole toplevel transaction is
+ * being aborted, since ReorderBufferCleanupTXN() frees the whole list
+ * anyway; the caller passes the abort record's primary xid and we skip
+ * the scan when it is xid's toplevel. Note that the opposite decision
+ * -- cleaning only when the primary xid's own association is known --
+ * would be wrong: abort records are written once the subtransaction is
+ * already in TRANS_ABORT, so they carry no toplevel xid in their
+ * header, and an outer subtransaction that never wrote WAL of its own
+ * never gets an association at all. When such an outer subtransaction
+ * rolls back, released inner subtransactions listed in its abort record
+ * do have known associations and are cleaned here.
+ *
+ * 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().
+ */
+void
+ReorderBufferCleanupSubTxnTupleCids(ReorderBuffer *rb, TransactionId xid,
+ TransactionId primary_xid)
+{
+ ReorderBufferTXN *txn;
+ ReorderBufferTXN *toptxn;
+ dlist_mutable_iter it;
+
+ txn = ReorderBufferTXNByXid(rb, xid, false, NULL, InvalidXLogRecPtr,
+ false);
+
+ /* unknown transaction, or unknown association: nothing to remove */
+ if (txn == NULL || !rbtxn_is_known_subxact(txn))
+ return;
+
+ toptxn = rbtxn_get_toptxn(txn);
+
+ /*
+ * The whole toplevel transaction is being aborted (the abort record's
+ * primary xid is xid's toplevel): ReorderBufferCleanupTXN() will free
+ * the whole list shortly, don't scan it once per aborted subxid.
+ */
+ if (toptxn->xid == primary_xid)
+ return;
+
+ dlist_foreach_modify(it, &toptxn->tuplecids)
+ {
+ ReorderBufferChange *change;
+
+ change = dlist_container(ReorderBufferChange, node, it.cur);
+
+ Assert(change->action == REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID);
+
+ if (change->data.tuplecid.subxid == xid)
+ {
+ dlist_delete(&change->node);
+ ReorderBufferFreeChange(rb, change, false);
+ toptxn->ntuplecids--;
+ }
+ }
+}
+
/*
* Abort all transactions that aren't actually running anymore because the
* server restarted.
@@ -3490,7 +3572,8 @@ void
ReorderBufferAddNewTupleCids(ReorderBuffer *rb, TransactionId xid,
XLogRecPtr lsn, RelFileLocator locator,
ItemPointerData tid, CommandId cmin,
- CommandId cmax, CommandId combocid)
+ CommandId cmax, CommandId combocid,
+ TransactionId subxid)
{
ReorderBufferChange *change = ReorderBufferAllocChange(rb);
ReorderBufferTXN *txn;
@@ -3502,6 +3585,7 @@ ReorderBufferAddNewTupleCids(ReorderBuffer *rb, TransactionId xid,
change->data.tuplecid.cmin = cmin;
change->data.tuplecid.cmax = cmax;
change->data.tuplecid.combocid = combocid;
+ change->data.tuplecid.subxid = subxid;
change->lsn = lsn;
change->txn = txn;
change->action = REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID;
diff --git a/src/backend/replication/logical/snapbuild.c b/src/backend/replication/logical/snapbuild.c
index 69caf5b02e7..451b2b89286 100644
--- a/src/backend/replication/logical/snapbuild.c
+++ b/src/backend/replication/logical/snapbuild.c
@@ -743,7 +743,7 @@ SnapBuildProcessNewCid(SnapBuild *builder, TransactionId xid,
ReorderBufferAddNewTupleCids(builder->reorder, xlrec->top_xid, lsn,
xlrec->target_locator, xlrec->target_tid,
xlrec->cmin, xlrec->cmax,
- xlrec->combocid);
+ xlrec->combocid, xid);
/* figure out new command id */
if (xlrec->cmin != InvalidCommandId &&
diff --git a/src/include/replication/reorderbuffer.h b/src/include/replication/reorderbuffer.h
index ff825e4b7b2..23c447c4953 100644
--- a/src/include/replication/reorderbuffer.h
+++ b/src/include/replication/reorderbuffer.h
@@ -146,6 +146,11 @@ typedef struct ReorderBufferChange
CommandId cmin;
CommandId cmax;
CommandId combocid;
+ TransactionId subxid; /* xid that wrote the tuplecid record;
+ * differs from the xid of the txn this
+ * change is queued on (always the
+ * toplevel xid) when a subtransaction
+ * modified the catalog */
} tuplecid;
/* Invalidation. */
@@ -738,6 +743,8 @@ extern void ReorderBufferCommitChild(ReorderBuffer *rb, TransactionId xid,
XLogRecPtr end_lsn);
extern void ReorderBufferAbort(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn,
TimestampTz abort_time);
+extern void ReorderBufferCleanupSubTxnTupleCids(ReorderBuffer *rb, TransactionId xid,
+ TransactionId primary_xid);
extern void ReorderBufferAbortOld(ReorderBuffer *rb, TransactionId oldestRunningXid);
extern void ReorderBufferForget(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn);
extern void ReorderBufferInvalidate(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn);
@@ -751,7 +758,9 @@ extern void ReorderBufferAddNewCommandId(ReorderBuffer *rb, TransactionId xid,
extern void ReorderBufferAddNewTupleCids(ReorderBuffer *rb, TransactionId xid,
XLogRecPtr lsn, RelFileLocator locator,
ItemPointerData tid,
- CommandId cmin, CommandId cmax, CommandId combocid);
+ CommandId cmin, CommandId cmax,
+ CommandId combocid,
+ TransactionId subxid);
extern void ReorderBufferAddInvalidations(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn,
Size nmsgs, SharedInvalidationMessage *msgs);
extern void ReorderBufferAddDistributedInvalidations(ReorderBuffer *rb, TransactionId xid,
--
2.34.1
v7-0003-Extra-tests-to-be-removed-on-committing.patch (application/octet-stream, 9.5K) download
From 7cf7b19f3aa49021ac7e6ddddc19c4edf06f637f Mon Sep 17 00:00:00 2001
From: Hou Zhijie <sherlockcpp@foxmail.com>
Date: Fri, 9 Oct 2026 23:12:19 +0800
Subject: [PATCH v7 3/3] Extra tests to be removed on committing
---
contrib/test_decoding/Makefile | 2 +-
contrib/test_decoding/expected/tuplecid.out | 199 ++++++++++++++++++++
contrib/test_decoding/meson.build | 1 +
contrib/test_decoding/sql/tuplecid.sql | 76 ++++++++
4 files changed, 277 insertions(+), 1 deletion(-)
create mode 100644 contrib/test_decoding/expected/tuplecid.out
create mode 100644 contrib/test_decoding/sql/tuplecid.sql
diff --git a/contrib/test_decoding/Makefile b/contrib/test_decoding/Makefile
index a33e6295d8c..d84bf3603dd 100644
--- a/contrib/test_decoding/Makefile
+++ b/contrib/test_decoding/Makefile
@@ -5,7 +5,7 @@ PGFILEDESC = "test_decoding - example of a logical decoding output plugin"
REGRESS = ddl xact rewrite toast permissions decoding_in_xact \
decoding_into_rel binary prepared replorigin time messages \
- repack spill slot truncate stream stats twophase twophase_stream
+ repack spill slot truncate stream stats tuplecid twophase twophase_stream
# slot_creation_error terminates another backend, whose FATAL message can be
# lost on Windows, making the test unstable there.
diff --git a/contrib/test_decoding/expected/tuplecid.out b/contrib/test_decoding/expected/tuplecid.out
new file mode 100644
index 00000000000..1db2df1bad9
--- /dev/null
+++ b/contrib/test_decoding/expected/tuplecid.out
@@ -0,0 +1,199 @@
+-- Tests for decoding of transactions in which a catalog-modifying
+-- subtransaction was rolled back (BUG #19555).
+--
+-- When a subtransaction modifies catalog tuples and is then rolled back,
+-- its dead heap-only line pointers can be marked LP_UNUSED by on-access
+-- pruning and reused by later catalog inserts of the same top-level
+-- transaction. The aborted subtransaction's xl_heap_new_cid records must
+-- not be consulted when building the historic snapshot used to decode the
+-- transaction; on unfixed builds they collide with the records of the
+-- reused line pointer and decoding dies with
+-- TRAP: failed Assert("ent->cmin == change->data.tuplecid.cmin")
+-- (or, on non-assert builds, silently uses wrong cmin/cmax mappings).
+--
+-- Whether the collision triggers depends on the physical layout of the
+-- catalog pages, so run in a fresh database where prior tests cannot have
+-- changed it, and loop enough times to leave headroom for layout
+-- differences across versions.
+CREATE DATABASE regression_tuplecid;
+-- snapshot the original database name (make and meson use different
+-- names for it) so we can switch back before dropping the test database
+\set prevdb :DBNAME
+\c regression_tuplecid
+-- predictability
+SET synchronous_commit = on;
+SELECT 'init' FROM pg_create_logical_replication_slot('regression_slot', 'test_decoding');
+ ?column?
+----------
+ init
+(1 row)
+
+-- Catalog churn to push the catalog pages into a state where on-access
+-- pruning frees the aborted subtransaction's line pointer and the second
+-- ALTER's catalog insert reuses it.
+CREATE TABLE tpc_filler1(f1 char(4));
+CREATE TABLE tpc_filler2(data text);
+INSERT INTO tpc_filler2 VALUES ('before-test');
+CREATE TYPE tpc_complex AS (r float8, i float8);
+CREATE TABLE tpc_filler3 (a int PRIMARY KEY, b text DEFAULT 'Unspecified');
+CREATE TABLE tpc_filler4 (id serial, t text);
+CREATE TABLE tpc_filler5(data text);
+INSERT INTO tpc_filler5 SELECT repeat('a', 2000) || g.i FROM generate_series(1, 1) g(i);
+TRUNCATE table tpc_filler5;
+CHECKPOINT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+ count
+-------
+ 9
+(1 row)
+
+-- Each iteration runs the trigger shape: catalog DDL inside a rolled-back
+-- subtransaction, then the same DDL again, then decode. Unfixed builds
+-- typically die within a handful of iterations.
+-- (temporarily hide the queries, to avoid flooding the expected output)
+\set ECHO none
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+ count
+-------
+ 0
+(1 row)
+
+DROP TABLE tpc_filler1;
+DROP TABLE tpc_filler2;
+DROP TYPE tpc_complex;
+DROP TABLE tpc_filler3;
+DROP TABLE tpc_filler4;
+DROP TABLE tpc_filler5;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+ count
+-------
+ 0
+(1 row)
+
+SELECT pg_drop_replication_slot('regression_slot');
+ pg_drop_replication_slot
+--------------------------
+
+(1 row)
+
+\c :prevdb
+DROP DATABASE regression_tuplecid;
diff --git a/contrib/test_decoding/meson.build b/contrib/test_decoding/meson.build
index 667ea76518f..b0d3ce66649 100644
--- a/contrib/test_decoding/meson.build
+++ b/contrib/test_decoding/meson.build
@@ -67,6 +67,7 @@ tests += {
'stats',
'twophase',
'twophase_stream',
+ 'tuplecid',
],
'regress_args': [
'--temp-config', files('logical.conf'),
diff --git a/contrib/test_decoding/sql/tuplecid.sql b/contrib/test_decoding/sql/tuplecid.sql
new file mode 100644
index 00000000000..69a7e6db77f
--- /dev/null
+++ b/contrib/test_decoding/sql/tuplecid.sql
@@ -0,0 +1,76 @@
+-- Tests for decoding of transactions in which a catalog-modifying
+-- subtransaction was rolled back (BUG #19555).
+--
+-- When a subtransaction modifies catalog tuples and is then rolled back,
+-- its dead heap-only line pointers can be marked LP_UNUSED by on-access
+-- pruning and reused by later catalog inserts of the same top-level
+-- transaction. The aborted subtransaction's xl_heap_new_cid records must
+-- not be consulted when building the historic snapshot used to decode the
+-- transaction; on unfixed builds they collide with the records of the
+-- reused line pointer and decoding dies with
+-- TRAP: failed Assert("ent->cmin == change->data.tuplecid.cmin")
+-- (or, on non-assert builds, silently uses wrong cmin/cmax mappings).
+--
+-- Whether the collision triggers depends on the physical layout of the
+-- catalog pages, so run in a fresh database where prior tests cannot have
+-- changed it, and loop enough times to leave headroom for layout
+-- differences across versions.
+CREATE DATABASE regression_tuplecid;
+-- snapshot the original database name (make and meson use different
+-- names for it) so we can switch back before dropping the test database
+\set prevdb :DBNAME
+\c regression_tuplecid
+
+-- predictability
+SET synchronous_commit = on;
+
+SELECT 'init' FROM pg_create_logical_replication_slot('regression_slot', 'test_decoding');
+
+-- Catalog churn to push the catalog pages into a state where on-access
+-- pruning frees the aborted subtransaction's line pointer and the second
+-- ALTER's catalog insert reuses it.
+CREATE TABLE tpc_filler1(f1 char(4));
+CREATE TABLE tpc_filler2(data text);
+INSERT INTO tpc_filler2 VALUES ('before-test');
+CREATE TYPE tpc_complex AS (r float8, i float8);
+CREATE TABLE tpc_filler3 (a int PRIMARY KEY, b text DEFAULT 'Unspecified');
+CREATE TABLE tpc_filler4 (id serial, t text);
+CREATE TABLE tpc_filler5(data text);
+INSERT INTO tpc_filler5 SELECT repeat('a', 2000) || g.i FROM generate_series(1, 1) g(i);
+TRUNCATE table tpc_filler5;
+CHECKPOINT;
+
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+
+-- Each iteration runs the trigger shape: catalog DDL inside a rolled-back
+-- subtransaction, then the same DDL again, then decode. Unfixed builds
+-- typically die within a handful of iterations.
+-- (temporarily hide the queries, to avoid flooding the expected output)
+\set ECHO none
+SELECT format($fmt$
+CREATE TABLE tpc_cmin(data int, pad1 text, pad2 int, pad3 text);
+BEGIN;
+SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE text;
+ROLLBACK TO SAVEPOINT a;
+ALTER TABLE tpc_cmin ALTER COLUMN data TYPE bigint;
+COMMIT;
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+DROP TABLE tpc_cmin;
+$fmt$)
+FROM generate_series(1, 25) \gexec
+\set ECHO all
+
+DROP TABLE tpc_filler1;
+DROP TABLE tpc_filler2;
+DROP TYPE tpc_complex;
+DROP TABLE tpc_filler3;
+DROP TABLE tpc_filler4;
+DROP TABLE tpc_filler5;
+
+SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+
+SELECT pg_drop_replication_slot('regression_slot');
+
+\c :prevdb
+DROP DATABASE regression_tuplecid;
--
2.34.1
v7-0002-Refactor-the-code-and-improve-some-comments.patch (application/octet-stream, 10.9K) download
From 6a23469d7c32dec52609739437582b7f8f5a1661 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=C3=81lvaro=20Herrera?= <alvherre@kurilemu.de>
Date: Wed, 7 Oct 2026 12:42:01 +0200
Subject: [PATCH v7 2/3] Refactor the code and improve some comments
Author: Hayato Kuroda <kuroda.hayato@fujitsu.com>
Author: Zhijie Hou <houzhijie22@gmail.com>
---
src/backend/replication/logical/decode.c | 26 ++---
.../replication/logical/reorderbuffer.c | 103 +++++++++++-------
src/include/replication/reorderbuffer.h | 6 +-
3 files changed, 75 insertions(+), 60 deletions(-)
diff --git a/src/backend/replication/logical/decode.c b/src/backend/replication/logical/decode.c
index 0e7d4840a8e..2958183c298 100644
--- a/src/backend/replication/logical/decode.c
+++ b/src/backend/replication/logical/decode.c
@@ -893,32 +893,20 @@ DecodeAbort(LogicalDecodingContext *ctx, XLogRecordBuffer *buf,
else
{
/*
- * Remove tuplecid changes queued by the aborted (sub)transactions
- * from the toplevel's list, before the transactions are torn down.
- * The abort record's primary xid tells
- * ReorderBufferCleanupSubTxnTupleCids() whether the whole toplevel
- * is going away, in which case scanning the list is pointless.
- *
- * 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.
+ * Remove tuplecid changes queued by the aborted subtransactions from
+ * the toplevel's list, before ReorderBufferAbort() tears the
+ * transactions down.
*/
+ ReorderBufferCleanupAbortedSubTxnTupleCids(ctx->reorder, xid,
+ parsed->nsubxacts,
+ parsed->subxacts);
+
for (i = 0; i < parsed->nsubxacts; i++)
{
- ReorderBufferCleanupSubTxnTupleCids(ctx->reorder,
- parsed->subxacts[i],
- xid);
ReorderBufferAbort(ctx->reorder, parsed->subxacts[i],
buf->record->EndRecPtr, abort_time);
}
- ReorderBufferCleanupSubTxnTupleCids(ctx->reorder, xid, xid);
ReorderBufferAbort(ctx->reorder, xid, buf->record->EndRecPtr,
abort_time);
}
diff --git a/src/backend/replication/logical/reorderbuffer.c b/src/backend/replication/logical/reorderbuffer.c
index e1c6a7c4d32..dbc10dccc8a 100644
--- a/src/backend/replication/logical/reorderbuffer.c
+++ b/src/backend/replication/logical/reorderbuffer.c
@@ -240,6 +240,9 @@ static ReorderBufferTXN *ReorderBufferTXNByXid(ReorderBuffer *rb,
XLogRecPtr lsn, bool create_as_top);
static void ReorderBufferTransferSnapToParent(ReorderBufferTXN *txn,
ReorderBufferTXN *subtxn);
+static bool TransactionIdInSubxactArray(TransactionId xid,
+ TransactionId *subxacts,
+ int nsubxacts);
static void AssertTXNLsnOrder(ReorderBuffer *rb);
@@ -3158,13 +3161,13 @@ ReorderBufferAbort(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn,
}
/*
- * Remove tuplecid changes queued by subtransaction xid from its toplevel
- * transaction's list.
+ * Remove tuplecid changes queued by aborted subtransactions from their
+ * toplevel transaction's list.
*
* Unlike regular changes, tuplecid changes are always queued on the toplevel
* transaction (see ReorderBufferAddNewTupleCids), so they would otherwise
- * survive the abort of the subtransaction that wrote them. That's wrong:
- * they describe catalog tuple versions created or killed by the aborted
+ * survive the abort of the subtransaction that wrote them. That's wrong: they
+ * describe catalog tuple versions created or killed by the aborted
* subtransaction, which never became visible, and keeping them can corrupt
* ReorderBufferBuildTupleCidHash() at commit time -- both when the toplevel
* transaction later reuses the same tid (the stale entry collides with the
@@ -3172,56 +3175,56 @@ ReorderBufferAbort(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn,
* the tid again (a stale cmax would make a still-live tuple look deleted on
* historic snapshots).
*
- * The cleanup is pointless when the whole toplevel transaction is
- * being aborted, since ReorderBufferCleanupTXN() frees the whole list
- * anyway; the caller passes the abort record's primary xid and we skip
- * the scan when it is xid's toplevel. Note that the opposite decision
- * -- cleaning only when the primary xid's own association is known --
- * would be wrong: abort records are written once the subtransaction is
- * already in TRANS_ABORT, so they carry no toplevel xid in their
- * header, and an outer subtransaction that never wrote WAL of its own
- * never gets an association at all. When such an outer subtransaction
- * rolls back, released inner subtransactions listed in its abort record
- * do have known associations and are cleaned here.
+ * To reach the toplevel, we need one of the abort set's xids to be a known
+ * subtransaction. The primary xid may have no entry at all: an abort record
+ * never carries the toplevel xid, so an outer subtransaction that wrote no WAL
+ * of its own (a savepoint that only wraps other savepoints) is never assigned
+ * to its toplevel, while a subcommitted child that did write WAL is. Hence we
+ * search the subxacts too, rather than testing the primary xid alone.
*
- * 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().
+ * The cleanup is pointless either when the whole toplevel transaction is
+ * being aborted, since ReorderBufferCleanupTXN() frees the whole list
+ * anyway, or when the aborting transaction is a subtransaction that has no
+ * association with its toplevel. The latter can happen if the transaction
+ * was already consumed by an earlier decoding pass, so the restart point
+ * has advanced past the subtransaction's first (toplevel-xid-bearing) WAL
+ * record. Since the transaction is skipped, its tuplecid entries will
+ * never be referenced again, so no cleanup is needed.
*/
void
-ReorderBufferCleanupSubTxnTupleCids(ReorderBuffer *rb, TransactionId xid,
- TransactionId primary_xid)
+ReorderBufferCleanupAbortedSubTxnTupleCids(ReorderBuffer *rb,
+ TransactionId xid,
+ int nsubxacts,
+ TransactionId *subxacts)
{
ReorderBufferTXN *txn;
ReorderBufferTXN *toptxn;
dlist_mutable_iter it;
+ /*
+ * Search the passed-in xids for a known subtransaction, and use it to
+ * find the toplevel transaction.
+ */
txn = ReorderBufferTXNByXid(rb, xid, false, NULL, InvalidXLogRecPtr,
false);
- /* unknown transaction, or unknown association: nothing to remove */
- if (txn == NULL || !rbtxn_is_known_subxact(txn))
- return;
-
- toptxn = rbtxn_get_toptxn(txn);
+ for (int i = 0; txn == NULL && i < nsubxacts; i++)
+ txn = ReorderBufferTXNByXid(rb, subxacts[i], false, NULL,
+ InvalidXLogRecPtr, false);
/*
- * The whole toplevel transaction is being aborted (the abort record's
- * primary xid is xid's toplevel): ReorderBufferCleanupTXN() will free
- * the whole list shortly, don't scan it once per aborted subxid.
+ * Skip when nothing usable was found. No entry at all means no NEW_CID
+ * record from these xids was decoded in this pass, so nothing was queued.
+ * An entry that is not a known subtransaction means either the toplevel
+ * is being aborted or this pass started after the assigning WAL record,
+ * so the commit is skipped here anyway.
*/
- if (toptxn->xid == primary_xid)
+ if (txn == NULL || !rbtxn_is_known_subxact(txn))
return;
+ /* Get the top-level transaction to clean up its tuplecid list */
+ toptxn = rbtxn_get_toptxn(txn);
+
dlist_foreach_modify(it, &toptxn->tuplecids)
{
ReorderBufferChange *change;
@@ -3230,15 +3233,37 @@ ReorderBufferCleanupSubTxnTupleCids(ReorderBuffer *rb, TransactionId xid,
Assert(change->action == REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID);
- if (change->data.tuplecid.subxid == xid)
+ /*
+ * Remove the entry if it's part of the aborting subtransaction or one
+ * of its children.
+ *
+ * The abort record's subxacts are preserved in logical order (see
+ * AtSubCommit_childXids), so we can use binary search to look up the
+ * xid.
+ */
+ 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--;
}
}
}
+/*
+ * Check whether xid is in an array sorted in logical XID order.
+ */
+static bool
+TransactionIdInSubxactArray(TransactionId xid, TransactionId *subxacts,
+ int nsubxacts)
+{
+ return bsearch(&xid, subxacts, nsubxacts,
+ sizeof(TransactionId), xidLogicalComparator) != NULL;
+}
+
/*
* Abort all transactions that aren't actually running anymore because the
* server restarted.
diff --git a/src/include/replication/reorderbuffer.h b/src/include/replication/reorderbuffer.h
index 23c447c4953..7cfa43ad163 100644
--- a/src/include/replication/reorderbuffer.h
+++ b/src/include/replication/reorderbuffer.h
@@ -743,8 +743,10 @@ extern void ReorderBufferCommitChild(ReorderBuffer *rb, TransactionId xid,
XLogRecPtr end_lsn);
extern void ReorderBufferAbort(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn,
TimestampTz abort_time);
-extern void ReorderBufferCleanupSubTxnTupleCids(ReorderBuffer *rb, TransactionId xid,
- TransactionId primary_xid);
+extern void ReorderBufferCleanupAbortedSubTxnTupleCids(ReorderBuffer *rb,
+ TransactionId xid,
+ int nsubxacts,
+ TransactionId *subxacts);
extern void ReorderBufferAbortOld(ReorderBuffer *rb, TransactionId oldestRunningXid);
extern void ReorderBufferForget(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn);
extern void ReorderBufferInvalidate(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn);
--
2.34.1
^ permalink raw reply [nested|flat] 53+ messages in thread
* Re: Bug in logical decoding with DDL and subtransactions
@ 2026-10-09 18:11 Álvaro Herrera <alvherre@kurilemu.de>
parent: Zhijie Hou <houzhijie22@gmail.com>
1 sibling, 1 reply; 53+ messages in thread
From: Álvaro Herrera @ 2026-10-09 18:11 UTC (permalink / raw)
To: Zhijie Hou <houzhijie22@gmail.com>; Bingshuai Li <lucian1412@outlook.com>; +Cc: kuroda.hayato@fujitsu.com <kuroda.hayato@fujitsu.com>; Michael Paquier <michael@paquier.xyz>; Tom Lane <tgl@sss.pgh.pa.us>; Alexander Lakhin <exclusion@gmail.com>; L. pgsql-hackers <pgsql-hackers@lists.postgresql.org>; mark.dilger@enterprisedb.com <mark.dilger@enterprisedb.com>; Amit Kapila <amit.kapila16@gmail.com>; Masahiko Sawada <sawada.mshk@gmail.com>; Andrey Rachitskiy <pl0h0yp1@gmail.com>; a.kozhemyakin@postgrespro.ru <a.kozhemyakin@postgrespro.ru>
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
^ permalink raw reply [nested|flat] 53+ messages in thread
* Re: Bug in logical decoding with DDL and subtransactions
@ 2026-10-11 21:40 Álvaro Herrera <alvherre@kurilemu.de>
parent: Álvaro Herrera <alvherre@kurilemu.de>
0 siblings, 0 replies; 53+ messages in thread
From: Álvaro Herrera @ 2026-10-11 21:40 UTC (permalink / raw)
To: Zhijie Hou <houzhijie22@gmail.com>; Bingshuai Li <lucian1412@outlook.com>; +Cc: kuroda.hayato@fujitsu.com <kuroda.hayato@fujitsu.com>; Michael Paquier <michael@paquier.xyz>; Tom Lane <tgl@sss.pgh.pa.us>; Alexander Lakhin <exclusion@gmail.com>; L. pgsql-hackers <pgsql-hackers@lists.postgresql.org>; mark.dilger@enterprisedb.com <mark.dilger@enterprisedb.com>; Amit Kapila <amit.kapila16@gmail.com>; Masahiko Sawada <sawada.mshk@gmail.com>; Andrey Rachitskiy <pl0h0yp1@gmail.com>; a.kozhemyakin@postgrespro.ru <a.kozhemyakin@postgrespro.ru>
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)
Attachments:
v8-0001-Fix-stale-tuplecid-records-left-behind-by-aborted.patch (text/x-diff, 29.5K) download
From 6e192c8b9fbbe8469eb8ca0bd1499e3ba2f7fe77 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=C3=81lvaro=20Herrera?= <alvherre@kurilemu.de>
Date: Sun, 11 Oct 2026 23:22:26 +0200
Subject: [PATCH v8] Fix stale tuplecid records left behind by aborted
subtransactions
Tuplecid changes are always queued on the toplevel transaction, so
unlike regular changes they are not dropped when the subtransaction
that wrote them aborts. The stale mappings corrupt
ReorderBufferBuildTupleCidHash() at commit time: if a later catalog
insert reuses the aborted subtransaction's line pointer (made
LP_UNUSED by on-access pruning or by vacuum), the fresh record
collides with the stale one with a different cmin, tripping the cmin
equality assertion; where nothing reuses the tid, a stale cmax makes
a still-live catalog tuple look deleted on historic snapshots. On
non-assert builds there is no crash, but the stale mappings risk
misjudging historic catalog visibility, which could produce
incorrect decoding output.
Remove the aborted subtransaction's tuplecid entries when its abort
is decoded. The cleanup is not needed when the whole toplevel
transaction is being aborted, because ReorderBufferCleanupTXN()
frees the whole list anyway; to avoid scanning the list once per
aborted subxid in that case, DecodeAbort() passes the abort record's
primary xid to the new ReorderBufferCleanupSubTxnTupleCids(), which
skips the scan when that xid is the toplevel of the xid being
cleaned.
The decision cannot be based on whether the primary xid's own
association with its toplevel is known: abort records are written
after the subtransaction has entered TRANS_ABORT, so they never
carry the toplevel xid in their header, and an outer subtransaction
that never wrote WAL of its own -- for example a savepoint that only
wraps other savepoints -- can never get its association established
at all. When such an outer subtransaction is rolled back, the
released inner subtransactions listed in its abort record do have
known associations, and their tuplecids must be removed from the
surviving toplevel's list. The existing tuplecid and tuplecid_restart
tests only cover aborts of subtransactions that wrote WAL themselves,
which is why this shape needs its own test.
Skipping the cleanup when the association of the xid being cleaned
is unknown is safe because of how a slot's restart point advances:
SnapBuildProcessRunningXacts() cannot move the restart point past
the oldest in-progress transaction, so any pass that output-decodes
the toplevel commit must have replayed the subtransaction's first
record and therefore knows 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 via
SnapBuildXactNeedsSkip(), so any stale tuplecid entries left behind
are dropped along with the transaction state and never reach
ReorderBufferBuildTupleCidHash().
Add an isolation test for the nested shape: the toplevel writes WAL
first, an inner subtransaction modifies a user catalog table and is
released, and the outer subtransaction -- which produces no WAL of
its own -- is then rolled back; with the page-fill and vacuum recipe
of tuplecid_restart, the toplevel's later insert deterministically
reuses the aborted subtransaction's line pointer. On unfixed assert
builds the final get_changes dies with the original cmin assertion
in ReorderBufferBuildTupleCidHash(); with the fix it passes. The
existing tests keep covering the simple savepoint and the restart
shapes.
Author: Bingshuai Li <lucian1412@outlook.com>
Author: Hayato Kuroda <kuroda.hayato@fujitsu.com>
Author: Zhijie Hou <houzhijie22@gmail.com>
Author: Mark Dilger <mark.dilger@enterprisedb.com>
Reported-by: Alexander Kozhemyakin <a.kozhemyakin@postgrespro.ru>
Backpatch-through: 14
Bug: #19555
Discussion: https://postgr.es/m/CAHgHdKu5e3XY5e90Tuaxq_R4WrKxSV734Q%2BLwo5y39Omp2A-Gg@mail.gmail.com
---
contrib/test_decoding/Makefile | 3 +-
.../expected/tuplecid_nested.out | 32 +++++
.../expected/tuplecid_restart.out | 68 +++++++++++
contrib/test_decoding/meson.build | 2 +
.../test_decoding/specs/tuplecid_nested.spec | 77 ++++++++++++
.../test_decoding/specs/tuplecid_restart.spec | 75 ++++++++++++
src/backend/replication/logical/decode.c | 11 +-
.../replication/logical/reorderbuffer.c | 111 +++++++++++++++++-
src/backend/replication/logical/snapbuild.c | 2 +-
src/backend/utils/time/snapmgr.c | 8 +-
src/include/replication/reorderbuffer.h | 18 ++-
11 files changed, 393 insertions(+), 14 deletions(-)
create mode 100644 contrib/test_decoding/expected/tuplecid_nested.out
create mode 100644 contrib/test_decoding/expected/tuplecid_restart.out
create mode 100644 contrib/test_decoding/specs/tuplecid_nested.spec
create mode 100644 contrib/test_decoding/specs/tuplecid_restart.spec
diff --git a/contrib/test_decoding/Makefile b/contrib/test_decoding/Makefile
index a7f7b7ae789..a33e6295d8c 100644
--- a/contrib/test_decoding/Makefile
+++ b/contrib/test_decoding/Makefile
@@ -15,7 +15,8 @@ SLOT_CREATION_TST = $(if $(filter win32,$(PORTNAME)),,slot_creation_error)
ISOLATION = mxact delayed_startup ondisk_startup concurrent_ddl_dml \
oldest_xmin snapshot_transfer subxact_without_top concurrent_stream \
twophase_snapshot $(SLOT_CREATION_TST) catalog_change_snapshot \
- skip_snapshot_restore invalidation_distribution parallel_session_origin
+ skip_snapshot_restore invalidation_distribution parallel_session_origin \
+ tuplecid_restart tuplecid_nested
REGRESS_OPTS = --temp-config $(top_srcdir)/contrib/test_decoding/logical.conf
ISOLATION_OPTS = --temp-config $(top_srcdir)/contrib/test_decoding/logical.conf
diff --git a/contrib/test_decoding/expected/tuplecid_nested.out b/contrib/test_decoding/expected/tuplecid_nested.out
new file mode 100644
index 00000000000..5d816374fbc
--- /dev/null
+++ b/contrib/test_decoding/expected/tuplecid_nested.out
@@ -0,0 +1,32 @@
+Parsed test spec with 3 sessions
+
+starting permutation: s1_init s0_begin s0_topwrite s0_outer s0_inner s0_catinsert1 s0_release_inner s0_rollback_outer s2_vacuum s0_catinsert2 s0_commit s1_get_changes
+step s1_init: SELECT 'init' FROM pg_create_logical_replication_slot('tuplecid_nested_slot', 'test_decoding');
+?column?
+--------
+init
+(1 row)
+
+step s0_begin: BEGIN;
+step s0_topwrite: INSERT INTO tbl1 VALUES (0);
+step s0_outer: SAVEPOINT outer_sp;
+step s0_inner: SAVEPOINT inner_sp;
+step s0_catinsert1: INSERT INTO user_cat VALUES (5, 'e');
+step s0_release_inner: RELEASE SAVEPOINT inner_sp;
+step s0_rollback_outer: ROLLBACK TO SAVEPOINT outer_sp;
+step s2_vacuum: VACUUM user_cat;
+step s0_catinsert2: INSERT INTO user_cat VALUES (6, 'f');
+step s0_commit: COMMIT;
+step s1_get_changes: SELECT data FROM pg_logical_slot_get_changes('tuplecid_nested_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%';
+data
+------------------------------------------
+BEGIN
+table public.tbl1: INSERT: val1[integer]:0
+COMMIT
+(3 rows)
+
+?column?
+--------
+stop
+(1 row)
+
diff --git a/contrib/test_decoding/expected/tuplecid_restart.out b/contrib/test_decoding/expected/tuplecid_restart.out
new file mode 100644
index 00000000000..e5b4bc2543d
--- /dev/null
+++ b/contrib/test_decoding/expected/tuplecid_restart.out
@@ -0,0 +1,68 @@
+Parsed test spec with 3 sessions
+
+starting permutation: s0_init s0_begin s0_savepoint s0_insert s1_checkpoint s1_get_changes s0_catinsert1 s0_rollback s2_vacuum s0_catinsert2 s1_checkpoint s1_get_changes s0_commit s1_get_changes
+step s0_init: SELECT 'init' FROM pg_create_logical_replication_slot('isolation_slot', 'test_decoding');
+?column?
+--------
+init
+(1 row)
+
+step s0_begin: BEGIN;
+step s0_savepoint: SAVEPOINT sp1;
+step s0_insert: INSERT INTO tbl1 VALUES (1);
+step s1_checkpoint: CHECKPOINT;
+step s1_get_changes: SELECT data FROM pg_logical_slot_get_changes('isolation_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%';
+data
+----
+(0 rows)
+
+step s0_catinsert1: INSERT INTO user_cat VALUES (5, 'e');
+step s0_rollback: ROLLBACK TO SAVEPOINT sp1;
+step s2_vacuum: VACUUM user_cat;
+step s0_catinsert2: INSERT INTO user_cat VALUES (6, 'f');
+step s1_checkpoint: CHECKPOINT;
+step s1_get_changes: SELECT data FROM pg_logical_slot_get_changes('isolation_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%';
+data
+----
+(0 rows)
+
+step s0_commit: COMMIT;
+step s1_get_changes: SELECT data FROM pg_logical_slot_get_changes('isolation_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%';
+data
+------
+BEGIN
+COMMIT
+(2 rows)
+
+?column?
+--------
+stop
+(1 row)
+
+
+starting permutation: s0_begin s0_savepoint s0_insert s1_init s0_catinsert1 s0_rollback s2_vacuum s0_catinsert2 s0_commit s1_get_changes
+step s0_begin: BEGIN;
+step s0_savepoint: SAVEPOINT sp1;
+step s0_insert: INSERT INTO tbl1 VALUES (1);
+step s1_init: SELECT 'init' FROM pg_create_logical_replication_slot('isolation_slot', 'test_decoding'); <waiting ...>
+step s0_catinsert1: INSERT INTO user_cat VALUES (5, 'e');
+step s0_rollback: ROLLBACK TO SAVEPOINT sp1;
+step s2_vacuum: VACUUM user_cat;
+step s0_catinsert2: INSERT INTO user_cat VALUES (6, 'f');
+step s0_commit: COMMIT;
+step s1_init: <... completed>
+?column?
+--------
+init
+(1 row)
+
+step s1_get_changes: SELECT data FROM pg_logical_slot_get_changes('isolation_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%';
+data
+----
+(0 rows)
+
+?column?
+--------
+stop
+(1 row)
+
diff --git a/contrib/test_decoding/meson.build b/contrib/test_decoding/meson.build
index dbc0ef0f63e..667ea76518f 100644
--- a/contrib/test_decoding/meson.build
+++ b/contrib/test_decoding/meson.build
@@ -30,6 +30,8 @@ test_decoding_isolation = [
'skip_snapshot_restore',
'invalidation_distribution',
'parallel_session_origin',
+ 'tuplecid_nested',
+ 'tuplecid_restart',
]
# slot_creation_error terminates another backend, whose FATAL message can be
diff --git a/contrib/test_decoding/specs/tuplecid_nested.spec b/contrib/test_decoding/specs/tuplecid_nested.spec
new file mode 100644
index 00000000000..52c80eb55eb
--- /dev/null
+++ b/contrib/test_decoding/specs/tuplecid_nested.spec
@@ -0,0 +1,77 @@
+# Test decoding of a partially rolled back transaction where the aborted part
+# is nested: the aborting outer subtransaction never produced any WAL of its
+# own, so decoding cannot know its toplevel transaction, while an inner
+# subtransaction it rolls back did produce WAL and its tuplecid records still
+# have to be removed (BUG #19555 nested shape).
+#
+# The tuplecid records written by the aborted inner subtransaction are queued
+# on the toplevel transaction and must be removed when the outer
+# subtransaction's abort is decoded; otherwise they collide with the records
+# of the line pointer that gets reused by the toplevel transaction's later
+# catalog insert, failing Assert(ent->cmin == change->data.tuplecid.cmin) in
+# ReorderBufferBuildTupleCidHash() when the commit is decoded.
+#
+# - s0_topwrite makes the toplevel transaction produce its first WAL record
+# before any subtransaction exists.
+# - s0_outer establishes the outer savepoint, which never gets a WAL record
+# of its own.
+# - s0_catinsert1 generates an xl_heap_new_cid record in the inner
+# subtransaction, which is then released.
+# - s0_rollback_outer rolls the outer savepoint back. Its abort record is
+# written once the backend is already in TRANS_ABORT, so it carries no
+# toplevel xid in its header and the outer subtransaction's association
+# with the toplevel can never be established. The released inner
+# subtransaction is listed in the same abort record, though, and its
+# tuplecid records still must be removed from the toplevel's list.
+# - s2_vacuum reclaims the aborted row's line pointer (dead inserts are
+# removed regardless of the xid horizon, so this is deterministic even
+# while the toplevel transaction is still open); s0_catinsert2 then reuses
+# the same tid with a different cmin.
+# - s1_get_changes then decodes the toplevel commit and builds the tuplecid
+# hash; on unfixed builds the stale tuplecid of the aborted inner
+# subtransaction collides there with the fresh one.
+setup
+{
+ DROP TABLE IF EXISTS tbl1;
+ DROP TABLE IF EXISTS user_cat;
+ CREATE TABLE tbl1 (val1 integer);
+ -- Four rows of ~1.5kB fill the first heap page to within a few hundred
+ -- bytes, so that vacuuming away the aborted fifth row leaves exactly one
+ -- line pointer for the next insert to reuse.
+ CREATE TABLE user_cat (c1 int, filler char(1500)) WITH (user_catalog_table = true);
+ INSERT INTO user_cat VALUES (1, 'a'), (2, 'b'), (3, 'c'), (4, 'd');
+}
+
+teardown
+{
+ DROP TABLE tbl1;
+ DROP TABLE user_cat;
+ SELECT 'stop' FROM pg_drop_replication_slot('tuplecid_nested_slot');
+}
+
+session "s0"
+setup { SET synchronous_commit=on; }
+step "s0_begin" { BEGIN; }
+step "s0_topwrite" { INSERT INTO tbl1 VALUES (0); }
+step "s0_outer" { SAVEPOINT outer_sp; }
+step "s0_inner" { SAVEPOINT inner_sp; }
+step "s0_catinsert1" { INSERT INTO user_cat VALUES (5, 'e'); }
+step "s0_release_inner" { RELEASE SAVEPOINT inner_sp; }
+step "s0_rollback_outer" { ROLLBACK TO SAVEPOINT outer_sp; }
+step "s0_catinsert2" { INSERT INTO user_cat VALUES (6, 'f'); }
+step "s0_commit" { COMMIT; }
+
+session "s1"
+setup { SET synchronous_commit=on; }
+step "s1_init" { SELECT 'init' FROM pg_create_logical_replication_slot('tuplecid_nested_slot', 'test_decoding'); }
+# The user_cat rows carry ~1.5kB filler values which would flood the expected
+# output; filter them out (decoding still processes them server-side).
+step "s1_get_changes" { SELECT data FROM pg_logical_slot_get_changes('tuplecid_nested_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%'; }
+
+session "s2"
+setup { SET synchronous_commit=on; }
+step "s2_vacuum" { VACUUM user_cat; }
+
+# The slot is created before the transaction begins, so the final
+# s1_get_changes decodes the whole transaction through its commit.
+permutation "s1_init" "s0_begin" "s0_topwrite" "s0_outer" "s0_inner" "s0_catinsert1" "s0_release_inner" "s0_rollback_outer" "s2_vacuum" "s0_catinsert2" "s0_commit" "s1_get_changes"
diff --git a/contrib/test_decoding/specs/tuplecid_restart.spec b/contrib/test_decoding/specs/tuplecid_restart.spec
new file mode 100644
index 00000000000..58da414e8b7
--- /dev/null
+++ b/contrib/test_decoding/specs/tuplecid_restart.spec
@@ -0,0 +1,75 @@
+# Test decoding of a transaction in which a catalog-modifying subtransaction
+# was rolled back, where the transaction spans a logical decoding restart
+# point (BUG #19555 restart shape).
+#
+# The tuplecid records written by the aborted subtransaction are queued on the
+# toplevel transaction and must be removed when the subtransaction's abort is
+# decoded; otherwise they collide with the records of the line pointer that
+# gets reused by the toplevel transaction's later catalog insert, failing
+# Assert(ent->cmin == change->data.tuplecid.cmin) in
+# ReorderBufferBuildTupleCidHash() when the commit is decoded.
+#
+# - s0_insert runs in a subtransaction and produces its first WAL record.
+# - s0_catinsert1 generates an xl_heap_new_cid record in that subtransaction.
+# - s0_rollback aborts the subtransaction.
+# - s2_vacuum reclaims the aborted row's line pointer (dead inserts are
+# removed regardless of the xid horizon, so this is deterministic even
+# while the toplevel transaction is still open); s0_catinsert2 then reuses
+# the same tid with a different cmin.
+# - The transaction stays open across both checkpoints, so the final
+# s1_get_changes replays the transaction's records from the first
+# checkpoint and decodes its commit for output, building the tuplecid
+# hash. On unfixed builds the stale tuplecid of the aborted
+# subtransaction collides there with the fresh one.
+setup
+{
+ DROP TABLE IF EXISTS tbl1;
+ DROP TABLE IF EXISTS user_cat;
+ CREATE TABLE tbl1 (val1 integer);
+ -- Four rows of ~1.5kB fill the first heap page to within a few hundred
+ -- bytes, so that vacuuming away the aborted fifth row leaves exactly one
+ -- line pointer for the next insert to reuse.
+ CREATE TABLE user_cat (c1 int, filler char(1500)) WITH (user_catalog_table = true);
+ INSERT INTO user_cat VALUES (1, 'a'), (2, 'b'), (3, 'c'), (4, 'd');
+}
+
+teardown
+{
+ DROP TABLE tbl1;
+ DROP TABLE user_cat;
+ SELECT 'stop' FROM pg_drop_replication_slot('isolation_slot');
+}
+
+session "s0"
+setup { SET synchronous_commit=on; }
+step "s0_init" { SELECT 'init' FROM pg_create_logical_replication_slot('isolation_slot', 'test_decoding'); }
+step "s0_begin" { BEGIN; }
+step "s0_savepoint" { SAVEPOINT sp1; }
+step "s0_insert" { INSERT INTO tbl1 VALUES (1); }
+step "s0_catinsert1" { INSERT INTO user_cat VALUES (5, 'e'); }
+step "s0_rollback" { ROLLBACK TO SAVEPOINT sp1; }
+step "s0_catinsert2" { INSERT INTO user_cat VALUES (6, 'f'); }
+step "s0_commit" { COMMIT; }
+
+session "s1"
+setup { SET synchronous_commit=on; }
+step "s1_init" { SELECT 'init' FROM pg_create_logical_replication_slot('isolation_slot', 'test_decoding'); }
+step "s1_checkpoint" { CHECKPOINT; }
+# The user_cat rows carry ~1.5kB filler values which would flood the expected
+# output; filter them out (decoding still processes them server-side).
+step "s1_get_changes" { SELECT data FROM pg_logical_slot_get_changes('isolation_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%'; }
+
+session "s2"
+setup { SET synchronous_commit=on; }
+step "s2_vacuum" { VACUUM user_cat; }
+
+# The transaction commits only after the second s1_get_changes, so the last
+# s1_get_changes both replays the transaction from the first checkpoint and
+# decodes its commit for output.
+permutation "s0_init" "s0_begin" "s0_savepoint" "s0_insert" "s1_checkpoint" "s1_get_changes" "s0_catinsert1" "s0_rollback" "s2_vacuum" "s0_catinsert2" "s1_checkpoint" "s1_get_changes" "s0_commit" "s1_get_changes"
+
+# Variant with the slot created while the transaction is already open: slot
+# creation waits for a consistent point past the open transaction, so the
+# transaction is never decoded by this slot at all (no output). This locks in
+# the behavior that decoding cannot start in the middle of a transaction.
+permutation "s0_begin" "s0_savepoint" "s0_insert" "s1_init" "s0_catinsert1" "s0_rollback" "s2_vacuum" "s0_catinsert2" "s0_commit" "s1_get_changes"
diff --git a/src/backend/replication/logical/decode.c b/src/backend/replication/logical/decode.c
index 4a739230264..f44f94d9f07 100644
--- a/src/backend/replication/logical/decode.c
+++ b/src/backend/replication/logical/decode.c
@@ -860,7 +860,6 @@ DecodeAbort(LogicalDecodingContext *ctx, XLogRecordBuffer *buf,
xl_xact_parsed_abort *parsed, TransactionId xid,
bool two_phase)
{
- int i;
XLogRecPtr origin_lsn = InvalidXLogRecPtr;
TimestampTz abort_time = parsed->xact_time;
ReplOriginId origin_id = XLogRecGetOrigin(buf->record);
@@ -892,7 +891,15 @@ DecodeAbort(LogicalDecodingContext *ctx, XLogRecordBuffer *buf,
}
else
{
- for (i = 0; i < parsed->nsubxacts; i++)
+ /*
+ * Remove tuplecid changes queued by the aborted subtransactions from
+ * the toplevel's list.
+ */
+ ReorderBufferCleanupAbortedTupleCids(ctx->reorder, xid,
+ parsed->nsubxacts,
+ parsed->subxacts);
+
+ for (int i = 0; i < parsed->nsubxacts; i++)
{
ReorderBufferAbort(ctx->reorder, parsed->subxacts[i],
buf->record->EndRecPtr, abort_time);
diff --git a/src/backend/replication/logical/reorderbuffer.c b/src/backend/replication/logical/reorderbuffer.c
index 94112c30501..a4e77728854 100644
--- a/src/backend/replication/logical/reorderbuffer.c
+++ b/src/backend/replication/logical/reorderbuffer.c
@@ -242,6 +242,8 @@ static void ReorderBufferTransferSnapToParent(ReorderBufferTXN *txn,
ReorderBufferTXN *subtxn);
static void AssertTXNLsnOrder(ReorderBuffer *rb);
+static bool TransactionIdInSubxactArray(TransactionId xid,
+ TransactionId *subxacts, int nsubxacts);
/* ---------------------------------------
* support functions for lsn-order iterating over the ->changes of a
@@ -3157,6 +3159,109 @@ ReorderBufferAbort(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn,
ReorderBufferCleanupTXN(rb, txn);
}
+/*
+ * 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.
+ *
+#ifdef INCLUDE_LLM_WRITTEN_COMMENTS
+ * 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().
+#endif
+ *
+ * (This is pointless when xid is a top-level transaction. That case is
+ * handled instead by ReorderBufferCleanupTXN() removing the whole list.)
+ */
+void
+ReorderBufferCleanupAbortedTupleCids(ReorderBuffer *rb,
+ TransactionId xid,
+ int nsubxacts,
+ TransactionId *subxacts)
+{
+ ReorderBufferTXN *txn;
+ ReorderBufferTXN *toptxn;
+ dlist_mutable_iter it;
+
+ /*
+ * Search the passed-in xids for a 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 in this pass, so nothing was queued.
+ * An entry that is not a known subtransaction means either the toplevel
+ * is being aborted or this pass started after the assigning WAL record,
+ * so the commit is skipped here anyway.
+ */
+ 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's part 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--;
+ }
+ }
+}
+
+/*
+ * Check whether the given xid exists in the subxacts array, which must be
+ * sorted in logical order.
+ */
+static bool
+TransactionIdInSubxactArray(TransactionId xid, TransactionId *subxacts,
+ int nsubxacts)
+{
+ /* otherwise bsearch the (logically ordered) given subxact array */
+ return bsearch(&xid, subxacts, nsubxacts,
+ sizeof(TransactionId), xidLogicalComparator) != NULL;
+}
+
/*
* Abort all transactions that aren't actually running anymore because the
* server restarted.
@@ -3489,8 +3594,9 @@ ReorderBufferChangeMemoryUpdate(ReorderBuffer *rb,
void
ReorderBufferAddNewTupleCids(ReorderBuffer *rb, TransactionId xid,
XLogRecPtr lsn, RelFileLocator locator,
- ItemPointerData tid, CommandId cmin,
- CommandId cmax, CommandId combocid)
+ ItemPointerData tid, TransactionId subxid,
+ CommandId cmin, CommandId cmax,
+ CommandId combocid)
{
ReorderBufferChange *change = ReorderBufferAllocChange(rb);
ReorderBufferTXN *txn;
@@ -3502,6 +3608,7 @@ ReorderBufferAddNewTupleCids(ReorderBuffer *rb, TransactionId xid,
change->data.tuplecid.cmin = cmin;
change->data.tuplecid.cmax = cmax;
change->data.tuplecid.combocid = combocid;
+ change->data.tuplecid.subxid = subxid;
change->lsn = lsn;
change->txn = txn;
change->action = REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID;
diff --git a/src/backend/replication/logical/snapbuild.c b/src/backend/replication/logical/snapbuild.c
index 69caf5b02e7..0d31724746d 100644
--- a/src/backend/replication/logical/snapbuild.c
+++ b/src/backend/replication/logical/snapbuild.c
@@ -742,7 +742,7 @@ SnapBuildProcessNewCid(SnapBuild *builder, TransactionId xid,
ReorderBufferAddNewTupleCids(builder->reorder, xlrec->top_xid, lsn,
xlrec->target_locator, xlrec->target_tid,
- xlrec->cmin, xlrec->cmax,
+ xid, xlrec->cmin, xlrec->cmax,
xlrec->combocid);
/* figure out new command id */
diff --git a/src/backend/utils/time/snapmgr.c b/src/backend/utils/time/snapmgr.c
index bbb6cb87203..048450da2d3 100644
--- a/src/backend/utils/time/snapmgr.c
+++ b/src/backend/utils/time/snapmgr.c
@@ -160,7 +160,7 @@ TransactionId TransactionXmin = FirstNormalTransactionId;
TransactionId RecentXmin = FirstNormalTransactionId;
/* (table, ctid) => (cmin, cmax) mapping during timetravel */
-static HTAB *tuplecid_data = NULL;
+static HTAB *HistoricTupleCidHash = NULL;
/*
* Elements of the active snapshot stack.
@@ -1708,7 +1708,7 @@ SetupHistoricSnapshot(Snapshot historic_snapshot, HTAB *tuplecids)
HistoricSnapshot = historic_snapshot;
/* setup (cmin, cmax) lookup hash */
- tuplecid_data = tuplecids;
+ HistoricTupleCidHash = tuplecids;
}
@@ -1719,7 +1719,7 @@ void
TeardownHistoricSnapshot(bool is_error)
{
HistoricSnapshot = NULL;
- tuplecid_data = NULL;
+ HistoricTupleCidHash = NULL;
}
bool
@@ -1732,7 +1732,7 @@ HTAB *
HistoricSnapshotGetTupleCids(void)
{
Assert(HistoricSnapshotActive());
- return tuplecid_data;
+ return HistoricTupleCidHash;
}
/*
diff --git a/src/include/replication/reorderbuffer.h b/src/include/replication/reorderbuffer.h
index ff825e4b7b2..c8ec007c9f5 100644
--- a/src/include/replication/reorderbuffer.h
+++ b/src/include/replication/reorderbuffer.h
@@ -136,8 +136,12 @@ typedef struct ReorderBufferChange
CommandId command_id;
/*
- * New cid mapping for catalog changing transaction, set when action
- * == *_INTERNAL_TUPLECID.
+ * tuplecid changes are used to follow catalog tuple movements (i.e.,
+ * DDL changes); we need them to create the HistoricTupleCidHash table
+ * used with historical snapshots. For historical reasons we store
+ * these with the toplevel txn, not each subtxn; and yet we need to
+ * remove them on subxact aborts, so we record the subxid separately.
+ * Set when action == *_INTERNAL_TUPLECID.
*/
struct
{
@@ -146,6 +150,7 @@ typedef struct ReorderBufferChange
CommandId cmin;
CommandId cmax;
CommandId combocid;
+ TransactionId subxid;
} tuplecid;
/* Invalidation. */
@@ -738,6 +743,10 @@ extern void ReorderBufferCommitChild(ReorderBuffer *rb, TransactionId xid,
XLogRecPtr end_lsn);
extern void ReorderBufferAbort(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn,
TimestampTz abort_time);
+extern void ReorderBufferCleanupAbortedTupleCids(ReorderBuffer *rb,
+ TransactionId xid,
+ int nsubxacts,
+ TransactionId *subxacts);
extern void ReorderBufferAbortOld(ReorderBuffer *rb, TransactionId oldestRunningXid);
extern void ReorderBufferForget(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn);
extern void ReorderBufferInvalidate(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn);
@@ -750,8 +759,9 @@ extern void ReorderBufferAddNewCommandId(ReorderBuffer *rb, TransactionId xid,
XLogRecPtr lsn, CommandId cid);
extern void ReorderBufferAddNewTupleCids(ReorderBuffer *rb, TransactionId xid,
XLogRecPtr lsn, RelFileLocator locator,
- ItemPointerData tid,
- CommandId cmin, CommandId cmax, CommandId combocid);
+ ItemPointerData tid, TransactionId subxid,
+ CommandId cmin, CommandId cmax,
+ CommandId combocid);
extern void ReorderBufferAddInvalidations(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn,
Size nmsgs, SharedInvalidationMessage *msgs);
extern void ReorderBufferAddDistributedInvalidations(ReorderBuffer *rb, TransactionId xid,
--
2.47.3
^ permalink raw reply [nested|flat] 53+ messages in thread
* Re: Bug in logical decoding with DDL and subtransactions
@ 2026-10-12 17:15 alvherre@kurilemu.de <alvherre@kurilemu.de>
parent: Zhijie Hou <houzhijie22@gmail.com>
1 sibling, 2 replies; 53+ messages in thread
From: alvherre@kurilemu.de @ 2026-10-12 17:15 UTC (permalink / raw)
To: Zhijie Hou <houzhijie22@gmail.com>; +Cc: Bingshuai Li <lucian1412@outlook.com>; Hayato Kuroda (Fujitsu) <kuroda.hayato@fujitsu.com>; Michael Paquier <michael@paquier.xyz>; Tom Lane <tgl@sss.pgh.pa.us>; Alexander Lakhin <exclusion@gmail.com>; pgsql-hackers@lists.postgresql.org <pgsql-hackers@lists.postgresql.org>; mark.dilger@enterprisedb.com <mark.dilger@enterprisedb.com>; Amit Kapila <amit.kapila16@gmail.com>; Masahiko Sawada <sawada.mshk@gmail.com>; Andrey Rachitskiy <pl0h0yp1@gmail.com>; a.kozhemyakin@postgrespro.ru <a.kozhemyakin@postgrespro.ru>
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)
^ permalink raw reply [nested|flat] 53+ messages in thread
* RE: Bug in logical decoding with DDL and subtransactions
@ 2026-10-13 09:17 Hayato Kuroda (Fujitsu) <kuroda.hayato@fujitsu.com>
parent: alvherre@kurilemu.de <alvherre@kurilemu.de>
1 sibling, 0 replies; 53+ messages in thread
From: Hayato Kuroda (Fujitsu) @ 2026-10-13 09:17 UTC (permalink / raw)
To: 'alvherre@kurilemu.de' <alvherre@kurilemu.de>; Zhijie Hou <houzhijie22@gmail.com>; +Cc: Bingshuai Li <lucian1412@outlook.com>; Michael Paquier <michael@paquier.xyz>; Tom Lane <tgl@sss.pgh.pa.us>; Alexander Lakhin <exclusion@gmail.com>; pgsql-hackers@lists.postgresql.org <pgsql-hackers@lists.postgresql.org>; mark.dilger@enterprisedb.com <mark.dilger@enterprisedb.com>; Amit Kapila <amit.kapila16@gmail.com>; Masahiko Sawada <sawada.mshk@gmail.com>; Andrey Rachitskiy <pl0h0yp1@gmail.com>; a.kozhemyakin@postgrespro.ru <a.kozhemyakin@postgrespro.ru>
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
^ permalink raw reply [nested|flat] 53+ messages in thread
* Re: Bug in logical decoding with DDL and subtransactions
@ 2026-10-14 07:16 Zhijie Hou <houzhijie22@gmail.com>
parent: alvherre@kurilemu.de <alvherre@kurilemu.de>
1 sibling, 1 reply; 53+ messages in thread
From: Zhijie Hou @ 2026-10-14 07:16 UTC (permalink / raw)
To: alvherre@kurilemu.de <alvherre@kurilemu.de>; +Cc: Bingshuai Li <lucian1412@outlook.com>; Hayato Kuroda (Fujitsu) <kuroda.hayato@fujitsu.com>; Michael Paquier <michael@paquier.xyz>; Tom Lane <tgl@sss.pgh.pa.us>; Alexander Lakhin <exclusion@gmail.com>; pgsql-hackers@lists.postgresql.org <pgsql-hackers@lists.postgresql.org>; mark.dilger@enterprisedb.com <mark.dilger@enterprisedb.com>; Amit Kapila <amit.kapila16@gmail.com>; Masahiko Sawada <sawada.mshk@gmail.com>; Andrey Rachitskiy <pl0h0yp1@gmail.com>; a.kozhemyakin@postgrespro.ru <a.kozhemyakin@postgrespro.ru>
Hi,
On Tue, Oct 13, 2026 at 1:15 AM alvherre@kurilemu.de
<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
^ permalink raw reply [nested|flat] 53+ messages in thread
* RE: Bug in logical decoding with DDL and subtransactions
@ 2026-10-14 08:37 Bingshuai Li <lucian1412@outlook.com>
parent: Zhijie Hou <houzhijie22@gmail.com>
0 siblings, 1 reply; 53+ messages in thread
From: Bingshuai Li @ 2026-10-14 08:37 UTC (permalink / raw)
To: Zhijie Hou <houzhijie22@gmail.com>; alvherre@kurilemu.de <alvherre@kurilemu.de>; +Cc: Hayato Kuroda (Fujitsu) <kuroda.hayato@fujitsu.com>; Michael Paquier <michael@paquier.xyz>; Tom Lane <tgl@sss.pgh.pa.us>; Alexander Lakhin <exclusion@gmail.com>; pgsql-hackers@lists.postgresql.org <pgsql-hackers@lists.postgresql.org>; mark.dilger@enterprisedb.com <mark.dilger@enterprisedb.com>; Amit Kapila <amit.kapila16@gmail.com>; Masahiko Sawada <sawada.mshk@gmail.com>; Andrey Rachitskiy <pl0h0yp1@gmail.com>; a.kozhemyakin@postgrespro.ru <a.kozhemyakin@postgrespro.ru>
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
^ permalink raw reply [nested|flat] 53+ messages in thread
* Re: Bug in logical decoding with DDL and subtransactions
@ 2026-10-14 18:04 alvherre@kurilemu.de <alvherre@kurilemu.de>
parent: Bingshuai Li <lucian1412@outlook.com>
0 siblings, 2 replies; 53+ messages in thread
From: alvherre@kurilemu.de @ 2026-10-14 18:04 UTC (permalink / raw)
To: Bingshuai Li <lucian1412@outlook.com>; +Cc: Zhijie Hou <houzhijie22@gmail.com>; Hayato Kuroda (Fujitsu) <kuroda.hayato@fujitsu.com>; Michael Paquier <michael@paquier.xyz>; Tom Lane <tgl@sss.pgh.pa.us>; Alexander Lakhin <exclusion@gmail.com>; pgsql-hackers@lists.postgresql.org <pgsql-hackers@lists.postgresql.org>; mark.dilger@enterprisedb.com <mark.dilger@enterprisedb.com>; Amit Kapila <amit.kapila16@gmail.com>; Masahiko Sawada <sawada.mshk@gmail.com>; Andrey Rachitskiy <pl0h0yp1@gmail.com>; a.kozhemyakin@postgrespro.ru <a.kozhemyakin@postgrespro.ru>
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")
^ permalink raw reply [nested|flat] 53+ messages in thread
* Re: Bug in logical decoding with DDL and subtransactions
@ 2026-10-14 18:10 alvherre@kurilemu.de <alvherre@kurilemu.de>
parent: alvherre@kurilemu.de <alvherre@kurilemu.de>
1 sibling, 1 reply; 53+ messages in thread
From: alvherre@kurilemu.de @ 2026-10-14 18:10 UTC (permalink / raw)
To: Bingshuai Li <lucian1412@outlook.com>; +Cc: Zhijie Hou <houzhijie22@gmail.com>; Hayato Kuroda (Fujitsu) <kuroda.hayato@fujitsu.com>; Michael Paquier <michael@paquier.xyz>; Tom Lane <tgl@sss.pgh.pa.us>; Alexander Lakhin <exclusion@gmail.com>; pgsql-hackers@lists.postgresql.org <pgsql-hackers@lists.postgresql.org>; mark.dilger@enterprisedb.com <mark.dilger@enterprisedb.com>; Amit Kapila <amit.kapila16@gmail.com>; Masahiko Sawada <sawada.mshk@gmail.com>; Andrey Rachitskiy <pl0h0yp1@gmail.com>; a.kozhemyakin@postgrespro.ru <a.kozhemyakin@postgrespro.ru>
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
^ permalink raw reply [nested|flat] 53+ messages in thread
* Re: Bug in logical decoding with DDL and subtransactions
@ 2026-10-14 18:15 alvherre@kurilemu.de <alvherre@kurilemu.de>
parent: Hayato Kuroda (Fujitsu) <kuroda.hayato@fujitsu.com>
1 sibling, 0 replies; 53+ messages in thread
From: alvherre@kurilemu.de @ 2026-10-14 18:15 UTC (permalink / raw)
To: Hayato Kuroda (Fujitsu) <kuroda.hayato@fujitsu.com>; +Cc: Bingshuai Li <lucian1412@outlook.com>; Zhijie Hou <houzhijie22@gmail.com>; Michael Paquier <michael@paquier.xyz>; Tom Lane <tgl@sss.pgh.pa.us>; Alexander Lakhin <exclusion@gmail.com>; pgsql-hackers@lists.postgresql.org <pgsql-hackers@lists.postgresql.org>; mark.dilger@enterprisedb.com <mark.dilger@enterprisedb.com>; Amit Kapila <amit.kapila16@gmail.com>; Masahiko Sawada <sawada.mshk@gmail.com>; Andrey Rachitskiy <pl0h0yp1@gmail.com>; a.kozhemyakin@postgrespro.ru <a.kozhemyakin@postgrespro.ru>
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/
^ permalink raw reply [nested|flat] 53+ messages in thread
* Re: Bug in logical decoding with DDL and subtransactions
@ 2026-10-15 04:55 David Rowley <dgrowleyml@gmail.com>
parent: alvherre@kurilemu.de <alvherre@kurilemu.de>
0 siblings, 1 reply; 53+ messages in thread
From: David Rowley @ 2026-10-15 04:55 UTC (permalink / raw)
To: alvherre@kurilemu.de <alvherre@kurilemu.de>; +Cc: Bingshuai Li <lucian1412@outlook.com>; Zhijie Hou <houzhijie22@gmail.com>; Hayato Kuroda (Fujitsu) <kuroda.hayato@fujitsu.com>; Michael Paquier <michael@paquier.xyz>; Tom Lane <tgl@sss.pgh.pa.us>; Alexander Lakhin <exclusion@gmail.com>; pgsql-hackers@lists.postgresql.org <pgsql-hackers@lists.postgresql.org>; mark.dilger@enterprisedb.com <mark.dilger@enterprisedb.com>; Amit Kapila <amit.kapila16@gmail.com>; Masahiko Sawada <sawada.mshk@gmail.com>; Andrey Rachitskiy <pl0h0yp1@gmail.com>; a.kozhemyakin@postgrespro.ru <a.kozhemyakin@postgrespro.ru>
On Thu, 15 Oct 2026 at 07:10, alvherre@kurilemu.de <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
^ permalink raw reply [nested|flat] 53+ messages in thread
* Re: Bug in logical decoding with DDL and subtransactions
@ 2026-10-15 05:24 Tom Lane <tgl@sss.pgh.pa.us>
parent: David Rowley <dgrowleyml@gmail.com>
0 siblings, 1 reply; 53+ messages in thread
From: Tom Lane @ 2026-10-15 05:24 UTC (permalink / raw)
To: David Rowley <dgrowleyml@gmail.com>; +Cc: alvherre@kurilemu.de <alvherre@kurilemu.de>; Bingshuai Li <lucian1412@outlook.com>; Zhijie Hou <houzhijie22@gmail.com>; Hayato Kuroda (Fujitsu) <kuroda.hayato@fujitsu.com>; Michael Paquier <michael@paquier.xyz>; Alexander Lakhin <exclusion@gmail.com>; pgsql-hackers@lists.postgresql.org <pgsql-hackers@lists.postgresql.org>; mark.dilger@enterprisedb.com <mark.dilger@enterprisedb.com>; Amit Kapila <amit.kapila16@gmail.com>; Masahiko Sawada <sawada.mshk@gmail.com>; Andrey Rachitskiy <pl0h0yp1@gmail.com>; a.kozhemyakin@postgrespro.ru <a.kozhemyakin@postgrespro.ru>
David Rowley <dgrowleyml@gmail.com> 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
^ permalink raw reply [nested|flat] 53+ messages in thread
* Re: Bug in logical decoding with DDL and subtransactions
@ 2026-10-15 10:34 David Rowley <dgrowleyml@gmail.com>
parent: Tom Lane <tgl@sss.pgh.pa.us>
0 siblings, 1 reply; 53+ messages in thread
From: David Rowley @ 2026-10-15 10:34 UTC (permalink / raw)
To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: alvherre@kurilemu.de <alvherre@kurilemu.de>; Bingshuai Li <lucian1412@outlook.com>; Zhijie Hou <houzhijie22@gmail.com>; Hayato Kuroda (Fujitsu) <kuroda.hayato@fujitsu.com>; Michael Paquier <michael@paquier.xyz>; Alexander Lakhin <exclusion@gmail.com>; pgsql-hackers@lists.postgresql.org <pgsql-hackers@lists.postgresql.org>; mark.dilger@enterprisedb.com <mark.dilger@enterprisedb.com>; Amit Kapila <amit.kapila16@gmail.com>; Masahiko Sawada <sawada.mshk@gmail.com>; Andrey Rachitskiy <pl0h0yp1@gmail.com>; a.kozhemyakin@postgrespro.ru <a.kozhemyakin@postgrespro.ru>
On Thu, 15 Oct 2026 at 18:25, Tom Lane <tgl@sss.pgh.pa.us> wrote:
>
> David Rowley <dgrowleyml@gmail.com> 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
Attachments:
0001-Update-.abi-compliance-history-for-struct-ReorderBuf.patch (application/octet-stream, 1.9K) download
From 00b3678df30dbd4a4f4084c18d269fd794592f51 Mon Sep 17 00:00:00 2001
From: David Rowley <dgrowley@gmail.com>
Date: Thu, 15 Oct 2026 23:21:57 +1300
Subject: [PATCH] Update .abi-compliance-history for struct ReorderBufferChange
Here we also add exceptions for two other commits; the latest one
undoes the ABI changes of the initial one. Listing the 3 commits is
required as the change to ReorderBufferChange was made in between and
57193b3a0 must be listed to establish the new baseline for the ABI.
Discussion: https://postgr.es/m/CAApHDvpeFwoJkOctNMGo8WbLZ4dtt2Muf1MXrp2VKKGZuDLE0Q@mail.gmail.com
---
.abi-compliance-history | 24 ++++++++++++++++++++++++
1 file changed, 24 insertions(+)
diff --git a/.abi-compliance-history b/.abi-compliance-history
index c32cb0e12e1..49f1f63fd51 100644
--- a/.abi-compliance-history
+++ b/.abi-compliance-history
@@ -18,6 +18,30 @@
# Be sure to replace "<ADD JUSTIFICATION HERE>" with details of your change and
# why it is deemed acceptable.
+57193b3a09ed3555e9c6e3822173427a3249b335
+#
+# Fix EPQ run-time pruning using the parent's PARAM_EXEC values
+# 2026-10-15 15:50:11 +1300
+#
+# Removes "initialized" field that was added in c7328770b and restores the ABI
+# state to what it was in c7328770b~1
+
+5eae2800a854cd60e973b576fd9dac9db299dfd1
+#
+# Reorderbuffer: handle catalog-change-bearing aborted subxacts better
+# 2026-10-14 19:42:04 +0200
+#
+# *** <Álvaro to fill in this part> ***
+
+c7328770ba50f6250930cb023effe3354c49de32
+#
+# Fix incorrect reinit of run-time pruning for EPQ rechecks
+# 2026-10-09 11:04:22 +1300
+#
+# Introduces a new boolean field into padding bytes of PartitionPruningData.
+# This change was removed later in 57193b3a0, as another issue was discovered
+# that made this fix inadequate.
+
af48a67026145bd02fa953524fcdb0d84c1d9de6
#
# Fix tuple search during apply after concurrent index DDL.
--
2.53.0
^ permalink raw reply [nested|flat] 53+ messages in thread
* Re: Bug in logical decoding with DDL and subtransactions
@ 2026-10-15 14:41 alvherre@kurilemu.de <alvherre@kurilemu.de>
parent: David Rowley <dgrowleyml@gmail.com>
0 siblings, 1 reply; 53+ messages in thread
From: alvherre@kurilemu.de @ 2026-10-15 14:41 UTC (permalink / raw)
To: David Rowley <dgrowleyml@gmail.com>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; Bingshuai Li <lucian1412@outlook.com>; Zhijie Hou <houzhijie22@gmail.com>; Hayato Kuroda (Fujitsu) <kuroda.hayato@fujitsu.com>; Michael Paquier <michael@paquier.xyz>; Alexander Lakhin <exclusion@gmail.com>; pgsql-hackers@lists.postgresql.org <pgsql-hackers@lists.postgresql.org>; mark.dilger@enterprisedb.com <mark.dilger@enterprisedb.com>; Amit Kapila <amit.kapila16@gmail.com>; Masahiko Sawada <sawada.mshk@gmail.com>; Andrey Rachitskiy <pl0h0yp1@gmail.com>; a.kozhemyakin@postgrespro.ru <a.kozhemyakin@postgrespro.ru>
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)
^ permalink raw reply [nested|flat] 53+ messages in thread
* Re: Bug in logical decoding with DDL and subtransactions
@ 2026-10-15 15:32 Tom Lane <tgl@sss.pgh.pa.us>
parent: alvherre@kurilemu.de <alvherre@kurilemu.de>
0 siblings, 0 replies; 53+ messages in thread
From: Tom Lane @ 2026-10-15 15:32 UTC (permalink / raw)
To: alvherre@kurilemu.de <alvherre@kurilemu.de>; +Cc: David Rowley <dgrowleyml@gmail.com>; Bingshuai Li <lucian1412@outlook.com>; Zhijie Hou <houzhijie22@gmail.com>; Hayato Kuroda (Fujitsu) <kuroda.hayato@fujitsu.com>; Michael Paquier <michael@paquier.xyz>; Alexander Lakhin <exclusion@gmail.com>; pgsql-hackers@lists.postgresql.org <pgsql-hackers@lists.postgresql.org>; mark.dilger@enterprisedb.com <mark.dilger@enterprisedb.com>; Amit Kapila <amit.kapila16@gmail.com>; Masahiko Sawada <sawada.mshk@gmail.com>; Andrey Rachitskiy <pl0h0yp1@gmail.com>; a.kozhemyakin@postgrespro.ru <a.kozhemyakin@postgrespro.ru>
"alvherre@kurilemu.de" <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
^ permalink raw reply [nested|flat] 53+ messages in thread
* Re: Bug in logical decoding with DDL and subtransactions
@ 2026-10-17 05:45 Ayush Tiwari <ayushtiwari.slg01@gmail.com>
parent: alvherre@kurilemu.de <alvherre@kurilemu.de>
1 sibling, 1 reply; 53+ messages in thread
From: Ayush Tiwari @ 2026-10-17 05:45 UTC (permalink / raw)
To: alvherre@kurilemu.de <alvherre@kurilemu.de>; +Cc: Bingshuai Li <lucian1412@outlook.com>; Zhijie Hou <houzhijie22@gmail.com>; Hayato Kuroda (Fujitsu) <kuroda.hayato@fujitsu.com>; Michael Paquier <michael@paquier.xyz>; Tom Lane <tgl@sss.pgh.pa.us>; Alexander Lakhin <exclusion@gmail.com>; pgsql-hackers@lists.postgresql.org <pgsql-hackers@lists.postgresql.org>; mark.dilger@enterprisedb.com <mark.dilger@enterprisedb.com>; Amit Kapila <amit.kapila16@gmail.com>; Masahiko Sawada <sawada.mshk@gmail.com>; Andrey Rachitskiy <pl0h0yp1@gmail.com>; a.kozhemyakin@postgrespro.ru <a.kozhemyakin@postgrespro.ru>
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
inline patch 1: src/backend/replication/logical/reorderbuffer.c (+17/-0 lines) download inline-1.patch
--- 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
^ permalink raw reply [nested|flat] 53+ messages in thread
* Re: Bug in logical decoding with DDL and subtransactions
@ 2026-10-17 12:02 Manu <manuelreyesbravo@gmail.com>
parent: Ayush Tiwari <ayushtiwari.slg01@gmail.com>
0 siblings, 1 reply; 53+ messages in thread
From: Manu @ 2026-10-17 12:02 UTC (permalink / raw)
To: Ayush Tiwari <ayushtiwari.slg01@gmail.com>; +Cc: alvherre@kurilemu.de <alvherre@kurilemu.de>; Bingshuai Li <lucian1412@outlook.com>; Zhijie Hou <houzhijie22@gmail.com>; Hayato Kuroda (Fujitsu) <kuroda.hayato@fujitsu.com>; Michael Paquier <michael@paquier.xyz>; Tom Lane <tgl@sss.pgh.pa.us>; Alexander Lakhin <exclusion@gmail.com>; Mark Dilger <mark.dilger@enterprisedb.com>; Amit Kapila <amit.kapila16@gmail.com>; Masahiko Sawada <sawada.mshk@gmail.com>; Andrey Rachitskiy <pl0h0yp1@gmail.com>; a.kozhemyakin@postgrespro.ru <a.kozhemyakin@postgrespro.ru>; pgsql-hackers@lists.postgresql.org
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
^ permalink raw reply [nested|flat] 53+ messages in thread
* Re: Bug in logical decoding with DDL and subtransactions
@ 2026-11-23 09:46 Rajesh Kumar Thandapani <rajeshkumarth@google.com>
0 siblings, 0 replies; 53+ messages in thread
From: Rajesh Kumar Thandapani @ 2026-11-23 09:46 UTC (permalink / raw)
To: Manu <manuelreyesbravo@gmail.com>; Ayush Tiwari <ayushtiwari.slg01@gmail.com>; +Cc: alvherre@kurilemu.de, Bingshuai Li <lucian1412@outlook.com>; Zhijie Hou <houzhijie22@gmail.com>; Hayato Kuroda <kuroda.hayato@fujitsu.com>; Amit Kapila <amit.kapila16@gmail.com>; Masahiko Sawada <sawada.mshk@gmail.com>; pgsql-hackers@lists.postgresql.org
On Sat, Oct 17, 2026 at 12:02 PM Manu <manuelreyesbravo@gmail.com> wrote:
> 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.
Hi Manu, Ayush,
Since this did not seem to get picked up as a formal patch yet, I put
together a v1 patch (attached) building on Ayush's snippet and your
feedback.
On top of the earlier snippet, it also returns early when
toptxn->tuplecids is already empty (so pure DML transactions avoid the
subxacts[] lookups), 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.
On an assert-enabled build of master, decoding a transaction with 50,000
catalog tuplecids followed by 5,000 rolled-back DML subtransactions drops
from ~2310 ms to ~104 ms, and all test_decoding tests pass.
Regards,
Rajesh Kumar Thandapani
Attachments:
v1-0001-Skip-tuplecid-cleanup-scan-when-aborted-subxacts-.patch (application/x-patch, 6.0K) download
From 60c044d3e9030b3cea676c3a8601b721aca700f8 Mon Sep 17 00:00:00 2001
From: Rajesh Kumar Thandapani <rajeshkumarth@google.com>
Date: Thu, 19 Nov 2026 04:40:08 +0000
Subject: [PATCH v1] Skip tuplecid cleanup scan when aborted subxacts have no
catalog changes.
Commit beff3cd0098 added ReorderBufferCleanupAbortedTupleCids() to drop
TUPLECID entries queued by an aborted subtransaction or its subcommitted
children from toptxn->tuplecids. However, it currently scans
toptxn->tuplecids on every known subtransaction abort, even when the
list is empty or none of the aborting xids modified any catalogs.
When a transaction accumulates many tuplecids (for example from creating
temporary tables) and later rolls back many DML-only savepoints or
PL/pgSQL EXCEPTION blocks, decoding spends O(tuplecids * aborts) walking
toptxn->tuplecids without removing anything.
Since SnapBuildProcessNewCid() marks subxid with
RBTXN_HAS_CATALOG_CHANGES before calling ReorderBufferAddNewTupleCids()
and the flag is never cleared, return early when toptxn->tuplecids is
empty or none of the aborting xids has that flag set. Assert this in
ReorderBufferAddNewTupleCids(), and add a permutation to
tuplecid_nested.spec where the outer savepoint writes to a regular table
while its released inner savepoint modifies a catalog table.
Author: Ayush Tiwari <ayushtiwari.slg01@gmail.com>
Author: Rajesh Kumar Thandapani <rajeshkumarth@google.com>
Reviewed-by: Manu <manuelreyesbravo@gmail.com>
Discussion: https://postgr.es/m/CAJTYsWXAQmRfNi1zg7-yeuMc56yeOkq22eyxDiQa_Q+2tD+sGg@mail.gmail.com
---
.../expected/tuplecid_nested.out | 32 +++++++++++++++++++
.../test_decoding/specs/tuplecid_nested.spec | 5 +++
.../replication/logical/reorderbuffer.c | 21 ++++++++++++
3 files changed, 58 insertions(+)
diff --git a/contrib/test_decoding/expected/tuplecid_nested.out b/contrib/test_decoding/expected/tuplecid_nested.out
index 5d816374..a706db11 100644
--- a/contrib/test_decoding/expected/tuplecid_nested.out
+++ b/contrib/test_decoding/expected/tuplecid_nested.out
@@ -30,3 +30,35 @@ COMMIT
stop
(1 row)
+
+starting permutation: s1_init s0_begin s0_topwrite s0_outer s0_outerwrite s0_inner s0_catinsert1 s0_release_inner s0_rollback_outer s2_vacuum s0_catinsert2 s0_commit s1_get_changes
+step s1_init: SELECT 'init' FROM pg_create_logical_replication_slot('tuplecid_nested_slot', 'test_decoding');
+?column?
+--------
+init
+(1 row)
+
+step s0_begin: BEGIN;
+step s0_topwrite: INSERT INTO tbl1 VALUES (0);
+step s0_outer: SAVEPOINT outer_sp;
+step s0_outerwrite: INSERT INTO tbl1 VALUES (1);
+step s0_inner: SAVEPOINT inner_sp;
+step s0_catinsert1: INSERT INTO user_cat VALUES (5, 'e');
+step s0_release_inner: RELEASE SAVEPOINT inner_sp;
+step s0_rollback_outer: ROLLBACK TO SAVEPOINT outer_sp;
+step s2_vacuum: VACUUM user_cat;
+step s0_catinsert2: INSERT INTO user_cat VALUES (6, 'f');
+step s0_commit: COMMIT;
+step s1_get_changes: SELECT data FROM pg_logical_slot_get_changes('tuplecid_nested_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%';
+data
+------------------------------------------
+BEGIN
+table public.tbl1: INSERT: val1[integer]:0
+COMMIT
+(3 rows)
+
+?column?
+--------
+stop
+(1 row)
+
diff --git a/contrib/test_decoding/specs/tuplecid_nested.spec b/contrib/test_decoding/specs/tuplecid_nested.spec
index 8dd52984..eec8673e 100644
--- a/contrib/test_decoding/specs/tuplecid_nested.spec
+++ b/contrib/test_decoding/specs/tuplecid_nested.spec
@@ -54,6 +54,7 @@ setup { SET synchronous_commit=on; }
step "s0_begin" { BEGIN; }
step "s0_topwrite" { INSERT INTO tbl1 VALUES (0); }
step "s0_outer" { SAVEPOINT outer_sp; }
+step "s0_outerwrite" { INSERT INTO tbl1 VALUES (1); }
step "s0_inner" { SAVEPOINT inner_sp; }
step "s0_catinsert1" { INSERT INTO user_cat VALUES (5, 'e'); }
step "s0_release_inner" { RELEASE SAVEPOINT inner_sp; }
@@ -75,3 +76,7 @@ step "s2_vacuum" { VACUUM user_cat; }
# The slot is created before the transaction begins, so the final
# s1_get_changes decodes the whole transaction through its commit.
permutation "s1_init" "s0_begin" "s0_topwrite" "s0_outer" "s0_inner" "s0_catinsert1" "s0_release_inner" "s0_rollback_outer" "s2_vacuum" "s0_catinsert2" "s0_commit" "s1_get_changes"
+
+# Same as above, but outer_sp also does a regular write so it exists in
+# reorderbuffer without RBTXN_HAS_CATALOG_CHANGES.
+permutation "s1_init" "s0_begin" "s0_topwrite" "s0_outer" "s0_outerwrite" "s0_inner" "s0_catinsert1" "s0_release_inner" "s0_rollback_outer" "s2_vacuum" "s0_catinsert2" "s0_commit" "s1_get_changes"
diff --git a/src/backend/replication/logical/reorderbuffer.c b/src/backend/replication/logical/reorderbuffer.c
index 46843985..b52389fc 100644
--- a/src/backend/replication/logical/reorderbuffer.c
+++ b/src/backend/replication/logical/reorderbuffer.c
@@ -3299,6 +3299,24 @@ ReorderBufferCleanupAbortedTupleCids(ReorderBuffer *rb,
/* Get the top-level transaction whose tuplecid list we're to clean */
toptxn = rbtxn_get_toptxn(txn);
+ if (dlist_is_empty(&toptxn->tuplecids))
+ return;
+
+ /*
+ * Skip the scan if none of the aborting xids has catalog changes (the
+ * flag is set before queueing tuplecids and never cleared).
+ */
+ if (!rbtxn_has_catalog_changes(txn))
+ {
+ bool subtxn_has_catalog_changes = false;
+
+ for (int i = 0; !subtxn_has_catalog_changes && i < nsubxacts; i++)
+ subtxn_has_catalog_changes =
+ ReorderBufferXidHasCatalogChanges(rb, subxacts[i]);
+
+ if (!subtxn_has_catalog_changes)
+ return;
+ }
dlist_foreach_modify(it, &toptxn->tuplecids)
{
@@ -3599,6 +3617,9 @@ ReorderBufferAddNewTupleCids(ReorderBuffer *rb,
ReorderBufferChange *change = ReorderBufferAllocChange(rb);
ReorderBufferTXN *txn;
+ /* ReorderBufferCleanupAbortedTupleCids() relies on this flag being set */
+ Assert(ReorderBufferXidHasCatalogChanges(rb, subxid));
+
txn = ReorderBufferTXNByXid(rb, xid, true, NULL, lsn, true);
change->data.tuplecid.locator = locator;
--
2.56.1.750.gf70dc682cf-goog
^ permalink raw reply [nested|flat] 53+ messages in thread
* Re: Bug in logical decoding with DDL and subtransactions
@ 2026-11-23 10:43 alvherre@kurilemu.de <alvherre@kurilemu.de>
parent: Manu <manuelreyesbravo@gmail.com>
0 siblings, 3 replies; 53+ messages in thread
From: alvherre@kurilemu.de @ 2026-11-23 10:43 UTC (permalink / raw)
To: Manu <manuelreyesbravo@gmail.com>; +Cc: Ayush Tiwari <ayushtiwari.slg01@gmail.com>; Bingshuai Li <lucian1412@outlook.com>; Zhijie Hou <houzhijie22@gmail.com>; Hayato Kuroda (Fujitsu) <kuroda.hayato@fujitsu.com>; Michael Paquier <michael@paquier.xyz>; Tom Lane <tgl@sss.pgh.pa.us>; Alexander Lakhin <exclusion@gmail.com>; Mark Dilger <mark.dilger@enterprisedb.com>; Amit Kapila <amit.kapila16@gmail.com>; Masahiko Sawada <sawada.mshk@gmail.com>; Andrey Rachitskiy <pl0h0yp1@gmail.com>; a.kozhemyakin@postgrespro.ru <a.kozhemyakin@postgrespro.ru>; pgsql-hackers@lists.postgresql.org
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)
^ permalink raw reply [nested|flat] 53+ messages in thread
* Re: Bug in logical decoding with DDL and subtransactions
@ 2026-11-23 12:39 Rajesh Kumar Thandapani <rajeshkumarth@google.com>
parent: alvherre@kurilemu.de <alvherre@kurilemu.de>
2 siblings, 1 reply; 53+ messages in thread
From: Rajesh Kumar Thandapani @ 2026-11-23 12:39 UTC (permalink / raw)
To: alvherre@kurilemu.de <alvherre@kurilemu.de>; Manu <manuelreyesbravo@gmail.com>; +Cc: Ayush Tiwari <ayushtiwari.slg01@gmail.com>; Bingshuai Li <lucian1412@outlook.com>; Zhijie Hou <houzhijie22@gmail.com>; Hayato Kuroda (Fujitsu) <kuroda.hayato@fujitsu.com>; Michael Paquier <michael@paquier.xyz>; Tom Lane <tgl@sss.pgh.pa.us>; Alexander Lakhin <exclusion@gmail.com>; Mark Dilger <mark.dilger@enterprisedb.com>; Amit Kapila <amit.kapila16@gmail.com>; Masahiko Sawada <sawada.mshk@gmail.com>; Andrey Rachitskiy <pl0h0yp1@gmail.com>; a.kozhemyakin@postgrespro.ru <a.kozhemyakin@postgrespro.ru>; pgsql-hackers@lists.postgresql.org
On Mon, Nov 23, 2026 at 11:43 AM Alvaro Herrera <alvherre@kurilemu.de> 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
Attachments:
v1-0001-Skip-tuplecid-cleanup-scan-when-aborted-subxacts-.patch (application/x-patch, 6.0K) download
From 60c044d3e9030b3cea676c3a8601b721aca700f8 Mon Sep 17 00:00:00 2001
From: Rajesh Kumar Thandapani <rajeshkumarth@google.com>
Date: Thu, 19 Nov 2026 04:40:08 +0000
Subject: [PATCH v1] Skip tuplecid cleanup scan when aborted subxacts have no
catalog changes.
Commit beff3cd0098 added ReorderBufferCleanupAbortedTupleCids() to drop
TUPLECID entries queued by an aborted subtransaction or its subcommitted
children from toptxn->tuplecids. However, it currently scans
toptxn->tuplecids on every known subtransaction abort, even when the
list is empty or none of the aborting xids modified any catalogs.
When a transaction accumulates many tuplecids (for example from creating
temporary tables) and later rolls back many DML-only savepoints or
PL/pgSQL EXCEPTION blocks, decoding spends O(tuplecids * aborts) walking
toptxn->tuplecids without removing anything.
Since SnapBuildProcessNewCid() marks subxid with
RBTXN_HAS_CATALOG_CHANGES before calling ReorderBufferAddNewTupleCids()
and the flag is never cleared, return early when toptxn->tuplecids is
empty or none of the aborting xids has that flag set. Assert this in
ReorderBufferAddNewTupleCids(), and add a permutation to
tuplecid_nested.spec where the outer savepoint writes to a regular table
while its released inner savepoint modifies a catalog table.
Author: Ayush Tiwari <ayushtiwari.slg01@gmail.com>
Author: Rajesh Kumar Thandapani <rajeshkumarth@google.com>
Reviewed-by: Manu <manuelreyesbravo@gmail.com>
Discussion: https://postgr.es/m/CAJTYsWXAQmRfNi1zg7-yeuMc56yeOkq22eyxDiQa_Q+2tD+sGg@mail.gmail.com
---
.../expected/tuplecid_nested.out | 32 +++++++++++++++++++
.../test_decoding/specs/tuplecid_nested.spec | 5 +++
.../replication/logical/reorderbuffer.c | 21 ++++++++++++
3 files changed, 58 insertions(+)
diff --git a/contrib/test_decoding/expected/tuplecid_nested.out b/contrib/test_decoding/expected/tuplecid_nested.out
index 5d816374..a706db11 100644
--- a/contrib/test_decoding/expected/tuplecid_nested.out
+++ b/contrib/test_decoding/expected/tuplecid_nested.out
@@ -30,3 +30,35 @@ COMMIT
stop
(1 row)
+
+starting permutation: s1_init s0_begin s0_topwrite s0_outer s0_outerwrite s0_inner s0_catinsert1 s0_release_inner s0_rollback_outer s2_vacuum s0_catinsert2 s0_commit s1_get_changes
+step s1_init: SELECT 'init' FROM pg_create_logical_replication_slot('tuplecid_nested_slot', 'test_decoding');
+?column?
+--------
+init
+(1 row)
+
+step s0_begin: BEGIN;
+step s0_topwrite: INSERT INTO tbl1 VALUES (0);
+step s0_outer: SAVEPOINT outer_sp;
+step s0_outerwrite: INSERT INTO tbl1 VALUES (1);
+step s0_inner: SAVEPOINT inner_sp;
+step s0_catinsert1: INSERT INTO user_cat VALUES (5, 'e');
+step s0_release_inner: RELEASE SAVEPOINT inner_sp;
+step s0_rollback_outer: ROLLBACK TO SAVEPOINT outer_sp;
+step s2_vacuum: VACUUM user_cat;
+step s0_catinsert2: INSERT INTO user_cat VALUES (6, 'f');
+step s0_commit: COMMIT;
+step s1_get_changes: SELECT data FROM pg_logical_slot_get_changes('tuplecid_nested_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%';
+data
+------------------------------------------
+BEGIN
+table public.tbl1: INSERT: val1[integer]:0
+COMMIT
+(3 rows)
+
+?column?
+--------
+stop
+(1 row)
+
diff --git a/contrib/test_decoding/specs/tuplecid_nested.spec b/contrib/test_decoding/specs/tuplecid_nested.spec
index 8dd52984..eec8673e 100644
--- a/contrib/test_decoding/specs/tuplecid_nested.spec
+++ b/contrib/test_decoding/specs/tuplecid_nested.spec
@@ -54,6 +54,7 @@ setup { SET synchronous_commit=on; }
step "s0_begin" { BEGIN; }
step "s0_topwrite" { INSERT INTO tbl1 VALUES (0); }
step "s0_outer" { SAVEPOINT outer_sp; }
+step "s0_outerwrite" { INSERT INTO tbl1 VALUES (1); }
step "s0_inner" { SAVEPOINT inner_sp; }
step "s0_catinsert1" { INSERT INTO user_cat VALUES (5, 'e'); }
step "s0_release_inner" { RELEASE SAVEPOINT inner_sp; }
@@ -75,3 +76,7 @@ step "s2_vacuum" { VACUUM user_cat; }
# The slot is created before the transaction begins, so the final
# s1_get_changes decodes the whole transaction through its commit.
permutation "s1_init" "s0_begin" "s0_topwrite" "s0_outer" "s0_inner" "s0_catinsert1" "s0_release_inner" "s0_rollback_outer" "s2_vacuum" "s0_catinsert2" "s0_commit" "s1_get_changes"
+
+# Same as above, but outer_sp also does a regular write so it exists in
+# reorderbuffer without RBTXN_HAS_CATALOG_CHANGES.
+permutation "s1_init" "s0_begin" "s0_topwrite" "s0_outer" "s0_outerwrite" "s0_inner" "s0_catinsert1" "s0_release_inner" "s0_rollback_outer" "s2_vacuum" "s0_catinsert2" "s0_commit" "s1_get_changes"
diff --git a/src/backend/replication/logical/reorderbuffer.c b/src/backend/replication/logical/reorderbuffer.c
index 46843985..b52389fc 100644
--- a/src/backend/replication/logical/reorderbuffer.c
+++ b/src/backend/replication/logical/reorderbuffer.c
@@ -3299,6 +3299,24 @@ ReorderBufferCleanupAbortedTupleCids(ReorderBuffer *rb,
/* Get the top-level transaction whose tuplecid list we're to clean */
toptxn = rbtxn_get_toptxn(txn);
+ if (dlist_is_empty(&toptxn->tuplecids))
+ return;
+
+ /*
+ * Skip the scan if none of the aborting xids has catalog changes (the
+ * flag is set before queueing tuplecids and never cleared).
+ */
+ if (!rbtxn_has_catalog_changes(txn))
+ {
+ bool subtxn_has_catalog_changes = false;
+
+ for (int i = 0; !subtxn_has_catalog_changes && i < nsubxacts; i++)
+ subtxn_has_catalog_changes =
+ ReorderBufferXidHasCatalogChanges(rb, subxacts[i]);
+
+ if (!subtxn_has_catalog_changes)
+ return;
+ }
dlist_foreach_modify(it, &toptxn->tuplecids)
{
@@ -3599,6 +3617,9 @@ ReorderBufferAddNewTupleCids(ReorderBuffer *rb,
ReorderBufferChange *change = ReorderBufferAllocChange(rb);
ReorderBufferTXN *txn;
+ /* ReorderBufferCleanupAbortedTupleCids() relies on this flag being set */
+ Assert(ReorderBufferXidHasCatalogChanges(rb, subxid));
+
txn = ReorderBufferTXNByXid(rb, xid, true, NULL, lsn, true);
change->data.tuplecid.locator = locator;
--
2.56.1.750.gf70dc682cf-goog
^ permalink raw reply [nested|flat] 53+ messages in thread
* Re: Bug in logical decoding with DDL and subtransactions
@ 2026-11-23 23:39 Manu <manuelreyesbravo@gmail.com>
parent: alvherre@kurilemu.de <alvherre@kurilemu.de>
2 siblings, 1 reply; 53+ messages in thread
From: Manu @ 2026-11-23 23:39 UTC (permalink / raw)
To: alvherre@kurilemu.de <alvherre@kurilemu.de>; +Cc: Rajesh Kumar Thandapani <rajeshkumarth@google.com>; Ayush Tiwari <ayushtiwari.slg01@gmail.com>; Bingshuai Li <lucian1412@outlook.com>; Zhijie Hou <houzhijie22@gmail.com>; Hayato Kuroda (Fujitsu) <kuroda.hayato@fujitsu.com>; Amit Kapila <amit.kapila16@gmail.com>; Masahiko Sawada <sawada.mshk@gmail.com>; Michael Paquier <michael@paquier.xyz>; Tom Lane <tgl@sss.pgh.pa.us>; Alexander Lakhin <exclusion@gmail.com>; Mark Dilger <mark.dilger@enterprisedb.com>; Andrey Rachitskiy <pl0h0yp1@gmail.com>; a.kozhemyakin@postgrespro.ru; pgsql-hackers@lists.postgresql.org
Hi Álvaro,
On Mon, Nov 23, 2026 at 7:43 AM Álvaro Herrera <alvherre@kurilemu.de>
wrote:
> Hmm, so I'm inclined to do this in master only, as I don't think
> tuplecid lists are very large generally.
Agreed. In my tests a CREATE TABLE with 100 columns queues about 110
tuplecids, so a 10k list takes some 90 such tables in one
transaction.
Rajesh's v1 upthread passes the same tests as in October, on current
master:
- test_decoding passes. The new permutation fails on the cmin Assert
if the loop over the subxacts is removed.
- The same 60,000 random transactions decode identically to master,
and the new Assert never fired.
- Without asserts, 50k tuplecids followed by 10k DML-only aborts go
from 1056 ms to 19.5 ms.
One nit on its commit message: the empty-list return does not make
pure DML transactions faster than today, since master already does
nothing with an empty list. What it does is keep the new subxacts[]
lookups from costing anything there.
Regards,
Manu
^ permalink raw reply [nested|flat] 53+ messages in thread
* Re: Bug in logical decoding with DDL and subtransactions
@ 2026-11-24 00:15 Michael Paquier <michael@paquier.xyz>
parent: alvherre@kurilemu.de <alvherre@kurilemu.de>
2 siblings, 0 replies; 53+ messages in thread
From: Michael Paquier @ 2026-11-24 00:15 UTC (permalink / raw)
To: alvherre@kurilemu.de <alvherre@kurilemu.de>; +Cc: Manu <manuelreyesbravo@gmail.com>; Ayush Tiwari <ayushtiwari.slg01@gmail.com>; Bingshuai Li <lucian1412@outlook.com>; Zhijie Hou <houzhijie22@gmail.com>; Hayato Kuroda (Fujitsu) <kuroda.hayato@fujitsu.com>; Tom Lane <tgl@sss.pgh.pa.us>; Alexander Lakhin <exclusion@gmail.com>; Mark Dilger <mark.dilger@enterprisedb.com>; Amit Kapila <amit.kapila16@gmail.com>; Masahiko Sawada <sawada.mshk@gmail.com>; Andrey Rachitskiy <pl0h0yp1@gmail.com>; a.kozhemyakin@postgrespro.ru <a.kozhemyakin@postgrespro.ru>; pgsql-hackers@lists.postgresql.org
On Mon, Nov 23, 2026 at 11:43:52AM +0100, Alvaro Herrera wrote:
> 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.
I've read through the suggested patch, and I cannot really get excited
for doing what is an optimization on the back-branches. Targetting
only HEAD sounds fine enough here.
(Note: I've got to look at the original commits pushed for the sake of
this thread for some other work, hence the opinion.)
--
Michael
Attachments:
signature.asc (application/pgp-signature, 832B) download
^ permalink raw reply [nested|flat] 53+ messages in thread
* Re: Bug in logical decoding with DDL and subtransactions
@ 2026-11-24 05:17 Dilip Kumar <dilipbalaut@gmail.com>
parent: Rajesh Kumar Thandapani <rajeshkumarth@google.com>
0 siblings, 0 replies; 53+ messages in thread
From: Dilip Kumar @ 2026-11-24 05:17 UTC (permalink / raw)
To: Rajesh Kumar Thandapani <rajeshkumarth@google.com>; +Cc: alvherre@kurilemu.de <alvherre@kurilemu.de>; Manu <manuelreyesbravo@gmail.com>; Ayush Tiwari <ayushtiwari.slg01@gmail.com>; Bingshuai Li <lucian1412@outlook.com>; Zhijie Hou <houzhijie22@gmail.com>; Hayato Kuroda (Fujitsu) <kuroda.hayato@fujitsu.com>; Michael Paquier <michael@paquier.xyz>; Tom Lane <tgl@sss.pgh.pa.us>; Alexander Lakhin <exclusion@gmail.com>; Mark Dilger <mark.dilger@enterprisedb.com>; Amit Kapila <amit.kapila16@gmail.com>; Masahiko Sawada <sawada.mshk@gmail.com>; Andrey Rachitskiy <pl0h0yp1@gmail.com>; a.kozhemyakin@postgrespro.ru <a.kozhemyakin@postgrespro.ru>; pgsql-hackers@lists.postgresql.org
On Mon, Nov 23, 2026 at 6:10 PM Rajesh Kumar Thandapani
<rajeshkumarth@google.com> wrote:
>
> On Mon, Nov 23, 2026 at 11:43 AM Alvaro Herrera <alvherre@kurilemu.de> 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.
Yeah logically it makes sense to skip scanning the tuplecid list for
every aborted subtransaction, when it has not made any catalog
changes. I will review it one more time, but at high level it looks
good. And I think we should do this on master only.
--
Regards,
Dilip Kumar
Google
^ permalink raw reply [nested|flat] 53+ messages in thread
* Re: Bug in logical decoding with DDL and subtransactions
@ 2026-11-24 06:05 Rajesh Kumar Thandapani <rajeshkumarth@google.com>
parent: Manu <manuelreyesbravo@gmail.com>
0 siblings, 0 replies; 53+ messages in thread
From: Rajesh Kumar Thandapani @ 2026-11-24 06:05 UTC (permalink / raw)
To: Manu <manuelreyesbravo@gmail.com>; +Cc: alvherre@kurilemu.de, Dilip Kumar <dilipbalaut@gmail.com>; Michael Paquier <michael@paquier.xyz>; Ayush Tiwari <ayushtiwari.slg01@gmail.com>; Bingshuai Li <lucian1412@outlook.com>; Zhijie Hou <houzhijie22@gmail.com>; Hayato Kuroda <kuroda.hayato@fujitsu.com>; Amit Kapila <amit.kapila16@gmail.com>; Masahiko Sawada <sawada.mshk@gmail.com>; Tom Lane <tgl@sss.pgh.pa.us>; Alexander Lakhin <exclusion@gmail.com>; Mark Dilger <mark.dilger@enterprisedb.com>; Andrey Rachitskiy <pl0h0yp1@gmail.com>; a.kozhemyakin@postgrespro.ru; pgsql-hackers@lists.postgresql.org
On Mon, Nov 23, 2026 at 8:39 PM Manu <manuelreyesbravo@gmail.com> wrote:
> One nit on its commit message: the empty-list return does not make
> pure DML transactions faster than today, since master already does
> nothing with an empty list. What it does is keep the new subxacts[]
> lookups from costing anything there.
Good catch, thanks for testing v1 and pointing that out!
Attached is v2 with the commit message updated to clarify that the
dlist_is_empty(&toptxn->tuplecids) check avoids adding subxacts[] lookup
overhead when there are no tuplecids to clean up (no code changes from
v1).
Thanks Michael and Dilip for taking a look as well.
Regards,
Rajesh Kumar Thandapani
Attachments:
v2-0001-Skip-tuplecid-cleanup-scan-when-aborted-subxacts-.patch (application/x-patch, 6.1K) download
From 956906fe8317101b06838f6ca8ae1d01cf264674 Mon Sep 17 00:00:00 2001
From: Rajesh Kumar Thandapani <rajeshkumarth@google.com>
Date: Thu, 19 Nov 2026 04:40:08 +0000
Subject: [PATCH v2] Skip tuplecid cleanup scan when aborted subxacts have no
catalog changes.
Commit beff3cd0098 added ReorderBufferCleanupAbortedTupleCids() to drop
TUPLECID entries queued by an aborted subtransaction or its subcommitted
children from toptxn->tuplecids. However, it currently scans
toptxn->tuplecids on every known subtransaction abort, even when none of
the aborting xids modified any catalogs.
When a transaction accumulates many tuplecids (for example from creating
temporary tables) and later rolls back many DML-only savepoints or
PL/pgSQL EXCEPTION blocks, decoding spends O(tuplecids * aborts) walking
toptxn->tuplecids without removing anything.
Since SnapBuildProcessNewCid() marks subxid with
RBTXN_HAS_CATALOG_CHANGES before calling ReorderBufferAddNewTupleCids()
and the flag is never cleared, skip the walk when none of the aborting
xids has that flag set. Return early when toptxn->tuplecids is empty so
the new subxacts[] lookups add no overhead when there are no tuplecids
to clean up. Assert this invariant in ReorderBufferAddNewTupleCids(),
and add a permutation to tuplecid_nested.spec where the outer savepoint
writes to a regular table while its released inner savepoint modifies a
catalog table.
Author: Ayush Tiwari <ayushtiwari.slg01@gmail.com>
Author: Rajesh Kumar Thandapani <rajeshkumarth@google.com>
Reviewed-by: Manu <manuelreyesbravo@gmail.com>
Discussion: https://postgr.es/m/CAJTYsWXAQmRfNi1zg7-yeuMc56yeOkq22eyxDiQa_Q+2tD+sGg@mail.gmail.com
---
.../expected/tuplecid_nested.out | 32 +++++++++++++++++++
.../test_decoding/specs/tuplecid_nested.spec | 5 +++
.../replication/logical/reorderbuffer.c | 21 ++++++++++++
3 files changed, 58 insertions(+)
diff --git a/contrib/test_decoding/expected/tuplecid_nested.out b/contrib/test_decoding/expected/tuplecid_nested.out
index 5d816374..a706db11 100644
--- a/contrib/test_decoding/expected/tuplecid_nested.out
+++ b/contrib/test_decoding/expected/tuplecid_nested.out
@@ -30,3 +30,35 @@ COMMIT
stop
(1 row)
+
+starting permutation: s1_init s0_begin s0_topwrite s0_outer s0_outerwrite s0_inner s0_catinsert1 s0_release_inner s0_rollback_outer s2_vacuum s0_catinsert2 s0_commit s1_get_changes
+step s1_init: SELECT 'init' FROM pg_create_logical_replication_slot('tuplecid_nested_slot', 'test_decoding');
+?column?
+--------
+init
+(1 row)
+
+step s0_begin: BEGIN;
+step s0_topwrite: INSERT INTO tbl1 VALUES (0);
+step s0_outer: SAVEPOINT outer_sp;
+step s0_outerwrite: INSERT INTO tbl1 VALUES (1);
+step s0_inner: SAVEPOINT inner_sp;
+step s0_catinsert1: INSERT INTO user_cat VALUES (5, 'e');
+step s0_release_inner: RELEASE SAVEPOINT inner_sp;
+step s0_rollback_outer: ROLLBACK TO SAVEPOINT outer_sp;
+step s2_vacuum: VACUUM user_cat;
+step s0_catinsert2: INSERT INTO user_cat VALUES (6, 'f');
+step s0_commit: COMMIT;
+step s1_get_changes: SELECT data FROM pg_logical_slot_get_changes('tuplecid_nested_slot', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0') WHERE data NOT LIKE '%user_cat%';
+data
+------------------------------------------
+BEGIN
+table public.tbl1: INSERT: val1[integer]:0
+COMMIT
+(3 rows)
+
+?column?
+--------
+stop
+(1 row)
+
diff --git a/contrib/test_decoding/specs/tuplecid_nested.spec b/contrib/test_decoding/specs/tuplecid_nested.spec
index 8dd52984..eec8673e 100644
--- a/contrib/test_decoding/specs/tuplecid_nested.spec
+++ b/contrib/test_decoding/specs/tuplecid_nested.spec
@@ -54,6 +54,7 @@ setup { SET synchronous_commit=on; }
step "s0_begin" { BEGIN; }
step "s0_topwrite" { INSERT INTO tbl1 VALUES (0); }
step "s0_outer" { SAVEPOINT outer_sp; }
+step "s0_outerwrite" { INSERT INTO tbl1 VALUES (1); }
step "s0_inner" { SAVEPOINT inner_sp; }
step "s0_catinsert1" { INSERT INTO user_cat VALUES (5, 'e'); }
step "s0_release_inner" { RELEASE SAVEPOINT inner_sp; }
@@ -75,3 +76,7 @@ step "s2_vacuum" { VACUUM user_cat; }
# The slot is created before the transaction begins, so the final
# s1_get_changes decodes the whole transaction through its commit.
permutation "s1_init" "s0_begin" "s0_topwrite" "s0_outer" "s0_inner" "s0_catinsert1" "s0_release_inner" "s0_rollback_outer" "s2_vacuum" "s0_catinsert2" "s0_commit" "s1_get_changes"
+
+# Same as above, but outer_sp also does a regular write so it exists in
+# reorderbuffer without RBTXN_HAS_CATALOG_CHANGES.
+permutation "s1_init" "s0_begin" "s0_topwrite" "s0_outer" "s0_outerwrite" "s0_inner" "s0_catinsert1" "s0_release_inner" "s0_rollback_outer" "s2_vacuum" "s0_catinsert2" "s0_commit" "s1_get_changes"
diff --git a/src/backend/replication/logical/reorderbuffer.c b/src/backend/replication/logical/reorderbuffer.c
index 2917d971..bbea2150 100644
--- a/src/backend/replication/logical/reorderbuffer.c
+++ b/src/backend/replication/logical/reorderbuffer.c
@@ -3300,6 +3300,24 @@ ReorderBufferCleanupAbortedTupleCids(ReorderBuffer *rb,
/* Get the top-level transaction whose tuplecid list we're to clean */
toptxn = rbtxn_get_toptxn(txn);
+ if (dlist_is_empty(&toptxn->tuplecids))
+ return;
+
+ /*
+ * Skip the scan if none of the aborting xids has catalog changes (the
+ * flag is set before queueing tuplecids and never cleared).
+ */
+ if (!rbtxn_has_catalog_changes(txn))
+ {
+ bool subtxn_has_catalog_changes = false;
+
+ for (int i = 0; !subtxn_has_catalog_changes && i < nsubxacts; i++)
+ subtxn_has_catalog_changes =
+ ReorderBufferXidHasCatalogChanges(rb, subxacts[i]);
+
+ if (!subtxn_has_catalog_changes)
+ return;
+ }
dlist_foreach_modify(it, &toptxn->tuplecids)
{
@@ -3600,6 +3618,9 @@ ReorderBufferAddNewTupleCids(ReorderBuffer *rb,
ReorderBufferChange *change = ReorderBufferAllocChange(rb);
ReorderBufferTXN *txn;
+ /* ReorderBufferCleanupAbortedTupleCids() relies on this flag being set */
+ Assert(ReorderBufferXidHasCatalogChanges(rb, subxid));
+
txn = ReorderBufferTXNByXid(rb, xid, true, NULL, lsn, true);
change->data.tuplecid.locator = locator;
--
2.56.1.831.g720f3f5937-goog
^ permalink raw reply [nested|flat] 53+ messages in thread
end of thread, other threads:[~2026-11-24 06:05 UTC | newest]
Thread overview: 53+ messages (download: mbox mbox.gz follow: Atom feed)
-- links below jump to the message on this page --
2026-04-30 04:59 Bug in logical decoding with DDL and subtransactions Mark Dilger <mark.dilger@enterprisedb.com>
2026-08-04 02:33 ` kid <lucian1412@outlook.com>
2026-08-11 11:00 ` Bingshuai Li <lucian1412@outlook.com>
2026-08-12 03:39 ` Bingshuai Li <lucian1412@outlook.com>
2026-08-13 02:18 ` Bingshuai Li <lucian1412@outlook.com>
2026-08-15 08:17 ` Bingshuai Li <lucian1412@outlook.com>
2026-08-27 07:38 ` Bingshuai Li <lucian1412@outlook.com>
2026-09-17 06:00 ` Alexander Lakhin <exclusion@gmail.com>
2026-09-17 08:33 ` Bingshuai Li <lucian1412@outlook.com>
2026-09-17 11:16 ` alvherre@kurilemu.de <alvherre@kurilemu.de>
2026-09-17 16:42 ` Bingshuai Li <lucian1412@outlook.com>
2026-09-18 01:39 ` Bingshuai Li <lucian1412@outlook.com>
2026-09-18 02:19 ` Bingshuai Li <lucian1412@outlook.com>
2026-09-28 05:18 ` Hayato Kuroda (Fujitsu) <kuroda.hayato@fujitsu.com>
2026-09-29 18:31 ` Tom Lane <tgl@sss.pgh.pa.us>
2026-09-29 21:00 ` Alexander Lakhin <exclusion@gmail.com>
2026-09-29 21:17 ` Tom Lane <tgl@sss.pgh.pa.us>
2026-09-30 03:05 ` Michael Paquier <michael@paquier.xyz>
2026-09-30 05:07 ` Michael Paquier <michael@paquier.xyz>
2026-09-30 09:12 ` Bingshuai Li <lucian1412@outlook.com>
2026-09-30 09:58 ` Bingshuai Li <lucian1412@outlook.com>
2026-10-05 10:13 ` Hayato Kuroda (Fujitsu) <kuroda.hayato@fujitsu.com>
2026-10-07 09:55 ` Zhijie Hou <houzhijie22@gmail.com>
2026-10-07 10:48 ` alvherre@kurilemu.de <alvherre@kurilemu.de>
2026-10-07 14:25 ` alvherre@kurilemu.de <alvherre@kurilemu.de>
2026-10-08 09:16 ` Bingshuai Li <lucian1412@outlook.com>
2026-10-09 03:13 ` Hayato Kuroda (Fujitsu) <kuroda.hayato@fujitsu.com>
2026-10-09 09:18 ` Bingshuai Li <lucian1412@outlook.com>
2026-10-14 18:15 ` alvherre@kurilemu.de <alvherre@kurilemu.de>
2026-10-09 15:28 ` Zhijie Hou <houzhijie22@gmail.com>
2026-10-09 18:11 ` Álvaro Herrera <alvherre@kurilemu.de>
2026-10-11 21:40 ` Álvaro Herrera <alvherre@kurilemu.de>
2026-10-12 17:15 ` alvherre@kurilemu.de <alvherre@kurilemu.de>
2026-10-13 09:17 ` Hayato Kuroda (Fujitsu) <kuroda.hayato@fujitsu.com>
2026-10-14 07:16 ` Zhijie Hou <houzhijie22@gmail.com>
2026-10-14 08:37 ` Bingshuai Li <lucian1412@outlook.com>
2026-10-14 18:04 ` alvherre@kurilemu.de <alvherre@kurilemu.de>
2026-10-14 18:10 ` alvherre@kurilemu.de <alvherre@kurilemu.de>
2026-10-15 04:55 ` David Rowley <dgrowleyml@gmail.com>
2026-10-15 05:24 ` Tom Lane <tgl@sss.pgh.pa.us>
2026-10-15 10:34 ` David Rowley <dgrowleyml@gmail.com>
2026-10-15 14:41 ` alvherre@kurilemu.de <alvherre@kurilemu.de>
2026-10-15 15:32 ` Tom Lane <tgl@sss.pgh.pa.us>
2026-10-17 05:45 ` Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-10-17 12:02 ` Manu <manuelreyesbravo@gmail.com>
2026-11-23 10:43 ` alvherre@kurilemu.de <alvherre@kurilemu.de>
2026-11-23 12:39 ` Rajesh Kumar Thandapani <rajeshkumarth@google.com>
2026-11-24 05:17 ` Dilip Kumar <dilipbalaut@gmail.com>
2026-11-23 23:39 ` Manu <manuelreyesbravo@gmail.com>
2026-11-24 06:05 ` Rajesh Kumar Thandapani <rajeshkumarth@google.com>
2026-11-24 00:15 ` Michael Paquier <michael@paquier.xyz>
2026-09-30 16:33 ` Zhijie Hou <houzhijie22@gmail.com>
2026-11-23 09:46 Re: Bug in logical decoding with DDL and subtransactions Rajesh Kumar Thandapani <rajeshkumarth@google.com>
This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox