Repository navigation
Use COW-safe IColumn::mutate when finalizing merge output columns - #107451
Merged
Merged
Conversation
`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]>
Contributor
|
Workflow [PR], commit [120a33a] Summary: ✅
AI ReviewSummaryThis PR hardens Missing context / blind spots
Final VerdictStatus: ✅ Approve |
1 task
Contributor
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered by tests: 12/12 (100.00%) | Lost baseline coverage: none · Uncovered code |
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]>
This was referenced Jun 20, 2026
This was referenced Jun 28, 2026
1 task
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]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Hardens a copy-on-write violation on the merge write path that can lead to a heap use-after-free.
MergeTreeSequentialSource::generatefinalized the merge output columns throughassumeMutableRef()— once to runshrinkToFit(), and once to rewrite the_parent_part_offsetcolumn for projection parts.assumeMutableRef()bypasses copy-on-write, so when a column is shared, mutating it in place (and, forshrinkToFit, reallocating its buffer) corrupts or frees data that may still be referenced by another owner. These two sites now go throughIColumn::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
AddressSanitizerheap-use-after-freereported in MasterCI during a horizontal merge — the writer (MergeTreeDataPartWriterWide::writeSingleGranule) serialized a plainUInt16column 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):
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
Version info
26.6.1.799