Skip to content

Throw TOO_LARGE_STRING_SIZE instead of aborting on a corrupt String size stream - #108572

Closed
groeneai wants to merge 15 commits into
ClickHouse:masterfrom
groeneai:fix-string-size-stream-allocator-abort
Closed

groeneai wants to merge 15 commits into
ClickHouse:masterfrom
groeneai:fix-string-size-stream-allocator-abort

Conversation

@groeneai

Copy link
Copy Markdown
Collaborator

Related: #107196

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):

Fix a server abort when reading a String column stored with the separate size-stream format (WITH_SIZE_STREAM) from a corrupt or truncated part: a garbage per-row length in the .size sub-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 raises TOO_LARGE_STRING_SIZE at the point of deserialization instead.

Description

SerializationString::deserializeBinaryBulkWithSizeStream reads per-row lengths from a separate .size sub-stream, accumulates them into ColumnString offsets, then sizes the character buffer with data.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-read resize reaches Allocator::checkSize (size >= 0x8000000000000000), which throws a LOGICAL_ERROR and aborts under assert/sanitizer builds. Top of the observed stack:

checkSize  src/Common/Allocator.cpp:122  ("Too large size ... passed to allocator")
Allocator<false,false>::realloc
DB::SerializationString::deserializeBinaryBulkWithSizeStream
DB::MergeTreeReaderCompact::readData
...
DB::MergeTreeSource::tryGenerate

The existing readBigStrict hardening (#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 appendStringSizesToColumnStringOffsets and throws TOO_LARGE_STRING_SIZE, mirroring the bound the single-stream path already enforces in deserializeBinaryImpl (max_string_size = 16_GiB).

A unit test WithSizeStreamCorruptSizeStreamThrows was added (symmetric to the existing WithSizeStreamShortDataStreamThrows): it corrupts the first .size entry 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 existing StringSerialization.* unit tests still pass.

…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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Unit test WithSizeStreamCorruptSizeStreamThrows corrupts the first .size UInt64 to 0x8000000000000001; the unfixed binary aborts (SIGABRT, exit 134) in deserializeBinaryBulkWithSizeStream -> Allocator::checkSize every run.
b Root cause explained? Per-row lengths come from a separate .size sub-stream; appendStringSizesToColumnStringOffsets accumulates them with no bound, so bytes_to_read = offsets.back() - prev_last_offset >= 2^63; data.resize(...) reaches Allocator::checkSize (size >= 0x8000000000000000) -> LOGICAL_ERROR -> abort under assert/sanitizer.
c Fix matches root cause? Yes. Bounds the per-row size at the accumulation point (before it can grow bytes_to_read), throwing TOO_LARGE_STRING_SIZE.
d Test intent preserved / new test added? New test added (symmetric to the existing WithSizeStreamShortDataStreamThrows). No existing test weakened; all 4 StringSerialization.* tests pass.
e Demonstrated both directions? Yes. Aborts (exit 134) without the fix; throws TOO_LARGE_STRING_SIZE and the suite passes with the fix.
f Fix is general, not a narrow patch? Yes. Checked siblings: the single-stream path already guards this (deserializeBinaryImpl, 16_GiB); SerializationStringSize resizes by row-count, not by a stream-derived byte value, so it is not vulnerable. This was the only unguarded variable-length-resize-from-stream-value site.
g Generalizes across inputs (params/datatypes/wrappers)? Yes. The guard is per-row and catches both a single bit-63 length and any individual size > 16_GiB; cumulative overflow is bounded away (<= rows * 16_GiB cannot reach 2^63 in one call). Nullable(String) / LowCardinality(String) use the same SerializationString underneath, so the same guard covers them.
h Backward compatible? Yes. Pure hardening. Any legitimately serialized part has per-row sizes far below 16_GiB; the rejected range (> 16_GiB) was always an allocator abort before. No format / setting / default change.
i Invariants and contracts preserved? Yes. On the throw path nothing is committed (exception propagates before offsets/chars are finalized); on the valid path behavior is byte-identical. The offsets.back() == chars.size() consistency invariant is unaffected.

Session id: cron:clickhouse-worker-slot-6:20260626-052400

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @Avogar @Ergus — could you review this? It adds the missing per-row size bound on the WITH_SIZE_STREAM String read path so a corrupt/desynced .size sub-stream throws TOO_LARGE_STRING_SIZE instead of aborting in the allocator. This is the complement to the readBigStrict hardening in #107196 (which covers the data-stream-short desync, after the resize); here the sizes stream is the corrupt one and the abort happens at the pre-read data.resize().

@Ergus Ergus self-assigned this Jun 26, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 26, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [15d33b4]

Summary: ❌

job_name test_name status info comment
Integration tests (amd_llvm_coverage, 6/8) FAIL
test_storage_rabbitmq/test_system_stop.py::test_refresh_runs_once_while_start_keeps_consuming FAIL cidb
Stress test (arm_debug) FAIL
Logical error: Inconsistent KeyCondition behavior (STID: 5182-2f27) FAIL cidb

AI Review

Summary

This PR hardens WITH_SIZE_STREAM String deserialization against corrupt or truncated .size substreams and adds focused gtests around the failure modes. The corruption handling is materially better, but I cannot approve it as-is because the new per-row 16_GiB check changes the read compatibility contract for existing compact parts: the writer still persists larger row lengths, while the new reader now rejects them retroactively.

Findings

❌ Blockers

  • [src/DataTypes/Serializations/SerializationString.cpp:628] The new checkStringSizeFromSizeStream guard makes both SerializationString and SerializationStringSize reject any .size entry above 16_GiB, but serializeStringSizes / serializeBinaryBulkWithSizeStream still write arbitrary UInt64 lengths and the single-stream skip path at SerializationString::deserializeBinaryBulk (rows_offset handling) still allows oversized skipped rows. That means an existing WITH_SIZE_STREAM part containing a legitimate String value larger than 16_GiB becomes unreadable after upgrade, even for reads that start after that row.
    Suggested fix: either enforce the 16_GiB ceiling when writing new parts and gate it through compatibility, or keep the read-side hardening focused on the actual corruption values that cause the allocator abort / overflow (>= 1ULL << 63 and cumulative-overflow cases) so pre-existing parts remain readable.
Final Verdict

Status: ❌ Block

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 26, 2026

@Ergus Ergus left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

The channge looks good to me. The limit is pretty high, so not sure if it could be hit in a realistic use case. @Avogar WDYT?

@nikitamikhaylov nikitamikhaylov added the can be tested Allows running workflows for external contributors label Jun 26, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — c387724

Every failure below has an owner; none is in this PR's diff (SerializationString.cpp, gtest_string_serialization.cpp), so none is PR-caused.

Check / test Reason Owner / fixing PR
Stress test (amd_msan) / refresh scheduling LOGICAL_ERROR (STID 2508-3e7b; the Cannot-start-server + Check-failed rows are downstream of that crash) RefreshTask MULTI_READ NOT_IMPLEMENTED on ATTACH/restore #108441 (ours, fixes STID 2508-3e7b)
Stress test (amd_tsan) / Hung check failed, possible deadlock chronic hung-check deadlock family #101680 / #105905 (ours)
Config Workflow / Pre Hooks transient pre-hook step; Config Workflow re-ran SUCCESS on this head transient infra (self-resolved)
Mergeable Check / PR aggregators reflecting the reds above n/a
CH Inc sync private fork mirror CH Inc sync (not actionable by us)

Session id: cron:our-pr-ci-monitor:20260626-173000

@Ergus

Ergus commented Jul 15, 2026

Copy link
Copy Markdown
Member

@groeneai The performance tests are failing. Some tests are slower and other unstable.

  1. check just in case the performance unstability could be related with the change
  2. Are you sure that it is not possible to substitute the gtest with a simple sql test?
  3. Merge master to get the latest changes before triggering the CI next time

groeneai and others added 2 commits July 15, 2026 18:41
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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

@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 arm_release and the same tests are flagged slower in BOTH ::old (reference/master, which does not contain this change) and ::new runs: like_perfect_affix_rewrite, map_bucketed_serialization, codecs_int_select, tpcds #76, array_reduce, sort_patterns, read_from_comp_parts, optimized_select_final_one_part. ::old being slower on the same machine is the signature of runner instability, not a regression from the diff. None of them exercise the String WITH_SIZE_STREAM read path. The change adds one predictable per-row comparison in appendStringSizesToColumnStringOffsets plus the same in the (typically empty) skipped-prefix loop, so it cannot plausibly move these unrelated queries. The merge + re-run should clear the noise.

2. gtest vs SQL — I looked at converting it. The bug is a specific UInt64 in the compressed .size sub-stream of a MergeTree part having bit 63 set. Reproducing that from SQL means writing a part, then decompressing/patching/recompressing the interleaved .size stream on disk (compact parts interleave substreams, and the exact byte layout is compression- and version-dependent), which is fragile and not portable across builds. The gtest drives deserializeBinaryBulkWithSizeStream directly with the two substreams routed to separate buffers, so it corrupts exactly the untrusted UInt64 deterministically and asserts the throw. This is the behavior-not-observable-from-SQL case, so I kept it as a gtest (extending the existing gtest_string_serialization.cpp, symmetric to WithSizeStreamShortDataStreamThrows). Happy to convert if you know a reliable SQL way to desync the streams.

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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Both size-stream correctness gaps addressed in 3211787.

(i) Short/truncated .size stream: SerializationNumber<UInt64>::deserializeBinaryBulk appends whatever it finds without requiring the full prefix, so num_read_rows < rows_offset + limit could index past sizes_data or silently under-read. Now rejected with CANNOT_READ_ALL_DATA, symmetric to the short data-stream path. New test WithSizeStreamShortSizeStreamThrows (100 sizes for 500 requested).

(ii) Mid-range corrupt size leaving offsets.back() > chars.size(): the whole requested size slice (length and per-row 16 GiB bound) is now validated before any offset is pushed or data.resize() runs, so the throw path leaves the column internally consistent. New test WithSizeStreamMidRangeCorruptSizeLeavesColumnConsistent (corrupt size at index 250, rows_offset 0) asserts both the throw and offsets.back() <= chars.size().

Verified both new tests fail on the pre-fix binary (silent 100/500 rows; offsets.back()=36647 vs chars.size()=0) and pass after; all StringSerialization.* green. Master already merged (a93ef88).

groeneai and others added 2 commits July 16, 2026 00:18
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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Extended the same validation to SerializationStringSize::deserializeBinaryBulkWithSizeStream (the s.size subcolumn reader), pushed bdca9d7.

Before the compaction step it now:

  • rejects a short size stream (num_read_rows < rows_offset + limit -> CANNOT_READ_ALL_DATA), so actual_new_size = size() - rows_offset can no longer underflow (SerializationStringSize.cpp:265) and the loop can no longer walk past data (:266-267); the rows_offset == 0 silent under-read is gone too;
  • applies the same per-row 16 GiB bound (checkStringSizeFromSizeStream) so an oversized .size entry throws TOO_LARGE_STRING_SIZE instead of being exposed as s.size data.

checkStringSizeFromSizeStream moved to DB scope and is declared in SerializationString.h so both readers share one bound.

Regressions (gtest_string_serialization.cpp): StringSizeSubcolumnShortSizeStreamThrows and StringSizeSubcolumnOversizeThrows. Both FAIL on the pre-fix binary (100/500 rows silently; oversized size exposed as data) and PASS after; all StringSerialization.* green. Master merged before push.

groeneai and others added 2 commits July 16, 2026 01:26
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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 6838c33

Every failure below has an owner: a fixing PR (ours), or a full-effort fix task whose
fixing-PR link will be posted here when it opens. Neither failure is caused by this PR
(this PR only touches SerializationString / SerializationStringSize).

Check / test Reason Owner / fixing PR
Integration tests (amd_tsan, 3/6) / test_replicated_database::test_replicated_table_structure_alter flaky (612 FAIL / 317 PRs / 64 master, 30d) #110030 (ours, open)
Stateless tests (amd_tsan, parallel) / 02378_part_log_profile_events flaky (3 FAIL / 3 PRs / 1 master, 30d) a fix task is created (investigating at full effort — fixing-PR link to follow here)

Session id: cron:our-pr-ci-monitor:20260716-060000

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for 02378_part_log_profile_events flaky (amd_tsan): #110640

@Ergus Ergus left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Just a tiny comment

{
prev_offset += sizes[start + i];
const UInt64 size = sizes[start + i];
checkStringSizeFromSizeStream(size);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

the appended rows are bound-checked twice on the hot path?

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.

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]);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

The appended rows are bound-checked twice on the hot path? See?

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.

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).

groeneai and others added 6 commits July 24, 2026 17:30
…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]>
…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]>
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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review trail (Gate B) — click to expand

An independent second-model review pass ran on the size-check-removal change and its follow-ups. Adjudication:

Applied (agreed):

  • SerializationStringSize::deserializeBinaryBulkWithSizeStream lacked the null-stream early-return its String sibling has, so the short-stream CANNOT_READ_ALL_DATA check (added when the s.size reader was hardened) fired on an absent/defaulted .size substream. Added else { pop_back; return; }. New regression StringSizeSubcolumnNullStreamReturnsUnchanged (A/B: fails without the branch with "produced 0 rows but 500 requested", passes with it).
  • The corrupt-size tests wrote host-endian bytes into the little-endian .size stream, so they would not reproduce on a big-endian host. Encode explicitly little-endian; drop the now-unused <cstring>.
  • Trimmed over-long test/code comments; fixed a "crash" that is actually a debug/sanitizer LOGICAL_ERROR abort.

Not applied (disagreed, with reasons):

  • Three "blocker" claims (Regular-substream cache row count, size-column COW/assumeMutable, the 16 GiB reader bound "rejecting writer-persistable values") target the pre-existing WITH_SIZE_STREAM design (introduced in size-separated String serialization for MergeTree #82850), not code this PR added or changed. The 16 GiB bound already ships on the single-stream read path (deserializeBinaryImpl); making the size-stream path symmetric with it is the purpose of this PR.
  • A test-liveness concern on WithSizeStreamConsistentAfterMemoryLimitExceeded: the prior A/B empirically failed on the pre-fix binary (offsets.back()=6000000 vs chars.size()=0), so the injected fault demonstrably reaches the post-append data.resize; the test is live, and forcing determinism risks the flakiness the check guards against.

void checkStringSizeFromSizeStream(UInt64 size)
{
static constexpr size_t max_string_size = 16_GiB;
if (size > max_string_size)

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.

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.

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 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.

@clickhouse-gh

clickhouse-gh Bot commented Jul 24, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.20% 86.20% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 78.40% 78.30% -0.10%

Changed lines: Changed C/C++ lines covered: 292/297 (98.32%) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 15d33b4

CI finished (Finish Workflow green). Both failures are unrelated to this PR, which only touches SerializationString / SerializationStringSize. Each has an owner:

Check Test Reason Owner / fixing PR
Integration tests (amd_llvm_coverage, 6/8) test_storage_rabbitmq/test_system_stop.py::test_refresh_runs_once_while_start_keeps_consuming flaky, pre-existing regression (fails on master + many unrelated PRs; unrelated to string serialization) #111480 (ours, open)
Stress test (arm_debug) Logical error: Inconsistent KeyCondition behavior (STID 5182-2f27) chronic debug-only monotonicity canary (#90461); compiled out in release, zero correctness impact; fires across master + many unrelated PRs diagnostic #108011 (merged), targeted fix #109023 (open)

Session id: cron:our-pr-ci-monitor:20260725-000000

return;
}

/// Validate the requested `.size` slice BEFORE the compaction step, symmetric to the String path

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 Make the code comments 80% shorter.

@rschu1ze rschu1ze left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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 (...)

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.

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.

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.

@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.

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.

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;

@groeneai

Copy link
Copy Markdown
Collaborator Author

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:

  • The 16_GiB per-row bound is not new. The single-stream String path has enforced it since 2023 (SerializationString.cpp:174-181, f331b9b); the WITH_SIZE_STREAM path, default only since 25.11, reads the same lengths from a separate sub-stream without it. The same corrupt part is therefore rejected in one String format and not the other.
  • The behaviour being removed is a process abort, not an ugly error message: the pre-read data.resize() reaches Allocator::checkSize, which raises LOGICAL_ERROR, which calls abortOnFailedAssertion under debug/sanitizer builds.
  • CHECK TABLE cannot reach this code: checkDataPart verifies checksums and never deserializes column values.

I also offered a narrower version (reject only >= 1ULL << 63 and the cumulative-overflow case, dropping the 16_GiB bound), and an alternative to the try/catch that needs no catch at all.

On making the code comments 80% shorter (r3656514248): agreed, and I will do it. I am holding it plus the try/catch change until you rule on the approach, so that everything lands in one push rather than several workflow approvals. If the verdict is that the approach is wrong, I will close this instead.

groeneai added a commit to groeneai/ClickHouse that referenced this pull request Jul 29, 2026

@Ergus Ergus left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Please address @rschu1ze request to reduce the comment.

stream->ignore(bytes_to_skip);
stream->readBigStrict(reinterpret_cast<char *>(&data[chars_size_before]), bytes_to_read);
}
catch (...)

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.

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)

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.

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)

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.

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 Avogar left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Let's probably wait for #110320 and my refactoring #111427.
I don't like these changes at all tbh. And maybe after these 2 PRs we won't need most of these changes.

@groeneai

Copy link
Copy Markdown
Collaborator Author

@Avogar I read both. Overlap with this PR, measured:

Residue after both land: the throw-path consistency guard, and a bound on the s.size reader.

@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:

  1. I hold this PR until Add size-stream String serialization to the Native protocol #110320 and Refactor columns deserialization to avoid all assumeMutable calls, simplify the substreams cache, and remove rows_offset #111427 land, then rebase down to just the residue above; or
  2. I close this and the residue goes into Refactor columns deserialization to avoid all assumeMutable calls, simplify the substreams cache, and remove rows_offset #111427.

@Avogar

Avogar commented Aug 11, 2026

Copy link
Copy Markdown
Member

@groeneai

Two gaps it leaves. The bound runs after appendStringSizesToColumnStringOffsets has already committed offsets, so a throw there still leaves offsets.back() > chars.size(). And it does not touch SerializationStringSize.cpp at all, so the s.size subcolumn reader gets no bound.

  1. In case of an exception on deserialization it's totally ok to keep ColumnString state invalid, it will be just destroyed and not used anywhere.
  2. Size checks in SerializationStringSize are not needed at all, because this serialization reads sizes as UInt64 column that is not used as sizes/offsets anywhere, only as a separate UInt64 column, so bad values there won't lead to any problems. In case we share this column with String deserialization we need to check sizes in String serialization after we got it from cache and converted to offsets. Let me add it to the Add size-stream String serialization to the Native protocol #110320

@groeneai

Copy link
Copy Markdown
Collaborator Author

@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 SerializationStringSize bound goes away per (2). And #111427 removes rows_offset, which deletes the two underflows the short-size-stream check guarded (25 of its removed lines in SerializationStringSize.cpp alone reference it). So this PR is fully subsumed by #110320 plus #111427, and closing it is better than rebasing it down to nothing. I will close it if you confirm, or close it yourself.

@Ergus your four items (the SCOPE_EXIT scope guard, the short-read throw, the cross-reader double bound-check on SELECT s, s.size, and the comment trim) are moot under the same reasoning, so I am not pushing them.

@groeneai groeneai added the groeneai-origin-unknown PR origin: unclassified (legacy task) label Aug 19, 2026
@groeneai

groeneai commented Sep 3, 2026

Copy link
Copy Markdown
Collaborator Author

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:

  • rows_offset no longer appears in either SerializationString.cpp or SerializationStringSize.cpp. The short-size-stream check and the skipped-prefix bound only existed to guard the num_read_rows - rows_offset and size() - rows_offset underflows, and both are deleted.
  • DeserializeBinaryBulkStateStringWithSizeStream is gone and deserializeBinaryBulkWithSizeStream no longer takes a state parameter, so the diff has no context left to apply against.
  • MAX_TOTAL_STRING_SIZE covers the per-row bound, since bytes_to_read is the sum of the row sizes and any single size large enough to reach Allocator::checkSize exceeds it. It covers the shared-cache path too, because the size column taken from the cache is converted to offsets before that check, which was the remaining cross-reader item.
  • The throw-path rollback and the SerializationStringSize bound were both ruled out above.

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 MAX_TOTAL_STRING_SIZE that I am flagging rather than raising: the total is an unchecked UInt64 sum, so two per-row sizes of 1 << 63 add to 0, the check does not fire, and the offsets committed into the column end up non-monotonic against a much smaller chars. Only the on-disk path reaches that arithmetic, since Native reads cumulative offsets and has the monotonicity check instead. I have not produced a part that gets there, as the .size stream is checksummed, so I am not opening anything for it.

@abashkeev abashkeev added the comp-data-types Type system & core datatypes used across query planning/execution. label Sep 4, 2026
@Avogar

Avogar commented Sep 4, 2026

Copy link
Copy Markdown
Member

I think it should be fixed by #115702

@groeneai

groeneai commented Sep 4, 2026

Copy link
Copy Markdown
Collaborator Author

Confirmed for the arithmetic I flagged. I extracted both versions of appendStringSizesToColumnStringOffsets and ran the same size vectors through each: the three wrapping cases ({2^63, 2^63}, {3, 2^63, 2^63, 4}, {2^63, 2^63 + 12}) do not throw on master and all throw with #115702, while the controls behave the same in both ({3, 5, 4} passes, a single 2^63 throws). The 128-bit accumulator is what does it: those sums are 2^64 or more, so the one check of the untruncated total fires, and below that bound every partial sum stays under 2^48 and stores exactly.

It also closes something my note above understated. I pointed at the Native monotonicity check as the guard on that carrier, but on master that scan starts at offsets.begin() + prev_num_rows (SerializationString.cpp:795), so the pair spanning two calls is never compared. The PR starts one element earlier.

#115702 is still open and master is at 323d4264 with the unchecked UInt64 accumulator at :657, so the bound arrives when it merges. Nothing further from me on this PR.

@rschu1ze

rschu1ze commented Sep 7, 2026

Copy link
Copy Markdown
Member

Looks like nothing else needs to be done

@rschu1ze rschu1ze closed this Sep 7, 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 comp-data-types Type system & core datatypes used across query planning/execution. groeneai-origin-unknown PR origin: unclassified (legacy task) pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants