On Mon, Aug 3, 2026 at 6:13 AM Andrey Borodin <[email protected]> wrote:
> Hi hackers,
>
> I'd like to revive this patch.
>
> The patch adds a second, page-local level of keys to GiST internal pages.  A
> skip tuple contains the union key for a group and is immediately followed by
> the real downlinks in that group.  When Consistent returns false for the skip
> tuple, the scan skips the whole group.  Otherwise it examines every downlink
> normally.  Skip tuples themselves are never followed or added to the scan
> queue, including for ordered scans.

Hi Andrey,

I took a look at this patch. I like that you are working to improve
GiST performance! This will help with my temporal data efforts. It
seemed a bit scandalous when I learned that GiST checks every tuple on
the page. Being able to skip some seems like a big improvement.

It's a clever implementation: I like how the skip tuples have the same
kind of key as regular non-leaf tuples. And using InvalidBlockNumber
for their "downlink" means they can't be confused with existing
tuples, so old indexes work without migration. Most important, there
are no new cross-page invariants, so the existing page-level exclusive
lock we take on writes protects all the work we have to do.

An alternative I've considered before is to store tuples sorted (when
possible), thus getting binary search. This is mentioned in one of the
early GiST papers [0] but not really explored in detail. It probably
doesn't make sense to do this *and* your skip tuples.

Sorting would also give us can_order, so that the planner can omit
Sort nodes. Maybe it would require fewer writes, too? In your patch it
appears we move the group and all its children whenever any of them
change, which feels like a lot. We already have a GiST support
function for sorting keys, but currently we only use it for the
initial index build.

OTOH your patch seems simpler and safer (especially under
concurrency), plus it exists!

I asked Claude to do some research on the binary search idea. Its plan
came with a lot of complexity (e.g. a new flag for index pages and a
new field on WAL records) and a lot of limitations. Sorting only the
leaf pages was not too bad. Sorting non-leaf pages was harder. Neither
gave us cross-page sorting or let us omit Sort nodes. And apparently
the existing kNN ability could be leveraged to get us can_order, at
least for most opclasses, even without keeping tuples sorted on-disk.
So I don't think binary search is a good alternative to your patch.

I also explored how your patch would interact with my in-progress work
to let GiST indexes enforce uniqueness. I didn't find any
incompatibilities there. If anything it should speed up those checks.

Some way to opt out or control how many skip tuples you get per page
would be nice. Especially since it is not always a win (see cube
benchmark below).

I think I like the overall approach. Now on to the details. . . .

There was a minor rebase conflict, so here is a v4 patch to resolve that.

With those patches, everything builds, and tests pass, with one
caveat: in the TAP test the standby can fall behind and time out
requesting WAL. The test still passes, but it takes a long time.
Adding a replication slot would avoid that.

I benchmarked various types/opclasses (scripts attached), including a
two-column (int, tstzrange) key as you'd find in a temporal primary
key.

    point    selective-box      0.93x   (~7% faster)   size 1.00x  build 1.3x
    mrange   selective-overlap  0.85x   (~15% faster)  size 1.00x  build ~1x
    temporal pk-probe (id=)     0.90x   (~10% faster)  size 1.01x  build 1.0x
    temporal id-band            0.95x   (~5% faster)   (same temporal index)
    tsrange  selective-window   0.96x   (~4% faster)   size 1.00x  build 1.0x
    scalar   int8 range         1.00x   (no change)    size 1.00x  build 1.0x
    cube     selective-overlap  1.03x   (~3% slower)   size 2.11x  build 15.8x

Everything except the last two rows was faster to search. Build was
slower. "Scalar" is testing a btree_gist opclass (int8). It shows no
benefit, but normally you'd use btree for that. For cube, building was
*much* slower, enough that I suspect a bug. How can adding 1/16x
tuples take 16x time? It looks related to Ethan's find about skip
tuples getting the wrong penalty: you wind up storing tuples under the
wrong downlinks (consistent, but worse penalty).

To comment on Ethan's benchmarks:

> Local runs on an 8-core M2 Mac with 2 GB shared buffers reconstructed the
> 5M-point workloads described in your email. The original SQL was not included,
> so this was not an exact reproduction, but the direction of the performance
> gains was consistent with your results.

The read results seem consistent with my own.

> the 500k-row INSERT was about 1.4x faster. That INSERT generated
> approximately 5% more whole-statement WAL under the tested settings.

I was skeptical that insert could speed up, since we write strictly
more than before. But for sufficiently-large indexes, it is true.
That's because we improve the descent time for non-leaf pages.

> Sorted-tree joins were about 1.6-1.9x faster ...

I'm not sure what a "sorted-tree join" can mean here, since GiST never
yields sorted output. Ethan, can you share your SQL and the EXPLAIN
(ANALYZE) output you got?

I didn't review every line of code, but here is how far I got:

diff --git a/src/backend/access/gist/README b/src/backend/access/gist/README
 Any such enlargement would be to add child items that we aren't interested
 in returning anyway.

+Intrapage Indexing
+------------------
+
+Internal pages can contain a second, page-local level of GiST keys.  A skip
+tuple stores the Union key of a group and is followed immediately by the real
+downlinks covered by that key.  Its TID has InvalidBlockNumber, distinguishing
+it from real downlinks, and its offset field stores the number of following
+tuples in the group.  Groups do not overlap or contain other skip tuples.

"Followed immediately by the real downlinks": to clarify, not tids,
but regular index tuples, which store downlinks.

"Groups do not overlap" might not be the clearest. I think I
misunderstood on first reading and wrote this:

How do we enforce "Groups do not overlap", especially since downlink
keys are allowed to overlap?
What if a group has tons of identical tuples inside it, and you keep
adding more?
If we split it, the two groups will have identical keys, right?

Also can a skip group's key overlap a non-skip tuple from the same page?
I don't see anything to prevent it.

+A scan first applies Consistent to the skip tuple.  If it does not match, the
+whole group can be skipped.  If it matches, the scan examines each real tuple
+normally.  Skip tuples are never followed as downlinks or returned as heap
+TIDs.  Ordered searches use the same rule: the group key only rejects a group
+and does not contribute a queue item or distance.
+
+Insertion uses the same page-local level while choosing a subtree.  Once a
+candidate downlink has established the best penalty for the first key column,
+a group whose union key has a worse penalty is skipped.  Otherwise Penalty is
+evaluated for each member as usual.  Later key columns continue to break ties
+between individual downlinks in the normal way.
+
+Skip tuples are derived metadata.  Removing them must leave an ordinary valid
+GiST page with exactly the same downlinks.  Page updates rebuild the affected
+group from its real tuples, while page splits and both build methods account
+for metadata space.  Before VACUUM deletes a downlink, it moves that downlink
+out of its group and decrements the group count.

Is removing an entry from the skip tuple O(1)? O(n)? Do all the other
entries need to shift?
(In fact reading the code it appears we rewrite the whole group.)

+Existing pages without skip
+tuples therefore need no conversion.  The current implementation creates skip
+tuples only on internal pages; adding them to leaf pages would also require
+maintaining group boundaries during tuple-level vacuuming and LP_DEAD cleanup.
+

 Insert Algorithm
 ----------------
diff --git a/src/backend/access/gist/gist.c b/src/backend/access/gist/gist.c
index 8565e225be7..b7e64f30ead 100644
--- a/src/backend/access/gist/gist.c
+++ b/src/backend/access/gist/gist.c
@@ -243,6 +243,30 @@ gistplacetopage(Relation rel, Size freespace,
GISTSTATE *giststate,
  bool is_leaf = (GistPageIsLeaf(page)) ? true : false;
  XLogRecPtr recptr;
  bool is_split;
+ bool has_skip = false;
+ OffsetNumber groupoff = InvalidOffsetNumber;
+ OffsetNumber *groupdeloffs = NULL;
+ int ngroupdel = 0;
+ IndexTuple *groupwrite = NULL;
+ int ngroupwrite = 0;
+
+ if (!is_leaf)
+ {
+ OffsetNumber maxoff = PageGetMaxOffsetNumber(page);
+
+ for (OffsetNumber off = FirstOffsetNumber; off <= maxoff;
+ off = OffsetNumberNext(off))
+ {
+ IndexTuple pageitup = (IndexTuple) PageGetItem(page,
+ PageGetItemId(page, off));
+
+ if (GistTupleIsSkip(pageitup))
+ {
+ has_skip = true;
+ break;
+ }
+ }
+ }

So this adds an O(n) scan through all the tuples, if the index is legacy?
And how long 'til it finds a skip tuple when one is present?
Is there a bitfield in the header we can use instead?

  /*
  * Refuse to modify a page that's incompletely split. This should not
@@ -283,6 +307,102 @@ gistplacetopage(Relation rel, Size freespace,
GISTSTATE *giststate,
  is_split = gistnospace(page, itup, ntup, oldoffnum, freespace);
  }

+ /* Rebuild only the skip group containing the replaced downlink. */
+ if (has_skip && OffsetNumberIsValid(oldoffnum))
+ {
+ OffsetNumber maxoff = PageGetMaxOffsetNumber(page);
+ int groupcount = 0;
+
+ for (OffsetNumber off = FirstOffsetNumber; off <= maxoff;
+ off = OffsetNumberNext(off))
+ {
+ IndexTuple pageitup = (IndexTuple) PageGetItem(page,
+ PageGetItemId(page, off));
+

Scanning every tuple again, yet it helps? (Or maybe paying extra to
insert is worth it to read?)
At least we can jump ahead (`off += count`) when we fail a skip tuple.

+ if (GistTupleIsSkip(pageitup))
+ {
+ int count = GistTupleGetSkipCount(pageitup);

Can two concurrent inserts go "through" the same skip tuple at the
same time? Or do they take a lock on it? Is that different from
regular downlinks? If different (or even if not), are we harming
concurrency and increasing lock contention? No: we take a *page-level*
exclusive lock, so this patch doesn't change anything there. Also see
my concurrency benchmarks (attached).

+
+ if (count > maxoff - off)
+ ereport(ERROR,
+ (errcode(ERRCODE_INDEX_CORRUPTED),
+ errmsg("index \"%s\" contains an invalid GiST skip tuple",
+ RelationGetRelationName(rel))));

Should be elog? Nevermind, the existing code uses ereport for
ERRCODE_INDEX_CORRUPTED.

+ if (oldoffnum > off && oldoffnum <= off + count)
+ {
+ groupoff = off;
+ groupcount = count;
+ break;
+ }

A diagram of how child tuples sit physically after the skip tuple
would be nice for the README.
Can the skip tuple allocate space that is never filled?

+ off += count;
+ }
+ }
+

Add comment here: /* We found a skip tuple, so update it */
In general we need more comments below:

+ if (OffsetNumberIsValid(groupoff))
+ {
+ IndexTuple *members;
+ int nmembers = 0;
+ IndexTupleData *newlist;
+ int newlenlist;
+ char   *data;
+ Size required = freespace;
+
+ members = palloc_array(IndexTuple, groupcount - 1 + ntup);

What is ntup?

add: /* Walk through the group's children */

+ for (OffsetNumber off = OffsetNumberNext(groupoff);
+ off <= groupoff + groupcount; off = OffsetNumberNext(off))
+ {
+ if (off == oldoffnum)
+ {
+ for (int i = 0; i < ntup; i++)

This seems drastic. What is going on here?:

+ members[nmembers++] = itup[i];
+ }
+ else
+ members[nmembers++] = (IndexTuple) PageGetItem(page,
+   PageGetItemId(page, off));
+ }
+ Assert(nmembers == groupcount - 1 + ntup);
+
+ if (nmembers > 0 &&
+ gistFormSkipGroups(rel, page, members, nmembers, giststate,
+   &newlist, &newlenlist, &ngroupwrite))
+ {
+ data = (char *) newlist;
+ groupwrite = palloc_array(IndexTuple, ngroupwrite);
+ for (int i = 0; i < ngroupwrite; i++)
+ {
+ groupwrite[i] = (IndexTuple) data;
+ data += IndexTupleSize(groupwrite[i]);
+ }
+ is_split = false;
+ }
+ else
+ is_split = true;

So we set is_split to true when nmembers is 0? Why?

+
+ groupdeloffs = palloc_array(OffsetNumber, groupcount + 1);

The +1 is because we have to delete the skip tuple too.

Add: /* Mark all the old group members for deletion */

+ for (OffsetNumber off = groupoff;
+ off <= groupoff + groupcount; off = OffsetNumberNext(off))
+ groupdeloffs[ngroupdel++] = off;
+
+ if (!is_split)
+ {

Add: /* Compute the size needed for all the tuples outside the group,
plus the new group */

+ for (OffsetNumber off = FirstOffsetNumber; off <= maxoff;
+ off = OffsetNumberNext(off))
+ {
+ IndexTuple pageitup;
+
+ if (off >= groupoff && off <= groupoff + groupcount)
+ continue;
+ pageitup = (IndexTuple) PageGetItem(page,
+ PageGetItemId(page, off));
+ required += IndexTupleSize(pageitup) + sizeof(ItemIdData);
+ }
+ for (int i = 0; i < ngroupwrite; i++)
+ required += IndexTupleSize(groupwrite[i]) + sizeof(ItemIdData);
+ is_split = (required > GiSTPageSize);
+ }
+ }
+ }
+
  if (is_split)
  {
  /* no space for insertion */
@@ -303,17 +423,27 @@ gistplacetopage(Relation rel, Size freespace,
GISTSTATE *giststate,

Need to update the comment bleeding off the top of this hunk.

  * remove the old version from the vector.
  */
  itvec = gistextractpage(page, &tlen);
- if (OffsetNumberIsValid(oldoffnum))
+ if (has_skip || OffsetNumberIsValid(oldoffnum))
  {

So oldoffnum might be invalid here?
I don't see any tests below to make sure it's valid before using it though.

- /* on inner page we should remove old tuple */
- int pos = oldoffnum - FirstOffsetNumber;
+ int dst = 0;

- tlen--;
- if (pos != tlen)
- memmove(itvec + pos, itvec + pos + 1, sizeof(IndexTuple) * (tlen - pos));

Wow so the old code shifted every tuple by one on a delete??

+ /* Remove derived metadata and the replaced real tuple. */
+ for (int src = 0; src < tlen; src++)
+ {
+ OffsetNumber off = src + FirstOffsetNumber;
+
+ if (GistTupleIsSkip(itvec[src]) || off == oldoffnum)
+ continue;

Is this an aliasing concern? (I think not, because dst <= src, but
maybe a comment?):

+ itvec[dst++] = itvec[src];
+ }
+ tlen = dst;

This is a much slower way to shift all the tuples than before. Can we
still do it with one memmove? Probably not, since the skip tuple and
the deleted tuple might not be adjacent. I think one branch for
has_skip and another for OffsetNumberIsValid would be clearer and
safer, compared to mixing the cases together. Because it seems like we
are trying to give each case different behavior here too, with
`GistTupleIsSkip(itvec[src]) || off == oldoffnum`.

  }
  itvec = gistjoinvector(itvec, &tlen, itup, ntup);
- dist = gistSplit(rel, page, itvec, tlen, giststate);
+ if (is_leaf)
+ dist = gistSplit(rel, page, itvec, tlen, giststate, 0);
+ else
+ dist = gistSplitPageWithSkipGroups(rel, page, itvec, tlen,
+   giststate, true);

  /*
  * Check that split didn't produce too many pages.
@@ -419,6 +549,41 @@ gistplacetopage(Relation rel, Size freespace,
GISTSTATE *giststate,
  }
  }

+ /*
+ * Add derived intrapage indexes to internal pages.  The metadata is
+ * optional for correctness, so keep the ordinary representation when
+ * its extra tuples would no longer fit.
+ */
+ for (ptr = dist; ptr; ptr = ptr->next)
+ {

We are only handling the root page here?:

+ if (ptr->block.blkno == GIST_ROOT_BLKNO && ptr->block.num > 0)
+ {
+ IndexTuple *pagevec;
+ char   *data = (char *) ptr->list;
+ IndexTupleData *newlist;
+ int newlenlist;
+ int newlen;
+
+ pagevec = palloc_array(IndexTuple, ptr->block.num);
+ for (int i = 0; i < ptr->block.num; i++)
+ {
+ IndexTuple pageitup = (IndexTuple) data;
+
+ pagevec[i] = pageitup;
+ data += IndexTupleSize(pageitup);
+ }
+
+ if (gistFormSkipGroups(rel, ptr->page, pagevec,
+   ptr->block.num, giststate,
+   &newlist, &newlenlist, &newlen))
+ {
+ ptr->list = newlist;
+ ptr->lenlist = newlenlist;
+ ptr->block.num = newlen;
+ }

Break here? Why keep iterating? And surely there is a faster way to
find the root page?

+ }
+ }
+
  /*
  * Fill all pages. All the pages are new, ie. freshly allocated empty
  * pages, or a temporary copy of the old page.
@@ -538,16 +703,39 @@ gistplacetopage(Relation rel, Size freespace,
GISTSTATE *giststate,
  }
  else
  {

[not a split]

+ IndexTuple *writetup = itup;
+ int nwritetup = ntup;
+ OffsetNumber *deloffs = NULL;
+ int ndeloffs = 0;
+

This comment should go above the variable declarations:

  /*
  * Enough space.  We always get here if ntup==0.
  */
+ if (OffsetNumberIsValid(groupoff))
+ {
+ writetup = groupwrite;
+ nwritetup = ngroupwrite;
+ deloffs = groupdeloffs;
+ ndeloffs = ngroupdel;
+ }
+
+ /* A group rewrite registers one WAL data segment per new tuple. */
+ if (OffsetNumberIsValid(groupoff) && !is_build && RelationNeedsWAL(rel))
+ XLogEnsureRecordSpace(BufferIsValid(leftchildbuf) ? 2 : 1,
+  2 + nwritetup);
+
  START_CRIT_SECTION();

  /*
  * Delete old tuple if any, then insert new tuple(s) if any.  If
  * possible, use the fast path of PageIndexTupleOverwrite.

Needs "Delete old tuple(s) if any" and a second paragraph explaining
when deleting more than one would be needed (i.e. a skip tuple and its
children).

  */
- if (OffsetNumberIsValid(oldoffnum))
+ if (OffsetNumberIsValid(groupoff))
+ {
+ PageIndexMultiDelete(page, deloffs, ndeloffs);
+ gistfillbuffer(page, writetup, nwritetup, InvalidOffsetNumber);

We could just delete groupdeloffs and ngroupdel here, right? Seems
like less to track.

+ }
+ else if (OffsetNumberIsValid(oldoffnum))

Huh. So we may delete a bunch of tuples: a group and all its children.

  {
  if (ntup == 1)
  {
@@ -580,17 +768,19 @@ gistplacetopage(Relation rel, Size freespace,
GISTSTATE *giststate,
  {
  if (RelationNeedsWAL(rel))
  {
- OffsetNumber ndeloffs = 0,
- deloffs[1];
+ OffsetNumber local_deloffs[1];

- if (OffsetNumberIsValid(oldoffnum))
+ if (!OffsetNumberIsValid(groupoff) &&
+ OffsetNumberIsValid(oldoffnum))
  {
- deloffs[0] = oldoffnum;
+ local_deloffs[0] = oldoffnum;
+ deloffs = local_deloffs;
  ndeloffs = 1;
  }

Seems like a comment in all that ^^^ would be nice. Also do we really
need groupdeloffs and local_deloffs and deloffs? Could a comment
explain why?

Also if groupoff is set, we never delete oldoffnum. And we never tell
gistXLogUpdate about it.

Maybe an Assert would be good above that groupoff and oldoffnum are
never set at the same time? Because we seem to ignore oldoffnum when
groupoff is set. Or maybe I have that backwards. . . . Why have
callers send us things we will ignore, making readers reason about
that input combination?

  recptr = gistXLogUpdate(buffer,
- deloffs, ndeloffs, itup, ntup,
+ deloffs, ndeloffs,
+ writetup, nwritetup,
  leftchildbuf);
  }
  else
@@ -990,6 +1180,8 @@ gistFindPath(Relation r, BlockNumber child,
OffsetNumber *downlinkoffnum)
  {
  iid = PageGetItemId(page, i);
  idxtuple = (IndexTuple) PageGetItem(page, iid);

Add a comment here:

+ if (GistTupleIsSkip(idxtuple))
+ continue;
  blkno = ItemPointerGetBlockNumber(&(idxtuple->t_tid));
  if (blkno == child)
  {
@@ -1151,6 +1343,8 @@ gistformdownlink(Relation rel, Buffer buf,
GISTSTATE *giststate,
  IndexTuple ituple = (IndexTuple)
  PageGetItem(page, PageGetItemId(page, offset));

+ if (GistTupleIsSkip(ituple))
+ continue;

Why not use its key and skip its children, instead of calling
gistgetadjusted a bunch of times?

  if (downlink == NULL)
  downlink = CopyIndexTuple(ituple);
  else
@@ -1451,7 +1645,8 @@ gistSplit(Relation r,
   Page page,
   IndexTuple *itup, /* contains compressed entry */
   int len,
-  GISTSTATE *giststate)
+  GISTSTATE *giststate,
+  int max_page_tuples)
 {
  IndexTuple *lvectup,
    *rvectup;
@@ -1493,9 +1688,12 @@ gistSplit(Relation r,
  rvectup[i] = itup[v.splitVector.spl_right[i] - 1];

  /* finalize splitting (may need another split) */
- if (!gistfitpage(rvectup, v.splitVector.spl_nright))
+ if (!gistfitpage(rvectup, v.splitVector.spl_nright) ||
+ (max_page_tuples > 0 &&
+ v.splitVector.spl_nright > max_page_tuples))
  {
- res = gistSplit(r, page, rvectup, v.splitVector.spl_nright, giststate);
+ res = gistSplit(r, page, rvectup, v.splitVector.spl_nright,
+ giststate, max_page_tuples);
  }
  else
  {
@@ -1505,12 +1703,16 @@ gistSplit(Relation r,
  res->itup = gistFormTuple(giststate, r, v.spl_rattr, v.spl_risnull, false);
  }

- if (!gistfitpage(lvectup, v.splitVector.spl_nleft))
+ if (!gistfitpage(lvectup, v.splitVector.spl_nleft) ||
+ (max_page_tuples > 0 &&
+ v.splitVector.spl_nleft > max_page_tuples))
  {
  SplitPageLayout *resptr,
    *subres;

- resptr = subres = gistSplit(r, page, lvectup,
v.splitVector.spl_nleft, giststate);
+ resptr = subres = gistSplit(r, page, lvectup,
+ v.splitVector.spl_nleft, giststate,
+ max_page_tuples);

  /* install on list's tail */
  while (resptr->next)
@@ -1530,6 +1732,141 @@ gistSplit(Relation r,
  return res;
 }

+/*
+ * Form an intrapage index over an ordinary tuple vector.
+ *
+ * Skip tuples are derived metadata: each one is a union key followed by the
+ * real tuples that it summarizes.  If the metadata would make the vector no
+ * longer fit on a page, leave the caller's ordinary representation alone.

Need to say what the return value means. Also the output params.

+ */
+bool
+gistFormSkipGroups(Relation rel, Page page, IndexTuple *itvec, int len,
+   GISTSTATE *giststate, IndexTupleData **list, int *lenlist,
+   int *newlen)
+{
+ SplitPageLayout *groups;
+ SplitPageLayout *group;
+ IndexTuple *grouped;
+ int ngroups = 0;
+ int pos = 0;
+
+ Assert(len > 0);
+

This must not be an off-by-one but it looks like it. Oh len is how
many tuples we want to write, okay. Comment?

+ if (len <= GIST_SKIP_GROUP_SIZE)
+ {
+ groups = palloc0_object(SplitPageLayout);
+ groups->block.num = len;
+ groups->list = gistfillitupvec(itvec, len, &groups->lenlist);
+ groups->itup = gistunion(rel, itvec, len, giststate);
+ }
+ else
+ groups = gistSplit(rel, page, itvec, len, giststate,
+   GIST_SKIP_GROUP_SIZE);
+
+ for (group = groups; group != NULL; group = group->next)
+ ngroups++;
+
+ grouped = palloc_array(IndexTuple, len + ngroups);
+ for (group = groups; group != NULL; group = group->next)
+ {

Is `char *` the right way to do this?

+ char   *data = (char *) group->list;
+

add: /* Every group adds a skip tuple and its contents */

+ GistTupleSetSkip(group->itup, group->block.num);
+ grouped[pos++] = group->itup;
+ for (int i = 0; i < group->block.num; i++)
+ {
+ IndexTuple itup = (IndexTuple) data;
+
+ grouped[pos++] = itup;
+ data += IndexTupleSize(itup);
+ }
+ }
+ Assert(pos == len + ngroups);

This is a lot of copying, isn't it?

[0] https://dsf.berkeley.edu/papers/sigmod97-gist.pdf (cited in the GiST README)

Yours,
-- 
Paul              ~{:-)
[email protected]
GiST intrapage-indexing (skip tuples) -- A/B benchmark results
==============================================================
Patch:  v3 "Add intrapage indexing to GiST", CF 7200.
base =  11591f273e6 (parent of the patch)
gist =  e9689a3f633  (the patch)
Both built from the same tree, same configure; difference is the one commit.
Harness: bench/gist_intrapage_bench.sh (self-contained; see that file / README).
Machine: Apple M-series, macOS 15; shared_buffers=2GB, maintenance_work_mem=1GB,
         autovacuum=off, jit=off, fsync=off. Scans: pgbench 1 client, 3s warm +
         10s measured, latency-average (ms, lower is better).

Each row below is PATCHED-vs-BASE. "x" on build/size = test/base (>1 = worse);
"x" on lat = test/base (<1 = patch faster). Numbers reproduced across two
independent passes (BUILD_REPEATS=3 and =1); both are shown where they differ.

rows = 5,000,000 (cube: 2,000,000)
                                build (s)        index size        scan lat 
(ms)       patched
 dataset / query            base   gist    x    base    gist   x   base   gist  
  x    leaf/int/skip
 
----------------------------------------------------------------------------------------------------
 point    selective-box     22.2   29.2  1.3x  473 MB 473 MB 1.00  0.536  0.498 
0.93  60010/546/6368
 mrange   selective-overlap 53.3   47*   ~1x   240 MB 241 MB 1.00  0.100  0.085 
0.85  30534/258/2090
 temporal pk-probe (id=)     2.7    2.8   1.0x  318 MB 320 MB 1.01  0.036  
0.032 0.90  40540/441/3552
 temporal id-band           (same temporal index)                  0.073  0.069 
0.95  40540/441/3552
 tsrange  selective-window   2.5    2.5   1.0x  174 MB 174 MB 1.00  0.102  
0.098 0.96  22124/197/1568
 cube     selective-overlap  16.2  254.6 15.8x  232 MB 490 MB 2.11  0.031  
0.032 1.03  49117/13619/38215

 * mrange build at BUILD_REPEATS=1 measured faster on gist; that is single-shot
   noise (the patch cannot speed up a build). At BUILD_REPEATS=3 it is ~neutral.
   point's +30% build cost, by contrast, reproduced in both passes -- it is 
real.

datasets
 point    : box over a 10000x10000 grid; ~0.01% box-containment probe (control:
            cheap consistent, tiny key).
 mrange   : int4multirange, one small range each; selective && overlap probe.
 temporal : (id int, valid_at tstzrange), btree_gist + range_ops, ~10 periods 
per
            id, generated in id order (clustered) -- the WITHOUT OVERLAPS case.
            q1 = temporal PK probe (id = const AND valid_at @> instant);
            q2 = small id band (id BETWEEN x AND x+50).
 tsrange  : append-only time series, single tstzrange in time order; selective
            && window probe.
 cube     : 2,000,000 uniform-random 4-D point-cubes; selective && overlap probe
            (large union keys, poor pruning -- the adversarial case).

What it shows
-------------
1. THERE IS A REAL, REPRODUCIBLE READ WIN on common, well-clustered opclasses:
   ~15% (mrange), ~7-10% (point, temporal PK), ~4-5% (temporal id-band, 
tsrange).
   Every one of the 7 non-cube queries got faster, across two independent passes
   -- consistent direction, so this is signal, not noise. The temporal
   (int, tstzrange) case -- the single most common GiST use -- benefits (~5-10%)
   at +0.5% size and neutral build. That is the headline positive result.

   The win is MODEST (single digits to ~15%), as expected: skip tuples prune
   `consistent` calls only on INTERNAL pages, which are <2% of the index; the
   dominant leaf-level `consistent` cost is untouched (leaf-only exclusion).
   It grows with tree depth (invisible at 1M rows, measurable at 5M).

2. IT IS NOT FREE. CREATE INDEX regressed ~30% on point (reproduced), and skip
   tuples roughly DOUBLE the internal-page count on every dataset (point
   515->546 is mild; temporal 223->441, tsrange 99->197). Because internal pages
   are a small fraction of the index, total size barely moves (<=0.5%) for these
   opclasses -- but see cube.

3. IT IS NOT SELF-LIMITING. On cube (large union keys + poorly-clustered data)
   the internal-page doubling compounds a GiST that already has low fanout: 30x
   more internal pages, fanout ~65 -> ~3.6, index size 2.1x, build 15.8x, and
   ZERO read benefit (random high-dim unions overlap the query, so no group is
   ever rejected). This is a build/split pathology, not mere write
   amplification: a 1-skip-per-16-downlinks overhead cannot produce a 30x
   internal blowup.

Takeaway for the thread
-----------------------
The feature earns its keep on ranges/multiranges/points/temporal -- a small but
real read speedup at small cost -- so the direction is worthwhile. But it needs
a GUARD so it cannot fire on the cube-like cases: don't form a group whose union
is barely more selective than its members, and/or make skip-tuple formation
opt-in per opclass or per index (reloption). The patch should also (a) justify
GIST_SKIP_GROUP_SIZE=16 and the split behaviour that lets internal fanout fall
to ~3.6 on cube, and (b) report the CREATE INDEX cost (point +30%).

Reproduce
---------
  # from a postgres checkout on the patch branch:
  CONFIGURE_FLAGS="--enable-tap-tests" \
    bench/gist_intrapage_bench.sh build . HEAD~1 HEAD
  # or, if you already have two installs:
  bench/gist_intrapage_bench.sh run /path/base/bin /path/test/bin 5000000 10
  # knobs: ROWS (4th arg), SCAN_SECS (5th), BUILD_REPEATS, DATASETS env.

Incremental INSERT: time + WAL  (bench/insert_wal_ab.sh)
--------------------------------------------------------
Checking a second reviewer's claims ("500k INSERT ~1.4x faster" and "~5% more
WAL"). Preload 5,000,000 random points + GiST index, one warmup batch +
CHECKPOINT, then 6 measured 500k-row INSERT batches. gist run FIRST (so a
"faster" result cannot be a run-order cold-cache artifact). Steady state
(reps 2-6; rep1 carries post-checkpoint full-page images for both and is
excluded). point opclass, fsync=off, shared_buffers=2GB.

              insert time      WAL per 500k batch
   base       ~2.47 s          ~112 MB
   gist       ~2.03 s          ~125 MB
   ratio      gist 1.22x FASTER   gist +12% WAL

Both directions reproduce our own measurement:
* INSERT is genuinely faster (~1.22x here; reviewer said ~1.4x). Real mechanism:
  the insert DESCENT prunes whole groups when choosing a subtree, so it makes
  fewer `penalty` calls per internal page. Under fsync=off with the index in
  shared buffers the insert is CPU-bound, so fewer comparisons -> lower wall
  time. (I was initially wrong to call a faster insert impossible.)
* INSERT emits MORE WAL (~+12% steady-state here; reviewer said ~5%; including
  full-page images the single-batch figure was +3.7% -- FPIs dilute the %, so
  ~5% is plausible under their settings). Mechanism: full-page logging of the
  extra internal-page skip-tuple maintenance.
* The two are NOT contradictory: faster wall-clock (fewer CPU comparisons) and
  more WAL bytes (more page maintenance) coexist under in-memory / fsync=off.

NOTE the build-vs-insert split: bulk CREATE INDEX is SLOWER with the patch
(point ~+30%, cube 15.8x -- it forms skip groups via the split machinery, pure
added work with no descent savings), while incremental single-row INSERT is
FASTER (fewer penalty calls on descent). Different code paths, opposite signs.

The reviewer's third claim -- "sorted-tree joins 1.6-1.9x faster" -- is NOT
credible for this patch and was not reproduced: GiST produces no sorted output
(no amcanorder pathkeys, overlapping subtrees), so there is no sorted/merge-join
or Sort-elimination path for it to speed up, and the patch touches only internal
pages. If it means a nested-loop spatial/temporal join with an inner GiST probe,
the per-probe read win measured above (<=~15%) cannot yield 1.6-1.9x. Ask for
the exact query + EXPLAIN (ANALYZE); this figure likely reflects something other
than the patch (a plan change, caching, or a mis-attributed measurement).

Attachment: v4-0001-Add-intrapage-indexing-to-GiST.patch
Description: Binary data

Attachment: insert_wal_ab.sh
Description: Bourne shell script

Attachment: gist_intrapage_bench.sh
Description: Bourne shell script

Attachment: concurrency_bench.sh
Description: Bourne shell script

GiST intrapage-indexing -- concurrency A/B  (bench/concurrency_bench.sh)
=======================================================================
Question (from the review of gistplacetopage): do concurrent inserts that
descend THROUGH a skip tuple hurt lock contention, throughput, or bloat vs
plain GiST?

Setup: preload 3,000,000 random points + GiST index, then 8 concurrent pgbench
clients each insert 100,000 single rows (800,000 inserts total, same work on
both builds). A background sampler polls pg_stat_activity wait events every
~20 ms during the run. fsync=off, shared_buffers=2GB, autovacuum=off. base =
11591f273e6, gist = e9689a3f633.

SPREAD (KEYRANGE=1,000,000 -- inserts scattered across the whole tree)
                    time     tps      idx grew   free%   leaf/internal   top 
waits
   base            8.29s    96686    +51.0 MB    32.9    30770/266       
WALWrite280 ClientRead191 WalInsert48 SpinDelay39
   gist            8.05s    99597    +51.5 MB    32.9    30787/276       
WALWrite282 ClientRead192 WalInsert36 SpinDelay30

HOTSPOT (KEYRANGE=2,000 -- all 8 clients funnel into ONE tiny region, i.e.
the same subtree / internal page / skip group: the adversarial case)
                    time     tps      idx grew   free%   leaf/internal   top 
waits
   base            7.92s   101173    +49.5 MB    32.4    30558/261       
WALWrite247 ClientRead214 SpinDelay23 WalInsert17
   gist            7.77s   103128    +49.4 MB    32.4    30548/271       
WALWrite222 ClientRead214 SpinDelay39 WalInsert29

Findings
--------
* Throughput: gist is slightly FASTER in both workloads (~3% spread, ~2%
  hotspot) -- consistent with the cheaper insert descent seen elsewhere. Not a
  regression.
* Bloat / size: identical. Same free_percent (32.9 / 32.4), same index growth
  (+51 MB / +49 MB), same leaf/internal page counts to within ~10 internal
  pages (the skip-tuple overhead). Concurrent inserts through skip tuples do not
  bloat the index more than plain GiST.
* Lock contention: the wait-event profile is the SAME on both builds and is
  dominated by WAL (WALWrite / WALInsert / WalWrite) and ClientRead -- NOT by
  LWLock:BufferContent or LockManager. No index-page lock contention emerges on
  either build, even in the hotspot run. The patch adds no new lock: skip tuples
  live on the same internal page as the downlinks and are read under the same
  buffer lock, so descent locking is unchanged.

Caveat: fsync=off makes WAL flushing the bottleneck at this insert rate, which
is why WAL waits dominate. That is identical for both builds, so the A/B
comparison (no added contention, no added bloat) holds; it just means this test
does not stress disk. Re-running with fsync=on would raise absolute WAL waits
equally on both and is not expected to change the base-vs-gist verdict.

Reply via email to