nbtree: opt-in leaf key prefix compression

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

nbtree: opt-in leaf key prefix compression

От:
Greg Burd <greg@burd.me>
Дата:
Вложения:
Hello Hackers,

This is a patch that adds leaf key prefix compression to nbtree, behind
a new per-index storage parameter, prefix_compression, off by default.
It's something I started a long time ago when primarily working on
JSONB-like data storage/indexing/etc. in Postgres when a colleague
pointed out that it didn't yet exist and his measurements showed that it
should.  He wasn't wrong.  It's a solid win for performance and overhead
IMO, but YMMV.

The motivation is simple: indexes on keys that share a long leading
prefix (URLs, reverse-DNS names, a leading JSONB path, a tenant-id
prefix) spend most of their bytes storing that prefix over and over.
Store it once per page and the index gets a few times smaller, which
means fewer pages to read and less WAL to write.  All good things.

A URL index in my tests is about 3x smaller; an index with little shared
prefix is unchanged (the page is left alone when a prefix does not pay
off).


Overview:

When a leaf page is written as a whole (during an index build, as a
split half, or as the result of a deduplication pass) and its data items
share leading bytes in their first key column, the page is rebuilt in a
new BTP_PREFIX format: one PREFIX item after the high key holds the
shared bytes, and each data item is stored "coded", with its copy of the
shared prefix replaced by a one-byte length.  Reads of a leaf data item
go through a single accessor, _bt_getitem(), that decodes on demand into
caller-supplied scratch; high keys and internal-page downlinks are never
coded and are read with the existing PageGetItem().

This is a per-page opt-in with no on-disk version change: BTREE_VERSION
and the catalog version are not touched.  A page is converted only when
it is next written as a whole, never by an ordinary insert, VACUUM, or
key-range change. So an existing index "faults forward": old-format and
new-format pages coexist in the same index indefinitely.  That is what
makes the feature safe across pg_upgrade, physical replication, and
standbys with no REINDEX: a replica that has not yet replayed a page's
conversion still reads the old format correctly, and turning the
parameter back off stops new conversions while existing coded pages stay
readable.


Performance:

Release builds (cassert=off), origin/master vs the patch, on a
c7i.4xlarge, pgbench, fsync and synchronous_commit off so the index
effects are not masked by WAL flush latency.  "off" is the patch with
the parameter off (the default path), to show it is free when unused.

   index size (pages), CREATE INDEX on ~500k rows:

     shared prefix / key    master    patch=on
     ---------------------   ------    --------
     URL-like, distinct      10531      7848  (-25%)
     JSONB path, distinct    11636      5782  (-50%)
     int (no shared prefix)  (same)    (same, page left uncompressed)

   insert throughput (one row at a time into an existing index):

     workload           TPS master->on       WAL/txn master->on
     ---------------    ------------------    ------------------
     insert_random      143.7k -> 142.8k      292 B -> 226 B
     insert_ascending   144.9k -> 139.4k      277 B -> 228 B

WAL per insert is slightly *below* master because the coded tuple logged
is full-page-image penalty.  CREATE INDEX WAL is roughly half of
master's on these keys.

The "off" column tracks master within noise on every workload, so the
default path is not paying for a feature it is not using.


Deduplication composes with it:

Prefix compression and deduplication stack.  A build deduplicates first
and then codes the finished page, so a duplicate-heavy prefix index is
no larger than a plain one: the posting lists collapse the duplicates,
and the prefix then front-codes the distinct keys that remain. Across a
duplication sweep the prefix index is <= plain everywhere, and smaller
once there is any shared prefix among the distinct keys.  Without this
the earlier drafts were several times *larger* on duplicate-heavy data,
which is the trap to avoid if you try this yourself.

Bottom-up index deletion runs on coded pages unchanged, since it only
removes items and never rewrites survivors.  A runtime deduplication
pass on a coded page decodes its items first, and because a coded page
can hold more logical data than fits plain, the pass aborts cleanly and
the page splits instead when the decoded set would overflow, it never
errors out.


WAL:

The part I most want eyes on.  Replaying a coded page byte-for-byte is
the hard requirement (wal_consistency_checking has to pass on a
standby), and the obvious implementation (a forced full-page image on
every change to a coded page) costs a whole page of WAL per insert.

Instead redo reconstructs the coded bytes the way the primary did.  The
catch is that redo has no relcache and cannot run the prefix-choosing
heuristic, so the primary logs the prefix it chose, and a single
Relation-free layout routine (_bt_split_leaf_layout) is shared by the
primary and redo so both emit identical bytes from the same inputs:

   - an in-place insert logs the coded tuple; the standard insert redo adds
     it verbatim;
   - a split logs each half's chosen prefix plus the right half's plain
     items, and redo lays each half out coded;
   - a deduplication logs the chosen prefix plus the deduped plain items.

Each path keeps a bounded fallback to a forced image for a
pathologically compressible page whose plain payload would exceed one
block, so the logged payload can never exceed BLCKSZ.


What reviewers should know going in:

Things I already know are worth a hard look, so you don't have to find
them cold:

   - A posting-list split on a coded page, and a deduplication pass whose
     re-compression then declines, are the two fiddliest WAL paths.  I
     had bugs in both (a palloc inside a critical section on the first;
     redo not decoding on the second) and have fixed them, but they are
     where I would point a reviewer first.  I could not turn the second
     into a failing wal_consistency_checking case and would value a
     second opinion on whether the path is actually reachable.

   - Every read of a leaf *data* item must go through _bt_getitem().  I
     audited the readers; the one I missed on the first pass was the
     array-scan look-ahead in _bt_readpage(), now fixed.  A reviewer's
     instinct for "is this a data item or a pivot?" is exactly the check
     I want applied to the rest.

   - The split point is chosen on coded sizes, which breaks the usual
     assumption that a leaf holds at most two pages' worth of data; there
     is a guard against a degenerate split that would leave the left page
     with no data items.  nbtsplitloc.c is worth a read for that reason.

   - Runtime deduplication on a coded page is the one place that can
     decline and fall through to a split rather than reclaim space.  That
     is deliberate (the decoded set can exceed a page), but it means a
     duplicate-heavy index populated by one-row-at-a-time inserts is less
     compact than the same index built with CREATE INDEX.  I think that
     is an acceptable trade; it may warrant a doc note.

   - amcheck decodes every leaf data item, including under heapallindexed.

Tested with wal_consistency_checking=all on a primary and a streaming
standby across insert, split, deduplication, delete and vacuum
workloads, through immediate-crash recovery, and across a pg_upgrade
that carries both page formats in one index.  -Werror, --enable-cassert
and --enable-injection-points clean; make check, the isolation, amcheck,
pageinspect and pgstattuple suites, and 027_stream_regress all pass.


Open questions:

   (a) Is a per-page opt-in with no version bump the right contract?  I
       chose it so the feature needs no REINDEX and is a no-op risk for
       anyone who leaves it off, at the cost of old and new page formats
       living in one index forever.

   (b) Is the shared primary/redo layout routine the right factoring, or
       would you rather the build, split and dedup paths share even more (a
       common "code a leaf from plain items + prefix" helper)?

   (c) The forced-image fallback threshold is "plain payload > one block".
       It essentially never fires on real data; is that the right place to
       draw the line?

The patch is one commit against master.  I'd appreciate review of the
approach and the code, and I'm happy to work through whatever it turns
up.

best.

-greg

Re: nbtree: opt-in leaf key prefix compression

От:
Greg Burd <greg@burd.me>
Дата:
Вложения:
Hello,

v2 attached to appease the cf-bot, master moved under me (notably Peter's
d42c5457e5, the multi-level page-deletion WAL fix, which touches nbtpage.c
right where this patch drops the PREFIX item on an emptied leaf).  v2 is
rebased on top of that; the two changes don't actually overlap, and page
deletion of a prefix leaf still replays byte-for-byte under
wal_consistency_checking=all.

While rebasing I did a review pass of my own with Peter's nbtree
sensibilities in mind, since he's the obvious reviewer and I'd rather
not waste his time on things I can see coming.

To that end, three things changed:

1. One split-collection routine, not two.

   v1 had the primary _bt_split() build the left/right plain-item
   arrays with its own inline loop, while redo built them with
   _bt_split_leaf_collect() -- two hand-maintained copies of the same
   logic that have to agree exactly or a standby diverges with no
   version bump to catch it.  That's the classic footgun.  v2 has
   _bt_split() call _bt_split_leaf_collect() too, so the primary and
   redo derive the identical plain-item sequence from one place and
   then code it with the shared _bt_split_leaf_layout().  The incremental
   path for internal pages is unchanged.

2. amcheck actually checks the new format.

   v1 taught verify_nbtree.c to *decode* coded items (so the existing
   checks run on real keys), but it validated none of the BTP_PREFIX
   structure and the test suite never ran amcheck on a prefix index at
   all.  v2 adds structural checks -- the flag only on leaf pages, a
   well-formed PREFIX item at the expected offset with a legal length --
   and contrib/amcheck now builds a prefix-compressed index (shared
   prefix + no-shared-prefix + NULL, enough rows to split and dedup) and
   runs bt_index_check / bt_index_parent_check with heapallindexed over
   it.  amcheck is how "two formats coexist forever" stays true, so it
   should carry its weight here.

3. Docs and comments matched to the code.

   The README still described the first design, where split and dedup
   pages were carried by full-page image; that's long gone (redo rebuilds
   the coded bytes from logged plain items now), and it also still
   claimed dedup and bottom-up deletion don't run on prefix pages, which
   is also no longer true.  Rewritten to match.  A couple of stale
   XLH_SPLIT_RPREFIX-era comments went with it.  I also added the
   "can't happen" bounds asserts on the WAL-data-driven item loops in
   redo.

The one thing I deliberately did NOT change, because I think it's a
real design question rather than a cleanup, is how much nbtsplitloc.c
knows about the feature.

Right now _bt_findsplitloc()/_bt_recsplitloc() reason in coded (on-page)
bytes on a prefix page, and there's a small guard that rejects a split
point that would leave the left page with no data items.  I know the
history here: when deduplication went in, the strong preference was for
nbtsplitloc.c to stay ignorant of posting lists and for _bt_split() to
fix up reality at one point just before WAL-logging.  I tried to honor
that -- the split chooser still treats everything as plain tuples for
placement, and the "room for at least one heap TID" conservatism in
_bt_recsplitloc() is untouched.  But I could not make the *space*
accounting pretend coding doesn't exist: a compressed leaf legitimately
holds more logical data than two plain pages, so feeding plain sizes to
the split chooser makes some splits look infeasible that are not.  So
the accounting is in coded bytes, and the guard exists because coded-size
accounting can otherwise pick a degenerate point that plain accounting
never would.

I can see two ways to push the feature further out of nbtsplitloc.c and
I'd like an opinion before I build either:

  (a) leave the coded-size accounting where it is but move the
      degenerate-split guard into _bt_split() (reject/retry there), so
      nbtsplitloc.c at least stops having a prefix-only early return; or

  (b) have nbtsplitloc.c reason entirely in plain sizes and teach
      _bt_split() to fall back to a plain (uncompressed) left/right half
      when the chosen point doesn't fit coded -- i.e. the page just
      doesn't get compressed this time, rather than the chooser knowing
      about coding at all.

(b) is closer to the "nbtsplitloc.c knows nothing" ideal but gives up
compression on exactly the fullest pages; (a) keeps the space win but
leaves the accounting coded.  I lean (a).  Thoughts?

Two open items I flagged in v1 still stand: the forced-full-page-image
fallbacks (XLH_SPLIT_RFPI / XLH_DEDUP_RFPI) only fire for a page whose
plain payload would exceed a block, which I've never hit on real data,
I can either add a test that forces the path or demote it to a
can't-happen error if we decide it's unreachable; and I owe an
"alternatives considered" note on why this is a new on-disk format
rather than an extension of posting lists (short version: posting lists
collapse *equal* keys, this compresses *distinct* keys that share a
prefix, so they're complementary, which the dedup composition in the
patch relies on).

best.

-greg

Re: nbtree: opt-in leaf key prefix compression

От:
Greg Burd <greg@burd.me>
Дата:
Вложения:
Hello,

v3 attached.  This closes the two open items I flagged with v2 and reports back
on the nbtsplitloc.c design question, which turned out to have a clearer answer
than I expected once I measured it.

1. The forced-full-page-image fallbacks

   XLH_SPLIT_RFPI and XLH_DEDUP_RFPI carry a coded page as a full-page image in
   the one case redo can't rebuild from logged plain items: a page so
   compressible that its decoded payload exceeds a block.  I could not reach
   that threshold with any realistic data in v2, which left the path
   unexercised.  I instrumented it on maximally compressible keys (a 125-byte
   shared prefix, tiny suffixes), the right half of a split tops out around 6
   KB of plain payload, which is close, but the split-point balance keeps a
   half under a block, so the fallback never fires naturally.

   It is reachable in principle (a different item-size mix could get there), so
   I'm keeping it rather than demoting it to a can't-happen error.  An error
   there would be a rare production PANIC on data that is merely unusual, not
   corrupt.  To make it testable, there's now a nbtree-prefix-force-rfpi
   injection point that forces the fallback for every prefix split and
   deduplication, and a test in src/test/modules/nbtree that builds and
   deduplicates a prefix index with it attached, then amchecks the result.
   Writing that test immediately caught a bug (the injection-point check sat
   inside the WAL critical section, where the first-use cache load palloc()s)-
   which is now fixed (the decision is made before the critical section).
   Byte-for-byte redo through the forced image is covered by the existing
   crash-recovery and streaming runs under wal_consistency_checking.

2. Alternatives-considered

   The README now spells out why this is a separate mechanism rather than an
   extension of posting lists: deduplication collapses tuples whose whole key
   is equal; prefix compression factors out a leading run shared by distinct
   keys.  They attack different redundancy and compose on one page (deduplicate
   first, then code the survivors), which is why a build runs both.
   Overloading the posting-list format to also carry a shared prefix was
   considered and rejected; a posting list is one key plus many TIDs, prefix
   coding is many keys that share a prefix, so they'd need different per-item
   layouts anyway, and it would entangle the two paths this patch keeps apart.

3. The nbtsplitloc.c question

   I proposed moving the degenerate-split guard (the one that rejects a split
   leaving the left page with no data items) out of nbtsplitloc.c. I tried the
   cleanest version of that; make the guard unconditional instead of
   prefix-only, on the theory that upstream never chooses that split point for
   a plain page anyway, so it would be a no-op there.  It is not a no-op: a
   probe showed _bt_recsplitloc() is called at that point for plain pages all
   the time, and rejecting it unconditionally broke three test suites.  The
   guard genuinely has to be prefix-specific, because it exists precisely
   because coded-size accounting makes a point attractive that plain-size
   accounting rejects on its own via the leftfree check.

   Moving it into _bt_split() instead of nbtsplitloc.c doesn't help either:
   _bt_split() doesn't choose split points, so it would have to re-derive or
   reject-and-retry, which is more prefix logic in a more dangerous place (next
   to the critical section), not less.  So I've left the guard where it is: one
   well-commented "if" in _bt_recsplitloc().  The coded-size accounting stays
   too, for the reason in v2 (a compressed leaf legitimately holds more than
   two plain pages' worth, so plain-size accounting makes feasible splits look
   infeasible).  If you'd still rather see it elsewhere I'll do it, but I
   wanted to report that the "obvious" relocation makes the code worse, not
   better.

Everything else from v2 stands: one split-collection routine shared by
primary and redo, amcheck structural checks plus a prefix-index test,
docs matched to the tuple-rebuild WAL design.

I think v3 is in good shape, so I'll leave it here and pick it back up on
review feedback (or if cf-bot turns something up).

I might run more benchmarks, just for fun.

-greg

Re: nbtree: opt-in leaf key prefix compression

От:
Greg Burd <greg@burd.me>
Дата:
Вложения:
Hello,

v4 attached, rebased on current master (cfbot had gone stale on a
not-applying from the v3 window; the patch applies clean on HEAD, so
this mostly just gives the bot a fresh version to chew on).  No code
changes from v3.

I did say I'd run more benchmarks for fun, so here they are.  Release
builds (cassert=off), master vs the patch, c7i.4xlarge, fsync and
synchronous_commit off so the WAL numbers aren't buried under flush
latency.  "off" is the patch with prefix_compression left off, to show
the default path is free.

The headline is that the size win shows up where the keys are actually
distinct-but-prefixed, which is the case the feature is for.  One row at
a time into an existing URL index (37-byte shared prefix, distinct
suffixes):

   workload           index pages (master -> on)   WAL/txn (master -> on)
   ----------------   -------------------------    ----------------------
   insert_random        22177 ->  7506  (-66%)       292 -> 226 bytes
   insert_ascending     19036 ->  5429  (-71%)       277 -> 227 bytes

TPS is within noise either way (random 138k -> 136k, ascending 134k ->
131k).  WAL per insert drops because a coded tuple is smaller than the
plain one it replaces.  The split/dedup redo rework from the earlier
versions is what keeps that from turning into a full-page-image tax.

CREATE INDEX on 2M rows is a more mixed bag, because how much a prefix
buys depends entirely on the key shape:

   shape                index pages (master -> on)   build WAL (master -> on)
   ------------------   -------------------------    ------------------------
   url  (g % 1e6)         10531 ->  9538  (-9%)        80  -> 48 MB
   code (ACCT-...)         7140 ->  6495  (-9%)        48  -> 32 MB
   md5  (random hex)      14420 -> 13026  (-10%)       99  -> 109 MB
   jsonb (tenant+path)    11636 -> 10657  (-8%)        71  -> 28 MB
   int  (control)          5487 ->  5487  (0%)         32  -> 32 MB

Two things worth calling out there.  The build-time size wins look
smaller than the insert ones only because these build shapes use lots of
near-duplicate keys (g % 1e6) with a short shared run; deduplication
already collapses most of that, so prefix coding is adding a few percent
on top rather than doing the heavy lifting.

The insert workload above, with genuinely distinct keys, is the fairer
picture of what the feature does.  And the int control is exactly
unchanged.  A page whose keys share nothing is left alone, so there's no
cost to carrying the option on a table where it doesn't pay.

md5 is the one that surprised me a little: even random hex strings share
enough of a leading nibble run across a page to shave ~10% off, though
the build WAL ticked up slightly there (109 vs 99 MB), which I want to
look at.  Probably the recompression churn on a shape that barely
benefits.  Not a blocker, but I'd rather understand it than wave it off.

Update churn (indexUnchanged UPDATEs, 8 clients) is within noise on TPS
and WAL, and the index stays flat at 186 pages before and after on all
three variants, which is bottom-up deletion doing its job on coded pages.

Everything else stands from v3.

best.

-greg

Re: nbtree: opt-in leaf key prefix compression

От:
Yao Feng <fengyao0087@gmail.com>
Дата:
Hi Greg,

Thanks for working on this, took a look at the v4 patch.

 I think this is very worthwhile work. FWIW, a recent SIGMOD paper on B-tree compression (https://dl.acm.org/doi/10.1145/3654972) noted that while front-coding saves a lot of space for strings, decompression CPU cost tends to be the main bottleneck for queries on modern hardware. Looking at the v4 benchmarks, they mostly cover index size and write throughput -- did you have a chance to measure read-side performance (e.g. index scans, point lookups)?

A few quick questions from having played with something similar a while back:

1. Skipping decompression when index tuples aren't returned:
Right now _bt_readpage() eagerly calls _bt_getitem() to decode every leaf tuple. That's necessary when the scan actually needs to return the index tuple (like IndexOnlyScan), but for operations that don't return tuples and only care about the heap TID -- such as a plain IndexScan, BitmapIndexScan, or COUNT(*) -- could we skip decompression?

2. Multi-column indexes:
The patch requires column 0 to be a varlena. I'm curious if you considered supporting subsequent columns (e.g. for something like `(tenant_id int, url text)`), or if keeping it strictly to the first column was just a natural place to draw the line on complexity for now?

3. Prefix boundaries within a page:
With one prefix per page, if a page spans two different domains (say, a bunch of `http://example.com/1`, `.../2` followed by `http://sample.org/1`, `.../2`), the second group only shares "http://". Just curious if you've considered this kind of case?

Curious to hear your thoughts.

--
Yao Feng

Greg Burd <greg@burd.me> 于2026年10月30日周五 00:43写道:
Hello,

v4 attached, rebased on current master (cfbot had gone stale on a
not-applying from the v3 window; the patch applies clean on HEAD, so
this mostly just gives the bot a fresh version to chew on).  No code
changes from v3.

I did say I'd run more benchmarks for fun, so here they are.  Release
builds (cassert=off), master vs the patch, c7i.4xlarge, fsync and
synchronous_commit off so the WAL numbers aren't buried under flush
latency.  "off" is the patch with prefix_compression left off, to show
the default path is free.

The headline is that the size win shows up where the keys are actually
distinct-but-prefixed, which is the case the feature is for.  One row at
a time into an existing URL index (37-byte shared prefix, distinct
suffixes):

   workload           index pages (master -> on)   WAL/txn (master -> on)
   ----------------   -------------------------    ----------------------
   insert_random        22177 ->  7506  (-66%)       292 -> 226 bytes
   insert_ascending     19036 ->  5429  (-71%)       277 -> 227 bytes

TPS is within noise either way (random 138k -> 136k, ascending 134k ->
131k).  WAL per insert drops because a coded tuple is smaller than the
plain one it replaces.  The split/dedup redo rework from the earlier
versions is what keeps that from turning into a full-page-image tax.

CREATE INDEX on 2M rows is a more mixed bag, because how much a prefix
buys depends entirely on the key shape:

   shape                index pages (master -> on)   build WAL (master -> on)
   ------------------   -------------------------    ------------------------
   url  (g % 1e6)         10531 ->  9538  (-9%)        80  -> 48 MB
   code (ACCT-...)         7140 ->  6495  (-9%)        48  -> 32 MB
   md5  (random hex)      14420 -> 13026  (-10%)       99  -> 109 MB
   jsonb (tenant+path)    11636 -> 10657  (-8%)        71  -> 28 MB
   int  (control)          5487 ->  5487  (0%)         32  -> 32 MB

Two things worth calling out there.  The build-time size wins look
smaller than the insert ones only because these build shapes use lots of
near-duplicate keys (g % 1e6) with a short shared run; deduplication
already collapses most of that, so prefix coding is adding a few percent
on top rather than doing the heavy lifting.

The insert workload above, with genuinely distinct keys, is the fairer
picture of what the feature does.  And the int control is exactly
unchanged.  A page whose keys share nothing is left alone, so there's no
cost to carrying the option on a table where it doesn't pay.

md5 is the one that surprised me a little: even random hex strings share
enough of a leading nibble run across a page to shave ~10% off, though
the build WAL ticked up slightly there (109 vs 99 MB), which I want to
look at.  Probably the recompression churn on a shape that barely
benefits.  Not a blocker, but I'd rather understand it than wave it off.

Update churn (indexUnchanged UPDATEs, 8 clients) is within noise on TPS
and WAL, and the index stays flat at 186 pages before and after on all
three variants, which is bottom-up deletion doing its job on coded pages.

Everything else stands from v3.

best.

-greg

Re: nbtree: opt-in leaf key prefix compression

От:
Greg Burd <greg@burd.me>
Дата:
Вложения:
On Fri, 30 Oct 2026 19:52:00 +0800, Yao Feng  wrote:
> Hi Greg,

Hey Yao,

Quick list-etiquette note, don't top post.  Add your reply within the
content of the message or after it. :)

> Thanks for working on this, took a look at the v4 patch.

Thanks for taking the time to read and review it! :)

> I think this is very worthwhile work.

Thanks, so do I.

> FWIW, a recent SIGMOD paper on
> B-tree compression (https://dl.acm.org/doi/10.1145/3654972) noted that
> while front-coding saves a lot of space for strings, decompression CPU cost
> tends to be the main bottleneck for queries on modern hardware. Looking at
> the v4 benchmarks, they mostly cover index size and write throughput -- did
> you have a chance to measure read-side performance (e.g. index scans, point
> lookups)?

Thanks for the careful read, and for the SIGMOD pointer.  That
decompression-CPU-dominates finding matches what I see below, and it's
exactly the right thing to point out, these kinds of changes are
trade-offs.  Rarely is there a free win.  Yep, you're right that v4 only
reported size and write throughput, I should have considered CPU
overhead as an important metric earlier in my process.  So, I went and
measured the read side to see where it bites.

Read-side numbers:

Release build, c7i.4xlarge, shared_buffers=4GB, everything warm, 3M
distinct URL keys (37-byte shared prefix, 10-digit distinct suffix),
prefix_compression off vs on in the same binary so this isolates the
decode cost, nothing else:

   index size             off 24855 pages   on 22630 pages   (-9%)
   point lookup (IOS)     off 180.3k tps    on 178.3k tps    (~1%, noise)
   COUNT(*) index-only    off 341 ms        on 360 ms        (+6%)
   range scan, 100k keys  off 10.9 ms       on 11.7 ms       (+7%)

So: a point lookup decodes one tuple and the cost vanishes into the
noise, but a scan that walks many tuples pays a real ~6-7%.  That lines
up with the paper and with your instinct (that, the cost is proportional
to how many tuples you decode) so it shows up on traversal, not on
seeks.  This is also with a fairly short 37-byte prefix; a longer shared
prefix decodes more bytes per tuple and would cost a bit more, which I
I'll guess grows with the size of the prefix, but I should measure and not guess.

Which leads straight into your question 1.

1. Skipping decode when the tuple isn't returned

This is the right instinct, and the optimization makes sense.  The heap
TID lives in t_tid, which is never coded, so a scan that only needs the
TID (e.g. a plain IndexScan, BitmapIndexScan, COUNT(*)) genuinely does
not need the decoded key to *return* anything.

Two honest caveats on how far it reaches, though.  The tuple copy is
already skipped: _bt_saveitem() only materializes into so->currTuples
when the scan asked for the index tuple (IndexOnlyScan), so a plain
IndexScan already doesn't pay the copy.  What my eager _bt_getitem() in
_bt_readpage() still pays for is the *key check*, _bt_checkkeys() needs
the real key to decide whether a tuple satisfies the scan keys, and
that's true coded or not.

So the win is specifically only when a tuple is in the interior of a
matching range (the scan keys are already known-satisfied and we're not
returning the tuple), the decode feeds nothing.

That's exactly the COUNT(*) / full-range case above, which is where the
6% sits, so it's worth doing.  I just don't want to claim it makes all
scans free, only the "walking a known-matching run without returning it"
ones.

I'll prototype and measure it as a follow-up in this thread.  The "do I
need the key here?" signal (roughly, so->currTuples != NULL, or
key-check still required) into _bt_readpage() and keep the item coded
when neither holds.

2. Multi-column indexes

First-column-only was a deliberate line, not a fundamental limit.  The
coding is defined on the leading key column's bytes; extending it to a
shared prefix that spans into later columns is possible but means the
per-page prefix has to describe a column boundary and the decode has to
reassemble a multi-attribute tuple, which is more format and more decode
CPU for (I suspect) a smaller marginal win than the first column already
captures.  For (tenant_id int, url text) specifically the leading int is
fixed-width and usually low-cardinality, so you'd want to prefix-code
the *second* column within each leading-value run, which is really a
different feature (per-run prefixes, see 3).  I'd rather land the
first-column case, which is the common shape (a single text/jsonb key,
or a leading key that's the long one), and treat multi-column as a
follow-on proposal when/if this lands.  But I'm adding it to my list
because I'm optimistic on this patch.

3. Prefix boundaries within a page

Yes, this is the real limitation of one-prefix-per-page, and you have
hit on the right worst case: a page spanning example.com and sample.org
only gets to factor out "http://".  _bt_prefix_choose() picks the single
longest prefix common to all data items on the page, so a page
straddling two groups keeps only what both share.

Two things soften it in practice but don't remove it: the keys are
sorted, so a straddling page is the boundary page between two runs. Most
pages sit entirely inside one run and get the full prefix. Also a page
that compresses poorly is simply left uncompressed (the int control in
the v4 numbers), so a bad straddle costs nothing rather than bloating.

The actual fix is multiple prefixes per page (a small prefix directory,
each data item pointing at its group's prefix), which is a natural v2 of
the on-disk format and also what would make the multi-column case in (2)
fall out.

I deliberately kept v4 to one prefix to get the format and the
WAL/replay story reviewed before adding that complexity.  I think it's
the right thing to consider building next if the basic version is judged
commit-worthy, at minimum to benchmark it and see if it makes a
difference or not.

Here's a wild idea for another day: if the zstd-dict thread [1] lands or
the work from the thread started by Hannu [2] I might give adding
dictionary-based compression to the prefix compression algorithm and
measure that.  Who knows...

I'll fold the read-side numbers into the next revision and prototype the
skip-decode path.

Thanks again, these were the right questions.

best.

-greg

[1] https://postgr.es/m/CAMT0RQQ+7bhiM9FtrZ7cdWxxFR=jtQCq6poDPs75oJuGMDdPKg@mail.gmail.com
[2] https://postgr.es/m/CAMT0RQQtJprWKdK4L_wsD++aQaQ972kRdGfGA+su3JfFdYuEmA@mail.gmail.com

Re: nbtree: opt-in leaf key prefix compression

От:
Greg Burd <greg@burd.me>
Дата:
Вложения:
Hello,

v7 attached, one real fix since v4, found by the sanitizer CI.

CI was red on the Linux Autoconf and 32-bit legs (the ones built with
-fsanitize=alignment,undefined -fno-sanitize-recover=all) while every
other leg (64-bit meson, macOS, Windows) was green.  The standby's
startup process aborted (SIGABRT) replaying a prefix leaf split:

   itup.h:74: runtime error: member access within misaligned address
              ... for type 'const struct IndexTupleData'
   #1 btree_xlog_split_prefix  nbtxlog.c
   #2 btree_xlog_split
   #3 btree_redo

The split/dedup WAL payload for the right half is [chosen prefix bytes]
[high key][data items].  I was advancing past the prefix bytes by the
raw prefix length, not a MAXALIGN'd length, so the IndexTuple high key
(and the items after it) landed on an unaligned offset.  On x86-64 the
misaligned read happens to work, which is why plain cassert builds and
my own testing never caught it; the alignment sanitizer correctly
rejects it, and a big-endian or stricter-alignment platform would fault
for real.

Fix: MAXALIGN the prefix region on both the logging and the replay side,
in the split path (_bt_split / btree_xlog_split_prefix) and the matching
dedup path (_bt_dedup_pass / btree_xlog_dedup).  The left-half prefix is
logged last and read back as raw bytes, never dereferenced as a tuple,
so it was already fine and is unchanged.

The lesson for me is that WAL-payload packing has to be tested under the
alignment sanitizer, not just cassert.

No other changes from v4.  For the committer (I hope!), a BTREE_VERSION
and catalog version bump.

best.

-greg

Re: nbtree: opt-in leaf key prefix compression

От:
Greg Burd <greg@burd.me>
Дата:
Вложения:
Hello again,

v8 attached.  This is the skip-decode follow-up I promised Yao, now
implemented and measured on bare metal.

Recap of the idea: a prefix leaf stores each data item's first key
column front-coded against a per-page prefix, and a scan decodes it
through _bt_getitem() on the way past.  Yao pointed out (citing the
SIGMOD 2024 front-coding paper) that the decode CPU is the read-side
cost, and that a scan which only needs the heap TID (a plain IndexScan,
a BitmapIndexScan, COUNT(*)) shouldn't have to pay it.  I agreed, with
one caveat: the tuple copy is already skipped for those scans, so the
cost that's actually left is the key *check*, and you can only skip that
where the scan keys are already known satisfied for the whole page.

What v8 does: _bt_readpage() now skips both the decode and the
_bt_checkkeys() call for a data item when all three hold:

   - the scan is not an index-only scan (so->currTuples == NULL), so we
     never materialize the tuple and need only its heap TID / posting
     list -- both of which the coding leaves in place on the page; and
   - every scan key is already proven satisfied for the whole page
     (_bt_set_startikey advanced startikey to the end of the keys); and
   - the scan has no array keys (array-key advancement reads the key
     regardless of startikey).

In that state _bt_checkkeys()'s comparison loop starts past the last key
and reads nothing from the tuple, so the item is a guaranteed match and
continuescan is unchanged.  We can take the TID straight from the
on-page tuple with no decode.  I skip the whole _bt_checkkeys() call,
not just the decode: in an assert build it re-runs _bt_check_compare
from the first key to verify the startikey optimization, which would
read the still-coded key.

Index-only scans still decode, because they have to return the key. This
speeds up the "walking a known-matching run without returning the tuple"
case, not all scans.

Bare metal this time (c7i.metal-24xl, Xeon 8488C, performance governor,
turbo off, pinned to one core, THP off), 3M distinct keys sharing a
67-byte prefix, prefix index fully cached so this isolates decode CPU.
A/B is the same source built twice, once with the skip-decode gate and
once with it forced off, best-of-15 over two independent runs:

    scan                       skip off      skip on       delta
    ------------------------   ----------    ----------    ------
    bitmap index scan + count    304 ms        260 ms      -14.6%
    index scan + heap fetch      302 ms        241 ms      -19.9%
    index-only scan + count      277 ms        282 ms      ~0 (gate off)

So it recovers most of the ~6-7% traversal cost I measured in the v5
read-side numbers, on exactly the scans that only want the TID, and the
index-only-scan path is unchanged within noise, the gate correctly never
fires there.

Yao's other two points (multi-column keys, and more than one prefix per
page for a leaf that straddles two groups) I still think are a separate,
larger piece of work.  I'd rather land the first-column single-prefix
case first.  No change to that position here.

best.

-greg

Re: nbtree: opt-in leaf key prefix compression

От:
Peter Geoghegan <pg@bowt.ie>
Дата:
Вложения:
On Mon, Oct 26, 2026 at 4:25 PM Greg Burd  wrote:
> This is a patch that adds leaf key prefix compression to nbtree, behind
> a new per-index storage parameter, prefix_compression, off by default.
> It's something I started a long time ago when primarily working on
> JSONB-like data storage/indexing/etc. in Postgres when a colleague
> pointed out that it didn't yet exist and his measurements showed that it
> should.  He wasn't wrong.  It's a solid win for performance and overhead
> IMO, but YMMV.

I also have a vibe-coded patch adding prefix compression to nbtree,
from back in April. I had completely forgotten about it until you
reminded me. I attach it here now.

In the spirit of the age, I also had Claude do a comparative review of
both of our patches. I also attach that here. I skimmed it a bit,
which helped me to remember bits and pieces about the prompt I used
back in April. Apparently my patch doesn't compose with deduplication,
while yours does. On the other hand, your patch cannot handle prefixes
unless the prefix column is of a varlena type. So there are cases
where one performs much better than the other, and vice-versa. That's
what I would have guessed.

> The patch is one commit against master.  I'd appreciate review of the
> approach and the code, and I'm happy to work through whatever it turns
> up.

We're now living in a world where the cost of producing a prototype
like this has plummeted. The community's culture hasn't figured out
how to deal with this yet. I personally don't have much of a clue what
to do about it, but I am sure that certain things need to be assessed
very differently now. Generating a patch that, in some technical and
superficial sense, converges on being a complete implementation of
some complicated optimization means very little now.

Posting a huge AI generated patch that nobody will read could still
make sense if there were doubts about the general efficacy of a
particular technique, as a kind of informal proof of its feasibility,
but I don't think that applies here. It's fairly obvious that prefix
compression can cut the storage overhead of indexes by 3x or more in
sympathetic cases, at the cost of CPU overhead for decompression, and
lots of complexity.

The best feedback I can offer is that I think you should have started
with a very high level discussion of the architectural trade-offs. You
said "indexes on keys that share a long leading prefix (URLs,
reverse-DNS names, a leading JSONB path, a tenant-id prefix) spend
most of their bytes storing that prefix over and over", which is
obviously true, but you neglected to mention why you felt that was the
use case to target. Do users actually use nbtree indexes for JSONB
paths? I have to admit that I didn't know that.

It seems likely that a design such as yours, which omits column-level
compression, will never incorporate it later on once committed. Why do
you think that's the best trade-off? I personally tend to doubt that
it is, but I've given it little thought so who knows?

More generally, can you paint a detailed picture of what motivated you
to work on this? I wouldn't expect that kind of background with an
optimization that was an unalloyed good, and required no changes to
the on-disk format. But for something like this, which would commit us
to supporting its compressed representation forever, a detailed
picture of how it affects users is completely essential. A really
solid understanding of the trade-offs and the entire design space is
hugely important.

There are complex trade-offs around whether and to what extent prefix
compression works by compressing things in terms of the index key
space versus on a more ad-hoc basis. As Modern B-Tree Techniques puts
it: "Code simplicity argues for truncating the same prefix from all
entries in a B-tree node. Moreover, one can apply prefix truncation
based on the actual keys currently held in a node or based on the
possible key range as defined by the separator keys in parent (and
possibly other ancestor) pages."

Where does this design fit under his taxonomy? It looks like you're
not relying on the compressed prefix to act like a low key. Why was
that? What's the trade-off around picking a base key from the tuples
present when the page is "written as a whole"? What happens if, later
on, more tuples are inserted that are within the page's key space but
not compressible using its base key? Obviously you just don't compress
those tuples, but why is that generally okay?

You placed a lot of emphasis on your WAL logging strategy, and how
prefix compression needs to work during recovery, but I don't think
that's the place to start. When it comes to lower-level details I'd be
much more concerned about guarantees that a legal page split will
always be available, even in extreme pathological cases. But that's
really a facet of the on-disk representation itself, and the design as
it relates to that.

BTW, what is src/backend/access/bark/barkutils.c?

--
Peter Geoghegan

Re: nbtree: opt-in leaf key prefix compression

От:
Greg Burd <greg@burd.me>
Дата:

On Tuesday, November 3rd, 2026 at 4:48 PM, Peter Geoghegan  wrote:

> On Mon, Oct 26, 2026 at 4:25 PM Greg Burd  wrote:
> > This is a patch that adds leaf key prefix compression to nbtree, behind
> > a new per-index storage parameter, prefix_compression, off by default.
> > It's something I started a long time ago when primarily working on
> > JSONB-like data storage/indexing/etc. in Postgres when a colleague
> > pointed out that it didn't yet exist and his measurements showed that it
> > should.  He wasn't wrong.  It's a solid win for performance and overhead
> > IMO, but YMMV.

Hey Peter,

> I also have a vibe-coded patch adding prefix compression to nbtree,
> from back in April. I had completely forgotten about it until you
> reminded me. I attach it here now.

Excellent, I think we've talked about this idea a few times in person. The
reason for my interest is related to my "HOT for Expression Indexes" patch
where I am trying to make it possible for JSONB updates in heap to be HOT.
Today that isn't possible because all indexes on JSONB are expressions and
expression indexes spoil HOT.

At that time I noted that it is very common with JSONB data to index using
nbtree far too many fields in a JSONB document.  This is an especially easy
trap for people coming from a MongoDB background, which has been a trend
since JSONB was introduced (and likely a big part of the justification for
that type).

These JSONB paths are highly prefix-compressible and I don't imagine that
JSONB will be removed from core anytime soon, so I thought I'd take a
shot at improving that use case.

> In the spirit of the age, I also had Claude do a comparative review of
> both of our patches. I also attach that here. I skimmed it a bit,
> which helped me to remember bits and pieces about the prompt I used
> back in April. Apparently my patch doesn't compose with deduplication,
> while yours does. On the other hand, your patch cannot handle prefixes
> unless the prefix column is of a varlena type. So there are cases
> where one performs much better than the other, and vice-versa. That's
> what I would have guessed.

It is a new "age" and we're all adapting to it.  I've been doing software
development for 35 years now and this is, hands down, the biggest shift
I've seen for this profession.  Everyone will have to adjust to the new
norm once the dust settles, but we're not even at that stage yet.

Thanks for digging your patch out and dusting it off so that I could take
a look and run a comparison.  Two differences jump out.

Composing with deduplication was a hard requirement for my work with
Claude.

The varlena-first-column restriction was an efficiency choice early on
that got lost in the process and should have been dropped a while ago.

> > The patch is one commit against master.  I'd appreciate review of the
> > approach and the code, and I'm happy to work through whatever it turns
> > up.
> 
> We're now living in a world where the cost of producing a prototype
> like this has plummeted. The community's culture hasn't figured out
> how to deal with this yet. I personally don't have much of a clue what
> to do about it, but I am sure that certain things need to be assessed
> very differently now. Generating a patch that, in some technical and
> superficial sense, converges on being a complete implementation of
> some complicated optimization means very little now.

Absolutely true, Claude can prototype just about anything quickly and
sometimes quite well.  Feed it a problem, answer some questions and
wait while it burns a hole in your wallet.

I too am confused, but in this case a valuable feature (key-prefix
compression) can be worked out in a few weeks, not years, and deliver
a feature that many will benefit from.

But on this thread I think I let the LLM do the talking about the patch
instead of presenting this idea/work to the hacker community on its
merits.

I own that, it was the wrong order and your mail is a reasonable
reaction to it.  But let's not lose sight of the fact that this idea
provides value to users of nbtree, I hope that you agree on that point.

While I'm owning things... you asked what src/backend/access/bark/
barkutils.c is.  It's nothing that should be in this patch.  BARK is a
separate index AM I've been working on out of tree; this code started
as a port of its leaf prefix coding, and two stale comments pointing
back at that file rode along.  They reference a file that doesn't exist
in the tree, which is just confusing.  Apologies.

> Posting a huge AI generated patch that nobody will read could still
> make sense if there were doubts about the general efficacy of a
> particular technique, as a kind of informal proof of its feasibility,
> but I don't think that applies here.

You're right that the vibe-coded prototype patch shouldn't have led the
thread.  Focusing on technical merit rather than process, the efficacy
here isn't in doubt.  So the question isn't whether prefix compression
earns its place, it's whether this design is the right shape for it.

That's the conversation I want, along with code to demonstrate, test,
and evolve the idea into something we feel can be committed.

> It's fairly obvious that prefix
> compression can cut the storage overhead of indexes by 3x or more in
> sympathetic cases, at the cost of CPU overhead for decompression, and
> lots of complexity.

Yes, agreed.  It's an obvious improvement that, like all things, has
trade-offs one of which is additional code complexity.  But how is this
any different from other optimizations?

> The best feedback I can offer is that I think you should have started
> with a very high level discussion of the architectural trade-offs.

Fair point, can we rewind time a bit and do that now?

> You said "indexes on keys that share a long leading prefix (URLs,
> reverse-DNS names, a leading JSONB path, a tenant-id prefix) spend
> most of their bytes storing that prefix over and over", which is
> obviously true, but you neglected to mention why you felt that was the
> use case to target. Do users actually use nbtree indexes for JSONB
> paths? I have to admit that I didn't know that.

HEAVILY, they use nbtree nearly exclusively and you have to understand
that many are coming (as I said before) from MongoDB to Postgres where
it was standard operating procedure to have 10s, even 100s of indexed
fields within a particular document shape.  Worse yet, sometimes when
mapping MongoDB-shaped use onto Postgres (as the open source documentdb
project does) there is a need for additional indexes beyond what the
user specified to enable a similar experience.

But you're right, I should have led with the problem.  Talked over the
trade-offs and goals.  Then prototype a solution.  I skipped some steps.

Another use case is plain text/bytea keys with a long shared prefixes
such as URLs, reverse-DNS names, file paths, tenant-prefixed natural
keys, and the like.

Those are ordinary btree indexes today and the redundancy is obvious.
Most/all of these cases can easily be tested and I'll bet that the floor
for the compression is about 3x if we measured.

JSONB specifically, what I had in mind is a btree on an expression that
pulls a text path out of a document (btree on (doc->>'...'), or on a
materialized path column), not a GIN index.

> It seems likely that a design such as yours, which omits column-level
> compression, will never incorporate it later on once committed. Why do
> you think that's the best trade-off? I personally tend to doubt that
> it is, but I've given it little thought so who knows?

Column-level compression is a great technique, and I'd like to see that
happen too.  The time line for that is much longer primarily due to the
many ways that table/index/executor all implicitly agree on one shape
and one behavior defined by heap.  If we can more cleanly separate and
define the boundaries between those three then we could potentially see
that in core at some point, but I'll bet that takes a few years to sort
out.  In the mean time, let's compress some key prefixes and save some
bytes.

I think these two are not in competition, they are orthogonal and both
is the answer but the easier of the two in today's code base is the
prefix compression.

> More generally, can you paint a detailed picture of what motivated you
> to work on this? I wouldn't expect that kind of background with an
> optimization that was an unalloyed good, and required no changes to
> the on-disk format. But for something like this, which would commit us
> to supporting its compressed representation forever, a detailed
> picture of how it affects users is completely essential. A really
> solid understanding of the trade-offs and the entire design space is
> hugely important.
> 
> There are complex trade-offs around whether and to what extent prefix
> compression works by compressing things in terms of the index key
> space versus on a more ad-hoc basis. As Modern B-Tree Techniques puts
> it: "Code simplicity argues for truncating the same prefix from all
> entries in a B-tree node. Moreover, one can apply prefix truncation
> based on the actual keys currently held in a node or based on the
> possible key range as defined by the separator keys in parent (and
> possibly other ancestor) pages."
> 
> Where does this design fit under his taxonomy? It looks like you're
> not relying on the compressed prefix to act like a low key. Why was
> that?

You've read it correctly this is the "actual keys currently held in
the node" variant, not the "key range from separator keys" one.  The
per-page PREFIX item is the longest common byte prefix of the data
items that were on the page when it was written as a whole.  It is not
derived from, and does not act as, a low key, and the parent/separator
keys are untouched.

Why that side of the taxonomy?  The separator-key variant is the more
principled one IMO, it ties the compressible prefix to the page's key
space, so it's stable under inserts and composes with suffix truncation
but it's also the more invasive one.  It wants the prefix to be a real
boundary key, which means the split and the downlink and _bt_compare
all have to understand it, and that's a much deeper change to nbtree
code than a per-page item that only the leaf read/write path knows
about.

The "actual keys held" variant buys most of the space win for a change
that stays inside the leaf.  That was the trade I made that should have
been presented and discussed first is what I'm hearing from you.  It's
the one worth arguing about.  I made this decision for containment, not
because the separator-key variant is wrong.

> What's the trade-off around picking a base key from the tuples
> present when the page is "written as a whole"? What happens if, later
> on, more tuples are inserted that are within the page's key space but
> not compressible using its base key? Obviously you just don't compress
> those tuples, but why is that generally okay?

You've got the right idea, a later insert whose first column doesn't
share the page's prefix is stored uncoded, in place, next to coded
neighbors (the coded length byte distinguishes them per tuple, so a page
is a mix). No decode-time ambiguity, no rewrite on insert.

Why is this generally okay?  Good question, and there are places where
it might not be.

In my estimation, it is okay (read: the right choice) because the base
key is the common prefix of a sorted run, and btree order means the
tuples that share it are contiguous, so an insert landing in the page's
key space usually *does* share the prefix and so the page stays mostly
coded.

The case where it degrades is a page straddling a prefix boundary.  The
http://example.com / http://sample.org example from Yao's branch of the
thread is a case where the base key collapses to the short common run and
the page compresses poorly.  That's a genuine limitation of one prefix
per page.  It's the same root cause as the multiple-prefixes-per-page
idea, I'm open to a format that could carry more than one base key per
page.  This design trade-off was a simplification, not a requirement.

For now the answer is that the page is recompressed to the better base
the next time it's written as a whole (a split or a dedup pass), so a
straddling page is transient rather than permanent, and in the worst
case it's simply a plain page, never worse than today.

> You placed a lot of emphasis on your WAL logging strategy, and how
> prefix compression needs to work during recovery, but I don't think
> that's the place to start. When it comes to lower-level details I'd be
> much more concerned about guarantees that a legal page split will
> always be available, even in extreme pathological cases. But that's
> really a facet of the on-disk representation itself, and the design as
> it relates to that.

Agreed that split-availability is the real low-level question and WAL is
downstream of it.  I'm pleased with the guarantee the representation
gives, I think it's one of the strongest parts of the design.  I should
have presented this earlier on the thread rather than burying it under
the WAL text, another example of your point which is that a healthy
thread on a feature such as this starts with design discussion, not a
functional vibe-coded patch prototype.  So here's that idea written up
for discussion:

A prefix page never holds more logical data than a plain page would: a
coded tuple is never larger than the plain one (coding only kicks in
when at least BTREE_PREFIX_MIN_SHARED bytes are shared, and it replaces
those with a single code byte), and any tuple can always be stored
uncoded.  So any split point that is legal for a plain page is legal for
a prefix page, and the split chooser's existing leftfree/rightfree
feasibility still holds.  The one thing coding changes is that a prefix
page can hold *more* tuples than a plain page, which is why the split
accounting is in coded bytes but that only ever makes more split points
feasible, never fewer.

The degenerate guard you can see in _bt_recsplitloc() exists for exactly
one coded-size artifact (a point that leaves the left page with zero
data items, which plain-size accounting rejects on its own), and the
forced-full-page-image fallback is the belt-and-suspenders for the one
case redo can't rebuild from logged plain items.  There is no page a
prefix index can reach that a plain split can't resolve, because
"store it uncoded" is always available as the floor.

If that guarantee has a hole in it, that's the thing I most want found,
so please push on it.

The short version, I'll re-send with the architecture-first framing, the
string-key motivation instead of the JSONB lead, the bark comments gone,
and the split-availability argument up front where it belongs.

> BTW, what is src/backend/access/bark/barkutils.c?

As stated earlier, the first iteration of this key prefix compression was
in the context of a separate vibe-coded exploration I'm doing.  BARK is
the best name I could come up with that had B and "tree" combined into a
short word (CREATE INDEX using BARK).  I'll do the clean up, sorry for
the confusion.

> --
> Peter Geoghegan

best.

-greg


Re: nbtree: opt-in leaf key prefix compression

От:
Greg Burd <greg@burd.me>
Дата:
On Wed, 04 Nov 2026 14:31:45 +0000, Greg Burd  wrote:
> 
> On Tuesday, November 3rd, 2026 at 4:48 PM, Peter Geoghegan  wrote:
> 
> > It seems likely that a design such as yours, which omits column-level
> > compression, will never incorporate it later on once committed. Why do
> > you think that's the best trade-off? I personally tend to doubt that
> > it is, but I've given it little thought so who knows?
> 
> Column-level compression is a great technique, and I'd like to see that
> happen too.  The time line for that is much longer primarily due to the
> many ways that table/index/executor all implicitly agree on one shape
> and one behavior defined by heap.  If we can more cleanly separate and
> define the boundaries between those three then we could potentially see
> that in core at some point, but I'll bet that takes a few years to sort
> out.  In the mean time, let's compress some key prefixes and save some
> bytes.
> 
> I think these two are not in competition, they are orthogonal and both
> is the answer but the easier of the two in today's code base is the
> prefix compression.

Quick follow-up...

I may have misunderstood "column-level" to mean "columnar" and if that's
the case I apologize.  I think you are talking more about key prefix
compression across multiple columns that together form the btree key,
and if that's the case then yes I agree that's something required of a
solution.  I'd been side-stepping this just for simplicity sake but I'll
think about it a bit and see if I can bring that into the design.

best.

-greg



Re: nbtree: opt-in leaf key prefix compression

От:
Greg Burd <greg@burd.me>
Дата:
On Fri, 30 Oct 2026 19:52:00 +0800, Yao Feng  wrote:
> Hi Greg,

Hey Yao, I wanted to follow-up again on a suggestion you made.

> Thanks for working on this, took a look at the v4 patch.
> 
>  I think this is very worthwhile work. FWIW, a recent SIGMOD paper on
> B-tree compression (https://dl.acm.org/doi/10.1145/3654972) noted that
> while front-coding saves a lot of space for strings, decompression CPU cost
> tends to be the main bottleneck for queries on modern hardware. Looking at
> the v4 benchmarks, they mostly cover index size and write throughput -- did
> you have a chance to measure read-side performance (e.g. index scans, point
> lookups)?
> 
> A few quick questions from having played with something similar a while
> back:
> 
> 1. Skipping decompression when index tuples aren't returned:
> Right now _bt_readpage() eagerly calls _bt_getitem() to decode every leaf
> tuple. That's necessary when the scan actually needs to return the index
> tuple (like IndexOnlyScan), but for operations that don't return tuples and
> only care about the heap TID -- such as a plain IndexScan, BitmapIndexScan,
> or COUNT(*) -- could we skip decompression?
>
> 2. Multi-column indexes:
> The patch requires column 0 to be a varlena. I'm curious if you considered
> supporting subsequent columns (e.g. for something like `(tenant_id int, url
> text)`), or if keeping it strictly to the first column was just a natural
> place to draw the line on complexity for now?

This is a good idea and if I dismissed it earlier I apologize.  But it
will be tricky to do.  Each column used to form a key may need a
different key prefix, or maybe more than one can share a key prefix on a
page.

I'll have to think about this and do some research to find out how this
has been approached by other databases in the past.

> 3. Prefix boundaries within a page:
> With one prefix per page, if a page spans two different domains (say, a
> bunch of `http://example.com/1` , `.../2` followed by
> `http://sample.org/1` , `.../2`), the second group
> only shares "http://". Just curious if you've considered this kind of case?

I have not, in that case you'd ideally like multiple prefixes for the
same column.  Then you have a different set of issues to manage, which
prefix belongs to a tuple?  I'll have to dig on this one too.

> Curious to hear your thoughts.
> 
> -- 
> Yao Feng

thanks for the ideas,

-greg




Re: nbtree: opt-in leaf key prefix compression

От:
Greg Burd <greg@burd.me>
Дата:
Вложения:
Hello,

This is the design write-up I promised, with a vibe-coded working
prototype of it I used to test some ideas as v9. It is offered as a
proof of concept for the design below something concrete to discuss no
as something to commit.  It replaces the single-column, varlena-only
patch (v1-v8) completely.

I'd like agreement on the design and trade-offs before anyone spends
time reviewing the code line by line.

The earlier proposal (v8) had a design that closed off the multi-column
case (the "column-level" compression he asked about).  The most
contentious bit of this will be the on-disk format change which we'll
all have to live with for a while.


The design takes into account:

  - Bayer/Unterauer "Prefix B-trees" and Graefe's "Modern B-Tree
    Techniques": entries in a node share a common leading prefix of the
    key, stored once.  Graefe separates a prefix taken from the keys
    actually in the node from one derived from the node's key range
    (the separator keys above it).

  - Oracle: COMPRESS n factors out n whole leading columns, with a
    per-block table of distinct prefixes that rows point into, so a
    block can hold several prefixes.  Advanced Index Compression picks
    the scheme per block and adds partial-column prefixes.

  - SQL Server page compression: a per-page anchor value per column;
    each cell stores how many leading bytes of the anchor it reuses,
    plus its own bytes.  A dictionary step then dedups whole values.

From that research, "complete" for this feature means:
   - a prefix can cover one or more whole leading columns,
   - a prefix can end partway through a column,
   - a page can hold more than one prefix,
   - prefixes are chosen per page, not fixed at CREATE INDEX, and
   - nothing depends on the column's data type.

My earlier patches (v8 and earlier) did one prefix over part of the
first column.  This v9 design attempts to be "complete."

Where does this sits in Graefe's taxonomy, and the equality rule?

It compresses against the keys actually on the page, chosen each time
the page is written as a whole.  The prefix doesn't act as a low key;
separators and internal pages are untouched.  That keeps the feature
inside the leaf read and write paths, which is why it can be a per-page
opt-in with no BTREE_VERSION change.

This is because, as in other places, bytes are shared only when they are
identical as stored, *never* on the strength of opclass equality. As
I've learned working on the Tepid and Hot for Expressions patches an
index-only scan (IoS) returns the bytes the index stored, so a value can
only be rebuilt from another tuple's copy if the two were identical to
begin with.  Equal-but-different encodings (numeric 1.0 and 1.00,
nondeterministic collations, plenty of user-defined types) must not be
merged.

If that holds true, then two things follow:

  - It's correct for every type, including user-defined ones, with no
    equalimage requirement.  Deduplication needs equalimage because it
    merges tuples the comparator calls equal and keeps one copy; this
    never merges anything.  Search stays correct because identical
    bytes always compare equal.

  - It needs no new opclass support function.

Which makes it both correct and slightly less complicated.

I'd planned to compare column by column (shared whole columns plus a
byte count into the next one).  The prototype takes the longest common
prefix of the two tuples' data areas instead.  That covers whole leading
columns, part of the first differing column, and NULL bitmaps that
happen to match, and it needs no tuple descriptor at all.  That turned
out to matter a lot for WAL (section 6).

This spoils some types.  Sharing is by stored bytes, and integers and
timestamps are stored in native byte order, which is little-endian on
the machines most people run.  Two bigints or timestamps that differ
only in their low-order part differ in the *first* byte stored, so
nothing after them is shared.

So, an index on (bigint, timestamptz, text) gains almost nothing.  The
same values as text compress by 45%.  Leading integer columns that are
*equal* (the low-cardinality tenant_id case) are shared in full.  Doing
better for fixed-width types needs either an order-preserving byte
encoding of the key (Graefe's normalized keys, below) or type-aware
coding, which would give up the catalog-free property.

I've not expored normalized keys as yet, but I could if that's of
interest.  What to do about this is an open question, let me know your
thoughts.


On-disk format

A leaf of an index with prefix_compression on may carry a new page flag,
BTP_PREFIX (bit 9 of btpo_flags).  BTREE_VERSION, the catalog and
BTPageOpaqueData don't change.  A page takes the format only when it's
next written as a whole, so old and new pages coexist, and pg_upgrade,
replicas and turning the option back off all keep working.

A BTP_PREFIX page has one extra item, a PREFIX DIRECTORY, at the offset
where the first data item would otherwise be.  The data items follow it
in key order.  P_FIRSTDATAKEY therefore depends only on the page flags,
binary search over the data items is untouched, and all the code that
locates the first data item stays as it is.

The prefix directory holds:

  - one or more GROUPS of consecutive data items, each with an ANCHOR:
    a copy of the key part of the group's first member.  A new group
    starts when an item shares no leading byte with the current anchor.
    Several groups per page let a page that straddles (tenant, region,
    url) boundaries compress each run, rather than collapsing to the
    short prefix the whole page has in common.

  - a cache of the decoded size of the page's items (their total and
    the largest), which the split-fit rule in section 5 needs on every
    insert.  Every change to the page keeps it exact, and we can use
    amcheck to enforce it.

A coded item is an ordinary IndexTupleData header followed by a 6-byte
code header (group, number of shared bytes, the original t_info), the
original null bitmap, and the bytes after the shared prefix.  Its t_tid
is its real heap TID.  A posting list stays uncoded, in the standard
posting-tuple layout, so everything that only reads heap TIDs (VACUUM,
LP_DEAD hinting, deletion, posting list splits) works on coded items
unchanged.  Pivot tuples are never coded.  Decoding copies the anchor's
shared bytes back in front of the residual, which gives the original
tuple byte for byte.

Two things differ from the two prototypes already in the thread.  Unlike
the follower design, a coded tuple doesn't use a t_tid status bit, so a
reader that forgets to decode gets a wrong key, never a wrong TID.  And
unlike my earlier patch, there's more than one prefix per page and it
isn't limited to the first column.

There are trade-offs to be sure, the code header plus alignment means
short keys don't gain.  A plain item is a 4-byte line pointer, an 8-byte
tuple header and the key rounded up to 8 bytes; a coded item adds the
6-byte code header. A 12-byte SSN or phone-number key takes 28 bytes
plain and 28 coded, however much it shares.

Pages that wouldn't save at least a sixteenth stay plain, so such
indexes aren't hurt, but they don't benefit either.  A narrower code
header alone doesn't fix this; the 8-byte alignment of every item does
most of the damage.  Coded items are only ever copied out, never read in
place, so they could be packed without alignment, but PageAddItem aligns
every item, so that means placing them by hand.  I'd like an opinion on
whether that's worth it, I'm leaning toward 'no'.


Reading

The proposal said the hot path would compare a search key against a
coded item without rebuilding it.  The v9 prototype rebuilds into a
fixed per-backend buffer instead (a few memcpy calls, with no palloc or
index_form_tuple).

I did try/profile the compare-without-rebuilding path.  It saves less
than it looks like it should because most of the cost of a comparison
in a binary search is the cache miss on the item, which a plain page
pays too.  So I'd like to keep the simple form unless measurements on
the wider set of key shapes force our hand.

Scans that need only heap TIDs (plain index scans, bitmap scans,
count(*)) don't decode at all once every scan key is already satisfied
for the page, which is the skip-decode change Yao suggested earlier in
the thread (great idea, thanks!).


The split-fit guarantee

Building out the prototype helped immensely on this one. A coded page
legitimately holds *more* than a plain page's worth of decoded data
(that's the point of it), so its decoded items can't always be laid out
on two plain pages, and splitting requires exactly that.

After much trial and error the rule the prototype enforces instead:

  A coded page keeps: T + H + 2M + heap TID <= 2 * U

where T is the decoded size of its items (with line pointers), M the
largest of them, H the high key and U the usable space on a page.  I
believe that under that bound a legal split point always exists.

Take the leftmost point whose right half fits a page.  The point before
it didn't fit, so the left items before it total less than T - (U - H).
Adding one more item and the new high key (a truncated copy of an item
plus a heap TID) gives a left half under T - U + H + 2M + heap TID,
which the bound keeps under U.

An insert splits the page before it would break that bound, which is
what the cached decoded size in the directory is for.  A split decodes
the page, picks the point by plain sizes (the stock _bt_findsplitloc
when the decoded items fit one page, otherwise a size-checked balanced
point), writes both halves plain, and then codes each one.  Any tuple
can always be stored uncoded, and a page that won't compress stays
plain, so AFAICT the floor is always "exactly as today".

There is one addition case to consider, when a large incoming tuple
(close to BTMaxItemSize) arriving at a page that is already dense.
There may be no point that places the new tuple too.  The prototype
handles it by splitting the existing items alone and retrying the insert
from the top, the same way an insert that has to wait on another
transaction already restarts, including redoing the uniqueness check.
I'd especially like this argument/idea checked by others.


WAL

Because coding needs only the page and the tuple (no tuple descriptor,
no relcache), redo can run the same routines the primary ran:

  - An insert logs the coded tuple; redo adds it and updates the
    directory's cached size.

  - A split record gains a flags byte saying whether the original page
    and each half were coded.  Redo decodes the original page, collects
    the left half's items exactly as _bt_split did, and lays them out
    with the same routine.  The right half arrives as its coded items,
    which _bt_restore_page places exactly as the primary did.

  - Deduplication and posting list splits on a coded page are replayed
    by repeating the primary's steps.

So no record on a coded page needs a full-page image.  My earlier v8
patch forced one on most splits of compressible pages, so this is a good
discovery.

The records are also smaller than plain ones, since items and right
halves travel coded.  The flags byte is a WAL format change, so it needs
an XLOG_PAGE_MAGIC bump.  I added a new recovery test that replays every
coded-page record type on a standby with wal_consistency_checking on,
and I checked that it fails when the split redo is deliberately broken.


Composition with deduplication

They stay composable, not mutually exclusive.  Deduplication collapses
tuples whose whole key is equal into one key plus a TID list.  Prefix
grouping factors out a leading run shared by distinct keys.  On one page
a posting tuple is coded like any other, with its TID list carried after
the residual.  Runtime deduplication and bottom-up deletion work on
decoded copies of a coded page's items.  Deduplication then re-codes the
result against the page's existing directory, so the page can only
shrink and nothing has to abort.


Performance numbers

Measured on a bare-metal c7i.metal-24xl (one Xeon 8488C socket, turbo
and deep C-states off, server pinned to 12 cores), release build, C
collation, 2 million rows per key shape, the same binary with the
option on and off.  4 reps with the arms interleaved; reads are 20
samples per arm; the figure is the change in the median.  An A/A run
(the binary against itself) stayed within 1% on everything but VACUUM
and the shortest range scans (3%).  Harness, data generator, raw CSV
and per-cell confidence intervals are attached.

  % change, on vs off       size build insert  WAL  warm  warm  cold  cold
                                                   point  IOS point  IOS
  URLs                       -35   +10   +10   -17     0   +13   -30    -6
  file paths                 -27    +8    +9   -12    -2    +5   -18    -8
  tenant-prefixed keys       -18    +9   +11    -7    +5   +17   -11    +4
  (tenant_id, region,        -33    +4    +9   -12     .   +12     .    -5
   status, name)
  JSONB (status, placed)     -24    +4    +8    -4     .    -1     .     0
  reverse-DNS names           -3   +10    +6    -4    +5    +8    +7    +3
  JSONB sku                   -2    +2    +6    -1     .     0     .     0
  JSONB (city, street)        -1     0    +3     0     .     0     .     0
  phone numbers (E.164)        0    +5     0    +2     0     0     0     0
  SSN-format ids               0   +10     0    +2    -1     0     0    -1
  JSONB email                  0    +5    +1     0     .     0     .     0
  (tenant_id, bigint, ts)      0    +4    +2    -1     .     0     .    -1
  (ts, tenant_id, text)        0   +20    +1    -1     .     0     .     0

"insert" is a 2M-row bulk insert into an indexed empty table; "warm
IoS" a full index-only scan (an ordered index scan for the JSONB
expression indexes); "point" 20,000 lookups; "." marks queries that
don't apply.  Single-row insert throughput was within 1% for every
shape, VACUUM 2-9% faster on the compressible ones, bitmap range scans
1-2% faster.

Take-aways:

  - The design does what it should where keys share real prefixes:
    18-35% smaller, less WAL, cold point lookups 11-30% faster.

  - It costs CPU: 6-11% on inserts and 4-10% on CREATE INDEX where it
    compresses, and 5-17% on warm index-only scans, which have to
    decode every tuple (about 9 ns each).  Cold full scans gain less
    than the size suggests, because gp3 reads sequential pages fast
    enough that decoding dominates; on tenant keys the scan is 4%
    slower even cold.

  - The short-key shapes you'd might expect to benefit (phone numbers,
    SSNs, emails, SKUs) don't.  Under ~20 bytes the code header and
    8-byte alignment eat the shared bytes. Those pages stay plain, so
    they lose nothing, but the build still pays to find that out (up to
    20% on CREATE INDEX) and that's something that might push us to
    consider an opt-in strategy or push us to find some clever way to
    avoid that 20% (maybe by avoiding trying compression on well known
    types or having a way to record columns that aren't compressing
    after trying a few, I don't know on this one).

  - Fixed-width integer and timestamp columns that differ don't share
    much, so those multi-column indexes are unchanged and here's another
    reason we may want to skip well known types.

I didn't benchmark working sets larger than memory or collations other
than C.  I don't see those as necessary, stop me if I'm wrong.


Open questions


  - Opt-in or automatic.  I've kept it an off-by-default reloption,
    since the format commits us forever and has a real insert cost.  It
    could become the default later without an on-disk change.

  - Fixed-width types.  Is an order-preserving key encoding (Graefe's
    normalized keys) the right long-term answer for integer and
    timestamp prefixes, or is the byte-level form enough for the
    workloads people actually have?

  - A separate anchor in the directory vs. making each group's first
    tuple its anchor.  I chose separate anchors so deleting a group's
    first tuple never forces a re-code (or the full-page image that
    would come with it).  The cost is one extra copy of a key per
    group.

  - Short keys.  Packing coded items unaligned would let phone numbers,
    SSNs and similar keys compress, at the price of placing items by
    hand rather than through PageAddItem.  Worth it?

  - The read cost.  Warm index-only scans pay 5-17% to decode.
    Decoding straight into the scan's tuple workspace would save one
    copy per tuple; beyond that, is a cost of this size acceptable for
    an opt-in feature, or does it need to be closer to zero?

  - The split-fit bound and the retry path in, thoughts?

Peter, Yao: the on-disk format, WAL change, and split-fit are sections
where I could use your detailed feedback.

best.

-greg

Re: nbtree: opt-in leaf key prefix compression

От:
Yao Feng <fengyao0087@gmail.com>
Дата:
Hello,

Thanks for v9, Greg.

I went through the patch and have a couple of thoughts on prefix selection and
the on-disk layout.

1. Prefix selection: greedy byte-level vs. specifying columns

In _bt_prefix_choose_groups(), a new group only starts when shared_len == 0
against the current anchor. On composite indexes where leading fixed-width
columns are low-cardinality and a later varlena column has long prefixes, this
greedy check can get stuck in a bad grouping.

For instance, take (tenant_id int4, status int2, order_url text) where 50 rows
on a page all share (1001, 1). If row 1 is 'http://api.site.com/login' (25
bytes) and rows 2..50 are 'https://shop.com/pay/0001..0049' (29 bytes):
- Row 2 shares the 6 leading integer bytes with row 1, then stops at the 1-byte
  varlena length header of order_url (since 25 != 29).
- Because shared_len == 6 > 0, row 2 joins group 0 instead of starting a new
  group.
- Rows 3..50 also share those 6 integer bytes with row 1, so the entire page
  gets locked to row 1's anchor.
- As a result, we miss the 22-byte prefix (1-byte varlena header plus
  'https://shop.com/pay/') that rows 2..50 actually share with one another.

On the other hand, fixing the column count like Oracle's COMPRESS N has its own
problems: it can bloat pages that cross key boundaries or have skewed data
(creating too many prefix tuples), and it cannot compress substrings inside a
single text column at all.

Both extremes have clear downsides. How should we think about the trade-off
between explicit column selection and a dynamic/greedy approach?

> Open questions
> ...
>   - Short keys.  Packing coded items unaligned would let phone numbers,
>     SSNs and similar keys compress, at the price of placing items by
>     hand rather than through PageAddItem.  Worth it?
> ...

2. On-disk layout and the 6-byte header overhead

As your benchmarks showed on (tenant_id, bigint, ts) and short keys, the 6-byte
BTPrefixCode combined with 8-byte MAXALIGN eats up the savings on small leading
columns (for example, on (int4, int8, ts), saving 8 bytes of int4 plus padding
leaves 16 residual bytes + 14B header = 30B, which MAXALIGN rounds right back
to 32B). Also, because retail inserts can't add new anchors to the directory,
an inserted key that shares 0 bytes with its neighbor ends up storing the full
key plus the 6-byte header.

For what it's worth, here is another page layout I tried earlier in bpcauto
that avoids per-tuple headers:

+-----------------------------------------------------------------------+
| PageHeaderData |
+-----------------------------------------------------------------------+
| ItemId(1) -> [High Key] |
| ItemId(2..K+1) -> [Prefix Zone pointers] |
| ItemId(K+2..N) -> [Suffix Zone pointers] |
+-----------------------------------------------------------------------+
| ... Free Space ... |
+-----------------------------------------------------------------------+
| High Key : IndexTuple { ... } |
| Prefix Tuples : IndexTuple { t_tid.ip_posid = suffix offset, prefix } |
| Suffix Tuples : IndexTuple { t_tid = genuine Heap TID, suffix attrs } |
+-----------------------------------------------------------------------+
| Special Space (BTPageOpaqueData) |
+-----------------------------------------------------------------------+

Instead of a directory item and per-tuple headers, the page is split into a
prefix zone and a suffix zone:
- Prefix tuples sit at the start of the page as normal IndexTuples holding only
  the prefix columns. Since they don't point to the heap, t_tid.ip_posid in
  the IndexTuple header stores the starting offset of the matching contiguous
  suffix range.
- Suffix tuples sit after them holding only the remaining columns, with their
  normal Heap TID in t_tid and no extra header bytes at all (just the standard
  8-byte IndexTupleData).

The downside is that the page needs a field (e.g. in BTPageOpaqueData) to
track the prefix count K so readers know where the suffix zone starts, which
changes the on-disk page structure, unlike your directory item approach.

Sharing this as another data point while weighing whether the 6-byte coded
header (or packing unaligned items) is the right trade-off here.

Curious to hear your thoughts.

Regards,
Yao

Re: nbtree: opt-in leaf key prefix compression

От:
Greg Burd <greg@burd.me>
Дата:
Вложения:
On Tuesday, November 10th, 2026 at 12:01 AM, Yao Feng  wrote:

> Hello,
> 
> Thanks for v9, Greg.

Hello Yao, you're welcome I appreciate your help on this thread.  I can
tell that you've given it a good deal of thought.

> I went through the patch and have a couple of thoughts on prefix
> selection and the on-disk layout.

Thanks, both of these are good catches.

> 1. Prefix selection: greedy byte-level vs. specifying columns
>
> In _bt_prefix_choose_groups(), a new group only starts when shared_len
> == 0 against the current anchor. On composite indexes where leading
> fixed-width columns are low-cardinality and a later varlena column has
> long prefixes, this greedy check can get stuck in a bad grouping.
>
> For instance, take (tenant_id int4, status int2, order_url text) [...]
> Because shared_len == 6 > 0, row 2 joins group 0 instead of starting a
> new group. [...] the entire page gets locked to row 1's anchor.

You're right.  An index on (tenant_id, status, url) where each page
starts with one odd short URL followed by a long run that shares a long
prefix among itself did not compress at all, because the whole run
stayed anchored to the odd first row's 6-byte prefix.

The rule is now that a new group also starts when a tuple shares
strictly more with its immediate predecessor than with the current
anchor, by at least one MAXALIGN quantum.  The predecessor is already
the better anchor for the run, so the run breaks off into its own group.
The rule looks only backwards, which keeps the CREATE INDEX size
estimate exact (it has to make the same grouping decisions one tuple at
a time as the real layout does, or the build misjudges when a page is
full).

On your shape it's the difference between no compression and about half
the size.  A single-tenant leaf (one odd URL + 150 shop URLs) goes from
1.00x to 0.50x; a mixed table (100 tenants, a few api URLs and many shop
URLs each) from 119 to 68 pages.  There's a regression test for it now
(btree_index.sql, "groups_compress").

> On the other hand, fixing the column count like Oracle's COMPRESS N has
> its own problems [...]  Both extremes have clear downsides. How should
> we think about the trade-off between explicit column selection and a
> dynamic/greedy approach?

I'd keep it dynamic.  A fixed column count has the two problems you name
(skewed data makes too many tiny prefixes, and it can't share inside a
column, which is most of the URL/JSONB win), and it needs the user to
know their data's shape up front.  The byte-level rule adapts per page
with no knob.  I'm a big fan of keeping the number of knobs low so there
are fewer foot-guns.

If a real workload later wants to force or cap the prefix, a
COMPRESS-N-style hint could be added as a reloption on top, but I'd
rather not add that.

> 2. On-disk layout and the 6-byte header overhead
>
> [...] the 6-byte BTPrefixCode combined with 8-byte MAXALIGN eats up the
> savings on small leading columns [...]  Also, because retail inserts
> can't add new anchors to the directory, an inserted key that shares 0
> bytes with its neighbor ends up storing the full key plus the 6-byte
> header.

Both true.  MAXALIGN is the bigger cost of the two: a coded item is
still a PageAddItem item, so even a 3-byte header wouldn't help a short
key that's already padded up to the next 8 bytes.  The header itself can
shrink (the group number is one byte on any realistic page, and I think
the original t_info can be derived rather than stored), but that only
pays off once items are packed without alignment, which is the open
question from my last mail.  Coded items are only ever copied out, never
read in place, so packing them is possible; it just means placing them
by hand instead of through PageAddItem.

The non-sharing retail insert is the honest wart.  Today such a tuple is
stored coded against its neighbor's group with shared=0, so it's the
full key plus the header: larger than plain.  It's transient (the next
whole-page write regroups the page), and the worthwhile check keeps a
page from going coded in the first place unless it saves overall, but on
an already-coded page a single odd insert does cost those few bytes.  An
insert could instead append a new anchor to the directory; redo can
repeat that deterministically, it's just more WAL and more code, so I've
left it for now.

> For what it's worth, here is another page layout I tried earlier in
> bpcauto that avoids per-tuple headers: [prefix zone / suffix zone, with
> prefix tuples' t_tid.ip_posid pointing at the suffix range]

I like that it drops the per-tuple header, and holding the prefixes as
ordinary IndexTuples is clean.  The reason I went the other way is the
maintenance cost of the zone offsets.

With a prefix zone addressed by line-pointer ranges, every retail insert
and every VACUUM that adds or removes a line pointer shifts the suffix
offsets, so the prefix tuples' stored ranges have to be rewritten, and
redo has to repeat that.

A per-tuple group number costs 2 bytes but survives line-pointer motion
untouched, which is what lets the coded page compose with deduplication,
bottom-up deletion and posting-list splits without any of them knowing
about prefixes.  It also needs the count K in BTPageOpaqueData as you
note, which is an on-disk change I was trying to avoid.

So it's a real trade: your layout is denser per page, mine is cheaper to
maintain in place.  For a feature whose main use is write-heavy
JSONB/URL indexes I leaned toward the maintenance side, but I don't
think either is obviously right, and it's worth having both sketched on
the thread.

v10 also fixes two things cfbot found in v9 (an unused helper that only
clang's -Werror flagged, and a recovery test that needed a replication
slot).  Same design otherwise.

best.

-greg

Re: nbtree: opt-in leaf key prefix compression

От:
Greg Burd <greg@burd.me>
Дата:
Вложения:
Hello,

v12 attached.  While reviewing the code I found two correctness fixes in
the split path, plus a small reentrancy cleanup.

I spotted that the split-fit accounting was off by the item alignment.
The directory caches the decoded size of a coded page's data items, and
the split-fit check uses that cache to decide when a coded page must
split before it can no longer be divided into two plain pages.  The
cache was summing the unaligned IndexTupleSize of each decoded item,
while the split itself and the CREATE INDEX fill estimate both reason in
MAXALIGN(IndexTupleSize).  So the cache could undercount by up to the
alignment (7 bytes) per item, which is bad but what is fatal is that it
could undercount enough items and the gate could admit an insert onto a
page whose true decoded content no longer fits two plain pages, and the
split would then fail to find a legal point.

Fixed, added an assert to keep me honest in the future (belt and
suspenders).

_bt_compare() and _bt_prefix_try_plain_page() each held their decode
scratch in a static buffer, and because I care about a multi-threaded
future where that could be a problem (hidden process-global state) I
changed that to stack local memory.

As an aside, not really related to this thread... we're going to need
tooling to find existing and prevent future use of this pattern if we're
ever going to transition to a thread-based server.

best.

-greg

Re: nbtree: opt-in leaf key prefix compression

От:
Greg Burd <greg@burd.me>
Дата:
Вложения:
Hello,

v13 attached, rebased onto 45047c51aab.

Further testing found that fitting on a page does not guarantee that an
encoded tuple or prefix directory fits its size field.  I added
admission checks for those limits, plus checks for final build leaves
whose last item is a posting list.  The new tests reproduce both cases
on 32KB builds.

I also found why some incrementally built indexes grew larger with
compression enabled.  The coded-page split picker balanced the halves
even on rightmost pages, ignoring fillfactor.  Some pages that could
be decoded onto one page also unnecessarily bypassed the ordinary
split picker.  The patch now uses that picker when decoding fits and
honors rightmost fillfactor among legal split candidates otherwise.

For the fixed-width path workload, that reduced the 100,000-row index
from 8,118,272 to 5,414,912 bytes; compression off used 5,562,368 bytes.
The attached notes give the other results and reproduction details.
These are size observations, not timing results.  Variable-length
headers still limit sharing, and the change does not shrink every
workload or fillfactor setting.

Other changes since v12:

0001: Validate coded metadata before decoding, including raw pageinspect
input, and add corruption tests.  Copy amcheck's saved heap TID so the
next decode cannot overwrite a duplicate-key diagnostic.  Extend unique
index, NULL, representation-preservation, and standby coverage.

This remains a prototype, but a highly functional one.  The fixes do not
settle the format choice or establish that scan CPU costs and
default-off overhead are acceptable.

best.

-greg

Re: nbtree: opt-in leaf key prefix compression

От:
Greg Burd <greg@burd.me>
Дата:
Вложения:
Hello,

Prefix compression has been proposed for PostgreSQL's B-tree (nbtree)
indexes, on and off, since 2002. None of the attempts I found was posted
as a complete patch except duplicate-key work, which shipped as
"deduplication". Each one left a constraint this design follows. The
largest open question is the permanent on-disk format, and nobody on the
thread has agreed to one yet.

Key design decisions

Share identical stored bytes, not equal values. A key is rebuilt exactly
as it was stored, so index-only scans return the original value. Two
values that compare equal but are stored differently, like numeric 1.0
and 1.00, are never merged.  This avoid a lot of issues with UDTs,
comparisons, and also lets crash recovery rebuild compressed pages
without using the catalog or logging a full copy of each page.

The shared part is the longest common run of bytes. It can span several
whole leading columns and stop partway into the next one. That makes
multi-column keys, and keys that differ partway into a column, work
without the code knowing where columns start.

Per-page directory with several groups. A compressed leaf page carries
one directory item right after its high key. The directory holds several
anchors, one per group of neighbouring keys. Each compressed entry
stores a 6-byte header naming its group and how many bytes it shares,
then its remaining bytes. Because nothing else in the page layout moves,
the page header, the special area and BTREE_VERSION all stay unchanged.
Binary search over the page works as before.

The rest of nbtree barely changes.
 - TIDs and posting lists stay where they were. Each entry keeps its
   real row pointer (heap TID) and any posting list in the usual place.
   VACUUM, dead-tuple marking, deletion and posting-list splits work on
   compressed entries unchanged.
 - Internal pages are untouched. Separator keys on upper pages are never
   compressed, so the existing suffix truncation keeps working.

Anchors come from the keys actually on the page. In Graefe's taxonomy,
which Peter asked about, this compresses against the keys present when
the page is written, not against the key range set by the parent page.
The shared prefix is not used as a low key.

When pages get compressed.
 - Whole-page writes compress. A page is compressed when it's written as
   a whole: by CREATE INDEX, as either half of a split, or by a
   deduplication pass.
 - Single-row inserts don't. An insert compresses the new row against
   its neighbour's group, but it can't add a new anchor.
 - Deduplication composes. Deduplication runs on decoded copies of the
   entries and then re-compresses them.

A legal page split must always exist. Peter named this as his main
low-level worry. A compressed page can hold more than one page's worth
of decoded data, yet it must always be possible to split it into two
uncompressed pages. The directory caches the decoded size of the page,
and inserts are refused or split before that guarantee could fail.
 - If a huge incoming row leaves no legal split point, the existing
   entries are split first and the insert is retried.
 - Admission also checks the hard 8191-byte (INDEX_SIZE_MASK) limit on
   any single stored entry.

Split placement. When the decoded data fits on one page, the normal
split chooser runs unchanged. Otherwise a split on the rightmost page
honors fillfactor.

Crash recovery and pg_upgrade.
 - No full-page images. Recovery replays page splits, deduplication and
   posting-list inserts on compressed pages by repeating the primary's
   steps, without logging full-page images.
 - One WAL format change. The split record (xl_btree_split) gains a
   flags field, which needs an XLOG_PAGE_MAGIC bump at commit time.
 - Old and new pages coexist. Pages convert lazily ("fault forward"), so
   ALTER INDEX rewrites nothing and pg_upgrade needs no REINDEX.
 - Not readable by older servers. A server version without this patch
   can't read compressed pages.

One access path for readers. All readers decode through _bt_getitem(). A
scan that needs only row pointers skips decoding when every scan
condition is already known to hold for the whole page. amcheck and
pageinspect validate the page structure before decoding it.

Learning from the past...

The history of this idea goes way back to 2002 with Denis Perchine who
considered a Firebird-style prefix compression where each key drops the
bytes it shares with the previous one.  I'll attach a list of prior art
I found using my site (pg.ddx.io/mcp) and an LLM.  But we've learned
that:

 - Datatype neutrality is required. That pushed us to share exact bytes.
 - Accounting must use decoded sizes. That's the split guarantee.
 - Changes stay local to nbtree. No general page API churn, and WAL
   replay must be complete.
 - Compose with deduplication rather than compete with it.

 Open design decisions

1. The permanent on-disk format. Whatever is committed must be supported
forever. There are four candidates:
     - our directory item with a 6-byte header per entry;
     - Yao's prefix and suffix zones, which drop the per-entry header
       but need a page-header field;
     - Peter's whole-column anchor and follower layout;
     - unaligned packing.

    Yao showed the header plus 8-byte alignment eats the savings on
    short keys: an (int4, int8, ts) key rounds back to 32 bytes.

 2. Byte-level versus column-aware sharing. Raw-byte matching stops at a
 varlena length header. URLs of different lengths therefore share almost
 nothing beyond the leading columns, and keys whose lengths alternate
 don't compress at all. A fix would be either to skip the length header
 or to make the code column-aware. Either changes the format.

3. Grouping policy. Yao's (tenant, status, url) example misses a 22-byte
shared prefix because the page locks onto a poor first anchor. Our
backward-looking rule helps, but no rule has been agreed. A fixed column
count, like Oracle's COMPRESS N, has its own failure cases.

 4. Actual keys versus key range. Peter asked why it's acceptable that
 later inserts which don't fit the page's anchors stay uncompressed
 until the page is next rewritten.

5. CPU cost. There are no current, rigorous measurements on bare metal
of decode cost for scans and index-only scans, or of overhead when the
option is off.

6. Target workloads and user impact. Peter asked for this picture, and
it is still thin. The size results so far are synthetic.

7. Fillfactor and ordering edge cases. At fillfactor 10, honoring
fillfactor makes some indexes larger. Shuffled insertion made one index
a page bigger. That may be acceptable, but it's undecided.

8. Fit with future nbtree work, such as comparison skipping and key
normalization.

v14 attached, rebased onto 19db7e5b36e.  To appease the cf-bot and fix a
few things:

_bt_compare() declared the BLCKSZ decode buffer in its own frame, so
every call reserved an extra page of stack, including on indexes that
never use prefix_compression.  The decoding path now lives in a
separate out-of-line function, and the plain path has the same frame
as master again.

Splitting a coded leaf whose decoded items exceed a page leaked the
decoded copy of every item on the page.  They are now freed after the
split, leaving the caller's replacement posting list alone.

A backward scan with array keys decoded the page's first data item
twice into different buffers.  _bt_advance_array_keys() recognizes
finaltup by pointer, so that test could never succeed on a coded page.
The scan now reuses finaltup's decoded copy, as a plain page does.

The size-limit and split TAP tests lived in src/test/modules/nbtree,
which only runs with injection points enabled, although neither test
uses them.  They are now contrib/amcheck/t/008_prefix_limits.pl and
t/009_prefix_split.pl, and decide whether to skip before starting a
server.  The regression tests now show the plans for the index-only
digests and their heap comparison, so a plan change cannot turn them
into a heap-against-heap check.

best.

-greg
FAQ