Repository navigation
Conversation
…ize stream
SerializationString::deserializeBinaryBulkWithSizeStream reads per-row
lengths from a separate `.size` sub-stream (WITH_SIZE_STREAM format) and
accumulates them into ColumnString offsets in
appendStringSizesToColumnStringOffsets, then computes
`bytes_to_read = offsets.back() - prev_last_offset` and calls
`data.resize(...)` BEFORE reading any character bytes.
The accumulation had no bound on the per-row size. A corrupt or desynced
sizes sub-stream (the sizes and data streams are stored separately, so a
bad granule / version skew / seek can desync them) can deliver a garbage
length with bit 63 set, making bytes_to_read >= 2^63. The pre-read resize
then reaches Allocator::checkSize, which throws a LOGICAL_ERROR
("Too large size ... passed to allocator") that aborts the server under
assert/sanitizer builds.
The existing readBigStrict hardening (ClickHouse#107196) catches the opposite
desync (data stream short, sizes intact) but runs after the resize, so it
does not help when the sizes stream is the corrupt one.
Bound the per-row size at the accumulation point and throw
TOO_LARGE_STRING_SIZE on a corrupt part, mirroring the bound the
single-stream path already enforces in deserializeBinaryImpl
(max_string_size = 16_GiB). A corrupt part now fails loudly at the point
of deserialization instead of aborting.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-6:20260626-052400 |
|
cc @Avogar @Ergus — could you review this? It adds the missing per-row size bound on the |
|
Workflow [PR], commit [15d33b4] Summary: ❌
AI ReviewSummaryThis PR hardens Findings❌ Blockers
Final VerdictStatus: ❌ Block |
CI finish ledger — c387724Every failure below has an owner; none is in this PR's diff (
Session id: cron:our-pr-ci-monitor:20260626-173000 |
|
@groeneai The performance tests are failing. Some tests are slower and other unstable.
|
…eam-allocator-abort
deserializeBinaryBulkWithSizeStream summed the skipped-prefix sizes into bytes_to_skip before validating them. A corrupt/desynced .size sub-stream with bit-63 lengths could wrap the skip sum (two 1<<63 sizes sum to 0 on 64-bit), so ignore() left the data stream misaligned and the result was read from the wrong byte position instead of throwing. Apply the same 16 GiB per-row bound to the skipped-prefix sizes (shared helper checkStringSizeFromSizeStream) and accumulate bytes_to_skip with checked addition. Add a rows_offset>0 regression. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
@Ergus thanks, addressed all three (pushed a93ef88, merged current master). 1. Perf tests — not related to this change. The failing perf checks are all on 2. gtest vs SQL — I looked at converting it. The bug is a specific 3. Merged master before this push, so CI runs on the latest. |
…STREAM read Two correctness gaps in the size-stream deserialization path: - The .size sub-stream is read with SerializationNumber<UInt64>::deserializeBinaryBulk, which appends whatever it finds without demanding the full requested prefix. A short size stream (num_read_rows < rows_offset + limit) let the skipped-prefix loop index past sizes_data, or silently produced fewer rows than requested. Reject it with CANNOT_READ_ALL_DATA, symmetric to the short data-stream path. - deserializeBinaryBulkWithSizeStream mutates the column directly instead of the generic clone-and-assign path, so a corrupt size in the middle of the requested range threw after committing good offsets, leaving offsets.back() > chars.size(). The entire requested size slice is now validated (length and per-row bound) before any offset is pushed or data.resize runs, so the throw path leaves the column consistent. Adds regressions for a truncated size stream and a mid-range corrupt size. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Both size-stream correctness gaps addressed in 3211787. (i) Short/truncated (ii) Mid-range corrupt size leaving Verified both new tests fail on the pre-fix binary (silent 100/500 rows; |
…eam-allocator-abort
The s.size subcolumn (SerializationStringSize::deserializeBinaryBulkWithSizeStream) reads the same .size substream as SerializationString but lacked the corruption checks added to the String path. A short/truncated stream made actual_new_size = size() - rows_offset underflow and the compaction loop walk past the end of data; with rows_offset == 0 it silently returned fewer s.size rows. Oversized per-row entries were exposed as subcolumn data. Apply the same full-prefix validation (reject num_read_rows < rows_offset + limit with CANNOT_READ_ALL_DATA) and the same per-row 16 GiB bound (checkStringSizeFromSizeStream) before the compaction step. The size-bound helper is moved to DB scope and declared in SerializationString.h so both readers share it. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Extended the same validation to Before the compaction step it now:
Regressions (gtest_string_serialization.cpp): |
After the size slice passes validation, SerializationString::deserializeBinaryBulkWithSizeStream still appends offsets and runs fallible in-place ops (data.resize, ignore, readBigStrict) on the caller-owned column. A fault-injected MEMORY_LIMIT_EXCEEDED from data.resize (assumeMutable does not clone) or a short data stream would leave the committed offsets with the old chars buffer, so offsets.back() > chars.size() reappears on the exception path. Snapshot both buffers and restore them on any throw, mirroring deserializeBinary/deserializeBinaryImpl. Co-Authored-By: Claude Opus 4.8 <[email protected]>
…eam-allocator-abort
CI finish ledger — 6838c33Every failure below has an owner: a fixing PR (ours), or a full-effort fix task whose
Session id: cron:our-pr-ci-monitor:20260716-060000 |
|
Fixing PR for 02378_part_log_profile_events flaky (amd_tsan): #110640 |
| { | ||
| prev_offset += sizes[start + i]; | ||
| const UInt64 size = sizes[start + i]; | ||
| checkStringSizeFromSizeStream(size); |
There was a problem hiding this comment.
the appended rows are bound-checked twice on the hot path?
There was a problem hiding this comment.
Good catch, yes. The pre-validation loop already bound-checks the whole requested slice (skipped prefix + appended rows) before any offset is pushed, so the per-row checkStringSizeFromSizeStream inside appendStringSizesToColumnStringOffsets re-checked the appended rows a second time on the hot path. I removed the duplicate (15d33b4): the helper is file-local with a single caller that always pre-validates, so it now just accumulates offsets and I documented the precondition. The pre-validation loop stays the sole bound check. All StringSerialization.* gtests green; merged master.
| /// wrap the sum and misalign the data stream instead of throwing). | ||
| for (size_t i = prev_size; i != prev_size + num_read_rows; ++i) | ||
| { | ||
| checkStringSizeFromSizeStream(sizes_data[i]); |
There was a problem hiding this comment.
The appended rows are bound-checked twice on the hot path? See?
There was a problem hiding this comment.
This loop is the one that stays: it validates the entire requested slice up front (and sums bytes_to_skip with checked addition on the skipped prefix) before the column is mutated. The duplicate was the per-row check in appendStringSizesToColumnStringOffsets, now removed (15d33b4).
…eam-allocator-abort
…t path deserializeBinaryBulkWithSizeStream already validates the entire requested size slice (skipped prefix + appended rows) with checkStringSizeFromSizeStream before mutating the column, so the per-row check inside appendStringSizesToColumnStringOffsets re-checked the appended rows a second time. The helper is file-local with a single caller that always pre-validates; drop the duplicate branch and document the caller's pre-validation contract. No behavior change: the pre-validation loop is the sole bound check and still rejects corrupt/oversized sizes before any offset is appended. Co-Authored-By: Claude Opus 4.8 <[email protected]>
…eam-allocator-abort
…r; encode corrupt test sizes little-endian
Second-model review follow-up on the size-stream hardening:
- SerializationStringSize::deserializeBinaryBulkWithSizeStream lacked the
null-stream branch its String sibling has, so the CANNOT_READ_ALL_DATA
short-stream check (added when the subcolumn reader was hardened) fired on an
absent/defaulted .size substream (num_read_rows == 0, limit > 0). Add the
else { pop_back; return; } so a null stream returns the column unchanged, the
same way SerializationString::deserializeBinaryBulkWithSizeStream does. New
regression StringSizeSubcolumnNullStreamReturnsUnchanged (fails without the
branch with "produced 0 rows but N requested").
- The corrupt-size tests wrote host-endian bytes into the little-endian .size
stream via memcpy, so on a big-endian host the bit-63 values deserialized as
small numbers and the tests would not throw. Encode them explicitly
little-endian (putSizeLE); drop the now-unused <cstring>.
- Trim two over-long test preambles to test intent.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
…t comment The corrupt-size path aborts in the allocator with a LOGICAL_ERROR under debug/sanitizer builds; it is a handled exception in release, not an abnormal termination, so do not call it a crash. Co-Authored-By: Claude Opus 4.8 <[email protected]>
…eam-allocator-abort
Keep the append-helper precondition and the null-stream branch comments to what the next reader needs at the call site; the rationale is in the commit history. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Internal second-model review trail (Gate B) — click to expandAn independent second-model review pass ran on the size-check-removal change and its follow-ups. Adjudication: Applied (agreed):
Not applied (disagreed, with reasons):
|
| void checkStringSizeFromSizeStream(UInt64 size) | ||
| { | ||
| static constexpr size_t max_string_size = 16_GiB; | ||
| if (size > max_string_size) |
There was a problem hiding this comment.
serializeStringSizes / serializeBinaryBulkWithSizeStream still persist any UInt64 row length, but this helper now makes every WITH_SIZE_STREAM reader reject values above 16_GiB. That is a new backward-incompatibility for existing compact parts: a part that already contains a legitimate String value larger than 16_GiB was readable before this PR and now throws TOO_LARGE_STRING_SIZE on upgrade. The skipped-prefix validation at deserializeBinaryBulkWithSizeStream also means rows_offset reads now fail before the large row is even materialized, while the single-stream skip path at deserializeBinaryBulk:227-233 still just ignores oversized skipped rows.
If 16_GiB is meant to become a real format invariant, it needs to be enforced when writing new parts and gated through compatibility / versioning. Otherwise this read-side hardening should stay focused on the actual corruption values that trigger the allocator abort (>= 1ULL << 63 and cumulative-overflow cases), so old WITH_SIZE_STREAM parts remain readable.
There was a problem hiding this comment.
The 16 GiB read bound is not new here. The default single-stream bulk read path already rejects size > 16_GiB in deserializeBinaryImpl (SerializationString.cpp:174-181), and that check has been on master since 2023-03 (commit f331b9b), long before this PR. with_size_stream only became the default in 25.11 (SettingsChangesHistory.cpp:1418); every part written before that uses single_stream, where a >16 GiB row is already unreadable. So a legitimate >16 GiB String value is not readable on master today via the primary path, and this PR is making the size-stream path symmetric with the existing bound rather than introducing a new limit.
Narrowing the read side to only >= 1ULL << 63 (the allocator abort threshold, Allocator.cpp:125) would make the two read paths disagree and leave the 16 GiB..8 EiB range aborting again. Turning 16 GiB into a real write-side format invariant (enforcing it in serializeStringSizes + versioning) is a separate backward-incompatible change I will not make here without a maintainer asking for it.
On the skip-path asymmetry: it is benign. The single-stream skip loop uses istr.ignore(size) per row (ReadBuffer.h:103), which only advances the buffer position (or hits EOF), never allocates and never accumulates, so an oversized skipped size cannot reach the allocator. The size-stream path instead sums the skipped sizes into a single bytes_to_skip for one ignore(), which is exactly why it needs the per-row bound plus the checked __builtin_add_overflow at SerializationString.cpp:898. Different mechanics, same outcome: both reject a corrupt part. I would rather not add a per-row throw to the 2023 single-stream skip hot path with no reproducer for it.
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 292/297 (98.32%) · Uncovered code |
CI finish ledger - 15d33b4CI finished (Finish Workflow green). Both failures are unrelated to this PR, which only touches
Session id: cron:our-pr-ci-monitor:20260725-000000 |
| return; | ||
| } | ||
|
|
||
| /// Validate the requested `.size` slice BEFORE the compaction step, symmetric to the String path |
rschu1ze
left a comment
There was a problem hiding this comment.
The whole PR is in my view very dubious.
Let me explain why in a more generic way: The database serializes the data in a certain format. During de-serialization it makes the assumption that the loaded data is consistent with the serialization format. There are a million ways in which the persistent data may not conform with the expected format. This PR handles one specific situation gracefully BUT it will still not be sufficient. We are actually in an unknown unknown situation, and the best course of action is to not even try to anticipate what could go wrong during data load.
If we want to sanity-check persisted data, then the table consistency check is the only viable place (CHECK TABLE command).
| stream->ignore(bytes_to_skip); | ||
| stream->readBigStrict(reinterpret_cast<char *>(&data[chars_size_before]), bytes_to_read); | ||
| } | ||
| catch (...) |
There was a problem hiding this comment.
It's a strict rule, sorry: We must not have try/catch in the codebase without a very good reason (e.g. exceptions are thrown out of a destructor). Here, I don't see a very good reason.
There was a problem hiding this comment.
@rschu1ze Thanks for the clear statement of the principle, and I do not disagree with it: the ways a part can violate the format are unbounded, and a read path should not turn into a general sanity checker. Let me put the two facts that made me open this PR, then a concrete narrowing so the choice is yours.
1. This is not a new invariant, it is the missing half of an existing one. The default single-stream String read path has capped the per-row length at 16_GiB since 2023 (deserializeBinaryImpl, SerializationString.cpp:174-181, commit f331b9b, verified ancestor of master). The WITH_SIZE_STREAM variant became the default only in 25.11 and reads the same lengths from a separate .size sub-stream, without that bound. So today the exact same corrupt part is rejected with TOO_LARGE_STRING_SIZE in one String format and not in the other. This PR only makes the newer path agree with the one already shipping.
2. What I am removing is not an ungraceful error, it is server death. data.resize() is called with the accumulated length before any character byte is read, so a length with bit 63 set reaches Allocator::checkSize, which raises LOGICAL_ERROR; LOGICAL_ERROR calls abortOnFailedAssertion under debug_or_sanitizer_build (Exception.cpp:104-110), so the process aborts rather than the query failing.
That second point is also why I do not think CHECK TABLE can cover this case: checkDataPart verifies checksums and never deserializes column values (0 deserializeBinaryBulk calls in the file), so it cannot reach this code at all. A user who does not run it gets a dead server instead of one failed SELECT, and the abort happens before there is any opportunity to go and check the table.
For context, this is the same class of hardening as #107196 (readBigStrict, @Ergus, merged): that check catches the opposite desync (data stream short, sizes intact) but runs after the resize, so it does not help when the sizes stream is the corrupt one. This PR is the missing direction of that same check, which is how I arrived at it rather than by hunting for things to validate.
On the try/catch (r3656522487): understood, and I am declining the bot finding it was added for on your instruction rather than arguing it. I did measure it first rather than guess: with the block removed and rebuilt, WithSizeStreamConsistentAfterMemoryLimitExceeded fails with offsets.back() = 6000000 against chars.size() = 0. It is load-bearing, because the three fallible operations after validation (offsets reserve/push, data.resize, readBigStrict) mutate the caller-owned column in place and assumeMutable does not clone. This file already carries the same construction for the same invariant on the single-stream path (the function-try rollback at SerializationString.cpp:216, added by @azat in f117cfd). If a second one is still unwanted, the alternative without any catch is to compute bytes_to_read and grow chars before appending any offset, so no partial state is reachable. I am happy to do that instead.
The narrowing, if the goal is to keep this minimal: I can drop the 16_GiB bound and reject only the values that actually reach the allocator abort, that is >= 1ULL << 63 plus the cumulative-overflow case. That removes the abort, claims no format invariant, and leaves every part that is readable today readable.
And if you still consider the approach wrong after that, tell me and I will close it. The remaining 16_GiB asymmetry between the two String formats would be worth a separate note in that case, since the two paths currently disagree about the same part. Your call either way.
There was a problem hiding this comment.
I already had a similar issue in another PR. Growing chars before appending any offset is unsafe because it swaps one aborting inconsistency for another.
It can produce the opposite skew, chars.size() > offsets.back(), whenever readBigStrict throws or the offsets reserve throws. But in that case the copy constructor of ColumnString will reject it.
In this case I think that we need a scope guard instead. Something like (untested)
auto & data = mutable_string_column.getChars();
const size_t offsets_size_before = offsets.size();
const size_t chars_size_before = data.size();
bool committed = false;
SCOPE_EXIT({
if (!committed)
{
offsets.resize_assume_reserved(offsets_size_before);
data.resize_assume_reserved(chars_size_before);
}
});
appendStringSizesToColumnStringOffsets(...);
const size_t bytes_to_read = offsets.back() - prev_last_offset;
data.resize(chars_size_before + bytes_to_read);
stream->ignore(bytes_to_skip);
stream->readBigStrict(reinterpret_cast<char *>(&data[chars_size_before]), bytes_to_read);
committed = true;|
On the "whole PR is dubious" point I answered in-thread at #108572 (comment) so the reasoning sits next to the code it concerns. The short version:
I also offered a narrower version (reject only On making the code comments 80% shorter (r3656514248): agreed, and I will do it. I am holding it plus the |
The previous commit cites a CI report URL containing `PR=108572`; the repository instructions ask for the corresponding pull request link to accompany it. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108572&sha=6838c33f876538a34fdd6beb9de4320905ec3236&name_0=PR&name_1=Stateless%20tests%20%28amd_tsan%2C%20parallel%29 Corresponding pull request: ClickHouse#108572
| stream->ignore(bytes_to_skip); | ||
| stream->readBigStrict(reinterpret_cast<char *>(&data[chars_size_before]), bytes_to_read); | ||
| } | ||
| catch (...) |
There was a problem hiding this comment.
I already had a similar issue in another PR. Growing chars before appending any offset is unsafe because it swaps one aborting inconsistency for another.
It can produce the opposite skew, chars.size() > offsets.back(), whenever readBigStrict throws or the offsets reserve throws. But in that case the copy constructor of ColumnString will reject it.
In this case I think that we need a scope guard instead. Something like (untested)
auto & data = mutable_string_column.getChars();
const size_t offsets_size_before = offsets.size();
const size_t chars_size_before = data.size();
bool committed = false;
SCOPE_EXIT({
if (!committed)
{
offsets.resize_assume_reserved(offsets_size_before);
data.resize_assume_reserved(chars_size_before);
}
});
appendStringSizesToColumnStringOffsets(...);
const size_t bytes_to_read = offsets.back() - prev_last_offset;
data.resize(chars_size_before + bytes_to_read);
stream->ignore(bytes_to_skip);
stream->readBigStrict(reinterpret_cast<char *>(&data[chars_size_before]), bytes_to_read);
committed = true;| /// rows_offset`, and with `rows_offset == 0` we would silently deserialize fewer rows than | ||
| /// requested instead of rejecting the corrupt part. Reject it loudly, symmetric to the short | ||
| /// data-stream path (`readBigStrict` -> CANNOT_READ_ALL_DATA). | ||
| if (num_read_rows < rows_offset + limit) |
There was a problem hiding this comment.
IIUC the limit is intended to be used as "read up to this many rows"instead of "read exactly this many", but this treats "got fewer than limit" as corruption and throws. So it turns a legal outcome into an error.
| /// values are the last `num_read_rows` entries of `column`. | ||
| { | ||
| const auto & size_data = assert_cast<const ColumnUInt64 &>(*column).getData(); | ||
| for (size_t i = size_data.size() - num_read_rows; i != size_data.size(); ++i) |
There was a problem hiding this comment.
My precious double-check objection is back. With both s and s.size in one query, every .size value is bound-checked twice on the hot path.
|
@Avogar I read both. Overlap with this PR, measured:
Residue after both land: the throw-path consistency guard, and a bound on the @Ergus asked for four changes 45 minutes before your review (scope guard, the short-read throw, the cross-reader double check, comment trim). I have not pushed them. Which would you prefer:
|
|
|
@Avogar Understood on both, and thanks for taking the cache-path check into #110320. That leaves nothing here. The throw-path consistency guard was the last item not already covered elsewhere, and per (1) it is not a concern. The @Ergus your four items (the |
|
Both gating PRs have landed (#110320 on 2026-08-19, #111427 on 2026-08-26), so I re-measured this diff against merged master instead of carrying over the July analysis. Nothing in it survives:
Rebasing down to the residue leaves a zero-line diff, so this should be closed. I am leaving the close to you rather than doing it myself, since you are tracking the PR. One measured note on |
|
I think it should be fixed by #115702 |
|
Confirmed for the arithmetic I flagged. I extracted both versions of It also closes something my note above understated. I pointed at the #115702 is still open and master is at |
|
Looks like nothing else needs to be done |
Related: #107196
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix a server abort when reading a
Stringcolumn stored with the separate size-stream format (WITH_SIZE_STREAM) from a corrupt or truncated part: a garbage per-row length in the.sizesub-stream could trigger an out-of-bounds allocation (Too large size ... passed to allocator) and abort the server under assert/sanitizer builds. Such a corrupt part now raisesTOO_LARGE_STRING_SIZEat the point of deserialization instead.Description
SerializationString::deserializeBinaryBulkWithSizeStreamreads per-row lengths from a separate.sizesub-stream, accumulates them intoColumnStringoffsets, then sizes the character buffer withdata.resize(...)before reading any character bytes. The accumulation had no bound on the per-row size.The size and data sub-streams are stored separately, so a corrupt part (or a desynced/seeked sizes stream) can deliver a garbage length with bit 63 set, making
bytes_to_read >= 2^63. The pre-readresizereachesAllocator::checkSize(size >= 0x8000000000000000), which throws aLOGICAL_ERRORand aborts under assert/sanitizer builds. Top of the observed stack:The existing
readBigStricthardening (#107196) catches the opposite desync (data stream short, sizes intact) but runs after the resize, so it does not help when the sizes stream is the corrupt one.The fix bounds the per-row size at the accumulation point in
appendStringSizesToColumnStringOffsetsand throwsTOO_LARGE_STRING_SIZE, mirroring the bound the single-stream path already enforces indeserializeBinaryImpl(max_string_size = 16_GiB).A unit test
WithSizeStreamCorruptSizeStreamThrowswas added (symmetric to the existingWithSizeStreamShortDataStreamThrows): it corrupts the first.sizeentry with a bit-63 length and asserts the deserializer throws instead of aborting. Verified the test aborts (SIGABRT) on the unfixed code and passes with the fix; all existingStringSerialization.*unit tests still pass.