ZSTD TOAST compression, and an extensible compression method encoding
ZSTD TOAST compression, and an extensible compression method encoding
Hi all,
A while back I posted a patch adding zstd as a TOAST compression
method[1]. The main problem with it, and with any new method, is that
the compression method of a compressed varlena is stored in two bits,
and those bits are almost used up: pglz and lz4 take two of the four
values, and TOAST_INVALID_COMPRESSION_ID a third. Taking the last
value for zstd would have made it the last method we could ever add.
Attached is a reworked series, rebased on top of the recent TOAST
changes (varatt_external_oid/oid8, toast_external_data), which first
makes the encoding extensible and then adds zstd as its first user:
0001 Refactor TOAST compression header handling (no behavior change)
0002 Allow more than four TOAST compression methods
0003 Add zstd as a TOAST compression method
Existing on-disk data is not affected by any of them; pglz and lz4
values keep their current representation, bit for bit.
0001: Refactor TOAST compression header handling
------------------------------------------------
Preparatory, with no behavior change, so that 0002 only has to touch
one place for each thing it changes:
- toast_internals.h duplicated the layout of the compressed-in-line
header as toast_compress_header, with TOAST_COMPRESS_* macros to read
and write the tcinfo word, while varatt.h describes the same bytes as
varattrib_4b.va_compressed. The duplicate is removed and the header
is written through one inline function,
toast_compress_set_size_and_method().
- The compression method of an external value was fetched by callers
from the raw bits of va_extinfo. It is now decoded once, in
toast_external_info_get(), into a new compress_method field of
toast_external_data, and detoast_attr_slice(),
toast_get_compression_id() and amcheck read it from there.
- VARTAG_IS_ONDISK() is added next to VARTAG_IS_EXPANDED(), and the
TOAST pointer assembly at the end of toast_save_datum() moves into a
helper, toast_pointer_build().
0002: Allow more than four TOAST compression methods
----------------------------------------------------
The proposal is a "long form" of both the compressed-in-line header
and the on-disk TOAST pointer. The two method bits keep identifying
pglz and lz4 directly; the value 3, VARLENA_COMPRESS_METHOD_LONG, now
means "the method ID is stored in a byte of its own, right after the
fixed part". Value 2 stays unused in those bits.
Compressed-in-line datum:
plain (pglz, lz4) | va_header | va_tcinfo | data ...
long (all others) | va_header | va_tcinfo | va_cmid | data ...
4 bytes 4 bytes 1 byte
va_tcinfo = 30 bits of raw size + 2 method bits:
00 pglz, 01 lz4, 11 long form (see va_cmid), 10 unused
On-disk TOAST pointer (after the usual 2-byte external header):
tag 18 ONDISK_OID | rawsize | extinfo | valueid | toastrelid |
tag 19 ONDISK_OID_LONG | rawsize | extinfo | valueid |
toastrelid | cmid |
tag 4 ONDISK_OID8 | rawsize | extinfo | valueid lo | valueid
hi | toastrelid |
tag 5 ONDISK_OID8_LONG | rawsize | extinfo | valueid lo | valueid
hi | toastrelid | cmid |
So a long-form pointer is 19 or 23 bytes instead of 18 or 22, and the
inline header is 9 bytes instead of 8, for methods other than pglz and
lz4 only. This leaves room for method IDs up to 255.
The inline long form is described by a new struct:
typedef struct
{
uint32 va_header;
uint32 va_tcinfo; /* method bits =
VARLENA_COMPRESS_METHOD_LONG */
uint8 va_cmid; /* compression method ID */
char va_data[FLEXIBLE_ARRAY_MEMBER];
} varattrib_4b_long;
It is deliberately not a member of the varattrib_4b union. A member
with the extra byte pads to 12 bytes and would grow
sizeof(varattrib_4b) from 8, and a lot of code inspects varlena
headers of unknown or smaller size through pointers of that type;
Outside the union the struct's trailing padding is harmless, since
like the rest of varatt.h it is only ever used with offsetof() and
field access, never sizeof(). Two static assertions tie its va_tcinfo
and va_cmid offsets to va_compressed, so the "va_compressed plus one
byte" relationship is checked by the compiler rather than by a
comment.
The pointer side gets no struct at all. Those structs are memcpy'd
whole with sizeof(), and are asserted to have no padding for that
reason; a struct with a trailing uint8 would carry three bytes of
padding that must not reach disk. Instead the long form is "the plain
struct followed by one byte", and toast_external_info_get() decodes it
by reading the fixed part as before and then the byte. Using new tags
rather than a variable-size struct keeps VARTAG_SIZE() a pure function
of the tag, which matters for tuple deforming. The long tags are
their plain counterparts with the low bit set; that detail is confined
to VARTAG_IS_ONDISK_OID(), VARTAG_IS_ONDISK_OID8() and
VARTAG_IS_ONDISK_LONG(), which is what callers use.
Which methods use the long form is decided in exactly one place,
toast_compression_id_needs_cmid_byte(): pglz and lz4 don't, everything
else does.
TOAST_INVALID_COMPRESSION_ID moves from 2 to 3, on purpose equal to
VARLENA_COMPRESS_METHOD_LONG: code that mistakenly interprets the raw
two bits of a long-form value as a method ID gets an invalid ID rather
than a real method. As the method of an external value can no longer
be derived from va_extinfo alone, VARATT_EXTINFO_GET_COMPRESS_METHOD()
is removed in favor of toast_external_data.compress_method.
amcheck learns to verify that the method of an external value is
stored in the pointer form appropriate for it (a plain pointer
claiming a long-form method, or the marker without the long tag, is
reported), and that only compressed values use the long form.
0003: Add zstd as a TOAST compression method
--------------------------------------------
zstd gets ID 2 and is the first user of the long form. It is
available with --with-zstd / -Dzstd; libzstd is already linked into
the backend for WAL compression, so there are no build system changes.
Compression uses ZSTD_compress() at ZSTD_CLEVEL_DEFAULT, without a
dictionary. Slice decompression goes through the streaming API, since
the one-shot API can only decode a whole frame; as for lz4, the whole
compressed value has to be fetched from the TOAST table first, as
there is no way to bound how much compressed input a given prefix
needs.
The patch wires up pg_column_compression(),
default_toast_compression(the built-in default stays lz4 when
available), amcheck, pg_dump, psql's \d+ and tab completion, and the
documentation.
Tests: compression_zstd follows compression_lz4 and skips itself when
the server lacks zstd. It covers inline and external values with both
oid and oid8 value IDs, slices at the start, middle, end and past the
end of a value, values that stay uncompressed (below the TOAST
threshold, or incompressible), bytea/jsonb/arrays, the EXTERNAL, MAIN
and PLAIN storage modes, copying compressed values between tables and
methods in both directions, VACUUM FULL, CLUSTER and a rewriting ALTER
COLUMN TYPE, removal of old TOAST values on UPDATE and DELETE, indexes
on compressed keys, and the GUC. A pg_dump test checks the column
setting survives a dump. Each patch builds and passes the tests on
its own.
Not in this series: a compression level setting, and dictionary
support, which was the motivation for making the ID space large and
would be another method ID using the same long form.
Thanks to Michael Paquier for the TOAST pointer refactoring this
builds on, and for an off-list look at an earlier version.
[1] https://www.postgresql.org/message-id/flat/CAFAfj_HX84EK4hyRYw50AOHOcdVi-%2BFFwAAPo7JHx4aShCvunQ%40mail.gmail.com
--
Nikhil Veldanda
Re: ZSTD TOAST compression, and an extensible compression method encoding
On Mon, Sep 21, 2026 at 07:26:20PM -0700, Nikhil Kumar Veldanda wrote:
> 0001: Refactor TOAST compression header handling
> ------------------------------------------------
>
> Preparatory, with no behavior change, so that 0002 only has to touch
> one place for each thing it changes:
> - toast_internals.h duplicated the layout of the compressed-in-line
> header as toast_compress_header, with TOAST_COMPRESS_* macros to read
> and write the tcinfo word, while varatt.h describes the same bytes as
> varattrib_4b.va_compressed. The duplicate is removed and the header
> is written through one inline function,
> toast_compress_set_size_and_method().
+static varlena *
+toast_pointer_build(vartag_external tag, const void *fixed, Size fixedsize)
Hmm, why not. It is a pattern in two places. You raise it to 4, one
for each vartag.
+++ b/src/include/access/detoast.h
[...]
+#include "access/toast_compression.h"
[...]
+ ToastCompressionId compress_method; /* compression method ID */
So you need this new header dependency due to ToastCompressionId.
Okay.
> - The compression method of an external value was fetched by callers
> from the raw bits of va_extinfo. It is now decoded once, in
> toast_external_info_get(), into a new compress_method field of
> toast_external_data, and detoast_attr_slice(),
> toast_get_compression_id() and amcheck read it from there.
>
> - VARTAG_IS_ONDISK() is added next to VARTAG_IS_EXPANDED(), and the
> TOAST pointer assembly at the end of toast_save_datum() moves into a
> helper, toast_pointer_build().
How about splitting 0001 into a few more pieces, for clarity? It
looks like we could do the removal of toast_compress_header to the new
toast_compress_set_size_and_method() as a change of its own. The
introduction of toast_pointer_build() is a second one. I am not sure
that the new VARTAG_IS_ONDISK() buys us much, we have already too many
of these. Adding compress_method to toast_external_data and reducing
the footprint of VARATT_EXTINFO_GET_COMPRESS_METHOD() would be a third
one.
> 0002: Allow more than four TOAST compression methods
> ----------------------------------------------------
Seems like HEAD disagrees with this one in varatt.h and amcheck.
> So a long-form pointer is 19 or 23 bytes instead of 18 or 22, and the
> inline header is 9 bytes instead of 8, for methods other than pglz and
> lz4 only. This leaves room for method IDs up to 255.
With 8-byte alignment in mind, this does not bother me in heap, be it
for oid-based varlenas or oid8-based varlenas.
> The inline long form is described by a new struct:
> typedef struct
> {
> uint32 va_header;
> uint32 va_tcinfo; /* method bits =
> VARLENA_COMPRESS_METHOD_LONG */
> uint8 va_cmid; /* compression method ID */
> char va_data[FLEXIBLE_ARRAY_MEMBER];
> } varattrib_4b_long;
This is the fundamental part of the change for me. We just have one
bit left that gets redirected to this new "long" flavor, where we have
to pay a penalty of 1 byte to be able to store compression methods
other than pglz and lz4.
> It is deliberately not a member of the varattrib_4b union. A member
> with the extra byte pads to 12 bytes and would grow
> sizeof(varattrib_4b) from 8, and a lot of code inspects varlena
> headers of unknown or smaller size through pointers of that type;
> Outside the union the struct's trailing padding is harmless, since
> like the rest of varatt.h it is only ever used with offsetof() and
> field access, never sizeof(). Two static assertions tie its va_tcinfo
> and va_cmid offsets to va_compressed, so the "va_compressed plus one
> byte" relationship is checked by the compiler rather than by a
> comment.
I guess that's fine by me, on top of my mind. I am wondering if
others have different opinions and/or ideas about these structures?
> 0003: Add zstd as a TOAST compression method
> --------------------------------------------
The backend-side core change goes at 200 lines or so with the two
first refactorings in place, where most of it consists of the full
compression and decompression and slice handling.
> Not in this series: a compression level setting, and dictionary
> support, which was the motivation for making the ID space large and
> would be another method ID using the same long form.
Honestly, I don't care much about the level setting. If really
needed, we could bundle that as a GUC but i really doubt that people
are going to bother about tuning it. The default is usually good
enough, as support for compression of full pages in WAL has
demonstrated over the years.
An integration with dictionaries worry me a lot, because only somewhat
make sense when attached at tuple-level, and they evolve depending on
how zstd see fit. What worries me the most is the amount of work
between the on-disk data and the backend in terms of retention of past
dictionnaries.
--
Michael
Re: ZSTD TOAST compression, and an extensible compression method encoding
Thanks Michael for feedback.
On Wed, Sep 23, 2026 at 11:12 PM Michael Paquier wrote:
>
> +static varlena *
> +toast_pointer_build(vartag_external tag, const void *fixed, Size fixedsize)
>
> Hmm, why not. It is a pattern in two places. You raise it to 4, one
> for each vartag.
Right, that is what made a helper worthwhile: with the long tags it
would otherwise be four copies of the same three lines.
>
> How about splitting 0001 into a few more pieces, for clarity? It
> looks like we could do the removal of toast_compress_header to the new
> toast_compress_set_size_and_method() as a change of its own. The
> introduction of toast_pointer_build() is a second one. I am not sure
> that the new VARTAG_IS_ONDISK() buys us much, we have already too many
> of these. Adding compress_method to toast_external_data and reducing
> the footprint of VARATT_EXTINFO_GET_COMPRESS_METHOD() would be a third
> one.
Done, in that order, in the attached v3:
0001 removes toast_compress_header and the TOAST_COMPRESS_* macros in
favor of the varatt.h accessors and
toast_compress_set_size_and_method().
0002 adds toast_pointer_build().
0003 adds compress_method to toast_external_data and makes the three
callers read it from there.
0004 and 0005 are the format change and zstd, as before.
VARTAG_IS_ONDISK() is gone. With two tags the comparison is fine as
HEAD spells it, so the three refactoring patches no longer touch
varatt.h at all.
0004 adds two VARTAG_IS_* helpers, down from four in v2:
- VARTAG_IS_ONDISK_OID8() is true for the two oid8 tags, plain and
long. toast_external_info_get() uses it to pick the oid8 struct, and
amcheck uses it to compare the tag with the chunk_id type of the TOAST
table.
- VARTAG_IS_ONDISK_LONG() is true for the two long tags. It tells
toast_external_info_get() to read the method byte,
toast_pointer_build() to write it, and amcheck that the value must be
compressed.
Each one compares the tag with its two enum values by name. The
low-bit trick is gone, so the numbering of the long tags next to the
plain ones is only a mnemonic now. VARATT_IS_EXTERNAL_ONDISK() accepts
all four tags, and amcheck's "unexpected TOAST tag" check calls it
instead of keeping its own list.
> > 0002: Allow more than four TOAST compression methods
> > ----------------------------------------------------
>
> Seems like HEAD disagrees with this one in varatt.h and amcheck.
Sorry about that. v2 was generated from a tree that predated
be00f041a33, which touched the two comment lines that the patch edits.
v3 applies on HEAD as of 4545cee303c. While there I fixed a doubled
word that my reflow of the amcheck comment had introduced.
> > The inline long form is described by a new struct:
> > typedef struct
> > {
> > uint32 va_header;
> > uint32 va_tcinfo; /* method bits =
> > VARLENA_COMPRESS_METHOD_LONG */
> > uint8 va_cmid; /* compression method ID */
> > char va_data[FLEXIBLE_ARRAY_MEMBER];
> > } varattrib_4b_long;
>
> This is the fundamental part of the change for me. We just have one
> bit left that gets redirected to this new "long" flavor, where we have
> to pay a penalty of 1 byte to be able to store compression methods
> other than pglz and lz4.
Yes. That is the whole of the format change; the rest of 0004 is
plumbing for it.
> Honestly, I don't care much about the level setting. If really
> needed, we could bundle that as a GUC but i really doubt that people
> are going to bother about tuning it. The default is usually good
> enough, as support for compression of full pages in WAL has
> demonstrated over the years.
Agreed, it stays out. Nothing in the format depends on it, so it can
be added later as a GUC or an attribute option.
> An integration with dictionaries worry me a lot, because only somewhat
> make sense when attached at tuple-level, and they evolve depending on
> how zstd see fit. What worries me the most is the amount of work
> between the on-disk data and the backend in terms of retention of past
> dictionnaries.
I understand that, and this series does not try to answer it. How
dictionaries would be stored, versioned and retired is a separate
design, and I'd rather not touch it until plain zstd is in.
> Michael
--
Nikhil Veldanda
Re: ZSTD TOAST compression, and an extensible compression method encoding
On Thu, Sep 24, 2026 at 04:00:29PM -0700, Nikhil Kumar Veldanda wrote:
> 0001 removes toast_compress_header and the TOAST_COMPRESS_* macros in
> favor of the varatt.h accessors and
> toast_compress_set_size_and_method().
In this one, I got mixed feelings about the addition of the new inline
routine in toast_internals.h while we have already a set of two getter
routines in varatt.h that interact with va_tcinfo, so I have moved an
equivalent to varatt.h. An extra benefit of this move is that we
don't need to include toast_compression.h in toast_internals.h
anymore. Applied the result. Cool cleanup, thanks for that.
> 0002 adds toast_pointer_build().
+static varlena *
+toast_pointer_build(vartag_external tag, const void *fixed, Size fixedsize)
+{
+ varlena *result;
+
+ Assert(tag == VARTAG_ONDISK_OID || tag == VARTAG_ONDISK_OID8);
+ Assert(VARTAG_SIZE(tag) == fixedsize);
+
+ result = (varlena *) palloc(VARHDRSZ_EXTERNAL + VARTAG_SIZE(tag));
+ SET_VARTAG_EXTERNAL(result, tag);
+ memcpy(VARDATA_EXTERNAL(result), fixed, fixedsize);
+
+ return result;
+}
In this one, is there a need for fixedsize at all? We can guess the
size of the target based on the vartag and VARTAG_SIZE(), without
needing an assertion. If this brings any kind of extra protection, I
may have missed it..
Rename *fixed to *ptr? Should this use a VARATT_IS_EXTERNAL_ONDISK()
in the first assertion instead of declaring the two vartags?
> 0003 adds compress_method to toast_external_data and makes the three
> callers read it from there.
/* Compressed attributes should have a valid compression method */
- cmid = VARATT_EXTINFO_GET_COMPRESS_METHOD(toast_ext_data.extinfo);
+ cmid = toast_ext_data.compress_method;
It looks like we could remove VARATT_EXTINFO_GET_COMPRESS_METHOD().
That's kind of tempting..
--
Michael
Re: ZSTD TOAST compression, and an extensible compression method encoding
On Fri, Sep 25, 2026 at 1:04 AM Michael Paquier wrote:
>
> On Thu, Sep 24, 2026 at 04:00:29PM -0700, Nikhil Kumar Veldanda wrote:
> > 0001 removes toast_compress_header and the TOAST_COMPRESS_* macros in
> > favor of the varatt.h accessors and
> > toast_compress_set_size_and_method().
>
> In this one, I got mixed feelings about the addition of the new inline
> routine in toast_internals.h while we have already a set of two getter
> routines in varatt.h that interact with va_tcinfo, so I have moved an
> equivalent to varatt.h. An extra benefit of this move is that we
> don't need to include toast_compression.h in toast_internals.h
> anymore. Applied the result. Cool cleanup, thanks for that.
Thanks. That is a better home for it, and it sets the pattern for the
long form: the format patch now adds
VARDATA_COMPRESSED_SET_TCINFO_LONG() next to
VARDATA_COMPRESSED_SET_TCINFO() in varatt.h, and
toast_compress_datum() picks one or the other based on
toast_compression_id_needs_cmid_byte(). The series does not touch
toast_internals.h at all anymore. One small change to the routine you
committed: its assertion on the method becomes "cmethod <
VARLENA_COMPRESS_METHOD_LONG", since from that patch on the value 3 is
a flag for the long form, not a method.
> > 0002 adds toast_pointer_build().
>
> +static varlena *
> +toast_pointer_build(vartag_external tag, const void *fixed, Size fixedsize)
> +{
> + varlena *result;
> +
> + Assert(tag == VARTAG_ONDISK_OID || tag == VARTAG_ONDISK_OID8);
> + Assert(VARTAG_SIZE(tag) == fixedsize);
> +
> + result = (varlena *) palloc(VARHDRSZ_EXTERNAL + VARTAG_SIZE(tag));
> + SET_VARTAG_EXTERNAL(result, tag);
> + memcpy(VARDATA_EXTERNAL(result), fixed, fixedsize);
> +
> + return result;
> +}
>
> In this one, is there a need for fixedsize at all? We can guess the
> size of the target based on the vartag and VARTAG_SIZE(), without
> needing an assertion. If this brings any kind of extra protection, I
> may have missed it..
Only a cross-check that the struct the caller filled is the one the
tag announces; without it, a mismatch would read four bytes past the
caller's local. With both callers sitting right next to the struct
they fill, that is not worth a parameter. Removed, and the size now
comes from VARTAG_SIZE(). In the format patch the position of the
method byte is derived from it as well, so the helper's inputs are
down to the tag, the struct and the method.
> Rename *fixed to *ptr? Should this use a VARATT_IS_EXTERNAL_ONDISK()
> in the first assertion instead of declaring the two vartags?
>
Both done. VARATT_IS_EXTERNAL_ONDISK() wants a datum rather than a
tag, so the assertion moves after SET_VARTAG_EXTERNAL() and checks the
result. A nice side effect is that the format patch does not need to
touch that assertion when it adds the long tags.
> > 0003 adds compress_method to toast_external_data and makes the three
> > callers read it from there.
>
> /* Compressed attributes should have a valid compression method */
> - cmid = VARATT_EXTINFO_GET_COMPRESS_METHOD(toast_ext_data.extinfo);
> + cmid = toast_ext_data.compress_method;
>
> It looks like we could remove VARATT_EXTINFO_GET_COMPRESS_METHOD().
> That's kind of tempting..
Done in that patch. Once the callers read toast_external_data, the
only user left was toast_external_info_get() itself, which now shifts
the bits directly, and keeping the function around would only invite
code to bypass the struct. The format patch was removing it anyway,
so this just moves it earlier; the comment on
VARATT_EXTINFO_GET_EXTSIZE() points at compress_method instead.
v4 attached, rebased on e27f3b2cad7 and renumbered now that the first
patch is in:
0001 adds toast_pointer_build().
0002 adds compress_method to toast_external_data and removes
VARATT_EXTINFO_GET_COMPRESS_METHOD().
0003 is the format change.
0004 is zstd.
> --
> Michael
--
Nikhil Veldanda
Re: ZSTD TOAST compression, and an extensible compression method encoding
Hi Nikhil,
Thanks for the updated patch set! Looking at patch 4/4, I noticed a minor issue in zstd_compress_datum() regarding the check for incompressible data:
/* data is incompressible so just free the memory and return NULL */
if (len > (size_t) valsize)
{
pfree(tmp);
return NULL;
}
Should this condition be >= instead of >? if (len >= (size_t) valsize)
Reasons:
If len == valsize, the compressed payload alone is already the same size as the uncompressed data. Once VARHDRSZ_COMPRESSED_LONG (9 bytes) is added, the compressed datum is strictly larger than the original. There is no compression benefit here.
If len == valsize, zstd_compress_datum() currently proceeds to call SET_VARSIZE_COMPRESSED() and returns tmp, only for the caller toast_compress_datum() to immediately reject it via if (VARSIZE(tmp) < valsize - 2) and pfree(tmp). Freeing it early and returning NULL saves redundant operations.
This is also consistent with lz4_compress_datum() in the same file:
/*
* If the compressed size is greater than or equal to the raw data size,
* then data is incompressible so just free the memory and return NULL.
*/
if (len >= valsize)
{
pfree(tmp);
return NULL;
}
Re: ZSTD TOAST compression, and an extensible compression method encoding
On Fri, Sep 25, 2026 at 5:35 AM wenhui qiu wrote:
>
> Hi Nikhil,
>
>
> Thanks for the updated patch set! Looking at patch 4/4, I noticed a minor issue in zstd_compress_datum() regarding the check for incompressible data:
>
> /* data is incompressible so just free the memory and return NULL */
> if (len > (size_t) valsize)
> {
> pfree(tmp);
> return NULL;
> }
> Should this condition be >= instead of >? if (len >= (size_t) valsize)
> Reasons:
> If len == valsize, the compressed payload alone is already the same size as the uncompressed data. Once VARHDRSZ_COMPRESSED_LONG (9 bytes) is added, the compressed datum is strictly larger than the original. There is no compression benefit here.
> If len == valsize, zstd_compress_datum() currently proceeds to call SET_VARSIZE_COMPRESSED() and returns tmp, only for the caller toast_compress_datum() to immediately reject it via if (VARSIZE(tmp) < valsize - 2) and pfree(tmp). Freeing it early and returning NULL saves redundant operations.
The check in the compressors is deliberately loose. The real decision
is made once for all methods in toast_compress_datum(), which knows
about the header and the alignment margin and rejects anything that
does not save more than 2 bytes with the header included. So for zstd
every result from len == valsize - 11 upwards is thrown away there.
Changing > to >= in the compressor catches one of those twelve
lengths; the other eleven still take the round trip. To actually
avoid it, each compressor would need a copy of the caller's threshold,
which is what keeping the policy in one place is meant to avoid.
The saving would also be one store and one comparison in a case that
does not happen in practice: zstd's frame overhead means
incompressible input comes out strictly longer than valsize.
> This is also consistent with lz4_compress_datum() in the same file:
>
> /*
> * If the compressed size is greater than or equal to the raw data size,
> * then data is incompressible so just free the memory and return NULL.
> */
> if (len >= valsize)
> {
> pfree(tmp);
> return NULL;
> }
lz4_compress_datum() in master has "if (len > valsize)", unchanged
since bbe0a81db69 added it. The zstd check is a copy of it, so the
two are consistent as they stand.
--
Nikhil Veldanda
Re: ZSTD TOAST compression, and an extensible compression method encoding
Hi, Nikhil
On Fri, 25 Sep 2026 at 02:21, Nikhil Kumar Veldanda wrote:
> On Fri, Sep 25, 2026 at 1:04 AM Michael Paquier wrote:
>>
>> On Thu, Sep 24, 2026 at 04:00:29PM -0700, Nikhil Kumar Veldanda wrote:
>> > 0001 removes toast_compress_header and the TOAST_COMPRESS_* macros in
>> > favor of the varatt.h accessors and
>> > toast_compress_set_size_and_method().
>>
>> In this one, I got mixed feelings about the addition of the new inline
>> routine in toast_internals.h while we have already a set of two getter
>> routines in varatt.h that interact with va_tcinfo, so I have moved an
>> equivalent to varatt.h. An extra benefit of this move is that we
>> don't need to include toast_compression.h in toast_internals.h
>> anymore. Applied the result. Cool cleanup, thanks for that.
>
> Thanks. That is a better home for it, and it sets the pattern for the
> long form: the format patch now adds
> VARDATA_COMPRESSED_SET_TCINFO_LONG() next to
> VARDATA_COMPRESSED_SET_TCINFO() in varatt.h, and
> toast_compress_datum() picks one or the other based on
> toast_compression_id_needs_cmid_byte(). The series does not touch
> toast_internals.h at all anymore. One small change to the routine you
> committed: its assertion on the method becomes "cmethod <
> VARLENA_COMPRESS_METHOD_LONG", since from that patch on the value 3 is
> a flag for the long form, not a method.
>
>> > 0002 adds toast_pointer_build().
>>
>> +static varlena *
>> +toast_pointer_build(vartag_external tag, const void *fixed, Size fixedsize)
>> +{
>> + varlena *result;
>> +
>> + Assert(tag == VARTAG_ONDISK_OID || tag == VARTAG_ONDISK_OID8);
>> + Assert(VARTAG_SIZE(tag) == fixedsize);
>> +
>> + result = (varlena *) palloc(VARHDRSZ_EXTERNAL + VARTAG_SIZE(tag));
>> + SET_VARTAG_EXTERNAL(result, tag);
>> + memcpy(VARDATA_EXTERNAL(result), fixed, fixedsize);
>> +
>> + return result;
>> +}
>>
>> In this one, is there a need for fixedsize at all? We can guess the
>> size of the target based on the vartag and VARTAG_SIZE(), without
>> needing an assertion. If this brings any kind of extra protection, I
>> may have missed it..
>
> Only a cross-check that the struct the caller filled is the one the
> tag announces; without it, a mismatch would read four bytes past the
> caller's local. With both callers sitting right next to the struct
> they fill, that is not worth a parameter. Removed, and the size now
> comes from VARTAG_SIZE(). In the format patch the position of the
> method byte is derived from it as well, so the helper's inputs are
> down to the tag, the struct and the method.
>
>> Rename *fixed to *ptr? Should this use a VARATT_IS_EXTERNAL_ONDISK()
>> in the first assertion instead of declaring the two vartags?
>>
>
> Both done. VARATT_IS_EXTERNAL_ONDISK() wants a datum rather than a
> tag, so the assertion moves after SET_VARTAG_EXTERNAL() and checks the
> result. A nice side effect is that the format patch does not need to
> touch that assertion when it adds the long tags.
>
>> > 0003 adds compress_method to toast_external_data and makes the three
>> > callers read it from there.
>>
>> /* Compressed attributes should have a valid compression method */
>> - cmid = VARATT_EXTINFO_GET_COMPRESS_METHOD(toast_ext_data.extinfo);
>> + cmid = toast_ext_data.compress_method;
>>
>> It looks like we could remove VARATT_EXTINFO_GET_COMPRESS_METHOD().
>> That's kind of tempting..
>
> Done in that patch. Once the callers read toast_external_data, the
> only user left was toast_external_info_get() itself, which now shifts
> the bits directly, and keeping the function around would only invite
> code to bypass the struct. The format patch was removing it anyway,
> so this just moves it earlier; the comment on
> VARATT_EXTINFO_GET_EXTSIZE() points at compress_method instead.
>
> v4 attached, rebased on e27f3b2cad7 and renumbered now that the first
> patch is in:
>
> 0001 adds toast_pointer_build().
> 0002 adds compress_method to toast_external_data and removes
> VARATT_EXTINFO_GET_COMPRESS_METHOD().
> 0003 is the format change.
> 0004 is zstd.
>
In the v4-0001 commit message, it says no behavior change. However, it seems
an Assert introduced after setting vartag.
Since the access/detoast.h include the access/toast_compression.h, should we remove
the access/toast_compression.h in files that already include access/toash.h?
$ grep -rl '#include[[:space:]]*[<"]access/detoast\.h[>"]' . \
| xargs grep -l '#include[[:space:]]*[<"]access/toast_compression\.h[>"]'
./src/backend/access/brin/brin_tuple.c
./src/backend/access/common/toast_compression.c
./src/backend/access/common/detoast.c
./src/backend/access/common/toast_internals.c
./src/backend/utils/adt/varlena.c
./contrib/amcheck/verify_heapam.c
--
Regards,
Japin Li
ChengDu WenWu Information Technology Co., Ltd.
Re: ZSTD TOAST compression, and an extensible compression method encoding
Hi Japin, On Fri, Sep 25, 2026 at 8:25 PM Japin Li wrote: > > In the v4-0001 commit message, it says no behavior change. However, it seems > an Assert introduced after setting vartag. > Fair. The assertion cannot fire (both callers pass a constant tag) and is compiled out without --enable-cassert, but I'll mention it in the commit message next time. > Since the access/detoast.h include the access/toast_compression.h, should we remove > the access/toast_compression.h in files that already include access/toash.h? > I'd keep them. All six files use toast_compression.h symbols directly, and the convention is to include what you use rather than rely on a transitive include (src/tools/pginclude/README). detoast.h includes it for its own field, and e27f3b2cad7 added these includes to exactly these files for the same reason. -- Nikhil Veldanda
Re: ZSTD TOAST compression, and an extensible compression method encoding
Hi Nikhil, > v4 attached, rebased on e27f3b2cad7 and renumbered now that the first > patch is in: I ran some checks and numbers on v4, on master 3c5d9d914fa. Scripts and the full tables are attached. On-disk format. The cover letter says pglz and lz4 values keep their representation bit for bit. Writing the same data with master and with v4, the raw bytes of the inline compressed datums (pageinspect) and of the TOAST chunks hash the same, for pglz and lz4. pg_upgrade from master to v4 keeps every value, and verify_heapam(check_toast) finds nothing. It is also clean on v4 for a column holding pglz, lz4 and zstd values at once, and after VACUUM FULL, UPDATE and DELETE on a zstd table. No slowdown for the existing methods. v4 against master with lz4, paired within each of 6 rounds: the median ratio is between 0.97 and 1.06 for every point, and no point is slower in all rounds. The two rounds with pglz look the same. zstd itself, on -O2 builds, hot cache, 200 MB per case, sizes as a percentage of the raw data (pglz / lz4 / zstd): - SGML docs in 32 kB values: 35.7% / 41.0% / 26.9% - JSON documents in 1 MB values: 12.1% / 18.0% / 4.6% - base64 text in 32 kB values: 102.9% / 102.9% / 77.0% The last one is worth noting: pglz and lz4 get nothing out of base64 or hex text, and zstd saves about a quarter. The cost is on reads of small values. For 50,000 JSON values of 4 kB, reading them all takes 140 ms with zstd against 53 ms with lz4, and a 100-byte prefix costs the same as the whole value (140 ms, against 23 ms with lz4). One thing in 0004 that is easy to improve: zstd_decompress_datum_slice() creates and frees a ZSTD_DCtx for every value. The attached diff keeps one per backend, reset on each use, and uses it in both decompression paths. zstd, 4 rounds, ratio of the diff to v4: - 32 kB values, slice and prefix: 0.66 to 0.77, faster in every round - 32 kB values, full read: 0.87 to 0.89 for docs and base64 - 1 MB base64 values, slice: 0.70 - 4 kB values: 0.94 to 0.97 make check passes with it. At 4 kB the prefix still costs as much as the whole value, so what is left there is per frame, not the context. Regards, Manu
Re: ZSTD TOAST compression, and an extensible compression method encoding
On Fri, Sep 25, 2026 at 10:21:26PM -0700, Nikhil Kumar Veldanda wrote: > On Fri, Sep 25, 2026 at 8:25 PM Japin Li wrote: >> In the v4-0001 commit message, it says no behavior change. However, it seems >> an Assert introduced after setting vartag. > > Fair. The assertion cannot fire (both callers pass a constant tag) > and is compiled out without --enable-cassert, but I'll mention it in > the commit message next time. I'm not really sure that this is worth mentioning at all. You can qualify that as a "change" because it adds one line, yes, but it's just here to make sure that nobody does something stupid with the new routine introduced by v4-0001, and the code is still the same as the original version, just de-duplicated. Applied this one. >> Since the access/detoast.h include the access/toast_compression.h, should we remove >> the access/toast_compression.h in files that already include access/toash.h? > > I'd keep them. All six files use toast_compression.h symbols > directly, and the convention is to include what you use rather than > rely on a transitive include (src/tools/pginclude/README). detoast.h > includes it for its own field, and e27f3b2cad7 added these includes to > exactly these files for the same reason. Hmm. I'd say that this depends. Cleanups of dependencies in .h files are usually kind of nice, because it shows a cleaner chain of dependencies at header level. If you'd like to suggest a patch, please feel free. I am not sure how much this is worth it without looking at some code shaping your idea. -- Michael
Re: ZSTD TOAST compression, and an extensible compression method encoding
Thanks for the clarification! You are completely right about the caller threshold
policy in toast_compress_datum() and the zstd frame overhead, and my apologies
for misquoting lz4_compress_datum(). Keeping the compressors loose and
centralizing the storage policy makes total sense.
While studying the patch series further, I noticed a few technical points
regarding error handling, extensibility, and edge-case slicing that might be
worth looking into:
1. Potential slice-fetch length mismatch in detoast.c (Patch 3/4)
In detoast.c, toast_fetch_datum_slice() accounts for the compressed header
overhead with:
if (VARATT_EXTERNAL_IS_COMPRESSED(toast_pointer) && slicelength > 0)
slicelength = slicelength + sizeof(int32);
For plain compressed datums (pglz/lz4), the header in chunk 0 is va_tcinfo
(4 bytes). But for the long-form encoding introduced in patch 3, toast_save_datum()
stores va_tcinfo (4 bytes) PLUS va_cmid (1 byte), totaling 5 bytes
(VARHDRSZ_COMPRESSED_LONG - VARHDRSZ).
Currently, detoast_attr_slice() fetches the entire external datum for lz4 and zstd
so the length is clamped at attrsize, but if toast_fetch_datum_slice() is used
to fetch a true slice of a long-form external datum, hardcoding sizeof(int32)
would result in fetching 1 byte short of the payload.
Should this instead be computed based on VARTAG_IS_ONDISK_LONG(toast_pointer)?
Size hdrsize = VARTAG_IS_ONDISK_LONG(toast_ext_data.tag) ?
(VARHDRSZ_COMPRESSED_LONG - VARHDRSZ) :
(VARHDRSZ_COMPRESSED - VARHDRSZ);
slicelength += hdrsize;
2. Assertion failure during amcheck on corrupted on-disk datums (Patch 3)
In detoast.h, toast_external_info_get() has:
if (VARTAG_IS_ONDISK_LONG(toast_ext_data->tag))
{
uint8 cmid;
Assert(toast_ext_data->compress_method == VARLENA_COMPRESS_METHOD_LONG);
memcpy(&cmid, ptr + fixedsize, sizeof(cmid));
toast_ext_data->compress_method = (ToastCompressionId) cmid;
}
Because amcheck calls toast_external_info_get() to verify disk tuples, if an on-disk
datum is corrupted such that the tag is LONG but the va_extinfo bits were corrupted
to something else, an assert-enabled build will crash with AssertionFailed instead of
letting amcheck catch and report the corruption.
In contrast, VARDATA_COMPRESSED_GET_COMPRESS_METHOD() in varatt.h uses a non-asserting
"if (method == VARLENA_COMPRESS_METHOD_LONG)". Perhaps toast_external_info_get()
should do the same and set compress_method to TOAST_INVALID_COMPRESSION_ID on mismatch?
3. Hardcoded method enum in toast_save_datum() (Patch 3 & 4)
In toast_internals.c:
Assert(cmid == TOAST_PGLZ_COMPRESSION_ID ||
cmid == TOAST_LZ4_COMPRESSION_ID ||
cmid == TOAST_ZSTD_COMPRESSION_ID);
if (toast_compression_id_needs_cmid_byte(cmid))
Since the goal of patch 3 was to allow extensible compression methods without
hardcoding IDs across toast internals, should this assert simply be:
Assert(cmid != TOAST_INVALID_COMPRESSION_ID);
which matches the asserts in toast_compress_datum() and toast_pointer_build()?
4. Defensive underflow guard for VARSIZE in zstd_decompress_datum() (Patch 4)
In zstd_decompress_datum():
rawsize = ZSTD_decompress(VARDATA(result),
VARDATA_COMPRESSED_GET_EXTSIZE(value),
(const char *) value + VARHDRSZ_COMPRESSED_LONG,
VARSIZE(value) - VARHDRSZ_COMPRESSED_LONG);
Unlike LZ4_decompress_safe() where the compressed size argument is a signed int
(which immediately returns error if negative), ZSTD_decompress() takes size_t
(unsigned). If a corrupted on-disk datum has VARSIZE(value) < VARHDRSZ_COMPRESSED_LONG,
this underflows to a massive unsigned value, which could cause ZSTD_decompress()
to read out of bounds. Adding a check for VARSIZE(value) < VARHDRSZ_COMPRESSED_LONG
before calling ZSTD_decompress() would be safer.
5. Decompressed size verification in zstd_decompress_datum() (Patch 4)
ZSTD_decompress() only returns an error if dstCapacity is too small; if the frame
decompresses to fewer bytes than dstCapacity (the recorded extsize), it returns the
smaller size without error.
To protect against corrupted or truncated streams, should we also verify that
the decompressed size matches the recorded external size?
if (ZSTD_isError(rawsize) || rawsize != (size_t) VARDATA_COMPRESSED_GET_EXTSIZE(value))
ereport(ERROR, ...);
Thanks again for driving this work!
Re: ZSTD TOAST compression, and an extensible compression method encoding
On Sat, Sep 26, 2026 at 12:25 PM Manu wrote: > > Hi Nikhil, > > > v4 attached, rebased on e27f3b2cad7 and renumbered now that the first > > patch is in: > > I ran some checks and numbers on v4, on master 3c5d9d914fa. Scripts > and the full tables are attached. > > On-disk format. The cover letter says pglz and lz4 values keep their > representation bit for bit. Writing the same data with master and > with v4, the raw bytes of the inline compressed datums (pageinspect) > and of the TOAST chunks hash the same, for pglz and lz4. pg_upgrade > from master to v4 keeps every value, and verify_heapam(check_toast) > finds nothing. It is also clean on v4 for a column holding pglz, lz4 > and zstd values at once, and after VACUUM FULL, UPDATE and DELETE on > a zstd table. > Thanks a lot for checking both, and for the scripts. Those are the two things the format patch must not break. > The cost is on reads of small values. For 50,000 JSON values of > 4 kB, reading them all takes 140 ms with zstd against 53 ms with lz4, > and a 100-byte prefix costs the same as the whole value (140 ms, > against 23 ms with lz4). > The prefix part comes from the format: a zstd block holds up to 128 kB and can only be decoded whole, so for any smaller value a prefix is a full decode. v7 has a comment saying so above the slice loop. > One thing in 0004 that is easy to improve: > zstd_decompress_datum_slice() creates and frees a ZSTD_DCtx for every > value. The attached diff keeps one per backend, reset on each use, > and uses it in both decompression paths. zstd, 4 rounds, ratio of > the diff to v4: > I agree reusing the contexts is worth doing; zstd itself recommends it, and ZSTD_compress() allocates one per call too, so the write side would gain as well. For this series I'd rather stay with what the tree already does: the WAL code uses the one-shot ZSTD_compress() and ZSTD_decompress() calls, and 0003 matches that. A context kept for the backend's lifetime also brings its own questions (how much memory it may keep, and when to release it), which I'd rather settle separately than attach to the format change. So I'll propose it as a follow-up once this series is in, starting from your diff and your numbers, if that works for you. > > Regards, > Manu -- Nikhil Veldanda
Re: ZSTD TOAST compression, and an extensible compression method encoding
On Mon, Sep 28, 2026 at 3:01 AM wenhui qiu wrote:
>
> HI Nikhil
>>
>>
>> Thanks for the clarification! You are completely right about the caller threshold
>> policy in toast_compress_datum() and the zstd frame overhead, and my apologies
>> for misquoting lz4_compress_datum(). Keeping the compressors loose and
>> centralizing the storage policy makes total sense.
No problem, thanks for looking again.
>> 1. Potential slice-fetch length mismatch in detoast.c (Patch 3/4)
>> In detoast.c, toast_fetch_datum_slice() accounts for the compressed header
>> overhead with:
>> if (VARATT_EXTERNAL_IS_COMPRESSED(toast_pointer) && slicelength > 0)
>> slicelength = slicelength + sizeof(int32);
>> For plain compressed datums (pglz/lz4), the header in chunk 0 is va_tcinfo
>> (4 bytes). But for the long-form encoding introduced in patch 3, toast_save_datum()
>> stores va_tcinfo (4 bytes) PLUS va_cmid (1 byte), totaling 5 bytes
>> (VARHDRSZ_COMPRESSED_LONG - VARHDRSZ).
>> Currently, detoast_attr_slice() fetches the entire external datum for lz4 and zstd
>> so the length is clamped at attrsize, but if toast_fetch_datum_slice() is used
>> to fetch a true slice of a long-form external datum, hardcoding sizeof(int32)
>> would result in fetching 1 byte short of the payload.
>> Should this instead be computed based on VARTAG_IS_ONDISK_LONG(toast_pointer)?
Yes. It can't happen today because only pglz fetches a true prefix
and pglz never uses the long form, but the code shouldn't depend on
that. Fixed in the format patch: the header size now follows the tag.
>> 2. Assertion failure during amcheck on corrupted on-disk datums (Patch 3)
>> In detoast.h, toast_external_info_get() has:
>> if (VARTAG_IS_ONDISK_LONG(toast_ext_data->tag))
>> {
>> uint8 cmid;
>> Assert(toast_ext_data->compress_method == VARLENA_COMPRESS_METHOD_LONG);
>> memcpy(&cmid, ptr + fixedsize, sizeof(cmid));
>> toast_ext_data->compress_method = (ToastCompressionId) cmid;
>> }
>> Because amcheck calls toast_external_info_get() to verify disk tuples, if an on-disk
>> datum is corrupted such that the tag is LONG but the va_extinfo bits were corrupted
>> to something else, an assert-enabled build will crash with AssertionFailed instead of
>> letting amcheck catch and report the corruption.
>> In contrast, VARDATA_COMPRESSED_GET_COMPRESS_METHOD() in varatt.h uses a non-asserting
>> "if (method == VARLENA_COMPRESS_METHOD_LONG)". Perhaps toast_external_info_get()
>> should do the same and set compress_method to TOAST_INVALID_COMPRESSION_ID on mismatch?
Yes. I reproduced it by clearing the method bits of a long pointer on
disk, the kind of damage src/bin/pg_amcheck/t/004_verify_heapam.pl
injects to check that amcheck reports corruption without crashing. An
assert-enabled build then hits TRAP: failed Assert(...) in
verify_heapam(); a production build doesn't crash, but reads the
method byte anyway and reports nothing. Fixed as you suggest: a
mismatch now decodes as TOAST_INVALID_COMPRESSION_ID, and amcheck
reports "toast value 16399 has invalid compression method id 3", the
same way it already reports a plain pointer whose bits hold 0b11.
>> 3. Hardcoded method enum in toast_save_datum() (Patch 3 & 4)
>> In toast_internals.c:
>> Assert(cmid == TOAST_PGLZ_COMPRESSION_ID ||
>> cmid == TOAST_LZ4_COMPRESSION_ID ||
>> cmid == TOAST_ZSTD_COMPRESSION_ID);
>> if (toast_compression_id_needs_cmid_byte(cmid))
>> Since the goal of patch 3 was to allow extensible compression methods without
>> hardcoding IDs across toast internals, should this assert simply be:
>> Assert(cmid != TOAST_INVALID_COMPRESSION_ID);
>> which matches the asserts in toast_compress_datum() and toast_pointer_build()?
I'd keep the list. Master already lists pglz and lz4 there. Unlike
in toast_compress_datum(), where cmid comes from the switch just
above, here it is read from the datum, so the list also catches values
that are not methods at all, which "!= INVALID" would let through. A
new method missing from it fails its first test, so it can't go stale.
The format patch is about deciding the pointer form in one place, not
about never naming methods; the dispatch switches and amcheck name
them too.
>> 4. Defensive underflow guard for VARSIZE in zstd_decompress_datum() (Patch 4)
>> In zstd_decompress_datum():
>> rawsize = ZSTD_decompress(VARDATA(result),
>> VARDATA_COMPRESSED_GET_EXTSIZE(value),
>> (const char *) value + VARHDRSZ_COMPRESSED_LONG,
>> VARSIZE(value) - VARHDRSZ_COMPRESSED_LONG);
>> Unlike LZ4_decompress_safe() where the compressed size argument is a signed int
>> (which immediately returns error if negative), ZSTD_decompress() takes size_t
>> (unsigned). If a corrupted on-disk datum has VARSIZE(value) < VARHDRSZ_COMPRESSED_LONG,
>> this underflows to a massive unsigned value, which could cause ZSTD_decompress()
>> to read out of bounds. Adding a check for VARSIZE(value) < VARHDRSZ_COMPRESSED_LONG
>> before calling ZSTD_decompress() would be safer.
Agreed, added to both zstd decompressors. pglz and lz4 get away with
it because they take a signed size.
>> 5. Decompressed size verification in zstd_decompress_datum() (Patch 4)
>> ZSTD_decompress() only returns an error if dstCapacity is too small; if the frame
>> decompresses to fewer bytes than dstCapacity (the recorded extsize), it returns the
>> smaller size without error.
Not quite. A zstd datum records its uncompressed size twice: in our
header (va_tcinfo) and in the zstd frame header, which ZSTD_compress()
always fills in. zstd checks its own copy: a truncated frame, or one
that decodes to a different length than it records, is an error.
Checked against libzstd 1.5.7, a frame cut by one byte fails with "Src
size is incorrect", and one whose recorded size I raised fails with
"Data corruption detected".
>> To protect against corrupted or truncated streams, should we also verify that
>> the decompressed size matches the recorded external size?
Yes, because zstd never sees our copy of the size: we only pass it as
dstCapacity, and a destination larger than needed is not an error. So
if our header claims more than the frame holds, zstd returns the real
data without complaint, and the mismatch goes unnoticed.
That has visible effects. In a manual test (not part of the patch), I
raised the size in the header of an inline 3450-byte zstd datum from
3450 to 3460 in the heap file, leaving the frame alone. Without the
check, the value reads back as the correct 3450 bytes, yet "v = " returns false: texteq() compares lengths first, via
toast_raw_datum_size(), which for a compressed datum takes the size
from our header without decompressing. With the check, the read fails
with "compressed zstd data is corrupt" instead. pglz already does the
same, through check_complete; lz4 doesn't. The slice path can't check
this, since it stops before the end by design.
v7 attached
--
Nikhil Veldanda
Re: ZSTD TOAST compression, and an extensible compression method encoding
On Mon, Sep 28, 2026 at 10:39:42PM -0700, Nikhil Kumar Veldanda wrote: > v7 attached I was just looking at v7-0001 that wants to add the ToastCompressionId to toast_external_data, and this feels half-baked due to the inconsistency this brings with extsize and VARATT_EXTINFO_GET_EXTSIZE. Couldn't we do better here by normalizing more data from the existing fields? Another could be the is_compressed state which is guessed from a comparison between the raw size and the compressed size, perhaps? Regarding v7-0002 and v7-0003, I am doubting the wisdom of tackling the last-compression-bit issue for this release. The OID8 code has already changed a lot of code, and maybe we should be conservative in terms of the amount of the changes we do in this area for a single release. By that, I mean to catch up on the refactoring pieces on this thread once some dust has settled on HEAD and tackle this issue around the time v21 opens up (Aka I'm preparing myself for these dozens of agents to complain about the shape of the code already committed, we'll see how it goes). -- Michael
Re: ZSTD TOAST compression, and an extensible compression method encoding
Hi everyone I have been working on a more generic approach to compression and similar encoding/decoding tasks I have put my current thinking on this in https://wiki.postgresql.org/wiki/Pg_encoding_context This is meant to provide generic support functionality for things like compression dictionaries for zstd and lz4, Avro schemas, huffman tables and vector quanttization base data to name a few I appreciate any feedback on the approach --- Hannu On Wed, Sep 30, 2026 at 8:20 AM Michael Paquier wrote: > > On Mon, Sep 28, 2026 at 10:39:42PM -0700, Nikhil Kumar Veldanda wrote: > > v7 attached > > I was just looking at v7-0001 that wants to add the ToastCompressionId > to toast_external_data, and this feels half-baked due to the > inconsistency this brings with extsize and VARATT_EXTINFO_GET_EXTSIZE. > > Couldn't we do better here by normalizing more data from the existing > fields? Another could be the is_compressed state which is guessed > from a comparison between the raw size and the compressed size, > perhaps? > > Regarding v7-0002 and v7-0003, I am doubting the wisdom of tackling > the last-compression-bit issue for this release. The OID8 code has > already changed a lot of code, and maybe we should be conservative in > terms of the amount of the changes we do in this area for a single > release. By that, I mean to catch up on the refactoring pieces on > this thread once some dust has settled on HEAD and tackle this issue > around the time v21 opens up (Aka I'm preparing myself for these > dozens of agents to complain about the shape of the code already > committed, we'll see how it goes). > -- > Michael
Re: ZSTD TOAST compression, and an extensible compression method encoding
Hi Michael, Nikhil,
> I was just looking at v7-0001 that wants to add the ToastCompressionId
> to toast_external_data, and this feels half-baked due to the
> inconsistency this brings with extsize and VARATT_EXTINFO_GET_EXTSIZE.
>
> Couldn't we do better here by normalizing more data from the existing
> fields? Another could be the is_compressed state which is guessed
> from a comparison between the raw size and the compressed size,
> perhaps?
Looking closely at v7-0001 with this in mind, I completely agree. Once we
introducing toast_external_data to decouple callers from the low-level on-disk
representation, keeping extsize and is_compressed as raw macro calculations
for callers to repeat leaves the abstraction half-baked.
In fact, there is an even stronger argument for normalizing is_compressed
here: currently, when an external datum is uncompressed, the high 2 bits of
va_extinfo are zero (since payload size < 1GB). If a caller inspects
toast_ext_data.compress_method without manually checking
VARATT_EXTINFO_IS_COMPRESSED() first, they end up seeing 0
(TOAST_PGLZ_COMPRESSION_ID) instead of an invalid ID.
If we normalize both extsize and is_compressed inside toast_external_info_get(),
we can explicitly enforce:
```
typedef struct toast_external_data
{
vartag_external tag;
int32 rawsize;
int32 extsize; /* unpacked external payload size */
bool is_compressed; /* true if extsize < rawsize - VARHDRSZ */
ToastCompressionId compress_method; /* valid only if is_compressed */
Oid8 valueid;
Oid toastrelid;
uint32 extinfo; /* preserved raw bits */
} toast_external_data;
And in toast_external_info_get():
toast_ext_data->extsize = toast_ext_data->extinfo & VARLENA_EXTSIZE_MASK;
toast_ext_data->is_compressed =
(toast_ext_data->extsize < toast_ext_data->rawsize - VARHDRSZ);
if (toast_ext_data->is_compressed)
{
/* resolve compress_method, handling long form if tag demands */
...
}
else
toast_ext_data->compress_method = TOAST_INVALID_COMPRESSION_ID;
```
I checked the codebase: doing this cleans up repetitive calls to VARATT_EXTINFO_GET_EXTSIZE() and VARATT_EXTINFO_IS_COMPRESSED() across at least 11 sites in detoast.c, toast_internals.c, amcheck, and reorderbuffer.c. It makes the whole subsystem much cleaner.
Regarding v7-0002 and v7-0003, I am doubting the wisdom of tackling the last-compression-bit issue for this release. The OID8 code has already changed a lot of code, and maybe we should be conservative in terms of the amount of the changes we do in this area for a single release. By that, I mean to catch up on the refactoring pieces on this thread once some dust has settled on HEAD and tackle this issue around the time v21 opens up
From a release management standpoint, taking a conservative stance here makes total sense. The OID8 expansion was a major physical storage milestone, and avoided simultaneous churn on on-disk TOAST pointer formats right after it minimized risk to HEAD.
At the same time, I want to thank Nikhil for the great work on v7: having re-reviewed the patch series against latest HEAD (commit 45277ca0d1c) and verified it locally, all edge cases previously discussed (the slice fetch offset calculation, amcheck assertion guards on corrupt pointers, unsigned underflow checks, and header size verification) are cleanly resolved, and the entire test suite passes without issues.
Given that, I think splitting the timeline as Michael suggested is the best path forward:
Enhance 0001 into a standalone, fully-normalized toast_external_data refactoring and commit it in the current cycle. It carries zero on-disk format changes and strictly improves the codebase.
Hold 0002 and 0003 until HEAD settles and v21 opens up. Since 0002/0003 are already technically solid, having a fully-normalized toast_external_data in place now will make landing the long-form format and zstd in v21 remarkably straightforward.
Nikhil, what do you think about updating 0001 along these lines for a v8?
Best regards
Re: ZSTD TOAST compression, and an extensible compression method encoding
Hi Nikhil, I've been reviewing v7 and it looks solid to me. Full disclosure: Nikhil and I work together at AWS and used to be on the same team, which is where this patch set started, so I'm a fan and also biased. So, I applied v7 to master as of 54635e6892f and everything worked as expected. Two points on v7: 0001: For an external value that isn't compressed, the new compress_method field comes back as 0, which happens to mean pglz. Anyone who reads the field without first checking VARATT_EXTINFO_IS_COMPRESSED() will think the value is pglz-compressed. I'd have toast_external_info_get() fill in the size and the compressed flag as well, and set compress_method to TOAST_INVALID_COMPRESSION_ID when there's no compression. That's essentially what Michael and wenhui suggested, and it would make 0001 useful on its own this cycle. 0003: You held off on Manu's context reuse because the WAL code used the one-shot zstd calls. That's no longer true: Michael's 857340b0263 and ce3387b74b7 made WAL keep its zstd contexts for the life of the backend. Given Manu's numbers (slices 23-34% faster, full reads of 32kB values 11-13% faster), I'd fold something similar to his change into 0003. I know, I know... but why not talk about them? Dictionaries ------------ You and Michael have both put dictionaries out of scope until plain zstd is in, and that is the right order for commits. Michael's concern upthread still stands: > What worries me the most is the amount of work between the on-disk > data and the backend in terms of retention of past dictionnaries. The first thread stopped on the same problem. Robert's objections to v11's pg_depend tracking [1], Andres's point about undroppable dictionaries accumulating [2], and the per-insert cost of v13's flatten_datum [3] were deferred rather than answered. 0002 spends the last free value of the method bits on the grounds that dictionary support would be another method ID in the long form. It seems worth showing before 0002 lands that a dictionary method with a workable lifecycle fits that form. The attached v20261015-0004 is a patch on top of v7 that does that, following Robert's suggestion in [4]: dictionary-compressed datums exist only in the column that owns the dictionary, and are decompressed whenever they would be stored anywhere else. 0001-0003 of the attached series are your v7, unchanged apart from the rebase onto aa7b9cf132b. Ownership. A new catalog, pg_toast_dictionary (oid, tdrelid, tdattnum, tdcurrent, tddict), whose rows belong to one column as pg_statistic rows do. DROP TABLE removes them, next to RemoveStatistics(). DROP COLUMN does not: the dropped column's values remain in the heap, and whole-row references and REPLICA IDENTITY FULL still read them, until the next rewrite retires the dictionaries. There are no pg_depend entries. Containment. heap_fill_tuple() sets HEAP_HASEXTERNAL on a tuple holding a zstd_dict datum, as it does for a TOAST pointer. Every path that already flattens such tuples (toast_flatten_tuple() and its variants, expanded records, the catcache, heap_update()'s need_toast) therefore reaches the datum, and detoast_external_attr() decompresses it. The few places that test VARATT_IS_EXTERNAL() on a single datum (index_form_tuple, brin_form_tuple, tstoreReceiver, PL/pgSQL non-atomic assignment) also test VARATT_IS_COMPRESSED_DICT(). On store, toast_tuple_init() keeps a zstd_dict datum compressed only if the target column owns the dictionary and the dictionary is current; otherwise it decompresses it and the target column's method applies. Values compressed with pglz, lz4 or plain zstd are copied as before, so the CTAS slowdown seen with v13's flatten_datum applies only when the source column uses a dictionary. Retirement. pg_train_toast_dictionary(rel, col, dict_size) trains from the column's values and makes the new dictionary current; the previous one stays readable. The next rewrite (VACUUM FULL, CLUSTER, REPACK, or a rewriting ALTER TABLE) recompresses values that use a non-current dictionary, and finish_heap_swap() then deletes it. Dictionaries of a column switched to another method, or dropped, are retired the same way. Rewrites already hold AccessExclusiveLock. Training takes ShareUpdateExclusiveLock, as ANALYZE does. Upgrade. pg_upgrade keeps the heap files, which embed dictionary OIDs, so binary-upgrade dumps restore each dictionary with its OID and physical column number, including those of switched or dropped columns that have not been rewritten yet. On disk, a zstd_dict datum is the v7 long header plus the dictionary OID: va_header | va_tcinfo (method bits 11) | va_cmid = 4 | dictid | frame so 0002 needs no change for it. I've not yet toyed with the following, maybe you have ideas? - Training is an explicit call over the first 10000 rows. Training from ANALYZE's sample is the natural next step. - toast_dictionary_current() does an index probe per compressed value, and the CDict/DDict cache holds one entry each way. Both can move to the relcache entry if profiling shows a need. - Prefix slices of dictionary values decode the whole value, which costs nothing extra below zstd's 128kB block size. - No compression level setting. Hannu's encoding-context proposal [5] is broader. I'd expect the ownership and containment rules here to apply to it as well. If this matches what you had in mind for dictionaries, I'd suggest carrying it as a later patch in your series, so the long-form discussion has a concrete dictionary user to point at. I can rebase it on v8. best. -greg [1] https://postgr.es/m/CA+Tgmob1Ux7R2_0mbZmTbsVmUda04X1AdHGjpu6FkZfdbztugQ@mail.gmail.com [2] https://postgr.es/m/wjrd7ubqm4sq6t4ddv2ae7xaf26vcf4z6i7nftag3e6zexqmyc@yjilk5fsqcfh [3] https://postgr.es/m/CAFAfj_Fee7zQ7YNnJObLMqVF=MpFwVHszzPJ-ZWkiiade04SAw@mail.gmail.com [4] https://postgr.es/m/CA+TgmoY8uCKFvVYDQsLbfhY3JYrduXE7WHi75hmfTWxjWioaaw@mail.gmail.com [5] https://wiki.postgresql.org/wiki/Pg_encoding_context
Re: ZSTD TOAST compression, and an extensible compression method encoding
Hi Greg, > Given Manu's numbers [...] I'd fold something similar to his change > into 0003. Thanks for picking this back up, and for tying it to Michael's 857340b0263 / ce3387b74b7 -- that's the precedent the reuse was waiting on. I re-measured the ZSTD_DCtx reuse on v7 (over 54635e6892f). September holds: on 32 kB values slice and prefix are 0.62-0.75 of v7, full read 0.86-0.87 (json stays ~1.0), random 1 MB slice 0.67, and 4 kB 0.92-0.98. Compression is unchanged. make check passes (240 tests) in -O2 and under cassert+ASan. Attached (nocfbot-v7-0003-con-dctx-reuse.patch.txt) is your 0003 with the reuse folded in -- Nikhil still the author; against the current 0003 it only touches toast_compression.c, and the commit message notes Michael's two commits. The one thing worth checking on a long-lived context is the reset at the start of each use. I corrupted a block header mid-frame: the decode fails with "compressed zstd data is corrupt" and every later read is correct, for full and slice and after a rollback. A mutant without the reset fails -- after an errored slice every later slice errors, and after an early-cut prefix another value's slice returns wrong data with no error. Memory stays ~160 kB for 32 kB slices, at most ~2.5 MiB after large slices (the default window cap), and zstd shrinks it back itself. On scope: Michael ties the WAL's decompression context to the XLogReaderState that owns WAL decoding; detoast has no such owner, so the backend is the natural scope. Same pattern, scope per subsystem. This is independent of your 0004 dict_dctx. One note: the comment in 0004 about moving its slice to the streaming loop would need the same reset -- the mutant above shows why. Regards, Manu
Re: ZSTD TOAST compression, and an extensible compression method encoding
Hi Manu, Thanks for the integrated 0003 and the evidence file. I went through the change and re-ran the parts that matter on a few differently shaped hosts I have at home with v7 and your 0003 side by side on 54635e6892f. Re: reset, I took your point that it is what makes the reuse safe and checked it without any corruption: in one backend, take a 10-byte prefix of one 600kB value, then a 300kB slice of another. v7 and your 0003 both return the right bytes. With the ZSTD_DCtx_reset() call removed, every slice after the prefix fails with "compressed zstd data is corrupt", while full reads stay correct. I didn't reproduce the silent wrong-data case you saw, only the false error, but either is reason enough. An error on a corrupted value, inside a savepoint or not, left later reads correct with the reset in place. Speed, -O2, six rounds alternating builds, time with reuse over v7: 32kB values, 100-byte prefix 0.62 32kB values, slice at 10kB 0.62 32kB values, full read 0.96 4kB values, 100-byte prefix 0.66 1MB values, slice at 500kB 0.99 So it matches your numbers for slices and prefixes. Full reads gain less here than in yours, which I'd put down to my data compressing less well. ZSTD_sizeof_DCtx() gives 96kB for a fresh context, unchanged after one-shot reads, and 1.2MB after a 300kB slice of a 1MB value, also in line with what you measured. I folded it into 0003 for v8, attached, with you as Co-authored-by. Besides your change, 0003 now differs from v7 only in two places: - The comment above zstd_dctx says the reset is required rather than an optimization, and that anything else using the context has to go through zstd_get_dctx(). It explains why the scope is the backend (detoasting has no owner like the XLogReaderState that ce3387b74b7 uses), and it notes that zstd allocates the context with malloc(), so its memory doesn't show in pg_backend_memory_contexts. I expect a reviewer to ask about the last point first. - The commit message says the same things briefly, and gives the speedup. In 0004, the comment that suggested moving dictionary prefixes to the streaming loop now says that dict_dctx would then need the same reset before each use, and why. As you pointed out, the one-shot call it uses today doesn't need one. v8 is on master as of 45fc51fcbf4: 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 (now with context reuse) 0004 Add zstd compression dictionaries with a column-local lifecycle 0001 and 0002 are v7 unchanged. Each patch builds on its own with -Werror, cassert and injection points, and passes the regression tests. check-world on 0004 passes (387 tests, none failed), and so does a build without zstd. Nikhil, the first three are still yours; I only rebased them and added Manu's change to 0003. I hope to see you rejoin the conversation and lead the development again. best. -greg
Re: ZSTD TOAST compression, and an extensible compression method encoding
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 . Regards, Manu
Re: ZSTD TOAST compression, and an extensible compression method encoding
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] 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]. Michael took that direction for the Oid8 work [3], and it is now
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], and Dharin's second
version did that with an external-only VARTAG_ONDISK_ZSTD [5]. 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]; I'm raising it here so the earlier preference isn't
overlooked.
- Peter asked for numbers [7]. For compression ratio, Dharin measured
170MB of mixed data at 22MB with zstd against 36MB with pglz or lz4
[5], and Nikhil's tweet data set in the first thread gave 210MB with
zstd against 259MB pglz and 297MB lz4, or 114MB with a dictionary
[8]. For speed, your and my numbers on context reuse are earlier in
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] https://postgr.es/m/CAOj6k6dy2CRVA6Lsb5N59zE-7KNVKt=oYwWyg8ULK8zOOY8e7A@mail.gmail.com
[2] https://postgr.es/m/CAOj6k6dEVi0NvLjMLDhyrJS_n_NZO5D_OU89AO1u53u6NCDDwQ@mail.gmail.com
[3] https://postgr.es/m/aW8keI6WZxywRQIt@paquier.xyz
[4] https://postgr.es/m/aUOgmypuun0rc2xO@paquier.xyz
[5] https://postgr.es/m/CAOj6k6f2B3hNxDcnB5AgHX4kaTW8XTAfMAjRx4upDBOugxqF4w@mail.gmail.com
[6] https://postgr.es/m/arS_NVVZZ2XsfCYU@paquier.xyz
[7] https://postgr.es/m/4c70b0f6-5aba-464c-b145-464a620c1222@eisentraut.org
[8] https://postgr.es/m/CAFAfj_GACKVftwuRjy3Ls-1Xc3ojUUbVh=Rm7KpRuYbaS=uLPg@mail.gmail.com
Re: ZSTD TOAST compression, and an extensible compression method encoding
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
Re: ZSTD TOAST compression, and an extensible compression method encoding
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
Re: ZSTD TOAST compression, and an extensible compression method encoding
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.
-gregRe: ZSTD TOAST compression, and an extensible compression method encoding
Hi Greg, On Sat, Oct 24, 2026 at 6:33 PM Greg Burd 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
Re: ZSTD TOAST compression, and an extensible compression method encoding
On Saturday, October 24th, 2026 at 3:32 PM, Manu 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
Re: ZSTD TOAST compression, and an extensible compression method encoding
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
Re: ZSTD TOAST compression, and an extensible compression method encoding
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 On Sun, Oct 25, 2026 at 5:34 PM Greg Burd 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
Re: ZSTD TOAST compression, and an extensible compression method encoding
On Sun, Oct 25, 2026 at 5:34 PM Greg Burd 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
Re: ZSTD TOAST compression, and an extensible compression method encoding
Hi Greg, On Sun, Oct 25, 2026 at 4:33 PM Greg Burd 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
Re: ZSTD TOAST compression, and an extensible compression method encoding
On Sunday, October 25th, 2026 at 12:52 PM, Hannu Krosing 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
Re: ZSTD TOAST compression, and an extensible compression method encoding
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
Re: ZSTD TOAST compression, and an extensible compression method encoding
On Sunday, October 25th, 2026 at 9:21 PM, Manu 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
Re: ZSTD TOAST compression, and an extensible compression method encoding
On Monday, October 26th, 2026 at 3:02 PM, Greg Burd wrote: > > On Sunday, October 25th, 2026 at 12:52 PM, Hannu Krosing 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
Re: ZSTD TOAST compression, and an extensible compression method encoding
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
Re: ZSTD TOAST compression, and an extensible compression method encoding
Hi Greg, On Tue, Oct 27, 2026 at 11:57 AM Greg Burd 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
Re: ZSTD TOAST compression, and an extensible compression method encoding
Hi Greg, Manu, Nikhil,
On Thu, Oct 29, 2026 at 1:48 PM Manu wrote:
> On Tue, Oct 27, 2026 at 11:57 AM Greg Burd 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
On Thu, Oct 29, 2026 at 2:48 PM Manu wrote:
>
> Hi Greg,
>
> On Tue, Oct 27, 2026 at 11:57 AM Greg Burd 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
>
>
Re: ZSTD TOAST compression, and an extensible compression method encoding
On Tue, Oct 27, 2026 at 12:53 PM Greg Burd wrote: > > > On Monday, October 26th, 2026 at 3:02 PM, Greg Burd wrote: > > > > On Sunday, October 25th, 2026 at 12:52 PM, Hannu Krosing 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
Re: ZSTD TOAST compression, and an extensible compression method encoding
Hi Hannu, On Thu, Oct 29, 2026 at 11:15 PM Hannu Krosing 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] 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] https://www.postgresql.org/message-id/CABUcsRRuMHXWqgiZ5wy=4OPbET0niFQEVY_d8VofeumTxjBJjw@mail.gmail.com Manu
Re: ZSTD TOAST compression, and an extensible compression method encoding
Hannu, Manu, thank you both; this was a thorough pass. v13 is attached. It is v12 plus a sixth patch that collects the fixes, kept separate so the review is easy to follow; I will fold it into 0001-0005 before a commit. It passes check-world in all three configurations (zstd+lz4, lz4-only, zstd-only), and the containment, memory and cancel cases below behave as you'd want under cassert+ASan. Replies inline; Manu's confirmations folded in where they touch the same point. Hannu wrote: > 1. 1-byte out-of-bounds read on corrupt 8-byte compressed varlenas Fixed. toast_decompress_datum() and its slice form now check the datum is at least VARHDRSZ_COMPRESSED_LONG before the long-form method byte is read (a new VARDATA_COMPRESSED_GET_RAW_METHOD() reads only the two bits), and reject a long header whose method is pglz, lz4, or the invalid id, so a corrupt value no longer reads past the allocation or decodes from the wrong offset. I did not, in this pass, extend amcheck to validate inline compressed headers; that is a worthwhile separate addition and I have it noted, but the out-of-bounds read itself is closed at the decode path. > 2. One-shot ZSTD_compress() allocates/frees a ~1.3 MB CCtx per datum Fixed. plain zstd_compress_datum() reuses a backend-static ZSTD_CCtx via ZSTD_compressCCtx(), like the decompression context. > 3. Minor items in 0001-0003 CHECK_FOR_INTERRUPTS() is in the slice loop. toast_external_info_get() now reports an uncompressed external datum as TOAST_INVALID_COMPRESSION_ID rather than leaving the pglz-looking raw bits. On the toast_fetch_datum_slice() 5-vs-9 byte point you are right that it is latent (slice pushdown is disabled for the dictionary methods); I left the code as is for now with that understanding, and it should be tightened when prefix pushdown is enabled for them. > 4. Three containment escapes (b) and (c) are fixed: the indirect-pointer branch of detoast_external_attr() decompresses an inline dictionary datum, and datumTransfer() (so SPI_datumTransfer()) flattens one instead of copying it verbatim. For (a), the R/W ExpandedRecord fast path, v13 already marks inline dictionary datums with ER_FLAG_HAVE_EXTERNAL, so Muzzammil Sarwar's fast-path fix [1] closes it without a change here, as Manu confirmed; I'd rather rely on that core fix than special-case pl_exec.c, and I'll add a regression test once it lands. Thanks to Manu for reproducing all three and for pinning (a) to that patch. > 5. Lock-before-ACL, cross-session temp tables, per-call leak All three fixed in pg_train_toast_dictionary(): it checks ownership before taking ShareUpdateExclusiveLock, rejects RELATION_IS_OTHER_TEMP, and does its sampling and training in a short-lived memory context. > 6. TRUNCATE does not retire non-current dictionaries Fixed; ExecuteTruncateGuts() now retires the relation's non-current dictionaries, as a rewrite does. > 7. Inline HEAP_HASEXTERNAL overhead & unrelated-column UPDATE behavior This one I have not changed, and I want to flag it rather than paper over it. The extra per-UPDATE work on a row that holds an inline dictionary datum is real, and it is the cost of making those datums self-contained the same way a TOAST pointer is; I don't see a way to keep containment without HEAP_HASEXTERNAL set. I did fix the misleading comment in the test. If you see a way to narrow the flag to rows that actually carry a dictionary datum without losing containment, I'm interested. > 8. Cache sizing & invalidation Fixed. The caches now evict only the entry whose dictionary changed, comparing the hashvalue computed when the entry was cached (the callback must not touch the catalog, since it can run outside a transaction, which is what an early version of this got wrong). The 4-entry size is still arbitrary; a partitioned scan over more than four dictionaries will still turn entries over, but no longer wipes the whole cache on an unrelated change. > 9. compression_dict_evolve.sql compresses ZERO rows Fixed. The test now uses rows wide enough to be TOAST-compressed on disk (it asserts pg_column_size < octet_length), keeps distribution-A rows present while adding distribution-B rows so two dictionary generations coexist, and checks each generation still reads back. You are also right about the two policy gaps: v13 does not yet refuse to train on a table whose rows never approach the threshold, and still adopts the first dictionary without a held-out check against plain compression. Those are policy refinements I'd like to do, but they felt larger than this correctness pass, so I left them as follow-ups rather than rush them. > 10. Permanent C malloc() leaks across PG_CATCH() OOM rollback Fixed. The held-out evaluation allocates its output buffer before creating the CDict, and the lz4 paths use a backend-static stream reset per value instead of LZ4_createStream()/free, so an OOM longjmp cannot jump over the free. > 11. tdtrainrows = -1 breaks the growth gate & pg_upgrade loses metadata Both fixed. pg_train_toast_dictionary() clamps a reltuples estimate of -1 to 0, and binary_upgrade_add_toast_dictionary() now carries tdtrainrows and tdtraintime, so the gates are unchanged across an upgrade. > 12. Single-slot rd_toastdictattnum relcache cache thrashes on 2+ columns Fixed; it is a per-column array in CacheMemoryContext now, so a write into a table with several dictionary columns no longer misses on every row. > 13. PGC_USERSET evolution GUCs vs. MAINTAIN privilege Fixed; the three evolution GUCs are PGC_SUSET. The pg_stats-like view over pg_toast_dictionary metadata is a good idea and I've noted it as a follow-up. Manu wrote: > Two leftovers: the 0005 message still says compressed_size() ... The header comment is corrected to compressed_total(); the function comment already described the subtransaction after your earlier diff. And thank you for the v12 confirmation run and the containment matrix; it is what gave me confidence these were the right fixes. On Hannu's framing that 0001-0003 are close to committable on their own: I agree, and splitting the series that way for PG20 makes sense to me if a committer prefers it. 0001-0003 stand without the dictionary work. best. -greg [1] https://www.postgresql.org/message-id/CABUcsRRuMHXWqgiZ5wy=4OPbET0niFQEVY_d8VofeumTxjBJjw@mail.gmail.com
Re: ZSTD TOAST compression, and an extensible compression method encoding
Hi Greg,
On Fri, Oct 30, 2026 at 6:14 PM Greg Burd wrote:
> v13 is attached.
>
> It is v12 plus a sixth patch that collects the fixes, kept separate so
> the review is easy to follow; I will fold it into 0001-0005 before a
> commit.
Thanks for the fast turnaround and for keeping 0006 separate -- that made
the diff very easy to audit.
I ran a second review and live test pass on v13 (0001-0006) under both
zstd+lz4 and lz4-only (--without-zstd) with cassert enabled.
Items #2 (CCtx reuse), #3 (CHECK_FOR_INTERRUPTS + external uncompressed
method ID), #4b/c (indirect TOAST pointer + datumTransfer containment),
#5 (ownercheck before lock, RELATION_IS_OTHER_TEMP, workcxt, plus marking
pg_train_toast_dictionary proparallel => 'u'), #8 (hashvalue-targeted
DictCache invalidation and the --without-zstd build), #9 (rewritten
compression_dict_evolve.sql with compressed multi-generation rows), #10
(palloc ordering / static LZ4 stream), and #13 (PGC_SUSET) all look good.
Relying on Muzzammil's core fix for #4a also makes complete sense.
However, 0006 introduced two regressions (#1 and #2 below, one of which
breaks pg_upgrade whenever any dictionary exists), and a few of the v12
fixes are still incomplete (#3-#5). I also looked into your question on
#7 and found a clean way to eliminate most of the unrelated-column UPDATE
overhead without losing containment.
=== Regressions & incomplete fixes in v13 ===
1. [Blocker] pg_upgrade fails whenever pg_toast_dictionary is non-empty
pg_toast_dictionary.tdtraintime is declared as int8 in pg_toast_dictionary.h
(storing raw TimestampTz microseconds since 2000-01-01, e.g.
846716483046138), and binary_upgrade_dump_toast_dictionaries() dumps
d.tdtraintime directly from that int8 column.
However, 0006 declared binary_upgrade_add_toast_dictionary()'s 6th
parameter as timestamptz in pg_proc.dat (using PG_GETARG_TIMESTAMPTZ(5))
and emits:
'%s'::pg_catalog.timestamptz
in pg_dump.c:5882. When pg_restore runs during pg_upgrade, PostgreSQL
tries to parse the raw microsecond integer string as a timestamptz literal
and aborts immediately:
ERROR: date/time field value out of range: "846716483046138"
002_pg_upgrade.pl missed this only because compression_zstd_dict.sql,
compression_lz4_dict.sql, and compression_dict_evolve.sql all DROP their
schemas at the end, leaving zero rows in pg_toast_dictionary.
Making the 6th argument of binary_upgrade_add_toast_dictionary() int8
(PG_GETARG_INT64(5)) and emitting %s::pg_catalog.int8 in pg_dump.c -- just
like tdtrainrows -- fixes it cleanly. (Also, if live callers of
dict_install() pass GetCurrentTimestamp() explicitly instead of 0,
traintime == 0 won't collide with 2000-01-01 00:00:00+00.) Please also
leave at least one table with active + retired dictionaries behind in the
regression database so 002_pg_upgrade.pl exercises this path.
2. CacheMemoryContext leak and unreset pg_internal.init pointers on
rd_toastdictoids / rd_toastdictvalid
In toast_dictionary_current() (toast_dictionary.c:245-254),
rel->rd_toastdictoids and rel->rd_toastdictvalid are allocated directly in
CacheMemoryContext:
oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
rel->rd_toastdictoids = palloc0_array(Oid, natts);
...
rel->rd_toastdictvalid = bms_add_member(rel->rd_toastdictvalid, attnum);
Unlike rd_indexcxt / rd_rulescxt, RelationData has no per-relation memory
context: CacheMemoryContext lives for the entire backend lifetime, and
RelationDestroyRelation() in relcache.c explicitly pfrees every heap-
allocated field of RelationData. Because neither RelationDestroyRelation()
nor RelationClearRelation() frees rd_toastdictoids / rd_toastdictvalid,
every relcache rebuild leaks both allocations in CacheMemoryContext for
the life of the backend.
In addition, write_relcache_init_file() writes the raw RelationData bytes
to pg_internal.init, and load_relcache_init_file() resets all pointer
fields on reload; if a cached relation ever had those pointers populated,
reloading pg_internal.init in another process would leave dangling
pointers unless load_relcache_init_file() resets rd_toastdictoids = NULL
and rd_toastdictvalid = NULL (and bumps RELCACHE_INIT_FILEMAGIC).
(Nit: the comment above toast_dictionary_current() at lines 212-218 still
describes the v12 single-entry cache.)
3. Remaining OOB reads & non-canonical header bypass on corrupt 4B_C
datums (0002 / 0004 / 0006)
0006 fixed toast_decompress_datum() to check VARSIZE >=
VARHDRSZ_COMPRESSED_LONG (9) before reading va_cmid, and to reject
non-canonical long-form cmids ({0, 1, 3}). Three gaps remain:
(a) toast_get_compression_id() (toast_compression.c:534) and
VARATT_IS_COMPRESSED_DICT() (toast_compression.h:91) still call
VARDATA_COMPRESSED_GET_COMPRESS_METHOD(attr) with no VARSIZE >= 9
check. On a corrupt 8-byte 4B_C datum with raw_method == 3,
SELECT pg_column_compression(col) reads 1 byte past the datum, and
varlena.c:4252 even prints the exact decimal value of that OOB byte
in the error message ("ERROR: invalid compression method id 119")
for 6..255 while mapping 0..5 to codec names/NULL.
(b) None of toast_decompress_datum(), toast_decompress_datum_slice(),
toast_raw_datum_size(), toast_get_compression_id(), or
VARATT_IS_COMPRESSED_DICT() checks VARSIZE(attr) >=
VARHDRSZ_COMPRESSED (8) before reading va_tcinfo (bytes 4..7). A
corrupt 4B_C varlena with length 4..7 causes SELECT octet_length(col)
to read 4 bytes past the 4-byte header and return 30 bits of OOB
memory as the length (and pg_column_compression() reads up to 5 bytes
past the datum).
(c) toast_decompress_datum_slice() (detoast.c:602-627) got the VARSIZE >= 9
check, but missed the `!toast_compression_id_needs_cmid_byte(cmid)`
check that was added to toast_decompress_datum() (detoast.c:548-553).
So `substr(col, 1, 5)` on a corrupt long header with va_cmid in {0, 1}
still dispatches to pglz/lz4 slice decompression starting at offset 8
(&va_cmid) instead of rejecting it as corrupt.
Centralizing 4B_C header validation in a single inline helper (checking
VARSIZE >= 8, and if raw_method == 3 then VARSIZE >= 9 and
toast_compression_id_needs_cmid_byte(cmid)) shared by
toast_decompress_datum(), toast_decompress_datum_slice(), and
toast_get_compression_id() -- plus guarding toast_raw_datum_size() with
VARSIZE >= 8 and VARATT_IS_COMPRESSED_DICT() with VARSIZE >=
VARHDRSZ_COMPRESSED_DICT (13) -- would close all of these in one place.
Once that and #2/#1 are folded in, 0001-0003 look completely ready to me.
4. Same-subtransaction TRUNCATE misses toast_dictionary_retire()
In ExecuteTruncateGuts() (tablecmds.c:2231-2291), toast_dictionary_retire()
was placed inside the `else` branch (RelationSetNewRelfilenumber), so
truncating a table created or previously truncated in the same
(sub)transaction takes the `if (rel->rd_createSubid == mySubid ||
rel->rd_newRelfilelocatorSubid == mySubid)` in-place heap_truncate_one_rel()
branch and skips retirement:
BEGIN;
-- table created/rewritten/truncated in this xact, evolved, then:
TRUNCATE t;
COMMIT;
Moving toast_dictionary_retire(RelationGetRelid(rel)) right after that
if/else block handles both paths.
5. tdtrainrows = 0 clamping and un-updated cooldown when adopt == false
Two small state-machine bugs remain in 0005/0006:
- Clamping reltuples == -1 to 0 in pg_train_toast_dictionary() means
`0 * growth == 0`, so after `CREATE TABLE -> COPY ->
pg_train_toast_dictionary('t', 'c', 4096) -> ANALYZE`, the first ANALYZE
after min_interval sees totalrows >= 0 even with zero table growth and
can replace a user-sized 4 kB dictionary with a 64 kB auto-trained one.
Since pg_train_toast_dictionary() already scans the heap (or samples
blocks), passing the scanned/extrapolated row count when reltuples < 0
gives a realistic baseline.
- Worse, in toast_dictionary_maybe_evolve() (toast_dictionary.c:1503),
when both the growth gate and min_interval (86400s) have passed, if the
held-out check rejects the candidate (`adopt == false`, which is the
normal case when data grew 2x without changing distribution), neither
tdtraintime nor tdtrainrows is updated on the current dictionary row!
As a result, *every* subsequent ANALYZE / autoanalyze forever re-samples
30,000 rows, detoasts them, and runs ZDICT_trainFromBuffer() over and
over. Updating tdtraintime = GetCurrentTimestamp() (and tdtrainrows =
totalrows) on the tdcurrent row when !adopt resets the gates cleanly.
=== On #7: Narrowing inline HEAP_HASEXTERNAL UPDATE / DELETE overhead ===
> This one I have not changed, and I want to flag it rather than paper
> over it. The extra per-UPDATE work on a row that holds an inline
> dictionary datum is real, and it is the cost of making those datums
> self-contained the same way a TOAST pointer is; I don't see a way to
> keep containment without HEAP_HASEXTERNAL set. I did fix the misleading
> comment in the test. If you see a way to narrow the flag to rows that
> actually carry a dictionary datum without losing containment, I'm
> interested.
First, on the flag scope itself: fill_val() (heaptuple.c:378) already sets
HEAP_HASEXTERNAL only when VARATT_IS_EXTERNAL(val) ||
VARATT_IS_COMPRESSED_DICT(val), so rows whose column stayed uncompressed
or fell back to plain zstd/lz4 do not get HEAP_HASEXTERNAL. And I agree
that keeping HEAP_HASEXTERNAL on rows that *do* hold an inline dict datum
is necessary for containment without burning a scarce t_infomask2 bit.
However, we *can* eliminate two expensive pieces of that overhead without
changing on-disk flags or losing containment / retirement:
(1) Skip !toast_dictionary_keep() (and the TOASTDICTOID SysCache lookup +
eager ZSTD decompress/recompress) on unchanged columns during an
in-place UPDATE of the same relation.
In toast_tuple_init() (toast_helper.c:162), `ttc->ttc_oldvalues != NULL`
is true *only* during an in-place table_tuple_update() on `ttc->ttc_rel`
(INSERT, VACUUM FULL, CLUSTER, rewriting ALTER TABLE, REFRESH MATVIEW,
and cross-partition UPDATE row movement all pass oldtup == NULL; the
only rewrite path that replays concurrent updates through
table_tuple_update() is REPACK CONCURRENTLY in repack.c, where
OidIsValid(ttc->ttc_rel->rd_rel->relrewrite) is true on NewHeap).
So in toast_tuple_init(), if:
- ttc->ttc_oldvalues != NULL,
- !OidIsValid(ttc->ttc_rel->rd_rel->relrewrite),
- att->attstorage != TYPSTORAGE_PLAIN,
- !ttc->ttc_oldisnull[i], and
- old_value and new_value are byte-identical VARATT_IS_COMPRESSED_DICT
datums (same pointer or same VARSIZE + memcmp == 0),
then `new_value` came directly from `oldtup` of this exact (relid,
attnum) and is staying in this exact heap! Skipping the
!toast_dictionary_keep() check in that case:
- avoids the TOASTDICTOID SysCache lookup on every unrelated-column
UPDATE,
- avoids eagerly decompressing + recompressing inline dict columns on
unrelated-column UPDATEs after a dictionary evolves (while full
table rewrites still recompress everything via oldtup == NULL or
relrewrite != InvalidOid, so retirement remains 100% intact),
- still leaves `new_value` eligible for out-of-line toasting if
another updated column pushed the tuple past TOAST_TUPLE_THRESHOLD,
- and actually makes the comment in compression_zstd_dict.sql:135
("ordinary updates of other columns leave the value, and its old
dictionary, alone" -- which btw wasn't touched in 0006) true for
inline dictionary rows too!
(2) Guard heap_toast_delete() on DELETE when the table has no TOAST table:
Inline dictionary datums have no external chunks in pg_toast_ to
delete. In heapam.c:3185 (and speculative abort at 6526), checking
`OidIsValid(relation->rd_rel->reltoastrelid)` before calling
heap_toast_delete() avoids deforming the tuple on DELETE for tables
without a TOAST relation (e.g., STORAGE MAIN columns on an otherwise
fixed-width table).
=== Minor nits & docs ===
- toast_dictionary.c:1158-1166: when !object_ownercheck() fails in
pg_train_toast_dictionary(), get_rel_relkind(relid) and
get_rel_name(relid) are called unlocked; if the relation is concurrently
dropped between them, get_rel_name(relid) returns NULL into
aclcheck_error(). Looking up RELOID once in SysCache (or checking
relname == NULL) avoids that.
- toast_dictionary.c:268: "compressed zstd data is corrupt" in
dict_datum_get_id() is also reached for lz4_dict ("compressed dictionary
data is corrupt" would fit both). Similarly, under --without-zstd
--with-lz4, pg_train_toast_dictionary() on an lz4_dict column fails with
"compression method zstd_dict not supported" because ZDICT lives in
libzstd; a clearer message ("dictionary training requires zstd support")
would be less confusing.
- compression_dict_evolve.sql:18-19: stale comment ("the row count is held
constant below") now that the test grows from 4,000 to 12,000 rows.
- SGML docs:
* catalogs.sgml omits tdtrainrows and tdtraintime from
pg_toast_dictionary, omits 'd' and 'e' from pg_attribute.attcompression,
and says DROP COLUMN immediately deletes the column's dictionaries
(they remain until a table rewrite or DROP TABLE).
* func-admin.sgml and alter_table.sgml mention zstd_dict in a couple of
places where lz4_dict also applies.
Cheers,
Hannu
Re: ZSTD TOAST compression, and an extensible compression method encoding
On Sat, 31 Oct 2026 01:40:59 +0100, Hannu Krosing wrote: > Hi Greg, Hello Hannu, Thanks for the second pass. v14 is attached, rebased on master (fa5ecff759b). The fixes are folded into 0001-0005 this time, so there is no sixth patch. > 1. [Blocker] pg_upgrade fails whenever pg_toast_dictionary is non-empty Yes, I reproduced it: "date/time field value out of range: "846872593030845"". The sixth argument of binary_upgrade_add_toast_dictionary() is int8 now and pg_dump emits ::pg_catalog.int8, as you suggested. dict_install() no longer treats traintime 0 as "now"; every caller passes the time explicitly. compression_zstd_dict now leaves public.zstd_dict_upgrade behind, with a current and a retired dictionary, so 002_pg_upgrade covers this. > 2. CacheMemoryContext leak and unreset pg_internal.init pointers on > rd_toastdictoids / rd_toastdictvalid Fixed. RelationDestroyRelation() frees both, and load_relcache_init_file() resets them to NULL with the other transient fields. I did not bump RELCACHE_INIT_FILEMAGIC. The init files are removed at every startup, so a file written by another build is never read, and they only hold system catalogs, which cannot have dictionaries. The comment above toast_dictionary_current() is fixed too. > 3. Remaining OOB reads & non-canonical header bypass on corrupt 4B_C > datums (0002 / 0004 / 0006) Done as you suggested, in one place. 0002 adds toast_inline_compression_id() next to toast_compression_id_needs_cmid_byte(). It returns TOAST_INVALID_COMPRESSION_ID unless the datum has at least VARHDRSZ_COMPRESSED bytes, has at least VARHDRSZ_COMPRESSED_LONG if the bits say long form, and the form matches the method. Both decompression entry points and toast_get_compression_id() use it. The slice path now calls it before it reads the size for its whole-value shortcut, which covers (c). toast_raw_datum_size() checks for a complete header. In 0004, VARATT_IS_COMPRESSED_DICT() and toast_dict_decompress_datum() use the same helper, and dict_datum_get_id() still checks for VARHDRSZ_COMPRESSED_DICT. To test it I patched heap pages with five bad headers: 8 bytes with the long bits, 6 bytes, long form with va_cmid 0 and 1, and the plain form claiming zstd. On v13, pg_column_compression() returned a method for all five, octet_length() of the 6-byte one returned 3200 (read from the bytes after the datum), and substr() of the plain-form zstd one returned "abcde". On v14, pg_column_compression(), length() and substr() report "compressed data is corrupt" for all five. octet_length() reports it for the 6-byte one; for the others it returns the size recorded in their complete 8-byte header, as master does. amcheck still does not look at inline compressed headers; I'd still like to do that separately. > 4. Same-subtransaction TRUNCATE misses toast_dictionary_retire() Fixed: the call now follows the if/else. compression_zstd_dict has a case for it: train twice and TRUNCATE inside the transaction that created the table, leaving one dictionary. > 5. tdtrainrows = 0 clamping and un-updated cooldown when adopt == false Both fixed. For the first: pg_train_toast_dictionary() still records 0 when reltuples is -1, but evolution now reads 0 as "row count unknown" instead of a baseline. The first ANALYZE that finds rows records its own count and does not retrain, so a 4 kB dictionary trained by hand is not replaced on the next ANALYZE. I went this way instead of passing the scanned count because the trainer stops after DICT_MAX_SAMPLES values, so the scanned count is not the row count. compression_dict_evolve tests the exact sequence you gave. For the second: when the gates pass but the candidate loses, or no candidate can be trained, the current dictionary's tdtraintime and tdtrainrows are reset, so the following ANALYZEs skip it until the cooldown and growth gates pass again. The test checks that tdtraintime moves on the rejected ANALYZE. The docs for dictionary_evolution_min_interval and dictionary_evolution_growth say so. > === On #7: Narrowing inline HEAP_HASEXTERNAL UPDATE / DELETE overhead === (1) is in 0004, close to the form you described. toast_tuple_init() skips toast_dictionary_keep() when there is an old tuple, the relation is not a rewrite target (relrewrite is invalid), and the old and new values are byte-identical dictionary datums. I checked it with pageinspect: train, recompress every row, train again, then UPDATE an unrelated column of one row. On v13 that row's datum is recompressed with the new dictionary; on v14 it keeps the old one. VACUUM FULL still recompresses it and retires the old dictionary, and every value reads back. So the comment in compression_zstd_dict.sql is now true for inline values as well. I left (2) out. It is an existing heapam path, and the cost is a deform on DELETE for a table with no TOAST table that holds inline dictionary datums. That seems rare enough to wait until it shows up in a profile. > - toast_dictionary.c:1158-1166: when !object_ownercheck() fails in > pg_train_toast_dictionary(), get_rel_relkind(relid) and > get_rel_name(relid) are called unlocked Fixed: one RELOID syscache lookup, then has_privs_of_role() on relowner, which is the check object_ownercheck() does. > - toast_dictionary.c:268: "compressed zstd data is corrupt" in > dict_datum_get_id() is also reached for lz4_dict It says "compressed dictionary data is corrupt" now. Without zstd, pg_train_toast_dictionary() says "training compression dictionaries is not supported by this build", with a detail asking for zstd. > - compression_dict_evolve.sql:18-19: stale comment Fixed. > - SGML docs: catalogs.sgml documents tdtrainrows and tdtraintime, lists 'd' and 'e' under attcompression, and says a dropped column's dictionaries stay until the next rewrite. func-admin.sgml and alter_table.sgml mention lz4_dict where it applies. While I was in there, I added LZ4_stream_t to typedefs.list and ran pgindent over the series. Manu, the v13 containment fixes are unchanged in v14, so your repros for them should still hold. The new parts are the header validation in 0002 and the UPDATE fast path in 0004, if you want to point your harness at them. best. -greg
Re: ZSTD TOAST compression, and an extensible compression method encoding
Hi Greg,
On Mon, Nov 2, 2026 at 8:46 PM Greg Burd wrote:
> Thanks for the second pass. v14 is attached, rebased on master
> (fa5ecff759b). The fixes are folded into 0001-0005 this time, so there
> is no sixth patch.
Thanks! I ran another full review and test pass on v14 (zstd+lz4 and
--without-zstd, with cassert, 002_pg_upgrade, isolation/repack-concurrently,
and logical decoding).
All of the v13 regressions and major issues look cleanly resolved:
- 002_pg_upgrade passes with active + retired dictionaries in
public.zstd_dict_upgrade (and pg_dump's remoteVersion < 200000 check
looks right too);
- CacheMemoryContext shows zero growth across repeated relcache
invalidations + dictionary writes (and your reasoning on not bumping
RELCACHE_INIT_FILEMAGIC and leaving heap_toast_delete() alone makes
sense to me);
- the UPDATE fast path in toast_tuple_init() preserves old inline
dictionaries and HOT updates on unrelated-column UPDATEs while still
recompressing and retiring under VACUUM FULL and REPACK CONCURRENTLY;
- dict_set_gates(), the pre-lock RELOID ownership check, and the SGML
doc updates all read well.
What I found in this pass is much smaller and mostly surgical:
1. Missed VARATT_IS_COMPRESSED_DICT() in check_domain_for_new_field()
(expandedrecord.c, 0004)
0004 updated 5 of the 6 VARATT_IS_EXTERNAL() checks in expandedrecord.c,
but missed the 6th one in check_domain_for_new_field()
(src/backend/utils/adt/expandedrecord.c:1553):
if (!attr->attbyval && attr->attlen == -1 &&
VARATT_IS_EXTERNAL(DatumGetPointer(newValue)))
dummy_erh->flags |= ER_FLAG_HAVE_EXTERNAL;
Because expanded_record_set_field_internal() runs
check_domain_for_new_field() before setting ER_FLAG_HAVE_EXTERNAL on erh,
assigning an inline dictionary datum to a field of a domain-over-composite
variable leaves ER_FLAG_HAVE_EXTERNAL unset on dummy_erh. If the domain's
CHECK expression flattens VALUE (e.g., stores it or passes it to a SQL
function), ER_get_flat_size() skips toast_flatten_tuple_to_datum() and the
raw inline dictionary datum escapes into another table/composite:
CREATE TYPE comp_t AS (a text, b int);
CREATE TABLE escaped_sink (tag text, val comp_t);
CREATE FUNCTION capture_comp_sql(v comp_t) RETURNS bool LANGUAGE sql AS $$
INSERT INTO escaped_sink VALUES ('sql_fn', v) RETURNING true;
$$;
CREATE DOMAIN dom_comp_sql AS comp_t CHECK (capture_comp_sql(VALUE));
CREATE TABLE src_dict (id int, d text COMPRESSION zstd_dict);
INSERT INTO src_dict
SELECT g, repeat(format('{"user":%s,"role":"admin","org":"acme"}', g), 40)
FROM generate_series(1, 100) g;
SELECT pg_train_toast_dictionary('src_dict', 'd', 4096);
INSERT INTO src_dict
VALUES (101, repeat('{"user":101,"role":"admin","org":"acme"}', 40));
DO $$
DECLARE v dom_comp_sql;
BEGIN
v.a := (SELECT d FROM src_dict WHERE id = 101);
END;
$$;
SELECT pg_column_compression((val).a) FROM escaped_sink; -- zstd_dict
DROP TABLE src_dict;
SELECT length((val).a) FROM escaped_sink;
-- ERROR: compression dictionary 16480 does not exist
Adding `|| VARATT_IS_COMPRESSED_DICT(DatumGetPointer(newValue))` there
closes it.
2. Missed toast_inline_compression_id() caller in toast_save_datum()
(toast_internals.c, 0002 & 0004)
toast_save_datum() (toast_internals.c:334 after 0004) still calls raw
VARDATA_COMPRESSED_GET_COMPRESS_METHOD(dval) followed by Assert(...):
else if (VARATT_IS_COMPRESSED(dval))
{
cmid = VARDATA_COMPRESSED_GET_COMPRESS_METHOD(dval);
...
Assert(cmid == TOAST_PGLZ_COMPRESSION_ID || ...);
When a heap tuple already has an untouched inline 4B_C attribute and an
UPDATE widens *another* column past TOAST_TUPLE_THRESHOLD (or INSERT ...
SELECT copies a non-dict inline 4B_C datum), toast_tuple_externalize()
passes that on-disk 4B_C datum straight into toast_save_datum():
- a truncated 4..8-byte header reads out-of-bounds;
- a corrupt va_cmid (3 or >= 6) hits FailedAssertion on cassert builds
(or writes an invalid external pointer on non-assert builds);
- a non-canonical long header (e.g., raw_method = 3, va_cmid = 0) gets
externalized as a plain pglz pointer with the 9-byte long header stored
in pg_toast chunks.
Switching toast_save_datum() to `cmid = toast_inline_compression_id(dval)`
and raising ERRCODE_DATA_CORRUPTED on TOAST_INVALID_COMPRESSION_ID (and
on unknown cmid values instead of Assert alone) closes that path.
(Two tiny related validation polish items if you want them:
- In toast_inline_compression_id(), rejecting unknown method IDs (>= 6,
or > TOAST_ZSTD_COMPRESSION_ID in 0002-0003) and checking VARSIZE >=
VARHDRSZ_COMPRESSED_DICT for the dict methods would turn
`pg_column_compression()`
on a corrupt va_cmid = 99 or 10-byte dict header into
ERRCODE_DATA_CORRUPTED instead of elog("invalid compression method id 99")
or returning 'zstd_dict' before detoast fails.
- In toast_external_info_get() / toast_get_compression_id(), enforcing the
same pointer-form vs. method check as verify_heapam.c (and raising
ERRCODE_DATA_CORRUPTED in toast_get_compression_id() when a compressed
external pointer decodes to TOAST_INVALID_COMPRESSION_ID) would make
external pointer validation symmetric with inline headers.)
With toast_save_datum() tightened, 0001-0003 look completely ready to
commit.
3. Temp tables with ON COMMIT DELETE ROWS miss toast_dictionary_retire()
(heap.c, 0004)
ExecuteTruncateGuts() handles explicit SQL TRUNCATE, but `CREATE TEMP TABLE
... ON COMMIT DELETE ROWS` truncates at commit via
PreCommit_on_commit_actions() -> heap_truncate(oids_to_truncate) in
src/backend/catalog/heap.c:3669, bypassing ExecuteTruncateGuts(). So in
long-lived / pooled sessions reusing an ON COMMIT DELETE ROWS temp table,
retraining leaves retired dictionaries behind in pg_toast_dictionary even
after COMMIT empties the table:
CREATE TEMP TABLE tmp_ocdr (id int, a text COMPRESSION zstd_dict)
ON COMMIT DELETE ROWS;
BEGIN;
INSERT INTO tmp_ocdr
SELECT g, repeat(format('{"k":%s,"kind":"alpha"}', g), 12)
FROM generate_series(1, 100) g;
SELECT pg_train_toast_dictionary('tmp_ocdr', 'a', 4096);
INSERT INTO tmp_ocdr
SELECT g, repeat(format('{"k":%s,"kind":"beta"}', g), 12)
FROM generate_series(101, 200) g;
SELECT pg_train_toast_dictionary('tmp_ocdr', 'a', 4096);
COMMIT;
SELECT count(*) FILTER (WHERE NOT tdcurrent)
FROM pg_toast_dictionary WHERE tdrelid = 'tmp_ocdr'::regclass; -- 1
Two small subtleties if you wire toast_dictionary_retire() into
heap_truncate():
- Put it in heap_truncate() rather than heap_truncate_one_rel(), since
ExecuteTruncateGuts() calls heap_truncate_one_rel() in its same-subxact
branch and already retires right afterward.
- Because pg_toast_dictionary.tddict can be TOASTed out-of-line,
CatalogTupleDelete() -> toast_delete_datum() asserts ActiveSnapshotSet().
PreCommit_on_commit_actions() (tablecmds.c:20095) already wraps
performMultipleDeletions() in PushActiveSnapshot(GetTransactionSnapshot())
/ PopActiveSnapshot() for that exact reason, so heap_truncate() there
needs an active snapshot too.
4. Moving rd_toastdictoids / rd_toastdictvalid from 0005 into 0004
In v14, 0004's toast_dictionary_current() still does a table_open() +
systable_beginscan() on pg_toast_dictionary for every compressed datum
written (even when a zstd_dict/lz4_dict column has no dictionary yet),
and 0005 replaces that with rd_toastdictoids / rd_toastdictvalid.
If a committer decides to apply 0001-0004 first while iterating on 0005's
ANALYZE policy, 0004 on its own would pay that per-datum catalog scan on
every write. Moving the relcache cache (and RelationDestroyRelation /
load_relcache_init_file cleanup) from 0005 into 0004 would make 0001-0004
self-sufficient.
5. Two minor gate-ordering items in toast_dictionary_maybe_evolve() (0005)
- In toast_dictionary.c:1422-1425, dict_current_info(..., &curbytes, true)
detoasts/copies tddict (up to 1 MB) and dict_count() scans the index
*before* checking min_rows, growth, and the 24h min_interval cooldown,
so steady-state no-op ANALYZEs still detoast tddict from
pg_toast_dictionary's TOAST table. Passing wantbytes = false initially
(and deferring dict_count() until after the growth/cooldown gates, and
fetching curbytes only at step (f) when OidIsValid(curid) && nheld > 0)
avoids that catalog TOAST read on normal ANALYZEs.
- In toast_dictionary.c:1429-1444, `if (totalrows < min_rows) goto done;`
runs *before* the `if (currows <= 0)` baseline update. If a manual
dictionary was trained before the first ANALYZE on a 600-row table
(tdtrainrows = 0) with min_rows = 10000, ANALYZE at 600 rows skips
setting tdtrainrows = 600; when the table later reaches 10,000 rows,
ANALYZE records 10,000 as the baseline instead of 600 and waits until
20,000 rows to evolve. Recording the currows <= 0 baseline before the
min_rows exit captures the true starting size.
Cheers,
Hannu
On Mon, Nov 2, 2026 at 8:47 PM Greg Burd wrote:
>
> On Sat, 31 Oct 2026 01:40:59 +0100, Hannu Krosing wrote:
> > Hi Greg,
>
> Hello Hannu,
>
> Thanks for the second pass. v14 is attached, rebased on master
> (fa5ecff759b). The fixes are folded into 0001-0005 this time, so there
> is no sixth patch.
>
> > 1. [Blocker] pg_upgrade fails whenever pg_toast_dictionary is non-empty
>
> Yes, I reproduced it: "date/time field value out of range:
> "846872593030845"". The sixth argument of
> binary_upgrade_add_toast_dictionary() is int8 now and pg_dump emits
> ::pg_catalog.int8, as you suggested. dict_install() no longer treats
> traintime 0 as "now"; every caller passes the time explicitly.
>
> compression_zstd_dict now leaves public.zstd_dict_upgrade behind, with a
> current and a retired dictionary, so 002_pg_upgrade covers this.
>
> > 2. CacheMemoryContext leak and unreset pg_internal.init pointers on
> > rd_toastdictoids / rd_toastdictvalid
>
> Fixed. RelationDestroyRelation() frees both, and
> load_relcache_init_file() resets them to NULL with the other transient
> fields. I did not bump RELCACHE_INIT_FILEMAGIC. The init files are
> removed at every startup, so a file written by another build is never
> read, and they only hold system catalogs, which cannot have
> dictionaries. The comment above toast_dictionary_current() is fixed
> too.
>
> > 3. Remaining OOB reads & non-canonical header bypass on corrupt 4B_C
> > datums (0002 / 0004 / 0006)
>
> Done as you suggested, in one place. 0002 adds
> toast_inline_compression_id() next to
> toast_compression_id_needs_cmid_byte(). It returns
> TOAST_INVALID_COMPRESSION_ID unless the datum has at least
> VARHDRSZ_COMPRESSED bytes, has at least VARHDRSZ_COMPRESSED_LONG if the
> bits say long form, and the form matches the method. Both decompression
> entry points and toast_get_compression_id() use it. The slice path now
> calls it before it reads the size for its whole-value shortcut, which
> covers (c). toast_raw_datum_size() checks for a complete header. In
> 0004, VARATT_IS_COMPRESSED_DICT() and toast_dict_decompress_datum() use
> the same helper, and dict_datum_get_id() still checks for
> VARHDRSZ_COMPRESSED_DICT.
>
> To test it I patched heap pages with five bad headers: 8 bytes with the
> long bits, 6 bytes, long form with va_cmid 0 and 1, and the plain form
> claiming zstd. On v13, pg_column_compression() returned a method for all
> five, octet_length() of the 6-byte one returned 3200 (read from the
> bytes after the datum), and substr() of the plain-form zstd one returned
> "abcde". On v14, pg_column_compression(), length() and substr() report
> "compressed data is corrupt" for all five. octet_length() reports it for
> the 6-byte one; for the others it returns the size recorded in their
> complete 8-byte header, as master does.
>
> amcheck still does not look at inline compressed headers; I'd still
> like to do that separately.
>
> > 4. Same-subtransaction TRUNCATE misses toast_dictionary_retire()
>
> Fixed: the call now follows the if/else. compression_zstd_dict has a
> case for it: train twice and TRUNCATE inside the transaction that
> created the table, leaving one dictionary.
>
> > 5. tdtrainrows = 0 clamping and un-updated cooldown when adopt == false
>
> Both fixed.
>
> For the first: pg_train_toast_dictionary() still records 0 when
> reltuples is -1, but evolution now reads 0 as "row count unknown"
> instead of a baseline. The first ANALYZE that finds rows records its
> own count and does not retrain, so a 4 kB dictionary trained by hand is
> not replaced on the next ANALYZE. I went this way instead of passing the
> scanned count because the trainer stops after DICT_MAX_SAMPLES values,
> so the scanned count is not the row count. compression_dict_evolve
> tests the exact sequence you gave.
>
> For the second: when the gates pass but the candidate loses, or no
> candidate can be trained, the current dictionary's tdtraintime and
> tdtrainrows are reset, so the following ANALYZEs skip it until the
> cooldown and growth gates pass again. The test checks that tdtraintime
> moves on the rejected ANALYZE. The docs for
> dictionary_evolution_min_interval and dictionary_evolution_growth say
> so.
>
> > === On #7: Narrowing inline HEAP_HASEXTERNAL UPDATE / DELETE overhead ===
>
> (1) is in 0004, close to the form you described. toast_tuple_init()
> skips toast_dictionary_keep() when there is an old tuple, the relation
> is not a rewrite target (relrewrite is invalid), and the old and new
> values are byte-identical dictionary datums. I checked it with
> pageinspect: train, recompress every row, train again, then UPDATE an
> unrelated column of one row. On v13 that row's datum is recompressed
> with the new dictionary; on v14 it keeps the old one. VACUUM FULL
> still recompresses it and retires the old dictionary, and every value
> reads back. So the comment in compression_zstd_dict.sql is now true
> for inline values as well.
>
> I left (2) out. It is an existing heapam path, and the cost is a deform
> on DELETE for a table with no TOAST table that holds inline dictionary
> datums. That seems rare enough to wait until it shows up in a profile.
>
> > - toast_dictionary.c:1158-1166: when !object_ownercheck() fails in
> > pg_train_toast_dictionary(), get_rel_relkind(relid) and
> > get_rel_name(relid) are called unlocked
>
> Fixed: one RELOID syscache lookup, then has_privs_of_role() on relowner,
> which is the check object_ownercheck() does.
>
> > - toast_dictionary.c:268: "compressed zstd data is corrupt" in
> > dict_datum_get_id() is also reached for lz4_dict
>
> It says "compressed dictionary data is corrupt" now. Without zstd,
> pg_train_toast_dictionary() says "training compression dictionaries is
> not supported by this build", with a detail asking for zstd.
>
> > - compression_dict_evolve.sql:18-19: stale comment
>
> Fixed.
>
> > - SGML docs:
>
> catalogs.sgml documents tdtrainrows and tdtraintime, lists 'd' and 'e'
> under attcompression, and says a dropped column's dictionaries stay until
> the next rewrite. func-admin.sgml and alter_table.sgml mention lz4_dict
> where it applies.
>
> While I was in there, I added LZ4_stream_t to typedefs.list and ran
> pgindent over the series.
>
> Manu, the v13 containment fixes are unchanged in v14, so your repros
> for them should still hold. The new parts are the header validation
> in 0002 and the UPDATE fast path in 0004, if you want to point your
> harness at them.
>
> best.
>
> -greg
>
Re: ZSTD TOAST compression, and an extensible compression method encoding
Hi Greg, On Mon, Nov 2, 2026 at 7:46 PM Greg Burd wrote: > Manu, the v13 containment fixes are unchanged in v14, so your repros > for them should still hold. The new parts are the header validation > in 0002 and the UPDATE fast path in 0004, if you want to point your > harness at them. They hold: v14 gives the same results as v13, and 4(a) still fails without Muzzammil's v1 and passes with it. Header validation: of 1044 corrupt inline headers (4 to 12 bytes, both forms, va_cmid 0-255), with five readers each under cassert+ASan, none reads past the datum or fails an assertion. Hannu's toast_save_datum() point reproduces: va_cmid 3 or >= 6 fails its Assert through UPDATE, INSERT ... SELECT and CTAS, and his change makes all of them report "compressed data is corrupt". UPDATE fast path: 1M unrelated-column UPDATEs of values on a non-current dictionary stay HOT and take 0.9 s and 128 MB of WAL, where v13 takes 5.4-5.7 s and 460 MB; VACUUM FULL, CLUSTER, REPACK and REPACK (CONCURRENTLY) then recompress them and retire the old dictionary. Among 141 uses of the TOAST predicates and 24 other container paths, Hannu's check_domain_for_new_field() case is the only one missing; his one-line change fixes it in the repro. The tables are attached. Manu
Re: ZSTD TOAST compression, and an extensible compression method encoding
On Mon, Nov 2, 2026 at 23:45 UTC, Hannu Krosing wrote: > Thanks! I ran another full review and test pass on v14 (zstd+lz4 and > --without-zstd, with cassert, 002_pg_upgrade, isolation/repack-concurrently, > and logical decoding). Thanks, Hannu, and thanks, Manu, for the containment audit and the UPDATE numbers. v15 is attached; it applies on master as of 72b9498df9a. > 1. Missed VARATT_IS_COMPRESSED_DICT() in check_domain_for_new_field() > (expandedrecord.c, 0004) Fixed as you suggested. compression_zstd_dict has a case for it now: a domain over the composite whose CHECK stores VALUE, and a DO block that assigns a dictionary value to a field. Without the fix the stored copy is still zstd_dict. > 2. Missed toast_inline_compression_id() caller in toast_save_datum() > (toast_internals.c, 0002 & 0004) Fixed: toast_save_datum() uses toast_inline_compression_id() and reports "compressed data is corrupt", and the Assert is gone. I added the UPDATE path to my corrupt-header test, widening another column so that a bad value gets moved out of line. On v14 the long headers with va_cmid 0 and 1, and the plain header claiming zstd, were moved out of line as they were, and va_cmid 99 tripped the Assert. On v15 those and va_cmid 3 fail with the error. The two truncated headers (6 and 8 bytes) are smaller than a TOAST pointer, so they are never moved out of line and the UPDATE keeps them as master does; ASan reports nothing there. > (Two tiny related validation polish items if you want them: toast_inline_compression_id() rejects method IDs above the last one in use (TOAST_LAST_COMPRESSION_ID, which each patch that adds a method moves up). toast_external_info_get() rejects a long pointer whose method byte names pglz or lz4, and toast_get_compression_id() reports a compressed pointer that decodes to no method as corrupt. I did not add the VARHDRSZ_COMPRESSED_DICT check to the validator. pg_column_compression() on a 10-byte dictionary header still says zstd_dict, but reading the value fails in dict_datum_get_id(), and toast_compression.h can't see that macro without a new include. > 3. Temp tables with ON COMMIT DELETE ROWS miss toast_dictionary_retire() > (heap.c, 0004) Fixed in heap_truncate(), as you suggested, under an active snapshot. compression_zstd_dict tests it with your sequence. > 4. Moving rd_toastdictoids / rd_toastdictvalid from 0005 into 0004 Done. 0004 now has the relcache cache, its cleanup in relcache.c, and the invalidation in dict_install(), so 0001-0004 stand on their own. 0005 only adds the evolution policy. > 5. Two minor gate-ordering items in toast_dictionary_maybe_evolve() (0005) Both done. The gates read only the dictionary's row. The dictionary count is taken just before the cap gate, and the bytes are fetched only for the held-out test. The "row count unknown" baseline is now recorded before the min_rows check. compression_dict_evolve tests it with min_rows above the table's size. best. -greg
Re: ZSTD TOAST compression, and an extensible compression method encoding
Hi Greg,
On Fri, Nov 6, 2026 at 7:31 PM Greg Burd wrote:
> Thanks, Hannu, and thanks, Manu, for the containment audit and the
> UPDATE numbers. v15 is attached; it applies on master as of
> 72b9498df9a.
Thanks! I ran another pass on v15 under cassert + UBSan, 002_pg_upgrade,
amcheck, and a streaming Hot Standby.
All five v14 items look cleanly resolved and tested (and keeping
VARHDRSZ_COMPRESSED_DICT out of toast_compression.h makes sense). Modulo
rebasing onto today's 4a95f56c04d (noted in #5 below), 0001-0003 look
Ready for Committer to me, and 0004 is very close as well.
Here is what turned up on 0004-0005 (plus the rebase note):
1. Unbounded sample buffer (> 1 GB StringInfo failure + stuck gates) in
toast_dictionary_maybe_evolve() (0005)
pg_train_toast_dictionary() stops scanning once nsamples >=
DICT_MAX_SAMPLES (10,000) or samples.len + len > dict_size *
DICT_SAMPLE_FACTOR (6.4 MB for a 64 kB dictionary).
By contrast, toast_dictionary_maybe_evolve() (toast_dictionary.c:1499)
caps dictsize at DICT_DEFAULT_SIZE (64 kB), yet loops over all numrows
(30,000 at default_statistics_target = 100, and up to 3,000,000 at
SET STATISTICS 10000), detoasting up to DICT_SAMPLE_LIMIT (128 kB) per
row into StringInfoData train and held with neither a sample-count cap
nor a byte-budget cap.
Even at default_statistics_target = 100, 24,000 * 128 kB = 3.0 GB, which
blows past MaxAllocSize (1 GB) on wide rows:
SET dictionary_evolution_min_interval = 0;
CREATE TABLE big_evo (id int, f1 text COMPRESSION zstd_dict);
ALTER TABLE big_evo ALTER COLUMN f1 SET (
dictionary_evolution = on,
dictionary_evolution_min_rows = 50,
dictionary_evolution_growth = 1.0
);
INSERT INTO big_evo
SELECT g, format('{"id":%s,"hdr":"tenant-alpha"}', g) ||
repeat('{"k":"val","status":"active","role":"member"},', 2900)
FROM generate_series(1, 11000) g;
-- Table is ~1.6 MB on disk, yet ANALYZE allocates > 1.3 GB and fails:
ANALYZE big_evo;
-- WARNING: automatic dictionary evolution for column "f1" of "big_evo"
-- was skipped: string buffer exceeds maximum allowed length
-- (1073741823 bytes)
Two consequences:
- Initial evolution never trains a dictionary on wide columns (even though
pg_train_toast_dictionary('big_evo', 'f1') succeeds in milliseconds
using 6.4 MB).
- Worse, when a column already has a dictionary and its growth + cooldown
gates open, enlargeStringInfo() throws *before* `declined:` calls
dict_set_gates(). PG_CATCH() rolls back the subtransaction, leaving
tdtraintime and tdtrainrows unchanged -- so every subsequent ANALYZE /
autoanalyze repeats the > 1 GB TOAST read, > 1 GB allocation, and
WARNING forever.
Capping the sample loop in toast_dictionary_maybe_evolve() at
DICT_MAX_SAMPLES and a byte budget matching DICT_DEFAULT_SIZE *
DICT_SAMPLE_FACTOR (~6.4 MB for train + ~1.6 MB for held) fixes both.
Note that acquire_sample_rows() returns rows[0..numrows-1] in physical
block order, so when numrows is large, striding across rows[] (rather
than taking only the first ~60 rows when values are ~128 kB) will keep
the sample spread across the whole table. (Also a tiny commit-message
nit on 0005: "no extra I/O" holds for inline values, whereas external
values do fetch up to 128 kB from TOAST that std_typanalyze skipped above
WIDTH_THRESHOLD = 1024; the ~8 MB cap bounds that I/O nicely too.)
2. Hot Standby recovery guard (and READ ONLY txn semantics) in
pg_train_toast_dictionary() (0004 & 0005)
On a Hot Standby, `ANALYZE t` fails cleanly via
PreventCommandDuringRecovery() ("ERROR: cannot execute ANALYZE during
recovery"), whereas `SELECT pg_train_toast_dictionary('t', 'f1')` passes
the RELOID ownership check and fails inside table_open(relid,
ShareUpdateExclusiveLock) with the low-level lock error:
ERROR: cannot acquire lock mode ShareUpdateExclusiveLock on database
objects while recovery is in progress
Peer SQL-callable maintenance functions (pg_restore_attribute_stats(),
gin_clean_pending_list(), brin_summarize_range()) guard against recovery
up front, so pg_train_toast_dictionary() should at minimum call
PreventCommandDuringRecovery("pg_train_toast_dictionary()") before the
RELOID lookup.
Relatedly: because ClassifyUtilityCommandAsReadOnly() allows ANALYZE in
READ ONLY transactions on primary, both `BEGIN READ ONLY; ANALYZE t;` and
`BEGIN READ ONLY; SELECT pg_train_toast_dictionary(...);` currently write
to pg_toast_dictionary. Allowing both on primary (matching ANALYZE /
pg_restore_attribute_stats, with PreventCommandDuringRecovery() on
pg_train_toast_dictionary()) seems fine to me; if instead you'd rather
forbid catalog/OID writes in XactReadOnly transactions, then both
PreventCommandIfReadOnly("pg_train_toast_dictionary()") and `if
(XactReadOnly) return;` in toast_dictionary_maybe_evolve() should check
it together so manual and automatic training behave the same way.
3. Missing relkind / catalog guard in toast_dictionary_maybe_evolve()
(0005)
dict_check_column() in 0004 restricts dictionaries to RELKIND_RELATION
and RELKIND_MATVIEW (!IsCatalogRelation()), and pg_dump only dumps those.
However, PostgreSQL accepts `CREATE FOREIGN TABLE ft (id int, f1 text
COMPRESSION zstd_dict)` + `ALTER FOREIGN TABLE ft ALTER COLUMN f1 SET
(dictionary_evolution = on)`, and `ANALYZE ft` calls
toast_dictionary_maybe_evolve(), which currently doesn't check relkind or
IsCatalogRelation(onerel) and will install orphaned rows in
pg_toast_dictionary if the FDW returns sample rows. Adding the same
(RELKIND_RELATION || RELKIND_MATVIEW) && !IsCatalogRelation(onerel) guard
at step (a) closes that.
4. attstorage (STORAGE PLAIN / EXTERNAL) consistency (0004 & 0005)
`ALTER TABLE ... ALTER COLUMN ... SET STORAGE PLAIN` (or `EXTERNAL`)
leaves attcompression set ('d'/'e') while disabling compression
(heaptoast.c only compresses EXTENDED and MAIN). Right now:
- both pg_train_toast_dictionary() and toast_dictionary_maybe_evolve()
still train and install dictionaries on PLAIN / EXTERNAL columns that
the toaster will never use; and
- after `SET STORAGE EXTERNAL` (or `PLAIN`) + `VACUUM FULL`, external
dict values are decompressed, yet dict_column_uses_dict() still returns
true, so toast_dictionary_retire() never retires tdcurrent.
Checking IsStorageCompressible(att->attstorage) in dict_check_column()
and toast_dictionary_maybe_evolve() avoids training unused dictionaries.
Checking it in toast_dictionary_keep() and dict_column_uses_dict() as
well would let `SET STORAGE PLAIN/EXTERNAL` + `VACUUM FULL` decompress
inline dict values and retire all dictionaries for the column (with the
expected caveat that if an inline dict value decompresses past
MaxHeapTupleSize under STORAGE PLAIN, VACUUM FULL raises "row is too big",
matching what master already does for external compressed datums after
SET STORAGE PLAIN).
5. Rebase note on 4a95f56c04d + minor polish
- Commit 4a95f56c04d ("Harden some allocations against integer
wraparound", committed today) conflicts with 0002 in varatt.h,
detoast.c, and toast_compression.c, and adds AllocSizeIsValid() checks
in pglz_* and lz4_*. When rebasing 0003-0005, mirroring those checks
in the new codecs keeps everything consistent:
* zstd_compress_datum(), zstd_dict_compress_datum(), and
zstd_dict_compressed_total(): check `ZSTD_isError(max_size) ||
!AllocSizeIsValid(max_size)` before palloc;
* lz4_dict_compress_datum(): check `max_size <= 0 ||
!AllocSizeIsValid(max_size)` (LZ4_compressBound() returns 0 on
oversize input, where AllocSizeIsValid(0) is true);
* zstd_decompress_datum() and {zstd,lz4}_dict_decompress_datum():
`Assert(AllocSizeIsValid(VARDATA_COMPRESSED_GET_EXTSIZE(value)))`;
* zstd_decompress_datum_slice() and
{zstd,lz4}_dict_decompress_datum_slice(): check
`!AllocSizeIsValid(slicelength)` before palloc / comparison.
- Minor polish:
* doc/src/sgml/ref/alter_table.sgml: ~20 lines above 0005's new
paragraph, the existing text still says "Currently, the only defined
per-attribute options are n_distinct and n_distinct_inherited". It
may also help to mention that per-attribute options are not inherited
by partitions, so dictionary_evolution* must be set on leaf
partitions.
* detoast.h: toast_external_info_get() rejects a long pointer naming
pglz/lz4 (and could also check cmid > TOAST_LAST_COMPRESSION_ID),
while a corrupt *plain* pointer with method bits == 2 still decodes
as zstd in pg_column_compression(); adding the symmetric `else if`
branch makes external and inline validation match completely.
* toast_dictionary.c: dict_install() already has `Relation rel` open,
so CacheInvalidateRelcache(rel) avoids the extra RELOID syscache
lookup inside CacheInvalidateRelcacheByRelid().
Cheers,
Hannu
Re: ZSTD TOAST compression, and an extensible compression method encoding
On Sun, Nov 9, 2026 at 17:54 UTC, Hannu Krosing wrote:
> Thanks! I ran another pass on v15 under cassert + UBSan, 002_pg_upgrade,
> amcheck, and a streaming Hot Standby.
Thanks again Hannu for giving this your thought and time. I can see
that you are interested/invested in this thread, thanks for that effort.
> 1. Unbounded sample buffer (> 1 GB StringInfo failure + stuck gates)
Fixed.
The evolution sample loop now stops at DICT_MAX_SAMPLES values or a byte
budget (DICT_DEFAULT_SIZE * DICT_SAMPLE_FACTOR for training, plus a
quarter for the held-out set), like the manual trainer. rows[] is in
physical order and either bound can stop the loop early, so it visits
the rows on a stride coprime with numrows (close to the golden ratio),
which keeps a bounded sample spread across the whole table rather than
taking the first few wide rows. Your big_evo repro now trains in ~75 ms
using a few MB. Because the loop no longer throws, the stuck-gates case
is gone too, but the gate restart on a declined or failed candidate
(from v15) covers it regardless.
> 2. Hot Standby recovery guard (and READ ONLY txn semantics)
pg_train_toast_dictionary() now calls
PreventCommandDuringRecovery("pg_train_toast_dictionary()") before the
RELOID lookup, so on a standby it fails with "cannot execute
pg_train_toast_dictionary() during recovery", the same shape as ANALYZE,
instead of the lock error. I left READ ONLY as it is on the primary,
matching ANALYZE and pg_restore_attribute_stats(): both the manual
function and automatic evolution write pg_toast_dictionary in a READ
ONLY transaction, which seems right since ANALYZE does.
> 3. Missing relkind / catalog guard in toast_dictionary_maybe_evolve()
Fixed.
Evolution now returns early unless the relation is a plain table or
matview and not a catalog, the same check dict_check_column() makes for
the manual path, so ANALYZE on a foreign table with an opted-in
dictionary column installs nothing.
I didn't add a regression test, there's no in-tree FDW that returns
sample rows in a core test, and the dummy handler errors before
evolution runs.
> 4. attstorage (STORAGE PLAIN / EXTERNAL) consistency
Fixed with one predicate, dict_attr_uses_dict(), that requires a
dictionary method and a storage mode the toaster compresses (EXTENDED or
MAIN). pg_train_toast_dictionary() and evolution refuse a PLAIN or
EXTERNAL column, and dict_column_uses_dict() / toast_dictionary_keep()
use it too, so SET STORAGE EXTERNAL + VACUUM FULL decompresses the
inline values and retires every dictionary for the column.
compression_zstd_dict has a case for that.
> 5. Rebase note on 4a95f56c04d + minor polish
Done.
The new codecs mirror the hardening: zstd_compress_datum(),
zstd_dict_compress_datum() and zstd_dict_compressed_total() reject a bad
or oversize ZSTD_compressBound() (and lz4_dict_compress_datum() a bad
LZ4_compressBound()) before palloc; the whole-value decompressors assert
AllocSizeIsValid() on the stored size; and the slice decompressors check
the requested length.
Minor polish:
toast_external_info_get() now also maps a plain pointer whose method
bits name something other than pglz or lz4 to the invalid id, so
external and inline validation match; dict_install() uses
CacheInvalidateRelcache(rel) with the relation it already holds; and
alter_table.sgml drops the stale "only n_distinct and
n_distinct_inherited" sentence and notes that per-attribute options are
set on leaf partitions.
v16 is attached, it applies on master as of 952bab8b74d. It has the
AllocSizeIsValid() changes from 4a95f56c04d folded into the new codecs
as you noted.
best.
-greg
Re: ZSTD TOAST compression, and an extensible compression method encoding
On Sun, Nov 9, 2026 at 17:54 UTC, Hannu Krosing wrote:
> Thanks! I ran another pass on v15 under cassert + UBSan, 002_pg_upgrade,
> amcheck, and a streaming Hot Standby.
v17 is attached; it applies on master as of 77bba5454f9. There was no
new review of v16, so this round comes from a full pass of my own over
the series, held to the standard I'd expect a committer to apply.
Most of the changes are in 0001 and 0002, since those are the ones
closest to being committed.
0001 (toast_external_info_get)
Michael's objection to v7-0001 [1] was that adding only compress_method
to toast_external_data left it "half-baked due to the inconsistency this
brings with extsize and VARATT_EXTINFO_GET_EXTSIZE", and that
is_compressed belonged there too.
v16 still had that "half-baked" idea in code. Every caller derived the
saved size and the compressed flag from the raw extinfo word. v17's
0001 decodes all three (extsize, is_compressed, compress_method) once
and removes extinfo from the struct. The twelve places in detoast.c,
toast_compression.c, reorderbuffer.c and amcheck that computed the size
or the flag from extinfo now read the fields, and amcheck's
ToastedAttribute keeps the saved size rather than the raw word.
toast_save_datum() still builds va_extinfo itself. No behavior change.
0002 (long form)
With 0001 normalizing the struct, "invalid method" and "not compressed"
are now distinct (!is_compressed vs. is_compressed && compress_method ==
INVALID), so callers no longer need the raw word to tell them apart.
amcheck printed the folded method ID: a forged pointer whose method byte
was 0 or 200 was reported as "invalid compression method id 3".
toast_external_data now also keeps the stored method bits and method
byte, and amcheck reports what is on disk, distinguishing a plain
pointer with bad method bits, a long pointer without the long-form bits,
and a long pointer whose byte is not a long-form method. The validation
that the inline header and the pointer share is now one function,
toast_compression_id_resolve(), instead of two copies. I dropped
VARTAG_IS_ONDISK_OID8(): it had two callers, and you have said there are
already too many of these helpers.
There was no in-tree test of any of the new rejection paths; the
corruption checks I described earlier lived in a scratch harness. A new
TAP test, amcheck/t/007_verify_toast_pointer.pl, forges pointers on disk
and checks that amcheck reports each case with the stored value and that
reading them fails cleanly. 0002 has the plain-pointer cases; 0003 adds
the long-pointer ones once zstd writes long-form pointers. The commit
message also says plainly that 0002's writer side is first reached by
zstd in 0003.
0003 (zstd)
The slice decoder sizes its window buffer from the frame header, and
that buffer lives in the backend-lifetime decompression context, so a
corrupt header could grow the context to zstd's default limit of 128MB
outside any memory context. The context now caps the window at 2^23
(the default level never uses more than 2^21 in libzstd 1.4.0 through
1.5.7), and the slice path checks the frame's recorded content size
against our header, as the whole-value path already does through
ZSTD_decompressDCtx().
The slice "loop" made one ZSTD_decompressStream() call, since all the
input was handed over at once, so its CHECK_FOR_INTERRUPTS() did
nothing. It now feeds the input in ZSTD_DStreamInSize() chunks (four
calls for a 1.5MB slice under gdb). And the text slice tests did not
reach the slice path in a UTF-8 database, because text_substring() asks
for four bytes per character; the test now slices a bytea across the
128kB block boundary. The comment and commit message had overstated the
cost of a one-shot ZSTD_compress(): it allocates about 90kB for a 4kB
value, and about 1.3MB only from 1MB up.
0004 (dictionaries)
- REPLICA IDENTITY FULL logged old tuples with dictionary values
decompressed, because HEAP_HASEXTERNAL sends the tuple through
toast_flatten_tuple(). In a 2000-row UPDATE that was 10MB of WAL
instead of 0.7MB. Logical decoding reads those values with the
catalog as of the change, which still has their dictionary, so a new
toast_flatten_tuple_for_wal() fetches only out-of-line fields there.
test_decoding still decodes the old values after the dictionary has
been retired.
- pg_train_toast_dictionary() required ownership while ANALYZE, which
installs dictionaries through 0005, accepts MAINTAIN. It now requires
MAINTAIN too, checked before the lock as before.
- A table owner had no way to see their own dictionaries, since the
catalog is closed to PUBLIC. A new view, pg_toast_dictionaries, shows
their metadata (not their contents) for the columns the user can
read, as pg_stats does for pg_statistic.
- pg_dump --binary-upgrade ran one dictionary query per table. It now
collects the tables that have dictionaries up front.
- The docs now say that plain dumps and logical replication carry no
dictionaries.
0005 (evolution)
Several things here were wrong or undocumented.
- Autovacuum's ANALYZE trains and installs dictionaries. I think that
is what a column that opts in wants, but it was documented nowhere.
It is now, and a new SIGHUP setting, dictionary_evolution_autovacuum,
turns it off.
- ANALYZE in a READ ONLY transaction installed a dictionary. That
matches what I wrote last time about following ANALYZE, but ANALYZE
is allowed there because its statistics don't change what a dump
contains, and a new dictionary changes how every later value is
stored. Evolution now does nothing in a read-only transaction. The
manual function is unchanged, since it is an explicit request.
- dictionary_evolution_min_interval silently saturated at 24.8 days; it
now uses TimestampDifferenceExceedsSeconds().
- The sampling loop now honors the cost-based vacuum delay, and skips
values over 1MB: only pglz can decompress a prefix, so the "128kB
prefix" claim in the commit message was wrong for zstd and lz4.
- Hitting the retained-dictionary cap logged the same line on every
ANALYZE; it now restarts the gates, and the message follows the style
guide (errdetail/errhint, qualified name). The WARNING for a skipped
round keeps the original error code.
- TRUNCATE kept the old row-count baseline, so evolution stayed off
until the table regrew past it. TRUNCATE now resets it.
- The regression test claimed the first rows "decode with the retired
dictionary stamped into them", but they were plain zstd. The test
now rewrites them under the first dictionary and checks they read
back after a second is adopted and that VACUUM FULL then drops the
first. It also covers TRUNCATE and read-only transactions.
- The settings moved to the vacuum group; tab completion knows the
column options.
Cost when the feature is not used
Robert's question from the first thread [2] was what this costs users
who don't use it. I ran release builds (no cassert) of the series base
and of v17 on an m5d.metal (Xeon 8259CL, turbo and deep C-states off,
THP never), each server pinned to its own eight cores on one NUMA node,
15 runs per cell in ABBA order, with an A/A run of the base against
itself first:
workload base A/A v17/base v17/base
ms (cores A) (swapped)
INSERT..SELECT, 400k lz4 values 269 1.088 0.985 0.980
INSERT..SELECT, 100k pglz values 104 1.078 0.996 1.018
INSERT, 2M narrow rows 2969 1.070 1.034 0.971
UPDATE, 400k rows with lz4 687 1.025 1.009 1.022
scan + detoast, 400k lz4 values 1777 1.003 1.000 1.120*
scan + detoast, 2000 external 169 0.929 0.927 0.998
substr(), 2000 external 44 1.005 0.955 0.954
The A/A column is the noise floor: the base against itself, on
different cores, already moves up to 9%. Every v17/base ratio is inside
that. The one that holds on both core assignments is substr() of
external values, about 4.5% faster; I have not looked into why.
The 1.120 marked * came from a single run of that server; with both
builds on the same cores, one at a time and 24 runs each, that workload
measured 0.999 and 1.000.
So for users who use neither zstd nor dictionaries the series costs
nothing measurable here, which is what the code suggests. The only new
per-value work on these paths is a test of the compressed header's
method bits in heap_fill_tuple(), reached only for values already
compressed in-line.
best.
-greg
[1] https://postgr.es/m/aryp-_pANFiyzVlx@paquier.xyz
[2] https://postgr.es/m/CA+TgmoY8uCKFvVYDQsLbfhY3JYrduXE7WHi75hmfTWxjWioaaw@mail.gmail.com
Re: ZSTD TOAST compression, and an extensible compression method encoding
Hi Greg, On Sat, Nov 14, 2026 at 1:50 PM Greg Burd wrote: > Most of the changes are in 0001 and 0002, since those are the ones > closest to being committed. I found nothing broken in 0001 or 0002, and one check in 0002 that no test exercises. 0001: reading pglz and lz4 values through text, substr(), pg_column_*(), verify_heapam() and test_decoding gives byte-identical output (58,990 lines) on master and master+0001, and each of four wrong conversions I planted changes that output. 0002: on 0001-0003 under cassert, reverting any one check in toast_compression_id_resolve() fails t/007, except method_byte == TOAST_INVALID_COMPRESSION_ID. From 0004 on, with the last ID at 5, that check alone keeps a long pointer with byte 3 away from the Assert in toast_compression_id_needs_cmid_byte(), and t/007 has no byte-3 case. A byte-3 row in the long-form part of t/007 would cover it. Old data reads the same with a master data directory started under 0001-0003, and after pg_upgrade from REL_18 and REL_19 to 0001-0003. The scripts and the results, forged pointers included, are attached. Manu
Re: ZSTD TOAST compression, and an extensible compression method encoding
Hi Greg
> On Sun, Nov 9, 2026 at 17:54 UTC, Hannu Krosing wrote:
> > Thanks! I ran another pass on v15 under cassert + UBSan, 002_pg_upgrade,
> > amcheck, and a streaming Hot Standby.
>
> Thanks again Hannu for giving this your thought and time. I can see
> that you are interested/invested in this thread, thanks for that effort.
Thanks!
I am still working on a (more widely ambitious :) ) Direct TOAST project
some parts of which also have the dictionary-based compression
implementation, so following this has been very informative.
This also makes me interested to see this one moving forward in a way
that will not blow up maintainer load in the future.
And of course I am also interested in getting the idea of having an
efficient compression in the core more widely accepted :)
So here is the overview of joint findings after analyzing v16 and v17 patches
On Sat, Nov 14, 2026 at 2:50 PM Greg Burd wrote:
> v17 is attached; it applies on master as of 77bba5454f9. There was no
> new review of v16, so this round comes from a full pass of my own over
> the series, held to the standard I'd expect a committer to apply.
Thanks! I had just finished a review pass on v16 when v17 arrived, so I
ran the full build matrix, pgindent (with DWARF-extracted typedefs),
ASan + UBSan + cassert, 002_pg_upgrade, and two-cluster logical
replication (REPLICA IDENTITY FULL across retraining + VACUUM FULL + DROP
COLUMN) on v17 as well.
All of my v15 items were resolved in v16, and the v17 cleanups read very
well -- especially normalizing toast_external_data in 0001,
toast_compression_id_resolve() + 007_verify_toast_pointer.pl in 0002, the
2^23 window cap + chunked slice loop in 0003, toast_flatten_tuple_for_wal()
and pg_toast_dictionaries in 0004, and dictionary_evolution_autovacuum +
XactReadOnly + TRUNCATE baseline reset in 0005. Your benchmark table for
non-users is very reassuring too.
Here is what turned up across the combined v16 + v17 pass:
=== Important items ===
1. Big-endian failure in contrib/amcheck/t/007_verify_toast_pointer.pl
(0002 & 0003)
In 007_verify_toast_pointer.pl:
my ($lp, $dataoff, $b4, $b5) = split /\|/, $row;
is("$b4/$b5", "1/18", "tuple $lp holds a plain on-disk TOAST pointer");
...
is("$b4/$b5", "1/19", "tuple $lp holds a long on-disk TOAST pointer");
In varatt.h, SET_VARTAG_1B_E writes va_header = 0x01 (1) on little-endian
machines, but writes va_header = 0x80 (128) under WORDS_BIGENDIAN (s390x,
ppc64, sparc64). set_method_bits() right below checks `(pack('L', 1) eq
pack('V', 1))`, so deriving `$va_ext_hdr = ... ? 0x01 : 0x80` for those
two assertions will keep big-endian buildfarm animals green.
2. RelationInvalidateRelation() leaves a rolled-back subtransaction's
dictionary OID cached in rd_toastdictoids (relcache.c, 0004)
0004 frees rd_toastdictoids and rd_toastdictvalid in
RelationDestroyRelation() and zeroes them in load_relcache_init_file(),
but does not clear them in RelationInvalidateRelation() (relcache.c:2556,
right next to rd_amcache).
When a subtransaction installs a dictionary D1 (dict_install() ->
CacheInvalidateRelcache(rel)), populates rel->rd_toastdictoids via a
write, and then rolls back while an outer statement holds `rel` open
(rd_refcnt > 0, e.g. inside a trigger), AtEOSubXact_Inval(false) runs
with IsTransactionState() == false. RelationFlushRelation() takes the
`!IsTransactionState()` branch (relcache.c:2869) and calls
RelationInvalidateRelation(rel) instead of RelationRebuildRelation(rel),
while the outer statement continues using its open Relation pointer as-is.
dict_cache_invalidate() evicts D1 from cdicts[] / lz4dicts[], but
rel->rd_toastdictoids still holds D1's OID, so when the outer statement
writes its row, toast_dictionary_current() returns D1 and dict_fetch()
fails with `ERROR: compression dictionary does not exist` -- even
when the column already had a valid committed dictionary D0:
CREATE FUNCTION doc(i int) RETURNS text LANGUAGE SQL IMMUTABLE AS $$
SELECT repeat(format('{"id":%s,"tenant":"acme","status":"active"}',
i), 50)
$$;
CREATE TABLE t_d0 (id int, f1 text COMPRESSION zstd_dict);
INSERT INTO t_d0 SELECT g, doc(g) FROM generate_series(1, 100) g;
SELECT pg_train_toast_dictionary('t_d0', 'f1', 4096); -- commits D0
CREATE FUNCTION trg_d0_fn() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
IF NEW.id = 101 THEN
BEGIN
PERFORM pg_train_toast_dictionary('t_d0', 'f1', 4096);
INSERT INTO t_d0 VALUES (999, doc(999));
RAISE EXCEPTION 'abort subxact';
EXCEPTION WHEN OTHERS THEN
NULL;
END;
END IF;
RETURN NEW;
END $$;
CREATE TRIGGER trg_d0 BEFORE INSERT ON t_d0
FOR EACH ROW EXECUTE FUNCTION trg_d0_fn();
\c -
INSERT INTO t_d0 VALUES (101, doc(101));
-- ERROR: compression dictionary 16393 does not exist
Freeing and NULLing rd_toastdictoids and rd_toastdictvalid inside
RelationInvalidateRelation() (alongside rd_amcache) fixes this cleanly
and also covers RelationRebuildRelation()'s HistoricSnapshotActive()
early return.
=== Smaller correctness & consistency items ===
3. pg_train_toast_dictionary() ACL_MAINTAIN nuances (0004 & 0005)
Three small things to consider on the v17 switch from ownership to
ACL_MAINTAIN:
- Database-owner parity with ANALYZE: vacuum_is_permitted_for_relation()
(and RangeVarCallbackForStats) allows `(object_ownercheck(
DatabaseRelationId, MyDatabaseId, userid) && !relisshared)` in addition
to ACL_MAINTAIN. Right now a non-superuser database owner can install
a dictionary via ANALYZE in 0005, yet gets `permission denied` from
pg_train_toast_dictionary().
- Post-lock ACL recheck & pre-lock relkind: checking permissions before
table_open(relid, ShareUpdateExclusiveLock) avoids unprivileged lock
blocking, but re-checking after table_open() closes the TOCTOU window
if REVOKE MAINTAIN or ALTER TABLE OWNER TO committed while waiting on
the lock (and checking classform->relkind before table_open() avoids
locking views/sequences/partitioned/foreign tables and gives the same
error message on indexes).
- Retained-dictionary cap: in 0005, dictionary_evolution_max_retained (8)
and min_interval are PGC_SUSET so a non-owner MAINTAIN role cannot
churn ANALYZE to bloat pg_toast_dictionary; with ACL_MAINTAIN on
pg_train_toast_dictionary(rel, col, 1048576), a non-owner MAINTAIN role
can loop manual training without hitting max_retained unless manual
training either enforces max_retained (at least for non-owners) or
stays owner-only.
4. Sample starvation in pg_train_toast_dictionary() when dict_size <= 9175
on wide rows or early outliers (0004)
pg_train_toast_dictionary() slices up to DICT_SAMPLE_LIMIT (128 kB) per
row and breaks immediately on `samples.len + len > dict_size *
DICT_SAMPLE_FACTOR`, whereas zstd's ZDICT_trainFromBuffer() requires at
least 7 samples:
- On columns with >= 128 kB values, every dict_size in [256 .. 9175]
(including 4096 and 8192) breaks out with 0..6 samples and returns
NULL.
- Even on a normal small-row table (say 1,000 x 3 kB rows), a single
>= 128 kB outlier on block 0 causes dict_size = 1024 to break on row 0
with `nsamples = 0` without scanning rows 2..1000.
Capping the per-row slice in pg_train_toast_dictionary() to
`Min(DICT_SAMPLE_LIMIT, ((size_t) dict_size * DICT_SAMPLE_FACTOR) / 10)`
ensures even dict_size = 256 gathers ~2.5 kB prefixes across >= 10 rows
within the byte budget.
5. Missing DECLARE_FOREIGN_KEY in pg_toast_dictionary.h (0004)
pg_statistic.h and pg_attrdef.h both declare:
DECLARE_FOREIGN_KEY((tdrelid, tdattnum), pg_attribute, (attrelid, attnum));
so Catalog.pm emits the composite FK into system_fk_info.h for
pg_get_catalog_foreign_keys() and the oidjoins test. Since dropped
columns keep their pg_attribute row until heap_drop_with_catalog() (where
RemoveToastDictionaries() runs before DeleteAttributeTuples()), adding
that macro to pg_toast_dictionary.h (and updating oidjoins.out) gives
free catalog FK validation.
=== Minor polish ===
- 0002 (detoast.c / toast_compression.c / 007_verify_toast_pointer.pl):
verify_heapam() flags `!is_compressed && VARTAG_IS_ONDISK_LONG(tag)`
("is not compressed but has a long TOAST pointer"), whereas
toast_fetch_datum[_slice]() and toast_get_compression_id() accept an
uncompressed long pointer silently; rejecting that case at runtime (and
adding a test case to 007_verify_toast_pointer.pl) would make both
match.
- 0004 (toast_dictionary.c / compression_zstd_dict.sql):
* dict_get_ddict() creates dict_dctx without setting
ZSTD_d_windowLogMax = ZSTD_TOAST_WINDOWLOG_MAX (unlike zstd_get_dctx()
in 0003).
* compression_zstd_dict.sql comments "-- values nested in containers:
rows, arrays, ranges of text are flattened", though cmnest only tests
a composite and an array (we tested textrange/textmultirange and they
flatten properly).
- 0005 (matview.c / toast_dictionary.c):
* `REFRESH MATERIALIZED VIEW mv WITH NO DATA` swaps in an empty heap
via finish_heap_swap() -> toast_dictionary_retire(OIDOldHeap, false),
leaving the pre-empty tdtrainrows on a 0-row unpopulated matview
instead of resetting tdtrainrows = 0 like TRUNCATE does.
* zstd_dict_compressed_total() still has bare
`out = palloc(ZSTD_compressBound(maxlen));` without ZSTD_isError() /
AllocSizeIsValid() (and lz4_dict_compressed_total() omits
!AllocSizeIsValid(bound)).
* Under `--without-zstd --with-lz4`, an `#ifndef USE_ZSTD return;
#endif` at step (a) of toast_dictionary_maybe_evolve() avoids wasted
TOAST reads before dict_train_zdict() returns 0.
Cheers,
Hannu
Re: ZSTD TOAST compression, and an extensible compression method encoding
On Sun, Nov 15, 2026 at 11:33 UTC, Hannu Krosing wrote:
> I am still working on a (more widely ambitious :) ) Direct TOAST project
> some parts of which also have the dictionary-based compression
> implementation, so following this has been very informative.
>
> This also makes me interested to see this one moving forward in a way
> that will not blow up maintainer load in the future.
Hi Hannu,
Same goal here. If the dictionary lifecycle here turns out to be
something Direct TOAST can reuse, even better.
> 1. Big-endian failure in contrib/amcheck/t/007_verify_toast_pointer.pl
Good catch, and embarrassing: I checked the endianness for va_extinfo
and then hardcoded the header byte two lines above. The test now
expects 0x80 or 0x01 depending on the same pack() test. I have no
big-endian box to run it on, so that one is by reading varatt.h only.
> 2. RelationInvalidateRelation() leaves a rolled-back subtransaction's
> dictionary OID cached in rd_toastdictoids (relcache.c, 0004)
Reproduced it with your trigger exactly, and fixed it the way you
suggest: RelationInvalidateRelation() now frees rd_toastdictoids and
rd_toastdictvalid next to rd_amcache. Your case is in
compression_zstd_dict now; it fails with "compression dictionary N does
not exist" without the fix.
> 3. pg_train_toast_dictionary() ACL_MAINTAIN nuances (0004 & 0005)
All three. The function now accepts what ANALYZE accepts (MAINTAIN, or
owning the database), checks the relation kind before taking the lock,
and checks the privilege again once it holds the lock.
On the cap, I made max_retained bound manual training too, for everyone
but superusers. That seemed better than going back to owner-only: the
MAINTAIN role that could loop the function can also VACUUM FULL, so it
can clear the cap the normal way, and owners get the same limit, which
is easier to explain. The cap lives in 0005, so 0004 on its own still
has no limit. I'm on the fence with regards to moving the GUC into
0004.
While there I found two problems with the cap itself. It counts the
current dictionary, so at its old minimum of 1 a column could never be
trained again and the hint about VACUUM FULL could never help; the
minimum is 2 now. And when evolution hit the cap it restarted both
gates, so after the rewrite it waited for the table to double again
before retraining. It now restarts only the cooldown, and a test covers
resuming after a rewrite.
> 4. Sample starvation in pg_train_toast_dictionary() when dict_size <= 9175
> on wide rows or early outliers (0004)
Yes, and it is worse than an edge case: a 4kB dictionary on a column of
128kB values could never be trained. I used your cap on the per-value
slice, a tenth of the budget. Both of your examples train now, and
there's a test with one wide value in front of normal ones.
> 5. Missing DECLARE_FOREIGN_KEY in pg_toast_dictionary.h (0004)
Added, and oidjoins checks it.
> - 0002: verify_heapam() flags `!is_compressed && VARTAG_IS_ONDISK_LONG(tag)`
> ("is not compressed but has a long TOAST pointer"), whereas
> toast_fetch_datum[_slice]() and toast_get_compression_id() accept an
> uncompressed long pointer silently
Agreed; the readers refuse it now too, through one function that
toast_get_compression_id() also calls. It's worse than a mismatch: a
reader would have returned the compressed bytes as the value. t/007
forges one by shrinking va_rawsize.
> - 0004: dict_get_ddict() creates dict_dctx without setting
> ZSTD_d_windowLogMax
Fixed; the limit moved into toast_compression.h so both contexts use it.
(Strictly it only matters for streaming decompression, which the
dictionary path doesn't use yet, so the comment now says so.)
> compression_zstd_dict.sql comments "-- values nested in containers:
> rows, arrays, ranges of text are flattened", though cmnest only tests
> a composite and an array
The comment promised more than the test checked. It has a textrange
now.
> - 0005: `REFRESH MATERIALIZED VIEW mv WITH NO DATA` ... leaving the
> pre-empty tdtrainrows
Fixed for any non-concurrent REFRESH, which replaces the contents just
like TRUNCATE. The test no longer pokes the catalog to set it up.
> zstd_dict_compressed_total() still has bare
> `out = palloc(ZSTD_compressBound(maxlen));`
Fixed, and lz4_dict_compressed_total() too.
> Under `--without-zstd --with-lz4`, an `#ifndef USE_ZSTD return;
> #endif` at step (a) of toast_dictionary_maybe_evolve()
Done.
On Sun, Nov 15, 2026 at 04:53 UTC, Manu wrote:
> From 0004 on, with the last ID at 5, that check alone keeps a long
> pointer with byte 3 away from the Assert in
> toast_compression_id_needs_cmid_byte(), and t/007 has no byte-3 case.
Thanks, that is exactly the kind of hole I wanted t/007 to close.
There's a byte-3 row now.
Your other remark in checks.txt, that a zstd value whose pointer says 4
or 5 goes unnoticed because readers trust the stored header, also seemed
worth fixing. amcheck now compares the pointer's method with the
compressed header at the start of the first chunk (with check_toast).
An invalid header there is reported by what is stored, like the pointer
checks, and a valid but different method by both IDs. t/007 has the
second case from 0004 on, where 4 is a real method; in 0003 the same
forged byte is just an unknown method. The scripts were a big help, I
reused their layout for the new cases.
What else changed:
- t/007 read the forged uncompressed value with length(), which
answers from va_rawsize without fetching anything, so the test
passed or failed depending on the platform. CI caught it on 32-bit,
autoconf and MinGW. It reads the value now. The test also used
md5(), which FIPS builds refuse, and its zstd values stayed inline
at 32kB blocks; both fixed.
- lz4_dict used LZ4_initStream() and LZ4_resetStream_fast(), which are
lz4 1.9.0 and later, while configure accepts any lz4. LZ4_loadDict()
resets the stream in every version, so the stream is now created
once with LZ4_createStream() and nothing else is needed.
- Smaller cleanups: the zstd_dict and lz4_dict cases in
toast_compress_datum_rel() are one case; the relkind check is done
once, with errdetail_relkind_not_supported(); DictCompressRoutine
loses train(), which both codecs pointed at the same function; the
docs say lz4 uses only the last 64kB of a dictionary, and the
superuser-only settings say so.
Thank you both. v19 is attached; it applies on master as of
11591f273e6.
best.
-greg
Re: ZSTD TOAST compression, and an extensible compression method encoding
Hi Greg,
On Tue, Nov 17, 2026 at 6:54 PM Greg Burd wrote:
> Thank you both. v19 is attached; it applies on master as of
> 11591f273e6.
Thanks for v19, and especially for attaching notes.txt -- having the exact
H*/M*/R* mapping and test names made this pass a pleasure to verify.
I ran v19 on current master under ASan + UBSan + cassert, pgindent, the
pg_upgrade suites (including matviews and dropped zstd_dict columns),
SP-GiST / GIN / BRIN index checks, and a concurrent UPDATE loop
overlapping REPACK (CONCURRENTLY).
All of the v17 items (and your R* fixes, including the liblz4 < 1.9.0
stream fix and the cap minimum/baseline fixes) look good. 0001-0003 look
Ready for Committer to me, and 0004-0005 only have one real logic bug in
v19's matview refresh change plus a FIPS test nit and tiny polish.
=== On moving max_retained into 0004 ===
> On the cap, I made max_retained bound manual training too, for everyone
> but superusers. That seemed better than going back to owner-only: the
> MAINTAIN role that could loop the function can also VACUUM FULL, so it
> can clear the cap the normal way, and owners get the same limit, which
> is easier to explain. The cap lives in 0005, so 0004 on its own still
> has no limit. I'm on the fence with regards to moving the GUC into
> 0004.
Your rule (bounding non-superuser manual training too, bumping min to 2,
and restarting only the cooldown when hitting the cap) makes a lot of
sense.
If there is any chance 0004 lands ahead of 0005, I'd vote for moving the
GUC into 0004 since 0004 is what opens pg_train_toast_dictionary() to
MAINTAIN. (Naming it `toast_dictionary_max_retained` might also read a
bit more naturally now that it applies to manual training even when
`dictionary_evolution = off`, though keeping the current name if 0004 and
0005 go in together is fine too.)
=== Remaining items in v19 ===
1. Unconditional tdtrainrows reset on non-concurrent REFRESH MATERIALIZED
VIEW prevents matviews from ever evolving (matview.c, 0005)
In RefreshMatViewByOid() (matview.c:354):
refresh_by_heap_swap(matviewOid, OIDNewHeap, relpersistence);
toast_dictionary_retire(matviewOid, true);
For `REFRESH MATERIALIZED VIEW mv WITH NO DATA` (or a refresh that
populates 0 rows), resetting `tdtrainrows = 0` like TRUNCATE is right.
However, doing it unconditionally on every populated non-concurrent
`REFRESH MATERIALIZED VIEW mv` breaks automatic evolution on matviews:
unlike a regular table (which grows via INSERTs after TRUNCATE + ANALYZE
sets a baseline), a matview can *only* grow across REFRESH cycles. With
`tdtrainrows` reset to 0 on every plain REFRESH, the next `ANALYZE mv`
always enters the "row count unknown" branch in
toast_dictionary_maybe_evolve():
if (OidIsValid(curid) && currows <= 0)
{
if (totalrows > 0)
dict_set_gates(onerel, attnum, (int64) totalrows, curtime);
goto done;
}
so it records the new row count and jumps to `goto done` without ever
testing a candidate dictionary (e.g., 300 rows -> ANALYZE installs dict1
-> plain REFRESH to 1,500 rows -> ANALYZE just sets tdtrainrows=1500 ->
plain REFRESH to 6,000 rows -> ANALYZE just sets tdtrainrows=6000, keeping
dict1 forever, whereas REFRESH CONCURRENTLY evolves to dict2).
Since RefreshMatViewByOid() already tracks `uint64 processed`, and
finish_heap_swap() inside refresh_by_heap_swap() has already called
`toast_dictionary_retire(OIDOldHeap, false)` to delete superseded
dictionaries, guarding the reset with:
if (skipData || processed == 0)
toast_dictionary_retire(matviewOid, true);
resets the baseline whenever a refresh empties the matview while letting
populated refreshes evolve normally across ANALYZE runs.
2. Three md5() calls left in 0004's SQL tests (FIPS-mode OpenSSL)
In R2 you switched t/007 from md5() to sha256() for FIPS builds, but
three md5() calls remain in 0004's SQL regression tests:
- compression_zstd_dict.sql: doc(i) (`md5(i::text)`) and cmwide
(`repeat(md5('wide'), 8000)`)
- compression_lz4_dict.sql: doc(i) (`md5(i::text)`)
Switching those three to `fipshash(...)` (like compression_zstd.sql)
avoids failures on FIPS-enabled OpenSSL animals.
=== Minor polish ===
- verify_heapam.c:1680 (0002 & 0004): the new chunk-0 header check is
gated by `chunksize >= (int32) sizeof(uint32)`, so if chunk 0 of a
compressed external value is truncated below 4 bytes (0002), or has
5..8 bytes on a zstd_dict / lz4_dict value (truncating the 4-byte
dictid, 0004), `verify_heapam(..., check_toast => true)` reports 0
errors while detoasting fails with `compressed [dictionary] data is
corrupt`.
- 007_verify_toast_pointer.pl:55 (0002): comment still says `one byte
0x01` three lines below `$va_1b_e`.
- pg_dump TAP tests (0004 & 0005): 0003 added `test_compression_zstd` to
006_pg_dump_compress.pl; adding `zstd_dict`/`lz4_dict` cases there and
a `dictionary_evolution` attoptions check in 002_pg_dump.pl would round
out the pg_dump test coverage (the C code itself dumps both fine).
- SGML nits (0004):
* create_table.sgml:372 and alter_table.sgml:471 still say "The
supported compression methods are pglz, lz4, and zstd." right before
the new paragraphs introducing zstd_dict and lz4_dict.
* system-views.sgml: stray extra blank line added between pg_tables and
pg_timezone_abbrevs, and missing blank line before
pg_toast_dictionaries.
Cheers,
Hannu
Re: ZSTD TOAST compression, and an extensible compression method encoding
On Thursday, November 19th, 2026 at 3:27 PM, Hannu Krosing wrote:
> Hi Greg,
Hi Hannu,
Thanks for the careful pass over v19, and for separating the one real
bug from the polish.
> If there is any chance 0004 lands ahead of 0005, I'd vote for moving the
> GUC into 0004 since 0004 is what opens pg_train_toast_dictionary() to
> MAINTAIN. (Naming it `toast_dictionary_max_retained` might also read a
> bit more naturally now that it applies to manual training even when
> `dictionary_evolution = off`, though keeping the current name if 0004 and
> 0005 go in together is fine too.)
I left the GUC in 0005 for v20. The cap only has teeth once 0005 adds
the retention logic: in 0004 alone, pg_train_toast_dictionary() keeps
every dictionary it trains and a VACUUM FULL is the only way to shed
them, so a bound there would have nothing to enforce. 0004 and 0005 are
meant to go in together, and the name reads fine that way. If a
committer wants to take 0004 on its own, I'll move the GUC and the two
cap checks into it and rename it toast_dictionary_max_retained in the
same motion; it's a mechanical split and I'd rather do it when we know
0004 is landing alone than carry a cap that does nothing in the
single-patch case.
> 1. Unconditional tdtrainrows reset on non-concurrent REFRESH MATERIALIZED
> VIEW prevents matviews from ever evolving (matview.c, 0005)
[...]
> if (skipData || processed == 0)
> toast_dictionary_retire(matviewOid, true);
>
> resets the baseline whenever a refresh empties the matview while letting
> populated refreshes evolve normally across ANALYZE runs.
Fixed as you suggested. A populated REFRESH now keeps the recorded row
count so evolution can progress across refresh cycles; a refresh that
empties the matview (WITH NO DATA, or a query that returns no rows)
still resets the baseline the way TRUNCATE does. The regression test in
0005 now checks both arms: it trains a dictionary, does a populated
REFRESH and confirms the baseline is kept, then a REFRESH ... WITH NO
DATA and confirms it drops back to zero.
> 2. Three md5() calls left in 0004's SQL tests (FIPS-mode OpenSSL)
Switched all three to fipshash(), matching compression_zstd.sql.
> - verify_heapam.c:1680 (0002 & 0004): the new chunk-0 header check is
> gated by `chunksize >= (int32) sizeof(uint32)`, so if chunk 0 of a
> compressed external value is truncated below 4 bytes (0002), or has
> 5..8 bytes on a zstd_dict / lz4_dict value (truncating the 4-byte
> dictid, 0004), `verify_heapam(..., check_toast => true)` reports 0
> errors while detoasting fails with `compressed [dictionary] data is
> corrupt`.
Fixed. The check no longer skips a too-short chunk 0; it reports the
truncation. 0002 reports a chunk 0 shorter than the 4-byte va_tcinfo,
and, once the method is known, shorter than the header that method needs
(5 bytes for the long form's method byte). 0004 extends that to the
dictionary methods, whose header carries a 4-byte dictionary OID after
the method byte (VARHDRSZ_COMPRESSED_DICT). So a value whose chunk 0
stops inside the header is now a reported corruption rather than a clean
verify_heapam() followed by a detoast failure.
> - 007_verify_toast_pointer.pl:55 (0002): comment still says `one byte
> 0x01` three lines below `$va_1b_e`.
Fixed. The comment now points at $va_1b_e rather than naming the
little-endian byte.
> - pg_dump TAP tests (0004 & 0005): 0003 added `test_compression_zstd` to
> 006_pg_dump_compress.pl; adding `zstd_dict`/`lz4_dict` cases there and
> a `dictionary_evolution` attoptions check in 002_pg_dump.pl would round
> out the pg_dump test coverage (the C code itself dumps both fine).
Added to 006_pg_dump_compress.pl: a zstd_dict case and an lz4_dict case
alongside 0003's zstd case, each checking the dumped SET COMPRESSION
line, and a third case that sets dictionary_evolution and checks the
dumped attoption. I put the attoption check in 006 rather than
002_pg_dump.pl: 002 creates its tables unconditionally, so a zstd_dict
column there would break the suite on a build without zstd, whereas 006
already gates each case on compile_option. The lz4_dict case gates on
lz4 alone, since CREATE TABLE ... COMPRESSION lz4_dict needs only liblz4
(the zstd trainer is a train-time dependency, not a DDL-time one).
> - SGML nits (0004):
Both fixed. create_table.sgml and alter_table.sgml now list zstd_dict
and lz4_dict in the supported-methods sentence (pointing at the
paragraphs below), and the stray and missing blank lines in
system-views.sgml are gone.
v20 attached, rebased onto 0cb41ee8070. Changes since v19:
0002: verify_heapam() reports a chunk 0 truncated short of the
compressed header instead of passing it; fixed the stale $va_1b_e
comment in 007_verify_toast_pointer.pl.
0004: verify_heapam() extends that check to the dictionary methods'
4-byte dictid; three md5() calls in the SQL tests become
fipshash(); added zstd_dict and lz4_dict pg_dump cases;
create_table/alter_table list both dictionary methods; fixed the
system-views.sgml blank lines.
0005: a populated REFRESH MATERIALIZED VIEW keeps the evolution
baseline, only an empty refresh resets it, with the test covering
both; added the dictionary_evolution attoption pg_dump case.
0001-0003 are unchanged but for the two 0002 fixes above. With the
matview bug fixed I think 0004-0005 are ready too. I'd be happy to hear
whether a committer will pick the series up.
-greg
Re: ZSTD TOAST compression, and an extensible compression method encoding
Hi Greg, On Fri, Nov 20, 2026 at 4:13 PM Greg Burd wrote: > v20 attached, rebased onto 0cb41ee8070. Thanks! I ran another full pass over v20 on master under ASan + UBSan + cassert, pgindent, 006_pg_dump_compress, 007_verify_toast_pointer, and 002_pg_upgrade. All of the v19 items look cleanly resolved: - populated vs. empty REFRESH MATERIALIZED VIEW behaves properly across repeated refresh + ANALYZE evolution cycles; - the fipshash(), 006_pg_dump_compress.pl (gating on compile_option was definitely the right call for --without-zstd builds), verify_heapam truncated chunk-0 checks, and SGML updates all look good; - and your plan on dictionary_evolution_max_retained (keeping it in 0005 since 0004 and 0005 are meant to land together, and moving it into 0004 only if a committer ever takes 0004 standalone) makes complete sense to me. In this pass I also specifically tested partitioned tables and legacy inheritance end-to-end (multi-level declarative partitioning, ATTACH / DETACH [CONCURRENTLY] including dropped/reordered columns, cross-partition UPDATE / MERGE / INSERT ... SELECT, trigger transition tables, partitioned indexes, whole-tree REPACK / VACUUM FULL, pg_upgrade, and pgoutput logical replication with publish_via_partition_root = true and REPLICA IDENTITY FULL), checking on-disk headers via pageinspect. Dictionaries stay strictly attached to individual leaf partitions / tables throughout, with zero cross-partition dictionary references. At some future time it may make sense to re-visit the strict one relation == one dictionary mapping and see if we can do better for partitioned tables, where same dictionary could be used for many partitions. If nothing else, then maybe just copy the dictionary to the other table when UPDATE moves a row there and the dictionary for some fields in row does not exist. (One strictly non-blocking committer-level trivia note in verify_heapam.c, not worth a v21 on its own: at chunksize == 4 with method_bits == 3, method_byte stays -1 so toast_compression_id_resolve() already reports "has invalid compression method id 3 in its data" and returns before reaching the `else if (method_bits == VARLENA_COMPRESS_METHOD_LONG)` arm, while 5..8-byte truncated dictionary headers in 0004 hit the new header_size check as intended -- so every truncated length is caught.) I have no further findings; the whole v20 series (0001-0005) looks Ready to me. Cheers, Hannu
Re: ZSTD TOAST compression, and an extensible compression method encoding
On Sat, 21 Nov 2026 00:21:49 +0100, Hannu Krosing wrote: > In this pass I also specifically tested partitioned tables and legacy > inheritance end-to-end (multi-level declarative partitioning, ATTACH / > DETACH [CONCURRENTLY] including dropped/reordered columns, cross-partition > UPDATE / MERGE / INSERT ... SELECT, trigger transition tables, partitioned > indexes, whole-tree REPACK / VACUUM FULL, pg_upgrade, and pgoutput logical > replication with publish_via_partition_root = true and REPLICA IDENTITY > FULL), checking on-disk headers via pageinspect. Dictionaries stay > strictly attached to individual leaf partitions / tables throughout, with > zero cross-partition dictionary references. Hi Hannu, Thank you. The dropped and reordered columns across ATTACH and DETACH are a case I had not tried, so that is good to know. > At some future time it may make sense to re-visit the strict one > relation == one dictionary mapping and see if we can do better for > partitioned tables, where same dictionary could be used for many > partitions. > > If nothing else, then maybe just copy the dictionary to the other > table when UPDATE moves a row there and the dictionary for some fields > in row does not exist. Agreed, and I think it belongs in its own thread once this is in. Copying the dictionary along with a moved row keeps the lifecycle local: the copy belongs to the target partition and retires with it, so nothing in this series stands in its way. Sharing one dictionary across partitions is the bigger step, since it brings back the question of when a shared dictionary may be dropped. > (One strictly non-blocking committer-level trivia note in verify_heapam.c, > not worth a v21 on its own: at chunksize == 4 with method_bits == 3, > method_byte stays -1 so toast_compression_id_resolve() already reports > "has invalid compression method id 3 in its data" and returns before > reaching the `else if (method_bits == VARLENA_COMPRESS_METHOD_LONG)` arm, > while 5..8-byte truncated dictionary headers in 0004 hit the new > header_size check as intended -- so every truncated length is caught.) Right. I forged them on a cluster to be sure: chunk 0 cut to 3 and 4 bytes on a zstd value, and to 4, 5, 8 and 9 bytes on a zstd_dict one. 3 reports the short header, 4 the invalid ID 3, 5 and 8 the 9-byte header, and 9 passes. The flip side is that before 0004 the header_size test can never fire: by the time the method is known, chunk 0 already holds the 4- or 5-byte header. I kept it in 0002 so that 0004 only adds the dictionary case, but if a committer would rather 0002 not carry a check that 0004 makes live, it moves over without touching anything else. > I have no further findings; the whole v20 series (0001-0005) looks Ready > to me. Thanks for staying with this through so many versions. v20 still applies cleanly to master and cfbot is green on it, so I'm not posting a new version just yet. -greg
Re: ZSTD TOAST compression, and an extensible compression method encoding
Hi all,
v21 is attached, rebased onto 3ed10f282f9.
Where things stand: Hannu reviewed v20 and found nothing further, and
0001-0003 have had no new findings for several versions. Since then the
review has turned to whether a dictionary-compressed value can outlive
the dictionary it needs, and v21 is about that.
The rule the design rests on is that such a value never leaves the
column that owns its dictionary in compressed form. heap_fill_tuple()
sets HEAP_HASEXTERNAL on a tuple that holds one, so the paths that
already make a tuple self-contained for TOAST pointers (composite
datums, tuplestores, holdable cursors, PL/pgSQL records, the syscache,
index tuples) decompress it too. That costs nothing for anyone not
using dictionaries: under callgrind, heap_fill_tuple() runs the same
number of instructions for values that are not compressed in-line, and
about five more per compressed value, which is 0.03% of an INSERT ...
SELECT.
Three questions came up about where that rule could break, and v21
changes 0004 to answer them:
- A PL/pgSQL function could keep a value in a record variable after its
dictionary was gone. Within a transaction, a function fills a record
variable without flattening it, which is safe for TOAST pointers
because a table cannot lose its TOAST data before the transaction
ends. A dictionary can go sooner: rolling back the subtransaction
that trained it (an EXCEPTION block is enough) deletes its row, and so
does a rewrite of the table. v20 then failed with "compression
dictionary N does not exist", and since a later dictionary may get the
same OID, it could have decoded with the wrong one. The record path
now always decompresses dictionary values, and the regression test
covers the rollback, the rewrite and DROP TABLE.
- Other places could miss the rule. I went through every place in core
and contrib that tests a single value with VARATT_IS_EXTERNAL() and
found no other gap; the list is in notes.txt. So that new code cannot
miss it the same way, the test is now one predicate,
VARATT_IS_EXTERNAL_OR_DICT(), which every such place uses.
- An extension type that embeds other varlenas could copy one byte for
byte. Core cannot see a value once it is inside another type's bytes,
so this cannot be enforced, only documented: the user-defined types
chapter now says such a type must detoast what it embeds, as it
already must for TOAST pointers. hstore, ltree, intarray, jsonb,
pgvector and PostGIS all do.
Changes since v20:
0004: dictionary values in PL/pgSQL record variables are decompressed
when the record is filled (toast_flatten_tuple_dict()), with tests
for subtransaction rollback, rewrite and DROP TABLE
0004: VARATT_IS_EXTERNAL_OR_DICT() replaces the paired tests
0004: xtypes.sgml documents the rule for container types
0002: a comment in verify_heapam.c rewrapped for pgindent
0001, 0003 and 0005 are unchanged apart from the rebase. The audit, the
extension survey and the instruction counts are in the attached
notes.txt created with a bit of LLM help.
-greg