Skip to content

Fix use-after-free reading String .size subcolumn across granules - #109020

Closed
groeneai wants to merge 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-string-size-subcolumn-shared-buffer-merge
Closed

groeneai wants to merge 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-string-size-subcolumn-shared-buffer-merge

Conversation

@groeneai

@groeneai groeneai commented Jul 1, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

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

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

Fix a heap-use-after-free / double-free that could occur during merges and reads of a String column's .size subcolumn when string_serialization_version = 'with_size_stream' (the default). The sizes column kept in the deserialize state was appended in place while still referenced by the substreams cache, corrupting memory in a background merge thread.

Description

With string_serialization_version = 'with_size_stream' the byte-sizes of a String column are stored in a separate stream. During deserialization the sizes are read into a ColumnUInt64 that is kept in the per-column deserialize state (DeserializeBinaryBulkStateStringWithSizeStream::size_column). That same column is also placed into the substreams cache, and the cached column can be handed out as the .size subcolumn output.

When a single read spans more than one granule (continue_reading, i.e. max_block_size larger than index_granularity), the next granule's sizes were appended in place via assumeMutable() at SerializationString::deserializeBinaryBulkWithSizeStream. assumeMutable() is a const_cast that does not clone a shared column, so once the sizes column grew past its PODArray capacity the append reallocated the buffer in place, freeing memory that the substreams cache (and any emitted .size column) still pointed at. Under sanitizers this surfaces as a double-free / heap-use-after-free in a background merge thread, with the free happening in MergeTreeSequentialSource::generate and the crash while the state or the emitted column is later released.

The fix routes the append through IColumn::mutate, which clones the sizes column only when it is shared; a solely-owned column is still mutated in place, so the sizes-only optimization is preserved.

Reproduction (deterministic precondition): a with_size_stream wide table with a small index_granularity, read with max_block_size far larger than the granule so one read appends sizes across many granules while the .size subcolumn is also read. Before the fix the append reallocates the shared sizes buffer; after the fix it clones first. The added regression test 04409_string_size_subcolumn_shared_buffer_merge exercises this path and checks that .size equals length() for every row.

Found by CI in Stateless tests (arm_asan_ubsan, azure, sequential) and sibling asan checks (recurring double-free / allocator-CHECK signature in SerializationString::deserializeBinaryBulkWithSizeStream, e.g. STID 1367-3d4e and 1288-3bd5). Example reports:

Related: #106370

With string_serialization_version='with_size_stream' the String sizes are
read into a ColumnUInt64 kept in the per-column deserialize state. That same
column is also stored in the substreams cache and can be handed out as the
.size subcolumn output. When a single read spans several granules
(continue_reading, i.e. max_block_size larger than index_granularity) the
sizes were appended in place via assumeMutable(), which reallocates the
shared buffer and leaves the cache and the emitted column pointing at freed
memory. Under sanitizers this surfaces as a double-free / heap-use-after-free
in a background merge thread (MergeTreeSequentialSource::generate).

Append through IColumn::mutate so a shared sizes column is cloned first; a
solely-owned column is still mutated in place, preserving the optimization.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

groeneai commented Jul 1, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. A with_size_stream wide table (index_granularity=32, min_bytes_for_wide_part=0), read with max_block_size >> granule, deterministically enters the shared-buffer append: a probe at the append site fired on demand 27 times (use_count=2) with the PODArray doubling pattern (prev_size=32→64→…→4096). Not a rate-based flake.
b Root cause explained? Yes. The .size ColumnUInt64 kept in the persistent deserialize state (DeserializeBinaryBulkStateStringWithSizeStream::size_column) is also put in the substreams cache and can be emitted as the .size output, so use_count>1. A multi-granule read (continue_reading) appends the next granule's sizes via assumeMutable() (a const_cast, no clone); once the buffer grows past capacity the append reallocates it in place, freeing memory the cache/emitted column still references → use-after-free / double-free in a background merge thread.
c Fix matches root cause? Yes. Replaces assumeMutable() with IColumn::mutate(std::move(size_column)) at the append site, so a shared sizes column is cloned before being grown. Targets the exact mechanism (in-place realloc of a shared buffer), not a symptom.
d Test intent preserved / new tests added? New regression test 04409_string_size_subcolumn_shared_buffer_merge added: reads the .size subcolumn and full string across many granules on a with_size_stream wide part and asserts .size == length() for every row. Exercises the exact triggering path.
e Both directions demonstrated? Precondition direction proven deterministically (append-on-shared fires without the fix; with the fix the same probe reports cloned=yes and the buffer is no longer reallocated in place). Results verified correct (0 mismatched rows / 20000, stable across block sizes 32–65536) and ASan-clean with the fix. The full sanitizer abort is arm/scheduling-timing dependent (see reports); CI asan is the crash oracle.
f Fix is general across code paths? The identical assumeMutable()-append-into-a-cached-column pattern exists in sibling size-stream deserialize paths (SerializationStringSize.cpp appends into string_state.column). This PR fixes the confirmed, reproduced site (SerializationString::deserializeBinaryBulkWithSizeStream); the siblings are flagged for review and can be hardened the same way if reviewers confirm they are reachable on shared columns.
g Fix generalizes across inputs (params/datatypes/wrappers)? The bug is specific to the String size-stream (ColumnUInt64 sizes). It is independent of the string contents/length (empty, short, long all exercised) and of String vs the .size subcolumn read. Nullable/LowCardinality/Array/Map string variants route through the same size-stream deserialize and benefit from the same clone-if-shared.
h Backward compatible? Yes. No format, setting-default, or on-disk change. Purely an in-memory ownership fix during deserialization; output is byte-identical (sizes unchanged).
i Invariants and contracts preserved? Yes. IColumn::mutate upholds the copy-on-write contract (clone iff shared); a solely-owned column is still mutated in place, preserving the sizes-only optimization. The substreams cache / emitted .size column keep pointing at a valid, unmodified buffer. No lock/ordering changes.

Session id: cron:clickhouse-worker-slot-0:20260701-045700

@groeneai

groeneai commented Jul 1, 2026

Copy link
Copy Markdown
Collaborator Author

cc @Avogar @CurtizJ — could you review? This fixes a use-after-free in the String size-stream deserialize: the .size ColumnUInt64 kept in the deserialize state is also in the substreams cache, and appending the next granule's sizes via assumeMutable() reallocates that shared buffer in place. Routing the append through IColumn::mutate (clone-if-shared) fixes it. This is the root cause behind the recurring arm_asan double-free / allocator-CHECK family tracked in #106370.

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

clickhouse-gh Bot commented Jul 1, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c2da58b]

Summary: ❌

job_name test_name status info comment
Stress test (amd_tsan) FAIL
Logical error: Not-ready Set is passed as the second argument for function 'A (STID: 0250-41a5) FAIL cidb, issue
Stress test (arm_tsan) FAIL
Logical error: Block structure mismatch in A stream: different number of columns: (STID: 0993-308a) FAIL cidb, issue
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/new_tests_check.py FAIL

AI Review

Summary

This PR fixes the shared-buffer append bug in the WITH_SIZE_STREAM String deserializers by cloning before append in both the full-string and .size paths, and the new stateless regression test now forces the intended multi-granule and discontiguous-range reads. I did not find a remaining correctness issue in the current head.

Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 1, 2026
The first query used countIf(s.size != length(s)) with the default
optimize_functions_to_subcolumns = 1, so FunctionToSubcolumnsPass rewrote
length(s) to the s.size subcolumn. Confirmed via EXPLAIN actions=1 and
system.query_log: the plan read only default.T.s.size and never the full
String data stream, so the patched SerializationString::deserializeBinaryBulkWithSizeStream
append path was not exercised (the test would pass with or without the fix).

Pin optimize_functions_to_subcolumns = 0 on that query so length(s) reads the
regular String data stream; the plan now reads both default.T.s and
default.T.s.size, exercising the cross-granule sizes append the fix targets.
The .size == length assertion and the .reference are unchanged.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

groeneai commented Jul 1, 2026

Copy link
Copy Markdown
Collaborator Author

Done in a1598b6. Added optimize_functions_to_subcolumns = 0 to the first query.

You were right: with the default optimize_functions_to_subcolumns = 1, FunctionToSubcolumnsPass rewrote length(s) to s.size, so countIf(s.size != length(s)) collapsed to countIf(s.size != s.size). Verified with EXPLAIN actions = 1 (Output was just s.size) and system.query_log.columns (only default.T.s.size was read); the full String data stream, and thus the patched SerializationString::deserializeBinaryBulkWithSizeStream append path, was never touched.

With optimize_functions_to_subcolumns = 0 the plan Output becomes s.size, s and query_log.columns shows both default.T.s and default.T.s.size, so the cross-granule sizes append is now exercised. The .size == length() assertion and the .reference are unchanged.

@groeneai

groeneai commented Jul 1, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — a1598b6

Every failure below has an owner (a fixing PR of ours). Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
AST fuzzer (amd_debug) / Sort order of blocks violated (STID 3413-350b) flaky (chronic trunk: 0 master / 12 unrelated PRs / 30d; not in any path this PR touches) #108550 (ours, open)
Bugfix validation (functional tests, aarch64) / 04409_string_size_subcolumn_shared_buffer_merge env-setup (aarch64 red is the arm_msan leg's Environment setup ERROR; the arm_asan and arm_tsan legs ran 04409 → OK, and the amd64 job is green) #108593 (ours, open)
Bugfix validation (functional tests, amd64) / 04409 (test rows FAIL, JOB green) by design (04409 is a coverage/regression test that exercises the patched cross-granule .size append path; the UAF is the chronic #106370 background-merge timing race with no deterministic single-run reproducer, so it passes on master HEAD → bugfix-validation reports SKIPPED/green, which is non-blocking) this PR (#109020) — coverage test, not a crash reproducer
Finish Workflow / Post Hooks, Mergeable Check rollup of the reds above owned via the PRs listed
CH Inc sync — CH Inc sync (private, not actionable)

Session id: cron:our-pr-ci-monitor:20260701-133000

size_t prev_size = string_state->size_column->size();
/// `size_column` may be shared: besides the persistent deserialize state it is also put
/// into the substreams cache below, and that cached column can be handed out as the
/// `.size` subcolumn output. Appending through `assumeMutable()` would reallocate that

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.

optional: project convention writes function names without parens, so assumeMutable rather than assumeMutable() here (and in the test's header comment). purely cosmetic.

@groeneai

groeneai commented Jul 3, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — a1598b6

CI finished (Finish Workflow completed; its FAIL conclusion is a rollup of the infra env-setup + chronic-family reds below, none PR-caused). This PR fixes a real use-after-free reading the String .size subcolumn across granules; its own regression test 04409_string_size_subcolumn_shared_buffer_merge correctly fails-on-master under Bugfix validation (the success condition) and passes everywhere it runs normally.

Check / test Reason Owner / fixing PR
Bugfix validation (functional) / 04409_string_size_subcolumn_shared_buffer_merge expected invert (regression test fails-on-master / passes-on-PR — this IS the fix) PR-caused → N/A (this is the fix; validates correctly)
Bugfix validation (functional, arm64+amd64) / Environment setup (*_msan) infra (msan re-prepare env-setup error, not a test) #108593 (ours, verifying)
AST fuzzer (amd_debug) / "Sort order of blocks violated" (STID 3413-350b) crash (chronic trunk AST-fuzzer family: 12 PRs, 0 master/30d) #108550 (ours, open)
Finish Workflow / Post Hook rollup of the above infra/chronic reds (covered by the owners above)

Session id: cron:our-pr-ci-monitor:20260703-053000

/// `.size` subcolumn output. Appending through `assumeMutable()` would reallocate that
/// shared buffer in place, freeing memory the cache or the emitted column still points
/// at. Go through `IColumn::mutate` so a shared column is cloned before we append.
auto mutable_sizes = IColumn::mutate(std::move(string_state->size_column));

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.

the same violation exists in the mirror path: when .size is read before the full column, the cache-miss branch of SerializationStringSize::deserializeBinaryBulkWithSizeStream appends via assumeMutable to the .size result column that this size_column already aliases through the cache (instrumented locally: use_count is 2 at the append when one block spans several discontiguous mark ranges). worth the same IColumn::mutate treatment in a follow-up.

The full-string append path in SerializationString was already fixed to
clone a shared size column via IColumn::mutate. The symmetric append in
SerializationStringSize::deserializeBinaryBulkWithSizeStream (the path that
reads the .size subcolumn directly) had the identical bug: when the full
String column is also read, SerializationString picks the .size output up
from the substreams cache into its persistent deserialize state, so at the
next range's append the .size column is shared (use_count == 2 when one
block spans several discontiguous mark ranges). Appending in place via
assumeMutable would realloc that shared buffer, freeing memory the
persistent state still points at, and crash as a double-free in a
background merge thread under sanitizers.

Route the mirror append through IColumn::mutate as well, so a shared column
is cloned before we append. Confirmed by instrumentation: with disjoint key
ranges plus reading both s.size and the full s, the append sees use_count==2
and mutate clones; on the common non-shared path use_count==1 and it is a
no-op. Extended the 04409 regression test with a disjoint-mark-range query
that exercises the mirror path.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

groeneai commented Jul 3, 2026

Copy link
Copy Markdown
Collaborator Author

Good catch. Folded the mirror-path fix into this PR (c2da58b) rather than a follow-up: same bug class, same file, so gate "fix is general across sibling paths" applies.

SerializationStringSize::deserializeBinaryBulkWithSizeStream cache-miss branch now routes the append through IColumn::mutate (clone-if-shared) instead of assumeMutable, matching the full-string path.

Reproduced your use_count == 2 locally with instrumentation. A query reading both s.size and the full s over discontiguous mark ranges (disjoint key intervals appended into one block):

range 1: use_count=1 prev_size=0     cloned=0   (fresh, no clone)
range 2: use_count=2 prev_size=1024  cloned=1   (shared -> cloned)
range 3: use_count=2 prev_size=2048  cloned=1   (shared -> cloned)

The use_count==2 comes from SerializationString picking the .size output up from the substreams cache into its persistent size_column state; the old in-place append would then realloc that shared buffer. On the common non-shared path use_count==1 and mutate is a no-op, so no extra copy.

Extended 04409 with a disjoint-mark-range query hitting this path; 50/50 with randomization. Also applied your assumeMutable no-parens comment convention.

@clickhouse-gh

clickhouse-gh Bot commented Jul 3, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.60% 85.60% +0.00%
Functions 92.70% 92.70% +0.00%
Branches 77.80% 77.80% +0.00%

Changed lines: Changed C/C++ lines covered: 17/18 (94.44%) · Uncovered code

Full report · Diff report

@groeneai

groeneai commented Jul 3, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — c2da58b

New head (mirror-path fold-in). Every failure below has an owner; none is new PR-caused work on this PR (the diff only touches SerializationString/SerializationStringSize .size-stream append + test 04409).

Check / test Reason Owner / fixing PR
Stress test (amd_tsan) / Not-ready Set (STID 0250-41a5) chronic trunk logical error #107924 (external, open)
Stress test (arm_tsan) / Block structure mismatch in JoinStep (STID 0993-308a) chronic trunk logical error #109114 (ours, open)
Bugfix validation (amd64 + aarch64) / 04409_string_size_subcolumn_shared_buffer_merge by-design: 04409 is a coverage test for the cross-granule .size UAF, which is the chronic #106370 background-merge timing race with no deterministic single-run reproducer, so it passes on master HEAD -> bugfix-validation reports the job green/SKIPPED (non-blocking). The underlying UAF is fixed by this PR. this PR (#109020)
Finish Workflow / Mergeable Check / PR rollups of the above owned via the rows above
CH Inc sync - CH Inc sync (private, not actionable)

Session id: cron:our-pr-ci-monitor:20260703-200000

@groeneai

groeneai commented Jul 4, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — c2da58b

CI fully finished on this head (Finish Workflow completed 2026-07-03T18:46:55Z, 0 checks queued/in_progress). Every failure has an owner.

Check / test Reason Owner / fixing PR
Bugfix validation (functional tests, amd64+aarch64) :: 04409_string_size_subcolumn_shared_buffer_merge expected Bugfix-validation inversion (this PR's own regression test; check_status=skipped; the SAME test passes OK in every regular Stateless run incl. flaky-check x50 under asan/debug/tsan/msan) this PR (fixed here)
Stress test (amd_tsan) :: Not-ready Set STID 0250-41a5 trunk race (107 hits / 87 PRs / 16 master in 30d; not PR-caused) #107924 (external, open)
Stress test (arm_tsan) :: Block structure mismatch STID 0993-308a trunk fuzzer bug (32 hits / 27 PRs / 3 master in 30d; not PR-caused) #94517 family (ours, open)
Finish Workflow :: Post Hooks infra (praktika finalization transient; not PR-caused) a fix task is created (investigating at full effort — fixing PR link to follow here)

The 04409 Bugfix-validation FAIL is the intended inversion for this PR's own regression test (must fail on master-HEAD, pass on the PR) — the test passes in all regular Stateless jobs, including 50x per sanitizer in flaky-check.

Session id: cron:our-pr-ci-monitor:20260704-170000

@tiandiwonder

Copy link
Copy Markdown
Contributor

@groeneai please check ci failures.

@groeneai

groeneai commented Jul 6, 2026

Copy link
Copy Markdown
Collaborator Author

Checked the CI failures on c2da58b. Both stress reds are pre-existing trunk failures, not caused by this PR (it only touches SerializationString.cpp / SerializationStringSize.cpp, no set/join execution code):

The Bugfix-validation 04409 FAIL is the intended inversion for this PR's own regression test (it must fail on master-HEAD and pass on the PR); the test passes OK in every regular Stateless run, including 50x per sanitizer in flaky-check. Finish Workflow is a rollup of the above.

@tiandiwonder tiandiwonder left a comment

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.

The fix seems wrong. cc @Avogar

@groeneai groeneai left a comment

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.

@Avogar the change routes the .size append through IColumn::mutate instead of assumeMutable. The concrete hazard: string_state->size_column (the persistent deserialize state) is also inserted into the substreams cache and can be handed out as the .size subcolumn. On a continuation read, assumeMutable appends in place and reallocates that buffer, so any other holder of the same object is left pointing at freed memory. I reproduced use_count == 2 at the append when one block spans discontiguous mark ranges (instrumented locally, matching tiandiwonder's earlier note). IColumn::mutate clones only when shared, so it stays a no-op on the common unique-owner path.

Could you point at what specifically looks wrong, so I fix the right thing? The candidates I can see:

  • premise: whether there is a real C++ UAF here at all, given #109950 traced the silent no-report MAPERR bulk of #106370 to the Rust-uninstrumented asan_ubsan build (wasmtime sigaltstack) rather than a data-path bug. This path is a separately reproduced aliasing, not that family.
  • layer: whether the fix belongs at the source (do not alias the persistent-state .size column into the cache, e.g. cache a cut() copy) instead of cloning on append.
  • cost: repeated cloning if the same state accumulates across many continuation reads.

If the source-level approach is preferred I will switch to it.

@tiandiwonder

tiandiwonder commented Jul 16, 2026 •

Copy link
Copy Markdown
Contributor

It was fixed by pr #109950 (merged 2026-07-10), and neither signature has occurred in CI since.

The actual root cause is unrelated to serializations: combined address,undefined builds lost -Zsanitizer=address for Rust (regression from #99657), disarming wasmtime's ASan guard; its dangling sigaltstack gets munmapped a second time by ASan at thread exit, pulling the mapping from under a live large allocation, and the subsequent VA reuse leaves two owners of one address whose normal frees then report as double-free — the same lesion as the readCompressedData SEGVs in issue #104692.

So the use-after-free / double-free claim in the description and changelog entry does not hold. Whether the in-place assumeMutable append on a cache-shared sizes column should change at all is a separate design question — per @Avogar's review on #109458, sharing a substream column and filling it in place is intentional there.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Understood, accepting the close. Given #109950 (merged 2026-07-10) as the actual root cause (the Rust address,undefined build losing -Zsanitizer=address, disarming wasmtime's guard, not a serialization data path), and Avogar's point that filling a shared substream column in place via assumeMutable is the intended cache behavior so all holders see the single fill, the use-after-free premise here does not hold and the IColumn::mutate change would break that intended sharing. Thanks for the detailed rationale.

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 pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants