Skip to content

Fix use-after-free on shared storage snapshot in ReadFromMergeTree - #111192

Merged
alexey-milovidov merged 11 commits into
masterfrom
fix/shared-snapshot-strip-uaf
Aug 1, 2026
Merged

alexey-milovidov merged 11 commits into
masterfrom
fix/shared-snapshot-strip-uaf

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Jul 21, 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):

Fix a use-after-free (segmentation fault) when a query with a shared storage snapshot (setting enable_shared_storage_snapshot_in_query) strips data parts from the snapshot — e.g. a streaming subquery reading the same MergeTree table that another part of the query reads concurrently.

Documentation entry for user-facing changes

ReadFromMergeTree::initializePipeline replaced storage_snapshot->data in place when stripping data parts from the snapshot (for streaming queries, and for merge_tree_enable_remove_parts_from_snapshot_optimization). With enable_shared_storage_snapshot_in_query (on by default), the StorageSnapshot object is shared across all parts of the query via QueryMetadataCache, so the in-place replacement freed the old StorageSnapshot::Data while other threads of the same query could still be reading it. The optimization path is already gated off for shared snapshots (see the enable_remove_parts_from_snapshot_optimization member initialization), but the streaming path (query_info.isStream()) was not.

The fix replaces the step's own snapshot pointer with a stripped clone (StorageSnapshot::clone) instead of mutating the shared object in place.

Found by AST fuzzer (amd_msan) as a segmentation fault in MergeTreeAnalyzeIndexSource::getIndexAnalysis, which read mutations_snapshot from the shared snapshot while a streaming IN-subquery of another UNION ALL branch concurrently stripped it. CI report (from an unrelated PR run): https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110938&sha=7cf404c52497443c4c2d93f51a31c99e7eae1147&name_0=PR&name_1=AST%20fuzzer%20%28amd_msan%29

Reproduced locally under ASan with the fuzzer query:

SELECT * FROM mergeTreeAnalyzeIndexes(currentDatabase(), data, (key IN (SELECT key FROM data ORDER BY key DESC NULLS LAST LIMIT 10)))
UNION ALL
SELECT * FROM mergeTreeAnalyzeIndexes(currentDatabase(), data, (key IN (SELECT key FROM data STREAM ORDER BY key DESC NULLS LAST LIMIT 10)))
GROUP BY ALL

ASan reports heap-use-after-free in shared_ptr<MergeTreeData::IMutationsSnapshot const> copy at StorageMergeTreeAnalyzeIndexes.cpp while another thread frees the old StorageSnapshot::Data in ReadFromMergeTree::initializePipeline (reached through FutureSetFromSubquery::buildOrderedSetInplace from KeyCondition). After the fix, the same scenario runs without ASan errors.

No functional test is added: the only known reproducer requires a STREAM subquery inside the analyzed IN predicate, which by design never finishes (and is not cancellable by max_execution_time — a separate issue), so it cannot run as a stateless test. The race is covered by the AST fuzzer that found it.

Related: #110938

alexey-milovidov and others added 2 commits July 21, 2026 08:29
`ReadFromMergeTree::initializePipeline` replaced `storage_snapshot->data`
in place when stripping data parts from the snapshot (for streaming
queries and for `merge_tree_enable_remove_parts_from_snapshot_optimization`).
With `enable_shared_storage_snapshot_in_query` the `StorageSnapshot`
object is shared across all parts of the query via `QueryMetadataCache`,
so the in-place replacement freed the old `StorageSnapshot::Data` while
other threads of the same query could still be reading it. The
optimization path is gated off for shared snapshots, but the streaming
path (`query_info.isStream()`) was not.

Found by AST fuzzer as a segmentation fault in
`MergeTreeAnalyzeIndexSource::getIndexAnalysis`, which read
`mutations_snapshot` from the shared snapshot while a streaming
IN-subquery of another UNION branch concurrently stripped it:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110938&sha=7cf404c52497443c4c2d93f51a31c99e7eae1147&name_0=PR&name_1=AST%20fuzzer%20%28amd_msan%29
(CI run for #110938,
whose changes are unrelated to the crash.)

Reproduced locally under ASan as heap-use-after-free. Replace the
step's own snapshot pointer with a stripped clone instead of mutating
the shared object.

Co-Authored-By: Claude Fable 5 <[email protected]>
The streaming subquery never finishes, so the query ends with
`TIMEOUT_EXCEEDED`; before the fix, a sanitizer build reported a
heap-use-after-free in `MergeTreeAnalyzeIndexSource::getIndexAnalysis`
instead.

Co-Authored-By: Claude Fable 5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 21, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [fbae717]

Summary: ✅


AI Review

Summary

This PR fixes the shared-StorageSnapshot use-after-free in ReadFromMergeTree by replacing the step-local snapshot with a stripped clone instead of mutating the shared object in place, and the regression test now correctly pins enable_shared_storage_snapshot_in_query and skips unsupported parallel replicas. I did not find a remaining code-level correctness or lifetime issue in the current diff, but the PR metadata still overstates the affected surface.

PR Metadata

⚠️ Changelog category is not aligned with the actual trigger surface. The reproducer in this PR goes through STREAM, and STREAM is still an experimental feature guarded by enable_streaming_queries = 1, while Bug Fix is reserved for user-visible misbehavior in an official stable release.

Exact replacement:

### Changelog category (leave one):
- Not for changelog (changelog entry is not required)

⚠️ If you switch to Not for changelog, drop the current Changelog entry. If you keep a user-visible category instead, the entry should explicitly say this is a STREAM-specific fix rather than a general shared-snapshot bug.

Final Verdict

⚠️ Code looks good; adjust the PR metadata before merge.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 21, 2026
alexey-milovidov and others added 4 commits July 21, 2026 19:54
…as in test

Explicitly `SET enable_shared_storage_snapshot_in_query = 1` so the regression
test exercises the shared-`StorageSnapshot` path regardless of the `compatibility`
profile default, and tag the test `no-parallel-replicas` because `STREAM` is not
supported with parallel replicas (`ILLEGAL_STREAM`).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The regression test set `max_execution_time = 2` at the session level so the
streaming `SELECT` would end with `TIMEOUT_EXCEEDED`. That short timeout also
applied to the subsequent `DROP TABLE`, which on slow (e.g. sanitizer) builds
could itself exceed 2000 ms and fail the test with `TIMEOUT_EXCEEDED`
(observed on the amd_msan run). Reset `max_execution_time` to `0` before the
cleanup `DROP` so it can no longer hit the timeout.

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=111192&sha=04f5f073d49827934b51f209c2ca36d825d730f3&name_0=PR&name_1=Stateless%20tests%20%28amd_msan%2C%20WasmEdge%2C%20parallel%2C%202%2F2%29

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

Copy link
Copy Markdown
Member Author

Both remaining CI failures are unrelated to this PR:

No unresolved review feedback; the AI review verdict is approve.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

Both CI failures on 740ce3b are unrelated to this PR:

@groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=111192&sha=740ce3bcdecf657aabf88e39ca1a647709b1ac3f&name_0=PR&name_1=Stateless%20tests%20%28arm_binary%2C%20parallel%29 (03915_spilling_hash_join, result differs with reference under randomized settings) 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, investigating. Confirmed this is a trunk flaky, not caused by #111192: 0 master hits in 30d, and the same failure recurs across unrelated PRs.

Root-cause direction: the tail profile events block asserts on spill / non-joined ProfileEvents counters (JoinNonJoinedTransformRowCount, JoinSpillingHashJoinSwitchedToGraceJoin, JoinDelayed*) that shift under CI-randomized memory/threshold settings, while the test only pins max_bytes_before_external_join / join_algorithm / max_threads (no -- Tags: line). No 03915-specific fix PR exists yet. I will pin the exact randomized setting(s) that perturb the counters (preserving the spilling-behavior assertions) and follow up here with a separate fix PR.

@groeneai

Copy link
Copy Markdown
Collaborator

@alexey-milovidov fix PR: #111500

Root cause of the 03915_spilling_hash_join result diff: the tail profile-events block asserts JoinNonJoinedTransform* counters, which depend on which physical side of a join emits non-joined rows. With query_plan_join_swap_table = auto the planner swaps build/probe sides when the left row estimate is smaller than the right; those estimates come from the join-reordering statistics cache (use_hash_table_stats_for_join_reordering, randomized and on by default), so randomized runs flip the swap and move the counters between queries (q12/q13/q15). Results stay correct; only the ProfileEvents shift. The test pinned query_plan_optimize_join_order_randomize = 0 but not the swap decision. #111500 pins query_plan_join_swap_table = 0; verified both directions locally and 50/50 with randomization.

@Michicosun Michicosun self-assigned this Jul 23, 2026
pull Bot pushed a commit to Mattlk13/ClickHouse that referenced this pull request Jul 26, 2026
The profile-events assertions depend on which physical side of a join emits
non-joined rows. With query_plan_join_swap_table=auto the planner swaps
build/probe sides based on row-count estimates, which randomized settings can
tip, moving the JoinNonJoinedTransform counters between queries and causing
result diffs. Pin the setting so the physical plan is deterministic.

Related: ClickHouse#111192

Co-Authored-By: Claude Opus 4.8 <[email protected]>

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

This is very reasonable. Mutation == bad.

@alexey-milovidov alexey-milovidov self-assigned this Aug 1, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member Author

@Michicosun, please don't hesitate to approve - the original code is obviously wrong, and the fix is trivial.

…-strip-uaf

Picks up the fix for the s3_queue server abort that failed the integration
tests on this branch: an out-of-bounds `vector` access in
`ObjectStorageQueueSource::FileIterator::next` (PR #108977, merged as
2f335d3).

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=111192&sha=fe3e297d38e5b6974711ee5cd522baa3a90d6d99&name_0=PR&name_1=Integration%20tests%20%28arm_binary%2C%20distributed%20plan%2C%202%2F4%29
Related: #111192
Related: #108977
Related: #111659

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`ci/jobs/check_style.py` now requires every stateless test that sets
`enable_streaming_queries` (or sources `streaming.lib`) to carry
`_streaming_queries_` in its file name. Rename
`04619_shared_snapshot_stream_strip_race` to
`04619_streaming_queries_shared_snapshot_strip_race` accordingly.

The `Style check` failure also dropped the `Bugfix validation (functional
tests)` jobs, which is why `new_tests_check.py` reported that no per-arch
job validated the bug.
-- before the fix, a sanitizer build reported a heap-use-after-free here instead.
SELECT * FROM mergeTreeAnalyzeIndexes(currentDatabase(), t_snapshot_strip_race, (key IN (SELECT key FROM t_snapshot_strip_race ORDER BY key DESC NULLS LAST LIMIT 10)))
UNION ALL
SELECT * FROM mergeTreeAnalyzeIndexes(currentDatabase(), t_snapshot_strip_race, (key IN (SELECT key FROM t_snapshot_strip_race STREAM ORDER BY key DESC NULLS LAST LIMIT 10)))

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.

This reproducer goes through STREAM, and STREAM is still an experimental feature gated by enable_streaming_queries = 1.

That matters for the PR metadata: with enable_shared_storage_snapshot_in_query enabled, the non-STREAM merge_tree_enable_remove_parts_from_snapshot_optimization branch is already disabled in the ReadFromMergeTree constructor, so this is not really a general stable-release shared-snapshot bug. Bug Fix is reserved for misbehavior in an official stable release, so I would switch the category to Not for changelog (or the team's preferred experimental-only bucket) and make the entry explicit that the fixed path is the experimental STREAM one if you keep a changelog entry at all.

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.

Changed to Improvement.

@clickhouse-gh

clickhouse-gh Bot commented Aug 1, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.60% 86.50% -0.10%
Functions 91.90% 91.90% +0.00%
Branches 78.80% 78.70% -0.10%

Changed lines: Changed C/C++ lines covered: 6/6 (100.00%) · Uncovered code

Full report · Diff report

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 1, 2026
Merged via the queue into master with commit 05db29f Aug 1, 2026
179 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix/shared-snapshot-strip-uaf branch August 1, 2026 14:41
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 1, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
The profile-events assertions depend on which physical side of a join emits
non-joined rows. With query_plan_join_swap_table=auto the planner swaps
build/probe sides based on row-count estimates, which randomized settings can
tip, moving the JoinNonJoinedTransform counters between queries and causing
result diffs. Pin the setting so the physical plan is deterministic.

Related: ClickHouse#111192

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-bugfix Pull request with bugfix, not backported by default 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