Repository navigation
Cherry pick #113877 to 26.3: Fix out-of-bounds write on a long codec chain - #126673
Merged
Merged
Conversation
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 #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.
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.
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.
… created A chain long enough to compound its reserved size past a UInt32 could not compress a block of any size, but the table was still created and the failure only surfaced on the first write. Reject it in the metadata sanity check instead, by probing the chain with a one-byte block: a codec never reserves less than its input, so a reserve below the input means the compounding wrapped, and wrapping on the weakest possible block means no block can ever be compressed. The write-path guard stays as the backstop for chains that only overflow at some block sizes, which cannot be decided before the block size is known, and for the metadata-load path where the sanity check is deliberately not enforced. The test's 150-FPC arm now asserts the rejection at CREATE TABLE. It also pins min_columns_to_activate_adaptive_write_buffer, whose low values shrink the compressed block enough that the boundary arms stop overflowing (1 failure in 110 runs before, 0 in 60 after).
Both ALTER forms that carry a codec go through the same metadata sanity check as CREATE, so both already rejected such a chain. Pin that, so the coverage cannot regress unnoticed.
A codec whose reserve depends on the column width resolves to a different concrete codec per substream, and the writers re-resolve it per substream when they compress. The metadata sanity check kept only the last resolved codec of each AST element, so for a heterogeneous column it probed one substream's chain and accepted the DDL on that answer. Tuple(Float32, Float64) CODEC(FPC x150) was accepted because the Float64 element is visited last and FPC(8) never wraps, while the Float32 substream still wrapped at stage 148 and failed the first INSERT with CANNOT_COMPRESS. The element order decided the verdict: Tuple(Float64, Float32) was rejected. Collect one chain per substream and require every one of them to fit, so a chain that no substream of the column can compress is rejected when the metadata is created, whatever the element order. Tuple(Float64, Float64) with the same chain stays accepted, so this is not a length limit.
MODIFY COLUMN may omit the type, and `validate` passed the command's nullable type straight through while `apply` falls back to the existing column type. A codec whose parameters depend on the column width therefore resolved to its null-type default during validation, so the reserve check judged the chain by that width instead of the column's. ALTER TABLE t MODIFY COLUMN d CODEC(FPC x150) on a Float64 column resolved FPC(4) and was rejected, while spelling out `d Float64 CODEC(...)` succeeded. Use the same fallback as `apply`, and pin both directions on a type-omitted ALTER: rejected on Float32, accepted on Float64.
The style check requires containers in src/Compression to allocate through AllocatorWithMemoryTracking. The outer vector is sized from the number of substreams of the column type, i.e. from user DDL, so an untracked allocation here is exactly what that rule exists to prevent, and it would be inconsistent with this change reserving a bound on user-driven codec allocations. The element type Codecs is already VectorWithMemoryTracking, so only the outer container was missing it. Style check on 431ac3f: src/Compression/CompressionFactoryAdditions.cpp:130: Use an -WithMemoryTracking alternative or mark these usages with STYLE_CHECK_ALLOW_STD_CONTAINERS
Two conflicts, both from the codec validation refactor on master (per-codec enable settings): validateCodecAndGetPreprocessedAST now takes a CodecValidationSettings instead of the sanity_check / allow_experimental_codecs pair, and its body moved to validateCodecAndGetPreprocessedASTImpl. Resolved by keeping both sides: the chain-length and reserve-overflow checks stay in the sanity_check block of the Impl function, and the ALTER MODIFY COLUMN call site keeps the column type fallback while adopting the new settings parameter. The bound was re-verified on the merged tree rather than assumed: the 150-codec FPC repro now fails with CANNOT_COMPRESS at codec 105 instead of writing past the destination buffer, and the same repro still aborts on a master build without the fix. All 15 call sites of the validation entry points were checked to keep the sanity_check value they passed before the refactor. Master's new enable_<family>_codec gating covers alp, quantized, sz3 and zxc, none of which the test uses.
…flow Fix out-of-bounds write on a long codec chain
Member
|
@groenai Resolve the merge conflicts. |
Collaborator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Original pull-request #113877
Do not merge this PR manually
This pull-request is a first step of an automated backporting.
It contains changes similar to calling
git cherry-picklocally.If you intend to continue backporting the changes, then resolve all conflicts if any.
Otherwise, if you do not want to backport them, then just close this pull-request.
The check results does not matter at this step - you can safely ignore them.
Before you resolve anything
Conflicts are often caused by a prerequisite change that has not been backported yet, rather than by a real divergence. The bot re-tries this cherry-pick against the release branch on every run, so if that is the case here it will merge itself as soon as the prerequisite lands, and you will see a comment saying so. Manual resolution is only needed while the conflict persists.
Troubleshooting
If the conflicts were resolved in a wrong way
If this cherry-pick PR is completely screwed by a wrong conflicts resolution, and you want to recreate it:
pr-cherrypicklabel from the PRYou also need to check the Original pull-request for
pr-backports-createdlabel, and delete if it's presented thereThe PR source
The PR is created in the CI job