[SP-]GiST IOS visibility bug (was: Why doens't GiST require super-exclusive lock)

Поиск
Список
Период
Сортировка
Искать

[SP-]GiST IOS visibility bug (was: Why doens't GiST require super-exclusive lock)

От:
Matthias van de Meent <boekewurm@gmail.com>
Дата:
Вложения:
Hi,

In the original thread [0] we established that GIST and SP-GiST
support index-only scans, but don't have sufficient interlocking to
prevent dead tuples from being revived for their scan by vacuum. As
that thread already contains a lot of detail, I won't go into the
specifics here, but the gist (heh) of it is as follows:

(SP-)GiST index scans don't interlock with their index vacuum in a way
that guarantees that their index-only scans only return TIDs that are
known to be valid TIDs when they're returned by amgettuple, thus
allowing index vacuum to clean TIDs up and let VACUUM mark their pages
ALL_VISIBLE before the tids were returned by the index-only scan.

The keen-eyed reader may have noticed that this issue is very similar
to the issue fixed with 459e7bf8, and that's correct. Both are cases
where the visibility map was accessed to determine the visibility of a
TID of which we didn't know for sure it was still a valid TID on that
heap page.


While the thread in [0] contains a very thorough fix, and (IMO) some
good additions to how index-only scans work with table AMs, the patch
currently proposed there changes things in non-backpatchable ways. So,
attached is a set of 4 patches designed for backpatching a fix.

The patches work similar to [0]'s, but with less invasive code changes
and no meaningful ABI breaks:
index vacuum's lock requirements are increased to super-exclusive
(cleanup) locks. Additionally, index-only scans will now do visibility
checks of each tuple they want to return, before the pin on the index
page that contains those tuples is released.
The visibility check is done on a tuple-by-tuple basis, through a new
function table_index_vischeck_tuple (so as to not totally break the
semantic barrier between indexes and tables regarding visibility
checks). In the patchset of [0] I added a table AM routine to allow
tableAMs to extend this, but that's not backportable, hence this
separate thread for discussing a backpatchable bugfix.
The one exposed ABI change is done by adding a single-byte
"visrecheck" field in an alignment area in IndexScanDescData - which
historically has been the place to put new fields required for
backported bugfixes. The size of the struct doesn't change, and there
should be no backward or forward compatibility issues for extensions
that might make use of this new field as long as they don't assume the
value of the field when they haven't set it themselves.

Kind regards,

Matthias van de Meent
Neon (https://neon.tech)

[0] https://postgr.es/m/flat/CAH2-Wz=PqOziyRSrnN5jAtfXWXY7-BJcHz9S355LH8Dt=5qxWQ@mail.gmail.com

Re: [SP-]GiST IOS visibility bug (was: Why doens't GiST require super-exclusive lock)

От:
Álvaro Herrera <alvherre@kurilemu.de>
Дата:
On 2025-Apr-25, Matthias van de Meent wrote:

> Hi,
> 
> In the original thread [0] we established that GIST and SP-GiST
> support index-only scans, but don't have sufficient interlocking to
> prevent dead tuples from being revived for their scan by vacuum.

Hello,

This commitfest entry
https://commitfest.postgresql.org/patch/5721/
is stale.  I would have brought it forward because it's tagged as a bug
fix, but the patches look a bit intimidating to consider it a
backpatchable bug fix.  So, what's the status here?

Thanks

-- 
Álvaro Herrera        Breisgau, Deutschland  —  https://www.EnterpriseDB.com/


Re: [SP-]GiST IOS visibility bug (was: Why doens't GiST require super-exclusive lock)

От:
Matthias van de Meent <boekewurm@gmail.com>
Дата:
Вложения:
On Tue, 3 Feb 2026 at 23:39, Álvaro Herrera  wrote:
>
> On 2025-Apr-25, Matthias van de Meent wrote:
>
> > Hi,
> >
> > In the original thread [0] we established that GIST and SP-GiST
> > support index-only scans, but don't have sufficient interlocking to
> > prevent dead tuples from being revived for their scan by vacuum.
>
> Hello,
>
> This commitfest entry
> https://commitfest.postgresql.org/patch/5721/
> is stale.  I would have brought it forward because it's tagged as a bug
> fix, but the patches look a bit intimidating to consider it a
> backpatchable bug fix.  So, what's the status here?

Sorry for the delay. I've finally gotten back to this patch, as it's
the simpler option vs the patch in the original thread, even if it may
have a higher performance impact for GIST and SP-GIST IOS scans.

Attached is v02, which is a simple rebase with some language and
wrapping changes in comments, as well as some fixes for assert-enabled
builds.


Kind regards,

Matthias van de Meent
Databricks (https://www.databricks.com)

Re: [SP-]GiST IOS visibility bug (was: Why doens't GiST require super-exclusive lock)

От:
solai v <solai.cdac@gmail.com>
Дата:
I tested the v02 patch series.
The patches applied cleanly and PostgreSQL built successfully.
I created a GiST index and verified that the query uses an Index Only
Scan (Heap Fetches: 0). I also tried to reproduce the reported race
condition by running concurrent Index Only Scans together with DELETE
and VACUUM operations, but I wasn't able to reproduce the issue
manually. Since this is a timing-dependent race condition, that wasn't
too surprising.
After applying the patches, I rebuilt PostgreSQL and ran the test
suite. All 245 tests passed, including the new regression test added
by this patch, and I didn't notice any regressions during my testing.
Overall, the patch applied cleanly, built successfully, and my testing
didn't reveal any issues.

regards

solai


Re: [SP-]GiST IOS visibility bug (was: Why doens't GiST require super-exclusive lock)

От:
Mihail Nikalayeu <mihailnikalayeu@gmail.com>
Дата:
Вложения:
Hello!

I am working on a stress-test framework and was trying to use it to
reproduce this bug.
It reproduced, but SP-GiST failed after the fix was applied.

AI tool decided the issue was caused by a problem in the patch; the
AI-crafted fix is attached.
I haven't validated it carefully, sorry, but I think it will be helpful.

Best regards,
Mikhail.

Re: [SP-]GiST IOS visibility bug (was: Why doens't GiST require super-exclusive lock)

От:
solai v <solai.cdac@gmail.com>
Дата:
Вложения:
Hi Mikhail,
I tested the attached follow-up patch (nocfbot_spgistvischeckwrongtid.patch).
The patch applied cleanly on top of the v02 patch series. PostgreSQL
built successfully, and all regression tests passed .
I also verified that SP-GiST Index Only Scan continued to work
correctly after applying the patch and did not observe any build or
functional regressions during my testing.
I was not able to verify the reported stress-test failure because no
reproducer or stress-test framework was provided.

Regards,
Solai


Re: [SP-]GiST IOS visibility bug (was: Why doens't GiST require super-exclusive lock)

От:
Paul A Jungwirth <pj@illuminatedcomputing.com>
Дата:
Вложения:
On Mon, Aug 3, 2026 at 6:40 AM Matthias van de Meent
 wrote:
>
> Attached v3, which fixes that, and hopefully also fixes the
> fallthrough compiler warning that cfbot has been reporting. Thanks for
> the report!

Haibo Yan, Surya Poondla, and I reviewed this patch as part of the
Patch Review Workshop.

Our understanding is that the four patches here (currently at v3) are
intended for backpatches only, and [0] holds the intended fix for
master. We have only reviewed the v3 backpatch patches.

The patches no longer apply cleanly. Here are v4 patches that apply to
REL_19_STABLE.

We can reproduce the problem (see gist-ios-vacuum.{spec,out},
attached). The patches fix it.

We don't think the final cleanup lock is required (although we left it
in v4 for now). If we drop it, the test above still passes, as do many
other stress tests we had Claude perform. Unlike nbtree, {SP-,}GiST
check the visibility map right away, while still holding a leaf-page
share lock. Also they drop the pin after that read, instead of holding
it for later. So (1) there is no pin to conflict with the cleanup lock
(2) we are already checking the VM safely: either vacuum removed the
tuple before our read and we never saw it, or vacuum removed the tuple
after our read (since it takes an exclusive lock on the page), so it
changes the VM after we checked it. The relevant ordering seems to be:

leaf SHARE lock
-> read index entry
-> check/cache visibility
-> release SHARE lock
-> VACUUM gets EXCLUSIVE lock
-> remove index entry
-> LP_DEAD -> LP_UNUSED / VM all-visible

Since a cleanup lock additionally waits for outstanding buffer pins,
it can introduce stalls that the previous ordinary EXCLUSIVE lock did
not. Our pgbench results were fairly noisy, especially for GiST, but
we observed slowdowns of up to 26%.

Another hint that the lock is not required here is that WAL redo and
replication don't take it.

@@ -381,6 +388,13 @@ spgrescan(IndexScanDesc scan, ScanKey scankey,
int nscankeys,
  if (scankey && scan->numberOfKeys > 0)
  memcpy(scan->keyData, scankey, scan->numberOfKeys * sizeof(ScanKeyData));

+ /* prepare index-only scan requirements */
+ if (scan->xs_want_itup)
+ {
+ if (so->visrecheck == NULL)
+ so->visrecheck = palloc(MaxIndexTuplesPerPage);
+ }
+
  /* initialize order-by data if needed */
  if (orderbys && scan->numberOfOrderBys > 0)
  {

This is allocated during rescan and, unlike the neighboring per-tuple
arrays, is not explicitly freed or reused as inline storage.  Every
other similar field in SpGistScanOpaqueData is an inline fixed-size
array, so should this be one as well? Also, the struct is private, so
I think shifting the fields is acceptable, buf if not, we should add
this field (and the rest) to the end.

The comment on table_index_vischeck_tuple doesn't seem to match the
function. It is talking about checkop->checktids and TMVC_* constants.
Also the comment on TMVC_Result talks about checking multiple tuples
at once, but that seems to be leftover from somewhere else.

TMVC_Result needs to be added to typedefs.list.

xs_visrecheck is a somewhat misleading name. TMVC_MaybeVisible
actually means that a later VM lookup must not be done and that the
heap must be visited. So this is really a cached visibility result
rather than a "recheck" flag. Can we name it something like
xs_visresult (ideally on master too)? And we'd rather store a
TMVC_Result than an undocumented uint8.

SP-GiST also has an assertion that an IOS result has acquired a
visibility result before it is returned, while the corresponding GiST
path doesn't. Adding the same invariant assertion there seems
worthwhile.

RelationGetIndexScan initializes the other xs_* fields, but not
xs_visrecheck. I don't think there is a bug there, but we might as
well do it for consistency.

There are some testing gaps:

- In v3 we fixed the item->heapPtr bug, but no test fails if we undo that fix.
- The tests pass even with enable_indexonlyscan=false.
- Some mutations that lose queued KNN results can pass as well,
because the expected tail of the cursor is empty.

We think the tests should at least verify that an IOS was selected,
verify the intended VACUUM/visibility transition, exercise multiple
leaf pages/KNN state, and include a direct regression test for the
SP-GiST wrong-TID case.

[0] https://postgr.es/m/flat/CAH2-Wz=PqOziyRSrnN5jAtfXWXY7-BJcHz9S355LH8Dt=5qxWQ(at)mail(dot)gmail(dot)com

Yours,

-- 
Paul              ~{:-)
pj@illuminatedcomputing.com

Re: [SP-]GiST IOS visibility bug (was: Why doens't GiST require super-exclusive lock)

От:
solai v <solai.cdac@gmail.com>
Дата:
Hi Paul,

I tested the v4 patch series on REL_19_STABLE.

Here are my test results:

- v4-0001 through v4-0004 applied cleanly.
- PostgreSQL built successfully.
- 'make check' passed with 239/239 tests.
- The isolation test suite passed with 135/135 tests with the complete
v4 series.
- The new GiST and SP-GiST IOS/VACUUM tests passed for both sorted and
unsorted scans.
- I also tested the new v4-0004 regression tests on unpatched
REL_19_STABLE. In that case, 2 of 135 isolation tests failed:
  - 'index-only-scan-gist-vacuum'
  - 'index-only-scan-spgist-vacuum'
- Without the fixes, both tests returned the 9 rows that had been
deleted before VACUUM, instead of the expected 0 rows.
- With the complete v4 series applied, both tests passed and returned
the expected 0 rows after VACUUM.
- I also checked the SP-GiST visibility check and confirmed that it
uses 'leafTuple->heapPtr' for the visibility check.

And one observation on my review is that the isolation tests force
enable_indexonlyscan = true and disable bitmap scans, but they do not
explicitly verify the selected plan with EXPLAIN.

Overall, the v4 series passed my testing, and the new regression tests
correctly exposed the issue on the unpatched code.

Regards,
Solai


FAQ