VACUUM of a user_catalog_table started before the first logical slot exists keeps the data horizon and prunes row versions the slot's catalog_xmin protects (wrong decoding output) =================================================================================================================================================================================== AI-generated bug report from the AI Annex Report ID: 01a11f56-4edd-74dd-9a36-aebb8a0a9a80 Filed: 2026-10-09 06:25:12 UTC Severity: 70/100 Blamed commit: 67c20979ce72b8c236622e5603f9775968ff501c ## Summary Since logical decoding is switched on dynamically by the presence of a logical slot (commit 67c20979ce72, "Toggle logical decoding dynamically based on logical slot presence"), the macro `RelationIsAccessibleInLogicalDecoding()` can change from false to true while the server runs, because it is gated on `XLogLogicalInfoActive()`. `GlobalVisHorizonKindForRel()` uses that macro to decide whether a `user_catalog_table = true` relation is pruned against the catalog horizon (which honours slot `catalog_xmin`) or the data horizon (which does not). `heap_vacuum_rel()` makes that choice once, at the start of the relation, by caching the pointer returned by `GlobalVisTestFor(rel)`. If no logical slot exists when a VACUUM (or autovacuum) of a user catalog table starts, the data horizon is chosen. When the first logical slot is created while that VACUUM is still scanning, the process barrier flips `XLogLogicalInfo` in the vacuum backend, but the cached `vacrel->vistest` still points at `GlobalVisDataRels`. Any later horizon refresh in that backend rewrites `GlobalVisDataRels` from the data horizon, which ignores the new slot's `catalog_xmin`, so `lazy_scan_prune()` removes row versions whose xmax is at or above the slot's `catalog_xmin`. Such a refresh happens on a natural code path: nbtree index vacuuming calls `GetOldestNonRemovableTransactionId()` from `_bt_pendingfsm_finalize()` whenever it deleted index pages, and a mid-scan index pass is routine for a bloated table. The slot then decodes with a historic snapshot that is missing user catalog rows it is entitled to see. A plugin that reads the user catalog (the purpose of `user_catalog_table`) silently produces wrong output for transactions that committed before the deleting transaction. Reproduced on master 412848dac37f and REL_19_STABLE 2359968b449a with `wal_level = replica`. Not reachable before v19, where the macro's value could not change during a server's lifetime (`wal_level` needs a restart, and `ALTER TABLE ... SET (user_catalog_table)` conflicts with VACUUM's lock). ## Reproduction Tested at master 412848dac37f2e4455e1505f83f0af0f3d28a67d (debug build, cassert) and REL_19_STABLE 2359968b449a0fd53cfc04d4a644ae02370adec6. Server settings: `wal_level = replica` (the default), `autovacuum = off` (only to keep the test deterministic). `pageinspect` and `test_decoding` are used for inspection. Setup: a user catalog table with a btree index, enough dead tuples on its first pages that VACUUM has to run an index pass in the middle of the heap scan, and live rows on its last pages: ```sql CREATE EXTENSION pageinspect; CREATE TABLE uc (id int, pad text) WITH (user_catalog_table = true); INSERT INTO uc SELECT g, repeat('x', 500) FROM generate_series(1, 4000) g; CREATE INDEX uc_idx1 ON uc (id); DELETE FROM uc WHERE id <= 2000; -- dead tuples on early pages SHOW effective_wal_level; -- replica: no logical slot yet ``` Session 1: a deliberately slow VACUUM with a tiny dead-item budget so that index vacuuming runs mid-scan (267 heap pages, about 100 ms per page, roughly 30 s in total): ```sql SET vacuum_cost_delay = '100ms'; SET vacuum_cost_limit = 1; SET maintenance_work_mem = '64kB'; VACUUM (VERBOSE) uc; ``` Session 2, a couple of seconds after the VACUUM has started: ```sql SELECT pg_create_logical_replication_slot('s1', 'test_decoding'); SELECT slot_name, catalog_xmin FROM pg_replication_slots; SHOW effective_wal_level; -- now "logical" DELETE FROM uc WHERE id > 3900; SELECT pg_current_xact_id(); ``` Observed: `catalog_xmin` = 694 and `pg_current_xact_id()` = 694. The deleting transaction's xid equals the slot's `catalog_xmin`, so by definition its row versions must be kept. VACUUM VERBOSE output, actual: ``` INFO: finished vacuuming "postgres.public.uc": index scans: 5 pages: 0 removed, 267 remain, 267 scanned (100.00% of total), 0 eagerly scanned tuples: 2100 removed, 1900 remain, 0 are dead but not yet removable removable cutoff: 694, which was 1 XIDs old when operation ended new relfrozenxid: 691, which is 1 XIDs ahead of previous value frozen: 0 pages from table (0.00% of total) had 0 tuples frozen visibility map: 267 pages set all-visible, 140 pages set all-frozen (0 were all-visible) index scan needed: 141 pages from table (52.81% of total) had 2100 dead item identifiers removed index "uc_idx1": pages: 13 in total, 5 newly deleted, 5 currently deleted, 0 reusable ``` Expected (and observed when the slot is created *before* the VACUUM starts, everything else identical): ``` tuples: 2000 removed, 2000 remain, 100 are dead but not yet removable ``` pageinspect confirms the 100 versions deleted by xid 694 are gone: ```sql SELECT count(*) FROM generate_series(0, pg_relation_size('uc') / 8192 - 1) b, LATERAL heap_page_items(get_raw_page('uc', b::int)) WHERE t_xmax = 694; -- bug: 0 control (slot created before VACUUM): 100 ``` ### Decoding-visible consequence To show the effect on decoding, I used a minimal output plugin that, in its change callback, scans `public.uc` through the historic snapshot and reports what it sees (this is exactly what `user_catalog_table` is for; `test_decoding` does not read user catalogs). The relevant part: ```c static void uc_change(LogicalDecodingContext *ctx, ReorderBufferTXN *txn, Relation relation, ReorderBufferChange *change) { Oid ucoid; Relation ucrel; TableScanDesc scan; HeapTuple tup; int64 nvisible = 0, maxid = 0; /* catalog lookups use the historic snapshot set up by decoding */ ucoid = RangeVarGetRelid(makeRangeVar("public", "uc", -1), NoLock, true); ucrel = table_open(ucoid, AccessShareLock); scan = table_beginscan(ucrel, GetCatalogSnapshot(ucoid), 0, NULL, 0); while ((tup = heap_getnext(scan, ForwardScanDirection)) != NULL) { bool isnull; Datum d = heap_getattr(tup, 1, RelationGetDescr(ucrel), &isnull); nvisible++; if (!isnull && DatumGetInt32(d) > maxid) maxid = DatumGetInt32(d); } table_endscan(scan); table_close(ucrel, AccessShareLock); OutputPluginPrepareWrite(ctx, true); appendStringInfo(ctx->out, "table %s: user catalog uc visible rows: " INT64_FORMAT ", max id: " INT64_FORMAT, RelationGetRelationName(relation), nvisible, maxid); OutputPluginWrite(ctx, true); } ``` (`begin_cb`/`commit_cb` print `BEGIN`/`COMMIT`; `startup_cb` sets `OUTPUT_PLUGIN_TEXTUAL_OUTPUT`. On master the library must be listed in `output_plugin_libraries`.) Same setup as above plus `CREATE TABLE t (a int)`. While the slow VACUUM of `uc` runs, in session 2: ```sql SELECT pg_create_logical_replication_slot('s1', 'uc_decoding'); INSERT INTO t VALUES (1); -- T1: committed BEFORE the delete DELETE FROM uc WHERE id > 3900; -- D INSERT INTO t VALUES (2); -- T2: committed after the delete ``` After the VACUUM finishes: ```sql SELECT data FROM pg_logical_slot_get_changes('s1', NULL, NULL); ``` Actual (slot created during the VACUUM): ``` table t: user catalog uc visible rows: 1900, max id: 3900 <- T1, wrong table uc: ... (100 DELETE changes) table t: user catalog uc visible rows: 1900, max id: 3900 <- T2 ``` Expected, and observed both with the slot created before the VACUUM and with no VACUUM at all: ``` table t: user catalog uc visible rows: 2000, max id: 4000 <- T1 table uc: ... (100 DELETE changes) table t: user catalog uc visible rows: 1900, max id: 3900 <- T2 ``` T1 committed before D, so its historic snapshot treats D as not yet committed and must see the 100 rows D later deleted. They were pruned, so the plugin sees the catalog as of a later point in the stream. No error is raised; the output is simply wrong. ## Analysis Code references are to master 412848dac37f. 1. `heap_vacuum_rel()` (src/backend/access/heap/vacuumlazy.c:794) does `vacrel->vistest = GlobalVisTestFor(rel)` once per relation, after `vacuum_get_cutoffs()`. The comment above it already notes the intention to possibly "recompute vistest from time to time". 2. `GlobalVisTestFor()` (src/backend/storage/ipc/procarray.c) returns a pointer to one of four static `GlobalVisState` structs, selected by `GlobalVisHorizonKindForRel()`: ```c else if (IsCatalogRelation(rel) || RelationIsAccessibleInLogicalDecoding(rel)) return VISHORIZON_CATALOG; else if (!RELATION_IS_LOCAL(rel)) return VISHORIZON_DATA; ``` with (src/include/utils/rel.h) ```c #define RelationIsAccessibleInLogicalDecoding(relation) \ (XLogLogicalInfoActive() && \ RelationNeedsWAL(relation) && \ (IsCatalogRelation(relation) || \ RelationIsUsedAsCatalogTable(relation))) ``` and `XLogLogicalInfoActive()` being `wal_level >= logical || XLogLogicalInfo`, where `XLogLogicalInfo` is the backend-local cache maintained by src/backend/replication/logical/logicalctl.c. With `wal_level = replica` and no logical slot, a user catalog table is therefore a VISHORIZON_DATA relation. System catalogs are not affected: `IsCatalogRelation()` is checked unconditionally. 3. Slot creation (`create_logical_replication_slot()` in src/backend/replication/slotfuncs.c, likewise the walsender path) calls `EnsureLogicalDecodingEnabled()` -> `EnableLogicalDecoding()`, which sets the shared flag and waits for `PROCSIGNAL_BARRIER_UPDATE_XLOG_LOGICAL_INFO`. The vacuum backend absorbs it in `vacuum_delay_point()`'s `CHECK_FOR_INTERRUPTS()` (`ProcessBarrierUpdateXLogLogicalInfo()` updates immediately since VACUUM holds no XID). From then on `GlobalVisTestFor(rel)` *would* return `&GlobalVisCatalogRels`, but nothing revisits the pointer the running VACUUM cached; the barrier handler has no knowledge of in-progress vacuums. Only afterwards does `CreateInitDecodingContext()` compute the slot's `catalog_xmin` via `GetOldestSafeDecodingTransactionId()` and publish it with `ReplicationSlotsComputeRequiredXmin()`. 4. `ComputeXidHorizons()` (procarray.c:1854) derives the two horizons as "catalog = data, backed up to slot_catalog_xmin"; the data horizon never sees `catalog_xmin`. It also skips `PROC_IN_VACUUM` backends (procarray.c:1770), so the vacuum's own snapshot does not hold the horizon back either. 5. Pruning: `heap_prune_satisfies_vacuum()` (src/backend/access/heap/pruneheap.c:1488) asks `GlobalVisTestIsRemovableXid(prstate->vistest, dead_after, true)`. With the start-of-VACUUM boundaries alone the deleter's xid lies at or above `definitely_needed`, so nothing is removed (that is why the control variants keep the rows). The failure needs the vacuum backend to refresh its `GlobalVisState`s after the deleting transaction committed. `GlobalVisUpdateApply()` then sets `GlobalVisDataRels.maybe_needed` from `data_oldest_nonremovable`, which is past the deleter, and the next prune of the page removes the versions. 6. The natural refresh: nbtree's `_bt_pendingfsm_finalize()` (src/backend/access/nbtree/nbtpage.c:3049, since 9dd963ae2534 in v14) calls `GetOldestNonRemovableTransactionId(heaprel)` precisely to "forcibly update the XID horizon state for this backend" so it can recycle pages it deleted in the same VACUUM. Index vacuuming runs in the middle of the heap scan whenever the dead-item store fills up, so for a bloated user catalog table with a btree index this is ordinary behaviour. Attaching gdb to the vacuum backend in the reproduction (SIGUSR1 passed through) shows exactly this chain as the only mid-scan horizon update: ``` GlobalVisUpdateApply <- ComputeXidHorizons <- GetOldestNonRemovableTransactionId <- _bt_pendingfsm_finalize <- btvacuumscan <- btbulkdelete <- index_bulk_delete <- vac_bulkdel_one_index <- lazy_vacuum_all_indexes <- lazy_vacuum <- lazy_scan_heap <- heap_vacuum_rel ``` Any other code path that computes a snapshot or horizon in the vacuum backend mid-scan (for example a catalog snapshot taken on a syscache miss) has the same effect; without such a refresh the rows survive by luck, not by design. Forcing a single `GetLatestSnapshot()` in the vacuum backend with gdb, on a table without indexes, pruned the 100 versions as well. 7. Why only VACUUM: on-access pruning (`heap_page_prune_opt()`) calls `GlobalVisTestFor()` on every invocation, so it switches horizons as soon as the barrier is absorbed, which happens before the slot's `catalog_xmin` even exists. The one lag is a backend that holds an XID when the barrier arrives (`XLogLogicalInfoUpdatePending`, logicalctl.c:217); its data horizon is bounded by its own XID, which is older than any transaction whose row versions the new slot can need, so it cannot remove them. Autovacuum runs the same `heap_vacuum_rel()` code and is exposed identically (the setting `effective_wal_level` flips under it in the same way); I did not drive the reproduction through an autovacuum worker. Freezing is not affected: freeze decisions are bounded by the start-of-VACUUM `OldestXmin`, which is never above the new slot's `catalog_xmin`. 8. Why 67c20979ce72 is to blame: before it, `XLogLogicalInfoActive()` reduced to `wal_level >= WAL_LEVEL_LOGICAL`, a postmaster-start constant, and `user_catalog_table` cannot be toggled under a running VACUUM, so the horizon kind of a relation could not change during a VACUUM. The commit made the macro dynamic without adapting `GlobalVisHorizonKindForRel()` or the vacuum code that caches its result (neither procarray.c nor vacuumlazy.c is touched by it). REL_19_STABLE contains the commit and reproduces the problem; REL_18_STABLE and older do not have dynamic logical decoding. ## Candidate fixes 1. Make the horizon choice independent of the WAL level. In `GlobalVisHorizonKindForRel()`, treat a WAL-logged relation with `user_catalog_table = true` as VISHORIZON_CATALOG whether or not `XLogLogicalInfoActive()`: ```c else if (IsCatalogRelation(rel) || RelationIsAccessibleInLogicalDecoding(rel) || (RelationNeedsWAL(rel) && RelationIsUsedAsCatalogTable(rel))) return VISHORIZON_CATALOG; ``` This mirrors how system catalogs are already handled unconditionally. It costs nothing when no logical slot exists: the catalog horizon only differs from the data horizon by `slot_catalog_xmin`, which is invalid then. Verified against the reproduction (see Testing). The remaining design question is whether `RelationIsAccessibleInLogicalDecoding()` should keep its WAL-level gate for the WAL-logging decisions in heapam.c (yes) while horizon selection drops it; a short comment at the call site would capture that. 2. Alternatively, re-evaluate `GlobalVisTestFor(rel)` in VACUUM at the points where the horizon can be refreshed (after each `lazy_vacuum()` round, or before each `heap_page_prune_and_freeze()` call). This closes the VACUUM window but leaves the general hazard that `GlobalVisHorizonKindForRel()` depends on a value that changes under callers that cache its result. 3. Making `EnableLogicalDecoding()` wait for in-progress VACUUMs of user catalog tables would also work but adds a new interlock to slot creation for little gain. No patch is attached because option 1, while small, deserves a regression test with an injection point between `GlobalVisTestFor()` and the heap scan, and the choice between 1 and 2 is a design call. ## Testing All runs on the setup from Reproduction, `wal_level = replica`. Outcome for the 100 row versions deleted by the slot's `catalog_xmin` xid, per variant: - no index, slot created mid-VACUUM: kept (no mid-scan horizon refresh happens, so the stale `definitely_needed` bound refuses the xid); - same, plus DDL and GRANT churn on the table during the VACUUM: kept (the vacuum backend does not process sinval messages mid-scan); - no index, slot mid-VACUUM, one `GetLatestSnapshot()` forced in the vacuum backend with gdb after the delete: REMOVED; - one btree index, mid-scan index pass, slot mid-VACUUM, master: REMOVED (gdb trace: the only mid-scan horizon update comes from `_bt_pendingfsm_finalize()`); - two btree indexes, `VACUUM (PARALLEL 2)`, slot mid-VACUUM, master: REMOVED; - one btree index, slot mid-VACUUM, REL_19_STABLE 2359968b449a: REMOVED; - one btree index, slot created before the VACUUM: kept ("100 are dead but not yet removable"); - one btree index, decoding still enabled from an earlier slot when the VACUUM starts: kept; - one btree index, slot mid-VACUUM, candidate fix 1 applied (run as the decoding scenario below): kept, "100 are dead but not yet removable", and T1 decodes correctly (2000 rows, max id 4000). Decoding with the user-catalog-reading plugin: wrong output for T1 (1900 rows visible) with the slot created mid-VACUUM; correct (2000) with the slot created first or with no VACUUM. ## Prior discussion I found no report of this in the pgsql-hackers or pgsql-bugs archives (searched for `user_catalog_table` together with `effective_wal_level`, `catalog_xmin` and horizon terms), nor any upstream commit since 2026-08 touching the horizon choice. The original thread for the feature is: ``` https://postgr.es/m/CAD21AoCVLeLYq09pQPaWs+Jwdni5FuJ8v2jgq-u9_uFbcp6UbA@mail.gmail.com ```