Skip to content

Use COW-safe IColumn::mutate when finalizing merge output columns - #107451

Merged
alexey-milovidov merged 1 commit into
masterfrom
fix-merge-uaf-cow-mutate
Jun 15, 2026
Merged

alexey-milovidov merged 1 commit into
masterfrom
fix-merge-uaf-cow-mutate

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Jun 14, 2026 •

Copy link
Copy Markdown
Member

Hardens a copy-on-write violation on the merge write path that can lead to a heap use-after-free.

MergeTreeSequentialSource::generate finalized the merge output columns through assumeMutableRef() — once to run shrinkToFit(), and once to rewrite the _parent_part_offset column for projection parts. assumeMutableRef() bypasses copy-on-write, so when a column is shared, mutating it in place (and, for shrinkToFit, reallocating its buffer) corrupts or frees data that may still be referenced by another owner. These two sites now go through IColumn::mutate, which clones the column only when it is shared (use_count > 1) and is a no-op when it is uniquely owned (the common case), so the normal merge path is unchanged.

Motivated by an AddressSanitizer heap-use-after-free reported in MasterCI during a horizontal merge — the writer (MergeTreeDataPartWriterWide::writeSingleGranule) serialized a plain UInt16 column whose buffer had already been freed:

https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=0577669cbc1cc363bbcd38da7a9e2668c7fed077&name_0=MasterCI&name_1=Stateless%20tests%20%28amd_asan_ubsan%2C%20db%20disk%2C%20distributed%20plan%2C%20sequential%29

The crash is intermittent and could not be reproduced locally, so this is a targeted copy-on-write hardening on the merge output-production path rather than a confirmed fix for that exact report; the ASan CI is the validation.

Changelog category (leave one):

  • CI Fix or Improvement (changelog entry is not required)

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

Not required (CI Fix or Improvement).

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.6.1.799

`MergeTreeSequentialSource::generate` mutated the merge output columns
through `assumeMutableRef` before `shrinkToFit` (and when adjusting the
`_parent_part_offset` column for projection parts). `assumeMutableRef`
bypasses copy-on-write, so when the column is shared this mutates - and
`shrinkToFit` reallocates - data that may still be referenced elsewhere,
which is a use-after-free hazard.

Route these through `IColumn::mutate`, which clones the column only when
it is shared (`use_count > 1`) and is a no-op when it is uniquely owned,
so the common path is unchanged.

Motivated by an ASan heap-use-after-free reported during a horizontal
merge in MasterCI (writer serializing a `UInt16` column whose buffer was
freed):
https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=0577669cbc1cc363bbcd38da7a9e2668c7fed077&name_0=MasterCI&name_1=Stateless%20tests%20%28amd_asan_ubsan%2C%20db%20disk%2C%20distributed%20plan%2C%20sequential%29

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jun 14, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [120a33a]

Summary: ✅


AI Review

Summary

This PR hardens MergeTreeSequentialSource::generate by routing the _parent_part_offset rewrite and final shrinkToFit through IColumn::mutate, so shared columns and shared nested subcolumns are cloned before mutation. The changed ownership path is consistent with IColumn copy-on-write semantics, and I did not find a correctness issue that needs an inline comment.

Missing context / blind spots
  • ⚠️ The linked MasterCI ASan report is intermittent and the report artifacts did not include full logs, so I could not prove this exact report is fixed deterministically; the current PR Praktika report has no failed tests, and ASan CI remains the practical validation.
Final Verdict

Status: ✅ Approve

@clickhouse-gh

clickhouse-gh Bot commented Jun 15, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.90% 84.90% +0.00%
Functions 92.30% 92.40% +0.10%
Branches 77.30% 77.30% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 12/12 (100.00%) | Lost baseline coverage: none · Uncovered code

Full report · Diff report

@alexey-milovidov alexey-milovidov left a comment

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.

LGTM

@alexey-milovidov alexey-milovidov self-assigned this Jun 15, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jun 15, 2026
Merged via the queue into master with commit 2703c85 Jun 15, 2026
166 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-merge-uaf-cow-mutate branch June 15, 2026 02:07
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 15, 2026
pull Bot pushed a commit to SINHASantos/ClickHouse that referenced this pull request Jun 18, 2026
…uild paths

Several places obtained a mutable column via `assumeMutable`/`assumeMutableRef`
(which bypass copy-on-write with a bare `const_cast`) and then mutated or
reallocated it in place. When such a column happens to be shared
(`use_count > 1`), this corrupts or frees data that may still be referenced
elsewhere.

Replace these with `IColumn::mutate(std::move(...))`, which clones only when
the column is shared and is a no-op (same cost) when it is uniquely owned, and
write the mutated result back into its holder. The common, uniquely-owned path
is unchanged; the shared path becomes safe.

Converted sites: MergeTree readers (`MergeTreeReaderTextIndex`,
`MergeTreeReaderCompact`, `MergeTreeReaderIndex`), the `MergeTreeIndexSet`
granule builder, the virtual-column and minmax block builders
(`VirtualColumnUtils`, `MergeTreeData::getBlockWithVirtualsForFilter`),
`SerializationObjectCombinedPath` deserialization, the hash-join rerange
builder (`HashJoin::tryRerangeRightTableDataImpl`), `StorageExecutable` result
accumulation, and the Prometheus remote-write id-column accumulator.

Intentionally left as-is: the copy-on-write `create(const ColumnPtr &)`
factories, the patch-parts in-place write-back (`applyPatches`), the
substreams-cache offsets grow-in-place (`SerializationSparse`), and the
in-place column-algorithm subcolumn idioms - these are deliberately shared and
converting them would force a clone (a regression) or change semantics.
`ProtobufSerializer` is left for a follow-up that makes it operate on mutable
columns directly.

Related: ClickHouse#107451

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
pull Bot pushed a commit to mikeyhodl/ClickHouse that referenced this pull request Jul 5, 2026
…y paths

`MergeTreeSequentialSource::generate` finalizes merge output columns with an
in-place `shrinkToFit` that reallocates their buffers. Under ASan this keeps
producing `heap-use-after-free` / `double-free` reports during horizontal
merges (the latest is a `double-free` at `shrinkToFit` on a plain `UInt64`
column deserialized from disk), which means a merge output column shares an
underlying buffer with another owner via a path that bypasses copy-on-write
reference counting.

PR ClickHouse#107451 hardened the `generate` finalize sites themselves; this continues
that sweep for the read/deserialize and patch-apply paths that feed those
columns, replacing the remaining in-place mutations of potentially-shared
columns with `IColumn::mutate` (clone only when `use_count > 1`, a no-op for
the common uniquely-owned case):

- `ISerialization::deserializeBinaryBulkWithMultipleStreams` appended freshly
  deserialized data into `column` via `assumeMutable`; when `column` was
  already placed into the substreams cache by an earlier substream read this
  mutated shared data in place.
- `ISerialization::insertDataFromCachedColumn` appended cached rows into a
  `result_column` that may be shared with the substreams cache via
  `assumeMutable`.
- `applyPatchesToBlockRaw` / `applyPatchesToBlockCombined` applied patches
  in place via `assumeMutableRef().updateInplaceFrom` on a result column that
  may still be referenced elsewhere.

The crash is intermittent and could not be reproduced locally, so this is
targeted copy-on-write hardening on the paths that produce merge output
columns rather than a confirmed fix for that exact report; the ASan CI is the
validation.

CI report:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=c794d5be5e1c4c2de860253ce712bdffa9a7e50e&name_0=MasterCI&name_1=Stateless%20tests%20%28amd_asan_ubsan%2C%20db%20disk%2C%20distributed%20plan%2C%20sequential%2C%201%2F2%29

Related: ClickHouse#107451

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
alexey-milovidov added a commit to groeneai/ClickHouse that referenced this pull request Jul 27, 2026
…ze states

The crash family tracked in issue ClickHouse#105626 (SEGV in
CompressedReadBufferFromFile::readBig during merges, ASan double-free on
reader stream buffers, heap-use-after-free on columns freed by
SubstreamsCacheColumnWithNumReadRowsElement destruction while still
referenced by MergeTreeRangeReader) is caused by broken copy-on-write
reference counting: some holder of a column obtains it without a counted
reference, so the column is freed while still in use. The IColumn::mutate
sweeps (ClickHouse#107451, ClickHouse#109105) did not stop the family because they defend
against in-place mutation of shared columns, not against an under-counted
reference.

This change adds debug/sanitizer-build diagnostics that turn the weekly
flaky crashes into deterministic failures at the point where the
inconsistency is still observable:

- ColumnsOwnershipValidator: enumerates the column references that provably
  exist (from substreams cache elements, deserialize states, and result
  columns with their subcolumn trees) and checks that use_count covers
  them. Runs at the end of MergeTreeReaderWide::readRows and per granule in
  MergeTreeReaderCompactSingleBuffer::readRows, right before the caches are
  dropped. Throws LOGICAL_ERROR, which aborts in debug and sanitizer builds.
- forEachColumn enumeration hooks on ISubstreamsCacheElement and
  DeserializeBinaryBulkState, implemented for all elements and states that
  hold columns (column-with-num-read-rows element, sparse offsets element,
  Object shared data paths-data element, String size stream and full-column
  states, Variant element and null-map states, Dynamic element, Object
  dynamic/shared-data paths, Map key-value, LowCardinality).
- chasserts of the column->size() >= num_read_rows invariant at substreams
  cache insert and lookup and in insertDataFromCachedColumn (its consumers
  do insertRangeFrom(*cached, size - num_read_rows, num_read_rows), which
  would silently underflow).

All checks compile to no-ops in release builds.

Related: ClickHouse#105626

Co-Authored-By: Claude Fable 5 <[email protected]>
scanhex12 pushed a commit to scanhex12/ClickHouse that referenced this pull request Jul 29, 2026
…ze states

The crash family tracked in issue ClickHouse#105626 (SEGV in
CompressedReadBufferFromFile::readBig during merges, ASan double-free on
reader stream buffers, heap-use-after-free on columns freed by
SubstreamsCacheColumnWithNumReadRowsElement destruction while still
referenced by MergeTreeRangeReader) is caused by broken copy-on-write
reference counting: some holder of a column obtains it without a counted
reference, so the column is freed while still in use. The IColumn::mutate
sweeps (ClickHouse#107451, ClickHouse#109105) did not stop the family because they defend
against in-place mutation of shared columns, not against an under-counted
reference.

This change adds debug/sanitizer-build diagnostics that turn the weekly
flaky crashes into deterministic failures at the point where the
inconsistency is still observable:

- ColumnsOwnershipValidator: enumerates the column references that provably
  exist (from substreams cache elements, deserialize states, and result
  columns with their subcolumn trees) and checks that use_count covers
  them. Runs at the end of MergeTreeReaderWide::readRows and per granule in
  MergeTreeReaderCompactSingleBuffer::readRows, right before the caches are
  dropped. Throws LOGICAL_ERROR, which aborts in debug and sanitizer builds.
- forEachColumn enumeration hooks on ISubstreamsCacheElement and
  DeserializeBinaryBulkState, implemented for all elements and states that
  hold columns (column-with-num-read-rows element, sparse offsets element,
  Object shared data paths-data element, String size stream and full-column
  states, Variant element and null-map states, Dynamic element, Object
  dynamic/shared-data paths, Map key-value, LowCardinality).
- chasserts of the column->size() >= num_read_rows invariant at substreams
  cache insert and lookup and in insertDataFromCachedColumn (its consumers
  do insertRangeFrom(*cached, size - num_read_rows, num_read_rows), which
  would silently underflow).

All checks compile to no-ops in release builds.

Related: ClickHouse#105626

Co-Authored-By: Claude Fable 5 <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…y paths

`MergeTreeSequentialSource::generate` finalizes merge output columns with an
in-place `shrinkToFit` that reallocates their buffers. Under ASan this keeps
producing `heap-use-after-free` / `double-free` reports during horizontal
merges (the latest is a `double-free` at `shrinkToFit` on a plain `UInt64`
column deserialized from disk), which means a merge output column shares an
underlying buffer with another owner via a path that bypasses copy-on-write
reference counting.

PR ClickHouse#107451 hardened the `generate` finalize sites themselves; this continues
that sweep for the read/deserialize and patch-apply paths that feed those
columns, replacing the remaining in-place mutations of potentially-shared
columns with `IColumn::mutate` (clone only when `use_count > 1`, a no-op for
the common uniquely-owned case):

- `ISerialization::deserializeBinaryBulkWithMultipleStreams` appended freshly
  deserialized data into `column` via `assumeMutable`; when `column` was
  already placed into the substreams cache by an earlier substream read this
  mutated shared data in place.
- `ISerialization::insertDataFromCachedColumn` appended cached rows into a
  `result_column` that may be shared with the substreams cache via
  `assumeMutable`.
- `applyPatchesToBlockRaw` / `applyPatchesToBlockCombined` applied patches
  in place via `assumeMutableRef().updateInplaceFrom` on a result column that
  may still be referenced elsewhere.

The crash is intermittent and could not be reproduced locally, so this is
targeted copy-on-write hardening on the paths that produce merge output
columns rather than a confirmed fix for that exact report; the ASan CI is the
validation.

CI report:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=c794d5be5e1c4c2de860253ce712bdffa9a7e50e&name_0=MasterCI&name_1=Stateless%20tests%20%28amd_asan_ubsan%2C%20db%20disk%2C%20distributed%20plan%2C%20sequential%2C%201%2F2%29

Related: ClickHouse#107451

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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

2 participants