Assert that a snapshot is active or registered before it's used
authorHeikki Linnakangas <heikki.linnakangas@iki.fi>
Tue, 11 Mar 2025 21:20:34 +0000 (23:20 +0200)
committerHeikki Linnakangas <heikki.linnakangas@iki.fi>
Tue, 11 Mar 2025 21:20:34 +0000 (23:20 +0200)
commit8076c00592e40e8dbd1fce7a98b20d4bf075e4ba
tree261664f7645cff970a845c4c136e91987cbf8591
parentbd65cb3cd48a7a5ce48b26f8031ad3968efed87e
Assert that a snapshot is active or registered before it's used

The comment in GetTransactionSnapshot() said that you "should call
RegisterSnapshot or PushActiveSnapshot on the returned snap if it is
to be used very long". That felt too unclear to me. Make the comment
more strongly worded.

To enforce that rule and to catch potential bugs where a snapshot
might get invalidated while it's still in use, add an assertion to
HeapTupleSatisfiesMVCC() to check that the snapshot is registered or
pushed to active stack. No new bugs were found by this, but it seems
like good future-proofing. It's not a great place for the check;
HeapTupleSatisfiesMVCC() is in fact safe to call with an unregistered
snapshot, and the assertion won't catch other unsafe uses. But it goes
a long way in practice.

Fix a few cases that were playing fast and loose with that and just
assumed that the snapshot cannot be invalidated during a scan. Those
assumptions were not wrong, but they're not performance critical, so
let's drop the excuses and just register the snapshot. These were
false positives found by the new assertion.

Discussion: https://www.postgresql.org/message-id/7c56f180-b9e1-481e-8c1d-efa63de3ecbb@iki.fi
src/backend/access/heap/heapam_visibility.c
src/backend/access/index/genam.c
src/backend/commands/dbcommands.c
src/backend/utils/cache/relcache.c
src/backend/utils/time/snapmgr.c