Skip to content

Add COW ownership sanity checks to the substreams cache and deserialize states - #110471

Merged
alexey-milovidov merged 23 commits into
masterfrom
substreams-cache-ownership-checks
Jul 27, 2026
Merged

alexey-milovidov merged 23 commits into
masterfrom
substreams-cache-ownership-checks

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Jul 15, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Improvement

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 the MergeTree substreams 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 in MergeTree reading were found and fixed. First, reading String columns 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 a JSON column stored with object_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

  • Documentation is written (mandatory for new features)

Debug- and sanitizer-build diagnostics for the crash family tracked in #105626: SEGV in CompressedReadBufferFromFile::readBig during background merges, ASan double-free on reader stream buffers, and heap-use-after-free on columns freed by SubstreamsCacheColumnWithNumReadRowsElement destruction while still referenced by MergeTreeRangeReader.

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::mutate sweeps (#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 String size-stream serialization, deserializeBinaryBulkWithSizeStream recorded num_read_rows instead of num_read_rows - rows_offset for 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). In SerializationSubObjectSharedData, 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 the deserialization prefixes cache handed every reader a clone sharing one mutable map_state with the cached original — concurrent readers could race and sequential re-reads could start from an already-advanced state (map_state is now deep-cloned like its siblings, matching the parent DeserializeBinaryBulkStateObjectSharedData::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:

  • ColumnsOwnershipValidator enumerates column references that provably exist — held by substreams cache elements, by deserialize states, and by the result columns with their subcolumn trees — and verifies that use_count() of each column covers all enumerated references. It runs at the end of MergeTreeReaderWide::readRows and per granule in MergeTreeReaderCompactSingleBuffer::readRows (through a reusable MergeTreeReaderCompact::validateColumnsOwnership helper), 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 throws LOGICAL_ERROR with a per-holder-kind breakdown of the enumerated references (substreams cache / deserialize states / result columns), and LOGICAL_ERROR aborts 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 of LogSource::fillPhysicalColumns for the Log engine family (where one SubstreamsCache is deliberately shared across the subcolumns of a Nested group), and both branches of SerializationObjectSharedData::deserializePathsData — typed-subcolumn and whole-path reads of shared-data JSON paths under the advanced serialization — where local caches and per-path deserialize states die before the outer cache element that later covers the produced columns is created.
  • When the DeserializationPrefixesCache is 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-part LowCardinality global_dictionary). The originals are extra live holders, so DeserializationPrefixesCache::addToOwnershipValidator enumerates them read-only (without cloning) and both MergeTreeReaderWide and MergeTreeReaderCompact::validateColumnsOwnership feed them into the validator; otherwise an under-counted reference on a reader-local clone could stay invisible on prefix-cached reads.
  • The check is designed to be free of false positives, including under concurrency: every enumerated reference is a live ColumnPtr owned by a structure of the current thread or by the shared prefixes cache (other threads can only make use_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.
  • New forEachColumn enumeration hooks on ISerialization::ISubstreamsCacheElement and ISerialization::DeserializeBinaryBulkState, implemented for all cache elements and states that hold columns: the column-with-num-read-rows element, the sparse offsets element, the Object shared-data paths-data element, and the String size-stream/full-column, Variant element and null-map, Dynamic element, Object dynamic/shared-data path, Map key-value and LowCardinality states. A forEachNestedState enumeration on the states complements it: composite states (Variant, Dynamic, Tuple, Map, Object and 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 (SerializationLowCardinality never registers its state there), so the validator recurses through it; a seen_states set 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 shared LowCardinality dictionaries explicitly, which ColumnLowCardinality::forEachSubcolumn intentionally 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 the column->size() >= num_read_rows invariant at substreams cache insert and lookup and in insertDataFromCachedColumn: its consumers compute insertRangeFrom(*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 matching subcolumn/substream — no validator hits (the only failures are environment ones: no ZooKeeper / predefined clusters in the local setup).

Related: #105626

alexey-milovidov and others added 2 commits July 14, 2026 23:55
…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]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 15, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [67fa63b]

Summary: ✅


AI Review

Summary

This PR adds debug/sanitizer-only ColumnsOwnershipValidator coverage around MergeTree/Log deserialization caches and fixes two release-active read-path bugs: incorrect String substreams-cache row accounting for rows_offset reads and shallow cloning of SerializationSubObjectSharedData's map_state. On the current head, the earlier validator coverage gaps and clone-depth issues are addressed, the new regression coverage now exercises the release-active String fix and the shared-data prefixes-cache path, and I did not find a remaining correctness, concurrency, or coverage issue that warrants a new review comment.

Final Verdict

✅ No new inline findings on the current revision.

@Avogar Avogar self-assigned this Jul 15, 2026
@Avogar

Avogar commented Jul 15, 2026 •

Copy link
Copy Markdown
Member

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

clickhouse-gh Bot commented Jul 16, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

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
  • StressHouse run: 8661b0d4-8269-465f-bc5b-1e94a45d755a
  • MIRAI run: ddbda2ca-43e0-41ec-a4f8-7030ad8cf2a3
  • PR check IDs:
    • clickbench_289940_1784980508
    • clickbench_289952_1784980508
    • clickbench_289959_1784980508
    • tpch_adapted_1_official_289970_1784980508
    • tpch_adapted_1_official_289996_1784980508
    • tpch_adapted_1_official_290010_1784980508

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.
alexey-milovidov and others added 3 commits July 17, 2026 06:07
`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]>
alexey-milovidov and others added 3 commits July 17, 2026 15:44
…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).
@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 18, 2026
@clickhouse-gh clickhouse-gh Bot removed the pr-not-for-changelog This PR should not be mentioned in the changelog label Jul 18, 2026
…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.
alexey-milovidov and others added 3 commits July 18, 2026 16:31
…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]>
@alexey-milovidov alexey-milovidov added pr-improvement Pull request with some product improvements and removed pr-bugfix Pull request with bugfix, not backported by default labels Jul 19, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member Author

The Finish Workflow job was red only because of the new_tests_check.py merge gate. With the Bug Fix category (label pr-bugfix) plus new functional tests, the gate requires at least one per-arch Bugfix validation job to confirm a new functional/integration test reproduces the bug on master HEAD. All four per-arch jobs came back SKIPPED — the functional ones reported "Bug does not reproduce on this arch — bugfix validation N/A" with Failed: 0, Passed: 5, i.e. the five new 0_stateless tests all pass on master HEAD.

That is expected: those tests exercise the debug/sanitizer-only ColumnsOwnershipValidator (they verify the validator does not misfire; they are not bug-reproducing regression tests), so they correctly pass on master. The gate deliberately does not credit the unit test when functional tests are present.

The two genuinely release-active fixes in this PR do not have a stable, deterministic functional regression test:

  • The String num_read_rows - rows_offset fix is proven by the gtest StringSerialization.WithSizeStreamRowsOffsetSubstreamsCacheReuse (reverting the fix fails it). Its only production trigger for rows_offset > 0 is the experimental text-index fallback reader (MergeTreeReaderTextIndex.cpp:476 is the sole non-zero readRows(..., rows_offset, ...) caller), so a plain-SQL functional reproduction would depend on experimental full-text index behavior.
  • The SerializationSubObjectSharedData map_state shallow-clone fix only manifests as a TSan data race; 04615 guards it via a deterministic-correctness assertion + TSan, not a single-thread failure.

Per the established resolution for this gate (see PR #108033), I reclassified the changelog category from Bug Fix to Improvement — the PR is predominantly a debug/sanitizer-only diagnostic — and rewrote the changelog entry so both data-corruption fixes remain fully documented for users. I then re-ran the failed jobs so the gate re-evaluates with the pr-improvement label (it now early-returns "Not a bug fix PR — skip").

If you prefer to keep Bug Fix, the alternative is to add a functional test that reproduces the String bug on master HEAD via the text-index fallback path (an experimental full-text index over a nested String column, read so the fallback consumes the substreams cache with rows_offset > 0) — happy to do that instead.

@clickhouse-gh

clickhouse-gh Bot commented Jul 26, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.20% 86.30% +0.10%
Functions 92.00% 92.00% +0.00%
Branches 78.40% 78.40% +0.00%

Changed lines: Changed C/C++ lines covered: 120/286 (41.96%) · 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.

Reviewed. I think this will help.

@alexey-milovidov alexey-milovidov self-assigned this Jul 27, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jul 27, 2026
Merged via the queue into master with commit 4d6dc82 Jul 27, 2026
351 of 353 checks passed
@alexey-milovidov
alexey-milovidov deleted the substreams-cache-ownership-checks branch July 27, 2026 20:50
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 27, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Jul 29, 2026
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.
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Jul 29, 2026
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.
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Jul 29, 2026
…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.
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Jul 29, 2026
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.
scanhex12 pushed a commit to scanhex12/ClickHouse that referenced this pull request Jul 29, 2026
`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]>
@groeneai

groeneai commented Aug 2, 2026

Copy link
Copy Markdown
Collaborator

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: AST fuzzer (amd_debug, targeted), 2026-07-31 18:58:53 UTC, ~4 days after this merged. Build commit 6f1f8158795d78aef72b5e28003e263e18ca697c. STID 3293-49f0. CI report (the carrier PR is unrelated; the fuzzer interleaves pre-existing tests). 1 sighting in 60 days, 0 on master. The block is still byte-identical on current master.

Where it dies: MergeTreeReaderWide.cpp:237, i.e. ownership_validator.add(deserialize_binary_bulk_state_map), then ISerialization.cpp:907 on the first virtual call through the state. Not the deserialize_states_caches loop at :235-236. Both overloads demangle identically because SubstreamsDeserializeStatesCache and DeserializeBinaryBulkStateMap are the same type, so only line:column separates them.

The part I cannot explain: si_addr is 0xaf960 with si_code == SEGV_MAPERR. That is a small non-heap word, while heap and binary addresses in the same trace are 0x55…/0x7f…. So state.get() was non-null but held a garbage value, not a freed-but-once-valid pointer. And the container is reader-local (IMergeTreeReader.h:124), holding make_shared clones returned by value from getOrSet/clonePrefixes. A reader-local map of fresh clones should not be able to contain that.

Ruled out from source, in case it saves you time:

  • No recursion or cycle: exactly one add(StatePtr) frame under one add(map) frame, so forEachNestedState at :914 is not involved.
  • All 30 clone() overrides use make_shared; no aliasing or non-owning clone exists.
  • No ODR/vtable-layout hazard: the three state virtuals are declared unconditionally (ISerialization.h:135-155).
  • Not a DeserializationPrefixesCache publication race: addToOwnershipValidator at :243 had not run yet.
  • Not prefetch-thread mutation: getTask waits on readers_future before createTask, and MergeTreeReaderIndex keeps its own state maps.
  • Not the prefixes-deserialization thread pool: its only consumer is SerializationObject.cpp:579, gated on non-empty sorted_dynamic_paths, and the fixture has no Object column.
  • No retained-iterator-across-insert, and no overflow-shaped write landing on a reader member.
  • The MergeTreeProjectionIndexSelectAlgorithm frame is a red herring: readFromTask is just return task.read();.

Fixture, if you want to chase it: the query read events2 with 14 streams over 1.26M rows / 155 granules; tests/queries/0_stateless/03742_nested_loop_join_long.sql is the only definer of that table, (Id UInt64, Payload String, Time DateTime), no projections and no JSON/Dynamic/LowCardinality, so the defect looks type-agnostic. The Wide path engages the prefixes cache with no remote-disk requirement (MergeTreeReaderWide.cpp:548), unlike Compact, so a local-disk Wide fixture is enough. The published core is unsymbolizable (S3 build-id a7e108c1… vs the core's 518F7211…, a re-run overwrote the artifact).

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 state.get(), use_count() and the container's size()/bucket_count() just before :237, plus TSAN on that fixture.

User impact is zero, since the whole block is DEBUG_OR_SANITIZER_BUILD-only and release compiles add/validate to empty bodies. But it does mean the UAF canary from #105626 can itself abort instead of producing the actionable error, which is why I did not want to leave it unreported.

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.

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

Labels

pr-improvement Pull request with some product improvements 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.

4 participants