Skip to content

Add assertions in IColumn::mutate to verify deep unique ownership of sub-columns - #100185

Merged
alexey-milovidov merged 253 commits into
masterfrom
assert-cow-ownership-in-mutate
Nov 20, 2026
Merged

alexey-milovidov merged 253 commits into
masterfrom
assert-cow-ownership-in-mutate

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Mar 20, 2026 •

Copy link
Copy Markdown
Member

Investigation for #99920

This is a draft PR with diagnostic assertions to help find a COW violation bug where columns stored in HashJoin have their allocatedBytes() change because internal sub-columns are modified by someone who treats immutable columns as mutable.

What was found

The bug manifests as data->allocated_size != debug_allocated_size exception in debug builds. Investigation narrowed it down to:

  1. Removing the single-chunk optimization in Squashing.cpp:70-72 fixes the bug — this optimization passes chunks through without IColumn::mutate, so columns remain shared with Memory engine blocks
  2. The modification happens between addBlockToJoin calls — during pipeline processing of the next chunk
  3. The mutation is a reallocation (reserve/grow), not a data write — protect() (mprotect) doesn't catch it
  4. The assertions in this PR (IColumn::mutate deep ownership check) do NOT fire — meaning the mutation happens outside the IColumn::mutate path entirely. Someone treats an immutable column as mutable without going through mutate.

Reproducer

The test 04049_fix_hashjoin_shared_column_allocated_size reproduces the exception in debug builds.

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):

...

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Workflow [PR]
Sync PR [sync-upstream/pr/100185]

Version info

  • Merged into: 26.12.1.23-master (included in 26.12 and later)

@clickhouse-gh

clickhouse-gh Bot commented Mar 20, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [8c8b466]

Summary: ✅


AI Review

Summary

The PR adds ownership assertions to COW::assumeMutable and COW::assumeMutableRef, verifies deep ownership after IColumn::mutate, and adjusts column factories, filtering, deserialization, and remote block adaptation to respect those checks. Reviewed the full diff and current code at 8c8b4667233b56293f8edaa4e35205dd5b69393c, including all prior discussion. No new actionable findings remain; previously discussed borrowing and decompression tradeoffs are explicitly accepted by the author. Fast test passes, including 04049_fix_hashjoin_shared_column_allocated_size.

Missing context / blind spots
  • ⚠️ Debug/sanitizer builds and the broader test jobs for the current head are still pending. No local build or test binaries are available; completion of the existing CI jobs will provide the remaining runtime validation.
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 Mar 20, 2026
Comment thread src/Columns/IColumn.h Resolved
Comment thread src/Columns/IColumn.h Resolved
@alexey-milovidov
alexey-milovidov force-pushed the assert-cow-ownership-in-mutate branch from 8a94b4e to 1f89ce7 Compare March 20, 2026 11:09
alexey-milovidov and others added 3 commits March 22, 2026 12:12
…exSet

- ProtobufSerializer: Add `columnRef()` helper using `const_cast` for
  deserialization columns that are borrowed from the caller. Replace all
  `column->assumeMutableRef()` calls with `columnRef()`. Replace
  `presence_column` MutableColumnPtr with raw pointer to avoid extra ref.
- MergeTreeIndexSet: Move column from block before using `assumeMutableRef`
  to ensure use_count == 1, then move it back afterward.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…columns

Add a free function `borrowColumnRef` to centralize the `const_cast`
pattern for columns that are borrowed from the caller for mutation during
deserialization. Use it consistently across Nullable, LowCardinality,
Array, Tuple, and OneOf serializers.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
- SerializationDynamicElement.cpp: Replace `MutableColumnPtr` copy
  (deleted constructor) with raw `IColumn *` pointer for the
  `non_nullable_variant_column` alias.
- Remove extra blank lines in ColumnArray.cpp and ColumnNullable.cpp.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Comment thread src/Common/COW.h Resolved
alexey-milovidov and others added 3 commits March 22, 2026 13:30
Use `shallowMutate` instead of `IColumn::mutate` in column
`create(const ColumnPtr&)` methods and temporary wrapping patterns.

`IColumn::mutate` does deep recursive sub-column mutation which breaks
column invariants (e.g. ColumnLowCardinality dictionary/index relationship,
ColumnDynamic cached pointers). `shallowMutate` creates a shallow clone
when shared (use_count > 1) or returns the same object when unique,
preserving sub-column sharing which is the intended behavior for these
immutable composite column creation patterns.

Also make `COW::shallowMutate` public so it can be called on sub-columns
from static `create` methods.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Replace `shallowMutate` with `assumeMutableForCreation` in column
`create(const ColumnPtr&)` methods. `shallowMutate` clones when
use_count > 1, but these methods are designed to share sub-columns
(not clone them). The cloning broke column invariants, causing SIGSEGV
in arrayResize with Dynamic types.

`assumeMutableForCreation` is a simple type conversion (like the original
`assumeMutable`) without the use_count assertion, explicitly intended
for creating immutable composite objects from shared sub-objects.

Also fix redundant `public:` access specifier in COW.h (clang-tidy).

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…create methods

The `assumeMutableForCreation` method was a backdoor that defeated the
purpose of the assertion. Restore the original `assumeMutable` calls in
`create(const ColumnPtr&)` methods. Any assertion failures from shared
columns will point to the actual callers that need fixing — they should
either pass uniquely-owned columns or clone via `shallowMutate` first.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Comment thread src/Columns/ColumnArray.cpp Resolved
Comment thread src/Columns/ColumnArray.cpp Resolved
…ements

The previous refactoring accidentally replaced `IColumn::mutate` (which
clones shared offsets) with `assumeMutable` (which shares them) for all
tuple iterations. This corrupted data: the first iteration's in-place
filter modified the shared offsets, breaking subsequent iterations.

Restore the original logic: clone offsets for all iterations except the
last one.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
alexey-milovidov and others added 4 commits March 24, 2026 00:31
- Guard the diagnostic sub-column traversal in `IColumn::mutate` with
  `#if defined(DEBUG_OR_SANITIZER_BUILD)` so release builds do not pay
  the cost of walking nested subcolumns for no effect.
- Restore `assumeMutableRef` calls in `chameleon_ptr` mutable accessors
  instead of raw `const_cast`, keeping the uniqueness check on mutable
  access so COW violations are still detected in debug/sanitizer builds.
- Fix typo: `subolumn` → `subcolumn` in `SerializationDynamicElement.cpp`.

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

Copy link
Copy Markdown
Member Author

The flaky failure of 02494_query_cache_http_introspection in this PR's CI is addressed by #102165.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

The flaky check failure is fixed in #102148, let's update the branch.

Comment thread src/Common/COW.h Resolved
The prior refactor inadvertently widened `COW::shallowMutate` from
`protected` to `public`, exposing a shallow-only mutation primitive
that bypasses deep unsharing of nested `WrappedPtr` sub-columns that
`IColumn::mutate` relies on for COW safety.

Since this PR strengthens COW diagnostics, the widened API surface
goes in the opposite direction. Restore `shallowMutate` to `protected`
and keep `mutate`/`assumeMutable`/`assumeMutableRef` `public`, matching
the original structure while preserving the new `chassert(use_count == 1)`
in `assumeMutable` and `assumeMutableRef`.

Addresses review feedback on #100185.
alexey-milovidov and others added 4 commits November 10, 2026 05:10
…em per row subgroup

`IColumn::mutate` on the dictionary values, which are still owned by the column chunk,
cloned the whole dictionary for every row subgroup. Use the immutable
`ColumnReplicated::create` overload that shares the values, as before the change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…oryLimit` independent of test order

The test relied on the calling thread having no `ThreadStatus`, so that every
allocation goes straight to `total_memory_tracker` and hits the clamped limit.
Other tests (e.g. `AllocationInterceptors.*`) call `MainThreadStatus::getInstance`,
after which small allocations on the main thread are deferred as untracked memory
and never reach the limit, so no exception is thrown and the test fails with
`error_code == 0`. This happened in `Unit tests (amd_debug)` of the private sync
PR ClickHouse/clickhouse-private#53091, where the tests run
in a different order. It reproduces locally with `--gtest_shuffle`.

Run the part under the memory limit in a separate `std::thread`, which has no
`ThreadStatus`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 On 15bf9b8, the public CI was green. The only red check was CH Inc sync (tests failed) in https://github.com/ClickHouse/clickhouse-private/pull/53091:

  • Unit tests (amd_debug): ColumnUnique.NullableViewIsRestoredWhenItsReconstructionHitsMemoryLimit failed with error_code == 0. This PR causes it: the test depends on the order in which tests run. It assumed the calling thread has no ThreadStatus, so that every allocation goes straight to total_memory_tracker. In the private binary, AllocationInterceptors.* runs first and calls MainThreadStatus::getInstance. After that, small allocations are deferred as untracked memory and never hit the clamped limit, so no exception is thrown. It reproduces locally with --gtest_shuffle. 9a251b7 runs the memory-limited part in a separate std::thread without a ThreadStatus. The test now passes in 30 of 30 shuffled runs together with AllocationInterceptors.*.
  • 05345_hash_join_row_store_strings (amd_debug and amd_release): TOO_MANY_ROWS while scanning system.text_log. This PR does not cause it. Master fixed it in Filter system.text_log by event_time in tests #130490, so I merged master (7128a74) to pick that up. The merge had no conflicts, and clickhouse and unit_tests_dbms build locally.
  • 05303_json_shared_typed_paths_s3 hit the 600 s timeout in amd_msan. This PR does not cause it. Its per-job durations on this PR match master, and on master it already takes a median of 260 s (up to 439 s) in msan jobs.

# Conflicts:
#	src/Storages/MergeTree/MergeTreeReaderWide.cpp
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 On 7128a74, the only failures were the six Performance Comparison (arm_release, master_head, N/6) jobs. They did not run any test: test selection failed with GitHub API 403 Client Error: rate limit exceeded (https://s3.amazonaws.com/clickhouse-test-reports/PRs/100185/7128a749220a9e5ee503ebe71049542ae5f60067/pr/performance_comparison_arm_release_master_head_1_6/job.log), so this is an infrastructure problem, not this PR.

I merged master (41fb22b) to re-run CI. It had a conflict in MergeTreeReaderWide::accumulateRowsForColumnsCache. I kept the ensureOwnership call from this PR and the new reserve sizing from master. All the translation units this PR changes, and its column gtests, compile.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 On 41fb22b, the public CI was green. The only red check was CH Inc sync (conflicts found): private master had changed the reserve call in MergeTreeReaderWide::accumulateRowsForColumnsCache, right next to the ensureOwnership call this PR adds there. I merged private master and this PR's head into sync-upstream/pr/100185, keeping both changes. The resolved file is identical to the public PR head, and the sync PR diff matches this PR's diff exactly. The sync PR is MERGEABLE now and private CI is rerunning.

…p-in-mutate

# Conflicts:
#	src/QueryPipeline/RemoteQueryExecutor.cpp

@clickhouse-gh clickhouse-gh Bot 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.

AI review approves this commit, see the AI Review comment.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Status on 40159aa:

@groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=100185&sha=40159aa954e556bc4f1b1188e2aaed3b560ad18e&name_0=PR&name_1=Performance%20Comparison%20%28arm_release%2C%20master_head%2C%205%2F6%29 (server killed silently during jit_aggregate_functions, no stack trace) and provide a fix in a separate PR. If the fix is already in progress, link it here.

@groeneai

Copy link
Copy Markdown
Collaborator

Acknowledged. I'm investigating the silent right-server death in Performance Comparison (arm_release, master_head, 5/6) during jit_aggregate_functions (query 292); I'll follow up here with a PR (or my findings) shortly.

@groeneai

Copy link
Copy Markdown
Collaborator

Follow-up on the Performance Comparison (arm_release, master_head, 5/6) failure: it is not caused by this PR.

  • It is a new ARM-only problem: since 2026-11-15 a perf server died silently in 6 ARM runs (0 from 2026-10-07 to 2026-11-14, 0 on amd), on PRs and on master, and the dead server is the master reference binary in two of them (master, 1, 2, 3, 4). Not tied to JIT: three of the dead servers never compiled an expression. Not OOM: 4.4 GiB resident, 50 GiB available. Every death I could place is at or right before a prewarm0 run, the only run with the query profilers enabled.
  • There is no trace because the watchdog loses it: it logs Child process was terminated by signal N and calls _exit on the next line, while that line is still queued in the asynchronous logger. Do not lose the watchdog's log line about how the server process ended #132409 makes the watchdog log synchronously, so the next death names its signal.
  • Merged right before the first death: Use clang-23 #117346 (clang and LLVM 23) and Isolate the filesystem of the server at startup #128412 (filesystem isolation); the ARM runners also moved to kernel 6.8.0-1069 about a day earlier. I could not reproduce it (no aarch64 host), so I am not proposing a revert yet; once a death names its signal I will follow up here with the cause or the revert.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Thanks @groeneai for tracing the Performance Comparison (arm_release, master_head, 5/6) failure. Since 2026-11-15 the server has been dying silently on ARM perf runs on master and on other PRs, so this PR does not cause it. #132409 will make the watchdog log the signal, so the next occurrence can be diagnosed. Please follow up in a separate PR with the cause or a revert once a death names its signal.

I merged the latest master (95bfedb) to re-run CI. The merge had no conflicts and clickhouse builds locally. On the sync PR, the only failed job on the previous head was one private-only test whose failure is in a metadata commit path that this PR does not touch. The new head re-runs it. There are no open review threads.

@groeneai

Copy link
Copy Markdown
Collaborator

The cause is already known, so this does not have to wait for #132409. It is return address signing (#131784, and #119685 before its revert) combined with the query profiler. Two cores of the same silent ARM death in other jobs show the chain (stress, master stateless):

  • A profiler sample lands in the outlined prologue of llvm::PassManager<Function>::addPass<InstCombinePass> during JIT compilation. That function is minsize, so the AArch64 backend emits only synchronous unwind info for it, and libunwind authenticates a return address that is not signed yet: autia1716 raises SIGILL.
  • signalHandler then faults again in its own stack capture while SIGILL is blocked, so the kernel kills the process before anything is logged.

The perf deaths fit: the dead binaries were built with return address signing, there were none on ARM from 2026-10-07 until the first enable, and every death I could place is at or right before prewarm0, the only run with the query profiler on. This one died right after it received query 292, whose first run JIT-compiles. The three that never compiled an expression presumably hit another window like this one. This replaces the suspects in my previous comment.

Fix: #132186. A SIGILL raised inside an asynchronous stack capture on AArch64 is now recovered, whichever frame raised it, so the sample is dropped and the server keeps running. The alternative is to revert return address signing, but #131784 no longer reverts cleanly on its own after #131996, so both would have to go.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Thanks @groeneai for identifying the cause of the silent ARM perf deaths: return address signing combined with the query profiler, fixed in #132186. That fix is independent of this PR.

The only red job on the previous head (26bf295) was Upgrade check (amd_release). It hit Logical error: 'Context has expired' in FunctionKQLMultiply::executeImpl, and the server that aborted was the old release 26.10.5.57, which ran the stress phase. The fix is #131363, and its backport #132081 shipped in 26.10.6.18 but not in 26.10.5.57. The other five failures in that job came after the abort (connection refused). So this PR does not cause it.

I merged the latest master (e3a18a7) to re-run CI, so the upgrade check now starts from a newer previous release. The merge had no conflicts. All translation units that both this PR and the new master commits touch compile locally (ColumnArray, ColumnObject, ColumnUnique, SerializationNullable, JSONExtractTree, FunctionHelpers, AvroRowInputFormat, Parquet/Reader, and the related gtests). There are no open review threads.

@stresshouse

stresshouse Bot commented Nov 20, 2026

Copy link
Copy Markdown

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 29 queries analysed

Release-transition baseline: compared against the most recent available 26.11 masters at or before the trusted base-commit anchor because no 26.12 master baseline exists there.

no significant changes detected. K_source=4 K_base=30 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: f09aaa8a-7e85-45f9-a9f5-8f333bf21733
  • MIRAI run: f14551dd-802a-48a8-9cdd-986cfd6f4ead
  • PR check IDs:
    • clickbench_447243_1795170006
    • clickbench_447249_1795170006
    • tpch_adapted_1_official_447287_1795170006
    • tpch_adapted_1_official_447308_1795170006

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

Labels

comp-data-types Type system & core datatypes used across query planning/execution. 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.

5 participants