Repository navigation
Add COW ownership sanity checks to the substreams cache and deserialize states - #110471
Conversation
…ze states The crash family tracked in issue #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 (#107451, #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: #105626 Co-Authored-By: Claude Fable 5 <[email protected]>
The first version of ColumnsOwnershipValidator walked the result columns with forEachSubcolumnRecursively, which descends into a shared interior column once per referencing parent. When one result block contains both a full column and its subcolumn sharing a nested column object (e.g. reading `t` and `t.m` of a `Tuple(m Dynamic)` with a Map value, as in 04074_map_dynamic_substreams_cache), the children of the shared object were counted once per path while only one member reference to them exists, producing a false positive. Walk the trees manually and descend into each column object only once: the reference TO a shared object is still counted once per referencing parent (each parent holds its own counted pointer), but the members of the single object are enumerated exactly once. Also split the enumerated references by holder kind (substreams cache, deserialize states, direct, result columns) and print the breakdown in the failure message to make CI reports actionable. Co-Authored-By: Claude Fable 5 <[email protected]>
|
Workflow [PR], commit [67fa63b] Summary: ✅
AI ReviewSummaryThis PR adds debug/sanitizer-only Final Verdict✅ No new inline findings on the current revision. |
|
I want to hear from you about #110434 (comment) |
…REAM data column `deserializeBinaryBulkWithSizeStream` cached the `Regular` substream (the `ColumnString` data) under `num_read_rows = rows_offset + limit`, but the column itself only grows by `limit` rows in this call — the `rows_offset` rows are only skipped over in the data stream, never inserted into `column`. A later cache hit for the same range (`insertDataFromCachedColumn`) computes `cached_column->size() - num_read_rows`, which underflows once `rows_offset > 0`, driving `insertRangeFrom` out of bounds. This is exactly the class of bug `ColumnsOwnershipValidator`'s new chassert in `addColumnWithNumReadRowsToSubstreamsCache` is meant to catch (#105626), and it caught this one: `StringSerialization.WithSizeStreamFaithfulRoundTripIsConsistent` started failing with `Logical error: 'column->size() >= num_read_rows'` once `rows_offset > 0`. Cache the data column under `num_read_rows - rows_offset`, matching the convention used by every other caller of `addColumnWithNumReadRowsToSubstreamsCache` (`column->size() - prev_size`, i.e. the actual row growth in this call).
…izeStateSparse Two coverage gaps in ColumnsOwnershipValidator flagged by review: - `validate` only walked subcolumn trees reachable from `res_columns`, so a column held only by a substreams cache or a deserialize state contributed just its own root reference, never the references its own members hold. A cached `ColumnMap`'s `offsets`/nested column can be shared with a `map.keys`/`map.values` subcolumn materialized by `IDataType::getSubcolumn` into the result columns; the cache side of that shared child was invisible to the validator, so dropping the cache could still free it without tripping the check. Walk from every `known_references` root as well; `walk`'s `visited` set still descends into any given column object once, and the root's own reference is already counted via `known_references`. - `DeserializeStateSparse` (used by `SerializationSparseNullMap`) holds a `column_offsets` `ColumnPtr` but did not override `forEachColumn`, so `ColumnsOwnershipValidator::add(DeserializeBinaryBulkStatePtr)` silently saw zero references for it. Verified with the ASan build: 04074_map_dynamic_substreams_cache.sql and 03792_sparse_offsets_in_substreams_cache_compact_part.sql pass unchanged, and StringSerialization.* unit tests still pass.
|
📊 Cloud Performance Report ✅ AI verdict: no significant changes detected. K_source=6 K_base=26 flagged=0/65 clickbench🟢 No significant changes tpch_adapted_1_official🟢 No significant changes Debug info
|
Both were found by the AI review on the sync PR: 1. `ColumnLowCardinality::forEachSubcolumn` intentionally hides the dictionary when it is shared, but the column still holds a counted reference to it, and a shared dictionary is exactly the place where broken COW reference counting turns into a use-after-free. Enumerate such dictionaries explicitly in the subcolumn-tree walk, so under-counted references on a shared dictionary are detected (e.g. after `SerializationLowCardinality` shares `global_dictionary` with the result column). 2. `ColumnsOwnershipValidator::add` only visited a state's own `forEachColumn`, so columns owned by deserialize states nested inside composite states stayed invisible: e.g. for `Variant(LowCardinality(String))`, the `LowCardinality` state holding `global_dictionary` is stored inside the `Variant` state and is never registered in a `SubstreamsDeserializeStatesCache`. Add a `forEachNestedState` enumeration to `DeserializeBinaryBulkState`, implement it in all composite states (`Variant`, `Dynamic`, `Tuple`, `Map`, `Object` and their subcolumn serializations, `Sparse`), and recurse in the validator; the `seen_states` set already guarantees each state is enumerated only once even when it is reachable both from a cache and from a parent state.
…es and nested states The test reads `LowCardinality(String)`, `Variant(LowCardinality(String), UInt64)` (the whole column, element subcolumns and an element null map together, to engage the substreams cache) and `Tuple` with a `LowCardinality` element from both Wide and Compact parts. In debug and sanitizer builds this exercises the `ColumnsOwnershipValidator` traversal of shared `LowCardinality` dictionaries and of deserialize states nested inside composite serializations.
`DeserializedStateProductQuantization` in `SerializationQuantizedVector` holds the part's one-row `codebook` column, and the result column is a `ColumnConst` wrapping that very same column. The state never exposed the `codebook` via `forEachColumn`, so `ColumnsOwnershipValidator` only saw the result-side reference: if the state side were the under-counted holder, the validator would miss the use-after-free it is meant to catch. Add a `forEachColumn` override to `DeserializedStateProductQuantization` so the `product_quantization_codebook` read path participates in the ownership validation too. Existing tests such as `02354_vector_search_quantize_codec_pq` already read this subcolumn and exercise the path under sanitizer/coverage builds. Addresses the AI review finding on #110471 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Extract the two `ColumnsOwnershipValidator` passes that `MergeTreeReaderCompactSingleBuffer::readRows` runs at the end of a granule into a single protected `MergeTreeReaderCompact::validateColumnsOwnership` helper on the base class, removing the duplication between the subcolumn and full-column checks. Besides de-duplicating, this gives both compact readers one shared entry point so their granule loops stay instrumented identically. Only `MergeTreeReaderCompactSingleBuffer` exists in this repository; the reusable hook lets the multi-buffer compact reader run the very same check without copy-pasting the logic. Every cache argument is optional so a reader passes `nullptr` for caches it does not keep alive at the check point; the per-reader deserialize-state maps are always included. The body stays behind `DEBUG_OR_SANITIZER_BUILD` and the method is a no-op in release. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…dator Address review: the ownership validator was only wired into the `MergeTree` readers, but two other read paths use the same substreams-cache / deserialize-state lifetime pattern and drop those holders while result columns escape, so a broken copy-on-write reference count on a shared child could still turn into a use-after-free there without ever tripping the validator (issue #105626). - `LogSource::fillPhysicalColumns` (`Log` engine): `getCacheKey` deliberately shares a single `SubstreamsCache` across the subcolumns of a `Nested` group (shared array offsets), and the local caches die at the end of the function. Validate the result columns against those caches, the deserialize-state caches and the member deserialize states before they go out of scope. - `SerializationObjectSharedData::deserializePathsData`: the local `cache_for_subcolumns` / `deserialize_states_cache` of a shared-data path (and the per-subcolumn deserialize states) are dropped right after populating `paths_subcolumns_data`, before the outer `SubstreamsCachePathsDataElement` that later holds the produced subcolumns is created. Validate the just-produced path subcolumns against those holders at that earlier destruction point. Both blocks are compiled in only for debug and sanitizer builds and are a no-op in release. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Exercises the two newly-covered destruction points of `ColumnsOwnershipValidator` under debug and sanitizer builds: shared `Nested` array offsets read as subcolumns from a `Log` table (`LogSource::fillPhysicalColumns`), and typed subcolumns of shared-data `JSON` paths in a Compact part (`SerializationObjectSharedData::deserializePathsData`). The queries only need to run without tripping the validator. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Zero-level parts use the `map_with_buckets` shared-data serialization by default, whose read path does not go through `SerializationObjectSharedData::deserializePathsData`. Set `object_shared_data_serialization_version_for_zero_level_parts = 'advanced'` on the table so the inserted parts use the ADVANCED serialization and the newly-instrumented `requested_paths_subcolumns` destruction point is actually exercised. Query results are unchanged, so the reference is unaffected. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
… with the ownership validator The `requested_paths` branch of `SerializationObjectSharedData::deserializePathsData` deserializes a whole shared-data path through a local `path_state` that is dropped right after the produced column is moved into the granule data, before the outer `SubstreamsCachePathsDataElement` that later covers the column is created — the same early destruction point the sibling `requested_paths_subcolumns` branch already validates. The state can hold column references through nested states (e.g. nested `Object` content of the path values exposed via the new `forEachColumn` hooks), so an under-counted reference would be released there without the validator ever seeing it. Add the same `ColumnsOwnershipValidator` pass over `path_state` and the just-produced column, and a test that reads whole shared-data paths holding arrays of nested `JSON` objects (so the dynamic serialization builds nested `Object` states) under `advanced` shared-data serialization, plus a mixed whole-path + typed-subcolumn query so both branches run in one `deserializePathsData` call. Verified under an ASan build: the new test and the substreams-cache regression tests (04549, 04551, 04074, 03792, 03207, 03036 families) all pass with no validator hits. Co-Authored-By: Claude Fable 5 <[email protected]>
… in the ownership validator When the `DeserializationPrefixesCache` is enabled, `getOrSet` keeps the original prefix states in the cache and hands the reader clones (`clonePrefixes`) that share the same column references — e.g. a single-part `LowCardinality` `global_dictionary`, including one held by a `LowCardinality` state nested inside a `Variant` state. The cached originals are extra live holders, but `ColumnsOwnershipValidator` only saw the reader-local clones, so on prefix-cached reads an under-counted reference on a clone could keep `use_count()` looking consistent and hide the very bug family this PR is meant to surface. Add `DeserializationPrefixesCache::addToOwnershipValidator`, which enumerates the retained originals read-only (without cloning them), and feed them into the validator from both `MergeTreeReaderWide::readRows` and `MergeTreeReaderCompact::validateColumnsOwnership`. A no-op in release builds.
…xes cache Reads a Wide part with a single-dictionary `LowCardinality` column and a `Variant(LowCardinality(String), UInt64)` column through the deserialization prefixes cache, exercising `ColumnsOwnershipValidator` over the cache-held prefix states and their shared dictionaries (including the dictionary of a `LowCardinality` state nested inside a `Variant` state).
…refix-cache clone `DeserializationPrefixesCache` is only safe if every reader mutates a private clone of the cached prefix state. `DeserializeBinaryBulkStateSubObjectSharedData::clone` deep-cloned `bucket_map_states` and `bucket_structure_states` but copied the nested `map_state` by pointer, so on the `MAP` shared-data path every clone shared one `map_state` with the cached original. `deserializeBinaryBulkWithMultipleStreams` mutates that state via `serialization_map->deserializeBinaryBulkWithMultipleStreams`, so a prefix-cached read of an existing / compatibility `object_shared_data_serialization_version = 'map'` part could reuse an already advanced state or race across concurrent readers. Clone `map_state` like the sibling states, matching the parent `DeserializeBinaryBulkStateObjectSharedData::clone`. Add `04615_substreams_prefix_cache_map_shared_data_subobject`: a concurrent, prefix-cached `json.^a` sub-object read (whole JSON and a JSON nested in a Tuple) over a `map`-serialized part, asserting it matches the single-threaded read that does not use the cache.
…se with a focused test The release-active fix in this PR caches the `WITH_SIZE_STREAM` data column under `num_read_rows - rows_offset` (its true row growth) instead of `num_read_rows`. The existing `WithSizeStreamFaithfulRoundTripIsConsistent` gtest reads a seeked range once with a null cache, so it never populates or reuses a cache entry and cannot regress this. Add `StringSerialization.WithSizeStreamRowsOffsetSubstreamsCacheReuse`: it first reads a `rows_offset > 0` subrange through a real `SubstreamsCache`, then serves the same range from the cache with `insert_only_rows_in_current_range_from_substreams_cache` set, which inserts `num_read_rows` rows off the tail of the cached column. With the over-count this underflows `cached_column->size() - num_read_rows` and drives `insertRangeFrom` out of bounds; with the fix the range is served correctly.
…mic::clone `DeserializeBinaryBulkStateDynamic::clone` deep-cloned `variant_state` and `structure_state` but copied `flattened_indexes_state` and every entry of `flattened_states` by pointer (via the copy constructor). On the `FLATTENED` serialization path those nested states are mutated while reading the indexes and each flattened type, so any caller that clones a state and reuses the originals - most notably `DeserializationPrefixesCache::clonePrefixes` - would hand out clones that share mutable state with the cached original, exactly the class of bug fixed for `map_state` in `DeserializeBinaryBulkStateSubObjectSharedData::clone`. Deep-clone them here so `clone` produces a fully independent copy, consistent with the other nested states. In practice `FLATTENED` is a Native-format-only serialization (see `SerializationDynamic.h`; MergeTree parts only ever use the `v1`/`v2`/`v3` versions of `MergeTreeDynamicSerializationVersion`) and the prefixes cache is a MergeTree-only construct, so a `FLATTENED` state never reaches `clone` today; this keeps `clone` a correct deep copy regardless. See #105626. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The test timed out (> 180s) under the randomized stateless settings because it inserted 40000 rows and then forced many tiny concurrent reads (`merge_tree_min_rows_for_concurrent_read = 1`, `max_block_size = 100`). Reduce both tables to 4000 rows and set a small `index_granularity = 128` so the part still has many granules read concurrently by several threads through the shared prefix state (which is what exercises the shallow-clone regression under TSan and the ownership validator), while the query cost drops by an order of magnitude. The number of distinct `a.*` sub-objects is `lcm(5, 7, 13) = 455`, so with 4000 > 455 rows the `uniqExact` assertion is unchanged. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
At `max_block_size = 100` over the (already reduced) part the concurrent read spends most of its time in per-block prefix-cache and shared-data setup rather than exercising the regression. Raising it to 256 keeps several blocks per thread (so a reader still does multiple sequential reads through the shared prefix state) and the 8-way concurrency intact, while the whole test now runs in a few seconds instead of well over a minute. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
The That is expected: those tests exercise the debug/sanitizer-only The two genuinely release-active fixes in this PR do not have a stable, deterministic functional regression test:
Per the established resolution for this gate (see PR #108033), I reclassified the changelog category from If you prefer to keep |
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 120/286 (41.96%) · Uncovered code |
alexey-milovidov
left a comment
There was a problem hiding this comment.
Reviewed. I think this will help.
Master gained a style check on 2026-07-27 (PR ClickHouse#110471) that rejects the wording "new analyzer" / "new query analyzer", because the analyzer has been enabled by default since 24.3. The branch was style-clean when the test was written; merging master surfaced the violation on the one comment line that used the old wording. Comment text only. Stripping the comment lines leaves the executable statements byte-identical, and the test has no echo directive, so the query text never reaches the output and the reference file is unchanged. "only supported by the analyzer" is the wording master already uses in seven other stateless tests.
Master gained a check-style rule on 2026-07-27 (PR ClickHouse#110471, ci/jobs/scripts/check_style/various_checks.sh) that rejects the phrases "new analyzer" and "new query analyzer": the analyzer has been enabled by default since 24.3 and is no longer new. Two comment lines in this test used that wording. They were style-clean when written; the rule arrived on this branch with a master merge, which is why Style check turned red without a change of ours. Comment text only: no assertion, setting or query is touched, so the byte-count assertions the test makes are unaffected. The "old analyzer" wording in the same paragraph is not covered by the rule (its pattern requires a leading "new") and remains the accepted term on master. Reverting either changed word alone reproduces one of the two reported lines, and reverting both reproduces the CI output verbatim; driving check_style.py's check_other over the tree reports OK after the change.
…QueryConditionCache` signature The master merge brought `ClickHouse#110471`, which added two parameters to `MergeTreeDataSelectExecutor::filterPartsByQueryConditionCache`: `top_k_filter_info` and `indexes`. Our re-trim helper still called it with six arguments, so `Build (arm_tidy)` failed with "too few arguments to function call, expected 8, have 6" and `Fast test` failed as a consequence. Both new parameters are `ReadFromMergeTree` members, and both are forwarded here exactly as the regular consult path in `selectRangesToRead` forwards them. That matters for correctness rather than only for compilation: skip-index exclusions are stored under a cache key salted with the effective skip-index profile via `getSkipIndexProfiledConditionHash`, and, on the WHERE path, with the TopK parameters. Passing a default-constructed `Indexes` or an empty `top_k_filter_info` would still compile while making every lookup miss, silently reverting the regression this pull request fixes. `indexes` is known to be non-empty at the call site, which already guards on `indexes.has_value()`. Verified both directions on a memory-capped local server, with the running server's `buildId` checked against the binary each time: with the re-trim enabled, `04342_query_condition_cache_join` reports a warm-run cache hit and zero rows read; with the re-trim disabled it reports no hit, so the argument values do produce real cache hits. The two guard tests `04344_query_condition_cache_join_parallel_replicas` and `04345_query_condition_cache_join_unique_key` pass, and the server logs no abort. A sweep of all 28 `query_condition_cache` stateless tests shows no new failure: the only two that fail do so identically with our source reverted to the merge base, because the minimal local server lacks the `CLICKHOUSE_DATABASE_1` substitution and the `test_cluster_one_shard_two_replicas` cluster that those two tests require.
The `various` style sub-check gained an analyzer-wording rule on master (2026-07-27, PR ClickHouse#110471): it rejects "new analyzer" because the analyzer has been enabled by default since ClickHouse 24.3. The comment in `04327_single_argument_or_in_join_on.sql` predates that rule, so merging master surfaced the violation and dropped all 151 downstream jobs. Comment text only; no assertion or statement changed.
`DeserializedStateProductQuantization` in `SerializationQuantizedVector` holds the part's one-row `codebook` column, and the result column is a `ColumnConst` wrapping that very same column. The state never exposed the `codebook` via `forEachColumn`, so `ColumnsOwnershipValidator` only saw the result-side reference: if the state side were the under-counted holder, the validator would miss the use-after-free it is meant to catch. Add a `forEachColumn` override to `DeserializedStateProductQuantization` so the `product_quantization_codebook` read path participates in the ownership validation too. Existing tests such as `02354_vector_search_quantize_codec_pq` already read this subcolumn and exercise the path under sanitizer/coverage builds. Addresses the AI review finding on ClickHouse#110471 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
The COW ownership validator added here segfaulted on master, inside its own check. Reporting it here since this PR owns that code; I have not pushed a fix because the mechanism is not proven and I would be guessing. Sighting: Where it dies: The part I cannot explain: Ruled out from source, in case it saves you time:
Fixture, if you want to chase it: the query read Two readings remain, and separating them needs runtime evidence I do not have: either one element was clobbered, or the map object itself was, in which case the real bug is an unrelated memory corruptor and this validator is only its first victim. The discriminator is an instrumented debug run logging User impact is zero, since the whole block is I did not open a PR because the two candidate fixes are a guard on the state before the dereference, which is a band-aid over whatever produced the bad word, and a corruptor fix I cannot yet point to. Happy to run the instrumented repro and report back if that is useful, or to leave it with you if you would rather harden the check. |
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes to CHANGELOG.md):
Add debug- and sanitizer-build-only ownership sanity checks (
ColumnsOwnershipValidator) to theMergeTreesubstreams cache and deserialization states to catch broken copy-on-write reference counting during reads (a no-op in release builds; see #105626). While developing them, two release-active data-corruption bugs inMergeTreereading were found and fixed. First, readingStringcolumns that use the serialization with a separate size stream (string_serialization_version = 'with_size_stream', the default since 25.11) when some leading rows are skipped recorded an incorrect number of rows in the substreams cache, which could lead to reading wrong data or an out-of-bounds read on a subsequent cache lookup. Second, reading a sub-object of aJSONcolumn stored withobject_shared_data_serialization_version = 'map'(used by older parts and compatibility mode) through the deserialization prefixes cache reused a prefix state that was cloned only shallowly, so concurrent readers could race on it and sequential re-reads could start from an already-advanced state, both yielding wrong data.Documentation entry for user-facing changes
Debug- and sanitizer-build diagnostics for the crash family tracked in #105626: SEGV in
CompressedReadBufferFromFile::readBigduring background merges, ASandouble-freeon reader stream buffers, andheap-use-after-freeon columns freed bySubstreamsCacheColumnWithNumReadRowsElementdestruction while still referenced byMergeTreeRangeReader.The investigation in that issue showed the root cause is 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::mutatesweeps (#107451, #109105) did not stop the family — verified by SHA ancestry of post-fix occurrences — because they defend against in-place mutation of shared columns, not against an under-counted reference.While writing the validator, it also surfaced two real release-active bugs. In the
Stringsize-stream serialization,deserializeBinaryBulkWithSizeStreamrecordednum_read_rowsinstead ofnum_read_rows - rows_offsetfor the data column in the substreams cache when leading rows were skipped, so a later cache lookup could take the wrong number of rows off the column's tail (wrong data or an out-of-bounds read). InSerializationSubObjectSharedData,DeserializeBinaryBulkStateSubObjectSharedData::clonedeep-clonedbucket_map_statesandbucket_structure_statesbut copied the nestedmap_stateby pointer, so on theMAPshared-data path the deserialization prefixes cache handed every reader a clone sharing one mutablemap_statewith the cached original — concurrent readers could race and sequential re-reads could start from an already-advanced state (map_stateis now deep-cloned like its siblings, matching the parentDeserializeBinaryBulkStateObjectSharedData::clone). Those two fixes are the only changes in this PR that are active in release builds; everything else below is a no-op in release.This PR turns those weekly flaky crashes into deterministic failures at the point where the inconsistency is still observable:
ColumnsOwnershipValidatorenumerates column references that provably exist — held by substreams cache elements, by deserialize states, and by the result columns with their subcolumn trees — and verifies thatuse_count()of each column covers all enumerated references. It runs at the end ofMergeTreeReaderWide::readRowsand per granule inMergeTreeReaderCompactSingleBuffer::readRows(through a reusableMergeTreeReaderCompact::validateColumnsOwnershiphelper), right before the substreams caches are dropped — which is exactly where the 2026-07-07 heap-use-after-free report from the issue shows the last reference being released. On violation it throwsLOGICAL_ERRORwith a per-holder-kind breakdown of the enumerated references (substreams cache / deserialize states / result columns), andLOGICAL_ERRORaborts with that message in debug and sanitizer builds — so the ASan CI shards where the family fires will pinpoint the broken path instead of crashing later in an unrelated place. The validator also runs at the earlier destruction points of short-lived caches and states: the end ofLogSource::fillPhysicalColumnsfor theLogengine family (where oneSubstreamsCacheis deliberately shared across the subcolumns of aNestedgroup), and both branches ofSerializationObjectSharedData::deserializePathsData— typed-subcolumn and whole-path reads of shared-dataJSONpaths under theadvancedserialization — where local caches and per-path deserialize states die before the outer cache element that later covers the produced columns is created.DeserializationPrefixesCacheis enabled, the reader operates on clones of the prefix states while the cache keeps the originals; both share the same column references (e.g. a single-partLowCardinalityglobal_dictionary). The originals are extra live holders, soDeserializationPrefixesCache::addToOwnershipValidatorenumerates them read-only (without cloning) and bothMergeTreeReaderWideandMergeTreeReaderCompact::validateColumnsOwnershipfeed them into the validator; otherwise an under-counted reference on a reader-local clone could stay invisible on prefix-cached reads.ColumnPtrowned by a structure of the current thread or by the shared prefixes cache (other threads can only makeuse_count()larger, never smaller than the enumerated count). The subcolumn trees are walked manually, descending into each column object only once — a column shared between several parents (e.g. a full column and its subcolumn in one result block) is counted once per referencing parent, but the members of the single shared object are enumerated exactly once.forEachColumnenumeration hooks onISerialization::ISubstreamsCacheElementandISerialization::DeserializeBinaryBulkState, implemented for all cache elements and states that hold columns: the column-with-num-read-rows element, the sparse offsets element, theObjectshared-data paths-data element, and theStringsize-stream/full-column,Variantelement and null-map,Dynamicelement,Objectdynamic/shared-data path,Mapkey-value andLowCardinalitystates. AforEachNestedStateenumeration on the states complements it: composite states (Variant,Dynamic,Tuple,Map,Objectand their subcolumn serializations,Sparse) hold the states of their nested serializations as members, and such a nested state is not necessarily registered in any states cache (SerializationLowCardinalitynever registers its state there), so the validator recurses through it; aseen_statesset guarantees each state — reachable from a cache, from a parent state, or from both — is enumerated exactly once, so references are never double-counted. The subcolumn-tree walk also enumerates sharedLowCardinalitydictionaries explicitly, whichColumnLowCardinality::forEachSubcolumnintentionally hides even though the reference is counted — a shared dictionary is exactly the place where broken reference counting turns into a use-after-free.chasserts of thecolumn->size() >= num_read_rowsinvariant at substreams cache insert and lookup and ininsertDataFromCachedColumn: its consumers computeinsertRangeFrom(*cached, size - num_read_rows, num_read_rows), which silently underflows if the invariant is broken (e.g. if a cached column is shrunk in place through another reference). The lookup-side check makes in-place mutation of a cached column visible at the first read after the mutation.Validated locally on a debug build: a smoke suite covering wide and compact parts, subcolumn reads of
Tuple/Array/Nested/Map/Variant/Dynamic/JSON/LowCardinality/sparse columns, merges and PREWHERE, plus 191 stateless tests matchingsubcolumn/substream— no validator hits (the only failures are environment ones: no ZooKeeper / predefined clusters in the local setup).Related: #105626