Hi hackers,
In our tests, a new TOAST value reused a deleted value's ID. When we
tried to read the new value on a read replica, the read failed:
ERROR: unexpected chunk number 0 (expected 1) for toast value N in
pg_toast_M
I reproduced this on community PostgreSQL 18.6 with a hot standby. The
table had autovacuum disabled and column v set to STORAGE EXTERNAL.
Inserting a 3000-byte value produced two chunks. I read the value's ID
with pg_column_toast_chunk_id(v) before deleting it. Once no snapshot
was older than the delete, I looked up the chunks in the TOAST table
with enable_seqscan and enable_bitmapscan off. The index lookup marked
both TOAST index entries LP_DEAD while both heap chunks were still
LP_NORMAL.
I ran CHECKPOINT, stopped the primary, and set the next OID with:
pg_resetwal -o <the old value ID>
After restarting the primary, I inserted a different 3000-byte value. It
got the old ID. The primary returned the new value, but SELECT on the
hot standby failed with the error above.
My reading is that since commit 0408e1ed599 (2018), GetNewOidWithIndex()
has probed the index with SnapshotAny so that deleted rows count as
collisions until they are pruned. Outside recovery,
RelationGetIndexScan() sets ignore_killed_tuples, so nbtree skips
LP_DEAD entries and the probe misses the old chunks. During recovery the
standby follows those entries as well as the new ones, and
HeapTupleSatisfiesToast() accepts chunk 0 of both values because it
checks only xmin.
In GetNewOidWithIndex(), the attached patch clears ignore_killed_tuples
on the index scan before the first systable_getnext(). It adds the
reproducer as a TAP test. The commit message explains why a standby
cannot rely on the LP_DEAD marks.
In 2016, Andres Freund wrote that to make GetNewOidWithIndex() safe,
"we'd at least make hint bit writes by the scan in GetNewOidWithIndex()
durable, and likely also disable the killtuples optimization". I think
the hint bit writes need not be durable because, with the attached
patch, the probe checks the heap for each matching index entry whether
or not it is marked LP_DEAD.
https://www.postgresql.org/message-id/[email protected]
The first email in "Bugs in TOAST handling, OID assignment and redo
recovery", the thread behind 0408e1ed599, lists killing the index
pointer as one way the window closes for readers. Does that reasoning
also cover a pointer that is already killed when the OID probe runs?
That's when I saw the ID get reused.
https://www.postgresql.org/message-id/CABOikdOgWT2hHkYG3Wwo2cyZJq2zfs1FH0FgX-=h4olosxh...@mail.gmail.com
I left toastrel_valueid_exists() alone. It makes the same SnapshotAny
probe, but runs only during CLUSTER and VACUUM FULL. I couldn't find a
case where an LP_DEAD entry there would cause a collision.
The attached .txt makes the change in index_beginscan_internal(), so any
index scan using SnapshotAny keeps LP_DEAD entries. I kept the change in
GetNewOidWithIndex() because the broader version also affects the
index-ordered copy in CLUSTER/REPACK, logical replication's
update_deleted conflict check, and extension index scans that use
SnapshotAny. Would index_beginscan_internal() be a better place for
this?
The new test fails without the fix. With either change, both the new
test and check-world pass.
Thanks,
Xnerv Wang
Amazon Web Services
diff --git a/src/backend/access/index/indexam.c
b/src/backend/access/index/indexam.c
index db811056991..6307ff0aede 100644
--- a/src/backend/access/index/indexam.c
+++ b/src/backend/access/index/indexam.c
@@ -341,6 +341,13 @@ index_beginscan_internal(Relation indexRelation, Relation
heapRelation,
scan->xs_snapshot = snapshot;
scan->instrument = instrument;
+ /*
+ * A scan with SnapshotAny must also return dead rows that have not been
+ * pruned yet, so it cannot skip index entries marked LP_DEAD.
+ */
+ if (snapshot == SnapshotAny)
+ scan->ignore_killed_tuples = false;
+
/*
* Initialize heap-side scan state when a heap relation is provided.
* Bitmap index scans don't provide one.
From 787e613be96ae7c3d3a28e7d4370187a6004effb Mon Sep 17 00:00:00 2001
From: xnervwang <[email protected]>
Date: Wed, 25 Nov 2026 20:29:44 +0000
Subject: [PATCH v1] Check LP_DEAD index entries before reusing an OID
After OID wraparound, GetNewOidWithIndex() can reuse a deleted TOAST
value's ID while its chunks are still in the heap. Commit 0408e1ed599
switched its systable_beginscan() probe from SnapshotDirty to
SnapshotAny. Outside recovery, RelationGetIndexScan() sets
ignore_killed_tuples, so nbtree skips LP_DEAD entries even with
SnapshotAny.
The primary reads the new value correctly, but in recovery
ignore_killed_tuples is false and a hot standby visits both generations
of (chunk_id, chunk_seq) entries. HeapTupleSatisfiesToast() checks only
xmin; both pass SnapshotToast and the standby reports:
ERROR: unexpected chunk number 0 (expected 1) for toast value N in pg_toast_M
The standby error persists until VACUUM removes the old generation. The
standby cannot rely on LP_DEAD marks to skip those entries. The marks
are hints that reach WAL only in full-page images, so a crash can lose
them and a standby may lack them even after promotion. Catalog reads use
MVCC snapshots that exclude the deleted rows.
In GetNewOidWithIndex(), clear ignore_killed_tuples before the first
systable_getnext() if the scan uses an index. SnapshotAny then counts
live and unpruned dead rows as collisions. Heap scans used during
reindexing or with ignore_system_indexes already see unpruned rows. Each
matching LP_DEAD entry costs one extra heap fetch. Reuse waits for
pruning, as 0408e1ed599 already required for unmarked entries.
The new TAP test in src/test/recovery sets the next OID with pg_resetwal
and reads the value on a hot standby; it fails without the fix.
---
src/backend/catalog/catalog.c | 13 ++++
src/test/recovery/Makefile | 3 +-
src/test/recovery/meson.build | 1 +
src/test/recovery/t/062_toast_oid_reuse.pl | 80 ++++++++++++++++++++++
4 files changed, 96 insertions(+), 1 deletion(-)
create mode 100644 src/test/recovery/t/062_toast_oid_reuse.pl
diff --git a/src/backend/catalog/catalog.c b/src/backend/catalog/catalog.c
index 6248e0f3ce9..8df8d150d77 100644
--- a/src/backend/catalog/catalog.c
+++ b/src/backend/catalog/catalog.c
@@ -22,6 +22,7 @@
#include "access/genam.h"
#include "access/htup_details.h"
+#include "access/relscan.h"
#include "access/table.h"
#include "access/transam.h"
#include "catalog/catalog.h"
@@ -564,6 +565,18 @@ GetNewOidWithIndex(Relation relation, Oid indexId, AttrNumber oidcolumn)
scan = systable_beginscan(relation, indexId, true,
SnapshotAny, 1, &key);
+ /*
+ * Also check index entries that are marked LP_DEAD, since the rows
+ * they point to may not have been pruned yet. The mark is only a
+ * hint: a crash can lose it, and a standby ignores it during recovery
+ * and may not have it after promotion. Wherever it is missing or
+ * ignored, reusing the OID of a deleted TOAST value whose chunks are
+ * still in the heap would make SnapshotToast return the chunks of
+ * both values.
+ */
+ if (scan->iscan)
+ scan->iscan->ignore_killed_tuples = false;
+
collides = HeapTupleIsValid(systable_getnext(scan));
systable_endscan(scan);
diff --git a/src/test/recovery/Makefile b/src/test/recovery/Makefile
index e90e0b1ad4c..ba776063759 100644
--- a/src/test/recovery/Makefile
+++ b/src/test/recovery/Makefile
@@ -9,7 +9,8 @@
#
#-------------------------------------------------------------------------
-EXTRA_INSTALL=contrib/pg_prewarm \
+EXTRA_INSTALL=contrib/pageinspect \
+ contrib/pg_prewarm \
contrib/pg_stat_statements \
contrib/pg_visibility \
contrib/test_decoding \
diff --git a/src/test/recovery/meson.build b/src/test/recovery/meson.build
index cb3df6ed895..19d8bdba818 100644
--- a/src/test/recovery/meson.build
+++ b/src/test/recovery/meson.build
@@ -70,6 +70,7 @@ tests += {
't/059_remote_apply_status_interval.pl',
't/060_multixact_crashed_updater.pl',
't/061_recovery_target_prefetch.pl',
+ 't/062_toast_oid_reuse.pl',
],
},
}
diff --git a/src/test/recovery/t/062_toast_oid_reuse.pl b/src/test/recovery/t/062_toast_oid_reuse.pl
new file mode 100644
index 00000000000..0cfd546ee5f
--- /dev/null
+++ b/src/test/recovery/t/062_toast_oid_reuse.pl
@@ -0,0 +1,80 @@
+# Copyright (c) 2026, PostgreSQL Global Development Group
+
+# A new TOAST value must not get the value ID of a deleted value whose chunks
+# are still in the TOAST table, even when the index entries for those chunks
+# are marked LP_DEAD. A hot standby does not skip LP_DEAD entries, so it
+# would find the chunks of both values.
+
+use strict;
+use warnings FATAL => 'all';
+
+use PostgreSQL::Test::Cluster;
+use PostgreSQL::Test::Utils;
+use Test::More;
+
+my $node_primary = PostgreSQL::Test::Cluster->new('primary');
+$node_primary->init(allows_streaming => 1);
+$node_primary->append_conf('postgresql.conf', 'autovacuum = off');
+$node_primary->start;
+
+$node_primary->safe_psql('postgres', 'CREATE EXTENSION pageinspect');
+
+# With STORAGE EXTERNAL, each value is stored uncompressed in two chunks.
+my $toastrel = $node_primary->safe_psql(
+ 'postgres', q{
+CREATE TABLE toast_reuse (v text)
+ WITH (autovacuum_enabled = off, toast.autovacuum_enabled = off);
+ALTER TABLE toast_reuse ALTER COLUMN v SET STORAGE EXTERNAL;
+INSERT INTO toast_reuse VALUES (repeat('a', 3000));
+SELECT reltoastrelid::regclass FROM pg_class WHERE relname = 'toast_reuse';
+});
+my $valueid = $node_primary->safe_psql('postgres',
+ 'SELECT pg_column_toast_chunk_id(v) FROM toast_reuse');
+
+$node_primary->safe_psql('postgres', 'DELETE FROM toast_reuse');
+
+# Flush the index page first, so that it is not being written out while the
+# index scan below sets its LP_DEAD bits.
+$node_primary->safe_psql('postgres', 'CHECKPOINT');
+
+# Fetch the deleted chunks through the index. The heap tuples are dead to
+# everyone, so the scan marks their index entries LP_DEAD, while the heap
+# page has too much free space to be pruned.
+$node_primary->safe_psql(
+ 'postgres', qq{
+SET enable_seqscan = off;
+SET enable_bitmapscan = off;
+SELECT count(*) FROM $toastrel WHERE chunk_id = '$valueid';
+});
+my $ndead = $node_primary->safe_psql('postgres',
+ "SELECT count(*) FROM bt_page_items('${toastrel}_index', 1) WHERE dead");
+is($ndead, '2',
+ 'index entries of the deleted TOAST value are marked LP_DEAD');
+
+# Make the deleted value's ID the next OID to be assigned, as if the OID
+# counter had wrapped around.
+$node_primary->stop;
+command_ok(
+ [ 'pg_resetwal', '--next-oid' => $valueid, $node_primary->data_dir ],
+ 'set next OID to the deleted TOAST value ID');
+$node_primary->start;
+
+$node_primary->safe_psql('postgres',
+ "INSERT INTO toast_reuse VALUES (repeat('b', 3000))");
+my $newid = $node_primary->safe_psql('postgres',
+ 'SELECT pg_column_toast_chunk_id(v) FROM toast_reuse');
+isnt($newid, $valueid,
+ 'new TOAST value does not reuse the ID of a deleted value');
+
+$node_primary->backup('backup');
+my $node_standby = PostgreSQL::Test::Cluster->new('standby');
+$node_standby->init_from_backup($node_primary, 'backup', has_streaming => 1);
+$node_standby->start;
+$node_primary->wait_for_replay_catchup($node_standby);
+
+my ($ret, $stdout, $stderr) = $node_standby->psql('postgres',
+ "SELECT v = repeat('b', 3000) FROM toast_reuse");
+is($ret, 0, 'standby can read the new TOAST value') or diag($stderr);
+is($stdout, 't', 'standby reads the new TOAST value correctly');
+
+done_testing();
--
2.47.3