| From: | Greg Burd <greg(at)burd(dot)me> |
|---|---|
| To: | Yao Feng <fengyao0087(at)gmail(dot)com> |
| Cc: | pgsql-hackers(at)lists(dot)postgresql(dot)org, Peter Geoghegan <pg(at)bowt(dot)ie> |
| Subject: | Re: nbtree: opt-in leaf key prefix compression |
| Date: | 2026-11-23 18:56:46 |
| Message-ID: | 179544087220.3296182.8223050100658393568@burd.me |
| Views: | Whole Thread | Raw Message | Download mbox | Resend email |
| Thread: | |
| Lists: | pgsql-hackers |
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
| Attachment | Content-Type | Size |
|---|---|---|
| v14-0001-nbtree-add-opt-in-leaf-key-prefix-compression.patch | application/octet-stream | 227.8 KB |
| From | Date | Subject | |
|---|---|---|---|
| Next Message | Zsolt Parragi | 2026-11-23 19:12:05 | Re: Preserve statistics targets with ALTER TABLE ALTER COLUMN TYPE |
| Previous Message | Robert Haas | 2026-11-23 18:49:27 | Re: log_postmaster_stats |