Review
Prevent foreign key references to unlogged partitions
- Proposal version
- 4
- CommitFest entry
- 7472
- Base commit
- 9ebc9a458c38465cd9609814cfc9ca3a2f46fef5
Summary
Reviewed Zsolt Parragi's v4 patch series (4 master patches plus 3
nocfbot-v4-REL_17 backpatch patches, posted 2026-11-15) against
master at commit 9ebc9a458c38465cd9609814cfc9ca3a2f46fef5:
v4-0001:pgbench: don't disable--unlogged-tableswhen partitioningv4-0002: Disallow foreign keys referencing unlogged partitionsv4-0003: Check foreign keys after adding them inALTER TABLE SET LOGGEDv4-0004: Don't undotable_rewriteevent trigger changes inALTER TABLE
None of these patches (nor the separate pgbench or table_rewrite
threads mentioned in the discussion) have been committed to master.
Verdict: Good core fixes in 0002 and 0003, but not ready to commit as
a series. v4-0004 introduces a verified regression (firing
table_rewrite triggers before forbidden-rewrite checks) and should be
dropped in favor of the separate re-entrancy fix; pg_upgrade --check
and minor-release backpatch breakage remain unaddressed; v4-0001 has
an undiscussed WAL tradeoff for pgbench_branches and missing TAP
assertions; and the REL_17 backpatch contains a lock-upgrade deadlock
hazard, a list leak, and behavioral divergence from master.
Applying, Building, and Testing
- All 4 master patches apply cleanly with
git amon9ebc9a458c38465cd9609814cfc9ca3a2f46fef5. git diff --check: clean.pgindent: clean (zero diff).- Debug/cassert build (
ninja) and documentation build (postgres-full.xml): clean, zero warnings. meson test regress/regress pgbench/001_pgbench_with_server: passed (243/243 regression subtests, 479/479 pgbench subtests).- Additionally ran a live test against
v4-0004confirming theuser_catalog_tableevent trigger regression described below.
Detailed Code Findings
1. v4-0004: Regression Firing table_rewrite Early (Blocker)
In src/backend/commands/tablecmds.c, v4-0004 moves
EventTriggerTableRewrite() above OldHeap = table_open(tab->relid, NoLock) (lines 5976-6050). Previously, three rewrite-disallowing guards
ran before the trigger fired:
IsSystemRelation(OldHeap)(line 5987)RelationIsUsedAsCatalogTable(OldHeap)(line 5993, reachable in plain SQL viaWITH (user_catalog_table = true))RELATION_IS_OTHER_TEMP(OldHeap)(line 6005)
With v4-0004 applied, table_rewrite event triggers now fire even
when the rewrite is forbidden and immediately rejected. Verified live:
CREATE TABLE ucat (a int) WITH (user_catalog_table = true);
CREATE FUNCTION ev_notice() RETURNS event_trigger LANGUAGE plpgsql AS $$
BEGIN
RAISE NOTICE 'table_rewrite FIRED on %',
pg_event_trigger_table_rewrite_oid()::regclass;
END;
$$;
CREATE EVENT TRIGGER ev_tr ON table_rewrite
EXECUTE FUNCTION ev_notice();
ALTER TABLE ucat ALTER COLUMN a TYPE bigint;
-- NOTICE: table_rewrite FIRED on ucat
-- ERROR: cannot rewrite table "ucat" used as a catalog table
A trigger could even alter user_catalog_table inside the callback to
bypass the guard. Furthermore, moving the trigger does not solve the
underlying re-entrancy problem (a table_rewrite trigger can still
DROP TABLE or ALTER TABLE ADD/DROP COLUMN on tab->relid,
invalidating tab->oldDesc captured in Phase 2, or have its
tablespace/AM/persistence changes overwritten if the outer command also
set tab->newTableSpace/tab->chgPersistence).
As Shihao Zhong noted in message 7, a separate thread addresses the root
cause by prohibiting DDL on the table being rewritten inside
table_rewrite triggers. v4-0004 should be dropped from this series
(or, if pursued separately, must keep the three prohibition checks ahead
of EventTriggerTableRewrite()).
2. v4-0002: Clean Fix, Upgrade/Backpatch Unaddressed (Major)
Repeating the permanent-to-unlogged check in addFkRecurseReferenced()
(tablecmds.c:11626) cleanly covers all PG 18+ entry points: existing
unlogged partitions on ATAddForeignKeyConstraint, CREATE TABLE ... PARTITION OF, ATTACH PARTITION (including multi-level sub-partition
trees), NOT VALID and NOT ENFORCED FKs, self-referencing partitioned
tables, and ShareRowExclusiveLock / AccessExclusiveLock concurrency
against SET UNLOGGED.
Concerns to address:
pg_upgrade --checkand backpatch risk: As Shihao Zhong demonstrated in message 9, existing PG 12-19 databases (including anything created bypgbench -i --unlogged-tables --partitions=2 --foreign-keyson PG 18/19!) passpg_upgrade --checkand then fail mid-upgrade during schema restore. Adding a pre-upgrade check insrc/bin/pg_upgrade/check.c(similar tocheck_for_not_null_inheritance()) should be seriously considered formaster. Likewise, backpatching0002to stable minor releases risks breakingpg_dump/pg_restoreof existing production clusters and needs explicit committer sign-off.errdetailassumption:addFkRecurseReferenced()has 4 call sites, includingDetachPartitionFinalize()(tablecmds.c:22704) which passes top-levelrefdRel. Checkingpkrel->rd_rel->relispartitionbefore emitting the partition-specificerrdetailis safer against already-inconsistent catalogs.- Test gaps in
foreign_key.sql: Add tests for partitioned referencing table -> partitioned referenced table with unlogged partition, self-referencing partitioned table,NOT VALID/NOT ENFORCEDFKs, and directCREATE UNLOGGED TABLE ... PARTITION OFunder a sub-partitioned table.
3. v4-0003: Solid Phase-3 Check with Minor Nits
Splitting ATCheckPersistenceForeignKeys() out of
ATPrepChangePersistence() and running it at both the start and end of
ATRewriteTables() (tablecmds.c:5911,6200) cleanly fixes Fujii
Masao's SET LOGGED, ADD FOREIGN KEY bypass, avoids rewriting/WAL bloat
on existing FK failures (Shihao Zhong's v3 finding), catches
partner-table mutations from USING expressions and event triggers, and
fixes ALTER TABLE u SET LOGGED, DROP CONSTRAINT ....
Minor nits:
- Sequences:
AT_SetLogged/AT_SetUnLoggedalso applies toRELKIND_SEQUENCE, sotab->chgPersistenceis true for sequences. Guarding with&& tab->relkind != RELKIND_SEQUENCEavoids two pointlesspg_constraintindex scans per sequence. - Lock release: Existing code inside
ATCheckPersistenceForeignKeyscallsrelation_close(foreignrel, AccessShareLock)(releasing early). No concurrent race occurs onmasterbecausetab->relidholdsAccessExclusiveLockuntil commit, but closing withNoLockwould be cleaner defensively. - Missing positive test: Add a regression test for
ALTER TABLE ... SET LOGGED, DROP CONSTRAINT ....
4. v4-0001: Thread Dependency & pgbench_branches WAL Tradeoff
- Contrary to message 6 stating later patches do not depend on
0001,src/bin/pgbench/t/001_pgbench_with_server.pl:132,149runspgbench --initialize --foreign-keys --unlogged-tables --partitions=2(and3). Without0001,pgbench_historystays permanent while referencing unloggedpgbench_accountspartitions, so0002breaks thepgbenchtest suite immediately. v4-0001keepspgbench_branchespermanent unconditionally whenever--partitionsis used, even without--foreign-keys. Because every defaulttpcb-liketransaction updatespgbench_branches, this forces WAL generation and commit flushes on every transaction despite--unlogged-tables. The only reason to keep it permanent without--foreign-keysis two-step initialization (-I dtgpfollowed later by-I f). This tradeoff should be explicitly discussed on-list (e.g., gating onforeign_keysvs keeping unconditional).001_pgbench_with_server.plshould querypg_class.relpersistenceto verify the expected permanent/unlogged table set.doc/src/sgml/ref/pgbench.sgmlis clear and matches the patch.
5. REL_17 Backpatch Issues (nocfbot-v4-REL_17-0001..0003)
- Lock-upgrade deadlock hazard (
REL_17-0001line 86):FindStoredRelWithPersistence()acquiresAccessShareLockviafind_all_inheritors(), after whichaddFkRecurseReferenced()/addFkRecurseReferencing()immediately upgrade those same partitions toShareRowExclusiveLock/AccessExclusiveLock. Pass the caller's stronger lock mode instead. - Memory leak (
REL_17-0001lines 85-101):relsis never freed withlist_free(rels). - Upgrade divergence vs
master:REL_17-0001explicitly allows and testsCREATE TABLE self (a int PK, b int REFERENCES self) PARTITION BY RANGE (a); CREATE UNLOGGED TABLE self1 PARTITION OF self ...(and permanent partitionedfkwith only unlogged leaves), whichv4-0002onmasterrejects. Even a patched PG 17 database would failpg_upgradeto PG 18+. REL_17-0003carries the samev4-0004event-trigger regression.
Community Discussion and Consensus
Eight substantive messages across Zsolt Parragi, Aleksander Alekseev,
Fujii Masao, and Shihao Zhong. Aleksander's brief RfC applied only to v2
(before 0003, 0004, and the REL_17 patches existed). Fujii found
the SET LOGGED, ADD CONSTRAINT bypass and asked about pre-18 unlogged
partitioned tables, but has not reviewed v3 or v4. Shihao Zhong caught
v3's WAL bloat (verified fixed in v4), flagged the 0004 thread
overlap, and asked in message 9 about pg_upgrade --check (currently
unanswered). Backpatch policy and 0001/0004 scope still need
committer direction.
Scores
- Assessment (62/100): Clear motivation and clean, minimal core
fixes in
0002and0003that build and pass all tests cleanly, but held back by the verifiedv4-0004event-trigger regression, unaddressedpg_upgrade --check/ backpatch implications, thepgbench_branchesWAL tradeoff and missing TAP assertions in0001, and lock-upgrade / leak / divergence bugs inREL_17-0001. - Consensus (45/100): Clear agreement on the underlying bugs and v4
WAL-bloat fix, but no committer review on v3/v4, unanswered
pg_upgrade --checkquestion, and unsettled scope for0001,0004, and backpatching.