public inbox for [email protected]  
help / color / mirror / Atom feed
From: Amit Langote <[email protected]>
To: Noah Misch <[email protected]>
Cc: Junwang Zhao <[email protected]>
Cc: Ayush Tiwari <[email protected]>
Cc: Nikolay Samokhvalov <[email protected]>
Cc: pgsql-hackers mailing list <[email protected]>
Cc: Andrey Borodin <[email protected]>
Cc: Kirk Wolak <[email protected]>
Subject: Re: PG19 FK fast path: OOB write and missed FK checks during batched
Date: Thu, 9 Jul 2026 20:37:04 +0900
Message-ID: <CA+HiwqGHa3tc6MZFSLyLrvwySdrmpkb1TqkH2jGd3HtKGGZ6cQ@mail.gmail.com> (raw)
In-Reply-To: <CA+HiwqGRorZfmC1WJ+vanLjOawrwjMP1Jgf1XgVOuumiyKGg5g@mail.gmail.com>
References: <CA+HiwqHUz50YqJn4XiNsSLN2c+9eYBy1af=y_dfdJTsz5BmbJg@mail.gmail.com>
	<CAM527d_2OpJ3KCOT1QqGh4neCPpgZTgM+VUxTqVgOSweOzTDQw@mail.gmail.com>
	<CA+HiwqFBXTTy3KcfGVxqxkhX5zV99R7=s2EwkxMiiWnVbyTpyw@mail.gmail.com>
	<CAJTYsWVgHCNDZb2F62F+aELnKJO2BWtHaAXcN-AmgPPP+GAnUQ@mail.gmail.com>
	<CA+HiwqELE-eyOfBBEmpr_eGf-04PUvZg5BjypW2CMHbed5QGhA@mail.gmail.com>
	<CAEG8a3JhZwvdeedTvQCvvXgVkeb6ENW2haiHfxnXkXbv3NMmjg@mail.gmail.com>
	<CA+HiwqG4Psv+777t8FsSpOTtMeqgBYTYfD8EXHYQmCwVcprC_g@mail.gmail.com>
	<CAEG8a3L6avXJNnk1BBZZvDG8dR15FWZdK8RALuZ4SLpgXTw3xg@mail.gmail.com>
	<CA+HiwqHHLyjtk_4LoNkoFYfHQJy9LjDhydKDHn=UHCxu=Qo6Qg@mail.gmail.com>
	<CA+HiwqFwUwakVfcmC2-AQEjO2kgqfy8n0qqxcMkvDBsLGdMgjA@mail.gmail.com>
	<[email protected]>
	<CA+HiwqGRorZfmC1WJ+vanLjOawrwjMP1Jgf1XgVOuumiyKGg5g@mail.gmail.com>

On Mon, Jul 6, 2026 at 11:29 PM Amit Langote <[email protected]> wrote:
> On Mon, Jul 6, 2026 at 7:21 AM Noah Misch <[email protected]> wrote:
> >
> > On Fri, Jun 12, 2026 at 11:46:07AM +0900, Amit Langote wrote:
> > > I've pushed these now.  Thank you everyone.
> >
> > commit 4113873 wrote:
> > >     Confine RI fast-path batching to the top transaction level
> >
> > I discourage this fix strategy, for three reasons:
> >
> > 1. It slows "BEGIN; SAVEPOINT s; COPY table_with_fk FROM ..." by the ~1.6x
> >    batching benefit, compared to omitting the SAVEPOINT.  That's a bad user
> >    experience not seen elsewhere.  Starting a high number of subtransactions
> >    is expensive, but wrapping a long-running transaction body in one
> >    subtransaction hasn't been a performance reducer.
>
> Ok, I agree it's a wart.
>
> > 2. It departs from the PostgreSQL norm of tracking resources by
> >    subtransaction.  You can see normal handling in many AbortSubTransaction()
> >    callees, e.g. AtEOSubXact_LargeObject().  This in turn makes the change
> >    harder to verify as correct.
> >
> > 3. It doesn't seem to have simplified code much, compared to our normal
> >    subxact-based approach.
>
> Fair, I added a special case, which I can see now doesn't actually
> simplify things.  I'll rework it to track batches per subtransaction
> the normal way.

0001 does this. It drops the top-level confinement and adds
AtEOSubXact_RI(), called from Commit/AbortSubTransaction() after the
subtransaction's ResourceOwnerRelease(). On abort it discards only the
entries opened by the ending subtransaction, identified by a subid
stamped on each entry at creation; it closes nothing itself, since the
ResourceOwner has already released those relations. Entries opened at
an outer level are left alone, so an inner subxact abort during
outer-level trigger firing no longer discards the outer statement's
batch. This follows the AtEOSubXact_* pattern you pointed at rather
than the special case I had.

> > >     First, on subtransaction abort ri_FastPathSubXactCallback discarded the
> > >     entire cache.  An entry's batch holds rows buffered by the enclosing
> > >     transaction, not just the aborting subxact -- the cache is keyed by
> > >     constraint, so a single entry can mix rows from multiple subxact levels.
> >
> > That would imply having started a subtransaction and then added to the batch
> > without an intervening pair of CommandCounterIncrement() and
> > AfterTriggerBeginQuery().  That's an invalid thing for C code to do, so I'd
> > make it an error if a batch would contain rows from different subtransactions.
>
> Agreed. I confirmed a batch is flushed at AfterTriggerEndQuery and
> deferred checks don't populate a batch until they fire at top-level
> commit, so an entry is always at a single subxact level. The "mixes
> levels" justification in my commit message was a hypothesis I never
> verified, and it's wrong; a can't-happen assert is most likely the
> right thing.

Attached 0003 adds such an assert: Assert(fpentry->subid ==
GetCurrentSubTransactionId()) in ri_FastPathBatchAdd(), so every row
added to an entry comes from the subtransaction that created it. It
doesn't fire anywhere in the regression tests. AtEOSubXact_RI() relies
on this invariant to identify an aborting subtransaction's entries by
their stamped subid.

> > (This relates to the reentrancy bug fixed in 0e47bb5.  With an intervening
> > CommandCounterIncrement() and AfterTriggerBeginQuery(), reusing the outer
> > batch is wrong even without subtransactions: it would check with the wrong
> > snapshot.  Each level of reentrancy needs to finish its FK checks separately,
> > even if the batch buffer were unbounded.)
> >
> > >     An internal subxact abort during after-trigger firing (e.g. a PL/pgSQL
> > >     BEGIN ... EXCEPTION block) therefore dropped buffered rows
> >
> > I suspect a subxact abort during after-trigger firing can still cause a
> > different problem via AfterTriggerEndQuery():
> >
> >   AfterTriggerEndQuery(EState *estate)
> >   {
> >   ...
> >         afterTriggers.firing_depth++;
> >
> > AfterTriggerEndSubXact() doesn't undo this increment.  Having identified that
> > as suspect, I asked Opus 4.8 to try to confirm or refute bug reachability.  I
> > have not personally verified its finding, but it said:
> >
> >   CLAUDE [CONFIRMED -- reachable bug; your instinct is right]: firing_depth is ++/-- in matched
> >   pairs inside AfterTriggerEndQuery/FireDeferred/SetState with NO PG_TRY, and AfterTriggerEndSubXact
> >   resets firing_batch_callbacks but NOT firing_depth. So a trigger ERROR caught by an outer
> >   subtransaction (PL/pgSQL EXCEPTION) skips the -- and strands firing_depth>0 for the rest of the
> >   xact. Its sole consumer is AfterTriggerIsActive() -> the RI_FKey_check batching gate; the only
> >   RI check that runs OUTSIDE genuine trigger firing is ALTER TABLE / VALIDATE CONSTRAINT per-row
> >   validation. With firing_depth stranded, that validation is wrongly routed into ri_FastPathBatchAdd.
> >   Repro (per-row forced via REFERENCES-only, no SELECT, so RI_Initial_Check bails):
> >     CONTROL: per-row-validated ALTER ADD FK with violating row 99 -> errors AT the ALTER (correct).
> >     BUG: run a caught FK violation first (DO/EXCEPTION), then the same ALTER in the same xact ->
> >       the ALTER does NOT error, marks convalidated=t, emits "WARNING: resource was not closed:
> >       relation pk2 / pk2_pkey / TupleDesc" (a resource-owner leak), and defers the violation to
> >       COMMIT. Consequences: resource leak + FK validation deferred past the ALTER (documented
> >       invariant broken). Fix: reset firing_depth in AfterTriggerEndSubXact, mirroring the
> >       firing_batch_callbacks reset right below it.
> >
> > Even if that's a hallucination, it's an example of what I meant in (2) about
> > making the change harder to verify.
>
> That looks like a real bug, likely of the same class as an earlier
> error-path reset I fixed. I'll verify the reproducer; the fix is
> likely resetting firing_depth in AfterTriggerEndSubXact alongside the
> firing_batch_callbacks reset.

Confirmed, and it's worse than a stranded flag -- it corrupts data.
0002 to fix it. The reproducer:

A caught FK-check error inside a subtransaction (a PL/pgSQL EXCEPTION
block) skips the firing_depth-- , leaving firing_depth set. A later
ALTER TABLE ... ADD FOREIGN KEY in the same transaction, whose
validation runs per-row rather than via RI_Initial_Check()'s bulk join
(e.g. because RLS is enabled on the referenced table, so
RI_Initial_Check() bails), then calls RI_FKey_check() with
AfterTriggerIsActive() wrongly true. The check is routed into the
batched fast path -- but a utility command has no
AfterTriggerEndQuery() to fire the flush callback, so the batch is
never flushed. The violating row is not reported, the constraint is
marked convalidated = t, and the cached PK relation and index leak
("resource was not closed"). So a foreign key ends up validated with a
row that violates it. I've added this as a regression test in 0003.

On the fix: 0003 saves firing_depth at subtransaction start and
restores it at end, in AfterTriggerEndSubXact(), next to the existing
query_depth handling. Resetting to 0 instead is wrong -- a subxact can
begin and end while an outer query is firing, where firing_depth is
legitimately positive, and zeroing it there trips the firing_depth > 0
assert in FireAfterTriggerBatchCallbacks() (the fp_subxact test in
0001 and the transition-table tests in the PL suites both hit this).

> > Also, it's not clear to me why AfterTriggerEndSubXact() is right to reset
> > afterTriggers.firing_batch_callbacks.  The outer xact may be firing.  If
> > that's okay, can you expand the code comment to explain it?
>
> I'll go back and reconstruct why that reset is correct.  If I can't,
> I'll treat it as suspect and address it in the rework, with a comment
> either way.

The unconditional clear is wrong for the same reason: a subtransaction
that begins and ends while an outer FireAfterTriggerBatchCallbacks()
loop is active leaves firing_batch_callbacks legitimately true at
AfterTriggerEndSubXact(), and clearing it drops a flag the outer
firing still needs. 0003 gives it the same save/restore treatment as
firing_depth. I could not construct an observable failure from the
firing_batch_callbacks case specifically -- a separate guard,
ri_fastpath_flushing, routes any FK check re-entered from user code
during a flush onto the per-row path, so a re-entrant check never
reaches RegisterAfterTriggerBatchCallback() while the flag might be
wrongly cleared -- but restoring it is correct regardless and matches
the firing_depth handling.

> > >     Cleanly unwinding the cache on subxact abort would require tracking the
> > >     originating subxact of each buffered row, since rows from different
> > >     levels share an entry (the cache is keyed by constraint) and deferred
> > >     constraints cannot be flushed early at a subxact boundary.
> >
> > It's true that they can't be flushed early, but I'm not seeing a need for
> > explicit code to avoid that.  A subxact commit shall just confirm there's no
> > batch of its subxact level.  A subxact abort shall discard any batch of its
> > subxact level, leaving higher-subxact batches untouched.  A deferred trigger
> > doesn't start a batch until the end of the top-level transaction.
>
> Yes. I was confused about the relationship between deferred firing and
> subxacts, which is where that justification came from; deferred
> batches only exist at the top level, so there's nothing to unwind for
> them at a subxact boundary.

This is what 0001 does. Abort discards the ending level's entries;
commit leaves nothing to do at that level, since the batch was already
flushed at statement end. Deferred checks populate a batch only when
they fire at top-level commit (query depth -1), so no subxact boundary
ever has a deferred batch to unwind.

> > >     The per-row fast path still bypasses SPI and stays well ahead of the
> > >     pre-19 SPI-based check.  A fuller fix that preserves batching across
> > >     subtransactions -- whether by tracking the originating subxact of each
> > >     buffered row or by per-subxact cache stacks merged into the parent on
> > >     commit -- is left for a future release.
> >
> > If the above suspicion corresponds to a live bug, I'd bet on the fuller fix
> > being cleaner than a surgical fix.  That may not pan out, but I recommend
> > trying it first.
>
> Trying it in the direction you describe: subxact abort discards that
> level's batch, and subxact commit just checks that there's no batch
> left at that level (it was already flushed at statement end). The part
> that needs care is the resource-owner handling of the cached PK
> relation and index when a batch flush errors partway through inside a
> subxact that then aborts.  That's more involved than a subid tag. I'll
> work through the details and try to post a patch tomorrow.

Done; the three patches are attached. The resource-owner handling
turned out simpler than I expected: because AtEOSubXact_RI() runs
after the subtransaction's ResourceOwnerRelease(), it only forgets the
aborting level's cache entries and never closes their relations
itself, so a batch flush that errors partway through inside a subxact
is cleaned up by the ResourceOwner on the way out.

On performance: with the top-level-txn-only confinement gone, a
savepoint-wrapped FK load no longer drops to the per-row path. On a
check-dominated test the savepoint case now matches the top-level
case. Before (i.e. with 4113873a) it was slowed by roughly 10% in my
tests, because it didn't take the same buffered path.

--
Thanks, Amit Langote


Attachments:

  [application/octet-stream] v1-0002-Restore-firing-state-at-subtransaction-end.patch (9.3K, ../CA+HiwqGHa3tc6MZFSLyLrvwySdrmpkb1TqkH2jGd3HtKGGZ6cQ@mail.gmail.com/2-v1-0002-Restore-firing-state-at-subtransaction-end.patch)
  download | inline diff:
From 970565ad88dd2e4befbb6c0cf7b64e64f5bbb529 Mon Sep 17 00:00:00 2001
From: Amit Langote <[email protected]>
Date: Thu, 9 Jul 2026 18:22:05 +0900
Subject: [PATCH v1 2/3] Restore firing state at subtransaction end

AfterTriggerEndQuery(), AfterTriggerFireDeferred(), and
AfterTriggerSetState() bracket their firing loops with
firing_depth++/--, and FireAfterTriggerBatchCallbacks() brackets its
loop with firing_batch_callbacks.  The closing step runs after the loop
and is not protected by PG_FINALLY, so if a trigger or batch callback
throws and the error is caught by a subtransaction (e.g. a PL/pgSQL
EXCEPTION block), firing_depth is left too high and/or
firing_batch_callbacks is left set for the rest of the transaction.

firing_depth feeds AfterTriggerIsActive(), which the RI fast path uses
to decide whether an FK check is running inside trigger firing (and
may batch).  firing_depth left too high makes AfterTriggerIsActive()
wrongly report firing as active afterwards.  This is reachable and
results in silent data corruption: after a caught FK-check error, an
ALTER TABLE ... ADD FOREIGN KEY whose validation runs per-row
(RI_Initial_Check() having bailed, e.g. because RLS is enabled on the
referenced table) calls RI_FKey_check() with AfterTriggerIsActive()
wrongly true, so the check is routed into the batched fast path.  A
utility command has no AfterTriggerEndQuery() to fire the flush
callback, so the batch is never flushed: the violating row is not
reported, the constraint is marked validated, and the cached PK
relation and index leak.

Fix by restoring firing_depth and firing_batch_callbacks in
AfterTriggerEndSubXact() to the values saved at subtransaction start,
next to the existing query_depth handling.  Restoring (rather than
zeroing/clearing) is required because a subtransaction can begin and
end while an outer query is firing, where firing_depth is legitimately
positive and firing_batch_callbacks legitimately set; forcing them to
0/false there breaks the outer firing (FireAfterTriggerBatchCallbacks()
asserts firing_depth > 0).

Reported-by: Noah Misch <[email protected]>
Discussion: https://postgr.es/m/[email protected]
Backpatch-through: 19
---
 src/backend/commands/trigger.c            | 29 ++++++++++++++--
 src/test/regress/expected/foreign_key.out | 41 +++++++++++++++++++++++
 src/test/regress/sql/foreign_key.sql      | 39 +++++++++++++++++++++
 3 files changed, 107 insertions(+), 2 deletions(-)

diff --git a/src/backend/commands/trigger.c b/src/backend/commands/trigger.c
index 8a10f69c315..739dccda11b 100644
--- a/src/backend/commands/trigger.c
+++ b/src/backend/commands/trigger.c
@@ -3946,6 +3946,8 @@ struct AfterTriggersTransData
 	SetConstraintState state;	/* saved S C state, or NULL if not yet saved */
 	AfterTriggerEventList events;	/* saved list pointer */
 	int			query_depth;	/* saved query_depth */
+	int			firing_depth;	/* saved firing_depth */
+	bool		firing_batch_callbacks; /* saved firing_batch_callbacks */
 	CommandId	firing_counter; /* saved firing_counter */
 };
 
@@ -5507,6 +5509,9 @@ AfterTriggerBeginSubXact(void)
 	afterTriggers.trans_stack[my_level].state = NULL;
 	afterTriggers.trans_stack[my_level].events = afterTriggers.events;
 	afterTriggers.trans_stack[my_level].query_depth = afterTriggers.query_depth;
+	afterTriggers.trans_stack[my_level].firing_depth = afterTriggers.firing_depth;
+	afterTriggers.trans_stack[my_level].firing_batch_callbacks =
+		afterTriggers.firing_batch_callbacks;
 	afterTriggers.trans_stack[my_level].firing_counter = afterTriggers.firing_counter;
 }
 
@@ -5607,8 +5612,28 @@ AfterTriggerEndSubXact(bool isCommit)
 		}
 	}
 
-	/* Reset in case a callback threw an error while firing. */
-	afterTriggers.firing_batch_callbacks = false;
+	/*
+	 * Restore firing_depth and firing_batch_callbacks to their values at
+	 * subtransaction start.  The matching decrement of firing_depth in
+	 * AfterTriggerEndQuery()/AfterTriggerFireDeferred(), and the clearing of
+	 * firing_batch_callbacks in FireAfterTriggerBatchCallbacks(), run after
+	 * their loops and are not protected by PG_FINALLY.  A trigger or batch
+	 * callback error caught by this subtransaction can therefore leave either
+	 * one set; restoring the saved values unwinds only this subtransaction's
+	 * firing.
+	 *
+	 * Restoring (rather than zeroing/clearing) matters because a
+	 * subtransaction can begin and end while an outer query's triggers are
+	 * firing -- for instance a batch callback whose user-supplied cast or
+	 * equality function runs DML in a BEGIN ... EXCEPTION block.  There
+	 * firing_depth is positive and firing_batch_callbacks is true; forcing
+	 * them to 0/false would corrupt the outer firing
+	 * (FireAfterTriggerBatchCallbacks() asserts firing_depth > 0, and
+	 * clearing the guard would defeat its re-entrancy check).
+	 */
+	afterTriggers.firing_depth = afterTriggers.trans_stack[my_level].firing_depth;
+	afterTriggers.firing_batch_callbacks =
+		afterTriggers.trans_stack[my_level].firing_batch_callbacks;
 }
 
 /*
diff --git a/src/test/regress/expected/foreign_key.out b/src/test/regress/expected/foreign_key.out
index 2dad1539cda..ac566f5826c 100644
--- a/src/test/regress/expected/foreign_key.out
+++ b/src/test/regress/expected/foreign_key.out
@@ -3864,3 +3864,44 @@ SELECT count(*) AS deferred_rows FROM fp_deferred_fk;  -- 1, check passed at com
 (1 row)
 
 DROP TABLE fp_deferred_fk, fp_deferred_pk;
+-- Stranded firing state must not misroute ALTER TABLE ... ADD FOREIGN KEY
+-- validation into the batched fast path.  A caught FK-check error inside a
+-- subtransaction leaves firing_depth set (its decrement is skipped); a
+-- following ALTER whose validation runs per-row (forced here by RLS on the
+-- referenced table, so RI_Initial_Check() bails) would then be wrongly treated
+-- as running inside trigger firing, batched, and never flushed (a utility
+-- command has no AfterTriggerEndQuery), silently validating a violating row.
+CREATE ROLE regress_fpav_role;
+CREATE TABLE fpav_pk (id int PRIMARY KEY);
+INSERT INTO fpav_pk VALUES (1);
+ALTER TABLE fpav_pk ENABLE ROW LEVEL SECURITY;
+CREATE POLICY fpav_pk_all ON fpav_pk FOR ALL USING (true) WITH CHECK (true);
+GRANT REFERENCES, SELECT ON fpav_pk TO regress_fpav_role;
+CREATE TABLE fpav_fk (a int);
+INSERT INTO fpav_fk VALUES (1), (99);
+ALTER TABLE fpav_fk OWNER TO regress_fpav_role;
+CREATE TABLE fpav_cv_pk (id int PRIMARY KEY);
+INSERT INTO fpav_cv_pk VALUES (1);
+CREATE TABLE fpav_cv_fk (a int REFERENCES fpav_cv_pk(id));
+GRANT INSERT ON fpav_cv_fk TO regress_fpav_role;
+GRANT SELECT, INSERT ON fpav_cv_pk TO regress_fpav_role;
+SET ROLE regress_fpav_role;
+BEGIN;
+-- Caught FK violation: leaves firing_depth set if it is not restored.
+DO $$
+BEGIN
+    BEGIN
+        INSERT INTO fpav_cv_fk VALUES (999);
+    EXCEPTION WHEN foreign_key_violation THEN
+        NULL;
+    END;
+END$$;
+-- Must ERROR on the violating row (99), not silently validate it.
+ALTER TABLE fpav_fk ADD CONSTRAINT fpav_fk_fkey
+    FOREIGN KEY (a) REFERENCES fpav_pk (id);
+ERROR:  insert or update on table "fpav_fk" violates foreign key constraint "fpav_fk_fkey"
+DETAIL:  Key (a)=(99) is not present in table "fpav_pk".
+ROLLBACK;
+RESET ROLE;
+DROP TABLE fpav_fk, fpav_pk, fpav_cv_fk, fpav_cv_pk;
+DROP ROLE regress_fpav_role;
diff --git a/src/test/regress/sql/foreign_key.sql b/src/test/regress/sql/foreign_key.sql
index bae83f2010d..d4e6e0559cf 100644
--- a/src/test/regress/sql/foreign_key.sql
+++ b/src/test/regress/sql/foreign_key.sql
@@ -2807,3 +2807,42 @@ INSERT INTO fp_deferred_pk VALUES (1);
 COMMIT;
 SELECT count(*) AS deferred_rows FROM fp_deferred_fk;  -- 1, check passed at commit
 DROP TABLE fp_deferred_fk, fp_deferred_pk;
+-- Stranded firing state must not misroute ALTER TABLE ... ADD FOREIGN KEY
+-- validation into the batched fast path.  A caught FK-check error inside a
+-- subtransaction leaves firing_depth set (its decrement is skipped); a
+-- following ALTER whose validation runs per-row (forced here by RLS on the
+-- referenced table, so RI_Initial_Check() bails) would then be wrongly treated
+-- as running inside trigger firing, batched, and never flushed (a utility
+-- command has no AfterTriggerEndQuery), silently validating a violating row.
+CREATE ROLE regress_fpav_role;
+CREATE TABLE fpav_pk (id int PRIMARY KEY);
+INSERT INTO fpav_pk VALUES (1);
+ALTER TABLE fpav_pk ENABLE ROW LEVEL SECURITY;
+CREATE POLICY fpav_pk_all ON fpav_pk FOR ALL USING (true) WITH CHECK (true);
+GRANT REFERENCES, SELECT ON fpav_pk TO regress_fpav_role;
+CREATE TABLE fpav_fk (a int);
+INSERT INTO fpav_fk VALUES (1), (99);
+ALTER TABLE fpav_fk OWNER TO regress_fpav_role;
+CREATE TABLE fpav_cv_pk (id int PRIMARY KEY);
+INSERT INTO fpav_cv_pk VALUES (1);
+CREATE TABLE fpav_cv_fk (a int REFERENCES fpav_cv_pk(id));
+GRANT INSERT ON fpav_cv_fk TO regress_fpav_role;
+GRANT SELECT, INSERT ON fpav_cv_pk TO regress_fpav_role;
+SET ROLE regress_fpav_role;
+BEGIN;
+-- Caught FK violation: leaves firing_depth set if it is not restored.
+DO $$
+BEGIN
+    BEGIN
+        INSERT INTO fpav_cv_fk VALUES (999);
+    EXCEPTION WHEN foreign_key_violation THEN
+        NULL;
+    END;
+END$$;
+-- Must ERROR on the violating row (99), not silently validate it.
+ALTER TABLE fpav_fk ADD CONSTRAINT fpav_fk_fkey
+    FOREIGN KEY (a) REFERENCES fpav_pk (id);
+ROLLBACK;
+RESET ROLE;
+DROP TABLE fpav_fk, fpav_pk, fpav_cv_fk, fpav_cv_pk;
+DROP ROLE regress_fpav_role;
-- 
2.47.3



  [application/octet-stream] v1-0003-Assert-RI-fast-path-batches-don-t-span-subtransac.patch (1.6K, ../CA+HiwqGHa3tc6MZFSLyLrvwySdrmpkb1TqkH2jGd3HtKGGZ6cQ@mail.gmail.com/3-v1-0003-Assert-RI-fast-path-batches-don-t-span-subtransac.patch)
  download | inline diff:
From 19f9054ccd1b66b7c9d0a34fa3a5bf72d9088e40 Mon Sep 17 00:00:00 2001
From: Amit Langote <[email protected]>
Date: Thu, 9 Jul 2026 18:21:57 +0900
Subject: [PATCH v1 3/3] Assert RI fast-path batches don't span subtransactions

A fast-path batch is filled and flushed within a single trigger-firing
cycle, so all rows in a batch come from the subtransaction that created
the cache entry.  AtEOSubXact_RI() relies on this: it identifies an
aborting subtransaction's entries by the subid stamped at entry
creation.  Assert the invariant in ri_FastPathBatchAdd() to catch any
future code that would violate it.

Suggested-by: Noah Misch <[email protected]>
Discussion: https://postgr.es/m/[email protected]
Backpatch-through: 19
---
 src/backend/utils/adt/ri_triggers.c | 8 ++++++++
 1 file changed, 8 insertions(+)

diff --git a/src/backend/utils/adt/ri_triggers.c b/src/backend/utils/adt/ri_triggers.c
index a5d0fa4721a..a8c5277bfdc 100644
--- a/src/backend/utils/adt/ri_triggers.c
+++ b/src/backend/utils/adt/ri_triggers.c
@@ -2907,6 +2907,14 @@ ri_FastPathBatchAdd(RI_ConstraintInfo *riinfo,
 		return;
 	}
 
+	/*
+	 * A batch is filled and flushed within a single trigger-firing cycle, so
+	 * every row added to an entry comes from the subtransaction that created
+	 * it.  AtEOSubXact_RI() relies on this to identify an aborting
+	 * subtransaction's entries by the subid stamped at entry creation.
+	 */
+	Assert(fpentry->subid == GetCurrentSubTransactionId());
+
 	/*
 	 * Buffer the row.  A full batch is flushed below and re-entry is handled
 	 * above, so there is always room here; the bounds check just guards the
-- 
2.47.3



  [application/octet-stream] v1-0001-Track-RI-fast-path-FK-check-batches-per-subtransa.patch (20.9K, ../CA+HiwqGHa3tc6MZFSLyLrvwySdrmpkb1TqkH2jGd3HtKGGZ6cQ@mail.gmail.com/4-v1-0001-Track-RI-fast-path-FK-check-batches-per-subtransa.patch)
  download | inline diff:
From 424891b41801044af1da32cdba889cd90bf002ce Mon Sep 17 00:00:00 2001
From: Amit Langote <[email protected]>
Date: Thu, 9 Jul 2026 18:20:58 +0900
Subject: [PATCH v1 1/3] Track RI fast-path FK-check batches per subtransaction

Commit 4113873 confined RI fast-path batching to the top transaction
level to avoid mishandling the batch cache on subtransaction abort.
That disabled batching for a foreign-key load wrapped in a savepoint
(e.g. "BEGIN; SAVEPOINT s; COPY fk_table FROM ..."), a surprising
performance cliff, and departed from the usual per-subtransaction
resource handling.

Handle the cache per subtransaction instead.  Add AtEOSubXact_RI(),
called from Commit/AbortSubTransaction() after the subtransaction's
ResourceOwnerRelease(): it drops the entries opened by the ending
subtransaction, whose relations that ResourceOwner has just released,
and leaves entries opened by an outer level intact (so an inner
subxact abort during outer-level trigger firing does not discard the
outer statement's batch).  Each entry records the subtransaction that
opened it for this.

Removing the top-transaction-level gate also lets checks batch inside
a nested trigger-firing cycle -- an AFTER trigger doing FK DML on
another table.  That batch must be flushed at its own cycle's end.
Registration of the ri_FastPathEndBatch() callback was gated behind a
single global flag; but RegisterAfterTriggerBatchCallback() appends to
the current after-trigger query depth's callback list, which
AfterTriggerEndQuery() fires for that depth (and a separate list at
depth -1, fired by AfterTriggerFireDeferred() for deferred
constraints).  So the callback must be registered once per firing
cycle.  The global flag, set by the first cycle, suppressed
registration for every cycle after the first, whose callback list
stayed empty; the entry was never flushed, silently skipping its FK
check and leaking its relations.  Register once per query depth that
has an entry (checking the cache for an existing entry at that depth),
tag each entry with its depth, and have ri_FastPathEndBatch() flush
and release only the ending cycle's entries, destroying the cache once
empty.  Add AfterTriggerCurrentQueryDepth() so ri_triggers.c can read
the current depth; depth -1 covers the deferred firing cycle.

Reported-by: Noah Misch <[email protected]>
Reported-by: Nikolay Samokhvalov <[email protected]>
Discussion: https://postgr.es/m/[email protected]
Backpatch-through: 19
---
 src/backend/access/transam/xact.c         |   2 +
 src/backend/commands/trigger.c            |  14 ++
 src/backend/utils/adt/ri_triggers.c       | 192 +++++++++++++++++++---
 src/include/commands/trigger.h            |   3 +
 src/test/regress/expected/foreign_key.out |  57 +++++++
 src/test/regress/sql/foreign_key.sql      |  44 +++++
 6 files changed, 289 insertions(+), 23 deletions(-)

diff --git a/src/backend/access/transam/xact.c b/src/backend/access/transam/xact.c
index 3a89149016f..9e2d507c8a9 100644
--- a/src/backend/access/transam/xact.c
+++ b/src/backend/access/transam/xact.c
@@ -5245,6 +5245,7 @@ CommitSubTransaction(void)
 					  s->parent->subTransactionId);
 	AtEOSubXact_HashTables(true, s->nestingLevel);
 	AtEOSubXact_PgStat(true, s->nestingLevel);
+	AtEOSubXact_RI(true, s->subTransactionId, s->parent->subTransactionId);
 	AtSubCommit_Snapshot(s->nestingLevel);
 
 	/*
@@ -5419,6 +5420,7 @@ AbortSubTransaction(void)
 						  s->parent->subTransactionId);
 		AtEOSubXact_HashTables(false, s->nestingLevel);
 		AtEOSubXact_PgStat(false, s->nestingLevel);
+		AtEOSubXact_RI(false, s->subTransactionId, s->parent->subTransactionId);
 		AtSubAbort_Snapshot(s->nestingLevel);
 	}
 
diff --git a/src/backend/commands/trigger.c b/src/backend/commands/trigger.c
index 401baddbfc6..8a10f69c315 100644
--- a/src/backend/commands/trigger.c
+++ b/src/backend/commands/trigger.c
@@ -6929,3 +6929,17 @@ AfterTriggerIsActive(void)
 {
 	return afterTriggers.firing_depth > 0;
 }
+
+/*
+ * AfterTriggerCurrentQueryDepth
+ *		Return the current after-trigger query nesting depth.
+ *
+ * Lets a batch-callback registrant (e.g. the RI fast path) associate cached
+ * state with the firing cycle that created it, so a nested cycle's callback
+ * acts only on its own entries.  Returns -1 outside any query level.
+ */
+int
+AfterTriggerCurrentQueryDepth(void)
+{
+	return afterTriggers.query_depth;
+}
diff --git a/src/backend/utils/adt/ri_triggers.c b/src/backend/utils/adt/ri_triggers.c
index 627a9fb38ea..a5d0fa4721a 100644
--- a/src/backend/utils/adt/ri_triggers.c
+++ b/src/backend/utils/adt/ri_triggers.c
@@ -255,6 +255,24 @@ typedef struct RI_FastPathEntry
 	 * re-entrant ri_FastPathBatchAdd from user code run during the flush.
 	 */
 	bool		flushing;
+
+	/*
+	 * Subtransaction whose resource owner opened this entry's relations.
+	 * AtEOSubXact_RI() drops only entries matching an aborting subxact, so a
+	 * subxact abort during outer-level trigger firing leaves the outer batch
+	 * intact.
+	 */
+	SubTransactionId subid;
+
+	/*
+	 * After-trigger query depth (firing cycle) that created this entry.  Its
+	 * ri_FastPathEndBatch() callback is registered in that cycle's callback
+	 * list and fires at that cycle's AfterTriggerEndQuery(), so the callback
+	 * acts only on entries matching its own depth -- a nested cycle must not
+	 * flush an outer cycle's still-accumulating batch (wrong snapshot; cf.
+	 * commit 0e47bb5).
+	 */
+	int			query_depth;
 } RI_FastPathEntry;
 
 /*
@@ -266,7 +284,6 @@ static HTAB *ri_compare_cache = NULL;
 static dclist_head ri_constraint_cache_valid_list;
 
 static HTAB *ri_fastpath_cache = NULL;
-static bool ri_fastpath_callback_registered = false;
 static bool ri_fastpath_flushing = false;
 
 /*
@@ -353,7 +370,7 @@ pg_noreturn static void ri_ReportViolation(const RI_ConstraintInfo *riinfo,
 static RI_FastPathEntry *ri_FastPathGetEntry(const RI_ConstraintInfo *riinfo,
 											 Relation fk_rel);
 static void ri_FastPathEndBatch(void *arg);
-static void ri_FastPathTeardown(void);
+static void ri_FastPathTeardown(int depth);
 
 
 /*
@@ -470,9 +487,7 @@ RI_FKey_check(TriggerData *trigdata)
 	 */
 	if (ri_fastpath_is_applicable(riinfo))
 	{
-		if (AfterTriggerIsActive() &&
-			GetCurrentTransactionNestLevel() == 1 &&
-			!ri_fastpath_flushing)
+		if (AfterTriggerIsActive() && !ri_fastpath_flushing)
 		{
 			/* Batched path: buffer and probe in groups */
 			ri_FastPathBatchAdd(riinfo, fk_rel, newslot);
@@ -480,15 +495,11 @@ RI_FKey_check(TriggerData *trigdata)
 		else
 		{
 			/*
-			 * Per-row path, used when batching is not safe or not applicable:
+			 * Per-row path, used when batching is not applicable:
 			 *
 			 * - ALTER TABLE validation, where no after-trigger firing is
 			 * active;
 			 *
-			 * - any FK check inside a subtransaction, since the batch cache
-			 * is confined to the top transaction level (it cannot be cleanly
-			 * unwound on subxact abort);
-			 *
 			 * - a re-entrant check from user cast/operator code running
 			 * during a batch flush, since adding a cache entry while
 			 * ri_FastPathEndBatch is iterating the cache could leave it
@@ -4195,6 +4206,7 @@ ri_FastPathEndBatch(void *arg)
 {
 	HASH_SEQ_STATUS status;
 	RI_FastPathEntry *entry;
+	int			my_depth = (int) (intptr_t) arg;
 
 	if (ri_fastpath_cache == NULL)
 		return;
@@ -4219,7 +4231,8 @@ ri_FastPathEndBatch(void *arg)
 		hash_seq_init(&status, ri_fastpath_cache);
 		while ((entry = hash_seq_search(&status)) != NULL)
 		{
-			if (entry->batch_count > 0)
+			/* Flush only entries created in the cycle now ending. */
+			if (entry->query_depth == my_depth && entry->batch_count > 0)
 			{
 				Relation	fk_rel = table_open(entry->fk_relid, AccessShareLock);
 				RI_ConstraintInfo *riinfo = ri_LoadConstraintInfo(entry->conoid);
@@ -4235,17 +4248,26 @@ ri_FastPathEndBatch(void *arg)
 	}
 	PG_END_TRY();
 
-	ri_FastPathTeardown();
+	/*
+	 * Release this cycle's entries and remove them from the cache; leave
+	 * outer cycles' entries for their own callbacks.  Destroy the cache once
+	 * empty.
+	 */
+	ri_FastPathTeardown(my_depth);
 }
 
 /*
  * ri_FastPathTeardown
- *		Tear down all cached fast-path state.
+ *		Release and remove the cached entries of one firing cycle, and drop
+ *		the cache once it holds no more entries.
  *
- * Called from ri_FastPathEndBatch() after flushing any remaining rows.
+ * Called from ri_FastPathEndBatch() with the depth of the cycle that is
+ * ending: it releases only that cycle's entries, leaving an outer cycle's
+ * still-live entries for their own callbacks.  The cache (and its static
+ * pointer) go away once the last entry is removed.
  */
 static void
-ri_FastPathTeardown(void)
+ri_FastPathTeardown(int depth)
 {
 	HASH_SEQ_STATUS status;
 	RI_FastPathEntry *entry;
@@ -4256,6 +4278,8 @@ ri_FastPathTeardown(void)
 	hash_seq_init(&status, ri_fastpath_cache);
 	while ((entry = hash_seq_search(&status)) != NULL)
 	{
+		if (entry->query_depth != depth)
+			continue;
 		if (entry->idx_rel)
 			index_close(entry->idx_rel, NoLock);
 		if (entry->pk_rel)
@@ -4266,11 +4290,15 @@ ri_FastPathTeardown(void)
 			ExecDropSingleTupleTableSlot(entry->fk_slot);
 		if (entry->flush_cxt)
 			MemoryContextDelete(entry->flush_cxt);
+		hash_search(ri_fastpath_cache, &entry->conoid, HASH_REMOVE, NULL);
 	}
 
-	hash_destroy(ri_fastpath_cache);
-	ri_fastpath_cache = NULL;
-	ri_fastpath_callback_registered = false;
+	if (hash_get_num_entries(ri_fastpath_cache) == 0)
+	{
+		hash_destroy(ri_fastpath_cache);
+		ri_fastpath_cache = NULL;
+		ri_fastpath_flushing = false;
+	}
 }
 
 /*
@@ -4316,7 +4344,6 @@ AtEOXact_RI(bool isCommit)
 	 * memory-context reset; here we only drop the references to it.
 	 */
 	ri_fastpath_cache = NULL;
-	ri_fastpath_callback_registered = false;
 
 	/*
 	 * Also clear the in-flush flag.  ri_FastPathEndBatch() already clears it
@@ -4327,6 +4354,90 @@ AtEOXact_RI(bool isCommit)
 	ri_fastpath_flushing = false;
 }
 
+/*
+ * AtEOSubXact_RI
+ *		Reset fast-path batching state at subtransaction end.
+ *
+ * Called from CommitSubTransaction() with isCommit true and from
+ * AbortSubTransaction() with isCommit false, in both cases after the
+ * subtransaction's ResourceOwnerRelease().
+ *
+ * The fast-path cache is created and torn down within a single trigger-firing
+ * batch (ri_FastPathEndBatch(), an AfterTriggerBatchCallback), so at a normal
+ * subtransaction boundary it is already empty and this is a no-op.
+ *
+ * The exception is a batch flush that errors out partway and is caught by this
+ * subtransaction (e.g. a PL/pgSQL EXCEPTION block): ri_FastPathEndBatch()'s
+ * teardown was skipped, so the cache still points at entries whose relations
+ * were opened under this subtransaction's resource owner.  That owner has just
+ * released those relations (this runs after ResourceOwnerRelease()), so the
+ * entries are now stale.  Drop the cache so a later statement in the parent
+ * doesn't reuse it.  Like AtEOXact_RI(), this touches only backend-local state
+ * and the hash table's own memory -- no relations, locks or buffers, which the
+ * ResourceOwner already handled.  The entries' slots and flush contexts live in
+ * TopTransactionContext and are freed by its end-of-transaction reset.
+ */
+void
+AtEOSubXact_RI(bool isCommit, SubTransactionId mySubid,
+			   SubTransactionId parentSubid)
+{
+	HASH_SEQ_STATUS status;
+	RI_FastPathEntry *entry;
+	long		remaining;
+
+	if (ri_fastpath_cache == NULL)
+		return;
+
+	/*
+	 * Drop only entries whose relations were opened under the ending
+	 * subtransaction's resource owner.  On abort that owner has just released
+	 * those relations (this runs after ResourceOwnerRelease()), so the entry
+	 * is stale and must go, but entries opened by an outer level -- e.g. an
+	 * outer statement's batch, mid-build when an inner subxact fired and
+	 * aborted -- must be left untouched.
+	 *
+	 * On commit the entry, if any, would have been flushed and torn down at
+	 * the end of its statement (ri_FastPathEndBatch()); reaching here with a
+	 * matching entry is not expected, but reassign it to the parent so it is
+	 * still cleaned up, rather than leaving it under a vanished subxact id.
+	 *
+	 * We touch no relations, locks or buffers -- the ResourceOwner handled
+	 * those.  The entry's slots and flush context are memory in
+	 * TopTransactionContext, freed at end-of-transaction reset; we only
+	 * remove the hash entry so it is not reused or torn down again.
+	 */
+	hash_seq_init(&status, ri_fastpath_cache);
+	while ((entry = hash_seq_search(&status)) != NULL)
+	{
+		if (entry->subid != mySubid)
+			continue;
+
+		if (isCommit)
+		{
+			/*
+			 * A committing subxact's entry should already have been flushed
+			 * and torn down at its statement's end (ri_FastPathEndBatch()),
+			 * so we don't expect to find one here.  If we do, reassign it to
+			 * the parent so it's still cleaned up rather than left under a
+			 * subxact id that no longer exists.
+			 */
+			Assert(false);
+			entry->subid = parentSubid;
+		}
+		else
+			hash_search(ri_fastpath_cache, &entry->conoid, HASH_REMOVE, NULL);
+	}
+
+	/* If that emptied the cache, drop it so the next batch starts clean. */
+	remaining = hash_get_num_entries(ri_fastpath_cache);
+	if (remaining == 0)
+	{
+		hash_destroy(ri_fastpath_cache);
+		ri_fastpath_cache = NULL;
+		ri_fastpath_flushing = false;
+	}
+}
+
 /*
  * ri_FastPathGetEntry
  *		Look up or create a per-batch cache entry for the given constraint.
@@ -4401,15 +4512,50 @@ ri_FastPathGetEntry(const RI_ConstraintInfo *riinfo, Relation fk_rel)
 												 ALLOCSET_SMALL_SIZES);
 		MemoryContextSwitchTo(oldcxt);
 
-		/* Ensure cleanup at end of this trigger-firing batch */
-		if (!ri_fastpath_callback_registered)
+		/*
+		 * Ensure ri_FastPathEndBatch() is registered for THIS firing cycle.
+		 * RegisterAfterTriggerBatchCallback() appends to the current
+		 * after-trigger query depth's callback list and fires at that depth's
+		 * AfterTriggerEndQuery(), so a nested cycle needs its own
+		 * registration; a single global latch would leave the nested cycle's
+		 * list empty and its batch unflushed.  Pass the depth as the callback
+		 * arg so the callback flushes only its own cycle's entries.
+		 */
 		{
-			RegisterAfterTriggerBatchCallback(ri_FastPathEndBatch, NULL);
-			ri_fastpath_callback_registered = true;
+			int			cur_depth = AfterTriggerCurrentQueryDepth();
+			bool		depth_registered = false;
+			HASH_SEQ_STATUS reg_status;
+			RI_FastPathEntry *other;
+
+			/*
+			 * Register the callback once per firing cycle (query depth),
+			 * including the deferred cycle at depth -1.  Rather than track
+			 * registered depths separately, check whether any other cache
+			 * entry was already created at this depth: if so, its creation
+			 * already registered the callback for this cycle.  (The
+			 * just-created entry is already in the hash, so skip it by
+			 * conoid.)
+			 */
+			hash_seq_init(&reg_status, ri_fastpath_cache);
+			while ((other = hash_seq_search(&reg_status)) != NULL)
+			{
+				if (other != entry && other->query_depth == cur_depth)
+				{
+					depth_registered = true;
+					hash_seq_term(&reg_status);
+					break;
+				}
+			}
+
+			if (!depth_registered)
+				RegisterAfterTriggerBatchCallback(ri_FastPathEndBatch,
+												  (void *) (intptr_t) cur_depth);
+			entry->query_depth = cur_depth;
 		}
 
 		entry->flushing = false;
 		entry->batch_count = 0;
+		entry->subid = GetCurrentSubTransactionId();
 	}
 
 	return entry;
diff --git a/src/include/commands/trigger.h b/src/include/commands/trigger.h
index 0c3d485abf4..fecdb785f35 100644
--- a/src/include/commands/trigger.h
+++ b/src/include/commands/trigger.h
@@ -309,7 +309,10 @@ typedef void (*AfterTriggerBatchCallback) (void *arg);
 extern void RegisterAfterTriggerBatchCallback(AfterTriggerBatchCallback callback,
 											  void *arg);
 extern bool AfterTriggerIsActive(void);
+extern int	AfterTriggerCurrentQueryDepth(void);
 
 extern void AtEOXact_RI(bool isCommit);
+extern void AtEOSubXact_RI(bool isCommit, SubTransactionId mySubid,
+						   SubTransactionId parentSubid);
 
 #endif							/* TRIGGER_H */
diff --git a/src/test/regress/expected/foreign_key.out b/src/test/regress/expected/foreign_key.out
index c334cce752c..2dad1539cda 100644
--- a/src/test/regress/expected/foreign_key.out
+++ b/src/test/regress/expected/foreign_key.out
@@ -3807,3 +3807,60 @@ DETAIL:  Key (a)=(999) is not present in table "fp_subxact_pk".
 DROP TRIGGER fp_subxact_trg ON fp_subxact_fk;
 DROP FUNCTION fp_abort_subxact();
 DROP TABLE fp_subxact_fk, fp_subxact_pk;
+-- Re-entrant fast-path check inside a committing subtransaction.  An AFTER
+-- trigger on one FK table runs FK DML on a second FK table inside a PL/pgSQL
+-- BEGIN ... EXCEPTION block, so the inner check batches in its own
+-- trigger-firing cycle nested in the outer check's.  The inner cycle must
+-- register its own end-of-batch callback and flush -- otherwise its FK check
+-- is skipped (an orphan commits) and its relations leak.
+CREATE TABLE fp_inner_pk (id int PRIMARY KEY);
+INSERT INTO fp_inner_pk VALUES (1);
+CREATE TABLE fp_inner_fk (a int REFERENCES fp_inner_pk (id));
+CREATE TABLE fp_outer_pk (id int PRIMARY KEY);
+INSERT INTO fp_outer_pk SELECT g FROM generate_series(1, 64) g;
+CREATE FUNCTION fp_reentry_subxact() RETURNS trigger LANGUAGE plpgsql AS $$
+BEGIN
+    IF NEW.a = 32 THEN
+        BEGIN
+            INSERT INTO fp_inner_fk VALUES (999);  -- violates; must be caught
+        EXCEPTION WHEN foreign_key_violation THEN
+            NULL;
+        END;
+    END IF;
+    RETURN NEW;
+END$$;
+CREATE TABLE fp_outer_fk (a int REFERENCES fp_outer_pk (id));
+CREATE TRIGGER fp_reentry_subxact_trg AFTER INSERT ON fp_outer_fk
+    FOR EACH ROW EXECUTE FUNCTION fp_reentry_subxact();
+INSERT INTO fp_outer_fk SELECT g FROM generate_series(1, 64) g;
+SELECT count(*) AS outer_rows FROM fp_outer_fk;   -- 64, outer batch intact
+ outer_rows 
+------------
+         64
+(1 row)
+
+SELECT count(*) AS inner_rows FROM fp_inner_fk;   -- 0, inner check caught
+ inner_rows 
+------------
+          0
+(1 row)
+
+DROP TRIGGER fp_reentry_subxact_trg ON fp_outer_fk;
+DROP FUNCTION fp_reentry_subxact();
+DROP TABLE fp_outer_fk, fp_outer_pk, fp_inner_fk, fp_inner_pk;
+-- Deferred FK check fires at commit (query depth -1); its batch must still get
+-- a callback registered and flushed.
+CREATE TABLE fp_deferred_pk (id int PRIMARY KEY);
+CREATE TABLE fp_deferred_fk (a int REFERENCES fp_deferred_pk (id)
+    DEFERRABLE INITIALLY DEFERRED);
+BEGIN;
+INSERT INTO fp_deferred_fk VALUES (1);
+INSERT INTO fp_deferred_pk VALUES (1);
+COMMIT;
+SELECT count(*) AS deferred_rows FROM fp_deferred_fk;  -- 1, check passed at commit
+ deferred_rows 
+---------------
+             1
+(1 row)
+
+DROP TABLE fp_deferred_fk, fp_deferred_pk;
diff --git a/src/test/regress/sql/foreign_key.sql b/src/test/regress/sql/foreign_key.sql
index 17eadc4bb5a..bae83f2010d 100644
--- a/src/test/regress/sql/foreign_key.sql
+++ b/src/test/regress/sql/foreign_key.sql
@@ -2763,3 +2763,47 @@ INSERT INTO fp_subxact_fk VALUES (999, 'bad'), (0, 'boom'), (1, 'ok');
 DROP TRIGGER fp_subxact_trg ON fp_subxact_fk;
 DROP FUNCTION fp_abort_subxact();
 DROP TABLE fp_subxact_fk, fp_subxact_pk;
+
+-- Re-entrant fast-path check inside a committing subtransaction.  An AFTER
+-- trigger on one FK table runs FK DML on a second FK table inside a PL/pgSQL
+-- BEGIN ... EXCEPTION block, so the inner check batches in its own
+-- trigger-firing cycle nested in the outer check's.  The inner cycle must
+-- register its own end-of-batch callback and flush -- otherwise its FK check
+-- is skipped (an orphan commits) and its relations leak.
+CREATE TABLE fp_inner_pk (id int PRIMARY KEY);
+INSERT INTO fp_inner_pk VALUES (1);
+CREATE TABLE fp_inner_fk (a int REFERENCES fp_inner_pk (id));
+CREATE TABLE fp_outer_pk (id int PRIMARY KEY);
+INSERT INTO fp_outer_pk SELECT g FROM generate_series(1, 64) g;
+CREATE FUNCTION fp_reentry_subxact() RETURNS trigger LANGUAGE plpgsql AS $$
+BEGIN
+    IF NEW.a = 32 THEN
+        BEGIN
+            INSERT INTO fp_inner_fk VALUES (999);  -- violates; must be caught
+        EXCEPTION WHEN foreign_key_violation THEN
+            NULL;
+        END;
+    END IF;
+    RETURN NEW;
+END$$;
+CREATE TABLE fp_outer_fk (a int REFERENCES fp_outer_pk (id));
+CREATE TRIGGER fp_reentry_subxact_trg AFTER INSERT ON fp_outer_fk
+    FOR EACH ROW EXECUTE FUNCTION fp_reentry_subxact();
+INSERT INTO fp_outer_fk SELECT g FROM generate_series(1, 64) g;
+SELECT count(*) AS outer_rows FROM fp_outer_fk;   -- 64, outer batch intact
+SELECT count(*) AS inner_rows FROM fp_inner_fk;   -- 0, inner check caught
+DROP TRIGGER fp_reentry_subxact_trg ON fp_outer_fk;
+DROP FUNCTION fp_reentry_subxact();
+DROP TABLE fp_outer_fk, fp_outer_pk, fp_inner_fk, fp_inner_pk;
+
+-- Deferred FK check fires at commit (query depth -1); its batch must still get
+-- a callback registered and flushed.
+CREATE TABLE fp_deferred_pk (id int PRIMARY KEY);
+CREATE TABLE fp_deferred_fk (a int REFERENCES fp_deferred_pk (id)
+    DEFERRABLE INITIALLY DEFERRED);
+BEGIN;
+INSERT INTO fp_deferred_fk VALUES (1);
+INSERT INTO fp_deferred_pk VALUES (1);
+COMMIT;
+SELECT count(*) AS deferred_rows FROM fp_deferred_fk;  -- 1, check passed at commit
+DROP TABLE fp_deferred_fk, fp_deferred_pk;
-- 
2.47.3



view thread (17+ messages)

reply

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Reply to all the recipients using the --to and --cc options:
  reply via email

  To: [email protected]
  Cc: [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected]
  Subject: Re: PG19 FK fast path: OOB write and missed FK checks during batched
  In-Reply-To: <CA+HiwqGHa3tc6MZFSLyLrvwySdrmpkb1TqkH2jGd3HtKGGZ6cQ@mail.gmail.com>

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

This inbox is served by agora; see mirroring instructions
for how to clone and mirror all data and code used for this inbox