Re: ZSTD TOAST compression, and an extensible compression method encoding

Started by Manuabout 1 month ago37 messageshackers
Jump to latest
#1Manu
manuelreyesbravo@gmail.com

Hi Greg,

Thanks for re-running it on your own hosts and folding the reset into 0003 --
much appreciated, and good that the slice/prefix and memory numbers line up.

I didn't reproduce the silent wrong-data case you saw, only the false error

The silent one needs a prefix that stops the stream mid-frame rather than a
corrupt value read to the end. Attached is what I used (rename back to .sh/.py;
run as BIN=/path/to/install/bin bash repro-dctx-reset.sh). In one backend,
without the ZSTD_DCtx_reset(): read a prefix of a value that ends before its
frame does (check B1), then take a slice of a different value (B2) -- that
slice comes back with wrong bytes and no error, while full reads stay correct
because ZSTD_decompressDCtx() starts a fresh frame. My setup reaches the
mid-frame stop with a 1 MB value whose third block header is corrupted
(corrupt_block.py): the prefix before the bad block decodes fine and leaves
the reused context mid-frame, and the next value's streaming slice then reads
stale state. With the reset in place B2, and all 221 values (md5-checked), are
right. Same root cause as the false error you saw; the reset closes both, and
the silent variant is the one I'd least want a connection pool to hit.

Thanks also for adding me to 0003. One small thing: the authorship trailer did
not make it into the posted v8-0003 commit message -- for the record, my name
there is Manuel Reyes Bravo <manuelreyesbravo@gmail.com>.

Regards,
Manu

Attachments:

repro-dctx-reset.sh.txttext/plainDownload
corrupt_block.py.txttext/plainDownload
#2Greg Burd
greg@burd.me
In reply to: Manu (#1)

Hi Manu,

The patches I attached as v8 came from the wrong branch, I was rushing
and I shouldn't have been. They were v7 plus the earlier 0004, so they
had neither your context reuse, nor the comments, nor your name. Sorry
for the noise. v9, attached, is what my last email described. Thanks for
the repro. I ran repro-dctx-reset.sh unchanged against v9 and against v9
with the ZSTD_DCtx_reset() call removed:

- v9: all checks true, B2 included, the three expected "compressed zstd
data is corrupt" errors and no others: "RESULT pass".
- Without the reset: B2 ("slice of another value after an early stop")
comes back false with no error, while the full reads A2, A3 and B3
stay true. The slices that should have succeeded after an error fail
instead, which is the false error I saw before.

So both cases reproduce here, and the reset fixes both.

I've added Dharin, Peter and Robert, because this series overlaps with
Dharin's "Add zstd compression for TOAST using extended header format"
thread [1]/messages/by-id/CAOj6k6dy2CRVA6Lsb5N59zE-7KNVKt=oYwWyg8ULK8zOOY8e7A@mail.gmail.com from December, which nobody here had referred to yet. That
thread is where several pieces of this one came from:

- Dharin proposed a decoded in-memory form of an external TOAST pointer
[2]: /messages/by-id/CAOj6k6dEVi0NvLjMLDhyrJS_n_NZO5D_OU89AO1u53u6NCDDwQ@mail.gmail.com
toast_external_info_get() and toast_external_data on master
(6e58d6356fc). 0001 extends it with compress_method, so v9-0001 now
carries Suggested-by: Dharin Shah (or maybe just Co-authored-by?)

- Michael's preference there was one new vartag_external per method,
keeping the TOAST pointer at its plain size [4]/messages/by-id/aUOgmypuun0rc2xO@paquier.xyz, and Dharin's second
version did that with an external-only VARTAG_ONDISK_ZSTD [5]/messages/by-id/CAOj6k6f2B3hNxDcnB5AgHX4kaTW8XTAfMAjRx4upDBOugxqF4w@mail.gmail.com. v7
went the other way: one pair of long-form tags plus a method byte.
The 0002 commit message now says why. An inline compressed datum has
no vartag, so a tag per method can't give inline values a third
method. And vartag_external is a uint8 shared with the in-memory
pointer kinds, so it shouldn't take one tag per method. The cost is
one byte, in the pointer or the inline header, for methods other than
pglz and lz4. Michael said upthread that this cost doesn't bother
him [6]/messages/by-id/arS_NVVZZ2XsfCYU@paquier.xyz; I'm raising it here so the earlier preference isn't
overlooked.

- Peter asked for numbers [7]/messages/by-id/4c70b0f6-5aba-464c-b145-464a620c1222@eisentraut.org. For compression ratio, Dharin measured
170MB of mixed data at 22MB with zstd against 36MB with pglz or lz4
[5]: /messages/by-id/CAOj6k6f2B3hNxDcnB5AgHX4kaTW8XTAfMAjRx4upDBOugxqF4w@mail.gmail.com
zstd against 259MB pglz and 297MB lz4, or 114MB with a dictionary
[8]: /messages/by-id/CAFAfj_GACKVftwuRjy3Ls-1Xc3ojUUbVh=Rm7KpRuYbaS=uLPg@mail.gmail.com
this thread. None of these is an end-to-end benchmark, and the
pgbench run you mentioned would be the first. If I have time I'll
give it a try.

v9 is rebased on current master (0f3b42ce806):

0001 Decode the compression method in toast_external_info_get()
0002 Allow more than four TOAST compression methods
0003 Add zstd as a TOAST compression method (with context reuse)
0004 Add zstd compression dictionaries with a column-local lifecycle

Training is an explicit call for now; doing it from ANALYZE's sample is
the obvious next step once the lifecycle is agreed on. Well, that and
doing some benchmarking.

best.

-greg

[1]: /messages/by-id/CAOj6k6dy2CRVA6Lsb5N59zE-7KNVKt=oYwWyg8ULK8zOOY8e7A@mail.gmail.com
[2]: /messages/by-id/CAOj6k6dEVi0NvLjMLDhyrJS_n_NZO5D_OU89AO1u53u6NCDDwQ@mail.gmail.com
[3]: /messages/by-id/aW8keI6WZxywRQIt@paquier.xyz
[4]: /messages/by-id/aUOgmypuun0rc2xO@paquier.xyz
[5]: /messages/by-id/CAOj6k6f2B3hNxDcnB5AgHX4kaTW8XTAfMAjRx4upDBOugxqF4w@mail.gmail.com
[6]: /messages/by-id/arS_NVVZZ2XsfCYU@paquier.xyz
[7]: /messages/by-id/4c70b0f6-5aba-464c-b145-464a620c1222@eisentraut.org
[8]: /messages/by-id/CAFAfj_GACKVftwuRjy3Ls-1Xc3ojUUbVh=Rm7KpRuYbaS=uLPg@mail.gmail.com

Attachments:

t254254_2
v9-0004-Add-zstd-compression-dictionaries-with-a-column-l.patchtext/x-patch; name=v9-0004-Add-zstd-compression-dictionaries-with-a-column-l.patchDownload+1812-21
v9-0001-Decode-the-compression-method-in-toast_external_i.patchtext/x-patch; name=v9-0001-Decode-the-compression-method-in-toast_external_i.patchDownload+17-13
v9-0002-Allow-more-than-four-TOAST-compression-methods.patchtext/x-patch; name=v9-0002-Allow-more-than-four-TOAST-compression-methods.patchDownload+280-49
v9-0003-Add-zstd-as-a-TOAST-compression-method.patchtext/x-patch; name=v9-0003-Add-zstd-as-a-TOAST-compression-method.patchDownload+1660-21
#3Manu
manuelreyesbravo@gmail.com
In reply to: Greg Burd (#2)

Hi Greg,

v9, attached, is what my last email described.

Thanks, and no worries about v8. I went through v9 on my side, on
0f3b42ce806 with zstd 1.5.7:

- All four patches apply cleanly with git am. There are no compiler
warnings at -O2 or under cassert+ASan, and make check passes in both
(241 tests, compression_zstd and compression_zstd_dict included), as
does contrib/amcheck.
- 0003 carries the context reuse as I sent it, only with a longer
comment above it, and with my name on it. Thanks for that.

I ran repro-dctx-reset.sh unchanged against v9 and against v9
with the ZSTD_DCtx_reset() call removed

I get the same here. v9 passes, B2 included, with exactly the three
expected "compressed zstd data is corrupt" errors, nothing else, and no
ASan reports. With only the reset removed, B2 comes back with wrong data
and no error while A2, A3 and B3 stay true, and the slices of good
values after an error fail instead (9 errors where 3 are expected).

I also re-ran the timings on v9 against v9 with the reuse undone (the
v7 decompression code): three independent runs, 38 paired rounds in
all, hot cache, each round checked against an idle CPU calibration and
none discarded. Median ratio over the 38 rounds, with the range covered
by the three runs' 95% CIs; below 1 means v9 is faster:

- 32 kB slice: docs 0.739 [0.694, 0.749], json 0.648 [0.598, 0.653],
random 0.741 [0.696, 0.752]
- 32 kB prefix: docs 0.747 [0.702, 0.754], json 0.701 [0.653, 0.709],
random 0.761 [0.714, 0.789]
- 32 kB full read: docs 0.887 [0.828, 0.890], random 0.872 [0.822,
0.880]; json 1.000 [0.988, 1.006]
- 1 MB random slice: 0.694 [0.686, 0.703]
- 4 kB slice: 0.943 to 0.978 across the three corpora
- load, i.e. compression, which the reuse does not touch: 0.988 to
0.998, every range containing 1

All the slices, the 32 kB prefixes and the docs and random 32 kB full
reads were faster in each of the 38 rounds.

One small thing in the 0003 commit message: "slices and prefixes of
4kB-32kB values take about 40% less time" is more than I see. Here it
is 24-35% less at 32 kB and 2-6% at 4 kB, so maybe "about 25-35% less
time for 32 kB values, a few percent at 4 kB", unless your hosts show
otherwise.

I also see that the XXX on the dictionary prefix path in 0004 now
mentions the reset it would need if it moved to the streaming loop.
My checks don't exercise dictionaries, so I have nothing to add there.

I can share the scripts and the per-run numbers if that is useful.

Regards,
Manu

#4Greg Burd
greg@burd.me
In reply to: Manu (#3)

Hi Manu,

Thanks for the careful review and the second round of timings. You are
right about the commit message, and I can now say so from my own
numbers.

I built v9 on a bare-metal box (c6id.metal, 128 vCPU, local NVMe, THP
off, performance governor) and ran the A/B you'd expect: v9 against the
same tree with the decompression reverted to the real v7 path, that is
a fresh ZSTD_createDCtx()/free per value, not the reset removed. The
reset-removed build is not a fair speed baseline, because it corrupts a
plain slice scan; I used it only to reproduce that corruption, which it
does.

Median of 30 paired rounds, alternating order, on 80k x 46kB docs plus
160k x 4kB plus 200 x 1MB, all external, warm:

query v9 ms v7 ms ratio v9 faster wins
32kB prefix(100B) 2441.7 3975.8 0.614 39% 30/30
32kB slice@20k 8876.7 9316.3 0.953 5% 30/30
32kB full read 9774.2 10222.8 0.956 4% 30/30
4kB prefix(100B) 501.4 517.7 0.969 3% 30/30
1MB slice@500k 647.8 647.0 1.001 0% 10/30

So the big number only shows up for a small prefix or slice of a large
value, where the allocation dwarfs the decode. For whole-value reads
and for 4kB values it's a few percent, which is your point. I'll change
the 0003 commit message to something like:

Reusing the context saves the per-value allocation. For whole-value
reads and small (4kB) values this is a few percent; it rises to about
40% for small slices and prefixes of large (32kB) values, where the
allocation dominates the decode.

Your repro passes here too: v9 gives exactly the three expected
"compressed zstd data is corrupt" errors and no ASan reports, and with
the reset removed B2 returns wrong data with no error. A bare
count(length(substr(v,1,100))) over 80k external zstd values is enough
to show it: v9 and true v7 both return 80000, the reset-removed build
raises the corrupt error.

Two more things from the same box, since they bear on the series.

Dictionaries. Compression ratio (raw/relation size), 150k rows per
shape:

shape pglz lz4 zstd zstd+dict
logs 1.57 1.57 2.75 4.32
text 16.7 19.7 26.9 63.8
random 0.92 0.92 1.37 (no dict: ZDICT declined to train)

The dictionary is where the structured-but-small values win: +57% over
plain zstd on logs, more on templated text. Per-value CLI numbers on
~1kB docs line up: lz4 2.0x -> 3.6x with a dictionary, zstd 2.9x ->
5.2x. The proportional gain is largest for small values and fades as
values grow, for both codecs, which fits the dictionary being a
cold-start aid.

Lifecycle under load. I ran a 65-minute torture test on a cassert
build: 48 pgbench clients reading slices, prefixes and whole values,
inserting and updating dict-compressed rows, while a background loop
retrained the dictionary, ran VACUUM FULL (which retires superseded
dictionaries), added and dropped a second zstd_dict column, vacuumed,
and ran pg_amcheck --heapallindexed. A control column holds md5(v) as
written, checked after every step. Across the whole run: zero bad
signatures, zero amcheck errors, zero failed transactions, no assertion
failure or crash, and the dictionary count cycled as designed
(retrain adds one, the next rewrite retires the old ones). An earlier
run I killed with -m immediate at 5.6M rows came back through crash
recovery with every row still matching its signature.

I'll fold the commit-message change into the next version along with
anything else that comes out of review, rather than post a v10 that
differs only in that one sentence. If you want to compare setups, send
your scripts and per-run numbers and I'll diff them against mine.

best.

-greg

#5Greg Burd
greg@burd.me
In reply to: Greg Burd (#4)

Here is v10, with the change I promised in the last message and two new
patches.

0001 Decode the compression method in toast_external_info_get()
0002 Allow more than four TOAST compression methods
0003 Add zstd as a TOAST compression method (context reuse)
0004 Add zstd compression dictionaries with a column-local lifecycle
0005 Abstract the dictionary codec behind a routine struct
0006 Add lz4 compression dictionaries

0001-0004 are v9 with one change: the 0003 commit message now reads, per
my last message,

For whole-value reads and small (4kB) values this saves a few percent;
it rises to about 40% for small slices and prefixes of large (32kB)
values, where the allocation dominates the decode.

0005 and 0006 are new. Rebased on master (1910daf9831); cfbot is green.

0005, abstracting the codec. Reviewing 0004 it became clear the whole
dictionary machinery (the pg_toast_dictionary catalog, column ownership,
containment, retirement, training with ZDICT) is codec-independent. Only
three calls differ per codec: compress a value with a dictionary,
decompress a whole value, decompress a prefix. 0005 puts those behind a
DictCompressRoutine struct dispatched on the datum's method byte, so a
second dictionary-aware codec is three functions plus a case. No behavior
change for zstd; it only opens the seam.

0006, lz4 dictionaries. lz4 has no trainer of its own; its headers point
at zstd's ZDICT, which 0004 already uses, so a trained lz4 dictionary is
just bytes stored in pg_toast_dictionary exactly like a zstd one, and the
lifecycle is reused unchanged. 0006 adds one DictCompressRoutine for lz4
(LZ4_loadDict + LZ4_compress_fast_continue, LZ4_decompress_safe_usingDict)
and the lz4_dict method. Training still needs zstd's builder, so an
lz4_dict column wants a server built with both; without a dictionary it
behaves like plain lz4.

lz4 dictionaries earn their place. Per-value CLI numbers, each document
compressed on its own against a 64kB ZDICT dictionary:

~1kB structured docs: lz4 2.0x -> 3.6x (+80%), zstd 2.9x -> 5.2x
~2-6kB structured docs: lz4 2.8x -> 3.8x (+33%), zstd 5.4x -> 6.0x

At the small sizes where TOAST dictionaries help most, lz4 nearly doubles,
and lz4+dict (3.6x) beats plain zstd (2.9x) while keeping lz4's much lower
decompression cost. The proportional gain is largest for small values and
fades as values grow, which matches the zstd dictionary numbers from my
last message.

I kept 0005 and 0006 separate so the abstraction reads as a no-op refactor
and lz4 as self-contained. If the series is already too large, I'm happy
to hold 0006; it does not change 0001-0005.

One thing worth settling: automatic dictionary evolution. Training is
manual today (pg_train_toast_dictionary). As a column accumulates data,
when should a dictionary be rebuilt, on what sample, and how do we tell a
new dictionary is actually better, all without touching the INSERT/UPDATE
fast path? I have a design with the following shape:

- Opt-in per column (an attribute option, default off), evaluated during
ANALYZE, which already has a block sample. No new scheduler; it rides
the autovacuum ANALYZE cadence.
- Trigger on a multiplicative row-growth ratio since the dictionary was
trained, plus a cooldown, so the retrain interval grows with the table.
- Decide "better" by a held-out size test: train a candidate on 80% of
the sample, compress the other 20% with both the current and candidate
dictionary, adopt only on a margin win (a GUC, say 5%). This runs in
the maintenance process, never on the write path.
- Cache the current dictionary OID in the relcache so the fast path is a
field read, not a catalog probe per value. This also resolves the XXX
already in toast_dictionary_current().
- Bound pg_toast_dictionary with a per-column cap on retained
dictionaries; when hit, decline and warn rather than force a rewrite.
Retirement stays rewrite-bound as it is now; cheaper VACUUM-driven
retirement is a harder follow-up, because proving a dictionary
unreferenced needs a full attribute scan.
- All of it is codec-agnostic: a codec supplies only train(samples) and a
compressed-size estimate, which is the seam 0005 adds.

I can post the full design, or turn it into a patch once the policy is
agreed. It can equally wait until the manual lifecycle lands; I don't want
to widen the series anymore before 0001-0004 are settled, but someone was
bound to ask about this aspect of the solution.

best.

-greg

Attachments:

t254254_5
v10-0001-Decode-the-compression-method-in-toast_external_.patchtext/x-patch; name=v10-0001-Decode-the-compression-method-in-toast_external_.patchDownload+17-13
v10-0004-Add-zstd-compression-dictionaries-with-a-column-.patchtext/x-patch; name=v10-0004-Add-zstd-compression-dictionaries-with-a-column-.patchDownload+1812-21
v10-0005-Abstract-the-dictionary-codec-behind-a-routine-s.patchtext/x-patch; name=v10-0005-Abstract-the-dictionary-codec-behind-a-routine-s.patchDownload+116-23
v10-0002-Allow-more-than-four-TOAST-compression-methods.patchtext/x-patch; name=v10-0002-Allow-more-than-four-TOAST-compression-methods.patchDownload+280-49
v10-0006-Add-lz4-compression-dictionaries.patchtext/x-patch; name=v10-0006-Add-lz4-compression-dictionaries.patchDownload+430-16
v10-0003-Add-zstd-as-a-TOAST-compression-method.patchtext/x-patch; name=v10-0003-Add-zstd-as-a-TOAST-compression-method.patchDownload+1660-21
#6Manu
manuelreyesbravo@gmail.com
In reply to: Greg Burd (#4)

Hi Greg,

On Sat, Oct 24, 2026 at 6:33 PM Greg Burd <greg@burd.me> wrote:

If you want to compare setups, send your scripts and per-run numbers
and I'll diff them against mine.

Thanks for re-measuring on bare metal, and for the new 0003 sentence.
Scripts and numbers are attached; first, the 1MB slice.

It is the database encoding. bench.sh runs on a SQL_ASCII database on
purpose. With a multibyte encoding, text_substring() asks detoast for
bytes [0, (start + len - 1) * eml) (varlena.c:666-718), and a request
at least as long as the raw size becomes a full decompression
(detoast.c:529); lines as of master 42e96cf2fe0, and v10 changes
neither. I checked it in the server, with breakpoints at the entry of
zstd_decompress_datum() and zstd_decompress_datum_slice(), on 20
values of 1 MB:

- UTF8: substr(v, 500000, 100) enters zstd_decompress_datum() 20
times and the slice function never.
- SQL_ASCII: the same query enters zstd_decompress_datum_slice() 20
times, with slicelength 500099.
- substr(v, 1, 100) is a slice in both (slicelength 400 and 100).

By the same code, substr(v, 20000, 100) on UTF8 asks for 80,396
bytes, more than a 32 or 46 kB value, so it is a full decompression
too; I did not run that one.

So, if your database is UTF8, your 1MB slice@500k (1.001) is a full
read, like our 1 MB full read (1.000 [0.985, 1.006]); your 32kB
slice@20k (0.953) sits with your full read (0.956); and your 32kB
prefix (0.614) is the one that stays a slice.

The 172 us per value that the reuse saves on our 1 MB slice (from the
median times) track page faults. On SQL_ASCII the backend takes 416
page faults per value on that slice with a fresh context and none with
the reused one, the same in three repetitions, about 0.4 us per fault.
The 1 MB prefix (0 and 0 faults) and full read (631 and 631) show no
fault difference, and their timings barely move (0.980 and 1.000).
These counts come from the builds I still have: v7 plus the reuse,
whose three zstd decode functions are line for line those of v10-0003,
and v7, whose two match v10 with the control diff below.

The 32 kB rows are not the same test: if I read your setup right,
they run on the 80k x 46kB docs, and ours on 32,000-byte docs, json
and random values. Size and content both differ, so I would not
read 0.614 vs our 0.70-0.76 as a disagreement.

Our setup: Ryzen AI 9 HX 370 laptop, 8 CPUs pinned, performance
profile; -O2 without asserts, gcc 16.2.1, zstd 1.5.7, --with-lz4
--with-zstd; shared_buffers 2GB; hot cache; SQL_ASCII, locale C.

Attached:
- bench.sh.txt: the benchmark as used, with only local paths replaced.
- run_v9_cite.sh.txt: the rounds, both builds back to back, order
alternating. Our lab's idle-CPU check is stubbed out; it only
flagged rounds, all 38 were clean, so no number depends on it.
- cite_v9.py.txt, cite_v9_runs.py.txt: the summaries (rename to .py;
the second imports the first).
- per-run-v9.txt: per round and point, the median of 5 reps for each
build and the ratio, runs A, B and C.
- nocfbot-v9n-without-reuse.diff.txt: our v7 control on top of 0003.
It also applies on top of v10-0004.
- branch_faults.sh.txt and branch_faults-out.txt: the breakpoint
and page-fault counts above, and their output.

Regards,
Manu

Attachments:

branch_faults-out.txttext/plainDownload
bench.sh.txttext/plainDownload
run_v9_cite.sh.txttext/plainDownload
cite_v9.py.txttext/plainDownload
cite_v9_runs.py.txttext/plainDownload
per-run-v9.txttext/plainDownload
nocfbot-v9n-without-reuse.diff.txttext/plainDownload+10-21
branch_faults.sh.txttext/plainDownload
#7Greg Burd
greg@burd.me
In reply to: Manu (#6)

On Saturday, October 24th, 2026 at 3:32 PM, Manu <manuelreyesbravo@gmail.com> wrote:

Hi Greg,

Hi Manu,

I confirmed your encoding analysis in my own tree, replies inline.

It is the database encoding. bench.sh runs on a SQL_ASCII database on
purpose. With a multibyte encoding, text_substring() asks detoast for
bytes [0, (start + len - 1) * eml) (varlena.c:666-718), and a request
at least as long as the raw size becomes a full decompression
(detoast.c:529); lines as of master 42e96cf2fe0, and v10 changes
neither.

Confirmed, same lines in my checkout. text_substring() takes the eml > 1
branch (varlena.c, "we can't get LC without detoasting, so we'll grab a
conservatively large slice"): it sets slice_start = 0 and asks for a
slice up to the end byte, (start + len) * eml. detoast then hits

if ((uint32) slicelength >= VARDATA_COMPRESSED_GET_EXTSIZE(attr))
return toast_decompress_datum(attr);

and decodes the whole value. On a single-byte encoding eml == 1 and the
request stays a real slice. So this is a property of the caller and the
encoding, not of the patch, and v11 does not touch either path.

- UTF8: substr(v, 500000, 100) enters zstd_decompress_datum() 20 times
and the slice function never. - SQL_ASCII: the same query enters
zstd_decompress_datum_slice() 20 times, with slicelength 500099.

That is the clean way to settle it, and it matches the code above. My box
was UTF8, so my "slice" rows were calling the full-decode path. I should
have run under SQL_ASCII as you did, or set a breakpoint instead of
trusting the query shape.

So, if your database is UTF8, your 1MB slice@500k (1.001) is a full
read, like our 1 MB full read (1.000 [0.985, 1.006]); your 32kB
slice@20k (0.953) sits with your full read (0.956); and your 32kB
prefix (0.614) is the one that stays a slice.

Agreed, line by line. Relabeled, my numbers are: full reads 0.956 and
1.001, which sit on your 0.956 and 1.000; and one true slice, the 32kB
prefix at 0.614. There was never a disagreement, just one genuine slice
measured two ways.

The 172 us per value that the reuse saves on our 1 MB slice track page
faults. On SQL_ASCII the backend takes 416 page faults per value on
that slice with a fresh context and none with the reused one [...] The
1 MB prefix (0 and 0 faults) and full read (631 and 631) show no fault
difference, and their timings barely move.

This is the mechanism I was missing, and it is the right one. A fresh
ZSTD_DCtx faults in its working buffers on every value; the reused
context keeps them resident, so the saving is the fault cost, not decode
work. That explains why the win lands only on a true slice of a large
value: the full read touches the buffers either way (your 631 vs 631),
and the small prefix never grows them (0 vs 0). The 0003 commit message
says "small slices and prefixes of large values," which is exactly this
case, so I'll leave the wording as it stands; if you think it is worth
naming the page-fault cause in the message I'm happy to add a line.

The 32 kB rows are not the same test: ours on 32,000-byte docs, json
and random values. Size and content both differ, so I would not read
0.614 vs our 0.70-0.76 as a disagreement.

Right, those are not comparable. Mine were 80k x 46kB docs; yours are
32,000-byte json and random values, so both the size and the
compressibility differ, and the prefix fraction that stays a slice
differs with them. I'll stop citing the two side by side.

Our setup: Ryzen AI 9 HX 370 laptop, 8 CPUs pinned, [...] SQL_ASCII,
locale C.

Noted; mine was c6id.metal, UTF8, locale C, which is the one variable
that mattered here. Thanks for the scripts and the per-run file; the
nocfbot-v9n-without-reuse.diff control is the same shape as the true-v7
build I used, so between the two we have the reuse isolated on both a
laptop and bare metal, and the page-fault counts explain the one number
that moves.

best.

-greg

#8Greg Burd
greg@burd.me
In reply to: Greg Burd (#7)

Hello, here is v11.

Two changes on top of v10, both in the dictionary area, plus a rebase on master
(065dc52f1a4). cfbot is green on all platforms. It does not touch 0003 or the
decode paths from the measurement thread.

0001 Decode the compression method in toast_external_info_get()
0002 Allow more than four TOAST compression methods
0003 Add zstd as a TOAST compression method
0004 Add TOAST compression dictionaries for zstd and lz4
0005 Add automatic dictionary evolution during ANALYZE

0001-0003 are unchanged.

Some callouts.

0004 folds the former abstraction and lz4-dictionary patches into one.

The split was artificial: the catalog, the column-local lifecycle, containment,
retirement and training are codec-independent, and only three calls differ per
codec (compress with a dictionary, decompress, decompress a prefix). So the
dictionary patch now carries both zstd_dict and lz4_dict from the start, with
the codec behind a small DictCompressRoutine. lz4 has no trainer of its own
and its headers point at zstd's ZDICT, so an lz4 dictionary is the same trained
bytes; only the compress/decompress calls change. For small, similar values,
which is where TOAST dictionaries help most, a dictionary roughly doubles lz4
(about +80% on ~1kB structured documents) and brings lz4+dict above plain zstd
while keeping lz4's lower decompression cost.

0005 automatic dictionary evolution, the open question from last time. (new)

A trained dictionary ages as a column's data drifts. This lets ANALYZE
retrain, opt-in per column (an attribute option, default off), on the block
sample ANALYZE already has, and never on the write path:

- Gates. Retrain only when the live row count has grown by a factor
since the current dictionary was trained, is past a floor, and the
current dictionary is older than a cooldown. A per-column cap bounds
how many dictionaries accumulate; at the cap it declines with a LOG
and suggests a rewrite, since retirement is still rewrite-bound.
- Adopt only on a win. Train a candidate on 80% of the sample,
compress the held-out 20% with both the current and the candidate
dictionary, and install the candidate only if it is at least a margin
smaller on data it was not trained on. The first dictionary is
adopted unconditionally.
- Off the fast path. All of this runs in the ANALYZE process. The
write path only reads the current dictionary OID, now cached in the
relcache (dict_install invalidates it), so a bulk load no longer
probes the catalog per value.
- Codec-agnostic. A codec adds only train() and a compressed-size
estimate, so zstd and lz4 share the whole policy.

Two pg_toast_dictionary columns feed the gates: tdtrainrows (the reltuples
estimate at training time) and tdtraintime.

Measured on drifting data: load one distribution, train, drift to a different
distribution, ANALYZE, rewrite, and compare the stored size of the drifted data
under three policies:

policy avg stored ratio
plain zstd (no dictionary) 868 B 3.94
stale dictionary (old data, kept) 892 B 3.83
evolved dictionary (retrained) 821 B 4.16

The point is the middle row: after drift a stale dictionary is worse than no
dictionary, because it mis-predicts the new data; evolution retrains
automatically and recovers the advantage (821 vs 892, about 8% smaller). The
decision is visible in the log at DEBUG1:

dictionary evolution for "v": heldout=6000 dictsize=65536
cur=5179154 cand=4910999 gain=5.2% adopt=1

When the distribution does not drift, the candidate does not beat the incumbent
by the margin, so nothing is installed and the dictionary count does not move.
The held-out test is a compression-ratio proxy, not an end-to-end TOAST
measurement; I think that is the right first cut, and the margin absorbs the
slack.

0005 depends only on 0004, so if the series is more than the thread wants to
carry at once I can hold it back and post it separately later.

The auto-training/retraining aspect is likely going to elicit a lot of good
design feedback and differing opinions, but I'd like those who participate in
the discussion about that to first acknowledge that the fundamental idea of
auto-retraining/evolution of dictionaries is an idea that they feel should be
in or out of this kind of solution explicitly and up front if possible. I do
think it is a good idea and should be in, but there should be functions to
manage dictionaries manually and a way to enable/disable the automatic piece.

my $0.02, fwiw. best.

-greg

Attachments:

t254254_8
v11-0003-Add-zstd-as-a-TOAST-compression-method.patchtext/x-patch; name=v11-0003-Add-zstd-as-a-TOAST-compression-method.patchDownload+1660-21
v11-0001-Decode-the-compression-method-in-toast_external_.patchtext/x-patch; name=v11-0001-Decode-the-compression-method-in-toast_external_.patchDownload+17-13
v11-0005-Add-automatic-dictionary-evolution-during-ANALYZ.patchtext/x-patch; name=v11-0005-Add-automatic-dictionary-evolution-during-ANALYZ.patchDownload+934-23
v11-0002-Allow-more-than-four-TOAST-compression-methods.patchtext/x-patch; name=v11-0002-Allow-more-than-four-TOAST-compression-methods.patchDownload+280-49
v11-0004-Add-TOAST-compression-dictionaries-for-zstd-and-.patchtext/x-patch; name=v11-0004-Add-TOAST-compression-dictionaries-for-zstd-and-.patchDownload+2321-21
#9Hannu Krosing
hannuk@google.com
In reply to: Greg Burd (#8)

Hi Greg

Please take a look at a generalized design for the compression dictionary

In email: [PATCH v1] Generic Datum Encoding and Compression Contexts
(pg_encoding_type, pg_encoding_context)

I have used this myself in dictionary compression for zstd and lz4 and
for keeping Apache Avro schemas for JSON and JSONB encodings and
defining cascaded Avro+zstd

And also I used the same for storing quantization tables for pgvector
int8 and other quantizations

This could also be used for other "encoding" tasks, like having a
public key for writes and a more restricted private key for reads,
etc.

The main point is that having a generic facility for these kinds of
tasks would benefit many use cases.

Cheers,
Hannu

Show quoted text

On Sun, Oct 25, 2026 at 5:34 PM Greg Burd <greg@burd.me> wrote:

Hello, here is v11.

Two changes on top of v10, both in the dictionary area, plus a rebase on master
(065dc52f1a4). cfbot is green on all platforms. It does not touch 0003 or the
decode paths from the measurement thread.

0001 Decode the compression method in toast_external_info_get()
0002 Allow more than four TOAST compression methods
0003 Add zstd as a TOAST compression method
0004 Add TOAST compression dictionaries for zstd and lz4
0005 Add automatic dictionary evolution during ANALYZE

0001-0003 are unchanged.

Some callouts.

0004 folds the former abstraction and lz4-dictionary patches into one.

The split was artificial: the catalog, the column-local lifecycle, containment,
retirement and training are codec-independent, and only three calls differ per
codec (compress with a dictionary, decompress, decompress a prefix). So the
dictionary patch now carries both zstd_dict and lz4_dict from the start, with
the codec behind a small DictCompressRoutine. lz4 has no trainer of its own
and its headers point at zstd's ZDICT, so an lz4 dictionary is the same trained
bytes; only the compress/decompress calls change. For small, similar values,
which is where TOAST dictionaries help most, a dictionary roughly doubles lz4
(about +80% on ~1kB structured documents) and brings lz4+dict above plain zstd
while keeping lz4's lower decompression cost.

0005 automatic dictionary evolution, the open question from last time. (new)

A trained dictionary ages as a column's data drifts. This lets ANALYZE
retrain, opt-in per column (an attribute option, default off), on the block
sample ANALYZE already has, and never on the write path:

- Gates. Retrain only when the live row count has grown by a factor
since the current dictionary was trained, is past a floor, and the
current dictionary is older than a cooldown. A per-column cap bounds
how many dictionaries accumulate; at the cap it declines with a LOG
and suggests a rewrite, since retirement is still rewrite-bound.
- Adopt only on a win. Train a candidate on 80% of the sample,
compress the held-out 20% with both the current and the candidate
dictionary, and install the candidate only if it is at least a margin
smaller on data it was not trained on. The first dictionary is
adopted unconditionally.
- Off the fast path. All of this runs in the ANALYZE process. The
write path only reads the current dictionary OID, now cached in the
relcache (dict_install invalidates it), so a bulk load no longer
probes the catalog per value.
- Codec-agnostic. A codec adds only train() and a compressed-size
estimate, so zstd and lz4 share the whole policy.

Two pg_toast_dictionary columns feed the gates: tdtrainrows (the reltuples
estimate at training time) and tdtraintime.

Measured on drifting data: load one distribution, train, drift to a different
distribution, ANALYZE, rewrite, and compare the stored size of the drifted data
under three policies:

policy avg stored ratio
plain zstd (no dictionary) 868 B 3.94
stale dictionary (old data, kept) 892 B 3.83
evolved dictionary (retrained) 821 B 4.16

The point is the middle row: after drift a stale dictionary is worse than no
dictionary, because it mis-predicts the new data; evolution retrains
automatically and recovers the advantage (821 vs 892, about 8% smaller). The
decision is visible in the log at DEBUG1:

dictionary evolution for "v": heldout=6000 dictsize=65536
cur=5179154 cand=4910999 gain=5.2% adopt=1

When the distribution does not drift, the candidate does not beat the incumbent
by the margin, so nothing is installed and the dictionary count does not move.
The held-out test is a compression-ratio proxy, not an end-to-end TOAST
measurement; I think that is the right first cut, and the margin absorbs the
slack.

0005 depends only on 0004, so if the series is more than the thread wants to
carry at once I can hold it back and post it separately later.

The auto-training/retraining aspect is likely going to elicit a lot of good
design feedback and differing opinions, but I'd like those who participate in
the discussion about that to first acknowledge that the fundamental idea of
auto-retraining/evolution of dictionaries is an idea that they feel should be
in or out of this kind of solution explicitly and up front if possible. I do
think it is a good idea and should be in, but there should be functions to
manage dictionaries manually and a way to enable/disable the automatic piece.

my $0.02, fwiw. best.

-greg

#10Hannu Krosing
hannuk@google.com
In reply to: Greg Burd (#8)

On Sun, Oct 25, 2026 at 5:34 PM Greg Burd <greg@burd.me> wrote:
...

The auto-training/retraining aspect is likely going to elicit a lot of good
design feedback and differing opinions, but I'd like those who participate in
the discussion about that to first acknowledge that the fundamental idea of
auto-retraining/evolution of dictionaries is an idea that they feel should be
in or out of this kind of solution explicitly and up front if possible.

At least the underlying storage should allow multiple dictionalries
for the same relation and moving to newer dictionaries or some
heuristic for dictionary selection.

It also would be nice to have an option for "retiring" a dictionary by
- setting it read-only, so no new rows can use it
- having some process re-encode old values (or maybe in some cases
just wait until partitions with such values are dropped)
- then have a verify and drop function

I do think it is a good idea and should be in, but there should be functions to
manage dictionaries manually and a way to enable/disable the automatic piece.

+1

#11Manu
manuelreyesbravo@gmail.com
In reply to: Greg Burd (#8)

Hi Greg,

On Sun, Oct 25, 2026 at 4:33 PM Greg Burd <greg@burd.me> wrote:

Hello, here is v11.

On the question you put up front: I think evolution belongs in,
opt-in and off by default as you have it; what follows is about how,
not whether, and point 3 is the one I'd fix first. On your question
in the previous mail, I'd leave the 0003 message as it is; it already
names the case.

v11 applies cleanly on master dfd7ede529. With zstd 1.5.7 and lz4
1.10.0, make check (243 tests) and amcheck pass at -O2 and under
cassert+ASan, with no warnings. The four attached diffs stack in the
order numbered below.

1. lz4 without zstd does not compile. lz4_dict_get() is only under
#ifdef USE_LZ4 and calls dict_fetch(), which is static and inside
#ifdef USE_ZSTD; the call is at toast_dictionary.c:537. The first diff
puts dict_fetch() under USE_ZSTD || USE_LZ4 and keeps only the zstd
callback registration under USE_ZSTD. An lz4-only build then passes
make check, and it reads and writes lz4_dict values whose dictionary a
zstd build trained.

2. With zstd but without lz4, compression_zstd_dict fails: its SET
COMPRESSION lz4 gets "compression method lz4 not supported". The same
diff uses pglz there.

3. 0005 swallows errors, a cancel included.
toast_dictionary_maybe_evolve() catches every ERROR with
FlushErrorState() and no subtransaction (toast_dictionary.c:1112-1290).
A real SIGINT on entry to it: ANALYZE completed and only logged "...
was skipped: canceling statement due to user request". A sampled
external value with a damaged chunk number, which errors inside the
TOAST index scan: ANALYZE returns with seven "resource was not closed"
warnings. From reading, an error halfway through dict_install() would
also commit the old dictionary as non-current with no new one.

The third diff runs the evaluation in an internal subtransaction and
re-throws a cancel. It tests the error code, because ProcessInterrupts()
clears QueryCancelPending before raising it; testing only the pending
flags still swallows the SIGINT. With it, under cassert+ASan, the
SIGINT gives the usual ERROR, the damaged chunk one WARNING and no
leak, and adoption works in plain ANALYZE, BEGIN/COMMIT,
BEGIN/ROLLBACK, a rolled-back savepoint and VACUUM (ANALYZE).

4. The dictionary caches hold one entry. Every switch between
dictionaries fetches the dictionary again, and zstd digests it again.
In user-space instructions per value: one zstd_dict column 23,223,
two in a row 265,236 (4,000 fetches for 4,000 values); lz4 11,501 and
189,002. One column retrained without a rewrite, which evolution now
does on its own, with new rows in space freed among old ones: 258,163
(1,946 fetches for 2,000 values).

The second diff, on top of the first, gives each cache 4 entries keyed
by OID, least recently used out. The victim is picked after
dict_fetch(), because dict_fetch() can run the invalidation callback.
With it, those cases take 2 fetches and 27,872, 10,836 and 27,891
instructions per value; one dictionary stays at 23,223. The 4 is
arbitrary, and lz4 can now keep up to 4 dictionary copies per backend,
each up to 1 MB. Under ASan it stays correct with retrains, VACUUM
FULL and DROP COLUMN from another session between one backend's
reads, eviction across six columns and debug_discard_caches = 1.

5. Evolution without drift: I ran 24 ANALYZEs on unchanged data with a
dictionary trained on the same distribution, setting min_gain to 1.0
so the incumbent stayed. The gains were 0.9% to 2.3% at 600 and at
6,000 held-out values, all under the default 5% margin. At 6,000 one
evaluation calls ZSTD_createCDict() 12,005 times: 12,000 from the
held-out test, one digest per size it measures, and 5 inside ZDICT.
The fourth diff replaces compressed_size() with compressed_total(),
one call per dictionary: two digests, same totals and decision.

6. On the ~1kB numbers: a 1 kB value alone in its row stays below
TOAST_TUPLE_THRESHOLD (heapam.c:2266), so it is stored uncompressed
with every method, even with toast_tuple_target = 128. At 3 kB the
dictionary takes lz4 from 1.94 to 2.50 on docs, 3.58 to 4.76 on json.

Corrupt dictionary values error cleanly under ASan, and substr()
matches the raw text at 56 offset/length pairs on UTF8 and SQL_ASCII.
Numbers: measurements-v11.txt; scripts: tests-v11.txt.

Regards,
Manu

Attachments:

nocfbot-v11-lz4-without-zstd.diff.txttext/plainDownload+15-4
nocfbot-v11-dict-cache-on-fix.diff.txttext/plainDownload+114-43
nocfbot-v11-evolve-subxact.diff.txttext/plainDownload+36-9
nocfbot-v11-evolve-digest-once.diff.txttext/plainDownload+81-71
measurements-v11.txttext/plainDownload
tests-v11.txttext/plainDownload
#12Greg Burd
greg@burd.me
In reply to: Hannu Krosing (#9)

On Sunday, October 25th, 2026 at 12:52 PM, Hannu Krosing <hannuk@google.com> wrote:

Hi Greg

Please take a look at a generalized design for the compression dictionary

In email: [PATCH v1] Generic Datum Encoding and Compression Contexts
(pg_encoding_type, pg_encoding_context)

Hey Hannu,

Sure thing, I'll give that a look and see how the two designs might become
one.

I have used this myself in dictionary compression for zstd and lz4 and
for keeping Apache Avro schemas for JSON and JSONB encodings and
defining cascaded Avro+zstd

Interesting use cases.

And also I used the same for storing quantization tables for pgvector
int8 and other quantizations

Hmmm... ok.

This could also be used for other "encoding" tasks, like having a
public key for writes and a more restricted private key for reads,
etc.

Are we at risk of over-generalizing/loading this one idea too much? I'd
imagine you to say "no", but I had to ask. :)

The main point is that having a generic facility for these kinds of
tasks would benefit many use cases.

I'm all for reuse and a generic facility if one can be agreed upon.

Cheers,
Hannu

best.

-greg

#13Hannu Krosing
hannuk@google.com
In reply to: Greg Burd (#12)

Hi Greg,

Please take a look at a generalized design for the compression dictionary

In email: [PATCH v1] Generic Datum Encoding and Compression Contexts
(pg_encoding_type, pg_encoding_context)

Hey Hannu,

Sure thing, I'll give that a look and see how the two designs might become
one.

I have to check if that version already has "fallback encodings" to
try if the main one fails.

And one-byte in-group "variants" to have something small to store
inside the data itself as an indicator.

I have used this myself in dictionary compression for zstd and lz4 and
for keeping Apache Avro schemas for JSON and JSONB encodings and
defining cascaded Avro+zstd

Interesting use cases.

Avro was especially efficient for JSONB because it didn't need to
parse anything; it could use the JSONB internal structure directly for
encoding.

And dictionary compression was in many cases faster than not using a
dictionary. So, dictionary compression is definitely worth doing.

And also I used the same for storing quantization tables for pgvector
int8 and other quantizations

Hmmm... ok.

This could also be used for other "encoding" tasks, like having a
public key for writes and a more restricted private key for reads,
etc.

Are we at risk of over-generalizing/loading this one idea too much? I'd
imagine you to say "no", but I had to ask. :)

We might be in some cases, but then we find out and can either fall
back to case-specific tables, or add more fields and types to
pg_encoding_context

We do have about 10 very different object types in pg_class and
somehow survive :)

The main point is that having a generic facility for these kinds of
tasks would benefit many use cases.

I'm all for reuse and a generic facility if one can be agreed upon.

Yup, would not be just saving on code but also on mental effort
learning many similar but subtly different ways of doing the same
thing :)

---
Hannu

#14Greg Burd
greg@burd.me
In reply to: Manu (#11)

On Sunday, October 25th, 2026 at 9:21 PM, Manu <manuelreyesbravo@gmail.com> wrote:

Hi Greg,

Hi Manu,

Thanks for the depth here. All four diffs are in v12, which I'll post as
its own message; replies inline.

1. lz4 without zstd does not compile. lz4_dict_get() is only under
#ifdef USE_LZ4 and calls dict_fetch(), which is static and inside
#ifdef USE_ZSTD; the call is at toast_dictionary.c:537.

Fixed as you had it: dict_fetch() now sits under USE_ZSTD || USE_LZ4 and
only the zstd invalidation-callback registration stays under USE_ZSTD. I
build all three configurations now (zstd+lz4, lz4-only, zstd-only), and
each passes make check (243). cfbot never caught this because it builds
with both; I should have built the single-codec configs myself.

2. With zstd but without lz4, compression_zstd_dict fails: its SET
COMPRESSION lz4 gets "compression method lz4 not supported". The same
diff uses pglz there.

Taken; the test uses pglz for the switch-away-from-zstd_dict case, which
does not depend on lz4 being built.

3. 0005 swallows errors, a cancel included. [...] A real SIGINT on entry
to it: ANALYZE completed and only logged "... was skipped: canceling
statement due to user request".

A swallowed cancel and the half-done dict_install() is fixed. v12 runs the
evaluation in an internal subtransaction and re-throws, exactly as your
diff does: BeginInternalSubTransaction, the work, then either
ReleaseCurrentSubTransaction on success or RollbackAndReleaseCurrent on
error; and it re-throws when edata->sqlerrcode is ERRCODE_QUERY_CANCELED
or an interrupt is still pending, since ProcessInterrupts() clears
QueryCancelPending before raising. A failed step now rolls back its TOAST
scan and buffer pins instead of leaking, and a mid-dict_install() error no
longer leaves the old dictionary non-current with no replacement. Under
cassert+ASan a SIGINT gives the normal ERROR, a damaged chunk gives one
WARNING and no leak, and adoption still works in plain ANALYZE, in
BEGIN/COMMIT, BEGIN/ROLLBACK, a rolled-back savepoint, and VACUUM
(ANALYZE).

4. The dictionary caches hold one entry. Every switch between
dictionaries fetches the dictionary again, and zstd digests it again.
[...] one column retrained without a rewrite, which evolution now does
on its own [...] 258,163 (1,946 fetches for 2,000 values).

Right, and evolution makes this the common case, not a corner one. v12
takes your 4-entry LRU keyed by OID for both directions, picking the
victim after dict_fetch() since the fetch can run the invalidation
callback and empty the cache. The instruction counts match what you saw:
the two-dictionary scan drops from ~265k to ~28k per value, and the
retrain-without-rewrite case from ~258k to ~28k. I kept your 4; it is
arbitrary but it covers a scan that alternates between an old and a new
dictionary with headroom, and the per-backend memory is bounded.

5. Evolution without drift: [...] At 6,000 one evaluation calls
ZSTD_createCDict() 12,005 times [...] The fourth diff replaces
compressed_size() with compressed_total(), one call per dictionary.

Taken. compressed_total() digests each dictionary once and loops the
held-out values inside, so an evaluation now builds two CDicts instead of
one per value. Same totals, same decision, and the held-out test stops
dominating the ANALYZE it rides on.

6. On the ~1kB numbers: a 1 kB value alone in its row stays below
TOAST_TUPLE_THRESHOLD (heapam.c:2266), so it is stored uncompressed with
every method [...]. At 3 kB the dictionary takes lz4 from 1.94 to 2.50
on docs, 3.58 to 4.76 on json.

You're right, a ~1 kB value never reaches the compressor, so the "+80%
at 1 kB" number was measuring nothing on the TOAST path; it came from a
standalone CLI run, not from values actually stored. The dictionary
helps once a value crosses TOAST_TUPLE_THRESHOLD.

Corrupt dictionary values error cleanly under ASan, and substr() matches
the raw text at 56 offset/length pairs on UTF8 and SQL_ASCII.

Matches my runs too, corrupt values raise the data-corrupted error with no
sanitizer report, and substr() over the offset/length grid matches the raw
text on both encodings.

Thanks again; the subtransaction and the cache fixes in particular are
ones the series needed. v12 follows.

best.

-greg

#15Greg Burd
greg@burd.me
In reply to: Greg Burd (#12)

On Monday, October 26th, 2026 at 3:02 PM, Greg Burd <greg@burd.me> wrote:

On Sunday, October 25th, 2026 at 12:52 PM, Hannu Krosing <hannuk@google.com> wrote:

Hi Hannu,

I read the Generic Datum Encoding and Compression Contexts patch. It is a
bigger idea than this one, and worth pulling apart where the two meet and
where they don't. Inline below.

Please take a look at a generalized design for the compression
dictionary [...] I have used this myself in dictionary compression for
zstd and lz4 and for keeping Apache Avro schemas for JSON and JSONB
encodings and defining cascaded Avro+zstd

Where we agree: a trained dictionary is just one case of "a value needs a
side artifact to be decoded." Your pg_encoding_context is that artifact
in the general form, and a zstd/lz4 dictionary is one kind of content for
it. The two designs even store nearly the same thing: an id, owning
state, and a bytea blob.

Where they differ is scope, and it is the scope that drove this design.
This series is about TOAST, specifically. The hard problem it solves is
not "store a dictionary," it is "know when a dictionary can be dropped
without a full table scan to prove no value still needs it." The answer
here is column-local ownership: a dictionary belongs to one (relid,
attnum) like a pg_statistic row, values compressed with it never leave
that column in compressed form (heap_fill_tuple marks them external so
every self-contained copy detoasts them), and a rewrite is what retires
the old one. That containment rule is the whole point, and it is TOAST
machinery, not general datum machinery; I don't see how to express it in a
facility that doesn't know about attcompression, detoast, and the rewrite
path.

We'll have to consider this, and other use cases if your generalized
method is going to work.

And also I used the same for storing quantization tables for pgvector
int8 and other quantizations [...] like having a public key for writes
and a more restricted private key for reads, etc. The main point is
that having a generic facility for these kinds of tasks would benefit
many use cases.

This is the part I'd be careful with. Quantization tables, Avro schemas,
and key management each have their own lifecycle and their own "when can
this be dropped" answer, and those answers are not the same as a TOAST
dictionary's. A facility general enough to hold all of them tends to push
the lifecycle decision back onto each caller, which is exactly the part
that was hard to get right here. I'm not against the generic facility; I
am wary of making the TOAST feature wait on, or inherit the constraints
of, a design that also has to satisfy pgvector and key rotation.

[from the follow-up] At least the underlying storage should allow
multiple dictionaries for the same relation and moving to newer
dictionaries or some heuristic for dictionary selection.

That part we already do, and it's the strongest point of overlap.
pg_toast_dictionary holds many dictionaries per column, each value carries
the 4-byte OID of the one it was compressed with, exactly one is current
(tdcurrent) and new writes use it, and 0005 adds the heuristic you
describe: ANALYZE trains a candidate and adopts it only when a held-out
test says it beats the incumbent. So the "multiple dictionaries, move to
newer ones, select by heuristic" shape is in the series today.

It also would be nice to have an option for "retiring" a dictionary by
- setting it read-only, so no new rows can use it
- having some process re-encode old values (or [...] wait until
partitions with such values are dropped)
- then have a verify and drop function

This is close to what happens, under different names. Marking a
dictionary non-current is your "read-only": no new value uses it, old ones
still read. The re-encode step is a table rewrite (VACUUM FULL, CLUSTER,
REPACK), which recompresses every value with the current dictionary and
then drops the non-current ones. What the series does not have, and your
framing makes a fair case for, is a rewrite-free retirement: a verify-then-
drop that proves no live value references a dictionary without a full
rewrite. I left that out on purpose because proving it needs a full
attribute scan, but a dedicated "verify and drop" function the way you
describe is a reasonable way to expose it, and I'd take it as a follow-up.

So, concretely, where I'd land:

- The two efforts aren't competitors; this one is the TOAST-specific
consumer, yours is the general facility. If pg_encoding_context lands,
the TOAST dictionary catalog is a natural thing to re-express on top of
it, with the column-local lifecycle kept as a TOAST-side policy.
- I'd rather not block this series on that re-expression. The containment
and retirement rules are the reviewed-and-tested core here, and they're
TOAST-shaped; rebasing them onto a generic store is a mechanical change
that can happen once the generic store exists and is agreed on.
- I'm happy to review the generic patch with the TOAST case as a concrete
first consumer, and to see whether the multiple-dictionary and
verify-and-drop pieces are better in the common layer than in TOAST.

Does that division make sense to you, or do you see the containment rule
fitting into the generic context after all? That's the piece I can't yet
see clearly.

best.

-greg

#16Greg Burd
greg@burd.me
In reply to: Greg Burd (#14)

Okay, v12 on master (065dc52f1a4).

Fixes since v11,

- lz4-without-zstd did not compile (dict_fetch() was under USE_ZSTD but
called from the lz4 path); it is now shared, and an lz4-only build
passes make check.
- compression_zstd_dict used SET COMPRESSION lz4, which fails on a
zstd-only build; it uses pglz for that case now.
- automatic evolution (0005) swallowed errors, a query cancel included,
and could leave a half-done dict_install(). It now runs in an
internal subtransaction and re-throws a cancel, so an error rolls back
cleanly and a cancel stops ANALYZE.
- the per-backend dictionary caches held one entry, so evolution's
dictionary switching re-fetched and re-digested per value; they are
now a 4-entry LRU, and the held-out evaluation digests each candidate
once instead of once per value.

0001-0003 are unchanged (Nikhil's zstd method and the extensible
encoding).

0004 adds column-local TOAST compression dictionaries for zstd and lz4.
The catalog, the lifecycle, containment, retirement and training are
codec-independent; only three calls differ per codec, behind a small
DictCompressRoutine. lz4 has no trainer of its own and its headers point
at zstd's ZDICT, so an lz4 dictionary is the same trained bytes. A
dictionary helps once a value crosses TOAST_TUPLE_THRESHOLD; at about 3 kB
it takes lz4 from roughly 1.9x to 2.5x on docs and 3.6x to 4.8x on json.

0005 adds automatic dictionary evolution: opt-in per column, run inside
ANALYZE on the block sample it already has. It retrains only when the
data has grown past a threshold since the last training and a cooldown has
elapsed, trains a candidate on 80% of the sample, and adopts it only if it
compresses the held-out 20% at least a margin better than the current
dictionary. Nothing runs on the INSERT/UPDATE path; the write path reads
the current dictionary OID from a relcache cache. A per-column cap bounds
how many dictionaries accumulate. It is codec-agnostic: a codec adds only
train() and a compressed-size estimate.

Measured on drifting data, the stored size of the drifted values: plain
zstd 868 B, a stale dictionary 892 B (worse than none, as expected), an
evolved dictionary 821 B. Evolution recovers the dictionary's advantage
automatically after drift.

0005 depends only on 0004 and can be held back if the series is too large
to carry at once.

best.

-greg

Attachments:

t254254_16
v12-0005-Add-automatic-dictionary-evolution-during-ANALYZ.patchtext/x-patch; name=v12-0005-Add-automatic-dictionary-evolution-during-ANALYZ.patchDownload+971-23
v12-0001-Decode-the-compression-method-in-toast_external_.patchtext/x-patch; name=v12-0001-Decode-the-compression-method-in-toast_external_.patchDownload+17-13
v12-0002-Allow-more-than-four-TOAST-compression-methods.patchtext/x-patch; name=v12-0002-Allow-more-than-four-TOAST-compression-methods.patchDownload+280-49
v12-0003-Add-zstd-as-a-TOAST-compression-method.patchtext/x-patch; name=v12-0003-Add-zstd-as-a-TOAST-compression-method.patchDownload+1660-21
v12-0004-Add-TOAST-compression-dictionaries-for-zstd-and-.patchtext/x-patch; name=v12-0004-Add-TOAST-compression-dictionaries-for-zstd-and-.patchDownload+2403-21
#17Manu
manuelreyesbravo@gmail.com
In reply to: Greg Burd (#16)

Hi Greg,

On Tue, Oct 27, 2026 at 11:57 AM Greg Burd <greg@burd.me> wrote:

Okay, v12 on master (065dc52f1a4).

v12 fixes all five on my side. It also applies cleanly on today's
master (76a55702d89), and make check (243) and amcheck pass with no
warnings with both libraries (-O2, cassert+ASan), lz4 only and zstd
only. A SIGINT on entry to the evaluation gives the usual ERROR, the
damaged chunk one WARNING and no "resource was not closed", and the
numbers match yours: 27,881 and 27,894 instructions per value with 2
fetches, and 7 CDicts per evaluation, 5 of them inside ZDICT.

The subtransaction also holds in VACUUM (PARALLEL 2, ANALYZE), BEGIN
READ ONLY, a DO block with EXCEPTION and autovacuum; an autovacuum
ANALYZE cancelled by LOCK TABLE inside the evaluation stops without
adopting, and a hot standby refuses ANALYZE and replays the adoption.

Containment also held everywhere I could take a value out of its
column before a rewrite retired its dictionary: INSERT ... SELECT,
CTAS, a whole-row composite, an array, another dictionary column, a
matview, partition row movement, a WITH HOLD cursor, a procedure
variable across COMMIT, logical decoding and an extended MCV list.
So did REPACK (CONCURRENTLY) with DML committed during the copy, and
pg_upgrade, which keeps the dictionary OIDs.

Two leftovers: the 0005 message still says compressed_size() and "any
failure is logged and swallowed, never aborting ANALYZE", and
toast_dictionary.h:39 still names compressed_size(); my diff missed it.

Thanks for taking all of these in.

Regards,
Manu

#18Hannu Krosing
hannuk@google.com
In reply to: Manu (#17)

Hi Greg, Manu, Nikhil,

On Thu, Oct 29, 2026 at 1:48 PM Manu <manuelreyesbravo@gmail.com> wrote:

On Tue, Oct 27, 2026 at 11:57 AM Greg Burd <greg@burd.me> wrote:

Okay, v12 on master (065dc52f1a4).

...

Containment also held everywhere I could take a value out of its
column before a rewrite retired its dictionary: INSERT ... SELECT,
CTAS, a whole-row composite, an array, another dictionary column, a
matview, partition row movement, a WITH HOLD cursor, a procedure
variable across COMMIT, logical decoding and an extended MCV list.

I did a full review and live testing pass over v12 (0001-0005) on master
with cassert enabled.

Overall, the split and the architecture read very cleanly -- especially
keeping varattrib_4b_long out of union varattrib_4b in 0002, and the
Ownership / Containment / Retirement write-up in toast_dictionary.c.
0001-0003 look quite close to committable on their own, while 0004-0005
have several containment, security/ACL, memory-management, and test bugs
that need another pass. (If helpful for PG20 progress, committing
0001-0003 first while iterating on 0004-0005 seems very natural.)

Here is what I found, grouped by patch.

=== 0001 - 0003 (Extensible encoding & stateless zstd) ===

1. 1-byte out-of-bounds read on corrupt 8-byte compressed varlenas (0002)

In src/include/varatt.h, VARDATA_COMPRESSED_GET_COMPRESS_METHOD(PTR)
unconditionally reads byte 8 (va_cmid, the 9th byte) whenever the top two
bits of va_tcinfo equal VARLENA_COMPRESS_METHOD_LONG (3):

if (method == VARLENA_COMPRESS_METHOD_LONG)
method = ((const varattrib_4b_long *) PTR)->va_cmid;

Both detoast.c:toast_decompress_datum() and the Assert() at the top of
zstd_decompress_datum() (and VARATT_IS_COMPRESSED_DICT() in 0004) call
this macro *before* zstd_decompress_datum() checks:

if (VARSIZE(value) < VARHDRSZ_COMPRESSED_LONG)

So a corrupted 8-byte 4B_C varlena with method bits == 3 at the end of a
palloc chunk or page reads 1 byte past the allocation. Also, if a
corrupt long header has va_cmid in {0, 1}, it dispatches to pglz/lz4
decompression, which reads starting at offset 8 instead of 9 (feeding
va_cmid itself into the bitstream). Long-form va_cmid values that do
not belong in a long header ({0, 1, 3}) should be rejected as corrupt,
and contrib/amcheck/verify_heapam.c currently returns early on
!VARATT_IS_EXTERNAL(attr) without validating inline compressed headers.

2. One-shot ZSTD_compress() allocates/frees a ~1.3 MB CCtx per datum (0003)

zstd_decompress_datum() nicely reuses a backend-static ZSTD_DCtx, and
zstd_dict_compress_datum() in 0004 reuses a backend-static ZSTD_CCtx
(dict_cctx), but plain zstd_compress_datum() in 0003 still calls one-shot
ZSTD_compress(), which mallocs, initializes, and frees a ~1.2-1.5 MB
ZSTD_CCtx per datum. Reusing a backend-static ZSTD_CCtx via
ZSTD_compressCCtx() avoids per-datum context churn / mmap syscalls on
bulk loads.

3. Minor items in 0001-0003:
- zstd_decompress_datum_slice(): the streaming while (outbuf.pos <
outbuf.size) loop should call CHECK_FOR_INTERRUPTS().
- toast_external_info_get() (0001): still leaves compress_method = 0
(pglz) when the external datum is uncompressed; setting it to
TOAST_INVALID_COMPRESSION_ID when !VARATT_EXTINFO_IS_COMPRESSED()
would make toast_external_data self-describing.
- toast_fetch_datum_slice() (0002): adds VARHDRSZ_COMPRESSED_LONG -
VARHDRSZ (5 bytes) for VARTAG_IS_ONDISK_LONG, which is 4 bytes too
short for 0004's VARHDRSZ_COMPRESSED_DICT - VARHDRSZ (9 bytes). It is
masked today only because slice pushdown is not enabled for zstd_dict /
lz4_dict, but will bite as soon as max_size < extsize is used.

=== 0004 (Compression dictionaries & containment) ===

4. Three containment escapes (including pure PL/pgSQL reproducer)

(a) R/W ExpandedRecord fast path into non-atomic DO / PROCEDURE:
When an atomic PL/pgSQL function returns a named-composite ExpandedRecord,
expanded_record_set_fields(..., !estate->atomic) passes expand_external =
false, keeping the inline zstd_dict datum compressed inside erh->dvalues.
When a non-atomic DO block or PROCEDURE assigns that result to a matching
composite variable, exec_move_row_from_datum() (pl_exec.c:7726) takes the
R/W transfer fast path:

if (VARATT_IS_EXTERNAL_EXPANDED_RW(value) && ...)
{
assign_record_var(estate, rec, erh);
return;
}

completely bypassing field detoasting even though !estate->atomic is true!
(Note: this fast path appears to have the same bug upstream for ordinary
on-disk external TOAST pointers across COMMIT + DROP TABLE.)

Minimal pure-SQL/PLpgSQL reproducer:

CREATE TYPE er_pair AS (a int, b text);
CREATE TABLE cmdict_er(id int, f1 text COMPRESSION zstd_dict,
pad text STORAGE PLAIN);
INSERT INTO cmdict_er
SELECT g,
'{"org":"acme-corporation","dept":"storage","seq":' || g || '}',
repeat('x', 1960)
FROM generate_series(1, 200) g;
SELECT pg_train_toast_dictionary('cmdict_er', 'f1');
INSERT INTO cmdict_er VALUES (
999,
'{"org":"acme-corporation","dept":"storage","seq":999}',
repeat('y', 1960));

CREATE FUNCTION make_er_pair(p_id int) RETURNS er_pair
LANGUAGE plpgsql AS $$
DECLARE r er_pair;
BEGIN
SELECT 1, f1 INTO r FROM cmdict_er WHERE id = p_id;
RETURN r;
END;
$$;

DO $$
DECLARE r er_pair;
BEGIN
r := make_er_pair(999);
RAISE NOTICE 'before: %', pg_column_compression(r.b); -- zstd_dict
COMMIT;
DROP TABLE cmdict_er CASCADE;
COMMIT;
RAISE NOTICE 'len: %', length(r.b);
END;
$$;

Output:
NOTICE: before: zstd_dict
ERROR: compression dictionary 16592 does not exist

(b) Indirect TOAST pointers in detoast_external_attr() (detoast.c):
In the VARATT_IS_EXTERNAL_INDIRECT(attr) branch, the recursion check still
says:

if (VARATT_IS_EXTERNAL(attr))
return detoast_external_attr(attr);

without `|| VARATT_IS_COMPRESSED_DICT(attr)`, so an indirect pointer
referencing an inline dict datum falls through to memcpy() and returns a
still-dictionary-compressed 4B_C datum.

(c) SPI_datumTransfer() / datumTransfer():
SPI_datumTransfer() only flattens VARATT_IS_EXTERNAL_EXPANDED, copying
inline VARATT_IS_COMPRESSED_DICT datums verbatim via datumCopy(). Non-
PL/pgSQL PLs (PL/Python, PL/Perl, PL/Tcl, extensions) or C procedures
using SPI_datumTransfer across SPI_commit() can hold a dangling dictid
after a concurrent rewrite or DROP.

5. Lock-before-ACL, cross-session temp tables, and per-call leak in
pg_train_toast_dictionary()

- Lock before ownership check: pg_train_toast_dictionary() is executable
by PUBLIC and calls `table_open(relid, ShareUpdateExclusiveLock)`
*before* dict_check_column() checks object_ownercheck(). Any
unprivileged role can therefore acquire ShareUpdateExclusiveLock on any
table (blocking VACUUM, ANALYZE, ALTER TABLE, CREATE INDEX CONCURRENTLY,
REPACK) before failing the ACL check. Ownership should be checked
before taking ShareUpdateExclusiveLock (similar to VACUUM/ANALYZE).
- Missing RELATION_IS_OTHER_TEMP(rel) check: dict_check_column() checks
RELKIND_RELATION (which includes temp tables) and object_ownercheck(),
but never rejects RELATION_IS_OTHER_TEMP(rel). A second session of the
same role locks another backend's temp table and enters table_beginscan
until localbuf errors out ("cannot access temporary tables of other
sessions").
- Memory leak in caller context: pg_train_toast_dictionary() allocates
samples.data (up to 100 * dict_size, i.e., ~100 MB at 1 MB dict_size),
sizes, and dictbuf in CurrentMemoryContext (ExecutorState) and never
pfrees them before returning, so calling it across multiple columns/
partitions in one SELECT accumulates hundreds of MBs to GBs in
ExecutorState.

6. TRUNCATE does not retire non-current dictionaries

Retirement is wired only into finish_heap_swap() (repack.c). TRUNCATE
(ExecuteTruncateGuts in tablecmds.c) acquires AccessExclusiveLock and
creates a new empty relfilenode, destroying all rows referencing old
dictionaries, yet never calls toast_dictionary_retire(). If a column hits
dictionary_evolution_max_retained, TRUNCATE + reload leaves all dead
dictionaries wedged until the user runs VACUUM FULL on the truncated table.

7. Inline HEAP_HASEXTERNAL overhead & unrelated-column UPDATE behavior

Setting HEAP_HASEXTERNAL on inline dict tuples preserves HOT updates, but
in heap_update() (heapam.c:3888) `need_toast` is true for every update of
any unrelated column on that row -- forcing an extra XLOG_HEAP_LOCK WAL
record, heap buffer unlock/relock, dual tuple deform, and TOASTDICTOID
syscache lookup on every single UPDATE (and tuple deform in
heap_toast_delete() on every DELETE).

Also note the behavioral difference vs. compression_zstd_dict.sql's
comment ("ordinary updates of other columns leave the value, and its old
dictionary, alone"): that holds for external TOAST pointers, whereas for
*inline* dict datums toast_tuple_init() runs !toast_dictionary_keep() on
every UPDATE and eagerly decompresses + recompresses the column as soon
as its dictionary becomes non-current or SET COMPRESSION changes.

8. Cache sizing & invalidation in toast_dictionary.c

- dict_cache_invalidate() / lz4_dict_cache_invalidate() ignore `hashvalue`
and wipe all 4 slots across the backend whenever *any* row in
pg_toast_dictionary changes anywhere in the database.
- With DICT_CACHE_SIZE = 4 per backend, scanning a partitioned table with

4 partitions (each partition has its own relid and dictid OID!) will

thrash ZSTD_createDDict() on every tuple.

=== 0005 (Automatic dictionary evolution during ANALYZE) ===

9. compression_dict_evolve.sql compresses ZERO rows on disk!

In compression_dict_evolve.sql, `evo (id int, f1 text COMPRESSION
zstd_dict)` stores docA(g) (~175 bytes) and docB(id) (~195 bytes). Total
tuple width is ~210 bytes -- roughly 10x below TOAST_TUPLE_THRESHOLD -- so
the toaster is never invoked on any row in the entire test:

SELECT pg_column_compression(f1), count(*) FROM evo GROUP BY 1;
pg_column_compression | count
-----------------------+-------
| 4000

So the test currently exercises catalog row churn in pg_toast_dictionary,
not actual multi-generation dictionary compression/decompression on disk
(and `UPDATE evo SET f1 = docB(id)` overwrote all rows anyway, so no
dictA-compressed tuples would coexist with dictB tuples even with wider
rows).

This also highlights a policy gap in toast_dictionary_maybe_evolve():
- On narrow tables whose tuples never approach TOAST_TUPLE_THRESHOLD,
ANALYZE still trains and installs 64 kB dictionaries that no row will
ever use.
- When !OidIsValid(curid), `adopt = true` is unconditional without
checking on the 20% held-out set whether dictionary compression actually
beats plain zstd/lz4 (e.g., on UUID/high-entropy text).

10. Permanent C malloc() leaks across PG_CATCH() OOM rollback (0004 & 0005)

In zstd_dict_compressed_total():

cd = ZSTD_createCDict(dict, dictlen, ZSTD_CLEVEL_DEFAULT); /* malloc */
if (cd == NULL)
return 0;
out = palloc(ZSTD_compressBound(maxlen)); /* can ereport(ERROR)! */

Because toast_dictionary_maybe_evolve() catches non-cancel errors in
PG_CATCH(), rolls back the subtransaction, and downgrades to WARNING, an
OOM in palloc() jumps over ZSTD_freeCDict(cd) and permanently leaks the
malloc'd CDict in long-lived backends / autovacuum workers. The same
pattern occurs with LZ4_createStream() before palloc() in
lz4_dict_compress_datum() (0004) and lz4_dict_compressed_total() (0005)
(where a stack or static LZ4_stream_t + LZ4_resetStream_fast() would also
avoid calling malloc/free inside the per-value loop).

11. tdtrainrows = -1 breaks the growth gate & pg_upgrade loses metadata

- In pg_train_toast_dictionary():
dict_install(..., (int64) rel->rd_rel->reltuples, ...);
On a freshly loaded table before its first VACUUM/ANALYZE, reltuples is
-1, storing tdtrainrows = -1. In toast_dictionary_maybe_evolve(),
`(double) currows * growth` is -2.0, so `totalrows < -2.0` is always
false; and whenever the candidate does not beat the manual dictionary by
min_gain, tdtrainrows (-1) and tdtraintime are left untouched -- causing
every subsequent post-cooldown ANALYZE to re-run ZDICT_trainFromBuffer()
forever.
- 0005 does not update pg_dump's binary_upgrade_dump_toast_dictionaries()
or binary_upgrade_add_toast_dictionary(), resetting tdtrainrows = 0 and
tdtraintime = now() across pg_upgrade.

12. Single-slot rd_toastdictattnum relcache cache thrashes 100% on 2+ columns

RelationData caches a single (rd_toastdictattnum, rd_toastdictoid) pair.
The comment notes "A single entry suffices for a scan of one column", but
toast_dictionary_current() is called tuple-by-tuple on the *write* path:
inserting into a table with two zstd_dict columns alternates attnum 2, 3,
2, 3... and misses the cache on 100% of calls, doing 2*N catalog index
scans. A lazily allocated Oid[natts] array in CacheMemoryContext would
avoid that completely.

13. PGC_USERSET evolution GUCs vs. MAINTAIN privilege

dictionary_evolution_min_interval, dictionary_evolution_min_gain, and
dictionary_evolution_max_retained are all PGC_USERSET. Since PG17, a role
with MAINTAIN (which grants neither DDL ownership nor SELECT on the table)
can run ANALYZE. With PGC_USERSET, a MAINTAIN role can set min_interval=0,
min_gain=0, max_retained=INT_MAX and loop ANALYZE to churn dictionaries
and bloat pg_toast_dictionary (or set client_min_messages=debug1 to read
the held-out compressed byte counts logged in DEBUG1). Making these
PGC_SUSET (or per-column attoptions owned by the table owner) would keep
the privilege boundary intact. Separately, since pg_toast_dictionary has
REVOKE ALL FROM PUBLIC, a security-barrier view (like pg_stats) exposing
metadata without tddict bytes would let non-superuser table owners inspect
their dictionaries.

Hope this helps!

Cheers,
Hannu

Show quoted text

On Thu, Oct 29, 2026 at 2:48 PM Manu <manuelreyesbravo@gmail.com> wrote:

Hi Greg,

On Tue, Oct 27, 2026 at 11:57 AM Greg Burd <greg@burd.me> wrote:

Okay, v12 on master (065dc52f1a4).

v12 fixes all five on my side. It also applies cleanly on today's
master (76a55702d89), and make check (243) and amcheck pass with no
warnings with both libraries (-O2, cassert+ASan), lz4 only and zstd
only. A SIGINT on entry to the evaluation gives the usual ERROR, the
damaged chunk one WARNING and no "resource was not closed", and the
numbers match yours: 27,881 and 27,894 instructions per value with 2
fetches, and 7 CDicts per evaluation, 5 of them inside ZDICT.

The subtransaction also holds in VACUUM (PARALLEL 2, ANALYZE), BEGIN
READ ONLY, a DO block with EXCEPTION and autovacuum; an autovacuum
ANALYZE cancelled by LOCK TABLE inside the evaluation stops without
adopting, and a hot standby refuses ANALYZE and replays the adoption.

Containment also held everywhere I could take a value out of its
column before a rewrite retired its dictionary: INSERT ... SELECT,
CTAS, a whole-row composite, an array, another dictionary column, a
matview, partition row movement, a WITH HOLD cursor, a procedure
variable across COMMIT, logical decoding and an extended MCV list.
So did REPACK (CONCURRENTLY) with DML committed during the copy, and
pg_upgrade, which keeps the dictionary OIDs.

Two leftovers: the 0005 message still says compressed_size() and "any
failure is logged and swallowed, never aborting ANALYZE", and
toast_dictionary.h:39 still names compressed_size(); my diff missed it.

Thanks for taking all of these in.

Regards,
Manu

#19Hannu Krosing
hannuk@google.com
In reply to: Greg Burd (#15)

On Tue, Oct 27, 2026 at 12:53 PM Greg Burd <greg@burd.me> wrote:

On Monday, October 26th, 2026 at 3:02 PM, Greg Burd <greg@burd.me> wrote:

On Sunday, October 25th, 2026 at 12:52 PM, Hannu Krosing <hannuk@google.com> wrote:

Hi Hannu,

I read the Generic Datum Encoding and Compression Contexts patch. It is a
bigger idea than this one, and worth pulling apart where the two meet and
where they don't.

Thanks for a thoughtful review!

Inline below.

Please take a look at a generalized design for the compression
dictionary [...] I have used this myself in dictionary compression for
zstd and lz4 and for keeping Apache Avro schemas for JSON and JSONB
encodings and defining cascaded Avro+zstd

Where we agree: a trained dictionary is just one case of "a value needs a
side artifact to be decoded." Your pg_encoding_context is that artifact
in the general form, and a zstd/lz4 dictionary is one kind of content for
it. The two designs even store nearly the same thing: an id, owning
state, and a bytea blob.

Where they differ is scope, and it is the scope that drove this design.

Yes, I left all the scope work to the user, so very little beyond
basig support for retiring is in the patch.

Because we lack reference-counted pg_depend (the possible need for
which was also revealed in recent PGQ retraction discussions) I
considered this something that should be tied to specific use, not the
context table itself.

This series is about TOAST, specifically. The hard problem it solves is
not "store a dictionary," it is "know when a dictionary can be dropped
without a full table scan to prove no value still needs it."

In some of my designs I just llet this to the admin, so the sequence would be
- lock the context
- run migration off the context
- call drop_context_if_safe(ditionary, VARIADIC user_columns[])

that was done to allow using the same contexts across tables without
making the lifetime tracking frameworks too complex.

The answer
here is column-local ownership: a dictionary belongs to one (relid,
attnum) like a pg_statistic row, values compressed with it never leave
that column in compressed form (heap_fill_tuple marks them external so
every self-contained copy detoasts them), and a rewrite is what retires
the old one. That containment rule is the whole point, and it is TOAST
machinery, not general datum machinery; I don't see how to express it in a
facility that doesn't know about attcompression, detoast, and the rewrite
path.

I think the high level lock-migrate-drop pattern still works, but the
details can be quite complex

We'll have to consider this, and other use cases if your generalized
method is going to work.

And also I used the same for storing quantization tables for pgvector
int8 and other quantizations [...] like having a public key for writes
and a more restricted private key for reads, etc. The main point is
that having a generic facility for these kinds of tasks would benefit
many use cases.

This is the part I'd be careful with. Quantization tables, Avro schemas,
and key management each have their own lifecycle and their own "when can
this be dropped" answer, and those answers are not the same as a TOAST
dictionary's. A facility general enough to hold all of them tends to push
the lifecycle decision back onto each caller, which is exactly the part
that was hard to get right here.

Yes, I started from the assumption that this belongs to the feature's user.

And I decided that until we have more capable dependency tracking,
I'll just fall back to manually managing this.

I'm not against the generic facility; I
am wary of making the TOAST feature wait on, or inherit the constraints
of, a design that also has to satisfy pgvector and key rotation.

Agreed. For me this is agood use case to test the design :)

[from the follow-up] At least the underlying storage should allow
multiple dictionaries for the same relation and moving to newer
dictionaries or some heuristic for dictionary selection.

That part we already do, and it's the strongest point of overlap.
pg_toast_dictionary holds many dictionaries per column, each value carries
the 4-byte OID of the one it was compressed with, exactly one is current
(tdcurrent) and new writes use it, and 0005 adds the heuristic you
describe: ANALYZE trains a candidate and adopts it only when a held-out
test says it beats the incumbent. So the "multiple dictionaries, move to
newer ones, select by heuristic" shape is in the series today.

Thanks for confirming also other see this popping up in multiple places.

It also would be nice to have an option for "retiring" a dictionary by
- setting it read-only, so no new rows can use it
- having some process re-encode old values (or [...] wait until
partitions with such values are dropped)
- then have a verify and drop function

This is close to what happens, under different names. Marking a
dictionary non-current is your "read-only": no new value uses it, old ones
still read. The re-encode step is a table rewrite (VACUUM FULL, CLUSTER,
REPACK), which recompresses every value with the current dictionary and
then drops the non-current ones. What the series does not have, and your
framing makes a fair case for, is a rewrite-free retirement: a verify-then-
drop that proves no live value references a dictionary without a full
rewrite. I left that out on purpose because proving it needs a full
attribute scan, but a dedicated "verify and drop" function the way you
describe is a reasonable way to expose it, and I'd take it as a follow-up.

And I was approaching the same issue from exactly the opposite
direction - considering the (VACUUM FULL, CLUSTER, REPACK) to be the
prohibitively expensive option for live databases :)

If there is a way to query for current dictionary one can do the
retiring of the locked ones as a lazy background process instead of
one-shot reorg.

So, concretely, where I'd land:

- The two efforts aren't competitors; this one is the TOAST-specific
consumer, yours is the general facility. If pg_encoding_context lands,
the TOAST dictionary catalog is a natural thing to re-express on top of
it, with the column-local lifecycle kept as a TOAST-side policy.

Indeed. I will take a close look at the differences and similarities
of the dictionary stores and see how they would map to each other.

- I'd rather not block this series on that re-expression. The containment
and retirement rules are the reviewed-and-tested core here, and they're
TOAST-shaped;

Yup, I sent a few more findings, but in general it looks good.

rebasing them onto a generic store is a mechanical change
that can happen once the generic store exists and is agreed on.
- I'm happy to review the generic patch with the TOAST case as a concrete
first consumer, and to see whether the multiple-dictionary and
verify-and-drop pieces are better in the common layer than in TOAST.

Does that division make sense to you, or do you see the containment rule
fitting into the generic context after all? That's the piece I can't yet
see clearly.

Absolutely makes sense. Thanks for taking the time to think about this :)

My main takeaway is that we have been spending our focus on different
parts of the same issue and, at least I hoe, there is a large overlap
that can be used at some point to reduce the complexity of similar
features,

--
Cheers
Hannu

#20Manu
manuelreyesbravo@gmail.com
In reply to: Hannu Krosing (#18)

Hi Hannu,

On Thu, Oct 29, 2026 at 11:15 PM Hannu Krosing <hannuk@google.com>
wrote:

(a) R/W ExpandedRecord fast path into non-atomic DO / PROCEDURE:

...

Output:
NOTICE: before: zstd_dict
ERROR: compression dictionary 16592 does not exist

Reproduced on v12, also in a PROCEDURE, and without DROP TABLE when
another session trains a second dictionary and runs VACUUM FULL or
REPACK. My procedure test read the column into a text variable, which
is detoasted on assignment, so it never took this path. The script
fails as is only on a UTF8 database: on SQL_ASCII, length() does not
detoast, so a regression test should use something that reads the
value.

Greg, Muzzammil Sarwar's v1 for that fast path [1]/messages/by-id/CABUcsRRuMHXWqgiZ5wy=4OPbET0niFQEVY_d8VofeumTxjBJjw@mail.gmail.com closes this on
v12 too: v12 marks inline dict datums with ER_FLAG_HAVE_EXTERNAL,
which is what it checks, and all the cases above then pass. So 0004
may not need its own change here.

(b) Indirect TOAST pointers in detoast_external_attr() (detoast.c):

...

(c) SPI_datumTransfer() / datumTransfer():

Both reproduce, from C only: a test function that wraps the raw datum
in an indirect pointer fails in a DO variable and in a WITH HOLD
cursor, and a C procedure fails after SPI_commit(). In core, only
PL/pgSQL calls SPI_datumTransfer().

I will run these on v13.

[1]: /messages/by-id/CABUcsRRuMHXWqgiZ5wy=4OPbET0niFQEVY_d8VofeumTxjBJjw@mail.gmail.com

Manu

#21Greg Burd
greg@burd.me
In reply to: Manu (#17)
#22Hannu Krosing
hannuk@google.com
In reply to: Greg Burd (#21)
#23Greg Burd
greg@burd.me
In reply to: Hannu Krosing (#22)
#24Hannu Krosing
hannuk@google.com
In reply to: Greg Burd (#23)
#25Manu
manuelreyesbravo@gmail.com
In reply to: Greg Burd (#23)
#26Greg Burd
greg@burd.me
In reply to: Hannu Krosing (#24)
#27Hannu Krosing
hannuk@google.com
In reply to: Greg Burd (#26)
#28Greg Burd
greg@burd.me
In reply to: Hannu Krosing (#27)
#29Greg Burd
greg@burd.me
In reply to: Greg Burd (#28)
#30Manu
manuelreyesbravo@gmail.com
In reply to: Greg Burd (#29)
#31Hannu Krosing
hannuk@google.com
In reply to: Greg Burd (#29)
#32Greg Burd
greg@burd.me
In reply to: Hannu Krosing (#31)
#33Hannu Krosing
hannuk@google.com
In reply to: Greg Burd (#32)
#34Greg Burd
greg@burd.me
In reply to: Hannu Krosing (#33)
#35Hannu Krosing
hannuk@google.com
In reply to: Greg Burd (#34)
#36Greg Burd
greg@burd.me
In reply to: Hannu Krosing (#35)
#37Greg Burd
greg@burd.me
In reply to: Greg Burd (#36)