Skip to content

Validate a verbatim codec's declared size in the passthrough read shortcut - #114344

Merged
rienath merged 16 commits into
ClickHouse:masterfrom
groeneai:bound-decompressed-frame-size
Sep 23, 2026
Merged

rienath merged 16 commits into
ClickHouse:masterfrom
groeneai:bound-decompressed-frame-size

Conversation

@groeneai

@groeneai groeneai commented Aug 11, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Reject a compressed block whose codec stores data verbatim (NONE, Quantized) when its declared uncompressed size does not match the body length. Previously the passthrough read path accepted such a block while every other decompression path rejected it

Description

For a method byte whose codec stores the body verbatim, the declared uncompressed size and the body length describe the same bytes and must be equal. CompressionCodecNone::doDecompressData and CompressionCodecQuantized::doDecompressData both enforce that, and every read path reaches one of them through codec->decompress, with one exception: the isNone() shortcut in CompressedReadBufferBase::decompress re-points the output buffer at the body and never calls the codec. There the declared size was simply ignored, so a block that every other reader refuses was read as valid. The check now sits in that shortcut, which is the only place it was missing.

Reachable at default settings on any transport that accepts a compressed block: the checksum is an unkeyed CityHash128 over bytes the sender chose, so a sender recomputes it for a header it crafted.

Not changed here: a reader still sizes its buffer from the declared value before the shortcut runs, so a small block can still make it reserve up to the 1 GiB a header may declare, bounded by DBMS_MAX_DECOMPRESSED_SIZE and, inside Multiple, by that codec's own 1 GiB guard. That ordering is the same as on master.

03003_codec_multiple_buffer_overflow carries a nested block of this shape and keeps its existing expectation, since the nested codec is what refuses it.

Related: #117011


Workflow [PR]
Sync PR [sync-upstream/pr/114344]

Version info

  • Merged into: 26.10.1.499-master (included in 26.10 and later)
  • Backported to: 26.9.2.32, 26.8.11.40, 26.7.14.39, 26.3.33.156

groeneai and others added 5 commits August 10, 2026 20:42
The compressed frame header carries two independent 32-bit size fields.
size_compressed is bounded at DBMS_MAX_COMPRESSED_SIZE in both header
parsers; size_decompressed is bounded nowhere, although it is the field
that directly sizes output buffers. ICompressionCodec::readDecompressedBlockSize
validates only that it is non-zero, and CompressedReadBuffer::nextImpl and
readBig call memory.resize with it, so a header can ask for a reservation of
up to 4 GiB for a frame that will fail to decode.

validateChecksum does not gate this. It is an unkeyed CityHash128 over the
frame body, compared against 16 bytes the same peer supplied, so a peer that
crafts a header also computes its checksum. The path is therefore reachable
at default settings over HTTP decompress=1. The impact stays low: the
reservation is virtual, decompression fails immediately afterwards, and
max_server_memory_usage caps it when configured.

Bounding the reader alone would reject frames that current ClickHouse writes,
because max_compress_block_size and clickhouse compressor --block-size are
unclamped and Log, StripeLog and the backup temp path pass them straight to a
compressed write buffer. So the writers are capped first: a frame's
size_decompressed is offset(), which cannot exceed buffer capacity, and
capacity comes from exactly two places in CompressedWriteBuffer (the initial
allocation and adaptive_buffer_max_size) plus one in
ParallelCompressedWriteBuffer. Capping all three is codec-independent, which
is why no codec reserve computation is involved.

With that invariant in place the reader bound is unconditional and on by
default. Data written before the cap existed can still hold a larger frame,
so the readers of such data opt out explicitly. Each site was traced to the
writer that produces its bytes and opted out only where that writer's buf_size
is unclamped; readers whose writers are a fixed size stay bounded, including
checksums.txt at 64 KiB and statistics at 1 MiB. The opt-out in
checkDataPart is per file rather than per site, because its lambda serves
every compressed checksum entry including statistics.

The direction of failure is what makes a short list the safe choice here.
After the writer cap, a site missing from the list throws
TOO_LARGE_SIZE_COMPRESSED on a legacy read, which is loud and one line to
fix, while an over-broad entry silently leaves a path unbounded. The list is
therefore deliberately minimal.

A codec that stores its body verbatim also gains a header-time consistency
check: the body length is the decompressed length, and the caller sizes its
output buffer from size_decompressed before decompressing, so the two must
agree. isNone() is overridden only by CompressionCodecNone and
CompressionCodecQuantized, both of which already enforce that equality inside
doDecompressData, so no legitimate writer is rejected.

The boundary is inclusive, matching the sibling bound: exactly 0x40000000 is
accepted and only a strictly larger value is rejected.

The Native format spec documents both bounds, the inclusive boundary, and the
legacy-data edge, since it previously stated neither limit.

Co-Authored-By: Claude Fable 5 <[email protected]>
… reads

Two defects in the previous commit, both found in review.

Capacity at the bound is not enough. The two header fields come from
different quantities: compress() serializes 9 + doCompressData(), and a codec
may expand rather than shrink. NONE returns source_size unchanged, so a
full-capacity frame serialized size_compressed = 1073741833, which the bounded
reader then rejected; LZ4 on incompressible input is the same class. Both are
reachable through clickhouse compressor and through Log with CODEC(NONE).
The change advertised that a current writer never emits a frame a current
reader rejects, so this had to hold rather than be documented away.

capUncompressedFrameSize measures the codec's overhead at the bound and
subtracts it, in closed form, with one getCompressedReserveSize call and no
search, rounded down to a 32-byte multiple so a codec that rejects a partial
element is never handed one. A codec can also answer nothing usable: a chain
deep enough to overflow its own UInt32 reserve arithmetic returns a value
below the frame it describes, and some codecs refuse the size outright.
Neither answer is a bound, so neither is reduced by, and the request passes
through unchanged. Treating those as infeasible instead was measurably wrong:
a 40-deep FPC chain wraps its Multiple reserve to 9082261, and clamping on
that produced 262144 frames where master produces 1. With the pass-through the
same input is byte-identical to master, as are all ordinary buffer sizes.

Since the cap now depends on the codec, the null codec is resolved before the
base class initializer consumes buf_size, and setCodec re-caps both capacity
sources. offset() is zero there, so nothing is dropped. No production caller
switches from a looser codec to a tighter one, so that part is an invariant
for future callers rather than a fix for a live path.

Second, checkDataPart decided from the file name, and no name test can express
what it needs. Secondary and text index substreams are .idx and .idx2, are
written with max_compress_block_size, and are read through a stream that opts
out, but they match neither .bin nor a mark nor .cidx. CHECK TABLE therefore
reported a pre-cap part with a large skip index as broken while SELECT read it
happily, and a spuriously broken part can be detached. The index extension is
versioned as well, so a literal list would rot. The decision now comes from
the three call sites, which already know the provenance. That leaves
isCompressedFromFileName without an external caller, so it returns to its
anonymous namespace and IMergeTreeDataPart.h is untouched.

The spec said a Multiple codec bounds its nested frames inclusively; it bounds
them exclusively. Corrected in the spec, not in the codec. The engine arm of
the test carried a session-level max_compress_block_size that Log and
StripeLog capture in their constructors, so it never applied; removed, and the
arm now says in the test that it is a no-regression control and which arms
carry the opt-out coverage.

Co-Authored-By: Claude Fable 5 <[email protected]>
… invariant, bound 04848's cost

Three review findings, no blockers. No codec is touched: the diff against the base
adds nothing to src/Compression/CompressionCodec*.{cpp,h}.

1. CHECK TABLE opted statistics out while their readers stayed bounded.

Round 1 moved the bounded/unbounded decision from file names to the call sites, which
closed the asymmetry for skip-index files and opened it for one class in the other
direction. Statistics are written with a hardcoded 1 MiB frame
(StatisticsSerialization.cpp:33 packed, :69 wide) and carry is_compressed = true, and
they are absent from getFileNamesWithoutChecksums(), so they reach the directory pass
and received allow_unbounded_decompressed_size = true, while their readers
(IMergeTreeDataPart.cpp:1265, :1305) are deliberately bounded. A corrupt statistics
header up to 4 GiB was therefore rejected by a SELECT and accepted by CHECK TABLE,
which also reserves that much while hashing it.

The directory pass now classifies the statistics name and passes false for it. The
.bin call sites and the ends_with(".bin") fallback stay unbounded. That pass walks
whatever is on disk, so it has no per-class caller to take the decision from; an
unclassified name is left unbounded, since that only forgoes hardening there while the
opposite mistake reports a good legacy part as broken.

Measured on two binaries differing only in this predicate, each against a fresh copy
of the same fixture (countmin statistics, statistics_v.stats with
size_decompressed = 155606, on a build whose reader bound is lowered to 64 KiB so the
1 MiB writer frame is genuinely over-bound): before, a statistics-loading SELECT
throws Code: 39 while CHECK TABLE returns 1; after, both reject the frame.

2. The docs and changelog claimed a writer invariant the cap does not deliver.

capUncompressedFrameSize reduces a frame by the worst-case expansion the codec
reports, so a codec computing that figure in wrapping UInt32 arithmetic understates it
and the request passes through unreduced. For Gorilla(1) at 2^30,
items_count * max_item_size_bits is 17 * 2^30, which wraps to exactly 1073741824, so
the reported reserve is 134217746 and no reduction happens; a deep Multiple chain
takes the other fallback. Closing that would require 64-bit reserve arithmetic across
every codec, which is out of scope here, and the pre-existing size_compressed reader
bound already rejects such frames.

So the specification is narrowed rather than the arithmetic changed: the format spec,
the changelog entry, the description and the comment in capUncompressedFrameSize now
state that the cap is only as good as the codec's own reserve figure and that the
reader bound is the backstop. Frame sizes at ordinary block sizes remain byte-identical
to master for Gorilla, Gorilla(1), NONE and the default codec.

3. 04848 carried multi-GiB cost with no tag protecting any lane.

Tagged long with a "Memory limits: 10 GiB" header, both of which the harness parses.
Each large output is removed once its last assertion is done, and the incompressible
input is regenerated from a key instead of being kept on disk, so the two 1 GiB files
no longer coexist. Sampled through a full run, the disk peak drops from 3.01 GiB with
three large files alive to 1.00 GiB with one, and no arm's assertion was weakened.

Note that long also scales flaky-check repetitions by --long-test-runs-ratio
(default 0.1), so reproducing a 50-run sweep on this test needs that flag set to 1.

Verification: 04848 passes 50/50 randomized. A 270-test sweep over compression,
codecs, statistics, CHECK TABLE and log engines was run on this build and on a
pristine master snapshot with the same harness invocation and config: 32 failing
versus 33, and the symmetric difference is exactly one test, 04848, which fails on
master and passes here. Zero failures are unique to this build.
…e reader bound's ordering

Round 3 is prose plus one test arm. No behaviour change, no codec touched.

The writer cap can only subtract the worst-case expansion a codec reports, so
it leaves the frame unreduced in two cases, not one. The first was already
documented: a reserve computed in wrapping 32-bit arithmetic understates itself
(Gorilla). The second was not: a reserve that is arithmetically honest but too
large for the limit to absorb returns the request unreduced at
ICompressionCodec.cpp:118-120. A 6x FPC chain reports 2176782471 for a 1 GiB
request, which is below 2^32, so it is not a wrap. The spec, the changelog entry
and the PR description all claimed that a codec reporting its expansion
correctly never emits a frame a reader rejects; that is false for exactly this
codec. All three now state what the code delivers and name the reader's own
bound as the backstop in both cases.

capUncompressedFrameSize returns zero for a zero request: the reserve is tiny,
so the reserve <= limit branch returns the request unchanged. The header comment
claimed it never returns zero. It now states the guarantee that does hold, that
a nonzero request is never reduced to zero. Master already produced an empty
working buffer for --block-size 0, so nothing here regresses and no clamp is
added.

CompressionCodecMultiple bounds the intermediate buffer length it tracks itself
and each nested header's declared uncompressed_size. It never reads a nested
declared compressed_size, and neither does anything else:
readCompressedBlockSize has one caller in the tree, the outer parser. The spec
said both nested fields were bounded.

04848 asserted only the exception text for the 2 GiB arm, which survives moving
the bound after the header-size check, so it did not discriminate the ordering
its label claimed. The frame helper takes an optional size_compressed override,
leaving every existing arm's bytes identical, and a new 30-byte arm declares a
size_compressed below the header size as well: reporting the size_decompressed
message pins that the bound is reached first, hence inside the header parser and
before any allocation. Moving the bound below that check reddens this arm and
nothing else.

Also stop discarding openssl's stderr in the incompressible-input helper, so a
refusal is diagnosable rather than an empty pipe.
… statistics parser reject malformed output

Round 4 is one comment, one test-helper hardening, one table setting and one
30-byte arm. No behaviour change, no codec touched.

capUncompressedFrameSize can only subtract the worst-case expansion a codec
reports, so it leaves a request unreduced when that expansion exceeds what the
limit can absorb: a 6x FPC chain reports 2176782471 for a 1 GiB request, which is
arithmetically honest rather than a wrap, and Gorilla passes through at widths 1,
2, 4 and 8. Of 24 codec and chain cases, 19 reduce and 5 pass through. Round 3
corrected the changelog, the spec and the second half of this header comment, but
the first sentence still promised unconditionally that a full frame serializes
both size fields within the limit, which is the sentence a caller would rely on.
It now states the best-effort contract and names the reader's own bound as the
backstop. CompressedReadBufferBase.h is untouched: its subject is
size_decompressed, which min(buf_size, limit) caps on every path.

The over_bound helper in 04848 merged stderr into its parser and special-cased
one error code. Any other diagnostic fell through to the counting rule, where
empty size fields compare as zero, so a failed read printed the same line as a
clean one: feeding it a file that is not a compressed frame reported zero
over-bound frames. Those four arms are the only oracle for the writer cap, so a
cap regression that also malformed the output would have passed. The parser now
counts a row only when it has three fields and both sizes are all-digits, and
reports anything else. compressor --stat emits exactly those three fields per
frame.

packed_skip_index_max_bytes defaults to 1 MiB and the test runner randomizes it
over five values, four of which bundle a minmax index over 1000 rows into
skp_idx.packed. A packed substream carries no per-file checksum entry, so
checkDataPart never visits it, and the CHECK TABLE arm reached the file class its
comment claimed in one draw of five. The table now pins the setting to zero, the
same mechanism the test already uses for compress_marks and
min_bytes_for_wide_part, and the part carries a standalone skp_idx_idx_s.idx2.

The verbatim-body check dispatches on isNone(), which Quantized overrides as well
as None, and the spec paragraph names both codecs. The read path builds Quantized
from its method byte alone, with no arguments and no experimental gate, so a new
arm covers 0x9e for 30 bytes. Restricting the check to the None method byte
reddens that arm and nothing else.
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (5 rounds, adjudicated)

An independent model reviewed this change cold at each round. Verdicts below; every accepted
finding is fixed in the pushed tree.

Fixed in earlier rounds (round 4 closed the last four):

⚠️ over_bound in the test counted any unrecognised compressor --stat diagnostic as a clean
zero. It now requires a three-column row with two numeric size fields; every other shape prints a
distinct failure text.

⚠️ The CHECK TABLE control did not deterministically reach the standalone skip-index file, because
packed_skip_index_max_bytes defaults to 1 MiB and the test runner randomises it. Pinned to 0 in
the query, which wins over the runner's injection.

⚠️ capUncompressedFrameSize's header comment promised that both frame fields fit, which two
deliberate branches do not provide (a reserve that wrapped in 32-bit arithmetic; an overhead the
limit cannot absorb, e.g. a six-deep FPC chain reporting 2176782471 for 1 GiB). The comment now
states the best-effort contract and the one guarantee that is unconditional: a nonzero buf_size is
never reduced to zero.

⚠️ Only NONE was tested with a mismatched verbatim header, so the Quantized half of the contract
could silently stop being checked. Added the method-byte 0x9e arm.

Not accepted:

❌ Nested NONE/Quantized frames inside a Multiple chain allocate from their declared size
before rejecting a mismatch.
Each step is refuted in source. CompressionCodecMultiple.cpp:109
throws on uncompressed_size >= 1_GiB before the resize at :121, so the nested
pre-allocation is bounded strictly below 1 GiB, i.e. tighter than the inclusive 1 GiB this change
establishes for a top-level frame. CompressionCodecMultiple.cpp is not in the diff, and this
change strictly reduces peak allocation on that path: the outer size_decompressed that sizes the
reader's destination falls from an unbounded 32-bit value to 1 GiB. There is no amplification across
stages, since the loop reuses two buffers via swap at :125. A nested regression arm would also be
vacuous: the mismatch is rejected by CompressionCodecNone::doDecompressData and
CompressionCodecQuantized::doDecompressData, neither of which this change touches, so the arm stays
green with the whole change reverted.

Noted, not blocking:

💡 One imprecision follows from the above: the specification says a verbatim-body mismatch is
rejected "at header-parse time", which is true of a top-level frame. A nested frame has no
CompressedReadBufferBase header parse, so its mismatch is caught one layer down in the codec. The
rejection is unconditional either way; only the stated stage differs.

💡 setCodec's re-cap only ever decreases and does not restore capacity if a later codec has a
looser bound. Unreachable in-tree: the sole caller alternates NONE and the original codec on a
stream clamped to 256 MiB, where the cap is a fixed point.

💡 The new verbatim check turns a previously silent outcome loud. The NONE shortcut in
decompress rebinds the output to the frame body and ignores size_decompressed entirely, so a
NONE frame overstating it used to deliver fewer bytes without complaint. No in-tree writer can
produce such a frame, so nothing legitimate is now rejected.

Session id: cron:clickhouse-review-slot-10:20260811-133900

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, 100% on demand. A 34-byte frame declaring size_decompressed = 2 GiB, with a valid CityHash128, POSTed to ?decompress=1 at default settings: the header-derived allocation is reached on master.
b Root cause explained? ICompressionCodec::readDecompressedBlockSize loads a UInt32 from wire offset 5 and validates only that it is non-zero. CompressedReadBuffer::nextImpl and readBig then size memory.resize from it. The sibling size_compressed is bounded at DBMS_MAX_COMPRESSED_SIZE in both header parsers; this field is bounded nowhere, so a peer-supplied number sizes an allocation up to 4 GiB. validateChecksum is an unkeyed CityHash128 over bytes the same peer supplied, so it does not gate the path.
c Fix matches root cause? Yes. The field is bounded where it is parsed, before any allocation, and writers cap their buffer capacity so that both header fields fit, making the bound an enforceable invariant rather than a check that would reject data ClickHouse itself writes. Capping only size_decompressed was not enough: size_compressed is 9 + doCompressData() and NONE/incompressible-LZ4 expand, so a full-capacity frame serialized 1073741833 and the fixed reader rejected it; the cap now subtracts the codec's worst-case expansion. That expansion is the figure the codec itself reports, and the cap can only subtract it, so the frame is left unreduced in two cases: the figure wraps in UInt32 arithmetic and understates itself (Gorilla), or it is arithmetically honest but larger than the limit can absorb (a 6x FPC chain reports 2176782471 for a 1 GiB request). The docs, changelog and description state both and name the reader bound as the backstop rather than claiming an invariant the cap does not deliver. No widened bounds, no no-random-* tags, no reduced datasets.
d Test intent preserved / new tests added? New test 04848_compressed_decompressed_size_bound.sh, 16 arms, tagged long with # Memory limits: 10 GiB (both header lines verified against the harness parser). No existing test weakened or removed, and no arm's assertion was relaxed to cut cost: each large output is deleted once its last assertion is done and the incompressible input is regenerated from a key, which drops the disk peak from a measured 3.01 GiB with 3 files alive to 1.00 GiB with 1. Arms cover the reader bound, its inclusive boundary in both directions, the ordering of that bound ahead of the next header check (a mutation moving the bound below that check reddens this arm and nothing else, on a separately-built binary), the verbatim-codec consistency check, both writer caps asserting both size fields, a NONE and an incompressible-LZ4 arm at exactly the bound, round-trip byte-equality, the legacy-read opt-outs, and a valid-frame control that proves the negative arms fail for the intended reason. The engine arm carries a shipped comment saying it is a no-regression control and naming the arms that do cover the opt-outs. Three oracles were later strengthened rather than added to: the --stat parser now counts only a well-formed three-field row, so a malformed read can no longer print the same line as a clean one (demonstrated before/after on a non-frame input); the engine table pins packed_skip_index_max_bytes = 0, so the CHECK TABLE arm reaches the per-file skip-index class in every randomizer draw instead of 1 in 5 (part layout observed directly, and against all five drawn values); and a 30-byte arm covers the second isNone() codec.
e Both directions demonstrated? Yes, Build-ID verified. On pristine master a 2 GiB declaration is accepted and the allocation is reached; with the fix it is Code: 39 ... Too large size_decompressed: 2147483648. compressor --block-size 1207959552 writes one 1,207,959,552-byte frame on master and 1073741824 + 134217728 with the fix. NONE at a 1 GiB block size serializes size_compressed = 1073741833 (above the bound) before the codec-aware cap and 1073741801 after; incompressible LZ4 1077952587 before and 1073725290 after. CHECK TABLE on a legacy over-bound skip index returns 0 (part broken) with the pre-fix predicate and 1 with the fix, while SELECT returns 1 in both. Conversely, on an over-bound statistics file CHECK TABLE returned 1 while a statistics-loading SELECT threw Code: 39 ... 155606, and now both reject it: the two file classes fail in opposite directions and each was proven on a fresh fixture copy with two binaries differing only in that predicate. Suite level: 04848 FAILs on the pristine master snapshot and passes with the fix, same config and harness invocation, zero fix-only failures across 270 tests.
f Fix is general across code paths? Both writer classes; both readHeaderAndGetCodecAndSize call sites (in-place and copying branches); both isNone() implementors (NONE 0x02 and Quantized 0x9e), which already enforce the same equality in doDecompressData and are now both covered by an arm, each proven live by a mutation restricting the check to the NONE method byte; both IMergeTreeDataPart::readFile and readFileIfExists; both compressor read paths; both StorageLog branches; both StorageMemory restore readers. Bounded at the parser rather than at nextImpl/readBig, so a future subclass cannot re-open it.
g Fix generalizes across inputs? Boundary values asserted on both sides: 0x40000000 accepted, 0x40000000 + 1 rejected, 2 GiB rejected, 0 already rejected. Codecs LZ4, NONE, ZSTD, Delta+LZ4, Gorilla+LZ4, T64+LZ4 and a 40-deep FPC chain, the last two classes verified byte-identical to pristine master so the cap costs nothing where it must not apply; Multiple keeps its own stricter nested guard. Frame sizes exercised from 12 bytes to 1,207,959,552 bytes, compressible and incompressible input at exactly the bound.
h Backward compatible? Yes. No setting default changes, so no SettingsChangesHistory.cpp entry, and no on-disk format change: a capped writer emits more, smaller frames and existing files are byte-unaffected. Data written before the cap is preserved by 20 per-site opt-outs, each traced to its writer's buf_size individually. Readers whose writers are a fixed size stay bounded, notably checksums.txt at 64 KiB and statistics at 1 MiB, and CHECK TABLE matches that per file class so it accepts what the corresponding read accepts, in both directions. In its directory pass, which walks whatever is on disk and so has no per-class caller, an unclassified name stays unbounded: that forgoes hardening there, while bounding a class a read accepts would report a good legacy part as broken.
i Invariants and contracts preserved? Both capacity sources of CompressedWriteBuffer are capped together, which a mutation proved necessary: capping only one leaves the other reachable. setCodec re-caps both, since the cap is now codec-dependent (no production caller reaches the loose-to-tight direction, so this is defence, not a live fix). A codec whose reserve arithmetic wraps or which refuses the size reports no usable bound, and the request is then left untouched rather than treated as infeasible: the "infeasible" reading clamped a 40-deep FPC chain to 32-byte frames, 262144 instead of 1. The opt-out is a post-construction setter, so it never inspects compressed_in, which is assigned after the base constructor in CompressedReadBufferFromFile and lazily in CachedCompressedReadBuffer. The existing < header_size check still precedes the subtraction in the verbatim-codec test, so it cannot underflow. Error and early-return paths are unchanged.

Session id: cron:clickhouse-impl-slot-6:20260811-042900

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @rschu1ze @alexey-milovidov, could you review this? The reader now rejects a size_decompressed above 1 GiB from the frame header before allocating, and because max_compress_block_size is unclamped the write buffers first cap a frame at the same value using the codec's reported worst-case expansion, with the readers of data an uncapped writer produced opting out per call site.

@rschu1ze

Copy link
Copy Markdown
Member

@groeneai Lots of code is added while the PR description is an unreadable word soup. Please phrase in plain and simple English: What problem are you trying to solve?

@groeneai

Copy link
Copy Markdown
Collaborator Author

Rewritten, thanks. The problem in one sentence: a compressed block header declares an uncompressed size that nothing validates, and the reader allocates exactly that many bytes before decoding, so a peer sending a header that claims 4 GiB makes the reader ask for 4 GiB. The compressed size next to it has been bounded at 1 GiB all along; this gives its sibling the same bound.

On the volume of code: the writer side is what makes it more than one if. max_compress_block_size and compressor --block-size are unclamped today, so a read-side check alone would leave ClickHouse unable to read data it wrote itself. Of the 23 files, 14 are readers of pre-cap data opting out, mechanical except CHECK TABLE.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Aug 12, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [fe598b2]

Summary: ✅


AI Review

Summary

This PR adds the missing body-length vs. size_decompressed validation to the CompressedReadBufferBase::decompress passthrough path for verbatim codecs, and backs it with focused stateless coverage for malformed NONE and Quantized frames plus ordinary Log and MergeTree reads. I did not find a remaining correctness, coverage, or metadata issue in the current three-file diff.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Measured on commit fe598b2.

Metric Baseline Current Δ
Lines 88.00% 88.00% +0.00%
Functions 91.70% 91.70% +0.00%
Branches 79.30% 79.40% +0.10%

Changed lines: Changed C/C++ lines covered: 6/8 (75.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Aug 12, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - beebbd6

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stress test (amd_debug) / Hung check failed, possible deadlock found deadlock: DROP TABLE prometheus parked in waitTableFinallyDropped (is_cancelled: 1, single thread, elapsed 2726 s) while the materialized shared subquery still holds a reference #114326 (external, merged 2026-08-12T01:14:16Z) - absent from this build, see below
Stress test (arm_tsan) / Hung check failed, possible deadlock found same signature, elapsed 3416 s #114326 (external, merged) - absent from this build
Stress test (arm_msan) / Hung check failed, possible deadlock found same signature, elapsed 3030 s #114326 (external, merged) - absent from this build
Stress test (arm_asan_ubsan, s3) / Hung check failed, possible deadlock found same signature, elapsed 2748 s #114326 (external, merged) - absent from this build
Stress test (amd_tsan) (job-level ERROR) same root cause, later phase: the hung DROP TABLE prometheus (elapsed 3317 s) leaves the server unresponsive, so stop_server's SYSTEM STOP DISTRIBUTED SENDS retry loop times out repeatedly until the 10800 s job budget expires (SIGTERM, exit -15) #114326 (external, merged) - absent from this build
Stress test (arm_asan_ubsan, s3) / Sanitizer (STID: 2064-22d0) LeakSanitizer, all-indirect / zero-direct: Context::createCopy retain cycle reached from the query path (issue #114396) #113397 (external, open)
Build (arm_release) / Post Hooks infra: build_profile_hook.py fails closed when the build-profile telemetry INSERT into the shared CI logs cluster is rejected (LogCluster query failed with code 500, 8 retries exhausted). Non-gating - the Build (arm_release) check-run itself is green. a fix task is moved to pending (investigating at full effort - fixing PR link to follow on this PR)
Sync - CH Inc sync (private, not actionable)

None of these is PR-caused. I checked the amd_tsan job specifically, because this PR does touch the
decompression read path: its job.log contains no Too large size_decompressed, no
CANNOT_DECOMPRESS, no ATTEMPT_TO_READ_AFTER_EOF, no sanitizer report and no server death, and the
only hung query is DROP TABLE prometheus. The new test 04848_compressed_decompressed_size_bound
does not appear in any failure. So the timeout is the PromQL hang blocking shutdown, not this diff.

#114326 is merged but not in this build, so a re-run picks it up. Verified from the run itself
rather than from commit distance: the job merged 50 master commits and
86e654b8459485b3448552b802f6934b4f66c15b is not among them, and the run still executed
04811_promql_topk_bottomk_limitk.sql - the very test file that revert deletes. I will merge master
here so CI re-runs with the fix.

⚠️ For anyone triaging this signature from CIDB: test_context_raw keeps the tail of
hung_check.log, so the processlist block naming DROP TABLE prometheus is truncated away and only
the post-mortem stack appendix survives. Read hung_check.log from S3, not the CIDB context.

#113397's fix is genuinely absent from this build, so that red is not evidence against it:
src/Processors/QueryPlan/MaterializingCTEStep.h at this head is blob
97935ebf769dbdec2b41784109abd94b30406259, that PR's exact pre-image.

Gates: (a) 175 check-runs, 0 incomplete non-exempt; (b) Finish Workflow and Config Workflow both
success; (c) last completion 05:55:21Z, >20 min buffer; (d) every line above has an owner.

Session id: cron:our-pr-ci-monitor:20260812-063000

Comment thread src/Storages/StorageMemory.cpp Resolved
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 59805fa

CI is fully finished on this head and there are no failures to own.

176 checks: 157 success, 19 skipped, 0 failure. Config Workflow and Finish Workflow both
concluded success, and the praktika report shows 0 dropped jobs, so the matrix really ran - every
skip carries an ordinary reason (not labeled pr-performance, not a bug-fix PR, reused from cache,
not affected by the changed files).

Session id: cron:our-pr-ci-monitor:20260812-120000

@rienath rienath self-assigned this Aug 17, 2026

@rienath rienath left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This PR is written as if #114189 is in master (and it makes sense). Let's wait for the merge and then continue the review. @groeneai please ping me here once it's merged

@groeneai

Copy link
Copy Markdown
Collaborator Author

Understood, holding the review. #114189 is still open (mergeable state BLOCKED), so there is nothing to ping yet; I will ping here as soon as it merges. No further pushes to this branch until then.

@groeneai groeneai added the groeneai-origin-oranjeai PR origin: delegated from the OranjeAI sibling fleet label Aug 19, 2026

@rienath rienath left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, sorry @groeneai! I meant we need to wait for #113877

@groeneai

Copy link
Copy Markdown
Collaborator Author

Confirmed, and thanks for the correction: the dependency is #113877, not #114189. I will ping you here once #113877 merges.

Status there: #113877 is still open with @ rschu1ze's changes requested from 2026-08-10, and PedroTadim asked him on 2026-08-14 to continue the review, so nothing is pending from me on it. #114189 shares no files with this branch, so its approval today does not change anything here.

…er helpers

Master moved `use_adaptive_buffer_size` and `adaptive_buffer_max_size` into
`BufferWithOwnMemory` behind `adaptiveBufferInitialSize` and
`enableAdaptiveBufferGrowth`. Both bounds are now capped with
`capBufferSize(codec, buf_size)` through those helpers, which keeps this fix's
guarantee that neither the initial allocation nor the growth ceiling can exceed
what the codec can describe in a frame header. `resolveCodec` in the initializer
list subsumes master's null-codec check in the body.

The translation unit was syntax-checked after the resolution.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Aug 29, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing fe598b206 with master 30e4870df (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

7 translation units recompiled, 6 s compile time in total, 7 of them have a recent master baseline.

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

The 04267_ttl_drop_merge_no_data_read failure in Stateless tests (arm_binary, parallel) on b32f1027cefb is not caused by this PR. Case 6 pinned an exact system.part_log.read_rows for a TTLDrop merge and CI randomized index_granularity to 1; the runner's own diagnosis named --index_granularity 1 as the sole culprit, the same signature has fired on six other unrelated PRs since 2026-08-03, and master has 0 failures in 30 days. Fixing PR: #117081.

@nikitamikhaylov

Copy link
Copy Markdown
Member

@groeneai refresh this PR.

@clickhouse-gh clickhouse-gh Bot added the comp-codecs Compression/encoding codecs (LZ4/ZSTD/etc.), archive formats (tar/zip/7z), codec selection and IO... label Sep 4, 2026
Comment on lines +1431 to +1440
### Size limits {#frame-size-limits}

Both size fields are 32-bit on the wire, but each is capped at `0x40000000` (1 GiB) **inclusive**: exactly `0x40000000` is accepted and only a strictly larger value is rejected. A decoder checks both from the header alone, before allocating any buffer sized from either field, and fails with `TOO_LARGE_SIZE_COMPRESSED`. A `Multiple` codec applies the same constant to its nested frames, but exclusively (exactly `0x40000000` is rejected) and to two quantities only: the length of the intermediate buffer it tracks itself, and each nested header's declared `uncompressed_size`. A nested header's declared `compressed_size` is not inspected, because each nested decoder is handed the length the outer decoder tracks rather than one read off the nested header.

The checksum does not gate these checks. It is an unkeyed CityHash128 over bytes the sender chose, so it detects corruption in transit but not a crafted header, and a decoder that sized a buffer from `uncompressed_size` before checking it would honour whatever the sender declared.

A limit is not a validation, so for a method byte whose codec stores the body verbatim (`NONE`, `Quantized`) the two fields are checked against each other as well: they describe the same bytes, so `compressed_size - 9` must equal `uncompressed_size`, and a frame where they disagree is rejected. The same rule applies to a nested frame, where the body length is the length the outer decoder tracks for it rather than a field of the nested header, and the comparison runs before the buffer sized from `uncompressed_size` is allocated.

All of these checks belong to the decoder. Beyond them the format does not constrain the sizes a writer puts in a header.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No need to alter NativeFormat.mdx. These boundary checks are not worth mentioning there

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reverted, the page is untouched now.

Comment on lines +164 to +170
/// A codec that stores data verbatim has body length equal to the decompressed length.
if (codec->isNone() && source_size - COMPRESSED_BLOCK_HEADER_SIZE != uncompressed_size)
throw Exception(decompression_error_code,
"The compressed data size without header ({}) does not match size_decompressed ({}) "
"for a codec that stores data uncompressed",
source_size - COMPRESSED_BLOCK_HEADER_SIZE, uncompressed_size);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This we already check in CompressionCodecNone, which is reached from here as we later call codec→decompress. Remove

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Removed. Checked it first: CompressionCodecMultiple.cpp:176 hands the nested frame to codec->decompress, which reaches CompressionCodecNone.cpp:33 (or CompressionCodecQuantized.cpp:55), and that rejects the mismatch, so the guard was redundant for correctness.

One consequence worth having on the record: uncompressed_buf is resized from the nested declaration at :173, before that call. A nested verbatim frame declaring just under 1 GiB behind a few bytes therefore still allocates and is refused afterwards. It is bounded by the >= 1_GiB guard at :161 and identical to master, so I left it alone.

"the compressed data size ({}, this should include header size) is less than the header size ({})",
size_compressed_without_checksum, static_cast<size_t>(header_size));

/// A codec that stores data verbatim has body length equal to the decompressed length.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Comment is obvious, remove. Remember forever that obvious comments shall not be written

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Removed, along with the check it sat on. Noted for future PRs.

Comment on lines +177 to +181
if (codec->isNone() && size_compressed_without_checksum - header_size != size_decompressed)
throw Exception(external_data ? ErrorCodes::CANNOT_DECOMPRESS : ErrorCodes::CORRUPTED_DATA, "Can't decompress data: "
"the compressed data size without header ({}) does not match size_decompressed ({}) "
"for a codec that stores data uncompressed",
size_compressed_without_checksum - header_size, size_decompressed);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The check is only missing in the isNone() shortcut in CompressedReadBufferBase::decompress, which re-points the output buffer at the body and never calls the codec. So the natural home is inside that shortcut

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Moved there in a17ae9d, and the copy in readHeaderAndGetCodecAndSize is gone. You are right that the shortcut is the only gap: both verbatim codecs check the relationship in their own doDecompressData, and ICompressionCodec::decompress:124 routes every other path through them, so the version I had was duplicating that check on the two paths that do call the codec.

Same ordering note as on the nested guard: CompressedReadBuffer::nextImpl:19 sizes memory from the declared value before decompress runs, so the allocation still precedes the rejection. That is unchanged from master, where the shortcut has no relationship check at all and the frame is accepted as well.

The nested test arms went with the nested guard; 03003_codec_multiple_buffer_overflow is back to its original expectation. The remaining arms in 04848 pin the shortcut in both mismatch directions and for both verbatim codecs, and with the check reverted they are the only lines that change. Title and description updated to match the reduced scope.

Both verbatim codecs already reject a body whose length contradicts the
declared uncompressed size, in CompressionCodecNone::doDecompressData and
CompressionCodecQuantized::doDecompressData. Every read path reaches one of
them through codec->decompress except the isNone() shortcut in
CompressedReadBufferBase::decompress, which re-points the output buffer at the
body and never calls the codec, so that is the only place the check was
missing and the only place it is now added.

The two checks this branch previously carried elsewhere are removed: the one in
readHeaderAndGetCodecAndSize duplicated the codec's own check on the two paths
that do call it, and the one in CompressionCodecMultiple::doDecompressData
duplicated it for a nested frame, which reaches the nested codec through
codec->decompress. Their only remaining effect was to reject before the buffer
sized from the declaration is allocated; that allocation is bounded at 1 GiB by
DBMS_MAX_DECOMPRESSED_SIZE and by the Multiple codec's own 1 GiB guard, and it
is unchanged from master either way.

The NativeFormat.mdx section is dropped, and 03003_codec_multiple_buffer_overflow
returns to its previous expectation now that its nested frame is refused by the
codec again. 04848 keeps the arms that pin the shortcut, in both mismatch
directions and for both verbatim codecs; with the check reverted those three
arms are the only lines that change, and the nested arms went with the nested
check.

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai groeneai changed the title Validate a verbatim codec's declared size before allocating, including inside Multiple Validate a verbatim codec's declared size in the passthrough read shortcut Sep 16, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - a17ae9d

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Build profile diff infra: RuntimeError: CI logs cluster query failed on the binary_sizes read in has_pr_data (build_profile_diff_job.py:723 -> :234), read from the report on this head #120121 (mine, open)
PR rollup mirroring the row above, no independent failure #120121 (mine, open)

157 pass, 18 skipping, 0 pending: no test leg failed on this head. Fast test, Style check, Config Workflow, Finish Workflow, Mergeable Check and CH Inc sync all pass, so nothing in the diff is in question from CI's side.

Session id: cron:our-pr-ci-monitor:20260916-230116

Comment on lines +59 to +60
# No-regression control: the shortcut is the ordinary read path for compressed marks and for the Log
# family, so engines reading frames they wrote themselves have to keep working.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The test below doesn't reach the shortcut

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You are right, it did not. With a breakpoint on the new check, the old control entered it 0 times and entered the else branch that calls codec->decompress 22 times: the shortcut needs codec->isNone(), but marks_compression_codec and primary_key_compression_codec default to ZSTD(3) and the column data defaults to LZ4, so nothing that control read was a NONE frame.

Fixed in 85a2feb by storing the column, the marks and the primary key uncompressed, which takes the shortcut 13 times. StripeLog is gone from the control: StorageStripeLog.cpp:207 builds its single CompressedWriteBuffer with getDefaultCodec() and ignores the column codec, so it cannot reach the shortcut at all (measured 0 entries).

The control is also no longer vacuous. With the header subtraction dropped from the check, it now fails at CompressedReadBufferBase.cpp:314 on the first Log read, where the old control stayed green on the same binary.

The control created its tables with the default codec, so every read went
through codec->decompress instead of the isNone() shortcut in
CompressedReadBufferBase::decompress. Measured with a breakpoint on the new
check: the control entered it 0 times and the else branch 22 times, and an
off-by-header mutation of the check (comparing size_compressed_without_checksum
itself rather than minus the header) left the control fully green.

Store the column, the marks and the primary key uncompressed so the reads go
through the shortcut, which makes the control fail on that same mutation.
StripeLog is dropped from it because StorageStripeLog builds its single
CompressedWriteBuffer with CompressionCodecFactory::getDefaultCodec() and
ignores the column codec, so its reads can never reach the shortcut.
@rienath rienath added pr-not-for-changelog This PR should not be mentioned in the changelog and removed pr-bugfix Pull request with bugfix, not backported by default labels Sep 22, 2026

@rienath rienath left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Very small nit, I don't see a reason to block this PR

@@ -0,0 +1,86 @@
#!/usr/bin/env bash
# Tags: no-fasttest

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not clear why no-fasttest

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nothing in it needed the tag, so I removed it in fe598b2.

It depends on python3, xxd, awk and clickhouse checksum-for-compressed-block. The Fast test image installs the first three (ci/docker/fasttest/Dockerfile:32,38,76), and programs/CMakeLists.txt:98,179 adds the subcommand unconditionally and links it into the binary, so ENABLE_LIBRARIES=0 does not drop it.

Verified rather than assumed: a server built with the cmake flags of ci/jobs/fast_test.py, its config installed by tests/config/install.sh --fast-test, and clickhouse-test --fast-tests-only run inside clickhouse/fasttest. With the tag it is skipped as "running fast tests only"; without it, 20 consecutive runs pass at about 0.55 sec each.

The test needs python3, xxd, awk and the clickhouse
checksum-for-compressed-block subcommand. The Fast test image installs the
first three, and programs/CMakeLists.txt adds the subcommand unconditionally,
so ENABLE_LIBRARIES=0 does not drop it.

Measured rather than argued: a server built with the cmake flags of
ci/jobs/fast_test.py, its config installed by tests/config/install.sh
--fast-test, and clickhouse-test run inside clickhouse/fasttest with
--fast-tests-only. With the tag the test is skipped as "running fast tests
only"; without it, 20 consecutive runs pass at about 0.55 seconds each.
@rienath
rienath added this pull request to the merge queue Sep 23, 2026
Merged via the queue into ClickHouse:master with commit c2816a7 Sep 23, 2026
176 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 23, 2026
@rschu1ze rschu1ze added the pr-must-backport Pull request should be backported intentionally. Use this label with great care! label Sep 24, 2026
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Sep 24, 2026
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Sep 24, 2026
clickhouse-gh Bot pushed a commit that referenced this pull request Sep 24, 2026
clickhouse-gh Bot added a commit that referenced this pull request Sep 24, 2026
Backport #114344 to 26.9: Validate a verbatim codec's declared size in the passthrough read shortcut
clickhouse-gh Bot added a commit that referenced this pull request Sep 24, 2026
Backport #114344 to 26.8: Validate a verbatim codec's declared size in the passthrough read shortcut
clickhouse-gh Bot added a commit that referenced this pull request Sep 24, 2026
Backport #114344 to 26.7: Validate a verbatim codec's declared size in the passthrough read shortcut
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Sep 25, 2026
…red size in the passthrough read shortcut
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Sep 25, 2026
…red size in the passthrough read shortcut
rienath added a commit that referenced this pull request Sep 25, 2026
Backport #114344 to 26.3: Validate a verbatim codec's declared size in the passthrough read shortcut
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Oct 2, 2026
…red size in the passthrough read shortcut
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-codecs Compression/encoding codecs (LZ4/ZSTD/etc.), archive formats (tar/zip/7z), codec selection and IO... groeneai-origin-oranjeai PR origin: delegated from the OranjeAI sibling fleet pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-must-backport Pull request should be backported intentionally. Use this label with great care! pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-not-for-changelog This PR should not be mentioned in the changelog pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants