Two more RI fast-path issues
Two more RI fast-path issues
Hi, While reviewing the RI fast path after removing batching from master, with help from Claude Opus 5.5, I found two more places where it behaves differently from the SPI path, apart from the cast issues discussed in [1]. 1. Fast-path doesn't refuse to take row locks in a read-only transaction, whereas the SPI path does. In the SPI path, the executor calls PreventCommandIfReadOnly(), but the fast-path continues without checking. With pk as a plain table and ppk as a partitioned one (whose checks use SPI), and both foreign keys deferred: CREATE TABLE pk (a int PRIMARY KEY); INSERT INTO pk VALUES (1); CREATE TABLE ppk (a int PRIMARY KEY) PARTITION BY LIST (a); CREATE TABLE ppk1 PARTITION OF ppk DEFAULT; INSERT INTO ppk VALUES (1); CREATE TABLE fk (a int REFERENCES pk DEFERRABLE INITIALLY DEFERRED); CREATE TABLE pfk (a int REFERENCES ppk DEFERRABLE INITIALLY DEFERRED); -- SPI BEGIN; INSERT INTO pfk VALUES (1); SET TRANSACTION READ ONLY; COMMIT; ERROR: cannot execute SELECT FOR KEY SHARE in a read-only transaction CONTEXT: SQL statement "SELECT 1 FROM "public"."ppk" x WHERE "a" OPERATOR(pg_catalog.=) $1 FOR KEY SHARE OF x" -- fast -path BEGIN; INSERT INTO fk VALUES (1); SET TRANSACTION READ ONLY; COMMIT; COMMIT 2. Fast-path can produce "attempted to lock invisible tuple" error due to a bug in how it calls table_tuple_lock(). In the SPI path the ExecLockRows() calls table_tuple_lock() with es_output_cid, whereas the fast-path uses GetCurrentCommandId(), which can result in the latter case using a command ID that is different from when the initial snapshot was taken. If user code running during the scan advances it, and if that code also updated the referenced row, the fast path can fail with "attempt to lock invisible tuple" when it should report an FK violation (). In this case, user code is the index's equality operator as shown in the test case added in 0002. Attached patches to fix both, which I'd like to get in before RC1 freeze. -- Thanks, Amit Langote [1] https://www.postgresql.org/message-id/CA%2BHiwqFqUhTc_oO%2B58Cs8mww8ZzJ8b8-DL%2BKGbeTMecLVTunvQ%40mail.gmail.com
Re: Two more RI fast-path issues
От:
Amit Langote <amitlangote09@gmail.com>
Дата:
On Tue, Oct 6, 2026 at 3:13 PM Amit Langote wrote: > > Hi, > > While reviewing the RI fast path after removing batching from master, > with help from Claude Opus 5.5, I found two more places where it > behaves differently from the SPI path, apart from the cast issues > discussed in [1]. > > 1. Fast-path doesn't refuse to take row locks in a read-only > transaction, whereas the SPI path does. In the SPI path, the executor > calls PreventCommandIfReadOnly(), but the fast-path continues without > checking. With pk as a plain table and ppk as a partitioned one > (whose checks use SPI), and both foreign keys deferred: > > CREATE TABLE pk (a int PRIMARY KEY); INSERT INTO pk VALUES (1); > CREATE TABLE ppk (a int PRIMARY KEY) PARTITION BY LIST (a); > CREATE TABLE ppk1 PARTITION OF ppk DEFAULT; INSERT INTO ppk VALUES (1); > CREATE TABLE fk (a int REFERENCES pk DEFERRABLE INITIALLY DEFERRED); > CREATE TABLE pfk (a int REFERENCES ppk DEFERRABLE INITIALLY DEFERRED); > > -- SPI > BEGIN; INSERT INTO pfk VALUES (1); SET TRANSACTION READ ONLY; > COMMIT; > ERROR: cannot execute SELECT FOR KEY SHARE in a read-only transaction > CONTEXT: SQL statement "SELECT 1 FROM "public"."ppk" x WHERE "a" > OPERATOR(pg_catalog.=) $1 FOR KEY SHARE OF x" > > -- fast -path > BEGIN; INSERT INTO fk VALUES (1); SET TRANSACTION READ ONLY; > COMMIT; > COMMIT > > 2. Fast-path can produce "attempted to lock invisible tuple" error > due to a bug in how it calls table_tuple_lock(). In the SPI path the > ExecLockRows() calls table_tuple_lock() with es_output_cid, whereas > the fast-path uses GetCurrentCommandId(), which can result in the > latter case using a command ID that is different from when the initial > snapshot was taken. If user code running during the scan advances it, > and if that code also updated the referenced row, the fast path can > fail with "attempt to lock invisible tuple" when it should report an > FK violation (). In this case, user code is the index's equality > operator as shown in the test case added in 0002. > > Attached patches to fix both, which I'd like to get in before RC1 freeze. I have added an open item for this. -- Thanks, Amit Langote
Re: Two more RI fast-path issues
On Tue, Oct 6, 2026 at 3:20 PM Amit Langote wrote: > On Tue, Oct 6, 2026 at 3:13 PM Amit Langote wrote: > > > > Hi, > > > > While reviewing the RI fast path after removing batching from master, > > with help from Claude Opus 5.5, I found two more places where it > > behaves differently from the SPI path, apart from the cast issues > > discussed in [1]. > > > > 1. Fast-path doesn't refuse to take row locks in a read-only > > transaction, whereas the SPI path does. In the SPI path, the executor > > calls PreventCommandIfReadOnly(), but the fast-path continues without > > checking. With pk as a plain table and ppk as a partitioned one > > (whose checks use SPI), and both foreign keys deferred: > > > > CREATE TABLE pk (a int PRIMARY KEY); INSERT INTO pk VALUES (1); > > CREATE TABLE ppk (a int PRIMARY KEY) PARTITION BY LIST (a); > > CREATE TABLE ppk1 PARTITION OF ppk DEFAULT; INSERT INTO ppk VALUES (1); > > CREATE TABLE fk (a int REFERENCES pk DEFERRABLE INITIALLY DEFERRED); > > CREATE TABLE pfk (a int REFERENCES ppk DEFERRABLE INITIALLY DEFERRED); > > > > -- SPI > > BEGIN; INSERT INTO pfk VALUES (1); SET TRANSACTION READ ONLY; > > COMMIT; > > ERROR: cannot execute SELECT FOR KEY SHARE in a read-only transaction > > CONTEXT: SQL statement "SELECT 1 FROM "public"."ppk" x WHERE "a" > > OPERATOR(pg_catalog.=) $1 FOR KEY SHARE OF x" > > > > -- fast -path > > BEGIN; INSERT INTO fk VALUES (1); SET TRANSACTION READ ONLY; > > COMMIT; > > COMMIT > > > > 2. Fast-path can produce "attempted to lock invisible tuple" error > > due to a bug in how it calls table_tuple_lock(). In the SPI path the > > ExecLockRows() calls table_tuple_lock() with es_output_cid, whereas > > the fast-path uses GetCurrentCommandId(), which can result in the > > latter case using a command ID that is different from when the initial > > snapshot was taken. If user code running during the scan advances it, > > and if that code also updated the referenced row, the fast path can > > fail with "attempt to lock invisible tuple" when it should report an > > FK violation (). In this case, user code is the index's equality > > operator as shown in the test case added in 0002. > > > > Attached patches to fix both, which I'd like to get in before RC1 freeze. > > I have added an open item for this. Barring comments, would like to push the attached slightly updated version (comment, commit message fixes) tomorrow after committing the patches in [1] because I rebased these over those other patches. -- Thanks, Amit Langote [1] https://www.postgresql.org/message-id/CA%2BHiwqGDY_T4NxBi-kg4Y3V%3DD1CmRhUmj_tyo8aP-ZGO145%3DEQ%40mail.gmail.com
Re: Two more RI fast-path issues
От:
Amit Langote <amitlangote09@gmail.com>
Дата:
On Wed, Oct 7, 2026 at 10:02 PM Amit Langote wrote: > On Tue, Oct 6, 2026 at 3:20 PM Amit Langote wrote: > > On Tue, Oct 6, 2026 at 3:13 PM Amit Langote wrote: > > > > > > Hi, > > > > > > While reviewing the RI fast path after removing batching from master, > > > with help from Claude Opus 5.5, I found two more places where it > > > behaves differently from the SPI path, apart from the cast issues > > > discussed in [1]. > > > > > > 1. Fast-path doesn't refuse to take row locks in a read-only > > > transaction, whereas the SPI path does. In the SPI path, the executor > > > calls PreventCommandIfReadOnly(), but the fast-path continues without > > > checking. With pk as a plain table and ppk as a partitioned one > > > (whose checks use SPI), and both foreign keys deferred: > > > > > > CREATE TABLE pk (a int PRIMARY KEY); INSERT INTO pk VALUES (1); > > > CREATE TABLE ppk (a int PRIMARY KEY) PARTITION BY LIST (a); > > > CREATE TABLE ppk1 PARTITION OF ppk DEFAULT; INSERT INTO ppk VALUES (1); > > > CREATE TABLE fk (a int REFERENCES pk DEFERRABLE INITIALLY DEFERRED); > > > CREATE TABLE pfk (a int REFERENCES ppk DEFERRABLE INITIALLY DEFERRED); > > > > > > -- SPI > > > BEGIN; INSERT INTO pfk VALUES (1); SET TRANSACTION READ ONLY; > > > COMMIT; > > > ERROR: cannot execute SELECT FOR KEY SHARE in a read-only transaction > > > CONTEXT: SQL statement "SELECT 1 FROM "public"."ppk" x WHERE "a" > > > OPERATOR(pg_catalog.=) $1 FOR KEY SHARE OF x" > > > > > > -- fast -path > > > BEGIN; INSERT INTO fk VALUES (1); SET TRANSACTION READ ONLY; > > > COMMIT; > > > COMMIT > > > > > > 2. Fast-path can produce "attempted to lock invisible tuple" error > > > due to a bug in how it calls table_tuple_lock(). In the SPI path the > > > ExecLockRows() calls table_tuple_lock() with es_output_cid, whereas > > > the fast-path uses GetCurrentCommandId(), which can result in the > > > latter case using a command ID that is different from when the initial > > > snapshot was taken. If user code running during the scan advances it, > > > and if that code also updated the referenced row, the fast path can > > > fail with "attempt to lock invisible tuple" when it should report an > > > FK violation (). In this case, user code is the index's equality > > > operator as shown in the test case added in 0002. > > > > > > Attached patches to fix both, which I'd like to get in before RC1 freeze. > > > > I have added an open item for this. > > Barring comments, would like to push the attached slightly updated > version (comment, commit message fixes) tomorrow after committing the > patches in [1] because I rebased these over those other patches. I've pushed these. -- Thanks, Amit Langote
Re: Two more RI fast-path issues
От:
Tom Lane <tgl@sss.pgh.pa.us>
Дата:
There is still something wrong in the RI_FKey stuff. BF animal
trilobite reported a SIGSEGV in the foreign_key test, and I was able
to reproduce that locally by compiling HEAD with -DCLOBBER_CACHE_ALWAYS.
Stack trace looks like
Program terminated with signal SIGSEGV, Segmentation fault.
#0 0x00000000007770df in _SPI_execute_plan (plan=plan@entry=0x184fafc0, options=options@entry=0x7fff7819da00, snapshot=snapshot@entry=0x0, crosscheck_snapshot=crosscheck_snapshot@entry=0x0,
fire_triggers=fire_triggers@entry=false) at spi.c:2498
2498 CachedPlanSource *plansource = (CachedPlanSource *) lfirst(lc1);
(gdb) bt
#0 0x00000000007770df in _SPI_execute_plan (plan=plan@entry=0x184fafc0, options=options@entry=0x7fff7819da00, snapshot=snapshot@entry=0x0, crosscheck_snapshot=crosscheck_snapshot@entry=0x0,
fire_triggers=fire_triggers@entry=false) at spi.c:2498
#1 0x0000000000778030 in SPI_execute_snapshot (plan=plan@entry=0x184fafc0, Values=Values@entry=0x7fff7819db00, Nulls=Nulls@entry=0x7fff7819dac0 " ", snapshot=snapshot@entry=0x0,
crosscheck_snapshot=crosscheck_snapshot@entry=0x0, read_only=read_only@entry=false, fire_triggers=false, tcount=1) at spi.c:796
#2 0x0000000000a1565c in ri_PerformCheck (riinfo=riinfo@entry=0x183d6738, qkey=qkey@entry=0x7fff7819ddb8, qplan=0x184fafc0, fk_rel=fk_rel@entry=0x7f4431f051d0, pk_rel=pk_rel@entry=0x7f4431f08190,
oldslot=oldslot@entry=0x0, newslot=0x1847e5a8, is_restrict=false, detectNewRows=false, expect_OK=5) at ri_triggers.c:2723
#3 0x0000000000a16026 in RI_FKey_check (trigdata=) at ri_triggers.c:535
#4 0x0000000000a17cdc in RI_FKey_check_ins (fcinfo=0x7fff7819e980) at ri_triggers.c:563
#5 0x0000000000702b6d in ExecCallTriggerFunc (trigdata=trigdata@entry=0x7fff7819eb50, tgindx=tgindx@entry=0, finfo=finfo@entry=0x1821a620, instr=instr@entry=0x0,
per_tuple_context=per_tuple_context@entry=0x18198a80) at trigger.c:2409
#6 0x0000000000704ed6 in AfterTriggerExecute (estate=, event=0x181a2bec, relInfo=0x1847c9c8, src_relInfo=, dst_relInfo=, trigdesc=0x1821a810,
finfo=0x1821a620, instr=0x0, per_tuple_context=, trig_tuple_slot1=0x0, trig_tuple_slot2=0x0) at trigger.c:4599
#7 afterTriggerInvokeEvents (events=events@entry=0x180523b0, firing_id=1, estate=estate@entry=0x18218960, delete_ok=delete_ok@entry=false) at trigger.c:4840
#8 0x000000000070a01b in AfterTriggerEndQuery (estate=estate@entry=0x18218960) at trigger.c:5222
#9 0x000000000072ff34 in standard_ExecutorFinish (queryDesc=0x18482ac0) at execMain.c:454
#10 0x000000000092f0d8 in ProcessQuery (plan=, sourceText=0x17fbc450 "INSERT INTO fp_reentry_fk SELECT row(1)::fp_vch FROM generate_series(1, 2);", params=0x0, queryEnv=0x0,
dest=0x184a2ba8, qc=0x7fff7819ee90) at pquery.c:190
#11 0x000000000092fbf6 in PortalRunMulti (portal=portal@entry=0x18044070, isTopLevel=isTopLevel@entry=true, setHoldSnapshot=setHoldSnapshot@entry=false, dest=dest@entry=0x184a2ba8,
altdest=altdest@entry=0x184a2ba8, qc=qc@entry=0x7fff7819ee90) at pquery.c:1273
#12 0x000000000092ffb7 in PortalRun (portal=portal@entry=0x18044070, count=count@entry=9223372036854775807, isTopLevel=isTopLevel@entry=true, dest=dest@entry=0x184a2ba8,
altdest=altdest@entry=0x184a2ba8, qc=qc@entry=0x7fff7819ee90) at pquery.c:788
#13 0x000000000092be16 in exec_simple_query (query_string=0x17fbc450 "INSERT INTO fp_reentry_fk SELECT row(1)::fp_vch FROM generate_series(1, 2);") at postgres.c:1297
#14 0x000000000092d9ad in PostgresMain (dbname=, username=) at postgres.c:4946
#15 0x0000000000927d5d in BackendMain (startup_data=, startup_data_len=) at backend_startup.c:124
#16 0x000000000086fb7d in postmaster_child_launch (child_type=, child_slot=4, startup_data=startup_data@entry=0x7fff7819f300, startup_data_len=startup_data_len@entry=24,
client_sock=client_sock@entry=0x7fff7819f320) at launch_backend.c:268
#17 0x000000000087331f in BackendStartup (client_sock=0x7fff7819f320) at postmaster.c:3650
#18 ServerLoop () at postmaster.c:1727
#19 0x0000000000874c0a in PostmasterMain (argc=argc@entry=3, argv=argv@entry=0x17fb7e50) at postmaster.c:1414
#20 0x0000000000532488 in main (argc=3, argv=0x17fb7e50) at main.c:227
(gdb) p debug_query_string
$1 = 0x17fbc450 "INSERT INTO fp_reentry_fk SELECT row(1)::fp_vch FROM generate_series(1, 2);"
It looks like something is not prepared for a cached plan to get
invalidated underneath it.
regards, tom lane
Re: Two more RI fast-path issues
От:
Amit Langote <amitlangote09@gmail.com>
Дата:
On Sat, Oct 17, 2026 at 12:17 AM Tom Lane wrote: > > There is still something wrong in the RI_FKey stuff. BF animal > trilobite reported a SIGSEGV in the foreign_key test, and I was able > to reproduce that locally by compiling HEAD with -DCLOBBER_CACHE_ALWAYS. > Stack trace looks like > > Program terminated with signal SIGSEGV, Segmentation fault. > #0 0x00000000007770df in _SPI_execute_plan (plan=plan@entry=0x184fafc0, options=options@entry=0x7fff7819da00, snapshot=snapshot@entry=0x0, crosscheck_snapshot=crosscheck_snapshot@entry=0x0, > fire_triggers=fire_triggers@entry=false) at spi.c:2498 > 2498 CachedPlanSource *plansource = (CachedPlanSource *) lfirst(lc1); > (gdb) bt > #0 0x00000000007770df in _SPI_execute_plan (plan=plan@entry=0x184fafc0, options=options@entry=0x7fff7819da00, snapshot=snapshot@entry=0x0, crosscheck_snapshot=crosscheck_snapshot@entry=0x0, > fire_triggers=fire_triggers@entry=false) at spi.c:2498 > #1 0x0000000000778030 in SPI_execute_snapshot (plan=plan@entry=0x184fafc0, Values=Values@entry=0x7fff7819db00, Nulls=Nulls@entry=0x7fff7819dac0 " ", snapshot=snapshot@entry=0x0, > crosscheck_snapshot=crosscheck_snapshot@entry=0x0, read_only=read_only@entry=false, fire_triggers=false, tcount=1) at spi.c:796 > #2 0x0000000000a1565c in ri_PerformCheck (riinfo=riinfo@entry=0x183d6738, qkey=qkey@entry=0x7fff7819ddb8, qplan=0x184fafc0, fk_rel=fk_rel@entry=0x7f4431f051d0, pk_rel=pk_rel@entry=0x7f4431f08190, > oldslot=oldslot@entry=0x0, newslot=0x1847e5a8, is_restrict=false, detectNewRows=false, expect_OK=5) at ri_triggers.c:2723 > #3 0x0000000000a16026 in RI_FKey_check (trigdata=) at ri_triggers.c:535 > #4 0x0000000000a17cdc in RI_FKey_check_ins (fcinfo=0x7fff7819e980) at ri_triggers.c:563 > #5 0x0000000000702b6d in ExecCallTriggerFunc (trigdata=trigdata@entry=0x7fff7819eb50, tgindx=tgindx@entry=0, finfo=finfo@entry=0x1821a620, instr=instr@entry=0x0, > per_tuple_context=per_tuple_context@entry=0x18198a80) at trigger.c:2409 > #6 0x0000000000704ed6 in AfterTriggerExecute (estate=, event=0x181a2bec, relInfo=0x1847c9c8, src_relInfo=, dst_relInfo=, trigdesc=0x1821a810, > finfo=0x1821a620, instr=0x0, per_tuple_context=, trig_tuple_slot1=0x0, trig_tuple_slot2=0x0) at trigger.c:4599 > #7 afterTriggerInvokeEvents (events=events@entry=0x180523b0, firing_id=1, estate=estate@entry=0x18218960, delete_ok=delete_ok@entry=false) at trigger.c:4840 > #8 0x000000000070a01b in AfterTriggerEndQuery (estate=estate@entry=0x18218960) at trigger.c:5222 > #9 0x000000000072ff34 in standard_ExecutorFinish (queryDesc=0x18482ac0) at execMain.c:454 > #10 0x000000000092f0d8 in ProcessQuery (plan=, sourceText=0x17fbc450 "INSERT INTO fp_reentry_fk SELECT row(1)::fp_vch FROM generate_series(1, 2);", params=0x0, queryEnv=0x0, > dest=0x184a2ba8, qc=0x7fff7819ee90) at pquery.c:190 > #11 0x000000000092fbf6 in PortalRunMulti (portal=portal@entry=0x18044070, isTopLevel=isTopLevel@entry=true, setHoldSnapshot=setHoldSnapshot@entry=false, dest=dest@entry=0x184a2ba8, > altdest=altdest@entry=0x184a2ba8, qc=qc@entry=0x7fff7819ee90) at pquery.c:1273 > #12 0x000000000092ffb7 in PortalRun (portal=portal@entry=0x18044070, count=count@entry=9223372036854775807, isTopLevel=isTopLevel@entry=true, dest=dest@entry=0x184a2ba8, > altdest=altdest@entry=0x184a2ba8, qc=qc@entry=0x7fff7819ee90) at pquery.c:788 > #13 0x000000000092be16 in exec_simple_query (query_string=0x17fbc450 "INSERT INTO fp_reentry_fk SELECT row(1)::fp_vch FROM generate_series(1, 2);") at postgres.c:1297 > #14 0x000000000092d9ad in PostgresMain (dbname=, username=) at postgres.c:4946 > #15 0x0000000000927d5d in BackendMain (startup_data=, startup_data_len=) at backend_startup.c:124 > #16 0x000000000086fb7d in postmaster_child_launch (child_type=, child_slot=4, startup_data=startup_data@entry=0x7fff7819f300, startup_data_len=startup_data_len@entry=24, > client_sock=client_sock@entry=0x7fff7819f320) at launch_backend.c:268 > #17 0x000000000087331f in BackendStartup (client_sock=0x7fff7819f320) at postmaster.c:3650 > #18 ServerLoop () at postmaster.c:1727 > #19 0x0000000000874c0a in PostmasterMain (argc=argc@entry=3, argv=argv@entry=0x17fb7e50) at postmaster.c:1414 > #20 0x0000000000532488 in main (argc=3, argv=0x17fb7e50) at main.c:227 > (gdb) p debug_query_string > $1 = 0x17fbc450 "INSERT INTO fp_reentry_fk SELECT row(1)::fp_vch FROM generate_series(1, 2);" > > It looks like something is not prepared for a cached plan to get > invalidated underneath it. Thanks for the heads up. Will debug this on Monday. -- Thanks, Amit Langote
Re: Two more RI fast-path issues
On Sat, Oct 17, 2026 at 10:36 AM Amit Langote wrote:
> On Sat, Oct 17, 2026 at 12:17 AM Tom Lane wrote:
> >
> > There is still something wrong in the RI_FKey stuff. BF animal
> > trilobite reported a SIGSEGV in the foreign_key test, and I was able
> > to reproduce that locally by compiling HEAD with -DCLOBBER_CACHE_ALWAYS.
> > Stack trace looks like
> >
> > Program terminated with signal SIGSEGV, Segmentation fault.
> > #0 0x00000000007770df in _SPI_execute_plan (plan=plan@entry=0x184fafc0, options=options@entry=0x7fff7819da00, snapshot=snapshot@entry=0x0, crosscheck_snapshot=crosscheck_snapshot@entry=0x0,
> > fire_triggers=fire_triggers@entry=false) at spi.c:2498
> > 2498 CachedPlanSource *plansource = (CachedPlanSource *) lfirst(lc1);
> > (gdb) bt
> > #0 0x00000000007770df in _SPI_execute_plan (plan=plan@entry=0x184fafc0, options=options@entry=0x7fff7819da00, snapshot=snapshot@entry=0x0, crosscheck_snapshot=crosscheck_snapshot@entry=0x0,
> > fire_triggers=fire_triggers@entry=false) at spi.c:2498
> > #1 0x0000000000778030 in SPI_execute_snapshot (plan=plan@entry=0x184fafc0, Values=Values@entry=0x7fff7819db00, Nulls=Nulls@entry=0x7fff7819dac0 " ", snapshot=snapshot@entry=0x0,
> > crosscheck_snapshot=crosscheck_snapshot@entry=0x0, read_only=read_only@entry=false, fire_triggers=false, tcount=1) at spi.c:796
> > #2 0x0000000000a1565c in ri_PerformCheck (riinfo=riinfo@entry=0x183d6738, qkey=qkey@entry=0x7fff7819ddb8, qplan=0x184fafc0, fk_rel=fk_rel@entry=0x7f4431f051d0, pk_rel=pk_rel@entry=0x7f4431f08190,
> > oldslot=oldslot@entry=0x0, newslot=0x1847e5a8, is_restrict=false, detectNewRows=false, expect_OK=5) at ri_triggers.c:2723
> > #3 0x0000000000a16026 in RI_FKey_check (trigdata=) at ri_triggers.c:535
> > #4 0x0000000000a17cdc in RI_FKey_check_ins (fcinfo=0x7fff7819e980) at ri_triggers.c:563
> > #5 0x0000000000702b6d in ExecCallTriggerFunc (trigdata=trigdata@entry=0x7fff7819eb50, tgindx=tgindx@entry=0, finfo=finfo@entry=0x1821a620, instr=instr@entry=0x0,
> > per_tuple_context=per_tuple_context@entry=0x18198a80) at trigger.c:2409
> > #6 0x0000000000704ed6 in AfterTriggerExecute (estate=, event=0x181a2bec, relInfo=0x1847c9c8, src_relInfo=, dst_relInfo=, trigdesc=0x1821a810,
> > finfo=0x1821a620, instr=0x0, per_tuple_context=, trig_tuple_slot1=0x0, trig_tuple_slot2=0x0) at trigger.c:4599
> > #7 afterTriggerInvokeEvents (events=events@entry=0x180523b0, firing_id=1, estate=estate@entry=0x18218960, delete_ok=delete_ok@entry=false) at trigger.c:4840
> > #8 0x000000000070a01b in AfterTriggerEndQuery (estate=estate@entry=0x18218960) at trigger.c:5222
> > #9 0x000000000072ff34 in standard_ExecutorFinish (queryDesc=0x18482ac0) at execMain.c:454
> > #10 0x000000000092f0d8 in ProcessQuery (plan=, sourceText=0x17fbc450 "INSERT INTO fp_reentry_fk SELECT row(1)::fp_vch FROM generate_series(1, 2);", params=0x0, queryEnv=0x0,
> > dest=0x184a2ba8, qc=0x7fff7819ee90) at pquery.c:190
> > #11 0x000000000092fbf6 in PortalRunMulti (portal=portal@entry=0x18044070, isTopLevel=isTopLevel@entry=true, setHoldSnapshot=setHoldSnapshot@entry=false, dest=dest@entry=0x184a2ba8,
> > altdest=altdest@entry=0x184a2ba8, qc=qc@entry=0x7fff7819ee90) at pquery.c:1273
> > #12 0x000000000092ffb7 in PortalRun (portal=portal@entry=0x18044070, count=count@entry=9223372036854775807, isTopLevel=isTopLevel@entry=true, dest=dest@entry=0x184a2ba8,
> > altdest=altdest@entry=0x184a2ba8, qc=qc@entry=0x7fff7819ee90) at pquery.c:788
> > #13 0x000000000092be16 in exec_simple_query (query_string=0x17fbc450 "INSERT INTO fp_reentry_fk SELECT row(1)::fp_vch FROM generate_series(1, 2);") at postgres.c:1297
> > #14 0x000000000092d9ad in PostgresMain (dbname=, username=) at postgres.c:4946
> > #15 0x0000000000927d5d in BackendMain (startup_data=, startup_data_len=) at backend_startup.c:124
> > #16 0x000000000086fb7d in postmaster_child_launch (child_type=, child_slot=4, startup_data=startup_data@entry=0x7fff7819f300, startup_data_len=startup_data_len@entry=24,
> > client_sock=client_sock@entry=0x7fff7819f320) at launch_backend.c:268
> > #17 0x000000000087331f in BackendStartup (client_sock=0x7fff7819f320) at postmaster.c:3650
> > #18 ServerLoop () at postmaster.c:1727
> > #19 0x0000000000874c0a in PostmasterMain (argc=argc@entry=3, argv=argv@entry=0x17fb7e50) at postmaster.c:1414
> > #20 0x0000000000532488 in main (argc=3, argv=0x17fb7e50) at main.c:227
> > (gdb) p debug_query_string
> > $1 = 0x17fbc450 "INSERT INTO fp_reentry_fk SELECT row(1)::fp_vch FROM generate_series(1, 2);"
> >
> > It looks like something is not prepared for a cached plan to get
> > invalidated underneath it.
>
> Thanks for the heads up. Will debug this on Monday.
I was able to reproduce this by adding set debug_discard_caches=1
before the test case seen in the above trace.
This is a use-after-free of a cached SPI plan in ri_triggers.c.
ri_FetchPreparedPlan() frees a plan it finds invalid without checking
whether an RI check further up the stack is still executing it, and
CLOBBER_CACHE_ALWAYS makes that happen in the fp_reentry test.
In that test case that I added to test the re-entrancy safety of the
fast-path code new in 19, a user-defined cast function running as a
part of the foreign key check itself performs an insert on the same
table thus re-entering RI_FKey_check(), which calls
ri_FetchPreparedPlan() for the same query key and so lands on the plan
the outer check is executing. Here’s the test, with a SET added before
the INSERT from your stack trace to get the CLOBBER_CACHE_ALWAYS
effect:
CREATE TABLE fp_reentry_pk (id int PRIMARY KEY);
INSERT INTO fp_reentry_pk VALUES (1), (2);
CREATE TYPE fp_vch AS (v int);
CREATE FUNCTION fp_vcast(fp_vch) RETURNS int LANGUAGE plpgsql AS $$
BEGIN
IF $1.v = 1 THEN
INSERT INTO fp_reentry_fk VALUES (row(2)::fp_vch);
END IF;
RETURN $1.v;
END$$;
CREATE CAST (fp_vch AS int) WITH FUNCTION fp_vcast(fp_vch) AS IMPLICIT;
CREATE TABLE fp_reentry_fk (a fp_vch REFERENCES fp_reentry_pk (id));
SET debug_discard_caches=1;
INSERT INTO fp_reentry_fk SELECT row(1)::fp_vch FROM generate_series(1, 2);
The inner check's ri_FetchPreparedPlan() sees under
CLOBBER_CACHE_ALWAYS that the plan is invalid and calls SPI_freeplan()
on it. The inner check completes using a fresh plan, but when the
control returns to the outer check in _SPI_execute_plan(), its loop
over plan->plancache_list reads the List header from freed memory
(0x7f-filled under CLOBBER_FREED_MEMORY), takes the garbage length to
mean there is a second cell, and segfaults dereferencing it. Any
invalidation of the plan between the outer check’s fetch and the inner
check’s fetch would have the same effect (cache clobbering just
guarantees one).
The bug itself is old. However, before 6aecabcd5ed5, in which I
changed the foreign key checks that need to call cast functions to go
through SPI, this test used the fast-path code and thus didn't hit
this bug. In fact, the fast-path had an analogous UAF bug, which I
fixed in 170c9344def. That bug occurred when an outer check was using
a FastPathMeta struct that InvalidateConstraintCacheCallBack() freed.
To fix, we can teach ri_FetchPreparedPlan() to “detach” a stale plan
from its ri_query_cache entry (by doing entry->plan = NULL), so a new
one can be put in place under the same key, and instead of calling
SPI_freeplan() append it to a list that is cleaned up at end of
transaction, when nothing on the stack can be referring to it. This
follows the model I used in 170c9344def, where invalidated
FastPathMeta structs are detached from their RI_ConstraintInfo and
added to a list that AtEOXact_RI() processes.
Patch for master attached. With it, the fp_reentry test case shown
above passes with debug_discard_caches=1. I’ve left the test as is but
added a comment mentioning that it exercises this under cache
clobbering, which is what found it.
This needs to go to all supported branches. AtEOXact_RI() exists only
in 19 and master; for the older ones I’d add it with just the plan
cleanup, so the code matches 19, rather than install a
RegisterXactCallback hook (which would also need to cover PREPARE, not
just COMMIT and ABORT).
Thoughts?
--
Thanks, Amit Langote
Re: Two more RI fast-path issues
От:
Lucas Jeffrey <luquijeffrey@gmail.com>
Дата:
Hi Amit About the reentrant RI check that frees a plan already in use, in this thread I already created a fix and it had a backfix for all supported branches: https://www.postgresql.org/message-id/flat/CAGHzy7S0XfXdK3amd5c4QhpS1o9dySVzPr+-d9ohaE4iV_vNog@mail.gmail.com It has this entry in the current commitfest: https://commitfest.postgresql.org/patch/6825/ On Mon, Oct 19, 2026 at 9:27 PM Amit Langote wrote: > > On Sat, Oct 17, 2026 at 10:36 AM Amit Langote wrote: > > On Sat, Oct 17, 2026 at 12:17 AM Tom Lane wrote: > > > > > > There is still something wrong in the RI_FKey stuff. BF animal > > > trilobite reported a SIGSEGV in the foreign_key test, and I was able > > > to reproduce that locally by compiling HEAD with -DCLOBBER_CACHE_ALWAYS. > > > Stack trace looks like > > > > > > Program terminated with signal SIGSEGV, Segmentation fault. > > > #0 0x00000000007770df in _SPI_execute_plan (plan=plan@entry=0x184fafc0, options=options@entry=0x7fff7819da00, snapshot=snapshot@entry=0x0, crosscheck_snapshot=crosscheck_snapshot@entry=0x0, > > > fire_triggers=fire_triggers@entry=false) at spi.c:2498 > > > 2498 CachedPlanSource *plansource = (CachedPlanSource *) lfirst(lc1); > > > (gdb) bt > > > #0 0x00000000007770df in _SPI_execute_plan (plan=plan@entry=0x184fafc0, options=options@entry=0x7fff7819da00, snapshot=snapshot@entry=0x0, crosscheck_snapshot=crosscheck_snapshot@entry=0x0, > > > fire_triggers=fire_triggers@entry=false) at spi.c:2498 > > > #1 0x0000000000778030 in SPI_execute_snapshot (plan=plan@entry=0x184fafc0, Values=Values@entry=0x7fff7819db00, Nulls=Nulls@entry=0x7fff7819dac0 " ", snapshot=snapshot@entry=0x0, > > > crosscheck_snapshot=crosscheck_snapshot@entry=0x0, read_only=read_only@entry=false, fire_triggers=false, tcount=1) at spi.c:796 > > > #2 0x0000000000a1565c in ri_PerformCheck (riinfo=riinfo@entry=0x183d6738, qkey=qkey@entry=0x7fff7819ddb8, qplan=0x184fafc0, fk_rel=fk_rel@entry=0x7f4431f051d0, pk_rel=pk_rel@entry=0x7f4431f08190, > > > oldslot=oldslot@entry=0x0, newslot=0x1847e5a8, is_restrict=false, detectNewRows=false, expect_OK=5) at ri_triggers.c:2723 > > > #3 0x0000000000a16026 in RI_FKey_check (trigdata=) at ri_triggers.c:535 > > > #4 0x0000000000a17cdc in RI_FKey_check_ins (fcinfo=0x7fff7819e980) at ri_triggers.c:563 > > > #5 0x0000000000702b6d in ExecCallTriggerFunc (trigdata=trigdata@entry=0x7fff7819eb50, tgindx=tgindx@entry=0, finfo=finfo@entry=0x1821a620, instr=instr@entry=0x0, > > > per_tuple_context=per_tuple_context@entry=0x18198a80) at trigger.c:2409 > > > #6 0x0000000000704ed6 in AfterTriggerExecute (estate=, event=0x181a2bec, relInfo=0x1847c9c8, src_relInfo=, dst_relInfo=, trigdesc=0x1821a810, > > > finfo=0x1821a620, instr=0x0, per_tuple_context=, trig_tuple_slot1=0x0, trig_tuple_slot2=0x0) at trigger.c:4599 > > > #7 afterTriggerInvokeEvents (events=events@entry=0x180523b0, firing_id=1, estate=estate@entry=0x18218960, delete_ok=delete_ok@entry=false) at trigger.c:4840 > > > #8 0x000000000070a01b in AfterTriggerEndQuery (estate=estate@entry=0x18218960) at trigger.c:5222 > > > #9 0x000000000072ff34 in standard_ExecutorFinish (queryDesc=0x18482ac0) at execMain.c:454 > > > #10 0x000000000092f0d8 in ProcessQuery (plan=, sourceText=0x17fbc450 "INSERT INTO fp_reentry_fk SELECT row(1)::fp_vch FROM generate_series(1, 2);", params=0x0, queryEnv=0x0, > > > dest=0x184a2ba8, qc=0x7fff7819ee90) at pquery.c:190 > > > #11 0x000000000092fbf6 in PortalRunMulti (portal=portal@entry=0x18044070, isTopLevel=isTopLevel@entry=true, setHoldSnapshot=setHoldSnapshot@entry=false, dest=dest@entry=0x184a2ba8, > > > altdest=altdest@entry=0x184a2ba8, qc=qc@entry=0x7fff7819ee90) at pquery.c:1273 > > > #12 0x000000000092ffb7 in PortalRun (portal=portal@entry=0x18044070, count=count@entry=9223372036854775807, isTopLevel=isTopLevel@entry=true, dest=dest@entry=0x184a2ba8, > > > altdest=altdest@entry=0x184a2ba8, qc=qc@entry=0x7fff7819ee90) at pquery.c:788 > > > #13 0x000000000092be16 in exec_simple_query (query_string=0x17fbc450 "INSERT INTO fp_reentry_fk SELECT row(1)::fp_vch FROM generate_series(1, 2);") at postgres.c:1297 > > > #14 0x000000000092d9ad in PostgresMain (dbname=, username=) at postgres.c:4946 > > > #15 0x0000000000927d5d in BackendMain (startup_data=, startup_data_len=) at backend_startup.c:124 > > > #16 0x000000000086fb7d in postmaster_child_launch (child_type=, child_slot=4, startup_data=startup_data@entry=0x7fff7819f300, startup_data_len=startup_data_len@entry=24, > > > client_sock=client_sock@entry=0x7fff7819f320) at launch_backend.c:268 > > > #17 0x000000000087331f in BackendStartup (client_sock=0x7fff7819f320) at postmaster.c:3650 > > > #18 ServerLoop () at postmaster.c:1727 > > > #19 0x0000000000874c0a in PostmasterMain (argc=argc@entry=3, argv=argv@entry=0x17fb7e50) at postmaster.c:1414 > > > #20 0x0000000000532488 in main (argc=3, argv=0x17fb7e50) at main.c:227 > > > (gdb) p debug_query_string > > > $1 = 0x17fbc450 "INSERT INTO fp_reentry_fk SELECT row(1)::fp_vch FROM generate_series(1, 2);" > > > > > > It looks like something is not prepared for a cached plan to get > > > invalidated underneath it. > > > > Thanks for the heads up. Will debug this on Monday. > > I was able to reproduce this by adding set debug_discard_caches=1 > before the test case seen in the above trace. > > This is a use-after-free of a cached SPI plan in ri_triggers.c. > ri_FetchPreparedPlan() frees a plan it finds invalid without checking > whether an RI check further up the stack is still executing it, and > CLOBBER_CACHE_ALWAYS makes that happen in the fp_reentry test. > > In that test case that I added to test the re-entrancy safety of the > fast-path code new in 19, a user-defined cast function running as a > part of the foreign key check itself performs an insert on the same > table thus re-entering RI_FKey_check(), which calls > ri_FetchPreparedPlan() for the same query key and so lands on the plan > the outer check is executing. Here’s the test, with a SET added before > the INSERT from your stack trace to get the CLOBBER_CACHE_ALWAYS > effect: > > CREATE TABLE fp_reentry_pk (id int PRIMARY KEY); > INSERT INTO fp_reentry_pk VALUES (1), (2); > CREATE TYPE fp_vch AS (v int); > CREATE FUNCTION fp_vcast(fp_vch) RETURNS int LANGUAGE plpgsql AS $$ > BEGIN > IF $1.v = 1 THEN > INSERT INTO fp_reentry_fk VALUES (row(2)::fp_vch); > END IF; > RETURN $1.v; > END$$; > CREATE CAST (fp_vch AS int) WITH FUNCTION fp_vcast(fp_vch) AS IMPLICIT; > CREATE TABLE fp_reentry_fk (a fp_vch REFERENCES fp_reentry_pk (id)); > > SET debug_discard_caches=1; > INSERT INTO fp_reentry_fk SELECT row(1)::fp_vch FROM generate_series(1, 2); > > The inner check's ri_FetchPreparedPlan() sees under > CLOBBER_CACHE_ALWAYS that the plan is invalid and calls SPI_freeplan() > on it. The inner check completes using a fresh plan, but when the > control returns to the outer check in _SPI_execute_plan(), its loop > over plan->plancache_list reads the List header from freed memory > (0x7f-filled under CLOBBER_FREED_MEMORY), takes the garbage length to > mean there is a second cell, and segfaults dereferencing it. Any > invalidation of the plan between the outer check’s fetch and the inner > check’s fetch would have the same effect (cache clobbering just > guarantees one). > > The bug itself is old. However, before 6aecabcd5ed5, in which I > changed the foreign key checks that need to call cast functions to go > through SPI, this test used the fast-path code and thus didn't hit > this bug. In fact, the fast-path had an analogous UAF bug, which I > fixed in 170c9344def. That bug occurred when an outer check was using > a FastPathMeta struct that InvalidateConstraintCacheCallBack() freed. > > To fix, we can teach ri_FetchPreparedPlan() to “detach” a stale plan > from its ri_query_cache entry (by doing entry->plan = NULL), so a new > one can be put in place under the same key, and instead of calling > SPI_freeplan() append it to a list that is cleaned up at end of > transaction, when nothing on the stack can be referring to it. This > follows the model I used in 170c9344def, where invalidated > FastPathMeta structs are detached from their RI_ConstraintInfo and > added to a list that AtEOXact_RI() processes. > > Patch for master attached. With it, the fp_reentry test case shown > above passes with debug_discard_caches=1. I’ve left the test as is but > added a comment mentioning that it exercises this under cache > clobbering, which is what found it. > > This needs to go to all supported branches. AtEOXact_RI() exists only > in 19 and master; for the older ones I’d add it with just the plan > cleanup, so the code matches 19, rather than install a > RegisterXactCallback hook (which would also need to cover PREPARE, not > just COMMIT and ABORT). > > Thoughts? > > -- > Thanks, Amit Langote
Re: Two more RI fast-path issues
От:
Amit Langote <amitlangote09@gmail.com>
Дата:
Hi Lucas,
On Tue, Oct 20, 2026 at 9:49 Lucas Jeffrey <luquijeffrey@gmail.com> wrote:
Hi Amit
About the reentrant RI check that frees a plan already in use, in this
thread I already created a fix and it had a backfix for all supported
branches:
https://www.postgresql.org/message-id/flat/CAGHzy7S0XfXdK3amd5c4QhpS1o9dySVzPr+-d9ohaE4iV_vNog@mail.gmail.com
It has this entry in the current commitfest:
https://commitfest.postgresql.org/patch/6825/
Ah, thanks for reminding me of it. I didn’t realize it’s chasing the same issue essentially.
I’ll take a look and reply over there.
- Amit
Re: Two more RI fast-path issues
От:
Amit Langote <amitlangote09@gmail.com>
Дата:
On Tue, Oct 20, 2026 at 10:45 AM Amit Langote wrote: > On Tue, Oct 20, 2026 at 9:49 Lucas Jeffrey wrote: >> >> Hi Amit >> About the reentrant RI check that frees a plan already in use, in this >> thread I already created a fix and it had a backfix for all supported >> branches: >> https://www.postgresql.org/message-id/flat/CAGHzy7S0XfXdK3amd5c4QhpS1o9dySVzPr+-d9ohaE4iV_vNog@mail.gmail.com >> >> It has this entry in the current commitfest: >> https://commitfest.postgresql.org/patch/6825/ > > > Ah, thanks for reminding me of it. I didn’t realize it’s chasing the same issue essentially. > > I’ll take a look and reply over there. FTR, I've posted the patch to that thread and will continue the discussion there. That thread has a title more relevant to the issue and the patch. -- Thanks, Amit Langote
Re: Two more RI fast-path issues
От:
Alexander Lakhin <exclusion@gmail.com>
Дата:
Hello Amit,
08.10.2026 06:58, Amit Langote wrote:
> On Wed, Oct 7, 2026 at 10:02 PM Amit Langote wrote:
>> On Tue, Oct 6, 2026 at 3:20 PM Amit Langote wrote:
>> ...
>> Barring comments, would like to push the attached slightly updated
>> version (comment, commit message fixes) tomorrow after committing the
>> patches in [1] because I rebased these over those other patches.
> I've pushed these.
I've accidentially discovered that a test case added with 061065e28 can
produce a new assertion failure with just:
- UPDATE fp_pk_cid SET v = v + 1 WHERE id OPERATOR(pg_catalog.=) $1;
+ UPDATE fp_pk_cid SET id = id + 1 WHERE id OPERATOR(pg_catalog.=) $1;
TRAP: failed Assert("entry->data.lockmode == BUFFER_LOCK_UNLOCK"), File: "bufmgr.c", Line: 5941, PID: 2303915
ExceptionalCondition at assert.c:51:13
BufferLockAcquire at bufmgr.c:5948:2
LockBufferInternal at bufmgr.c:6631:3
LockBuffer at bufmgr.h:340:1
_bt_lockbuf at nbtpage.c:1072:1
_bt_getbuf at nbtpage.c:839:2
_bt_getroot at nbtpage.c:380:13
_bt_search at nbtsearch.c:113:8
_bt_search_insert at nbtinsert.c:385:1
_bt_doinsert at nbtinsert.c:170:10
btinsert at nbtree.c:225:11
index_insert at indexam.c:235:9
ExecInsertIndexTuples at execIndexing.c:450:4
ExecUpdateEpilogue at nodeModifyTable.c:2372:20
ExecUpdate at nodeModifyTable.c:2754:19
ExecModifyTable at nodeModifyTable.c:4801:12
ExecProcNodeFirst at execProcnode.c:470:1
...
2026-11-18 07:06:47.374 EET postmaster[2302673] LOG: client backend (PID 2303915) was terminated by signal 6: Aborted
2026-11-18 07:06:47.374 EET postmaster[2302673] DETAIL: Failed process was running: INSERT INTO fp_fk_cid VALUES (1);
Could you please have a look?
Best regards,
Alexander
Re: Two more RI fast-path issues
От:
Amit Langote <amitlangote09@gmail.com>
Дата:
HI Alexander,
On Wed, Nov 18, 2026 at 3:00 PM Alexander Lakhin wrote:
>
> Hello Amit,
>
> 08.10.2026 06:58, Amit Langote wrote:
> > On Wed, Oct 7, 2026 at 10:02 PM Amit Langote wrote:
> >> On Tue, Oct 6, 2026 at 3:20 PM Amit Langote wrote:
> >> ...
> >> Barring comments, would like to push the attached slightly updated
> >> version (comment, commit message fixes) tomorrow after committing the
> >> patches in [1] because I rebased these over those other patches.
> > I've pushed these.
>
> I've accidentially discovered that a test case added with 061065e28 can
> produce a new assertion failure with just:
> - UPDATE fp_pk_cid SET v = v + 1 WHERE id OPERATOR(pg_catalog.=) $1;
> + UPDATE fp_pk_cid SET id = id + 1 WHERE id OPERATOR(pg_catalog.=) $1;
>
> TRAP: failed Assert("entry->data.lockmode == BUFFER_LOCK_UNLOCK"), File: "bufmgr.c", Line: 5941, PID: 2303915
> ExceptionalCondition at assert.c:51:13
> BufferLockAcquire at bufmgr.c:5948:2
> LockBufferInternal at bufmgr.c:6631:3
> LockBuffer at bufmgr.h:340:1
> _bt_lockbuf at nbtpage.c:1072:1
> _bt_getbuf at nbtpage.c:839:2
> _bt_getroot at nbtpage.c:380:13
> _bt_search at nbtsearch.c:113:8
> _bt_search_insert at nbtinsert.c:385:1
> _bt_doinsert at nbtinsert.c:170:10
> btinsert at nbtree.c:225:11
> index_insert at indexam.c:235:9
> ExecInsertIndexTuples at execIndexing.c:450:4
> ExecUpdateEpilogue at nodeModifyTable.c:2372:20
> ExecUpdate at nodeModifyTable.c:2754:19
> ExecModifyTable at nodeModifyTable.c:4801:12
> ExecProcNodeFirst at execProcnode.c:470:1
> ...
> 2026-11-18 07:06:47.374 EET postmaster[2302673] LOG: client backend (PID 2303915) was terminated by signal 6: Aborted
> 2026-11-18 07:06:47.374 EET postmaster[2302673] DETAIL: Failed process was running: INSERT INTO fp_fk_cid VALUES (1);
>
> Could you please have a look?
Thanks for testing.
I looked into this and it doesn't seem to be a bug in the fast-path or
elsewhere. With your change, fp_cid_eq() (the function behind the
index's equality operator) updates the indexed column, so the UPDATE
in it needs to insert a new entry into the index fp_pk_cid_id. But
fp_cid_eq() is called from _bt_readpage(), which holds a share lock on
the leaf page while checking scan keys. So the nested insert seems to
end up trying to lock the same page (the root is the only leaf here)
that the backend has already locked. On master, that fails the
assertion added by fcb9c977aa5. I also checked on 18 just to be sure
and I found that the backend hangs in _bt_search() instead, waiting
for an exclusive lock on the page that it already holds a share lock
on. In fact, a plain index scan using the operator hits the same
assertion on master, with no foreign key involved:
SET enable_seqscan = off;
SELECT * FROM fp_pk_cid WHERE id =~= 1;
server closed the connection unexpectedly
...
That's also why the test updates v and not id, as the comment above it mentions:
-- ... The
-- equality function runs while the scan holds the index page locked; its
-- UPDATE is a HOT update, since v isn't indexed, so it doesn't touch the
-- index.
The test only needs the equality function to update the referenced row
so that the command counter advances before the row lock is taken, and
a HOT update is enough for that.
--
Thanks, Amit Langote
Re: Two more RI fast-path issues
От:
Amit Langote <amitlangote09@gmail.com>
Дата:
On Wed, Nov 18, 2026 at 4:12 PM Amit Langote wrote:
>
> HI Alexander,
>
> On Wed, Nov 18, 2026 at 3:00 PM Alexander Lakhin wrote:
> >
> > Hello Amit,
> >
> > 08.10.2026 06:58, Amit Langote wrote:
> > > On Wed, Oct 7, 2026 at 10:02 PM Amit Langote wrote:
> > >> On Tue, Oct 6, 2026 at 3:20 PM Amit Langote wrote:
> > >> ...
> > >> Barring comments, would like to push the attached slightly updated
> > >> version (comment, commit message fixes) tomorrow after committing the
> > >> patches in [1] because I rebased these over those other patches.
> > > I've pushed these.
> >
> > I've accidentially discovered that a test case added with 061065e28 can
> > produce a new assertion failure with just:
> > - UPDATE fp_pk_cid SET v = v + 1 WHERE id OPERATOR(pg_catalog.=) $1;
> > + UPDATE fp_pk_cid SET id = id + 1 WHERE id OPERATOR(pg_catalog.=) $1;
> >
> > TRAP: failed Assert("entry->data.lockmode == BUFFER_LOCK_UNLOCK"), File: "bufmgr.c", Line: 5941, PID: 2303915
> > ExceptionalCondition at assert.c:51:13
> > BufferLockAcquire at bufmgr.c:5948:2
> > LockBufferInternal at bufmgr.c:6631:3
> > LockBuffer at bufmgr.h:340:1
> > _bt_lockbuf at nbtpage.c:1072:1
> > _bt_getbuf at nbtpage.c:839:2
> > _bt_getroot at nbtpage.c:380:13
> > _bt_search at nbtsearch.c:113:8
> > _bt_search_insert at nbtinsert.c:385:1
> > _bt_doinsert at nbtinsert.c:170:10
> > btinsert at nbtree.c:225:11
> > index_insert at indexam.c:235:9
> > ExecInsertIndexTuples at execIndexing.c:450:4
> > ExecUpdateEpilogue at nodeModifyTable.c:2372:20
> > ExecUpdate at nodeModifyTable.c:2754:19
> > ExecModifyTable at nodeModifyTable.c:4801:12
> > ExecProcNodeFirst at execProcnode.c:470:1
> > ...
> > 2026-11-18 07:06:47.374 EET postmaster[2302673] LOG: client backend (PID 2303915) was terminated by signal 6: Aborted
> > 2026-11-18 07:06:47.374 EET postmaster[2302673] DETAIL: Failed process was running: INSERT INTO fp_fk_cid VALUES (1);
> >
> > Could you please have a look?
>
> Thanks for testing.
>
> I looked into this and it doesn't seem to be a bug in the fast-path or
> elsewhere. With your change, fp_cid_eq() (the function behind the
> index's equality operator) updates the indexed column, so the UPDATE
> in it needs to insert a new entry into the index fp_pk_cid_id. But
> fp_cid_eq() is called from _bt_readpage(), which holds a share lock on
> the leaf page while checking scan keys. So the nested insert seems to
> end up trying to lock the same page (the root is the only leaf here)
> that the backend has already locked. On master, that fails the
> assertion added by fcb9c977aa5. I also checked on 18 just to be sure
> and I found that the backend hangs in _bt_search() instead, waiting
> for an exclusive lock on the page that it already holds a share lock
> on. In fact, a plain index scan using the operator hits the same
> assertion on master, with no foreign key involved:
>
> SET enable_seqscan = off;
> SELECT * FROM fp_pk_cid WHERE id =~= 1;
> server closed the connection unexpectedly
> ...
>
> That's also why the test updates v and not id, as the comment above it mentions:
>
> -- ... The
> -- equality function runs while the scan holds the index page locked; its
> -- UPDATE is a HOT update, since v isn't indexed, so it doesn't touch the
> -- index.
>
> The test only needs the equality function to update the referenced row
> so that the command counter advances before the row lock is taken, and
> a HOT update is enough for that.
Note that getting into this state requires an operator class whose
equality function modifies the index it's being called for, which
nomrally should not be the case. Only a superuser can create an
operator class, and the documentation of CREATE OPERATOR CLASS says
that "this restriction is made because an erroneous operator class
definition could confuse or even crash the server":
https://www.postgresql.org/docs/current/sql-createopclass.html
--
Thanks, Amit Langote