Repository navigation
Extend COW-safe IColumn::mutate sweep to deserialize and patch-apply paths - #109105
Conversation
…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 #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: #107451 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Workflow [PR], commit [21adeab] Summary: ✅
AI ReviewSummaryThis PR extends the deserialize-side and patch-apply copy-on-write hardening from the earlier merge-read fix: the generic cached-column append helper now clones before mutating shared state, the Final Verdict✅ No blocking findings in the current revision. |
…reams The previous commit changed `ISerialization::deserializeBinaryBulkWithMultipleStreams` to `auto mutable_column = IColumn::mutate(std::move(column))`. `std::move(column)` empties `column` immediately, and it was only restored via `column = std::move(mutable_column)` on the success path. When `deserializeBinaryBulk` threw (e.g. `MEMORY_LIMIT_EXCEEDED`), `column` was left moved-from (null), whereas the old `assumeMutable` path always left it valid. Callers that inspect the column after catching the exception then dereferenced a null `ColumnPtr`. This is what broke the `StringSerialization.IncorrectStateAfterMemoryLimitExceeded` unit test across all sanitizer variants (`asan_ubsan` reported UB in `intrusive_ref_counter`; `tsan`/`msan`/`llvm_coverage` segfaulted). Fix: reassign `column` to the (possibly cloned) column up front and mutate it in place via `assumeMutableRef`, so `column` stays a valid unique owner even if `deserializeBinaryBulk` throws. `IColumn::mutate` still clones only when the column is shared (a no-op for the common uniquely-owned case), preserving the copy-on-write hardening. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=109105&sha=3be6dbd3c4a1386d1ee43d059b7b2fcc8dbb7da4&name_0=PR&name_1=Unit%20tests%20%28asan_ubsan%29 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The previous sweep made `ISerialization::insertDataFromCachedColumn` copy-on-write safe for the zero-`rows_offset` cache append, but the `rows_offset > 0` cache-hit branches in `SerializationArrayOffsets::deserializeBinaryBulkWithMultipleStreams` and `SerializationStringSize::deserializeBinaryBulkWithSizeStream` still appended cached rows into `column` (and later compacted the `ColumnUInt64` in place) via `assumeMutable`. `column` can alias `cached_column`: the same size substream may be read first with `rows_offset == 0` — placing `column` itself into the substreams cache — and then re-read in the same range with `rows_offset > 0`. In that case both the append and the in-place compaction mutate storage still referenced by the cache, so the later `shrinkToFit` / destruction path can still hit the same `heap-use-after-free` / `double-free`. Clone `column` when shared via `IColumn::mutate` before the append; the subsequent compaction then always runs on a uniquely-owned column (the cache path cloned it when shared, and the fresh-read path caches a separate `cut()` copy). `IColumn::mutate` is a no-op for the common uniquely-owned case, so the hot path keeps the same cost. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Pushed two follow-up commits (
Validated locally by building Note: |
`insertDataFromCachedColumn` still used the move-out-then-restore-on-success shape: `auto mutable_result = IColumn::mutate(std::move(result_column))` emptied `result_column` up front and only reassigned it via `result_column = std::move(mutable_result)` on the success path. If `insertRangeFrom` throws mid-append (e.g. `MEMORY_LIMIT_EXCEEDED` on a cache-hit append), `result_column` is left moved-from (null), whereas the pre-sweep `assumeMutable` path preserved a valid column. This is the same exception-safety regression that was fixed in `deserializeBinaryBulkWithMultipleStreams`. Apply the identical treatment here: assign the (possibly cloned) column back to `result_column` first, then mutate in place via `assumeMutableRef`, so `result_column` stays a valid unique owner on the exception path while keeping the COW clone-if-shared behavior. This cache-hit helper is used by `SerializationStringSize`, `SerializationArrayOffsets`, `SerializationSparse`, `SerializationVariantElement`, `SerializationMapKeyValue` and others, so the regression affected all of them. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Pushed
The second AI-review blocker (
CI: the only red is |
Replace the "keep column valid on exception" shape from the previous commits
with the simpler and more readable move-based form:
MutableColumnPtr mutable_column = IColumn::mutate(std::move(column));
... work with mutable_column ...
column = std::move(mutable_column);
`IColumn::mutate` clones only when the column is shared (a no-op for the common
uniquely-owned case), which is what makes the append COW-safe; keeping the
`ColumnPtr` non-null across a throw is not worth the extra complexity. If
`deserializeBinaryBulk` / `insertRangeFrom` throws (e.g. `MEMORY_LIMIT_EXCEEDED`)
the caller may be left with a null column, which is acceptable — the read is
abandoned and the column discarded.
Applies to `ISerialization::deserializeBinaryBulkWithMultipleStreams`,
`ISerialization::insertDataFromCachedColumn`, and the `rows_offset` cache-hit
path of the `SerializationArrayOffsets` / `SerializationStringSize` size readers.
The `StringSerialization.IncorrectStateAfterMemoryLimitExceeded` gtest is updated
to tolerate a null column after `MEMORY_LIMIT_EXCEEDED`, still asserting that any
surviving column stays internally consistent.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…t path `SerializationVariant::deserializeBinaryBulkWithMultipleStreams` still appended cached discriminators in place via `assumeMutable` on the `rows_offset > 0` cache-hit path. A prior `rows_offset == 0` read of the same substream caches `col.getLocalDiscriminatorsPtr()` itself (not a `cut()` copy), so a later `rows_offset > 0` cache hit on the same column has `cached_column` aliasing the discriminators; the in-place append and the following in-place `rows_offset` compaction then mutate storage still referenced by the cache — the same COW hole the size readers close, and a candidate for the `heap-use-after-free` / `double-free` this sweep targets. Clone the discriminators via `IColumn::mutate` when shared before the append (a no-op when uniquely owned), using the same move-based form as the size readers. Adds `04504_variant_discriminators_cow_safe_rows_offset`, which reads a `Variant` column and its subcolumns under `PREWHERE` on a wide part with tiny `index_granularity` (`index_granularity_bytes = 0`) so the surviving rows are read at `rows_offset > 0`. Under ASan a regression surfaces as `heap-use-after-free` / `double-free`; the reference pins the correct results. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Pushed two follow-up commits (
|
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 35/47 (74.47%) · Uncovered code |
Avogar
left a comment
There was a problem hiding this comment.
I don't understand changes in serializations. It leads to extra data copy on shared subcolumns deserialization. And I don't see why we need to change this. It was intentional to share subcolumns and use assumeMutable() in serializations to insert into all shared instances of the same subcolumn. All MergeTree readers return constant ColumnPtr, so it should not lead to any problems if columns share the same subcolumns. We just can't use assumeMutable() outside of serializations (like in applyPatches).
|
And the test doesn't reproduce any problems in older binaries |
|
I will revert this |
…egression PR #109105 replaced assumeMutable with IColumn::mutate in serialization code. In ISerialization::deserializeBinaryBulkWithMultipleStreams this caused a severe performance regression (3-4x slower) because columns are intentionally shared via the substreams cache between multiple readers (e.g. reading both a full Tuple column and its named subcolumns). IColumn::mutate clones the column when use_count > 1, defeating the cache and causing unnecessary copies on every readRows call. MergeTree readers return a set of constant columns that are not mutated after reading, so sharing subcolumns via the same ColumnPtr is safe and assumeMutable is the correct approach in the base deserialization path. Keep IColumn::mutate in the other four call sites where the column is not shared via the cache: - ISerialization::insertDataFromCachedColumn - SerializationArrayOffsets (rows_offset > 0 path, cache stores cut() copy) - SerializationStringSize (rows_offset > 0 path, cache stores cut() copy) - SerializationVariant discriminators (rows_offset > 0 path, cache stores cut() copy) Also adds a performance test for Tuple subcolumn deserialization covering both wide parts (with alternating granule skipping via minmax index) and compact parts (with nested Tuple to exercise substream cache sharing). Co-Authored-By: Claude Opus 4.6 <[email protected]>
…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]>
…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]>
…ead-deserialize-double-free Extend COW-safe `IColumn::mutate` sweep to deserialize and patch-apply paths
Related: #107451
MergeTreeSequentialSource::generatefinalizes merge output columns with an in-placeshrinkToFitthat reallocates their buffers. Under ASan this keeps producingheap-use-after-free/double-freereports during horizontal merges — the latest (MasterCI report below) is adouble-freeatshrinkToFiton a plainUInt64column deserialized from disk during a background horizontal merge of plain (system) tables. That signature means a merge output column shares an underlying buffer with another owner through a path that bypasses copy-on-write reference counting.PR #107451 hardened the
generatefinalize sites themselves (and the follow-up sweep in36b1d340ecccovered several readers). 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 withIColumn::mutate(clone only whenuse_count > 1; a no-op for the common uniquely-owned case, so the hot path keeps the same cost):ISerialization::deserializeBinaryBulkWithMultipleStreamsappended freshly deserialized data intocolumnviaassumeMutable. Whencolumnwas already placed into the substreams cache by an earlier substream read, this mutated shared data in place.ISerialization::insertDataFromCachedColumnappended cached rows into aresult_columnthat may be shared with the substreams cache, viaassumeMutable.applyPatchesToBlockRaw/applyPatchesToBlockCombinedapplied patches in place viaassumeMutableRef().updateInplaceFromon 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
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.7.1.532(included in26.7and later)