BUG #19946: Caught foreign-key violations retain RI fast-path memory until transaction end

From: PG Bug reporting form <noreply(at)postgresql(dot)org>
To: pgsql-bugs(at)lists(dot)postgresql(dot)org
Cc: imchifan(at)163(dot)com
Subject: BUG #19946: Caught foreign-key violations retain RI fast-path memory until transaction end
Date: 2026-11-25 17:18:42
Message-ID: 19946-28f34d0807ee8535@postgresql.org
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-bugs

The following bug has been logged on the website:

Bug reference: 19946
Logged by: Qifan Liu
Email address: imchifan(at)163(dot)com
PostgreSQL version: 19.0
Operating system: Linux/amd64
Description:

Hi,

Repeatedly catching foreign-key violations in subtransactions retains one
"RI fast path flush temporary context" per violation until the top-level
transaction ends. This causes memory use to grow linearly in a long-running
transaction that recovers from such errors.

Run the following with psql as a superuser:

\set ON_ERROR_STOP on

BEGIN;

CREATE TABLE pk (id integer PRIMARY KEY);
INSERT INTO pk VALUES (1);
CREATE TABLE fk (id integer REFERENCES pk(id));

SELECT count(*) AS baseline_contexts,
coalesce(sum(total_bytes), 0) AS baseline_bytes
FROM pg_backend_memory_contexts
WHERE name = 'RI fast path flush temporary context';

DO $block$
BEGIN
FOR i IN 1..200 LOOP
BEGIN
INSERT INTO fk VALUES (999);
EXCEPTION WHEN foreign_key_violation THEN
NULL;
END;
END LOOP;
END
$block$;

SELECT count(*) AS retained_contexts,
coalesce(sum(total_bytes), 0) AS retained_bytes
FROM pg_backend_memory_contexts
WHERE name = 'RI fast path flush temporary context';

SELECT count(*) AS rows_in_fk FROM fk;

ROLLBACK;

The relevant output is:

baseline_contexts | baseline_bytes
-------------------+----------------
0 | 0
(1 row)

DO
retained_contexts | retained_bytes
-------------------+----------------
200 | 1024000
(1 row)

rows_in_fk
------------
0
(1 row)

The failed inserts are rolled back and the table remains empty, but 200
contexts totaling 1,024,000 bytes remain allocated. A bounded implementation
should release the per-entry resources when each subtransaction aborts,
returning these measurements to the baseline instead of retaining them until
the outer transaction ends.

The subtransaction-abort handling appears to remove the RI fast-path lookup
entry without releasing the associated slots and flush context allocated
under TopTransactionContext.

Browse pgsql-bugs by date

  From Date Subject
Next Message PG Bug reporting form 2026-11-25 17:22:24 BUG #19947: Rules see parent generated expression instead of routed partition's expression
Previous Message PG Bug reporting form 2026-11-25 16:27:47 BUG #19945: Partitionwise join omits lateral dependency from Memoize cache key