Write skew observed under serializable isolation
Write skew observed under serializable isolation
От:
Jacob Brazeal <jacob.brazeal@gmail.com>
Дата:
Hi hackers,
I found that a query using a Tid Range Scan can allow write skew under `SERIALIZABLE`.
Setup:
CREATE TABLE trs (id int, v int);
INSERT INTO trs VALUES (1, 0), (2, 0);
Then run the following in two sessions, interleaved as shown.
Session 1:
BEGIN ISOLATION LEVEL SERIALIZABLE;
SET enable_seqscan = off;
SELECT sum(v) FROM trs WHERE ctid >= '(0,0)' AND ctid <= '(0,100)';
-- 0 -- implies session 2 has not committed yet
Session 2:
BEGIN ISOLATION LEVEL SERIALIZABLE;
SET enable_seqscan = off;
SELECT sum(v) FROM trs WHERE ctid >= '(0,0)' AND ctid <= '(0,100)';
-- 0 -- implies session 1 has not committed yet
EXPLAIN shows a Tid Range Scan for both reads. Now:
-- session 1
UPDATE trs SET v = 1 WHERE ctid = '(0,1)';
-- session 2
UPDATE trs SET v = 1 WHERE ctid = '(0,2)';
-- session 1
COMMIT;
-- session 2
COMMIT; -- succeeds
Both transactions commit, and the final sum is 2:
SELECT sum(v) FROM trs;
-- 2
This result is not possible in any serial order: since both transactions read the full range, whichever transaction ran second would have observed a sum of 1 in its initial select instead of 0.
As a control, the same schedule using a sequential scan causes the second commit to fail with:
ERROR: could not serialize access due to read/write dependencies among transactions
(To run with seqscan, make sure to first do both SET enable_tidscan = off and SET enable_seqscan = on.)
I found that a query using a Tid Range Scan can allow write skew under `SERIALIZABLE`.
Setup:
CREATE TABLE trs (id int, v int);
INSERT INTO trs VALUES (1, 0), (2, 0);
Then run the following in two sessions, interleaved as shown.
Session 1:
BEGIN ISOLATION LEVEL SERIALIZABLE;
SET enable_seqscan = off;
SELECT sum(v) FROM trs WHERE ctid >= '(0,0)' AND ctid <= '(0,100)';
-- 0 -- implies session 2 has not committed yet
Session 2:
BEGIN ISOLATION LEVEL SERIALIZABLE;
SET enable_seqscan = off;
SELECT sum(v) FROM trs WHERE ctid >= '(0,0)' AND ctid <= '(0,100)';
-- 0 -- implies session 1 has not committed yet
EXPLAIN shows a Tid Range Scan for both reads. Now:
-- session 1
UPDATE trs SET v = 1 WHERE ctid = '(0,1)';
-- session 2
UPDATE trs SET v = 1 WHERE ctid = '(0,2)';
-- session 1
COMMIT;
-- session 2
COMMIT; -- succeeds
Both transactions commit, and the final sum is 2:
SELECT sum(v) FROM trs;
-- 2
This result is not possible in any serial order: since both transactions read the full range, whichever transaction ran second would have observed a sum of 1 in its initial select instead of 0.
As a control, the same schedule using a sequential scan causes the second commit to fail with:
ERROR: could not serialize access due to read/write dependencies among transactions
(To run with seqscan, make sure to first do both SET enable_tidscan = off and SET enable_seqscan = on.)
I reproduced this on current master. Tid Range Scans were introduced in PostgreSQL 14, and the behavior appears present in all branches since then.
Best,
Jacob Brazeal
Re: Write skew observed under serializable isolation
On Mon, 27 Jul 2026 at 07:58, Jacob Brazeal wrote: > > Hi hackers, > > I found that a query using a Tid Range Scan can allow write skew under `SERIALIZABLE`. Good find! On Mon, 27 Jul 2026 at 08:05, Jacob Brazeal wrote: > > A candidate patch to fix is attached. I think this patch is taking locks too aggressively; we shouldn't take a predlock on the whole relation when we're only looking at a small portion of the table using TID ranges. I think the more appropriate place to add the predicate locks is in heap_set_tidrange(), and have Assert(PageIsPredicateLocked(...)) for the returned TID in heap_getnextslot_tidrange() to make sure we don't regress. Kind regards, Matthias van de Meent.
Re: Write skew observed under serializable isolation
Hi Jacob, Thanks for the bug report and the fix. > [...] > > It seems that using page locks here would require some additional notion of heap gap locking, or corresponding changes to the insert conflict checks. With the existing predicate-locking scheme, I think the relation lock is needed to cover inserts as well as updates. Yes it looks like an architecturally correct approach with minimum overall overhead. In any case anyone who wants to implement an optimization can submit it as a separate patch. My only nitpick is that the patch doesn't update README-SSI. The corrected patch is attached. Also I added a proper commit message. I believe the patch is Ready for Committer. -- Best regards, Aleksander Alekseev
Re: Write skew observed under serializable isolation
От:
Andrey Borodin <x4mmm@yandex-team.ru>
Дата:
The locking change looks correct to me. On 21 Sep 2026, Aleksander Alekseev wrote: > +# other one read. No serial order produces sum(p) = 2, ... The constant assignments in this test produce a final sum of 2 in either serial order too. The anomaly is that both preceding reads return 0. Could we correct the comment? The test itself demonstrates the bug. Maybe we could also cover inserts after scanning an initially empty table. That would guard against moving lock acquisition into a per-page path later: there are no existing pages to lock. Without the fix both transactions commit; with v2 one is aborted. Thank you! Best regards, Andrey Borodin.
Re: Write skew observed under serializable isolation
Hi Andrey, Thanks for the great feedback. > > +# other one read. No serial order produces sum(p) = 2, ... > > The constant assignments in this test produce a final sum of 2 in either > serial order too. The anomaly is that both preceding reads return 0. > Could we correct the comment? The test itself demonstrates the bug. Good catch. Fixed. > Maybe we could also cover inserts after scanning an initially empty > table. That would guard against moving lock acquisition into a per-page > path later: there are no existing pages to lock. Without the fix both > transactions commit; with v2 one is aborted. Agree. Added. -- Best regards, Aleksander Alekseev
Re: Write skew observed under serializable isolation
От:
Andres Freund <andres@anarazel.de>
Дата:
Hi,
On 2026-09-21 15:41:54 +0300, Aleksander Alekseev wrote:
> + * For seqscan, sample and TID range scans in a serializable transaction,
> + * acquire a predicate lock on the entire relation. This is required not
> + * only to lock all the matching tuples, but also to conflict with new
> + * insertions into the table. In an indexscan, we take page locks on the
> + * index pages covering the range specified in the scan qual, but in a
> + * heap scan there is nothing more fine-grained to lock. A bitmap scan is
> + * a different story, there we have already scanned the index and locked
> + * the index pages covering the predicate. But in that case we still have
> + * to lock any matching heap tuples. For sample scan we could optimize the
> + * locking to be at least page-level granularity, but we'd need to add
> + * per-tuple locking for that. A TID range scan is like a seqscan in this
> + * respect: it reads heap blocks directly with no index involved, so there
> + * is nothing finer to lock, and heap_insert() only checks for conflicts
> + * against relation-level predicate locks anyway.
> + */
> + if (scan->rs_base.rs_flags & (SO_TYPE_SEQSCAN | SO_TYPE_SAMPLESCAN |
> + SO_TYPE_TIDRANGESCAN))
> {
> /*
> * Ensure a missing snapshot is noticed reliably, even if the
Seems like it'd be good to add a note to the SO_TYPE definitions mentioning
that this needs to be updated for additional scans.
I wish we could easily make the SO_TYPE ones an enum, so we could trigger
compiler warnings here by making it an switch() without a default. But it'd
probably be more annoying to change this than it's worth...
Do we have test coverage for the bitmap scan cases?
Greetings,
Andres Freund
Re: Write skew observed under serializable isolation
Hi Andres, Thanks for the feedback. > Seems like it'd be good to add a note to the SO_TYPE definitions mentioning > that this needs to be updated for additional scans. Good point. Added. > Do we have test coverage for the bitmap scan cases? It looks like predicate-lock-hot-tuple.spec sort of covers it but it is not guaranteed to use bitmap scan and all in all this is a regression test for another scenario. v4 adds a dedicated test. I choose not to split the patch into two parts. -- Best regards, Aleksander Alekseev
Re: Write skew observed under serializable isolation
От:
Zsolt Parragi <zsolt.parragi@percona.com>
Дата:
Hello!
- /* one of SO_TYPE_* may be specified */
+ /*
+ * One of SO_TYPE_* may be specified. When adding a scan type, check
+ * whether it must take predicate locks to be safe under SERIALIZABLE: see
+ * the flag test in heap_beginscan() and "Heap locking" in
+ * src/backend/storage/lmgr/README-SSI.
+ */
A wider llm-audit based on this claim pointed out that there's one
more preexisting issue: a tid scan that probes a tid holding no tuple
takes no predicate lock of any kind, so a concurrent INSERT that
materialises a tuple at exactly that TID creates no rw-conflict.
I'm not sure what's the proper solution for this, and if it even
should be part of this patch or something separate (as this patch is a
clear improvement even with this leftover issue), but it seems to be
at least worth a mention in a comment/commit message to state the
limitation?
An isolation test reproducing the problem:
setup
{
create table ta (id int);
insert into ta values (1), (2);
create table tb (id int);
insert into tb values (1), (2);
}
teardown { drop table ta; drop table tb; }
session s1
setup { begin isolation level serializable; set enable_seqscan = off; }
step r1 { select count(*) from tb where ctid = '(0,3)'; }
step w1 { insert into ta values (100); }
step c1 { commit; }
session s2
setup { begin isolation level serializable; set enable_seqscan = off; }
step r2 { select count(*) from ta where ctid = '(0,3)'; }
step w2 { insert into tb values (200); }
step c2 { commit; }
permutation r1 r2 w1 w2 c1 c2
Re: Write skew observed under serializable isolation
Hi Zsolt,
> An isolation test reproducing the problem:
>
> setup
> {
> create table ta (id int);
> insert into ta values (1), (2);
> create table tb (id int);
> insert into tb values (1), (2);
> }
> teardown { drop table ta; drop table tb; }
>
> session s1
> setup { begin isolation level serializable; set enable_seqscan = off; }
> step r1 { select count(*) from tb where ctid = '(0,3)'; }
> step w1 { insert into ta values (100); }
> step c1 { commit; }
>
> session s2
> setup { begin isolation level serializable; set enable_seqscan = off; }
> step r2 { select count(*) from ta where ctid = '(0,3)'; }
> step w2 { insert into tb values (200); }
> step c2 { commit; }
>
> permutation r1 r2 w1 w2 c1 c2
Great find, thanks for reporting.
Technically this is another bug since it affects Tid Scans, not Tid
Range Scans. This being said I see no reason not to fix it in the
scope of this discussion. The proper fix is to acquire SIREAD on the
relation.
Implemented as a separate patch.
--
Best regards,
Aleksander Alekseev
Re: Write skew observed under serializable isolation
От:
Zsolt Parragi <zsolt.parragi@percona.com>
Дата:
> The proper fix is to acquire SIREAD on the relation. That's a way to fix it, but I am not sure that it is the proper way to do it because it locks way more than needed. One issue is that now this takes a whole relation lock for UPDATE ... WHERE CURRENT OF, which can cause false-positive abort of cursor loops. I think this part is fixable with an extended condition. Also after I looked into this a bit more today, cb5b28613d5 in 2020 introduced SO_TYPE_TIDSCAN exactly to prevent full relation locks. Maybe the reasoning of that commit was wrong, and we indeed need whole relation locks there, but it doesn't seem like a trivial decision to me.
Re: Write skew observed under serializable isolation
От:
Aleksander Alekseev <aleksander@tigerdata.com>
Дата:
Hi Zsolt, > That's a way to fix it, but I am not sure that it is the proper way to > do it because it locks way more than needed. > > [...] This looks like the same concern Matthias expressed above. Let's be mindful of the fact that SIREAD locks despite the name are not actually locks. Also our SERIALIZABLE implementation allows false-positives by design [1]. Perhaps there is a smart way of minimizing false positives but personally I don't instantly see them. Firstly we should fix the broken feature and optimizations can be discussed as a separate patch. Users concerned with rollbacks can always choose other isolation levels. [1]: https://arxiv.org/abs/1208.4179 -- Best regards, Aleksander Alekseev