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

Started by PG Bug reporting form3 days ago1 messagesbugs

Thread notes

1 note#bug
hackorum-bot#bug
hackorum-bot
2 days ago

@global #bug

#bug
Jump to latest
#1PG Bug reporting form
noreply@postgresql.org

The following bug has been logged on the website:

Bug reference: 19946
Logged by: Qifan Liu
Email address: imchifan@163.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.