Skip to content

Fix integer overflow in String deserialization - #115702

Merged
Avogar merged 19 commits into
masterfrom
fix-string-deserialization-overflow
Sep 4, 2026
Merged

Avogar merged 19 commits into
masterfrom
fix-string-deserialization-overflow

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 21, 2026 •

Copy link
Copy Markdown
Member

The size of a string is read from the data in two places where adding it to the current size of the
column can overflow:

  • SerializationString::deserializeBinary (the single-value path used by RowBinary and the other
    binary formats) had no upper bound of its own; the limit was only the format_binary_max_string_size
    setting, which is documented to be disabled when it is set to 0. With it disabled, a size close
    to 2^64 wrapped the offset around, the column was resized to the wrapped value and the data was
    then copied past the end of it.
  • appendStringSizesToColumnStringOffsets (the path that reads the sizes of the strings from a
    separate stream) accumulated the sizes without checking them, and the offsets could wrap around
    as well, after which the spans computed from them pointed outside the data of the column.

The single-value path now rejects a size above SerializationString::MAX_STRING_SIZE, the hard limit
that is always enforced, next to the user-facing setting that can be disabled. The size stream
accumulates in unsigned __int128, which cannot wrap, and the total is checked once against
MAX_TOTAL_STRING_SIZE: below that bound every offset it wrote is exact. The other layout of the
size stream, the cumulative byte offsets that Native carries, is checked for monotonicity the way
SerializationArray checks its own offsets, and its total is bounded by the same limit in the caller,
so both carriers end up enforcing one and the same invariant.

SerializationDynamic::deserializeBinary recurses into itself, driven by the type tags in the data,
with nothing but the size of the input bounding the depth, so it now checks the stack size the way the
rest of the recursive code in ClickHouse does. The containers it can recurse through do not need a
check of their own: a deeply nested type has to be decoded before any value of it can be read, and
decodeDataTypeImpl checks the stack while decoding it.

Changelog category (leave one):

  • Critical Bug Fix (crash, data loss, RBAC)

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

Fix an integer overflow in the deserialization of String values in the binary formats, and bound the recursion of the binary deserialization of Dynamic and JSON values.


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

Version info

  • Merged into: 26.9.1.702 (included in 26.9 and later)
  • Backported to: 26.8.3.41, 26.7.7.30, 26.6.5.55, 26.3.32.8

@clickhouse-gh

clickhouse-gh Bot commented Aug 21, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [7e5309e]

Summary: ❌

job_name test_name status info comment
Stress test (amd_tsan) FAIL
Logical error: Got read request from replica A for unknown stream B. (STID: 5217-505b) FAIL cidb, issue ISSUE CREATED

AI Review

Summary

This PR hardens several binary String / Dynamic / JSON deserialization paths, but the final simplification also drops the hard per-string MAX_STRING_SIZE check from the WITH_SIZE_STREAM readers. That leaves malformed multi-stream String input able to request a 16 GiB+ single-string allocation on the size-stream and Native carriers, so I would still request changes.

PR Metadata

Changelog category is correct for the integer-overflow and recursion-hardening work. Changelog entry is required, but it is no longer accurate: the current branch does not reject duplicate flattened-Dynamic types anymore, because that hunk was removed in favor of still-open #117765. Suggested replacement:

Fix integer overflows in binary String deserialization and bound the recursion of binary Dynamic and JSON deserialization.

Findings

⚠️ Majors

  • [src/DataTypes/Serializations/SerializationString.cpp:666-888] The WITH_SIZE_STREAM readers no longer enforce SerializationString::MAX_STRING_SIZE on either carrier. On the position-independent path, appendStringSizesToColumnStringOffsets only checks the accumulated total after pushing all offsets; on the Native path, deserializeStringOffsetsAndGetDataSize only checks monotonicity and the total byte count. A one-row payload with size = MAX_STRING_SIZE + 1 is still below MAX_TOTAL_STRING_SIZE, so the code proceeds to data.resize(initial_size + bytes_to_read) instead of failing fast with TOO_LARGE_STRING_SIZE like the single-value and single-stream bulk paths. That breaks the “hard limit always enforced” contract and lets malformed input drive a huge allocation from one declared string.
    Suggested fix: restore a per-string MAX_STRING_SIZE check on both the per-row sizes stream and the cumulative-offset Native stream before appending/publishing offsets.
  • [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/115702#discussion_r3914959634] The dismissal says this only changes which corruption error is reported, but on the current code the single oversized string is not rejected at the size/offset stage at all; it reaches data.resize(...), so this is a real behavior and resource-usage gap, not just different wording.
Tests
  • ⚠️ The current regression coverage no longer proves the promised hard cap on the multi-stream readers. StringSerialization.WithSizeStreamHugeSizeIsRejected and OffsetsStreamHugeSizeIsRejected now only cover MAX_TOTAL_STRING_SIZE / monotonicity cases, and NativeStringSizeStream.CorruptedOffsetStream dropped the MAX_STRING_SIZE + 1 payload entirely. Please keep one focused MAX_STRING_SIZE + 1 rejection on each carrier and assert TOO_LARGE_STRING_SIZE.
Final Verdict

Status: ⚠️ Request changes

Minimum required actions:

  • Restore MAX_STRING_SIZE enforcement for both WITH_SIZE_STREAM carriers and cover it with focused regressions.
  • Update the changelog entry so it matches the current scope of the PR.

LLVM Coverage Report

Measured on commit 7e5309e.

Metric Baseline Current Δ
Lines 88.70% 88.70% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 81.00% 81.00% +0.00%

Changed lines: Changed C/C++ lines covered: 112/113 (99.12%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added pr-critical-bugfix pr-must-backport Pull request should be backported intentionally. Use this label with great care! labels Aug 21, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 21, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

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

✅ No significant changes.

Binary sizes

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

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

Compile time of recompiled translation units

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

Job report

…n every deserialization path

`SerializationString::deserializeBinary` for a `Field` had no hard upper bound of its own, and that
path is reachable for the values of the paths that go into the shared data of a `JSON` column, so a
malformed nested string could still be passed to `std::string::resize` when
`format_binary_max_string_size` is disabled. Both overloads now share `checkStringSize`, which
enforces the setting and `SerializationString::MAX_STRING_SIZE`.

`SerializationDynamic::deserializeBinary` and `SerializationObject::deserializeBinary` for a column
also recurse into each other on the main column-building path of `RowBinary` and `Native`, so the
`checkStackSize` call is now made there as well and not only in the `Field` overloads.
@Avogar Avogar self-assigned this Aug 24, 2026
Avogar and others added 4 commits August 24, 2026 14:01
…e redundant stack checks

The list of types of a flattened `Dynamic` column is now checked for duplicates while it is read,
instead of in a second pass over the list, and a test for a list with a duplicate type is added.

`SerializationObject::deserializeBinary` does not recurse into itself: every nested value goes
through `SerializationDynamic::deserializeBinary`, the only place where the type of a nested value
comes from the data. So the check of the stack size there bounds the whole mutual recursion, and the
checks in `SerializationObject` are removed.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
… a per-row cost

The skipped prefix of a seeked read (`rows_offset > 0`) summed the sizes from the sizes stream
into `bytes_to_skip` without any check, so a corrupted stream could wrap the sum around and make
the read start from a wrong byte boundary in the data stream instead of rejecting the part. The
prefix now goes through the same validation as the sizes of the materialized rows, and both cases
are covered by unit tests over hand-crafted sizes streams.

The per-row checks that the previous commits added to `appendStringSizesToColumnStringOffsets`
slowed reading of short strings down by 15-55%
(https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=115702&sha=5ba92a1a90a0c126424a7d9c8fbcb2f82c750c25&name_0=PR,
https://performance.ci.clickhouse.com/runs?q=115702), because the accumulation of the offsets is
one of the hot loops of reading a `String` column. The loop now OR-folds the sizes into a single
value that bounds each of them from above and checks it once per chunk sized so that a chunk of
validated sizes cannot wrap `UInt64`; in the astronomically rare case when the OR exceeds the
limit (which can also combine the bits of legitimate sizes), the accumulation is rolled back and
redone with the exact per-size validation. In a microbenchmark the OR-folding loop matches the
unchecked one (0.63 ns/row), while the per-row-checked one takes 0.94 ns/row.
…ization-overflow

# Conflicts:
#	src/DataTypes/Serializations/SerializationString.cpp
…lization

A typed path of a `JSON` type recurses back into `SerializationObject::deserializeBinary`
directly, without passing through `SerializationDynamic`, and the nesting depth of such a type
comes from the data (the binary encoding of a `Dynamic` value starts with the encoding of its
type). So the stack size checks in `SerializationObject::deserializeBinary` were not redundant
after all: they are restored, and `05033_row_binary_huge_string_size` now covers a
`Dynamic` value with a deeply nested typed-path `JSON` type, which has to be rejected with
`TOO_DEEP_RECURSION` instead of exhausting the stack.

Also adapt the new tests to the current master: `rows_offset` was removed from the
deserialization API in #115731, which makes the skipped-prefix validation and its unit test moot.

https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=115702&sha=latest&name_0=PR

Co-Authored-By: Claude Fable 5 <[email protected]>
offsets.reserve(offsets.size() + rows);

for (size_t i = 0; i < rows; ++i)
/// The sizes come from a separate stream, so they are not implicitly bounded by the amount of data

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This only hardens the position-independent size stream. The position_independent_encoding = false branch in deserializeStringOffsetsAndGetDataSize is still the Native/absolute-offset carrier (src/Formats/NativeReader.cpp sets it at false), and that branch only checks that the cumulative offsets are monotonic. A payload with one offset of SerializationString::MAX_STRING_SIZE + 1 is monotonic, keeps bytes_to_read well below MAX_TOTAL_STRING_SIZE, and still makes the reader materialize an oversized single string, so the new hard cap is still bypassable on Native input.

Could we validate the per-row deltas on the absolute-offset path too (or otherwise compare consecutive offsets against MAX_STRING_SIZE) and add a focused NativeStringSizeStream regression for that case?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

🕵 Right, the cumulative offsets that Native carries were only checked for monotonicity. Fixed in 60a826a: the difference between two consecutive offsets is the size of a string, so it is checked against MAX_STRING_SIZE there as well, which also subsumes the monotonicity check (the difference of a non-monotonic pair wraps around and lands far above the limit). The difference between the last offset already in the column and the first one of the stream is now covered too - it was outside the range that std::adjacent_find scanned. StringSerialization.OffsetsStreamHugeSizeIsRejected covers the position_independent_encoding = false path with a single offset of MAX_STRING_SIZE + 1, a huge difference in the middle of the stream, and the non-monotonic case.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This looks reintroduced on the current head. deserializeStringOffsetsAndGetDataSize now only checks that the cumulative offsets are monotonic at src/DataTypes/Serializations/SerializationString.cpp:813-826, and appendStringSizesToColumnStringOffsets only checks the total column size at src/DataTypes/Serializations/SerializationString.cpp:672-687. A Native offsets stream like [SerializationString::MAX_STRING_SIZE + 1] is still monotonic and stays well below MAX_TOTAL_STRING_SIZE, so deserializeBinaryBulkWithSizeStream reaches data.resize(...) at src/DataTypes/Serializations/SerializationString.cpp:887-893 instead of rejecting the single oversized string with TOO_LARGE_STRING_SIZE.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

🕵 This is not a reintroduction — it is the state that @Avogar deliberately established in e534e8e7de22 and 2fcfc07be4a6, and I agree with it (see his comment #115702 (comment) and my reply above).

Both streams now enforce one invariant instead of two overlapping ones: the total size of the batch is bounded by MAX_TOTAL_STRING_SIZE, and the offsets are monotonic, so no offset can address memory outside the block that the bound already allows. The sizes stream accumulates in unsigned __int128, so the sum cannot wrap and one check of the total is exact; the Native offsets stream carries the cumulative offsets directly, so std::adjacent_find for monotonicity plus the same total check in deserializeBinaryBulkWithSizeStream gives the same guarantee — exactly the way SerializationArray validates its offsets.

The per-difference MAX_STRING_SIZE check that this thread asks to restore does not add safety on top of that: with a bounded total, a single string is bounded too. It only changes which error code a corrupted stream produces (TOO_LARGE_STRING_SIZE instead of INCORRECT_DATA) and costs a comparison per row on every Native and every wide-part read; the measurement in the comment linked above puts the per-element variant at 0.47 ns/row against 0.33 for the checked bulk form and 0.30 for the unchecked one.

The overflow this pull request fixes — a sizes stream whose sum wraps the 64-bit offsets and yields a bytes_to_read far smaller than the offsets the column ends up carrying — is what the 128-bit accumulation and the total check close, and 05060_row_binary_huge_string_size covers it.

`deserializeStringOffsetsAndGetDataSize` reads the size stream in two layouts. The
`position_independent_encoding` one carries per-row sizes and now rejects a size above
`SerializationString::MAX_STRING_SIZE`, but the other one - the cumulative byte offsets
that `Native` carries (`NativeReader` sets `position_independent_encoding` to `false`) -
only checked that the offsets increase monotonically. A monotonically increasing stream
can still put a single string above the limit while the total stays below the limit on
the size of the whole column, so the hard cap was bypassable there.

The difference between two consecutive offsets is the size of a string, so it is checked
against the same limit, which also subsumes the monotonicity check: the difference of a
non-monotonic pair wraps around and lands far above it. The difference between the last
offset of the column and the first one of the stream is now covered as well; it was
outside the range that `std::adjacent_find` scanned.
…the containers

The type of a `Dynamic` value comes from the data, and after `decodeDataType` returns it
the value is read by `field_type->getDefaultSerialization()->deserializeBinary(...)`,
which recurses through `SerializationArray`, `SerializationTuple` and `SerializationMap`
for a nested container type. Those did not check the stack, so the guard added to
`SerializationDynamic` and `SerializationObject` only covered the types that pass through
`Dynamic` or `JSON` again.

In practice the depth was already bounded: `decodeDataTypeImpl` and
`IDataType::getDefaultSerialization` check the stack on the way in, and their frames are
larger than the ones of the value deserialization, so they throw first. That is a property
of the generated code rather than of the contract, so the containers now check the stack
themselves. The check is a thread-local load and two comparisons, once per container value.
…offsets validation

The offsets of a `String` column in the `Native` format are now validated not only for
monotonicity but also for the size of every string being within `MAX_STRING_SIZE`, so the
corrupted pair `[0xfffffffffffffff0, 0x20]` of the test is rejected with
`TOO_LARGE_STRING_SIZE` on the very first offset, before the pair is found to be
non-monotonic. Split the test into three payloads so that both rejections stay covered:
a non-monotonic pair, an offset far past the data, and a monotonic pair whose difference
is above the limit.
…formed size stream is rejected

The new validation appends offsets to the destination column before the batch is known to
be valid, so a rejection could leave `offsets.back() > chars.size()` behind for a caller that
catches the exception and reuses the column. Add a rollback guard in
`deserializeBinaryBulkWithSizeStream` that restores both `offsets` and `chars` to their
pre-call sizes on every exception path, and a gtest for it.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: Integration tests (amd_asan_ubsan, db disk, old analyzer, 6/6) — test_parallel_replicas_custom_key_load_balancing/test.py::test_parallel_replicas_custom_key_load_balancing[custom_key_range-key-0] timed out in https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=115702&sha=803db3933616e73276294b575eb91c7978613c54&name_0=PR&name_1=Integration%20tests%20%28amd_asan_ubsan%2C%20db%20disk%2C%20old%20analyzer%2C%206%2F6%29 and provide a fix in a separate PR. If the fix is already in progress, link it here.

This is unrelated to this pull request, which only touches binary String / Dynamic / JSON deserialization: the same test also timed out on unrelated pull requests #115981 and #113650 on 2026-08-29, and there is no open issue for it.

The other red, Upgrade check (amd_release) (Unknown elements 'enable_silk_runtime', 'silk' found in config), is fixed by the already merged #117172 and is cleared by the master merge just pushed.

@groeneai

groeneai commented Sep 1, 2026

Copy link
Copy Markdown
Collaborator

This is a memcg OOM kill of the test's own server, not a parallel replicas defect.

From that job's logs.tar.gz and docker-in-docker.log.zst:

  • n1 was SIGKILLed mid-test. The module's docker.log has /integration-tests-entrypoint.sh: line 26: 8 Killed "$@", Server exited with 137 and n1-1 exited with code 137, all of it ahead of the fixture teardown that then stops n2, n3 and n4 with Server exited with 0. n1's own log ends at 17:02:26.071 on an ordinary Logout line: no shutdown, no <Fatal>, no sanitizer report.
  • docker-in-docker.log has exactly one memcg OOM notification window in the whole job, 17:01:48.861 to 17:02:26.251. Its last event is 180 ms after n1's last log line.
  • The test was 14 s into its call phase by then. Its next query opened a fresh client connection about 1.4 s later and hit the 10 s connect bound at 17:02:37.65. The container had exited with the server, which is why this reads Code: 209 SOCKET_TIMEOUT rather than the Code: 210 the same kill gives when the container outlives its server.
  • The victim was small: the three surviving servers held about 2.4 GiB RSS each (ps aux in the same docker.log), so no per-container limit was anywhere near. The breach is above the container.
  • The retry of the same test alone on the same runner passed in 181 s.

So this is the /docker leaf condition your #117411 and #117412 address, in its test-failure form: the OOM victim was a clickhouse server rather than the shutdown gdb, so it costs a test instead of the job's signal. I am not opening a separate PR for it. Widening the 10 s connect bound for this suite would hide the kill.

Which cgroup breached is not recoverable from this run: 803db393 predates #117104 and #117199, so the kernel record was still a post-hoc snapshot of a wrapped buffer and named nothing. Your current head is past both, so a recurrence there will name it.

Breadth: 3 hits in 30 days, all on old analyzer, 6/6, against 31136 passing rows for this module on true master and none failing. On that shard the same kill hits test_s3_plain_rewritable 76 times in 7 days.

Your reading of the Upgrade check (amd_release) red matches mine.

Avogar and others added 2 commits September 2, 2026 13:26
…ding and the rollback

`appendStringSizesToColumnStringOffsets` accumulates the offsets in 128 bits, which cannot overflow,
so the total is checked once at the end instead of bounding every size on the way. Below a total
within `MAX_TOTAL_STRING_SIZE` every offset is exact, so a valid stream is accumulated exactly as
before. This replaces the chunked OR-folding of the sizes and the rollback that redid the
accumulation with the exact per-size validation, at the same speed: on short strings the loop takes
0.33 ns/row against 0.33 ns/row for the OR-folded one and 0.30 ns/row for the unchecked one, while
the per-size validation takes 0.47 ns/row.

The `Native` path, which carries cumulative offsets instead of sizes, checks that they increase
monotonically with `std::adjacent_find`, the way `SerializationArray` does. The total of a monotonic
stream of offsets is already checked by the caller, so the sizes it describes are bounded as well and
the OR-folding of the differences is not needed there either.

`ColumnStringRollbackGuard` is removed: `deserializeBinaryBulk*` does not restore the destination
column, a caller that needs it intact uses `ColumnCheckpoint`.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…rom the data

A type that nests deeply has to be decoded before any value of it is read, and `decodeDataTypeImpl`
checks the stack while decoding it, so the guards in `SerializationArray`, `SerializationTuple`,
`SerializationMap` and `SerializationObject` cannot be reached: the decoding throws first. They are
removed, together with their cost of a thread-local load and two comparisons per container value.

`SerializationDynamic::deserializeBinary` keeps its check. There the depth comes from the number of
values rather than from one deep type: every nested value carries its own type tag, so nothing bounds
the recursion but the size of the input.

The tests of the two recursion cases are unchanged and still pass: the deeply nested `JSON` value is
rejected by the check in `SerializationDynamic`, and the deeply nested type of a typed path by the
one in `decodeDataTypeImpl`, both with `TOO_DEEP_RECURSION`.

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

Avogar commented Sep 2, 2026

Copy link
Copy Markdown
Member

I pushed two commits that simplify the validation added in the last rounds.

My concern was that each round added a new mechanism on top of the previous one, and the result
was no longer reviewable: chunked OR-folding, a rollback that redid the accumulation, a second
copy of the OR trick for the offsets, and a rollback guard class — all for one integer overflow.

Sizes stream

The accumulation now runs in unsigned __int128 and the total is checked once at the end against
MAX_TOTAL_STRING_SIZE.

A 128-bit accumulator cannot overflow, and below a total within the limit every offset is exact,
so a valid stream is accumulated exactly as before. The chunk loop, the suspicious flag, the
rollback-and-redo, accumulateCheckedStringSize and the arithmeticOverflow.h include are gone.

This is not a performance concession. I measured the loop for short strings, and the 128-bit
accumulator matches the OR fold (ns per row):

variant 65536 rows 8192 rows
unchecked (master) 0.30 0.29
128-bit accumulator 0.33 0.35
OR-folded 0.33 0.36
per-element check + addOverflow 0.47 0.46

The per-element check really does cost what the earlier report showed, so the OR fold was the
right instinct — it just does not need the chunking or the rollback around it.

Offsets stream (Native)

Monotonicity is checked with std::adjacent_find, the same way SerializationArray does it.

The per-difference MAX_STRING_SIZE check is dropped: the caller already rejects a total above
MAX_TOTAL_STRING_SIZE, and monotonic offsets with a bounded total have bounded differences by
construction. Both streams now enforce the same invariant, which also makes them reviewable side
by side.

ColumnStringRollbackGuard

Removed. deserializeBinaryBulk* should not care about rollbacks: on an exception the contents of
the column are not used, and a caller that needs the column intact uses ColumnCheckpoint.

Recursion guards

Kept only in SerializationDynamic::deserializeBinary, removed from SerializationArray,
SerializationTuple, SerializationMap and SerializationObject.

As the commit message of 0b9a5fe conceded, those four cannot be reached: a deeply nested type has
to be decoded before any value of it is read, and decodeDataTypeImpl checks the stack while
decoding it, so it throws first. Paying a thread-local load and two comparisons per container
value on every RowBinary and Native read for an unreachable check is not a good trade.

Dynamic is different and keeps its check. There the depth comes from the number of values, each
carrying its own type tag, so nothing bounds the recursion but the size of the input.

Note that the test added for the typed-path guard cannot distinguish the two cases: the
10000-deep encoded type makes decodeDataTypeImpl hit its own stack check, which raises the same
TOO_DEEP_RECURSION. It passes with and without the guards. I verified that both recursion cases
still fail as expected.


If I got something wrong here, or you disagree with any of it, please feel free to fix it on top —
or simply revert my commits.

Merged via the queue into master with commit 2552273 Sep 4, 2026
172 of 174 checks passed
@Avogar
Avogar deleted the fix-string-deserialization-overflow branch September 4, 2026 18:05
@robot-clickhouse robot-clickhouse added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Sep 4, 2026
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 4, 2026
clickhouse-gh Bot added a commit that referenced this pull request Sep 4, 2026
Backport #115702 to 26.8: Fix integer overflow in String deserialization
alexey-milovidov added a commit that referenced this pull request Sep 5, 2026
Resolve the cherry-pick conflicts of #115702 for 26.6:
- `SerializationString.cpp`: 26.6 has no offsets-stream carrier and no
  `MAX_TOTAL_STRING_SIZE` constant, so the constant is introduced here and
  the `deserializeStringOffsetsAndGetDataSize` hunk is dropped; the
  `checkStringSize` helper and the 128-bit accumulator in
  `appendStringSizesToColumnStringOffsets` are ported as is.
- `SerializationDynamic.cpp`: the `checkStackSize` guards are added around
  the 26.6 `decodeDataType(istr)` calls.
- `gtest_string_serialization.cpp`: the `OffsetsStreamHugeSizeIsRejected`
  test is dropped (no offsets stream on 26.6).
- `gtest_native_string_size_stream.cpp` does not exist on 26.6; its hunk is
  dropped.
alexey-milovidov added a commit that referenced this pull request Sep 5, 2026
Resolve the conflicts of the cherry-pick of #115702 against 26.3:
- `SerializationDynamic.cpp`: keep the 26.3 `decodeDataType(istr)` call and add the `checkStackSize` guards.
- `SerializationString.cpp`: 26.3 has no `MAX_TOTAL_STRING_SIZE` and no Native offsets stream
  (`deserializeStringOffsetsAndGetDataSize`), so add the constant, the `checkStringSize` helper and
  the 128-bit accumulator in `appendStringSizesToColumnStringOffsets`; the offsets-stream hunk does not apply.
- `gtest_string_serialization.cpp`: port `WithSizeStreamHugeSizeIsRejected` to the 26.3 signatures
  (`ColumnPtr &`, `rows_offset`), drop the offsets-stream test.
- `src/Formats/tests/gtest_native_string_size_stream.cpp` does not exist on 26.3: dropped.
alexey-milovidov added a commit that referenced this pull request Sep 5, 2026
Resolve the conflicts of the cherry-pick of #115702 against 26.7:

- `SerializationString.cpp`: 26.7 has no cumulative-offsets carrier for the
  size stream (`deserializeStringOffsetsAndGetDataSize` does not exist there)
  and no `MAX_TOTAL_STRING_SIZE` constant yet, so the constant is added, the
  `checkStringSize` helper and the 128-bit accumulator in
  `appendStringSizesToColumnStringOffsets` are applied on top of the 26.7 code,
  and the monotonicity hunk for the offsets stream is dropped. 26.7 still has
  `rows_offset`, so the sum of the skipped prefix is bounded the same way.
- `gtest_string_serialization.cpp`: adapted to the `rows_offset` signature,
  the offsets-stream test is dropped, and a test for the skipped prefix is added.
- `gtest_native_string_size_stream.cpp` does not exist on 26.7; the hunk is dropped.
robot-clickhouse-ci-2 added a commit that referenced this pull request Sep 5, 2026
Cherry pick #115702 to 26.3: Fix integer overflow in String deserialization
robot-clickhouse-ci-2 added a commit that referenced this pull request Sep 5, 2026
Cherry pick #115702 to 26.6: Fix integer overflow in String deserialization
robot-clickhouse-ci-2 added a commit that referenced this pull request Sep 5, 2026
Cherry pick #115702 to 26.7: Fix integer overflow in String deserialization
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Sep 5, 2026
clickhouse-gh Bot added a commit that referenced this pull request Sep 5, 2026
Backport #115702 to 26.7: Fix integer overflow in String deserialization
alexey-milovidov added a commit that referenced this pull request Sep 5, 2026
Backport #115702 to 26.3: Fix integer overflow in String deserialization
clickhouse-gh Bot added a commit that referenced this pull request Sep 5, 2026
Backport #115702 to 26.6: Fix integer overflow in String deserialization
pull Bot pushed a commit to Lobinson1/ClickHouse that referenced this pull request Sep 11, 2026
`result_column_stats` is an `unordered_map`, so serializing it in iteration order made the bytes of one
plan vary between runs. It is emitted sorted by column name now, which is also the order the Cascades
identity encoding of the same members uses.

The local in `deserialize` is renamed to `step`, matching the two other open pull requests that add a
field to that function, so resolving the overlap between them is a one-line pick.

The header comment above these members read "Runtime info, do not serialize", which stopped being true
for them. It now describes the group it still applies to, and the note in `serialize` states the
property the new block exists for.

That note also drops a claim from the previous commit's message: `right_hash_table_cache_key` is not the
output of the plan cache key hashing. A `JoinStepLogical`'s contribution to a cache key is computed by
`calculateJoinStepCacheKeyContribution`, never by its `serialize`. The block is still left out of a cache
key, for the other reason given there: `optimized` and the estimates differ between the single-node and
the parallel-replicas plan build, and those two builds have to hash alike.

Both tests pin the randomized settings their case depends on. Four settings each independently remove the
divergence and the test runner draws two of them half the time, so without the pins the new case in
`04649_pr_plan_based_join_distributed` would have been vacuous on roughly three CI runs in four.
`04511_cascades_replicated_subplan_join` pins `use_hash_table_stats_for_join_reordering`: it is a full
pinned-text `EXPLAIN PLAN` that pins every other plan-shaping randomized setting, and join reordering
otherwise takes a leaf row estimate from the process-global hash table statistics, which any join that ran
earlier in the same server fills in. That already fails it one run in five on master under concurrency;
with the pin it passes five of five on master and five of five with this change, and its reference file is
unchanged.

CI report:
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=115702&sha=7e5309e6c513d335a722af6a869b2945818a27a7&name_0=PR&name_1=Stress%20test%20%28amd_tsan%29
Seen on ClickHouse#115702
Related: ClickHouse#110518

Co-Authored-By: Claude Opus 5 <[email protected]>
alexey-milovidov pushed a commit to amosbird/ClickHouse that referenced this pull request Oct 5, 2026
… value

A Dynamic value can hold a JSON object, a JSON object's dynamic path is a
Dynamic, and JSON/Object is a legal Variant member (checkAllowedInsideVariant
forbids only Nullable, LowCardinality(Nullable), a nested Variant and a direct
Dynamic). So one value can nest Object -> Dynamic -> Variant -> Object to any
depth, and that depth comes from the data: the declared type here is just
Dynamic, and each level's small type is decoded separately, so no type
complexity or parser limit bounds it.

Reading one row of such a value recurses once per level through five frames:

  ColumnObject::operator[]      (ColumnObject.cpp:305)
    -> ColumnDynamic::operator[] (ColumnDynamic.cpp:318)
    -> ColumnDynamic::get        (ColumnDynamic.cpp:328)
    -> ColumnVariant::get        (ColumnVariant.cpp:428)
    -> ColumnObject::get         (ColumnObject.cpp:327)
    -> ColumnObject::operator[]  ... repeats

at about 2.8 KB of stack per level. The one checkStackSize() that path already
reaches sits inside convertFieldToType, called at ColumnDynamic.cpp:330 after
variant_col.get(n, res) has returned, so it runs only once the descent has
completed and cannot stop the descent that overflows. Measured on a debug build
with an 8 MB stack: 1500 and 2000 levels report TOO_DEEP_RECURSION from that
call, while 3000 and 4000 levels take SIGSEGV on the way down. An -O2 build
behaves the same (these frames are dominated by Field, String and Object
temporaries rather than spills, so optimisation does not shrink them), and the
official 26.8.10.6-lts build dies the same way at default settings.

Checking the stack at the top of ColumnDynamic::get moves the check onto the way
down, once per level. Every data-driven level of this nesting passes through a
ColumnDynamic per-value method, because a JSON object's dynamic paths are
ColumnDynamic columns and its shared-data values are decoded by
SerializationDynamic, which is already guarded.

ColumnObject and ColumnVariant are deliberately left unguarded. Their nested
types come from the declared type, and DataTypeFactory.cpp:128-130 caps a
declared type's parse depth at 150 (debug) / 300, two orders of magnitude below
the depths that overflow; a probe confirms a deep JSON(a JSON(...)) is rejected
with "Maximum parse depth (150) exceeded" and the server survives. Adding a
guard there would also re-litigate 2fcfc07, which removed exactly that
construct one layer down in ClickHouse#115702 for its per-container-value cost.

About twenty further per-value methods on these three columns (insert*,
compareAt, computeHashInto, updateHashWithValue, serializeValueIntoArena,
compress, byteSizeAt, ...) recurse identically, with no observed overflow and no
reproducer; the reproducers for updateHashWithValue and getValueNameImpl are
pre-empted on this base by the analyzer recursion that ClickHouse#120885 guards, so they
are not covered here.

Alternatives rejected: guarding the entry points (eight-plus sites for one arm,
and it guards the symptom); bounding the nesting depth when the value is built
(a behaviour change that rejects values accepted today, and it cannot protect a
read of data an older server already wrote); guarding the operator[] alias as
well as get (operator[] is get, so it would double-check).

The regression test uses 4000 levels, the depth CI found and a depth measured to
overflow both a debug and an -O2 build. It should not be raised much above that:
from about 8000 levels the type-side guard in IDataType::getDefaultSerialization
fires first and returns the same error code without the column recursion ever
running deep.

Found by the AST fuzzer, STID 4709-36d5:
https://github.com/ClickHouse/ClickHouse/actions/runs/35623644754/job/106452545848
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-datatype-wrapper Type modifiers/wrappers (Nullable, LowCardinality, etc.). pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-critical-bugfix pr-must-backport Pull request should be backported intentionally. Use this label with great care! pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants