From 787e613be96ae7c3d3a28e7d4370187a6004effb Mon Sep 17 00:00:00 2001
From: xnervwang <xnervwang@gmail.com>
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

