Report
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)
- Severity
- 70
- Blamed commit
- 67c20979ce72b8c236622e5603f9775968ff501c REL_19_STABLE, master
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:
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):
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:
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:
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:
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:
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:
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.
-
heap_vacuum_rel()(src/backend/access/heap/vacuumlazy.c:794) doesvacrel->vistest = GlobalVisTestFor(rel)once per relation, aftervacuum_get_cutoffs(). The comment above it already notes the intention to possibly "recompute vistest from time to time". -
GlobalVisTestFor()(src/backend/storage/ipc/procarray.c) returns a pointer to one of four staticGlobalVisStatestructs, selected byGlobalVisHorizonKindForRel():else if (IsCatalogRelation(rel) || RelationIsAccessibleInLogicalDecoding(rel)) return VISHORIZON_CATALOG; else if (!RELATION_IS_LOCAL(rel)) return VISHORIZON_DATA;with (src/include/utils/rel.h)
#define RelationIsAccessibleInLogicalDecoding(relation) \ (XLogLogicalInfoActive() && \ RelationNeedsWAL(relation) && \ (IsCatalogRelation(relation) || \ RelationIsUsedAsCatalogTable(relation)))and
XLogLogicalInfoActive()beingwal_level >= logical || XLogLogicalInfo, whereXLogLogicalInfois the backend-local cache maintained by src/backend/replication/logical/logicalctl.c. Withwal_level = replicaand no logical slot, a user catalog table is therefore a VISHORIZON_DATA relation. System catalogs are not affected:IsCatalogRelation()is checked unconditionally. -
Slot creation (
create_logical_replication_slot()in src/backend/replication/slotfuncs.c, likewise the walsender path) callsEnsureLogicalDecodingEnabled()->EnableLogicalDecoding(), which sets the shared flag and waits forPROCSIGNAL_BARRIER_UPDATE_XLOG_LOGICAL_INFO. The vacuum backend absorbs it invacuum_delay_point()'sCHECK_FOR_INTERRUPTS()(ProcessBarrierUpdateXLogLogicalInfo()updates immediately since VACUUM holds no XID). From then onGlobalVisTestFor(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 doesCreateInitDecodingContext()compute the slot'scatalog_xminviaGetOldestSafeDecodingTransactionId()and publish it withReplicationSlotsComputeRequiredXmin(). -
ComputeXidHorizons()(procarray.c:1854) derives the two horizons as "catalog = data, backed up to slot_catalog_xmin"; the data horizon never seescatalog_xmin. It also skipsPROC_IN_VACUUMbackends (procarray.c:1770), so the vacuum's own snapshot does not hold the horizon back either. -
Pruning:
heap_prune_satisfies_vacuum()(src/backend/access/heap/pruneheap.c:1488) asksGlobalVisTestIsRemovableXid(prstate->vistest, dead_after, true). With the start-of-VACUUM boundaries alone the deleter's xid lies at or abovedefinitely_needed, so nothing is removed (that is why the control variants keep the rows). The failure needs the vacuum backend to refresh itsGlobalVisStates after the deleting transaction committed.GlobalVisUpdateApply()then setsGlobalVisDataRels.maybe_neededfromdata_oldest_nonremovable, which is past the deleter, and the next prune of the page removes the versions. -
The natural refresh: nbtree's
_bt_pendingfsm_finalize()(src/backend/access/nbtree/nbtpage.c:3049, since 9dd963ae2534 in v14) callsGetOldestNonRemovableTransactionId(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_relAny 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. -
Why only VACUUM: on-access pruning (
heap_page_prune_opt()) callsGlobalVisTestFor()on every invocation, so it switches horizons as soon as the barrier is absorbed, which happens before the slot'scatalog_xmineven 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 sameheap_vacuum_rel()code and is exposed identically (the settingeffective_wal_levelflips 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-VACUUMOldestXmin, which is never above the new slot'scatalog_xmin. -
Why 67c20979ce72 is to blame: before it,
XLogLogicalInfoActive()reduced towal_level >= WAL_LEVEL_LOGICAL, a postmaster-start constant, anduser_catalog_tablecannot 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 adaptingGlobalVisHorizonKindForRel()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
-
Make the horizon choice independent of the WAL level. In
GlobalVisHorizonKindForRel(), treat a WAL-logged relation withuser_catalog_table = trueas VISHORIZON_CATALOG whether or notXLogLogicalInfoActive():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 whetherRelationIsAccessibleInLogicalDecoding()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. -
Alternatively, re-evaluate
GlobalVisTestFor(rel)in VACUUM at the points where the horizon can be refreshed (after eachlazy_vacuum()round, or before eachheap_page_prune_and_freeze()call). This closes the VACUUM window but leaves the general hazard thatGlobalVisHorizonKindForRel()depends on a value that changes under callers that cache its result. -
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_neededbound 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