Skip to content

Fix out-of-bounds write on a long codec chain - #113877

Merged
alexey-milovidov merged 17 commits into
ClickHouse:masterfrom
groeneai:fix-codec-chain-reserve-overflow
Sep 1, 2026
Merged

alexey-milovidov merged 17 commits into
ClickHouse:masterfrom
groeneai:fix-codec-chain-reserve-overflow

Conversation

@groeneai

@groeneai groeneai commented Aug 7, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fixed a server crash and an out-of-bounds write when inserting into a column with a long chain of compression codecs, for example CODEC(FPC, FPC, ..., FPC). CompressionCodecMultiple compounded each stage's reserved size in a UInt32 without checking for overflow, so a long enough chain wrapped the reserved size below its own input and the destination buffer was then sized from the wrapped value while the real payload kept growing. Such a chain is now rejected with CANNOT_COMPRESS. A chain of more than 255 codecs, which used to write a part that could not be read back, is now rejected with BAD_ARGUMENTS when the codec is created, unless allow_suspicious_codecs is set. ALTER TABLE ... MODIFY COLUMN x CODEC(...) with the type omitted used to validate the codec against no type at all, skipping every check that needs the column width, and now validates against the column's existing type, which flips some verdicts in both directions under the default allow_suspicious_codecs = 0. Tables created earlier are unaffected.

Description

CompressionCodecMultiple::getMaxCompressedDataSize compounds each stage's reserve in a UInt32
with no overflow check (CompressionCodecMultiple.cpp:38). Every codec reserves at least its own
input, so the reserve grows each stage and eventually wraps below it, while the payload keeps growing
more slowly: the destination buffer is then sized from a small wrapped number while the real data is
hundreds of megabytes, and the unguarded memcpy in doCompressData (:64) writes past its end.
For Float32/FPC the reserve wraps at stage 105 and the server dies with a SIGSEGV at 150, on a
plain MergeTree table with an ordinary INSERT and no settings.

The guard is a per-stage monotonicity check, since a stage whose reserve comes back below its own
input has wrapped; a second check compares the real post-loop size against the bound just before the
memcpy, which also catches an overflow inside a codec. Widening the accumulator would not help:
getCompressedReserveSize itself returns an already-wrapped UInt32. This mirrors the
doDecompressData hardening in the same file from #60731.

Behaviour change: chains of 105-134 stages return correct results today and are now rejected,
their reserve being already a wrapped, meaningless bound. 104 stages still works unchanged, and
DoubleDelta and Gorilla chains wrap the same way.

Two further reserve defects had to be fixed for that check to be right on every path:

  • AlterCommands.cpp: MODIFY COLUMN may omit the type, and validate passed that null type on
    while apply already resolved it, so the codec was judged without the column's width and the chain
    reserve was computed at the null-type default. It now resolves as apply does, which under the
    default allow_suspicious_codecs = 0 also rejects CODEC(Gorilla, LZ4) on an integer column and
    accepts CODEC(SZ3) on a Float64 column, both the reverse of before. Tables created earlier
    still load, since metadata loading disables these sanity checks.
  • CompressionCodecGorilla.cpp: getCompressedDataSize cached its per-item bit widths in
    function-local statics although data_bytes_size is an argument, so the first Gorilla column in a
    process fixed those widths for all later ones: the chain boundary above depended on process history,
    and a Float64 column after a Float32 one reserved 2 bits per item below its own worst case.
Validation

Debug build, clickhouse local and a real server. The crash arms need the memory limit lifted, since
a limit masks the crash as Code: 241.

CODEC(FPC x N) before after
104 works works, unchanged
105-134 works, but the reserve has already wrapped CANNOT_COMPRESS
140 ASAN heap-buffer-overflow, WRITE of size 2940232275 CANNOT_COMPRESS
150 SIGSEGV / span:522 assertion CANNOT_COMPRESS

Chain length is capped at 255 separately: the codec count is stored in one byte, so 256 codecs used
to write a part whose count read back as 0 (Code: 246 on read).
255 codecs round-trips; 256 is now rejected at CREATE/ALTER with BAD_ARGUMENTS, and on the
write path with CANNOT_COMPRESS for metadata stored earlier.

  • Both directions, pristine master 25d677a44eb4be59 vs the fix: FPC x150 / 2 rows is rc=139
    SIGSEGV before and CANNOT_COMPRESS after; FPC x104 is byte-identical on both.
  • ASAN (master-asan-build, same base): pre-fix heap-buffer-overflow,
    WRITE of size 2940232275, 0 bytes after 2147483648-byte region.
  • Mutation arms: removing either guard alone still rejects the chain (the other catches it);
    removing both reproduces the SIGSEGV. With only the outer bound removed, the inner check reports
    Compressed data of size 2940232416 does not fit the reserved buffer of size 1622428514, the
    exact write ASAN flags.
  • New test 04812_codec_chain_reserve_overflow: 50/50 runs pass with randomized settings and
    50/50 with randomization off.
  • codec/compress suite (188 tests, identical population on both arms): 20 pre-existing
    environmental failures on both, identical failure sets, 0 regressions.

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

Version info

  • Merged into: 26.9.1.498-master (included in 26.9 and later)
  • Backported to: 26.8.31.4, 26.7.35.4, 26.3.57.6

CompressionCodecMultiple::getMaxCompressedDataSize compounds each stage's
reserved size in a UInt32 with no overflow check. Every in-tree codec is
expanding, so the reserve grows each stage and eventually wraps below its own
input: for a Float32 column with FPC the wrap is at stage 105, 4185597296 ->
413829664.

The actual payload also grows, at a measured 1.1215-1.1218x per stage, but more
slowly than the reserve. So from the wrap onward the destination buffer is sized
from a small wrapped number while the real data is hundreds of megabytes, and
doCompressData's unguarded memcpy writes past the end of it. On a plain
MergeTree table with an ordinary INSERT and no settings, a 140-codec chain gives
an ASAN heap-buffer-overflow with a WRITE of size 2940232275 into a 2 GiB
region, and a 150-codec chain kills the server.

Guard the per-stage accumulation instead: a codec never reserves less than its
input, so a smaller result means the computation wrapped. Widening the
accumulator does not detect this, because getCompressedReserveSize returns
UInt32 and would already hand back a wrapped value; only the per-stage
comparison sees it. Also check the final size against the bound the caller
reserved, since the codecs' actual output sizes are computed independently of
that chain of upper bounds.

This mirrors the hardening 9a5085a applied to doDecompressData in the
same file, making the two directions symmetric.

Chains whose reserve has already wrapped but whose payload has not yet overtaken
it (FPC 105 to 134) previously returned correct results and are now rejected.
Past the wrap the bound is a meaningless number and such a chain avoids
overflowing only because the payload has not caught up; 120 stages already
writes 294 MB to disk from 20 KB of input.
CompressionCodecMultiple::getMaxCompressedDataSize capped its total at
numeric_limits<UInt32>::max(), permitting a total_size of 2^32-1. Its own
caller ICompressionCodec::getCompressedReserveSize returns
getHeaderSize() + getMaxCompressedDataSize(...) in a UInt32, so any
total_size in [2^32-9, 2^32-1] wrapped there: 2^32-1 came back as 8 and
2^32-9 as 0. CompressedWriteBuffer::nextImpl sizes the destination buffer
from that value while doCompressData goes on to write up to total_size
bytes, which is the same undersized-destination write this change set
exists to prevent, one level further out. The inner check cannot cover it,
because the size it compares against is total_size rather than
9 + total_size.

Capping at max() - getHeaderSize() makes the largest permitted total_size
map to exactly UINT32_MAX, so the caller's addition can no longer wrap. No
input reaching that nine-value window could be constructed - 3,691,782
block sizes across FPC, Delta and Gorilla chains at every length from 1 to
255 produced no hits, because near 2^32 the accumulator steps over the
window - so this is a fail-closed correctness fix on the contract this
change set already promises, and it ships without a test arm rather than
with one that cannot fail.

Also reword the monotonicity comment: a codec never reserving less than
its input is what the check needs, and it holds wherever inside the callee
the arithmetic wrapped. The converse is not true - Gorilla with a
one-byte data size emits 17 bits per input byte, so its reserve can wrap
and still come back above its input - and the comment should not imply it.

Finally, record in the test that the block size sets the stage at which
the reserve wraps: two rows wrap at stage 148 of the 150 declared, which
is the latest any block size reaches, so the chain must not be shortened.
CompressionCodecMultiple compounded each stage's reserved size in a UInt32
without checking for overflow. Every codec reserves at least its own input, so
a long enough chain wrapped the reserve below its own input; the destination
buffer was then sized from the wrapped number while the real payload kept
growing, and the copy at the end of doCompressData wrote past the end of it.
On master a plain INSERT into a Float32 column with 150 chained FPC codecs
kills the server with a SIGSEGV on a write to an unmapped address, and ASAN
reports a heap-buffer-overflow. No setting is needed to reach it: the chain is
accepted by CREATE TABLE without a warning.

Three checks are added, in the order they can fire:

  - The codec count is stored in a single byte and read back from it when
    decompressing, so a chain of more than 255 codecs is refused. Before this
    the count truncated: a 256-codec chain wrote a part whose header claimed
    zero codecs, so CREATE and INSERT succeeded and the part was committed
    unreadable (CORRUPTED_DATA on every later SELECT).

  - Each stage's reserve is compared against that stage's input. A codec never
    reserves less than its input, so a smaller result means the UInt32
    arithmetic wrapped, wherever inside the callee it happened.

  - The total is capped so that getCompressedReserveSize, which adds
    getHeaderSize() to it in UInt32, cannot wrap in turn.

A final check compares the bytes actually written against the reserved size.
That one is computed from each codec's real output rather than from a bound, so
it still holds if a bound is ever computed wrongly.

Chains between 105 and 134 FPC stages returned correct results before this
change and are now rejected. Past the wrap the reserved size is meaningless;
those chains avoided the overflow only because the payload had not yet caught
up with it, and a 120-stage chain already writes 294,937,560 bytes from 20 KB
of input.

The decompress path in this same file was hardened the same way in ClickHouse#60731.
The comment claimed the 104-stage chain's reserve does not fit the
per-query limit CI's default profile sets. It does fit: limits.yaml sets
`max_memory_usage: 5G`, and `readTextWithSizeSuffix` applies the binary
shift only when the suffix is followed by `i`, so the value is
5,000,000,000 decimal. The reserve is 4,203,159,848 bytes and the
destination allocation `roundUpToPowerOfTwoOrZero` rounds it to 4 GiB,
which is 84% and 86% of that limit.

The `SET max_memory_usage = 0` line stays. The margin is a tenth of the
limit on a single allocation whose size is a pure function of the
reserve, and this arm asserts success, so a failure there would read as
a regression in this change rather than as an environment change. The
test measures a size bound, not memory consumption, which is the same
reason 03634_autopr_input_bytes_estimation gives for lifting it.

Comment only; no behaviour change.
`SET max_memory_usage = 0` in the test lifts the per-query limit, but its parent
is the per-user tracker, and CI pins that to `max_memory_usage_for_user: 32G`
for every stateless job. No query-level setting can raise a per-user limit.

The 104-stage arm allocates a 4 GiB destination buffer, so about seven
concurrent copies of this test fit under that cap and the eighth does not. The
flaky check runs a test 50 times across `--jobs` workers off one shared queue,
so the repeats overlap and the arm that asserts success would instead fail with
`Code: 241` naming the `User` limit.

Measured with eight concurrent copies against a server carrying CI's own
profile: untagged, seven of eight runs fail that way; tagged, the runner places
the test in the sequential group and all eight pass. The three other stateless
tests that touch `max_memory_usage_for_user` all carry `no-parallel` for the
same reason.
The changelog says the fix is not FPC-specific, but every reserve-overflow
rejection arm was an FPC chain: the Gorilla arm was a success control and
DoubleDelta did not appear at all. If rejection ever narrowed to an FPC-shaped
special case, the test stayed green while the advertised behaviour regressed.

Add a rejection arm for Gorilla and both halves of the boundary for
DoubleDelta, so each of the three reserve formulas is pinned by a pair: the
longest chain that still fits, and the first one rejected. Boundaries measured
on the fixture the test already pins, which is what fixes them -- a different
compressed block size moves the rejection stage, so the new arms carry the same
four SETTINGS pins as their FPC siblings.

Reverting the per-stage guard reddens exactly these three rejection arms and
leaves the six others green. The 150-stage FPC arm stays green under that
mutant, because the outer size bound catches that chain instead, so the new
arms cover a case the pre-existing ones could not.

Also correct the no-parallel tag comment. It claimed no query-level setting can
raise the per-user memory limit, which is false: max_memory_usage_for_user is an
ordinary session setting and setOrRaiseHardLimit clears the cap when it is 0.
The true reason the existing SET is not sufficient is narrower -- it sets
max_memory_usage, which bounds the query tracker, whose parent is the per-user
tracker that concurrent copies of this test share. The conclusion is unchanged,
so the tag stays; raising a limit shared with every other test running as
default would export the hazard to them.
@groeneai

groeneai commented Aug 7, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (6 rounds, 0 open findings)

This change went through six independent review rounds before publication: a cold code review
each round, plus a separate second-model gate. Final round: 0 findings from both.

Rounds and what they changed

round outcome
1 Reserve accumulation guarded per stage; a final written-vs-reserved check added.
2 Outer cap lowered by the block-header size, so the caller's own + getHeaderSize() cannot wrap in turn.
3 A comment claiming the boundary arm's reserve does not fit CI's per-query limit was corrected: it does fit (5G in the CI profile is decimal 5e9, not 5 GiB).
4 no-parallel added: the boundary arm allocates just under 4 GiB, and concurrent copies of one test share a per-user memory limit that SET max_memory_usage = 0 does not lift.
5 Rejection witnesses added for Gorilla and DoubleDelta; a false clause in the tag comment corrected.
6 Cold review and gate both clean. Published.

⚠️ The round-5 finding worth naming

The changelog says the fix is not FPC-specific, but every reserve-overflow rejection arm was
an FPC chain: Gorilla appeared only as a success control and DoubleDelta not at all. Had
rejection ever narrowed to an FPC-shaped special case, the test would have stayed fully green
while the advertised behaviour regressed.

Both boundaries were derived from the codecs' own formulas and then measured on the test's
existing pinned fixture: Gorilla accepts 29 stages and is rejected at 30, DoubleDelta
accepts 13 and is rejected at 14 , monotone above the boundary in both cases, so each arm sits
on a real edge. Each new arm carries the same four SETTINGS pins as its FPC sibling, because
the rejection stage is a function of the compressed block size (block 8 rejects at 148,
4096 at 118, 20000 at 105).

What makes them non-redundant rather than merely more coverage: with the per-stage guard
reverted, exactly the three *_over arms redden and the seven others stay green, including
the pre-existing 150-stage FPC arm
, which the outer cap catches instead. So the arms that
existed before provably could not cover what these two add, and the mutant demonstrates it
rather than the commit message asserting it.

💡 Verified and deliberately not changed

  • The overflows 4 GiB message on the sibling arms. For Gorilla and DoubleDelta what
    overflows is an internal bit count (items x 45 and items x 69), which crosses 2^32 while
    the codec's own input is only a few hundred MiB , so the message can read oddly next to the
    input it prints. Re-derived: at the Gorilla firing input of 394,475,519 bytes the product is
    4,437,849,555 = 1.033 x 2^32, genuinely above 4 GiB, and the number printed is the stage
    input, not a claimed bound. The sentence is true for every codec; changing it would have
    made a correct message wrong. Raised twice and settled twice.
  • The per-stage premise is a sound detector, not a complete one. Gorilla(1) and
    DoubleDelta can wrap internally and still return a value above their input (measured:
    28,071,697 such inputs for Gorilla(1); zero for FPC at either width). That cannot
    produce a heap write or a wrong result: the final check throws before the memcpy using each
    codec's actual output, and each of those codecs bounds its own writer from the same wrapped
    value, so BitWriter raises CANNOT_WRITE_AFTER_END_OF_BUFFER first. Disclosed rather than
    fixed here: it is a separate concern in the individual codecs, not in the accumulator.
  • The outer cap ships without a test arm, on purpose. Its admitting window is about ten
    bytes wide out of 2^32, and a search over 3,691,782 block sizes across FPC, Delta and
    Gorilla chains at every length from 1 to 255 found no input that lands in it, because the
    accumulator steps over the window near 2^32. It is a fail-closed correctness fix on a contract
    this change already makes; an arm that cannot fail would be worse than none.

Validation

Both directions on a pristine-master build and on the fix, plus an ASAN build; 50/50 runs with
randomized settings and 50/50 with randomization off, in the sequential group; the codec and
compress suites with an identical failure set on both arms and zero regressions. One earlier
batch read 42/50, and all eight failures were Code: 701 CLUSTER_DOESNT_EXIST from an incomplete
local cluster config, with no other error code present; repaired and re-run clean.

@groeneai

groeneai commented Aug 7, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation
# Check Result
a Deterministic repro? Yes, two of them. CREATE TABLE t (x Float32 CODEC(FPC x150)) ENGINE = MergeTree ORDER BY tuple(); INSERT INTO t SELECT number / 7 FROM numbers(2); on pristine master gives rc=139 SIGSEGV, reproduced 3 times independently this round (directly, through clickhouse-test, and again when the codec/compress suite ran the new test against a base server and aborted with StopTesting: ClickHouse server died). At 150 stages with 5000 rows it aborts at libcxx/include/span:522 instead (rc=134). Separately, a 256-codec CODEC(Delta x255, ZSTD) chain lets CREATE and INSERT succeed and then fails every later SELECT with Code: 246 Wrong compression methods list. No settings needed for either.
b Root cause explained? CompressionCodecMultiple::getMaxCompressedDataSize (CompressionCodecMultiple.cpp:34 on master) compounds each stage's reserve in a UInt32 with no overflow check. A codec never reserves less than its input, so the reserve grows per stage and eventually wraps below its own input (stage 105 for a 20000-byte Float32/FPC block: 4203159734 -> 433587418). The payload also grows, at a measured 1.1215-1.1218x per stage, but more slowly, so from the wrap onward dest is sized from a small wrapped number while the real data is hundreds of MB, and the unguarded memcpy(&dest[1 + codecs.size()], ...) (:64 on master) writes past the end. Independently, dest[0] = static_cast<UInt8>(codecs.size()) truncates above 255 while doDecompressData reads the count back from that one byte, so a longer chain commits a part that cannot be read.
c Fix matches root cause? Yes, all three checks sit in getMaxCompressedDataSize, the function every caller sizes its buffer from. A codec never reserves less than its input, so next < cur detects the wrap wherever inside the callee it happened. Widening the accumulator does not work: getCompressedReserveSize returns UInt32 and hands back an already-wrapped value. Clamping to UINT32_MAX was rejected because a clamped bound is still a lie about what the chain emits, so the write would persist. The count check is at compress time rather than in the factory, because the factory also builds codecs for reading and a table already on disk with such a chain must stay attachable.
d Test intent preserved / new tests added? New 04812_codec_chain_reserve_overflow with 10 arms: five rejection arms (FPC x150, FPC x105, Gorilla x30, DoubleDelta x14 and 256 codecs, each serverError CANNOT_COMPRESS) and five round-trip arms that must keep working (FPC x104, Gorilla x29 and DoubleDelta x13, the longest chains of each whose reserve still fits, plus 255 codecs and a short Delta, ZSTD chain). Each rejection arm is paired with the one-stage-shorter chain that must still succeed, so the arms pin a boundary rather than just an error. No existing test weakened or removed. Each new guard has a mutant that reddens only its own arm.
e Demonstrated in both directions? Yes, on the shipping binary 2df08e6ff4e6cacb37ced4b7c73de373090b6248 against the pristine master debug snapshot 0502ee8df849bfcb439c04b60c0879b53245a021 (git 31081d9f05014003), whose copy of the modified file is md5-identical to this PR's base 25d677a44eb4be59. FPC x150 / 2 rows: base SIGSEGV exit 139, <Fatal> Address: 0x7b239c600040. Access: write. Address not mapped to object., client Code: 32 ATTEMPT_TO_READ_AFTER_EOF then Code: 210 Connection refused; fixed server answers Code: 270 CANNOT_COMPRESS ... at codec 148 of 150 (FPC(12)) and stays alive. FPC x104 is 5000 0 on both. The 256-codec chain: SELECT fails Code: 246 on base, INSERT is refused on the fix. ASAN (master-asan-build, same git hash) reports pre-fix heap-buffer-overflow, WRITE of size 2940232275, 0 bytes after 2147483648-byte region.
f General across code paths? Fixed at the accumulator, not at a crash site. git grep -n getMaxCompressedDataSize -- src/Compression/, excluding tests/, finds 14 const override declarations plus the ICompressionCodec.h:120 virtual default; one of the 14 is Multiple (the accumulator) and the other 13 are the per-codec bounds that feed it. Every chained codec funnels through Multiple, the only compounding accumulator, so one guard covers them all. CompressionCodecAdaptive::getMaxCompressedDataSize takes std::max over a pool rather than a product, and its doCompressData is throwMustNotBeInvokedDirectly(), so it is not a carrier. Confirmed not FPC-specific by reproducing with DoubleDelta x140 (rc=134 before, rejected after), and the committed test now carries that as a permanent witness rather than a one-off measurement: Gorilla x30 and DoubleDelta x14 are rejection arms, each paired with the longest accepted chain of the same codec (x29 / x13). Boundaries measured on the test's own pinned fixture, and the rejection is the reserve guard itself, not merely the same error code. Gorilla x30 reports the size reserved for compressing 394475519 bytes overflows 4 GiB at codec 30 of 30 (Gorilla(4)) and DoubleDelta x14 reports the same at codec 14 of 14.
g Generalizes across inputs? Nullable(Float32) reproduces and is fixed. Float64 correctly does not reproduce at 150 stages: FPC's per-stage ratio is 1 + 1/(2*float_width), so 1.1250x for Float32 but 1.0625x for Float64, which pushes the wrap far out. Empty input is unaffected on both arms. Chain lengths swept 100, 102, 104, 105, 106, 120, 135, 140, 150 for the reserve path, and 255, 256, 257, 511 for the count path. Arms cover an expanding codec (FPC), two with successively larger per-stage reserves (Gorilla, DoubleDelta) and a non-expanding one (Delta): three different reserve formulas, so the guard is exercised at three widely separated chain lengths (105, 30, 14) rather than one.
h Backward compatible? No format, serialization or setting change, so no SettingsChangesHistory.cpp entry. Only the compress path changes; decompression is untouched and existing data was written by a chain that did not overflow. Two deliberate behaviour changes, both called out in the PR description: chains whose reserve has already wrapped but whose payload has not yet overtaken it (FPC 105-134) previously returned correct results and are now rejected, and chains longer than 255 codecs are now refused instead of writing an unreadable part.
i Invariants and contracts preserved? The new exceptions are not swallowed: a catch census of the reserve consumers is 0 for CompressedWriteBuffer.cpp, ParallelCompressedWriteBuffer.cpp and CompressedSizeCalculator.cpp; ConfigProcessor.cpp has catch sites but constructs a bare CompressionCodecEncrypted, never Multiple. All three checks throw before any destination buffer is allocated and before dest is written, so no partial output is produced. ParallelCompressedWriteBuffer has 0 construction sites in src/, so no path is left holding a lock across a throw. The symmetric doDecompressData in the same file was already hardened by #60731; this makes the two directions consistent.

Mutation arms, each with its own asserted Build ID. Reverting only the codec-count check rebuilds
to 0376a648669a57cb42be1fa5e3a590607aa4e37c and reddens only the 256-codec arm. Making the wrap
guard fire one wrap late instead of on the first
(92667aa026b358071640b98684d8a2643e9dd5aa) reddens only the 105-stage arm and leaves the 104-stage
arm green, which is what pins the 104/105 boundary. Removing either wrap guard alone still rejects the
150-stage chain because the other catches it; removing both reproduces the SIGSEGV. With only the
outer bound removed, the inner check reports Compressed data of size 2940232416 does not fit the reserved buffer of size 1622428514, which is the write ASAN flags. Reverting the per-stage guard
outright (802fd1af98f3be126abe9e9094a74db6ed35252c) reddens exactly the three rejection arms whose
verdict depends on it (FPC x105, Gorilla x30 and DoubleDelta x14, each on its own reason
the query succeeded but the server error '270' was expected), and leaves the other seven arms
green, including all three one-stage-shorter controls. The FPC x150 arm also stays green there,
because the outer bound catches that chain instead: the sibling arms cover a case the original
x150 arm could not. Restoring the fix rebuilt to the pre-mutation Build ID byte-exactly.

The outer bound stops at UINT32_MAX - getHeaderSize() rather than UINT32_MAX because its caller
ICompressionCodec::getCompressedReserveSize adds getHeaderSize() to the result in a UInt32.
Reverting just that subtraction makes total_size = 2^32-1 permitted, whereupon the caller returns
8 and the buffer is again smaller than the payload; with it, the largest permitted total_size
maps to exactly UINT32_MAX and cannot wrap. No input reaching that 9-value window could be
constructed (3,691,782 block sizes across FPC / Delta / Gorilla chains at every length 1..255, 0
hits), so this is a fail-closed correctness fix rather than a second reachable crash, and it
deliberately ships without a test arm.

The stage at which the reserve wraps is a function of the compressed block size, which the test
runner randomizes indirectly through index_granularity and index_granularity_bytes, so all six
boundary tables pin both of those along with min/max_compress_block_size. The four remaining
tables are count-path or control arms whose verdict does not depend on the block size, and they
carry no pin. Measured: with the granularity pin removed, 3 of 50 randomized runs fail on the
105-stage arm; with it, 50/50 pass.

Test runs: 04812 passes 50/50 with randomized settings and 50/50 with randomization off. The
codec/compress suite over an identical population (Found 181 parallel tests and 7 sequential tests on both arms, this PR's own test excluded so the base server survives) shows 20 pre-existing
environmental failures on both arms, identical failure sets, and 0 regressions.

@groeneai

groeneai commented Aug 7, 2026

Copy link
Copy Markdown
Collaborator Author

cc @CheSema @yakov-olkhovskiy, could you review this? CompressionCodecMultiple compounded each stage's reserved size in a UInt32 with no overflow check, so a long enough codec chain wrapped the reserve below its own input, dest was then sized from the wrapped value while the real payload kept growing, and the final memcpy wrote past the end of it (SIGSEGV on master, ASAN heap-buffer-overflow). The reserve is now checked per stage, and a chain of more than 255 codecs is refused because the codec count is stored in one byte.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Aug 7, 2026
@PedroTadim PedroTadim self-assigned this Aug 7, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [3585caf]

Summary: ✅


AI Review

Summary

This PR hardens CompressionCodecMultiple against reserve overflow, adds the early >255 codec-chain reject, fixes the Gorilla reserve-width cache bug, and expands the stateless coverage around the new boundaries. The column/ALTER/tuple fixes look coherent, but one metadata-validation path is still left behind in the MergeTree codec settings, so I would not treat the change as complete yet.

Findings

⚠️ Majors

  • [src/Compression/CompressionFactoryAdditions.cpp:67-72, src/Storages/MergeTree/registerStorageMergeTree.cpp:920-930, src/Storages/MergeTree/MergeTreeData.cpp:5409-5410] default_compression_codec, marks_compression_codec, and primary_key_compression_codec still validate through validateCodecString(..., /*sanity_check=*/ false), so they bypass the new >255/reserve-overflow sanity checks entirely. CREATE and later ALTER ... MODIFY|RESET SETTING can therefore still persist an unwritable 256-codec chain and only discover it on the first part write, which leaves the PR's “reject invalid chains when the metadata is created” contract incomplete on this settings surface. [dismissed by author -- https://github.com/Fix out-of-bounds write on a long codec chain #113877#discussion_r3740435973]
    Suggested fix: add a dedicated count / reserve-overflow validation path for codec-string settings, or run an equivalent count-only sanity check at the MergeTree setting call sites so these values fail at definition time without enabling the whole allow_suspicious_codecs bundle.
Final Verdict

Changes requested: the MergeTree codec-setting path still accepts metadata that the new guards only reject later at write time.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 87.00% 87.00% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 79.40% 79.30% -0.10%

Changed lines: Changed C/C++ lines covered: 90/96 (93.75%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 7, 2026
@PedroTadim PedroTadim added pr-critical-bugfix pr-must-backport Pull request should be backported intentionally. Use this label with great care! labels Aug 7, 2026
{
/// doCompressData stores the number of codecs in one byte, and doDecompressData reads it back
/// from there, so a longer chain would write a part that cannot be read.
if (codecs.size() > std::numeric_limits<UInt8>::max())

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Accepting a 256-codec chain only to fail on the first write still leaves an unsupported schema in metadata. This guard fires once compression starts, but new CREATE/ALTER column codecs, TTL ... RECOMPRESS CODEC(...), and MergeTree codec settings can still validate and persist the AST today, so replicated DDL can fan out a codec definition that no replica can ever use successfully.

Can we reject >255 chains in the metadata-validation paths as well, and keep this runtime check only as the backstop for old attached metadata / already-written parts?

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.

Agreed, and done in 9442583.

I checked the premise before changing anything, and it held: validateCodecAndGetPreprocessedAST
had no count check at all, so on the previous commit a 256-codec CREATE succeeded and stored the
AST, and only the INSERT failed. ALTER MODIFY COLUMN, ALTER ADD COLUMN and
ALTER ... MODIFY TTL ... RECOMPRESS CODEC(...) behaved the same way.

The consequence is a bit worse than write-time CANNOT_COMPRESS. Going through
default_compression_codec on unpatched master, the insert succeeds and every later read fails with
Code: 246 CORRUPTED_DATA.

The check now sits next to the other codec sanity checks, so it is gated on sanity_check and is
skipped on the metadata-load path, which is the backstop split you asked for. I verified that
directly: a table created with a 256-codec column by a pristine master binary still loads on the
patched one. CREATE/ALTER/TTL now give BAD_ARGUMENTS; the write-path guard stays as
CANNOT_COMPRESS for metadata stored earlier. I also corrected the changelog entry, which named
only CANNOT_COMPRESS.

Three test arms cover the new rejection, and reverting only the new check reddens exactly those
three, each on its own reason, while the ten existing write-path arms stay green.

One thing I deliberately did not fold in. The codec-valued MergeTree settings
(default_compression_codec, marks_compression_codec, primary_key_compression_codec) validate
with sanity_check=false, so they still accept a 256-chain, as does column DDL under
allow_suspicious_codecs=1. This change already turns the harmful half of that into a loud failure
at write time instead of unreadable data, so what is left is where the diagnosis appears. Passing
sanity_check=true there is not the fix: it would also switch on the NONE-with-others and
"does not compress anything" checks, and marks_compression_codec = 'NONE, LZ4' is accepted today
but rejected under sanity_check=true. Two in-tree tests already put multi-codec chains in those
settings (04402_adaptive_codec_encryption_preserved, 04616_experimental_codec_in_merge_tree_settings).
A count check independent of that bundle is a separate change, and I would rather not grow a
critical bug fix that is queued for backport.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This is still open for the MergeTree codec settings that were part of the original report. Both the CREATE/ATTACH path at src/Storages/MergeTree/registerStorageMergeTree.cpp:916 and the ALTER ... MODIFY|RESET SETTING path at src/Storages/MergeTree/MergeTreeData.cpp:5149 still call validateCodecString(..., /*sanity_check=*/ false), so they bypass the new >255 check at src/Compression/CompressionFactoryAdditions.cpp:243.

That means default_compression_codec, marks_compression_codec, and primary_key_compression_codec can still persist a 256-codec chain and only fail later on write instead of being rejected when the metadata is created.

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.

The two call sites are right, with one correction: the ALTER ... MODIFY|RESET SETTING path is MergeTreeData.cpp:5103, not :5149. Line 5149 is inside the partition-key alter checks. registerStorageMergeTree.cpp:916 and CompressionFactoryAdditions.cpp:243 are as you cite them.

What I am declining is the remedy, for the reason already in this thread: #113877 (comment)

Both halves re-measured on the current head b89c658 rather than restated:

  • marks_compression_codec = 'NONE, LZ4' and primary_key_compression_codec = 'NONE, LZ4' are accepted today. The same chain as a column codec is Code: 36. Passing sanity_check=true at those two sites switches on the whole bundle, not only the count check, so it would start rejecting settings values that work now.
  • The harmful half is already closed here. With 256 codecs in default_compression_codec, pristine master accepts the CREATE and the INSERT, then fails every read of the column with Code: 246 CORRUPTED_DATA. On this branch the INSERT fails with Code: 270 CANNOT_COMPRESS and nothing unreadable is written. What is left is where the diagnosis appears, not whether data can be corrupted.

One thing I should correct from my earlier reply, since I checked it properly this time: I cited 04402_adaptive_codec_encryption_preserved and 04616_experimental_codec_in_merge_tree_settings as putting multi-codec chains in those settings, which they do, but neither actually breaks under sanity_check=true. 'LZ4, AES_128_GCM_SIV' passes it, and 'LZ4, ZXC' on line 11 asserts only BAD_ARGUMENTS, which it would still get. So the in-tree tests are not the obstacle. The NONE, LZ4 case is, and that is about existing user configurations rather than the test suite.

A count check that does not drag in the rest of the sanity bundle is a reasonable thing to want. I would rather not grow a critical bug fix carrying pr-must-backport to add it, so I think it belongs in a separate change.

This is my second pass on the same point, so I will leave it here for a maintainer to decide.

CompressionCodecMultiple stores the number of codecs in a single byte, so a
chain of more than 255 codecs describes a part that cannot be read back. The
write-path guard added earlier in this PR rejects such a chain on the first
write, but by then the codec is already in the metadata: CREATE, ALTER MODIFY
COLUMN, ALTER ADD COLUMN and TTL ... RECOMPRESS CODEC all accepted and
persisted it, so replicated DDL could fan out a codec definition no replica can
ever write with. Measured before this commit: CREATE stored a 256-codec column
and only the INSERT failed.

Reject it in validateCodecAndGetPreprocessedAST instead, next to the other
codec sanity checks. It is a sanity check, so it is skipped on the
metadata-load path, where sanity_check is false: a table stored by an earlier
version stays loadable after an upgrade, verified by creating one with a
pristine master binary and loading it with this one. The write-path guard
remains as the backstop for such already stored metadata and for parts that
were written before.

Reverting only the new check reddens exactly the three new test arms, each on
its own reason, and leaves the ten existing write-path arms green.
getCompressedDataSize cached DATA_BIT_LENGTH in a function-local static, but
data_bytes_size is one of its arguments, so the first column compressed in a
process fixed the value for every later column of a different width.

A Float32 column then reserved per item as if it were 8 bytes wide once a
Float64 Gorilla column had been compressed first, and a Float64 column reserved
as if it were 4 bytes wide in the other order. The first direction only
over-reserves, but it moves the stage at which a long Gorilla chain's compounded
reserve crosses 4 GiB, which is how CI hit it: 04812's 29-stage arm is the
longest chain that fits, and it was rejected at stage 27 when an earlier test in
the same server had compressed a Float64 Gorilla column. The other direction
under-reserves, and BitWriter::doFlush then rejects the write rather than
overrunning the buffer.

The two statics were introduced with the codec in 2019. The other two in this
file are inside templates and are keyed on sizeof(T), so they are constant per
instantiation and are left alone.

04812 grows a Float64 Gorilla arm before its Float32 chain arms, so the boundary
they pin no longer depends on what ran before them.
The Float32 arms alone cannot witness the width-dependent reserve: whichever
width a process compressed first is the one the old static fixed, and a test
cannot choose that. When a Float32 Gorilla column happened to be compressed
first, the previous commit's revert left those arms behaving correctly and they
passed.

A Float64 Gorilla chain has its own boundary, at 48 stages for this fixture, and
it moves the opposite way: frozen at the Float32 width it accepts 49 stages,
which is one too many. So the two pairs redden in complementary orderings, and
between them one of them always does.
@groeneai

groeneai commented Aug 8, 2026

Copy link
Copy Markdown
Collaborator Author

The Stateless tests (amd_llvm_coverage, 2/3) failure on 9442583 was mine, and it was not a
calibration problem with the 29-Gorilla arm. Pushed b89c658 with the fix.

getCompressedDataSize in CompressionCodecGorilla.cpp cached its per-item bit length in a
function-local static, but data_bytes_size is one of its arguments, so the first Gorilla column
compressed in a process fixed that value for every later column of a different width:

static const auto DATA_BIT_LENGTH = getBitLengthOfLength(data_bytes_size);

A Float32 column then reserved as if it were 8 bytes wide once a Float64 Gorilla column had been
compressed first, which moves the stage at which a long chain's compounded reserve crosses 4 GiB from
30 to 27. That is exactly what CI reported: 439207233 bytes overflows 4 GiB at codec 27 of 29. I
reproduced it locally, byte for byte, by inserting into a Float64 Gorilla column before running the
test, and the same run passes on a fresh process. The statics date to the original 2019 Gorilla
commit. The other two in the file are inside templates keyed on sizeof(T), so they are constant per
instantiation and I left them alone.

The other direction under-reserves: a Float64 column reserving as if it were 4 bytes wide. That one
is caught by BitWriter::doFlush, which throws CANNOT_WRITE_AFTER_END_OF_BUFFER rather than
overrunning the buffer, so it rejects a legitimate write instead of corrupting memory.

On the test: my first attempt added only a Float64 arm before the Float32 chain arms, and that is
not enough. Whichever width a process compresses first is the one the old static fixed, and a test
cannot choose that, so with a Float32 Gorilla column compressed first the Float32 arms behave
correctly and pass even with the fix reverted. I measured that directly. The test now pins the
boundary for both widths, 29/30 for Float32 and 48/49 for Float64, and the two pairs redden in
complementary orderings: reverting the fix now fails in all three orderings I tried, and on the
Float64 arm specifically in the one where the Float32 arms go quiet.

Validation: 50/50 randomized and 50/50 with randomization off, plus 200 randomized runs in total. One
run in those 200 accepted all three _over chains, two of which predate this change, so that draw is
not introduced here and I have not been able to reproduce it by replaying its settings. A codec compress gorilla delta slice against a pristine-master control arm compares equal as sets by reason:
0 regressions. The one difference favours this branch, where master's arm died on the original
out-of-bounds write that this PR fixes.

@groeneai

groeneai commented Aug 8, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — b89c658

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
Stress test (amd_debug) / Sizes of nested column and null map of Nullable column are not equal after deserialization (STID 6726-6673) logical error thrown at SerializationNullable.cpp:178 under MergeTreeIndexGranuleSet::deserializeBinary -> MergeTreeIndexReader::read, i.e. a set skip index whose granules on disk were written with a different type than the one decoding them. Nothing in this diff touches serialization or skip indexes (it changes compression-codec reserve arithmetic), and the signature is trunk-wide: 17 rows / 17 distinct PRs / 1 on master over 30 days #112484 (mine, open)
Stress test (arm_msan) / Bad cast from type DB::ColumnString to DB::ColumnNullable (STID 3520-4525) assert_cast at SerializationNullable.cpp:47 inside enumerateStreams, reached through SerializationArray::enumerateStreams — a synthesized Nested group whose element type does not match the part's own column type. Unrelated to this diff; trunk-wide at 32 rows / 30 distinct PRs / 1 on master over 30 days #113925 (mine, open)
Build (arm_release) / Post Hooks non-gating build-profile telemetry upload: the shared CI logs cluster readiness probe failed (ERROR: No connection to LogCluster, ERROR: LogCluster not ready), so the INSERT retry loop was never entered. The Build (arm_release) check-run itself is green, and this mode is trunk-wide at 326 rows / 222 PRs / 53 on master over 7 days a fix task is created (investigating at full effort — fixing PR link to follow on this PR)
Sync not applicable CH Inc sync (private, not actionable)

Mergeable Check and PR are aggregates of the rows above rather than independent failures.
No failure is caused by this diff (CompressionCodecGorilla.cpp, CompressionCodecMultiple.cpp,
CompressionFactoryAdditions.cpp plus one new stateless test); the PR's own test
04812_codec_chain_reserve_overflow is green, including under llvm coverage.

On the Post Hooks row: #113409 ("Retry the build-profile telemetry INSERT") merged
2026-08-06T00:05:00Z and is deliberately not linked here. That change raises the INSERT retry count,
but this artifact carries zero LogCluster query failed with code lines and one
No connection to LogCluster plus one LogCluster not ready — the readiness probe failing strictly
before the retry loop, which the merged fix does not cover.

Session id: cron:our-pr-ci-monitor:20260808-143000

-- size bound, not memory consumption, so lift the limit rather than tune it.
SET max_memory_usage = 0;

DROP TABLE IF EXISTS t_codec_chain_overflow;

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.

@groeneai t_codec_chain_meta_alter and t_codec_chain_256_meta tables are not in this list.

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.

Added both, in 62bccc8.

t_codec_chain_meta_alter was only in the trailing cleanup, so an interrupted run left it behind and the next run in that database failed with TABLE_ALREADY_EXISTS. Reproduced by cutting the run short after it is created, then re-running: Code: 57 before, clean after.

t_codec_chain_256_meta I added to the leading list only. Its CREATE is an expected-error arm, so the table is never created and an unconditional DROP TABLE in the trailing list gives Code: 60 UNKNOWN_TABLE. I checked the other 13 tables the same way; those were already in both lists.

The metadata-validation arms added two tables, t_codec_chain_256_meta and
t_codec_chain_meta_alter, but neither reached the leading DROP TABLE IF EXISTS
list. A run interrupted between creating t_codec_chain_meta_alter and the
trailing cleanup therefore leaves it behind, and the next run of the test in
that database fails with TABLE_ALREADY_EXISTS instead of starting from a known
state.

t_codec_chain_256_meta is added to the leading list only: its CREATE is an
expected-error arm, so the table is never created and an unconditional DROP in
the trailing list would fail with UNKNOWN_TABLE.
@clickhouse-gh

clickhouse-gh Bot commented Aug 8, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 3585caf4f with master 5391ee5b1 (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
Binary Master PR Δ
programs/clickhouse-stripped 704.50 MiB 701.49 MiB -3.01 MiB (-0.43%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Object file sizes

6 object files changed (+43.21 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/clickhouse_compression.dir/Compression/CompressionCodecMultiple.cpp.o 80.53 KiB 103.00 KiB +22.47 KiB (+27.91%)
src/CMakeFiles/clickhouse_compression.dir/Compression/CompressionFactoryAdditions.cpp.o 109.43 KiB 130.96 KiB +21.54 KiB (+19.68%)

737 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Job report

@groeneai

groeneai commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the Build (arm_release) / Post Hooks line on b89c658d26d244131b729c2008c2bec37c0f74bc: #113592 (external, open, MERGEABLE/CLEAN, CI green).

That ledger line promised the link once a fix existed. It resolves the readiness-probe mode specifically: LogCluster.do_query probed is_ready() once before its retry ladder (ci/jobs/scripts/log_cluster.py:88-90), so one 3-second SELECT 1 blip abandoned the INSERT without attempting a single POST. #113592 deletes that pre-loop probe and re-probes inside the backoff loop, matching what select() in the same file already does. Line-for-line the three statements my analysis named as the cause are the three the diff removes.

Still deliberately NOT linking #113409: it raises do_querys retry count, and do_query is never reached in this mode.

@groeneai

groeneai commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 62bccc8

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_asan_ubsan) / Logical error query (STID 0250-41a5) trunk bug, not this PR #102308 (external, open)
Stateless tests (arm_binary, sequential) / 04650_replace_cancellation test oracle defect; merged #113031 is present and did not cover this shape a fix task is created (investigating at full effort - fixing-PR link to follow on this PR)
CH Inc sync private sync CH Inc sync (private, not actionable by me)

STID 0250-41a5 is the "Not-ready Set" family: the abort is a FunctionIn::executeImpl
(src/Functions/in.cpp:116) on a set that was never built, on a server-side-fuzzed
SELECT DISTINCT ... GROUP BY 1, isNullable(1) WITH TOTALS. Nothing in this PR's compression-codec
diff is on that path. @alexey-milovidov's #102308 ("Restore subquery plans after failed in-place set
build") is the tracked fix, still open as a draft; the family is tracked in issue #107619.

04650_replace_cancellation is not linked to a fixing PR on purpose. #113031 (merged
2026-08-03T10:02:18Z) fixed the broad flakiness - before it, 40 rows across 10 PRs in 60 days; after
it, 3 rows on 1 PR and 0 on master - but its merge commit a425931d393b285e is already an ancestor
of this head, so this failure happened with that fix present and it cannot be the owner. Both
captured diffs are a single folded case flipping to no timeout, which matches a residual I recorded
publicly when #113031 superseded my own #113034: the folded branch still falls back to bounding the
client's wall clock when no elapsed number is reported, and that bound can pass or fail on load
alone.

I am not calling it PR-caused, but I am also not calling it plain flakiness, because the numbers do
not look like either: post-fix this test ran 2133 times over 803 PRs on that check and failed 3 times,
and all 3 are this PR (3 of my 4 heads red, vs 0.14% fleet-wide). The obvious explanations are
refuted - this PR touches only the Gorilla/Multiple codecs and the codec factory, its own new test is
green 12 for 12 in the same check, and 04650's duration here (avg 32.6 s) is if anything slightly
below the 2130 other runs (avg 33.1 s). So the first job of the fix task is to explain that
correlation rather than assume a side.

Session id: cron:our-pr-ci-monitor:20260809-013000

@groeneai

groeneai commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the Stateless tests (arm_binary, sequential) / 04650_replace_cancellation failure created: #114018

Neither mechanism has a causal path from this PR's diff, so it is exonerated: case 6 genuinely finished inside its deadline (exception_code = 0 in 7 of 9 attempts recorded in the failing jobs' query_log, with UserTimeMicroseconds constant within 3% while SoftPageFaults swung 16-30x, i.e. host page-fault cost), and case 25 died of MEMORY_LIMIT_EXCEEDED rather than the deadline. Both landed on one catch-all oracle arm printing no timeout, which reads as a cancellation defect.

@groeneai

groeneai commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator Author

Update on that link: #114018 now removes 04650_replace_cancellation instead of re-sizing its two
drifting cases, at @ PedroTadim's request (the test had needed eight follow-up commits and three
further pull requests in the eight days since it landed). It still owns this ledger row, so the check
stops failing either way.

@clickhouse-gh

clickhouse-gh Bot commented Aug 24, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 39 queries analysed

no significant changes detected. K_source=6 K_base=30 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 6ac7ea58-0569-4f59-b9b3-8452c6b211c9
  • MIRAI run: 0e9ac08a-a87f-43a8-8bed-f53466362e50
  • PR check IDs:
    • clickbench_149276_1787547018
    • clickbench_149282_1787547018
    • clickbench_149293_1787547018
    • tpch_adapted_1_official_149318_1787547018
    • tpch_adapted_1_official_149708_1787547037
    • tpch_adapted_1_official_149841_1787547056

@alexey-milovidov

Copy link
Copy Markdown
Member

@rschu1ze, unassigning, because you don't review it.

@alexey-milovidov alexey-milovidov self-assigned this Aug 31, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 1, 2026
Merged via the queue into ClickHouse:master with commit 6d34bff Sep 1, 2026
178 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 1, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

@groeneai @alexey-milovidov — title/description suggestions:

Description (currently incomplete):

  • Why: The body explains the CompressionCodecMultiple overflow in detail but never mentions the two other source changes: the AlterCommands.cpp:2151 type resolution (which changes which ALTER ... MODIFY COLUMN ... CODEC(...) statements are accepted) and the CompressionCodecGorilla.cpp:171-173 static removal (a separate pre-existing under-reserve bug).

  • Suggested addition:

    Two further changes are in this PR and deserve a line each:

    • AlterCommands.cpp:2151: ALTER TABLE ... MODIFY COLUMN x CODEC(...) that omits the type previously validated the codec with a null data type, so every type-dependent sanity check was skipped. It now validates against the column's type. This makes some previously-accepted statements fail (e.g. CODEC(Gorilla, LZ4) on an integer column) and some previously-rejected ones work (e.g. CODEC(SZ3) on a Float64 column).
    • CompressionCodecGorilla.cpp:171-173: getCompressedDataSize cached data_bytes_size-derived bit widths in function-local statics, so the first compressed column's width was reused for every later one. A Float64 column compressed after a Float32 one got a reserve 2 bits per item short of its own worst case.

Ignore if intentional.

@rschu1ze rschu1ze added the pr-must-backport Pull request should be backported intentionally. Use this label with great care! label Oct 19, 2026
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Oct 19, 2026
clickhouse-gh Bot added a commit that referenced this pull request Oct 19, 2026
Backport #113877 to 26.8: Fix out-of-bounds write on a long codec chain
PedroTadim added a commit that referenced this pull request Oct 19, 2026
Cherry-pick of #113877 onto 26.3, as in the 26.8 backport
#126675: AlterCommands keeps this branch's
allow_suspicious_codecs / allow_experimental_codecs arguments and only validates against the
column's type when the ALTER does not give one; CompressionFactoryAdditions adds only the
VectorWithMemoryTracking include.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
PedroTadim added a commit that referenced this pull request Oct 19, 2026
Cherry-pick of #113877 onto 26.7, as in the 26.8 backport
#126675: AlterCommands keeps this branch's
allow_suspicious_codecs / allow_experimental_codecs arguments and only validates against the
column's type when the ALTER does not give one; CompressionFactoryAdditions adds only the
VectorWithMemoryTracking include.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Oct 19, 2026
clickhouse-gh Bot added a commit that referenced this pull request Oct 19, 2026
Backport #113877 to 26.7: Fix out-of-bounds write on a long codec chain
rschu1ze added a commit that referenced this pull request Oct 19, 2026
Backport #113877 to 26.3: Fix out-of-bounds write on a long codec chain
strtgbb pushed a commit to Altinity/ClickHouse that referenced this pull request Oct 21, 2026
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 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-bugfix Pull request with bugfix, not backported by default 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-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