Skip to content

Use COW-safe IColumn::mutate for in-place column mutation on read/build paths - #107457

Merged
alexey-milovidov merged 4 commits into
masterfrom
cow-safe-assume-mutable-sweep
Jun 18, 2026
Merged

alexey-milovidov merged 4 commits into
masterfrom
cow-safe-assume-mutable-sweep

Conversation

@alexey-milovidov

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

Copy link
Copy Markdown
Member

Proactive copy-on-write (COW) safety sweep, following the same fix as #107451.

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 — the class of bug fixed in #107451.

These sites are replaced 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, writing 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
  • MergeTreeIndexSet granule builder
  • virtual-column / minmax block builders: VirtualColumnUtils, MergeTreeData::getBlockWithVirtualsForFilter
  • SerializationObjectCombinedPath deserialization
  • HashJoin::tryRerangeRightTableDataImpl
  • StorageExecutable result accumulation
  • Prometheus remote-write id-column accumulator

Intentionally left as-is (converting would force a clone — a regression — or change semantics, because the column is deliberately shared and reallocation does not happen):

  • the COW create(const ColumnPtr &) factories
  • the patch-parts in-place write-back (applyPatches)
  • the substreams-cache offsets grow-in-place (SerializationSparse)
  • the in-place column-algorithm subcolumn idioms (ColumnArray/ColumnObject/ColumnVariant/…)

ProtobufSerializer is left for a follow-up that makes it operate on mutable columns directly (it keeps a persistently shared ColumnPtr alias to the row format's columns, so it needs a small refactor rather than a per-call mutate).

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

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

Not required (internal copy-on-write safety hardening, no user-facing behavior change).

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.6.1.1002

…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: #107451

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 [b48f721]

Summary: ✅


AI Review

Summary

This PR replaces several in-place assumeMutable / assumeMutableRef usages with COW-safe IColumn::mutate and includes follow-up fixes that hoist the expensive cases called out in prior review threads. I did not find remaining correctness or performance blockers in the current diff; the earlier MergeTreeIndexSet, HashJoin, and VirtualColumnUtils concerns are addressed in the current code.

Missing context / blind spots
  • ⚠️ Current GitHub checks still had Build (arm_tidy) and Fast test in progress at review time; completed CI would close the remaining build/test validation gap.
Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Jun 14, 2026
Comment thread src/Interpreters/HashJoin/HashJoin.cpp Resolved
alexey-milovidov and others added 2 commits June 16, 2026 12:24
The previous commit copied the reusable scratch column out of
`block_for_reading` into a local `ColumnPtr` before deserializing into it.
`IColumn::mutate(std::move(column))` for the `popBack` then saw the extra
owner still held by `block_for_reading`, cloned the filled column, and the
`popBack` reset landed only on the throwaway clone. The scratch column kept
the just-read rows, so the next granule started with stale rows and
`insertRangeFrom` copied the previous granule's values again, corrupting the
`set` skip index granules (and producing `Array elements column is longer
than the last offset` for array set indexes).

Bind `column` to the holder by reference instead of copying. With a single
owner, `IColumn::mutate` is a genuine no-op (no clone, no regression) and the
write-back resets the reusable scratch column for the next granule, exactly
preserving the previous in-place behaviour.

Fixes the Fast test failures: 00965_set_index_string_functions,
00997_set_index_array, 01576_alias_column_rewrite,
02346_exclude_materialize_skip_indexes_on_insert/merge, 03033_set_index_in,
03356_array_join_subcolumns_indexes, 03374_indexes_with_literals,
03374_indexes_with_trivial_cast, 03734_has_function_key_condition_skip_index,
04027_set_index_or_non_indexed_column,
04143/04144_skip_index_after_alter_modify_column,
04201_set_index_in_subquery_disabled_fallback,
04290_set_index_is_true_false_unknown.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
`tryRerangeRightTableDataImpl` called `IColumn::mutate(std::move(...))` inside
the per-row, per-column append loop. Even in the common uniquely-owned case,
`mutate` is not a free alias for `assumeMutableRef`: it performs the COW
refcount transition and recursively deep-mutates subcolumns on every call. Per
single `insertFrom` cell that contradicts the sweep's "same cost" contract and
can dominate the reranging hot path for large right tables.

Detach all destination columns once into `MutableColumns` before the row loop
(COW-safe: clones only if shared), append every row through those mutable
handles, then move them back. Correctness is unchanged: the source columns
(`it->columns_info`) are a distinct accumulator from the destination, so there
is no aliasing across the hoist.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Comment thread src/Storages/VirtualColumnUtils.cpp Resolved
@alexey-milovidov

Copy link
Copy Markdown
Member Author

@groeneai, fix 03001_consider_lwd_when_merge and send a PR.

@groeneai

Copy link
Copy Markdown
Collaborator

@alexey-milovidov on it — investigating 03001_consider_lwd_when_merge and will send a separate PR. CIDB diagnosis on this PR's Stateless tests (amd_tsan, s3 storage, parallel, 2/2) run: reproducible 2/2 with the randomized settings, passes 29/29 without, minimizer culprit = --index_granularity 1. The merge-selector byte thresholds in the test (80000 bytes) get blown past by the per-row marks/primary-index overhead at granularity 1, so the final OPTIMIZE that should merge fails with CANNOT_ASSIGN_OPTIMIZE. Confirming locally and will pin the culprit setting.

…lumn filtering

`getFilterByPathAndFileIndexes` calls `addPathAndFileToVirtualColumns` once per
listed file/object, and the COW-safe rewrite made that helper detach `_path`,
`_file`, the hive columns, and `_idx` via `IColumn::mutate` for every single
appended row. `IColumn::mutate` recursively re-wraps subcolumns through
`forEachMutableSubcolumn` even when the top-level column is uniquely owned, so
`LowCardinality` virtuals such as `_path`/`_file` paid repeated copy-on-write
plumbing on large object-storage listings before pruning.

Detach the block columns once via `Block::mutateColumns` around the `paths`
loop, append every row through the resulting mutable holders, and reattach
them once with `Block::setColumns` before `filterBlockWithExpression`. The
per-row inserts are unchanged; only the per-row `mutate` is removed.

Addresses review feedback on #107457

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

Copy link
Copy Markdown
Collaborator

@alexey-milovidov done: #107812. Root cause was randomized index_granularity (the runner draws from [1, 65536]); at small values the per-granule marks/primary.idx overhead inflates the part's bytes_on_disk well past the test's 80000-byte merge thresholds, so the final OPTIMIZE that must succeed fails with CANNOT_ASSIGN_OPTIMIZE. Fix pins index_granularity = 8192 in the CREATE TABLE; passes 50/50 over randomized granularity. (This PR's amd_tsan s3 failure was the same test; rebasing onto #107812 once it merges will clear it.)

@clickhouse-gh

clickhouse-gh Bot commented Jun 18, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.20% 85.20% +0.00%
Functions 92.30% 92.30% +0.00%
Branches 77.40% 77.40% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 92/105 (87.62%) | Lost baseline coverage (was covered on master, now uncovered in this PR): 6 line(s) · 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.

Very good.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-not-for-changelog This PR should not be mentioned in the changelog 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.

3 participants