Review
Halve peak memory allocation for toast_flatten_tuple (v1)
- Proposal version
- 1
- CommitFest entry
- 7362
- Base commit
- 412848dac37f2e4455e1505f83f0af0f3d28a67d
Summary
The patch rewrites toast_flatten_tuple() so that the result tuple is laid out first (using 4-byte "stub" varlenas that carry only the header of each external value) and each external attribute is then detoasted one at a time straight into its final position, instead of detoasting all of them up front and calling heap_form_tuple(). Peak private memory drops from (tuple + all detoasted values) to (tuple + the largest single detoasted value); the saving is (N-1) values for a tuple with N external attributes and zero for N = 1. I found no correctness problem: a review-only instrumentation that recomputed every flattened tuple the old way and memcmp'd it found 530 of 530 results byte-identical across the regress, test_decoding and subscription suites plus targeted scenarios (compressed, uncompressed, short-packable externals, NULLs, dropped columns, catcache and PL/pgSQL callers). The main objection is that, to get attribute positions, the patch threads two extra parameters through the generic heap_fill_tuple()/fill_val() path used by every heap_form_tuple(), and perf stat shows +4.3% to +7.5% more instructions on tuple-forming microbenchmarks (cycles and wall-clock within noise here). That cost is avoidable by computing attribute offsets in a dedicated helper instead. The patch also triples the stack frame of toast_flatten_tuple() (16.7 KB to 51.7 KB), duplicates ~30 lines of heap_form_tuple(), and relies on an unchecked cross-module invariant about what detoast_external_attr() returns. Verdict: needs changes; the idea is sound and worth finishing.
What was reviewed
- Series: v1, 1 patch, from message CALT9ZEG8W0-xVCYQmxebYQ55fE-SJmKOTrBqgMbcVekhGNMaAw@mail.gmail.com (CommitFest entry 7362), author Pavel Borisov.
- Applied on: 412848dac37f2e4455e1505f83f0af0f3d28a67d ("Treat any
negative ws_file as closed in xlogreader.c", master), cleanly. The
cfbot branch is a merge of the bot base 061065e28f0 with the patch
commit 2ad1cf9cb0d;
git amof the original attachment onto 061065e28f0 produced a tree and message identical to 2ad1cf9cb0d. - Built: meson, debug, cassert, injection_points, tap_tests, lz4, zstd, liburing, libnuma, icu, -Wtype-limits -Werror=missing-braces: no new warnings. Also debugoptimized without cassert for master and for the patch (used for measurements): no warnings.
- Ran (debug build):
meson test --suite setup --suite regress --suite isolation --suite test_decoding --suite subscription: 47/47 OK, including the patch's new block in src/test/subscription/t/100_bugs.pl (23 subtests). - Ran (debug build with review-only instrumentation that re-derives each flattened tuple with the pre-patch algorithm and PANICs on any difference): regress, test_decoding, subscription: 46/46 OK, 519 flatten calls compared, 0 mismatches. Ad-hoc scenarios on the same build: 11 flatten calls, 0 mismatches (details under Correctness).
- Logical decoding output (test_decoding, REPLICA IDENTITY FULL, UPDATE/DELETE of rows with compressed, uncompressed-external, NULL and dropped columns, plus a 41-column table with 25 small external values): md5 of the change stream identical on master and on the patch (43 changes, 1,813,333 bytes).
- pgindent on the three C files: clean. perltidy (v20250105 here, not the project's pinned version) wants one line break moved in the TAP test; possibly a version artifact.
- Measurements: VmHWM of a fresh backend around UPDATE/DELETE
(memory), and
perf stat -e instructions:uon single-user-mode backends (CPU); see Performance.
Motivation and scope
toast_flatten_tuple() is called from ExtractReplicaIdentity() in src/backend/access/heap/heapam.c (REPLICA IDENTITY FULL old tuples for UPDATE/DELETE under wal_level=logical, and the fallback when a key-only tuple still has external columns), from catcache.c when a catalog tuple has external fields, and from expandedrecord.c when PL/pgSQL must make a record independent of TOAST (non-atomic contexts). The first caller is where big tuples show up: an UPDATE of a row with several large EXTERNAL columns transiently needs the old tuple's full size twice (all detoasted values plus the formed tuple).
The patch is master-only, no catalog or on-disk format change, and keeps the result bit-identical. Its benefit is bounded: with one external column nothing changes; with N columns of equal size S the peak private allocation goes from 2NS to (N+1)S. "Halve" is the limit for large N. For the common single-large-column case the patch is a no-op, which the commit message should say.
Design and alternatives
Mechanics (src/backend/access/heap/heaptoast.c, toast_flatten_tuple):
- For every on-disk external attribute,
palloc(VARHDRSZ)a stub and set its header to what toast_fetch_datum() will return:SET_VARSIZE_COMPRESSED(stub, extsize + VARHDRSZ)if the pointer says compressed, elseSET_VARSIZE(stub, extsize + VARHDRSZ). INDIRECT pointers are detoasted inline as before; EXPANDED pointers get a stub of EOH_get_flat_size(). - Replicate heap_form_tuple()'s header computation and call the new
heap_fill_tuple_attr() with
skip_copy[](do not copy the stubs) andattr_data[](return each attribute's aligned position). - Free the stubs, then for each external attribute detoast_external_attr() and memcpy into the recorded position, applying the same short-header packing fill_val() would apply.
heap_compute_data_size() and fill_val() only look at the varlena header (VARATT_IS_EXTERNAL / VARATT_IS_SHORT / VARATT_CAN_MAKE_SHORT / VARSIZE_ANY / att_datum_alignby), so a header-only stub is enough to get an identical layout. I checked each macro; none touches payload bytes. Because toast_fetch_datum() builds its result header with the same two macros from the same extinfo, the stub and the fetched value always agree in size and in the 4B_C/4B_U flag, hence in packability and alignment. That is the whole correctness argument, and it holds, but it is an invariant between detoast.c and heaptoast.c that nothing checks (see Correctness, finding 2).
Alternatives worth considering:
- Keep the generic path untouched. The only new information needed
is the data offset of each attribute. That can be produced by a
small
heap_compute_data_size()-style helper that records offsets (the same alignment/packing arithmetic, ~20 lines), after which heap_form_tuple()/heap_fill_tuple() need no change at all and the stubs are only needed for heap_compute_data_size(), or not at all if the helper also returns the total. I also tried making the per-attribute helperpg_always_inlineso that heap_fill_tuple() keeps a specialized loop in which the constantfalse, NULLarguments fold away; it restores master's instruction count but measured slower in cycles on one workload (see Performance), so the offsets helper is the safer route. - Fetch directly into the destination. table_relation_fetch_toast_
slice() writes into a caller-supplied varlena, so a
toast_fetch_datum_into(attr, dest)variant would make the peak exactly one tuple and save one memcpy per external value. The layout machinery of this patch would still be needed, so this is a natural follow-up rather than a competing design; the short-packed case (values of at most 126 bytes) would need the temporary buffer. - Factor heap_form_tuple() instead of copying it. heap_form_tuple()
could become a wrapper around an internal routine taking the
skip_copy/attr_dataarrays, which removes the ~30 duplicated lines (hasnull scan, hoff, palloc0, header setup) from heaptoast.c.
Correctness
I found no wrong result, crash or memory-lifetime bug. What I tried:
the full suites with the differential instrumentation described above
(519 flattens, mostly catcache pg_proc tuples with 1 external column,
some with 2 or 3, one 300,040-byte 4-column tuple with 3 externals);
and an ad-hoc script on the same build covering: a REPLICA IDENTITY
FULL table mixing a compressed external text, an uncompressed EXTERNAL
bytea, NULLs, float8/int8/uuid, a short inline text, and a column
dropped after the row was written while still holding an external
value; a 41-column table with 40 EXTERNAL text columns of 100 bytes
(25 end up out of line, come back as 104-byte 4B values and are
short-packed, so the new SET_VARSIZE_SHORT(dest, ...) branch runs);
PL/pgSQL SELECT ... INTO of a toasted row in a DO block with COMMIT
(expand_external path); a function with a 300,000-byte prosrc
(catcache path). All results were byte-identical to the old
algorithm. Tuples with no external attribute never reach the function
(all callers test HeapTupleHasExternal first) and in that case the new
code degenerates to heap_form_tuple(), so there is no lost fast path.
The EXPANDED branch cannot be reached from a HeapTuple (heap_form_tuple
flattens expanded datums), but it is harmless.
Findings, most severe first:
-
Performance regression on the generic tuple-forming path (src/backend/access/common/heaptuple.c, heap_fill_tuple / heap_fill_tuple_attr / fill_val_attr). Not a wrong-result bug, but the most important finding; numbers under Performance. In the optimized build master's heap_fill_tuple() called an out-of-line fill_val(); with the patch it is a 26-byte thunk calling heap_fill_tuple_attr(), whose loop evaluates
skip_copy ? skip_copy[i] : falseandattr_data ? &attr_data[i] : NULLper attribute and calls a 9-argument out-of-line fill_val_attr() (three arguments go via the stack) that testsattr_data_outtwice andskip_copyonce per attribute. This is every heap_form_tuple()/heap_form_minimal_tuple call in the server. -
Unchecked size invariant (heaptoast.c, detoast loop at the
memcpy(dest, detoasted, VARSIZE(detoasted))and the short-pack branch). The destination slot was sized from the stub; the copy is sized from the fetched value. They agree today because both come from VARATT_EXTINFO_GET_EXTSIZE() plus the same compressed flag, but if toast_fetch_datum() ever returned something else (for example a future toaster that decompresses or pads), the result is a silent write past the palloc'd tuple rather than an error. Please keep the stub sizes (or recompute them) and addAssert(VARSIZE_ANY(detoasted) == expected)or an elog(ERROR), and add a comment at toast_fetch_datum() in src/backend/access/common/detoast.c saying toast_flatten_tuple() depends on the exact header it produces. The cost is one compare per external attribute. -
Stack usage (heaptoast.c, toast_flatten_tuple locals). Four new MaxTupleAttributeNumber-sized arrays (
toast_attr_data13,312 B,toast_origvals13,312 B,toasted_atts6,656 B,toast_skip1,664 B) raise the frame from 16,696 to 51,704 bytes (read from the stack-clash prologue of the optimized build:lea -0x4000(%rsp)- 0x138 before,
lea -0xc000(%rsp)+ 0x9f8 after). The function is reached from catcache misses at arbitrary call depth. The two per-external arrays can be collapsed into one small array of {attnum, Datum} or palloc'd after counting;toast_attr_dataonly needs entries for external attributes if heap_fill_tuple_attr() reports positions by index into a compact list instead.
- 0x138 before,
-
Minor:
int len(heaptoast.c) where heap_form_tuple() usesSize;len += data_lensilently narrows. A flattened tuple is bounded by MaxAllocSize so it cannot overflow today, but the types should match heap_form_tuple(). -
Pre-existing, unchanged: a column dropped after a row was written keeps its external value, and both old and new code fetch and inline it into the REPLICA IDENTITY FULL old tuple written to WAL. Not this patch's problem, but the author is now the person most familiar with the loop and could skip
attisdroppedattributes (setting them NULL) in a follow-up.
Error paths: if a toast fetch fails mid-loop the partially built tuple leaks in CurrentMemoryContext until the context is reset; the old code leaked the already-detoasted values in the same way. The catcache caller's PG_TRY only restores the in-progress stack, as before.
Performance
Memory. Fresh backend, REPLICA IDENTITY FULL table with N text columns in STORAGE EXTERNAL totalling 64 MB, wal_level=logical, MALLOC_MMAP_THRESHOLD_=1MB so freed blocks leave RSS; VmHWM read from /proc/self/status before and after the statement; optimized builds, two runs each (they agree within 1 MB). Deltas in MB:
| columns | UPD master | UPD patch | DEL master | DEL patch |
|---|---|---|---|---|
| 1 x 64 MB | 199.7 | 199.7 | 195.8 | 195.6 |
| 2 x 32 MB | 199.1 | 167.7 | 195.9 | 163.9 |
| 4 x 16 MB | 200.0 | 151.3 | 195.8 | 148.1 |
| 8 x 8 MB | 200.0 | 144.3 | 195.9 | 140.0 |
About 70 MB of each delta is unrelated to flattening (shared-buffer pages touched while reading the toast chunks, WAL insertion of the 64 MB old tuple); the master-minus-patch difference is 0, 31.4, 48.7 and 55.7 MB, i.e. (N-1) x S as predicted. The claim "halve" holds only asymptotically; for one toasted column there is no change.
CPU. perf stat -e instructions:u,cycles:u,task-clock around a
single-user backend (postgres --single -j) running each script.
Instruction counts repeat to 5 significant digits; cycles and
task-clock vary by a few percent on this shared machine. Three
builds: master, the patch, and the patch plus my experiment
"fill_val_attr always-inline, heap_fill_tuple() keeps its own loop"
(which compiles heap_fill_tuple() back to master's 0xfa bytes calling
an out-of-line fill_val, for +2 KB of text in heaptuple.o).
Workloads: w2_row = SELECT count(r) FROM (SELECT row(i, i::int8, 'abc'||i, i*2, i::float8, i::numeric, i, i) ...) over 3M rows
(heap_form_tuple per row); w3_ctas = CREATE TABLE AS of 3M 8-column
rows; w1c = 15,000 UPDATEs of RI FULL rows with eight 3 KB EXTERNAL
columns (all external); w1 = 1,000 flattens of rows with four 100 KB
EXTERNAL columns; w1b = 1,000 flattens of one 400 KB column.
Instructions (user space), rep 2 of 3 interleaved runs, master absolute and the others relative to it:
| workload | master | patch | always-inline |
|---|---|---|---|
| w2_row | 10,224,285,618 | +7.51% | -0.47% |
| w3_ctas | 16,925,364,626 | +4.32% | -0.30% |
| w1c | 2,790,698,734 | +0.77% | +0.45% |
| w1 | 605,370,513 | +0.12% | +0.07% |
| w1b | 553,350,421 | +0.04% | +0.01% |
Cycles (user space, 10^9) and task-clock (ms), min..max over five interleaved repetitions run in the order inline, patch, master:
| workload | master | patch | always-inline |
|---|---|---|---|
| w2_row | 2.10..2.13 | 2.08..2.13 | 2.08..2.11 |
| w3_ctas | 4.24..4.41 | 4.21..4.49 | 4.55..4.63 |
| workload | master | patch | always-inline |
|---|---|---|---|
| w2_row | 398..409 | 397..406 | 396..404 |
| w3_ctas | 858..891 | 859..908 | 918..932 |
Reading: the flatten path itself is unchanged within noise (the stubs, extinfo decode and extra loop are lost in toast-fetch cost; w1c, with eight small externals per row, is the worst case at +0.8%). The generic path pays 240-260 extra instructions per 8-attribute heap_fill_tuple(), about 30 per attribute, which is 4-8% of these tuple-forming microbenchmarks and about 1% of a plain UPDATE. In cycles and time the patch did not regress measurably here; the extra instructions are cheap, predictable branches. My always-inline experiment removes them but measured consistently about 5% more cycles and time on w3_ctas (not on w2_row), which I cannot explain other than by code layout, so I do not recommend it as-is. Both results argue for the same thing: leave the hot code in heaptuple.c alone and compute the attribute offsets in a dedicated helper, and benchmark any heaptuple.c change with cycles, not instruction counts alone.
Compatibility
No catalog, WAL, protocol or on-disk change; catversion untouched. Flattened tuples are byte-identical to before (verified as above), so logical decoding consumers, catcache entries and PL/pgSQL records see no difference. One new exported function, heap_fill_tuple_attr(), and a changed static helper; heap_fill_tuple() keeps its signature. This is a master-only improvement and is not back-patch material. No documentation is affected.
Code, tests, docs, style
- heaptoast.c, toast_flatten_tuple: the ~30 lines from "Compute
tuple header and data lengths" to
td->t_hoff = hoff;are heap_form_tuple() verbatim minus its natts ereport. Factor heap_form_tuple() into an internal routine that accepts the two optional arrays and call that; otherwise the two copies will drift (HeapTupleHeaderSet* changes, the Datum-length/typeid comments). - heaptoast.c: one
palloc(VARHDRSZ)plus pfree per external attribute. A localvarattrib_4barray sized by the count of externals, or one palloc, would avoid N tiny allocations; the separate "Free stubs" loop then disappears. - heaptoast.c:
memset(toast_skip, false, ...)andmemset(toast_free, false, ...); the existing code used0. - heaptoast.c, header comment of toast_flatten_tuple: fine, but src/include/access/heaptoast.h repeats the old comment; keep them in sync or drop one.
- heaptuple.c: the comment on fill_val_attr says "Per-attribute
helper for heap_fill_tuple_attr" while fill_val's says "and other
routines building tuples" (expand_tuple still calls fill_val);
pick one wording. Several added lines exceed 80 columns (for
example the
if (toast_isnull[i] || TupleDescCompactAttr(...) ->attlen != -1)test); pgindent accepts them but they are easy to wrap. - Naming:
heap_fill_tuple_attrsays nothing about what differs;heap_fill_tuple_extorheap_fill_tuple_layoutwould be clearer. - Tests: the new block lives in src/test/subscription/t/100_bugs.pl,
whose header says "Tests for various bugs found over time"; this is
not a bug fix, and the scenario (RI FULL, compressed and
uncompressed EXTERNAL columns, UPDATE old tuple) is already covered
more cheaply by contrib/test_decoding/sql/toast.sql
(
toasted_several, three EXTERNAL columns, REPLICA IDENTITY FULL). If a new test is wanted, put it there, and cover what no existing test does: external values small enough to be short-packed on the way back (a table with many ~100-byte EXTERNAL columns, as in my ad-hoc scenario), since that is the one branch the new code implements by hand. The TAP test compares onlylength(b), length(c); comparing md5 of the content would make its intent explicit (RI FULL row matching on the subscriber does check equality implicitly, which is why the test is not vacuous). - Commit message: "compared the toast-fetch I/O" is missing "to"; the memory claim should be stated as "all but one detoasted value" rather than "halve"; and the list of callers omits the key-tuple fallback in ExtractReplicaIdentity(). No "Discussion:" link yet.
- Docs: n/a, no user-visible behaviour.
Discussion and consensus
The thread consists of the single submission (2026-09-21, Pavel Borisov); as of 2026-10-09 there is no reply, no reviewer, and no objection or agreement on record. Nobody has yet discussed whether touching heap_fill_tuple() is acceptable, which is the question a committer will ask first. The CF entry is "Needs review", which is correct.
Verdict
Needs changes (not ready for committer). The approach is sound and I could not make it produce a different tuple than the old code, but three things should change before it is committable:
- Do not add per-attribute work to the generic heap_fill_tuple() path (finding 1). Preferably compute the attribute offsets with a dedicated helper and leave heaptuple.c's fill path alone; if heaptuple.c is changed anyway, show with cycle counts on a tuple-forming workload that heap_form_tuple() did not get slower (my always-inline attempt fixed the instruction count but not the cycles on CREATE TABLE AS).
- Cross-check the fetched size against the reserved slot before the memcpy, and document the dependency in toast_fetch_datum() (finding 2).
- Reduce the 35 KB of new stack usage (finding 3) and factor the duplicated heap_form_tuple() body.
Also: move or drop the TAP test in favour of a test_decoding SQL test
that covers the short-packed external case, and state the memory
benefit precisely in the commit message. A committer should
double-check the instruction-count numbers on their own hardware and
decide whether the toast_fetch_datum_into follow-up (peak exactly
one tuple, one memcpy fewer) should be done now instead, since it
would reuse the same layout machinery.
The assessment score is driven by finding 1 (a measurable, avoidable cost on a hot generic path that the thread has not noticed) together with findings 2 and 3; the consensus score reflects a single-message thread with no review activity.