notes.txt: v22 of the zstd / TOAST dictionary series ==================================================== v22 applies on master as of 4483697be0e. 0001-0003 have the same patch-ids as v21. 0004 and 0005 change how lz4_dict compresses (section 1, and 0004's commit message, which describes it), and 0004 adds tests (section 5). All timings below are from one c6id.metal (Xeon 8375C, 2 sockets, 128 vCPU, local NVMe) with turbo off, the performance governor, THP off, the server pinned to 16 cores of node 0, and the client to four others. Builds are release (-O2 -g, no cassert), base = master 4483697be0e, tip = base + v22. Each number is one statement timed with clock_timestamp() in the server, on a freshly loaded table after a CHECKPOINT; base and tip alternate ABBA over 5 rounds, and a second base cluster gives the A/A noise floor. Every run also records how its values were stored (method and in-line or out of line), so a case that compressed nothing would show up. Instruction counts come from callgrind over ExecutorRun of the same statement. 1. lz4_dict: attach the dictionary instead of loading it per value ----------------------------------------------------------------- v21 compressed each lz4_dict value by calling LZ4_loadDict() and then LZ4_compress_fast_continue(). LZ4_loadDict() hashes the whole dictionary into the stream's table every time, about 18us for a 64kB dictionary regardless of the value's size. From lz4 1.10 (where it is stable API), LZ4_attach_dictionary() lets a working stream reference a stream that LZ4_loadDict() prepared once; v22 caches that prepared stream next to the dictionary bytes in the per-backend cache, drops both together on invalidation or eviction, and attaches it for each value. With lz4 older than 1.10 the code keeps the v21 path. Standalone (lz4 1.10, 64kB dictionary, same input): value size loadDict per value attach per value 1 kB 17.7 us 0.24 us 4 kB 18.7 us 0.51 us 16 kB 20.0 us 1.72 us The compressed output is byte-identical. In the server, loading 200,000 documents of 2.6kB on average (section 4) into an lz4_dict column took 4.86 s with v21 and 1.36 s with v22 (lz4 without a dictionary: 1.22 s); documents of 9.5kB took 6.74 s and 3.20 s (lz4: 2.48 s). zstd_dict and lz4 are unchanged, and the stored size is the same to the byte. Checked: regress and the TAP suites with lz4 1.10 (attach path), and regress with a build against lz4 1.9.4 (load path); the compression suites under valgrind memcheck with no error; and a 30-minute run in which 8 clients inserted, updated, and checked the sha256 of lz4_dict values (23.7 million transactions) while another session retrained the column's dictionary every few seconds (180 times), ran VACUUM FULL every 12th round, and switched the column to zstd_dict and back every 30th. None of the 9.5 million rows left failed its sha256 check, verify_heapam() with check_toast reported nothing, and no client got an error. 2. Cost for tables without dictionaries --------------------------------------- tip/base, median of the per-round ratios, with the range over the 5 rounds and the A/A (second base cluster / base) next to it: case (rows) tip/base range A/A pglz 3.4kB in-line, INSERT (200k) 1.000 0.994-1.002 0.996 pglz in-line, INSERT ... SELECT 0.988 0.970-1.026 1.002 pglz in-line, UPDATE non-key 0.986 0.978-0.999 1.001 pglz in-line, DELETE 0.991 0.973-1.005 1.000 lz4 3.4kB in-line, INSERT 1.002 0.998-1.010 1.000 lz4 in-line, INSERT ... SELECT 0.982 0.966-1.022 0.991 lz4 in-line, UPDATE non-key 0.980 0.966-0.999 1.001 lz4 in-line, DELETE 0.996 0.976-1.010 0.994 pglz 12kB out of line, INSERT (40k) 1.000 0.999-1.000 1.000 pglz out of line, INSERT ... SELECT 1.002 0.986-1.012 1.002 pglz out of line, UPDATE non-key 0.989 0.987-0.997 1.004 pglz out of line, DELETE 0.987 0.983-0.998 1.002 lz4 12kB out of line, INSERT 1.002 0.995-1.002 1.000 lz4 out of line, INSERT ... SELECT 1.004 0.983-1.015 0.997 lz4 out of line, UPDATE non-key 0.986 0.932-0.990 0.996 lz4 out of line, DELETE 0.974 0.929-1.025 0.999 narrow rows (2M), INSERT 0.967 0.951-0.998 0.983 narrow rows, INSERT ... SELECT 0.985 0.957-0.994 1.017 narrow rows, UPDATE 0.936 0.931-0.943 1.000 narrow rows, DELETE 1.002 0.992-1.017 1.014 No case takes more than 1.004 times master's time, while the A/A comparison itself moves by up to 1.7%. The two narrow-row cases where tip is fastest (0.936 and 0.967) differ from master by under 0.002% in instructions, so I take them to be code layout. callgrind, ExecutorRun only: statement base Ir tip Ir INSERT 200k narrow rows 803,326,501 803,314,907 UPDATE 200k narrow rows 2,454,605,220 2,454,599,828 INSERT 20k 3.4kB docs, pglz in-line 5,000,728,451 4,998,450,582 INSERT 20k 3.4kB docs, lz4 in-line 1,100,712,883 1,098,543,501 The in-line cases come out about 110 instructions per row (0.05% and 0.2%) lower on tip, a third of it in dynahash lookups; I have not chased the rest. The five instructions per compressed value that fill_val() now spends, measured with v21, do not show at this level. An earlier run of the same benchmark on this host, with a generator whose "small" documents fell under the TOAST threshold, showed pglz small INSERT 7% slower on tip. It did not reproduce on freshly initialized clusters (0.997 and 1.000 with default and with -falign-functions=64 builds) or on the same cluster after a restart, and callgrind shows no extra work, so I am treating it as an artifact of that cluster. 3. Cost and benefit for tables with dictionaries ------------------------------------------------ Tip only, dictionary method / same method without a dictionary. The dictionary was trained on the first 5000 rows (64kB): case zstd_dict/zstd lz4_dict/lz4 3.4kB in-line, INSERT 0.678 1.016 in-line, UPDATE non-key 0.859 0.847 in-line, DELETE 0.905 0.915 12kB out of line, INSERT 1.235 1.442 out of line, UPDATE non-key 0.994 0.995 out of line, DELETE 0.991 0.953 The faster in-line UPDATE and DELETE are smaller tuples: a 3366-byte document is stored in 171 bytes with zstd_dict against 344 with zstd, and in 352 with lz4_dict against 564 with lz4, so the heap is 46% and 36% smaller. The out-of-line documents in this set carry a 32-digit hash per line, which no dictionary can predict, so the dictionary saves little (3004 bytes against 3064 for zstd) and costs compression time: callgrind puts 86% of the statement in ZSTD_compress_usingCDict() against 84% in ZSTD_compressCCtx() for plain zstd, so the extra time is the codec searching the dictionary as well as the value, not the series' bookkeeping. Section 4 shows larger documents with one hash each instead of one per line, where the dictionary still saves 20%. INSERT ... SELECT from a dictionary column into a column that has no dictionary of its own (a different table) decompresses and recompresses every value, by design, so the copy cannot carry a value out of the column that owns its dictionary. For the 200k 3.4kB documents: 2.50 s for zstd_dict against 0.27 s for zstd, whose values are copied as they are (9.2x), and 1.00 s for lz4_dict against 0.38 s for lz4 (2.6x). For the 40k 12kB documents: 4.6x and 2.0x. An INSERT ... SELECT within the table, an UPDATE that leaves the column alone, and a rewrite (VACUUM FULL, CLUSTER) keep values compressed when the dictionary is still the column's current one. 4. Compression ratio on DocumentDB-shaped JSON ---------------------------------------------- 200,000 documents per size, five methods, five runs each, on the v21 build; stored heap+TOAST size as a ratio of the raw text, and seconds to load, read every value in full, and do 50,000 point lookups (see section 1 for v22's lz4_dict load times). The two sets average 2.6kB and 9.5kB of raw JSON per document, and both compress to in-line values with every method: size method ratio size load full read lookups 2.6kB pglz 3.58 145MB 4.03 1.68 0.67 lz4 3.47 149MB 1.22 1.52 0.62 zstd 4.74 109MB 2.76 2.15 0.80 zstd_dict 9.20 56MB 1.62 1.73 0.69 lz4_dict 5.76 90MB 4.82 * 1.55 0.63 9.5kB pglz 6.99 273MB 13.74 5.60 1.66 lz4 5.83 328MB 2.46 5.44 1.62 zstd 11.43 167MB 4.46 6.29 1.85 zstd_dict 14.31 133MB 3.74 5.94 1.75 lz4_dict 7.38 259MB 6.57 * 5.54 1.65 * 1.36 s and 3.20 s with v22. At 2.6kB, zstd_dict halves zstd's size and reads faster than zstd; at 9.5kB the dictionary still saves 20%. lz4_dict keeps lz4's read speed and saves 40% at 2.6kB. The smallest documents in the same run (0.8kB) were below the TOAST threshold, so no method compressed them; that row is left out. 5. What else ran ---------------- - Each patch alone: -Werror build, no warnings, make check. pgindent, git diff --check, and ASCII clean. - test-world on v22: 380 passed, 54 skipped, 0 failed. - Valgrind memcheck (USE_VALGRIND, cassert) over test_setup and the seven compression suites, on v21 and again on v22: no errors. - Big-endian: s390x under qemu-user, Fedora 45 libzstd and liblz4, v22: build with no warnings, make check 247 of 247 including the three dictionary suites, amcheck t/007 34 of 34. - Dictionary OID reuse: a TAP test (test_misc/017) has an atomic PL/pgSQL function train a dictionary in a subtransaction, hold a value compressed with it in a record variable, roll back, and then install a different dictionary at the same OID through binary_upgrade_add_toast_dictionary() before reading the record. It reads back exactly; with the record-variable flattening removed it fails with "compressed zstd data is corrupt". - PL/Tcl and PL/Python: regression cases that keep a dictionary value in a variable across a rolled-back subtransaction that trained the dictionary. Both PLs copy values into their own types, so these pass with or without the flattening; they guard the PL side. PL/Perl has no subtransaction API; its case drops the table instead, checked by hand. - A 5.4-hour soak of a release build of master plus the series, on an r7i.8xlarge (the v21 code, which v22 changes only in the lz4_dict compression path that section 1 checks): pgbench churn with sha256 checks, a maintenance lane (REPACK in both forms, VACUUM FULL, CLUSTER, retraining, SET COMPRESSION flips, TRUNCATE, CTAS, and dump and restore), a streaming standby verified every 10 minutes (32 of 32 matched all 200,000 rows), logical decoding checked row by row (32 of 32 clean), the regression suites in a loop (634 runs), and an immediate stop every 2 hours. Both crash cycles recovered with all 200,000 rows matching; the only failed iterations were the ones the crash interrupted; no TRAP or PANIC; verify_heapam() with check_toast clean every 2 minutes on the wide, nested, docs, and hist tables (after the first 15 minutes, when the harness had not yet installed amcheck), and on four random dictionary tables every 30 minutes; and five CLUSTER runs failed, all from the upstream issue below. - A 65-hour soak of v21 on REL_19_STABLE, plus the master TOAST commits it needs, with the same lanes and also HammerDB TPROC-C and TPROC-H, DocumentDB's own tests with every collection dictionary-compressed, and an amcheck loop, found no failure attributable to the series. CLUSTER (and, in the PG 19 soak, amcheck) reported "missing chunk number 0 for toast value N" on a table under heavy UPDATE. The same error reproduces on master with pglz and no patch applied (a long transaction in another database, UPDATE of every row, VACUUM of the TOAST table), so it is the RECENTLY_DEAD case of BUG #18351 and not part of this series. 6. Where a dictionary value could leave its column -------------------------------------------------- The same audit as with v21; v22 changes none of these places, and none of the 31 master commits since v21's base touches them. Every test of a single value with VARATT_IS_EXTERNAL() or VARATT_IS_EXTERNAL_NON_EXPANDED() in src/backend, src/pl, and contrib, plus datumTransfer(), was read and classified: a) Decides whether to make a value self-contained; now uses VARATT_IS_EXTERNAL_OR_DICT(): brin_tuple.c (brin_form_tuple), indextuple.c (index_form_tuple), tstoreReceiver.c, heaptoast.c (toast_build_flattened_tuple), expandedrecord.c (6 places). b) Tests one kind on purpose and handles dictionary values beside it: heaptoast.c (toast_flatten_tuple_internal, by mode), pl_exec.c (assign_simple_var, non-atomic path), datum.c (datumTransfer). c) Already decompresses any compressed value, which covers a dictionary value: heaptoast.c (toast_flatten_tuple_to_datum), fmgr.c (pg_detoast_datum_packed), varlena.c (text_substring), toast_helper.c:252, amcheck verify_nbtree.c. d) Not a decision about keeping a value: detoast.c internals, Asserts (toast_internals.c, reorderbuffer.c, ts_selfuncs.c), heaptuple.c fill_val (expanded and indirect flattening; the dictionary flag is set later in the same function), heapam.c HeapDetermineColumnsInfo, toast_helper.c toast_tuple_init (old pointer reuse; dictionary values go through toast_dictionary_keep() there), rangetypes.c datum_write (an error guard; range_serialize() detoasts first), amcheck verify_heapam.c and pageinspect (raw page reads), pgrepack.c repack_store_change. pgrepack.c spills only out-of-line attributes and writes the tuple as is to a file read back by the same REPACK (CONCURRENTLY). The old dictionaries are retired only in finish_heap_swap(), after the replay, so the spilled values stay readable. Checked: REPACK (CONCURRENTLY) of a table with two dictionaries while 40 rounds of UPDATE and INSERT ran left one dictionary, and all 2040 values read back correctly. The audit covers in-core code only; extensions are section 7. 7. Extension container types ---------------------------- A type whose values embed other varlenas, and which copies a value it is handed byte for byte, would carry a dictionary value out of its column. Core cannot see the value once it is inside the type's own bytes, so there is no place for a check. xtypes.sgml (TOAST Considerations) now says such a type must detoast what it embeds, and that PG_DETOAST_DATUM(), PG_DETOAST_DATUM_PACKED(), and conversion through the output function decompress a dictionary value while a byte copy does not. toast_compression.h says the same next to VARATT_IS_COMPRESSED_DICT(). Survey, by reading the source: hstore PG_GETARG_TEXT_PP; hstore_from_record goes through the output function ltree, intarray, jsonb build from detoasted input pgvector DatumGetVector() is PG_DETOAST_DATUM() PostGIS PG_GETARG_GSERIALIZED_P() is PG_DETOAST_DATUM(); the header-slice path detoasts compressed values too None copies a varlena it was handed without detoasting it.