Repository navigation
Fix crash in direct JOIN over MergeTree with PREWHERE (shared PrewhereInfo corrupted by column pruning) - #109932
Conversation
tryRemoveUnusedColumns mutates prewhere_info->prewhere_actions and row_level_filter->actions in place. ReadFromMergeTree::clone copied query_info by value but shared these DAGs via shared_ptr, so re-optimizing a cloned plan corrupted the original. DirectJoinMergeTreeEntity clones and re-optimizes its MergeTree lookup plan on every lookup, so a pushed-down PREWHERE on the direct-join right table crashed under column pruning. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-1:20260709-182200 |
|
cc @antaljanosbenjamin @KochetovNicolai — this fixes a crash from the position-based column pruning in #106438 interacting with shared |
|
Workflow [PR], commit [a253e24] Summary: ✅
AI ReviewSummaryThis PR deep-copies Findings❌ Blockers
Tests
Final VerdictChanges requested. LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 20/21 (95.24%) · Uncovered code |
| /// corrupt the other (see DirectJoinMergeTreeEntity, which clones and re-optimizes lookup_plan). | ||
| SelectQueryInfo query_info_copy = query_info; | ||
| if (query_info_copy.prewhere_info) | ||
| query_info_copy.prewhere_info = std::make_shared<PrewhereInfo>(query_info_copy.prewhere_info->clone()); |
There was a problem hiding this comment.
❌ This still does not make the lookup-plan filters fully independent when the right-side PREWHERE / row policy contains IN (subquery). PrewhereInfo::clone() and ActionsDAG::clone() only duplicate the DAG nodes; the constant ColumnSet payload is still shared, so all clones keep the same FutureSetFromSubquery pointer (ActionsDAG::clone() copies each node by value, and ColumnSet::cloneDummy() also reuses data). Later, ReadFromMergeTree::applyFilters() calls VirtualColumnUtils::buildSetsForDAG() on these cloned filters, and FutureSetFromSubquery::buildSetInplace() consumes the shared build plan with std::move(source). That means one DirectJoinMergeTreeEntity::getByKeys() lookup can steal the subquery plan and another concurrent lookup can continue with an unready set, preserving a Not-ready Set is passed / similar logical-error path for direct joins whose pushed-down filter uses subquery-backed IN. Can we either deep-clone the FutureSet payload too, or force these sets to become ready before the shared lookup_plan is stored?
|
The IN(subquery) case does not hit the race. I could not reproduce it, and the plan shows why. For a direct JOIN over MergeTree, the right-side subquery-backed IN set is registered in the outer query's That step builds the subquery set once, before std::unique_ptr<QueryPlan> FutureSetFromSubquery::build(...)
{
if (set_and_key->set->isCreated()) // atomic Set::is_created, set by CreatingSets
return nullptr; // returns BEFORE `auto plan = std::move(source);`
...
}So Verified on this branch: Deep-cloning the Added a regression test for this exact shape in |
CI finish ledger — 1f9ee5bCI fully finished (Finish Workflow + Mergeable Check pass; 0 failed, 0 pending). No failures on this head; nothing to own.
Session id: cron:our-pr-ci-monitor:20260710-030000 |
| FROM events AS t0 LEFT JOIN attributes AS t1 ON t1.OtherId = t0.Idu32n | ||
| SETTINGS log_comment = '03712_nested_loop_join_merge_tree_full_scan'; | ||
|
|
||
| -- PREWHERE on the direct-join right table: the pushed-down filter becomes a shared PrewhereInfo |
There was a problem hiding this comment.
Do not modify the old tests if possible, create a new one
| /// Deep-copy the filter DAGs that plan optimizations (e.g. tryRemoveUnusedColumns) mutate in place. | ||
| /// query_info is copied by value, but prewhere_info / row_level_filter are shared_ptrs, so without | ||
| /// this the clone would share the same PrewhereInfo/FilterDAGInfo and re-optimizing one plan would | ||
| /// corrupt the other (see DirectJoinMergeTreeEntity, which clones and re-optimizes lookup_plan). |
There was a problem hiding this comment.
The comment is too long: "Filter DAGs can be modified by optimizations." is enough.
1f9ee5b to
ad509e8
Compare
|
@antaljanosbenjamin Done. Reverted |
ad509e8 to
a64efac
Compare
|
Shortened the comment to "Filter DAGs can be modified by optimizations." (a64efac). |
New dedicated stateless test 04510_direct_join_merge_tree_prewhere_clone instead of modifying the existing 03712 test (per review). Covers a direct JOIN whose MergeTree right table has a pushed-down filter that becomes a shared PrewhereInfo / row_level_filter on the lookup plan, which DirectJoinMergeTreeEntity::getByKeys clones per lookup. Exercised with query_plan_remove_unused_columns=1 across three shapes: - PREWHERE - PREWHERE with IN(subquery) - row policy on the right table (the row_level_filter carrier) Without the fix the row-policy case segfaults in ReadFromMergeTree::removeUnusedColumns -> applyPrewhereActions via the shared row_level_filter DAG. Co-Authored-By: Claude Opus 4.8 <[email protected]>
a64efac to
c47f238
Compare
|
Added a focused row-policy reproducer to Verified both directions on a debug server (
The policy is scoped to a per-test table ( |
CI finish ledger — c47f238Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task whose fixing-PR link will be posted here when it opens. Only
Not PR-caused: this PR only touches Session id: cron:our-pr-ci-monitor:20260710-140000 |
…getree-prewhere-clone
…ergeTree lookup DirectKeyValueJoin::getByKeys clones the lookup ReadFromMergeTree plan once per pipeline stream (JoinStep creates one JoiningTransform per stream, all sharing the DirectJoinMergeTreeEntity), so the clones run concurrently. ReadFromMergeTree::clone() copied storage_snapshot as a shared shared_ptr, so every concurrent clone shared one StorageSnapshot object. When the parts-from-snapshot strip is armed (enable_remove_parts_from_snapshot_optimization, i.e. enable_shared_storage_snapshot_in_query=0, or a STREAM read), initializePipeline resets storage_snapshot->data in place; two threads resetting the same unique_ptr double-free the StorageSnapshot::Data. This is the storage_snapshot facet of the DirectJoinMergeTreeEntity clone family (same class as the shared PrewhereInfo/row_level_filter fixed elsewhere in this PR). Fix: in clone(), when the step strips the snapshot in place, give the clone its own StorageSnapshot (fresh object with a copy of the SnapshotData; the parts and mutations snapshots stay shared shared_ptrs, so only the owning unique_ptr becomes private). When the step does not strip, sharing is preserved so enable_shared_storage_snapshot_in_query keeps a consistent query-wide snapshot. The strip condition is factored into a single helper used by both clone() and initializePipeline so the two sites cannot diverge (covers both the enable_remove_parts_from_snapshot_optimization and query_info.isStream() triggers). Reproduced deterministically under AddressSanitizer (double-free in ReadFromMergeTree::initializePipeline via getByKeys/executePlan, QueryPipelineEx threads); the same workload passes with the fix. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
This adds a second fix to the same DirectJoinMergeTreeEntity clone family: the shared Pre-PR validation gate (click to expand)
Note on the regression test: the shipped planner defense ( Session id: cron:clickhouse-author-slot-1:20260718-204700 |
Internal second-model review (click to expand)An independent second-model diff review was run on this commit. Findings and dispositions:
Session id: cron:clickhouse-author-slot-1:20260718-204700 |
|
cc @antaljanosbenjamin — pushed a second fix to the same clone family: |
|
New sighting of facet 1 (shared Query: SELECT DISTINCT countDistinct(identity('0.7')) AS cnt
FROM events2 AS t0 INNER JOIN attributes2 AS t1 ON t1.EventId = t0.Id
PREWHERE not(isNotDistinctFrom(t1.EventId, false))
SETTINGS join_algorithm = 'direct', min_joined_block_size_rows = 0Crash: SIGSEGV in Same mechanism as facet 1, hit through the |
CI finish ledger — a668f9fCI fully finished (Finish Workflow: success; Mergeable Check reflects the two below; 0 checks queued/in-progress). Neither failure is caused by this PR's diff (a
Session id: cron:our-pr-ci-monitor:20260719-040000 |
The test claimed the failure was observable only under a sanitizer build. That is false in both halves: run against this PR's own merge-base b702eb6 the committed file fails 16/25 on a plain RelWithDebInfo build (7 of them SIGSEGV) and 0/25 on the PR head. The corruption is a shared filter DAG pruned twice by concurrent per-lookup clones, i.e. logic corruption rather than a use-after-free, so no sanitizer is needed to see it. Replace the sentence with the SQL-level precondition a reader actually needs. max_threads was left to the runner, which draws 1-3 in 97% of runs. At max_threads = 1 there is one JoiningTransform, so no concurrent lookups and nothing to corrupt: the whole file fails 0/25 in that draw, so about a third of CI runs covered nothing. Pin max_threads = 4 per statement on the three live queries. Rebuild the left table as one INSERT of 320 rows under max_block_size = 10. StorageMemory does not prefer large blocks, so this yields 32 blocks and takes the failure rate to 25/25 while removing rows overall; max_block_size is restored to DEFAULT before the join queries run. The last query claimed to cover the shared-StorageSnapshot facet but cannot reach it. stripsStorageSnapshotDataInPlace() is enable_remove_parts_from_snapshot_optimization || isStream(), and the planner clears the first term for every direct-join lookup, while STREAM on the right side of a direct join hangs and is not testable. It measures 0/25 unfixed even on the amplified fixture, so it would pass with the snapshot fix reverted. Delete it and move enable_shared_storage_snapshot_in_query = 0 onto query 1, which does fail without the fix under both values of that setting. The snapshot fix itself stays: it addresses a real master crash that has its own recorded sanitizer A/B. Also drop the leftover row-policy table and policy in the header, so the test reruns after aborting mid-row-policy-case instead of failing with TABLE_ALREADY_EXISTS.
Internal second-model review (2 gate rounds, 10 findings adjudicated)An independent model reviewed this commit cold against the ClickHouse review checklist, in two ❌ Fixed before publishingPR description had dropped the CI provenance links. The draft cited
|
Pre-PR validation gate (click to expand)
Randomized verification: Session id: cron:clickhouse-review-slot-53:20260729-102200 |
CI finish ledger - 7ab33aeEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose fixing-PR link will be posted here when it opens. Only
Session id: cron:our-pr-ci-monitor:20260729-180000 |
…getree-prewhere-clone
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 36/37 (97.30%) · Uncovered code |
CI finish ledger - 494eb18Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
The other 172 checks are green (154 success, 18 skipped) and both aggregators, Config Workflow and Finish Workflow, completed successfully. Neither failure touches this PR's diff, which is confined to Session id: cron:our-pr-ci-monitor:20260802-043000 |
Resolves the one conflict in ReadFromMergeTree.cpp against c91625f ("Fix use-after-free on shared storage snapshot in ReadFromMergeTree"), which landed on master while this PR was open. That commit fixed the StorageSnapshot facet independently and better: the strip site now rebinds the step's own `storage_snapshot` to a stripped clone instead of mutating `storage_snapshot->data` in place, so no concurrent reader of a shared snapshot can observe a freed Data. It covers every path into the strip, not only the ones reached through clone(). Consequently this merge drops this PR's entire snapshot facet: - the `stripsStorageSnapshotDataInPlace()` guard around the strip site, - the private-StorageSnapshot construction in `clone()`, - the helper itself in ReadFromMergeTree.h. The helper could no longer compile in any case: 6b27f2d ("deprecate merge_tree_enable_remove_parts_from_snapshot_optimization") removed `enable_remove_parts_from_snapshot_optimization`, the flag it read, and made the strip unconditional. What remains of this PR is the filter-DAG facet, which is still live on master: `clone()` passes `query_info` through by value, so clones share one `PrewhereInfo` / `FilterDAGInfo`, and `removeUnusedColumns` prunes both DAGs in place. Concurrent `DirectJoinMergeTreeEntity::getByKeys` lookups then corrupt each other's filters. Verified both directions with test 04510 under a debug build: the master binary segfaults 3 out of 3 runs, the patched binary returns the expected 320/160/100. Co-Authored-By: Claude Fable 5 <[email protected]>
CI finish ledger - a253e24Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
The other 172 checks are green (155 success, 17 skipped) and both aggregators, Config Workflow and Neither failure is caused by this PR's diff, which is 3 files: the Session id: cron:our-pr-ci-monitor:20260804-190000 |
3140a8c
…h PREWHERE (shared PrewhereInfo corrupted by column pruning)
Backport #109932 to 26.7: Fix crash in direct JOIN over MergeTree with PREWHERE (shared PrewhereInfo corrupted by column pruning)
Backport #109932 to 26.6: Fix crash in direct JOIN over MergeTree with PREWHERE (shared PrewhereInfo corrupted by column pruning)
…geTree with PREWHERE (shared PrewhereInfo corrupted by column pruning)
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix server crashes and wrong
NOT_FOUND_COLUMN_IN_BLOCK/LOGICAL_ERRORfailures in adirectJOIN over a MergeTree right table. The plan is cloned and re-optimized per lookup across threads, but the clone shared two mutable objects with the original: thePrewhereInfo/row_level_filterDAG, corrupted in place by column pruning, and theStorageSnapshot, whose data parts are stripped in place.Description
Closes: #112568. Its fuzzer stack (
evaluatePartialResult/applyPrewhereActions/transformHeader) is this shared filter DAG read insideReadFromMergeTree::clonewhile a concurrent lookup's pruning destroys its nodes: 10/10 segfaults on an unpatchedamd_debugbuild, 0/10 on this head.DirectJoinMergeTreeEntity::getByKeysclones itslookup_planper lookup, one per pipeline stream, so clones run concurrently whileReadFromMergeTree::cloneshared per-plan state with the original. Two facets:1. Shared filter DAG.
clonecopiedquery_infoby value, butprewhere_infoandrow_level_filterareshared_ptrs, so all clones shared one DAG.tryRemoveUnusedColumns(#106438) prunes it in place and rewritesall_column_names/output_header, so one clone leaves a header missing outputs another expects.clonealready deep-copiedanalyzed_result_ptr; this extends that to both filter DAGs.No sanitizer is needed to see it:
04510_direct_join_merge_tree_prewhere_clone.sqlfails 25/25 on a plain RelWithDebInfo build of the merge-base (b702eb6e2932) and 0/25 on this head, with SIGSEGV,NOT_FOUND_COLUMN_IN_BLOCKandRequired output position N is out of range. Found by the stress test on a fuzzed03712_nested_loop_join_merge_tree.sql(arm_msan, STID 3434-4c9f): https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=109869&sha=5d9c118aaf5f3bc4e00c5f5beca71b1295c3e9d2&name_0=PR&name_1=Stress%20test%20%28arm_msan%292. Shared
StorageSnapshot. When the parts strip is armed,initializePipelineresetsstorage_snapshot->datain place, so two clones resetting oneunique_ptrdouble-free it.clonenow gives a stripping step its ownStorageSnapshot, preserving sharing otherwise soenable_shared_storage_snapshot_in_querystill yields a query-wide snapshot. One helper holds the strip condition for both paths so they cannot diverge. Found on master by the AST fuzzer (STID 3942-460f): https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=6b5099c5fef65deb0daa285895551e15538c922a&name_0=MasterCI&name_1=AST%20fuzzer%20%28arm_asan_ubsan%29 . Reproduced deterministically under ASan; facet 2 rests on that reproduction, not on a stateless test.Why facet 2 is not SQL-testable
stripsStorageSnapshotDataInPlace()isenable_remove_parts_from_snapshot_optimization || query_info.isStream(). The planner callsdisableMergeTreePartsSnapshotRemovalon every direct-join lookup step (PlannerJoinTree.cpp, pre-existing master behaviour), clearing the first term, and the only other trigger,STREAMon the right side of a direct join, hangs and cannot be used in a test.Measured accordingly: a query of that shape fails 0/25 on the unfixed binary even on the amplified 32-block fixture, at
max_threads4 and 16. It would therefore pass with this half of the fix reverted, which is false coverage, so it was removed rather than kept.enable_shared_storage_snapshot_in_query = 0moved onto query 1, which does fail without the fix under both values of that setting (25/25 unfixed, 0/25 fixed either way).Closes #113262
Version info
26.8.1.827(included in26.8and later)26.7.3.15,26.6.5.98