pg.ddx.io  pgsql-bugs@postgresql.org mailing list archive  
help / color / mirror / Atom feed
Lost FOR KEY SHARE lock
2+ messages / 2 participants
[nested] [flat]

* Lost FOR KEY SHARE lock
@ 2026-11-02 14:07  Heikki Linnakangas <hlinnaka@iki.fi>
  0 siblings, 1 reply; 2+ messages in thread

From: Heikki Linnakangas @ 2026-11-02 14:07 UTC (permalink / raw)
  To: pgsql-bugs@lists.postgresql.org <pgsql-bugs@lists.postgresql.org>

Hi,

While looking at another issue [1], I noticed that there's a race 
condition in heap_update() where a FOR KEY SHARE lock can be lost. 
Leaving out a lot of details, heap_update() looks like this:

>     /*
>      * If the tuple we're updating is locked, we need to preserve the locking
>      * info in the old tuple's Xmax.  Prepare a new Xmax value for this.
>      */
>     compute_new_xmax_infomask(HeapTupleHeaderGetRawXmax(oldtup.t_data),
>                               oldtup.t_data->t_infomask,
>                               oldtup.t_data->t_infomask2,
>                               xid, *lockmode, true,
>                               &xmax_old_tuple, &infomask_old_tuple,
>                               &infomask2_old_tuple);
>     ...
>     if (need_toast || newtupsize > pagefree)
>     {
>         ...
>         /*
>          * To prevent concurrent sessions from updating the tuple, we have to
>          * temporarily mark it locked, while we release the page-level lock.
>          *
>          * To satisfy the rule that any xid potentially appearing in a buffer
>          * written out to disk, we unfortunately have to WAL log this
>          * temporary modification.  We can reuse xl_heap_lock for this
>          * purpose.  If we crash/error before following through with the
>          * actual update, xmax will be of an aborted transaction, allowing
>          * other sessions to proceed.
>          */
> 
>         /*
>          * Compute xmax / infomask appropriate for locking the tuple. This has
>          * to be done separately from the combo that's going to be used for
>          * updating, because the potentially created multixact would otherwise
>          * be wrong.
>          */
>         compute_new_xmax_infomask(HeapTupleHeaderGetRawXmax(oldtup.t_data),
>                                   oldtup.t_data->t_infomask,
>                                   oldtup.t_data->t_infomask2,
>                                   xid, *lockmode, false,
>                                   &xmax_lock_old_tuple, &infomask_lock_old_tuple,
>                                   &infomask2_lock_old_tuple);
> 
>          /* ... update the old tuple with the computed values ... */
>
>          LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
> 
>          /* ... toast or find new page ... */
>
>          /* Re-acquire the lock on the old tuple's page. */
>          LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
>     }
> 
>     /* Clear obsolete visibility flags, possibly set by ourselves above... */
>     oldtup.t_data->t_infomask &= ~(HEAP_XMAX_BITS | HEAP_MOVED);
>     oldtup.t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
>     /* ... and store info about transaction updating this tuple */
>     Assert(TransactionIdIsValid(xmax_old_tuple));
>     HeapTupleHeaderSetXmax(oldtup.t_data, xmax_old_tuple);
>     oldtup.t_data->t_infomask |= infomask_old_tuple;
>     oldtup.t_data->t_infomask2 |= infomask2_old_tuple;
>     HeapTupleHeaderSetCmax(oldtup.t_data, cid, iscombo);

While we're not holding the lock, another backend can acquire a KEY 
SHARE lock on the tuple. But the 'xmax_old_tuple', 'infomask_old_tuple', 
and 'infomask2_old_tuple' values were calculated before releasing the 
lock, and won't include the new locker. By updating the old tuple with 
those values, any KEY SHARE lock acquired in that window is lost.

Attached is an isolation test case to demonstrate that. I ran out of 
energy trying to fix it; it doesn't seem that hard at first glance but 
it's a little subtle. If you just recompute the values after locking the 
tuple, then the values will also include the transaction's own lock on 
the tuple. That's not wrong, but I think it will lead to a lot of extra 
multixid. I think this needs to the members of the multixid, remove 
itself as a locker, and add back as an updater.

Another observation is that if the transaction already has a suitable 
lock on the tuple, there's no need to lock it again here. That would 
seem like an easy optimization. heap_lock_tuple() already contains logic 
for that, it could perhaps be reused here.

- Heikki

Attachments:

lost-for-share-lock-repro.patch (text/x-patch, 5.9K) download diff --git a/src/backend/access/heap/heapam.c b/src/backend/access/heap/heapam.c index 6a09a1a1517..b0bdb789523 100644 --- a/src/backend/access/heap/heapam.c +++ b/src/backend/access/heap/heapam.c @@ -3965,6 +3965,8 @@ l2: LockBuffer(buffer, BUFFER_LOCK_UNLOCK); + INJECTION_POINT("heap_update-toast-unlocked", NULL); + /* * Let the toaster do its thing, if needed. * @@ -4221,6 +4223,12 @@ l2: oldtup.t_data->t_infomask &= ~(HEAP_XMAX_BITS | HEAP_MOVED); oldtup.t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED; /* ... and store info about transaction updating this tuple */ + /* + * FIXME: These values were computed before temporarily released the + * lock. If the tuple was locked in FOR KEY SHARE mode while we were not + * holding the lock, these do not contain the locker's XID, and the lock + * is lost. + */ Assert(TransactionIdIsValid(xmax_old_tuple)); HeapTupleHeaderSetXmax(oldtup.t_data, xmax_old_tuple); oldtup.t_data->t_infomask |= infomask_old_tuple; diff --git a/src/test/modules/injection_points/Makefile b/src/test/modules/injection_points/Makefile index 8e2dfaa2384..b06a149b15c 100644 --- a/src/test/modules/injection_points/Makefile +++ b/src/test/modules/injection_points/Makefile @@ -37,7 +37,8 @@ ISOLATION = basic \ $(WAIT_CLEANUP_TST) \ heap_lock_update \ on_conflict_probe_window \ - multixact-aborted-updater + multixact-aborted-updater \ + heap_update_toast_lock # some isolation tests require wal_level=replica ISOLATION_OPTS = --temp-config $(top_srcdir)/src/test/modules/injection_points/extra.conf diff --git a/src/test/modules/injection_points/expected/heap_update_toast_lock.out b/src/test/modules/injection_points/expected/heap_update_toast_lock.out new file mode 100644 index 00000000000..57f0bfab2fc --- /dev/null +++ b/src/test/modules/injection_points/expected/heap_update_toast_lock.out @@ -0,0 +1,26 @@ +Parsed test spec with 3 sessions + +starting permutation: s1update s2begin s2keyshare wake s1keyupdate s2commit s1check +step s1update: UPDATE t SET val = bigstring() WHERE id = 1; <waiting ...> +step s2begin: BEGIN; +step s2keyshare: SELECT id FROM t WHERE id = 1 FOR KEY SHARE; +id +-- + 1 +(1 row) + +step wake: + SELECT FROM injection_points_detach('heap_update-toast-unlocked'); + SELECT FROM injection_points_wakeup('heap_update-toast-unlocked'); + <waiting ...> +step s1update: <... completed> +step wake: <... completed> +step s1keyupdate: UPDATE t SET id = id + 1; <waiting ...> +step s2commit: COMMIT; +step s1keyupdate: <... completed> +step s1check: SELECT id, length(val), other FROM t; +id|length|other +--+------+----- + 2| 6400| 0 +(1 row) + diff --git a/src/test/modules/injection_points/meson.build b/src/test/modules/injection_points/meson.build index 97e7a736282..db455f1d9b5 100644 --- a/src/test/modules/injection_points/meson.build +++ b/src/test/modules/injection_points/meson.build @@ -45,6 +45,7 @@ injection_points_isolation = [ 'heap_lock_update', 'on_conflict_probe_window', 'multixact-aborted-updater', + 'heap_update_toast_lock', ] # wait_cleanup terminates another backend, whose FATAL message can be lost diff --git a/src/test/modules/injection_points/specs/heap_update_toast_lock.spec b/src/test/modules/injection_points/specs/heap_update_toast_lock.spec new file mode 100644 index 00000000000..32088a534d4 --- /dev/null +++ b/src/test/modules/injection_points/specs/heap_update_toast_lock.spec @@ -0,0 +1,73 @@ +# Test that heap_update() protects the old tuple from concurrent updates +# while it has released the buffer lock to do TOASTing. +# +# When the new tuple needs toasting (or doesn't fit on the page), heap_update() +# temporarily marks the old tuple as locked by its own transaction, using the +# tuple lock mode computed from the modified columns (LockTupleNoKeyExclusive +# if no key columns were changed), and releases the buffer lock. While it's +# not holding the buffer lock, another transaction can acquire a KEY SHARE lock +# on the same tuple. +# +# The bug: the FOR SHARE lock acquired in that window will be lost when the +# update finishes, because the update overwrites the tuple's xmax with a new +# xmax and infomasks that were computed before releasing the lock. +setup +{ + CREATE EXTENSION injection_points; + + CREATE TABLE t (id int PRIMARY KEY, val text, other int); + INSERT INTO t VALUES (1, 'initial', 0); + + -- random, incompressible text well over TOAST_TUPLE_THRESHOLD + CREATE FUNCTION bigstring() RETURNS text AS $$ + SELECT string_agg(md5(i::text), '') FROM generate_series(1, 200) i + $$ LANGUAGE SQL +} +teardown +{ + DROP TABLE t; + DROP EXTENSION injection_points; +} + +session s1 +setup { + SELECT FROM injection_points_set_local(); + SELECT FROM injection_points_attach('heap_update-toast-unlocked', 'wait'); +} + +step s1update { UPDATE t SET val = bigstring() WHERE id = 1; } +step s1keyupdate { UPDATE t SET id = id + 1;} + +step s1check { SELECT id, length(val), other FROM t; } + +session s2 +step s2begin { BEGIN; } +step s2keyshare { SELECT id FROM t WHERE id = 1 FOR KEY SHARE; } +step s2commit { COMMIT; } + +session wake +step wake { + SELECT FROM injection_points_detach('heap_update-toast-unlocked'); + SELECT FROM injection_points_wakeup('heap_update-toast-unlocked'); +} + +# Concurrent non-key update must wait for s1 to commit. +permutation + # Start UPDATE on the tuple. This pauses on the injection point, after + # locking the tuple but before completing the UPDATE. + s1update + + # Lock the tuple from another session + s2begin s2keyshare + + # Finish the update and the s2 locker. Session s2 continues to + # hold its KEY SHARE lock. + wake(s1update) + + # Try to update the key column. This should block on s2's FOR KEY SHARE lock + # + # FIXME: this does not block as it should + s1keyupdate + + s2commit + s1check
^ permalink raw reply [nested|flat] 2+ messages in thread

* Re: Lost FOR KEY SHARE lock
@ 2026-11-17 02:10  shihao zhong <zhong950419@gmail.com>
  parent: Heikki Linnakangas <hlinnaka@iki.fi>
  0 siblings, 0 replies; 2+ messages in thread

From: shihao zhong @ 2026-11-17 02:10 UTC (permalink / raw)
  To: Heikki Linnakangas <hlinnaka@iki.fi>; +Cc: pgsql-bugs@lists.postgresql.org <pgsql-bugs@lists.postgresql.org>

Hi Heikki,

Thanks for the report. Any update that moves the row to a new page
hits this too, no TOAST needed. In a short pgbench run it left orphaned
FK rows on master, and none with the patch.

0001 does what you suggested. It drops our own lock and adds us back
as the updater, only when the xmax changed. 0002 is your test with a
few more cases.

The fix goes back to 15

Thanks,
Shihao

Attachments: download all (2 files, .tar.gz)

v1-0002-Add-test-for-KEY-SHARE-locks-taken-while-heap_update.patch (application/octet-stream, 10.9K) download From a632aaa3ae78a61764c13e916bcda5f3565c34a0 Mon Sep 17 00:00:00 2001 From: shihao zhong <zhong950419@gmail.com> Date: Mon, 16 Nov 2026 21:03:29 -0500 Subject: [PATCH 2/2] Add test for KEY SHARE locks taken while heap_update() is unlocked Adds an injection point where heap_update() has released the buffer lock, and an isolation test using it. Reported-by: Heikki Linnakangas <hlinnaka@iki.fi> Discussion: https://postgr.es/m/ce8b11dd-5908-45ac-bb3a-4ccfd5f88cf5@iki.fi Backpatch-through: 17 --- src/backend/access/heap/heapam.c | 2 + src/test/modules/injection_points/Makefile | 3 +- .../expected/heap_update_lock_window.out | 144 ++++++++++++++++++ src/test/modules/injection_points/meson.build | 1 + .../specs/heap_update_lock_window.spec | 139 +++++++++++++++++ 5 files changed, 288 insertions(+), 1 deletion(-) create mode 100644 src/test/modules/injection_points/expected/heap_update_lock_window.out create mode 100644 src/test/modules/injection_points/specs/heap_update_lock_window.spec diff --git a/src/backend/access/heap/heapam.c b/src/backend/access/heap/heapam.c index 56dde26d6c5..0cb65fbc93c 100644 --- a/src/backend/access/heap/heapam.c +++ b/src/backend/access/heap/heapam.c @@ -3978,6 +3978,8 @@ l2: LockBuffer(buffer, BUFFER_LOCK_UNLOCK); + INJECTION_POINT("heap_update-unlocked", NULL); + /* * Let the toaster do its thing, if needed. * diff --git a/src/test/modules/injection_points/Makefile b/src/test/modules/injection_points/Makefile index a7a16d5016a..bb748ad827f 100644 --- a/src/test/modules/injection_points/Makefile +++ b/src/test/modules/injection_points/Makefile @@ -37,7 +37,8 @@ ISOLATION = basic \ $(WAIT_CLEANUP_TST) \ heap_lock_update \ on_conflict_probe_window \ - multixact-aborted-updater + multixact-aborted-updater \ + heap_update_lock_window # some isolation tests require wal_level=replica ISOLATION_OPTS = --temp-config $(top_srcdir)/src/test/modules/injection_points/extra.conf diff --git a/src/test/modules/injection_points/expected/heap_update_lock_window.out b/src/test/modules/injection_points/expected/heap_update_lock_window.out new file mode 100644 index 00000000000..5f9d91294f8 --- /dev/null +++ b/src/test/modules/injection_points/expected/heap_update_lock_window.out @@ -0,0 +1,144 @@ +Parsed test spec with 4 sessions + +starting permutation: s1toast s2begin s2keyshare wake s1keyupdate s2commit s1check +step s1toast: UPDATE t SET val = bigstring() WHERE id = 1; <waiting ...> +step s2begin: BEGIN; +step s2keyshare: SELECT id FROM t WHERE id = 1 FOR KEY SHARE; +id +-- + 1 +(1 row) + +step wake: + SELECT FROM injection_points_detach('heap_update-unlocked'); + SELECT FROM injection_points_wakeup('heap_update-unlocked'); + +step s1toast: <... completed> +step s1keyupdate: UPDATE t SET id = id + 1; <waiting ...> +step s2commit: COMMIT; +step s1keyupdate: <... completed> +step s1check: SELECT id, length(val) FROM t; +id|length +--+------ + 2| 6400 +(1 row) + + +starting permutation: s1newpage s2begin s2keysharef wake s1keyupdatef s2commit +step s1newpage: UPDATE f SET other = other + 1 WHERE id = 1; <waiting ...> +step s2begin: BEGIN; +step s2keysharef: SELECT id FROM f WHERE id = 1 FOR KEY SHARE; +id +-- + 1 +(1 row) + +step wake: + SELECT FROM injection_points_detach('heap_update-unlocked'); + SELECT FROM injection_points_wakeup('heap_update-unlocked'); + +step s1newpage: <... completed> +step s1keyupdatef: UPDATE f SET id = -id WHERE id = 1; <waiting ...> +step s2commit: COMMIT; +step s1keyupdatef: <... completed> + +starting permutation: s1toast s2begin s2insertchild wake s1delete s2commit s1orphans +step s1toast: UPDATE t SET val = bigstring() WHERE id = 1; <waiting ...> +step s2begin: BEGIN; +step s2insertchild: INSERT INTO c VALUES (1); +step wake: + SELECT FROM injection_points_detach('heap_update-unlocked'); + SELECT FROM injection_points_wakeup('heap_update-unlocked'); + +step s1toast: <... completed> +step s1delete: DELETE FROM t WHERE id = 1; <waiting ...> +step s2commit: COMMIT; +step s1delete: <... completed> +ERROR: update or delete on table "t" violates foreign key constraint "c_pid_fkey" on table "c" +step s1orphans: SELECT count(*) AS orphans FROM c WHERE pid NOT IN (SELECT id FROM t); +orphans +------- + 0 +(1 row) + + +starting permutation: s1begin s1toast s2begin s2keyshare wake s1rollback s1keyupdate s2commit s1check +step s1begin: BEGIN; +step s1toast: UPDATE t SET val = bigstring() WHERE id = 1; <waiting ...> +step s2begin: BEGIN; +step s2keyshare: SELECT id FROM t WHERE id = 1 FOR KEY SHARE; +id +-- + 1 +(1 row) + +step wake: + SELECT FROM injection_points_detach('heap_update-unlocked'); + SELECT FROM injection_points_wakeup('heap_update-unlocked'); + +step s1toast: <... completed> +step s1rollback: ROLLBACK; +step s1keyupdate: UPDATE t SET id = id + 1; <waiting ...> +step s2commit: COMMIT; +step s1keyupdate: <... completed> +step s1check: SELECT id, length(val) FROM t; +id|length +--+------ + 2| 7 +(1 row) + + +starting permutation: s1toast s2begin s2keyshare s3begin s3keyshare wake s1keyupdate s2commit s3commit s1check +step s1toast: UPDATE t SET val = bigstring() WHERE id = 1; <waiting ...> +step s2begin: BEGIN; +step s2keyshare: SELECT id FROM t WHERE id = 1 FOR KEY SHARE; +id +-- + 1 +(1 row) + +step s3begin: BEGIN; +step s3keyshare: SELECT id FROM t WHERE id = 1 FOR KEY SHARE; +id +-- + 1 +(1 row) + +step wake: + SELECT FROM injection_points_detach('heap_update-unlocked'); + SELECT FROM injection_points_wakeup('heap_update-unlocked'); + +step s1toast: <... completed> +step s1keyupdate: UPDATE t SET id = id + 1; <waiting ...> +step s2commit: COMMIT; +step s3commit: COMMIT; +step s1keyupdate: <... completed> +step s1check: SELECT id, length(val) FROM t; +id|length +--+------ + 2| 6400 +(1 row) + + +starting permutation: s1toast s2begin s2keyshare s2commit wake s1keyupdate s1check +step s1toast: UPDATE t SET val = bigstring() WHERE id = 1; <waiting ...> +step s2begin: BEGIN; +step s2keyshare: SELECT id FROM t WHERE id = 1 FOR KEY SHARE; +id +-- + 1 +(1 row) + +step s2commit: COMMIT; +step wake: + SELECT FROM injection_points_detach('heap_update-unlocked'); + SELECT FROM injection_points_wakeup('heap_update-unlocked'); + +step s1toast: <... completed> +step s1keyupdate: UPDATE t SET id = id + 1; +step s1check: SELECT id, length(val) FROM t; +id|length +--+------ + 2| 6400 +(1 row) + diff --git a/src/test/modules/injection_points/meson.build b/src/test/modules/injection_points/meson.build index cf9cb219548..7824929d425 100644 --- a/src/test/modules/injection_points/meson.build +++ b/src/test/modules/injection_points/meson.build @@ -45,6 +45,7 @@ injection_points_isolation = [ 'heap_lock_update', 'on_conflict_probe_window', 'multixact-aborted-updater', + 'heap_update_lock_window', ] # wait_cleanup terminates another backend, whose FATAL message can be lost diff --git a/src/test/modules/injection_points/specs/heap_update_lock_window.spec b/src/test/modules/injection_points/specs/heap_update_lock_window.spec new file mode 100644 index 00000000000..17b724651df --- /dev/null +++ b/src/test/modules/injection_points/specs/heap_update_lock_window.spec @@ -0,0 +1,139 @@ +# Test that heap_update() keeps the locks that other transactions take on +# the old tuple while it has released the buffer lock. +# +# When the new tuple needs toasting, or doesn't fit on the old tuple's page, +# heap_update() marks the old tuple as locked by its own transaction and +# releases the buffer lock. For an update that doesn't change key columns, +# the lock is FOR NO KEY UPDATE, so another transaction can still take a FOR +# KEY SHARE lock on the tuple, for example a foreign key check. That lock +# must carry over to the old and the new tuple version once the update is +# done. +setup +{ + CREATE EXTENSION injection_points; + + CREATE TABLE t (id int PRIMARY KEY, val text); + INSERT INTO t VALUES (1, 'initial'); + CREATE TABLE c (pid int REFERENCES t (id)); + + -- random, incompressible text well over TOAST_TUPLE_THRESHOLD + CREATE FUNCTION bigstring() RETURNS text AS $$ + SELECT string_agg(md5(i::text), '') FROM generate_series(1, 200) i + $$ LANGUAGE SQL; + + -- A table where the tuple with id = 1 is on a full page, so that + -- updating it needs a new page, without toasting. + CREATE TABLE f (id int PRIMARY KEY, other int); + DO $$ + DECLARE + i int; + tid tid; + BEGIN + FOR i IN 1..5000 LOOP + INSERT INTO f VALUES (i, 0) RETURNING ctid INTO tid; + IF tid = '(1,1)' THEN + RETURN; + END IF; + END LOOP; + RAISE 'expected to insert tuple to (1,1)'; + END; + $$; +} +teardown +{ + DROP TABLE c; + DROP TABLE t; + DROP TABLE f; + DROP FUNCTION bigstring(); + DROP EXTENSION injection_points; +} + +session s1 +setup { + SELECT FROM injection_points_set_local(); + SELECT FROM injection_points_attach('heap_update-unlocked', 'wait'); +} +step s1begin { BEGIN; } +step s1toast { UPDATE t SET val = bigstring() WHERE id = 1; } +step s1newpage { UPDATE f SET other = other + 1 WHERE id = 1; } +step s1rollback { ROLLBACK; } +step s1keyupdate { UPDATE t SET id = id + 1; } +step s1keyupdatef { UPDATE f SET id = -id WHERE id = 1; } +step s1delete { DELETE FROM t WHERE id = 1; } +step s1check { SELECT id, length(val) FROM t; } +step s1orphans { SELECT count(*) AS orphans FROM c WHERE pid NOT IN (SELECT id FROM t); } + +session s2 +step s2begin { BEGIN; } +step s2keyshare { SELECT id FROM t WHERE id = 1 FOR KEY SHARE; } +step s2keysharef { SELECT id FROM f WHERE id = 1 FOR KEY SHARE; } +step s2insertchild { INSERT INTO c VALUES (1); } +step s2commit { COMMIT; } + +session s3 +step s3begin { BEGIN; } +step s3keyshare { SELECT id FROM t WHERE id = 1 FOR KEY SHARE; } +step s3commit { COMMIT; } + +session wake +step wake { + SELECT FROM injection_points_detach('heap_update-unlocked'); + SELECT FROM injection_points_wakeup('heap_update-unlocked'); +} + +# s2 takes a FOR KEY SHARE lock while s1 is toasting. A key update of the +# new tuple version must wait for s2. +permutation + s1toast + s2begin s2keyshare + wake + s1keyupdate + s2commit + s1check + +# Same, but the update needs a new page instead of toasting. +permutation + s1newpage + s2begin s2keysharef + wake + s1keyupdatef + s2commit + +# A foreign key check from s2 inserting a child row. Deleting the parent +# must wait for s2 and then fail, leaving no orphaned child row. +permutation + s1toast + s2begin s2insertchild + wake + s1delete + s2commit + s1orphans + +# If the update rolls back, the old tuple version must still be locked. +permutation + s1begin s1toast + s2begin s2keyshare + wake + s1rollback + s1keyupdate + s2commit + s1check + +# Two lockers in the window; the key update must wait for both. +permutation + s1toast + s2begin s2keyshare + s3begin s3keyshare + wake + s1keyupdate + s2commit + s3commit + s1check + +# A locker that ends while s1 is toasting doesn't hold anything after that. +permutation + s1toast + s2begin s2keyshare s2commit + wake + s1keyupdate + s1check -- 2.37.1 (Apple Git-137.1)
v1-0001-Don-t-lose-KEY-SHARE-locks-taken-while-heap_update-h.patch (application/octet-stream, 7.5K) download From 84c0efcf0cb7909a1d91d9d467630825ef361eed Mon Sep 17 00:00:00 2001 From: shihao zhong <zhong950419@gmail.com> Date: Mon, 16 Nov 2026 21:03:29 -0500 Subject: [PATCH 1/2] Don't lose KEY SHARE locks taken while heap_update() has no buffer lock When the new tuple needs toasting or a new page, heap_update() releases the buffer lock. The old tuple stays locked by us in that window. Another transaction can still take a FOR KEY SHARE lock on it, as foreign key checks do. heap_update() then overwrote the xmax with values computed before the window, so that lock was lost. A delete of the parent row could then leave orphaned child rows. Now heap_update() recomputes the xmax values if the xmax changed in the window. It drops its own temporary lock and adds itself back as the updater. That avoids MultiXactIds that only carry our own lock. Reported-by: Heikki Linnakangas <hlinnaka@iki.fi> Discussion: https://postgr.es/m/ce8b11dd-5908-45ac-bb3a-4ccfd5f88cf5@iki.fi Backpatch-through: 15 --- src/backend/access/heap/heapam.c | 149 +++++++++++++++++++++++++++++++ 1 file changed, 149 insertions(+) diff --git a/src/backend/access/heap/heapam.c b/src/backend/access/heap/heapam.c index 3bb33699349..56dde26d6c5 100644 --- a/src/backend/access/heap/heapam.c +++ b/src/backend/access/heap/heapam.c @@ -89,6 +89,15 @@ static void compute_new_xmax_infomask(TransactionId xmax, uint16 old_infomask, LockTupleMode mode, bool is_update, TransactionId *result_xmax, uint16 *result_infomask, uint16 *result_infomask2); +static void recompute_update_xmax_after_relock(MultiXactId cur_xmax, + TransactionId xid, + LockTupleMode mode, + TransactionId *xmax_old_tuple, + uint16 *infomask_old_tuple, + uint16 *infomask2_old_tuple, + TransactionId *xmax_new_tuple, + uint16 *infomask_new_tuple, + uint16 *infomask2_new_tuple); static TM_Result heap_lock_updated_tuple(Relation rel, uint16 prior_infomask, TransactionId prior_raw_xmax, @@ -4048,6 +4057,44 @@ l2: break; } } + + /* + * While we didn't hold the buffer lock, other transactions could + * acquire a lock on the old tuple that doesn't conflict with ours + * (FOR KEY SHARE, if this is not a key update). Doing so replaced + * the xmax we stored above with a new MultiXactId. The xmax values + * we computed for the update don't include those lockers, so their + * locks would be lost. Recompute them from the current xmax. + */ + if (xmax_infomask_changed(oldtup.t_data->t_infomask, + infomask_lock_old_tuple) || + !TransactionIdEquals(HeapTupleHeaderGetRawXmax(oldtup.t_data), + xmax_lock_old_tuple)) + { + HeapTupleHeader newtups[2] = {heaptup->t_data, newtup->t_data}; + + Assert(oldtup.t_data->t_infomask & HEAP_XMAX_IS_MULTI); + Assert(HEAP_XMAX_IS_LOCKED_ONLY(oldtup.t_data->t_infomask)); + + recompute_update_xmax_after_relock(HeapTupleHeaderGetRawXmax(oldtup.t_data), + xid, *lockmode, + &xmax_old_tuple, + &infomask_old_tuple, + &infomask2_old_tuple, + &xmax_new_tuple, + &infomask_new_tuple, + &infomask2_new_tuple); + + /* Fix the new tuple's xmax, in both copies of it */ + for (int i = 0; i < lengthof(newtups); i++) + { + newtups[i]->t_infomask &= ~HEAP_XMAX_BITS; + newtups[i]->t_infomask2 &= ~HEAP_KEYS_UPDATED; + newtups[i]->t_infomask |= infomask_new_tuple; + newtups[i]->t_infomask2 |= infomask2_new_tuple; + HeapTupleHeaderSetXmax(newtups[i], xmax_new_tuple); + } + } } else { @@ -5786,6 +5833,108 @@ l5: *result_xmax = new_xmax; } +/* + * Recompute the Xmax values for heap_update(), after it has temporarily + * released the buffer lock and other transactions have locked the old tuple + * in the meantime. + * + * While the buffer lock was released, the old tuple was marked as locked by + * our own transaction. Other transactions could still lock it in a mode that + * doesn't conflict with that, which turned its Xmax into 'cur_xmax', a + * lock-only MultiXactId with our own lock and the new lockers as members. + * + * We could pass 'cur_xmax' to compute_new_xmax_infomask(), but the result + * would carry our own temporary lock around, in both the old and the new + * tuple. Instead, look at the members, keep the other lockers that are + * still running, and add ourselves back as the updater. Dropping our own + * locks is OK: they were weak enough to let the other lockers in, so the + * update is at least as strong, and they share its fate. Locks held by our + * parent or by other subtransactions have a different XID, so they are kept. + * + * The new tuple gets the remaining lockers as Xmax, just like heap_update() + * does when it finds lockers before releasing the lock. + */ +static void +recompute_update_xmax_after_relock(MultiXactId cur_xmax, TransactionId xid, + LockTupleMode mode, + TransactionId *xmax_old_tuple, + uint16 *infomask_old_tuple, + uint16 *infomask2_old_tuple, + TransactionId *xmax_new_tuple, + uint16 *infomask_new_tuple, + uint16 *infomask2_new_tuple) +{ + MultiXactMember *members; + MultiXactMember *lockers; + int nmembers; + int nlockers = 0; + + /* + * A key update locks the tuple in a mode that conflicts with all other + * lock modes, so nobody could have locked it while we weren't looking. + */ + Assert(mode != LockTupleExclusive); + + nmembers = GetMultiXactIdMembers(cur_xmax, &members, false, true); + /* We are a member ourselves, and still running */ + Assert(nmembers > 0); + + lockers = palloc_array(MultiXactMember, nmembers + 1); + for (int i = 0; i < nmembers; i++) + { + /* Our own locks are superseded by the update */ + if (TransactionIdEquals(members[i].xid, xid)) + continue; + /* Lockers that are gone don't need to be preserved */ + if (!TransactionIdIsInProgress(members[i].xid)) + continue; + Assert(!ISUPDATE_from_mxstatus(members[i].status)); + lockers[nlockers++] = members[i]; + } + pfree(members); + + if (nlockers == 0) + { + /* Nobody else holds a lock anymore; same as no lockers at all */ + compute_new_xmax_infomask(InvalidTransactionId, HEAP_XMAX_INVALID, 0, + xid, mode, true, + xmax_old_tuple, infomask_old_tuple, + infomask2_old_tuple); + *xmax_new_tuple = InvalidTransactionId; + *infomask_new_tuple = HEAP_XMAX_INVALID; + *infomask2_new_tuple = 0; + } + else + { + /* + * The lockers carry over to the new tuple. Like heap_update(), use a + * plain XID rather than a MultiXactId for a single KEY SHARE locker. + */ + if (nlockers == 1 && lockers[0].status == MultiXactStatusForKeyShare) + { + *xmax_new_tuple = lockers[0].xid; + *infomask_new_tuple = HEAP_XMAX_KEYSHR_LOCK | HEAP_XMAX_LOCK_ONLY; + *infomask2_new_tuple = 0; + } + else + { + *xmax_new_tuple = MultiXactIdCreateFromMembers(nlockers, lockers); + GetMultiXactIdHintBits(*xmax_new_tuple, infomask_new_tuple, + infomask2_new_tuple); + } + + /* The old tuple has the lockers, plus us as the updater */ + lockers[nlockers].xid = xid; + lockers[nlockers].status = get_mxact_status_for_lock(mode, true); + nlockers++; + *xmax_old_tuple = MultiXactIdCreateFromMembers(nlockers, lockers); + GetMultiXactIdHintBits(*xmax_old_tuple, infomask_old_tuple, + infomask2_old_tuple); + } + + pfree(lockers); +} + /* * Subroutine for heap_lock_updated_tuple_rec. * -- 2.37.1 (Apple Git-137.1)
^ permalink raw reply [nested|flat] 2+ messages in thread


end of thread, other threads:[~2026-11-17 02:10 UTC | newest]

Thread overview: 2+ messages (download: mbox mbox.gz follow: Atom feed)
-- links below jump to the message on this page --
2026-11-02 14:07 Lost FOR KEY SHARE lock Heikki Linnakangas <hlinnaka@iki.fi>
2026-11-17 02:10 ` shihao zhong <zhong950419@gmail.com>

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