Skip to content

Fix crash in direct JOIN over MergeTree with PREWHERE (shared PrewhereInfo corrupted by column pruning) - #109932

Merged
diegomestre2 merged 9 commits into
ClickHouse:masterfrom
groeneai:fix-direct-join-mergetree-prewhere-clone
Aug 5, 2026
Merged

diegomestre2 merged 9 commits into
ClickHouse:masterfrom
groeneai:fix-direct-join-mergetree-prewhere-clone

Conversation

@groeneai

@groeneai groeneai commented Jul 9, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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_ERROR failures in a direct JOIN 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: the PrewhereInfo/row_level_filter DAG, corrupted in place by column pruning, and the StorageSnapshot, whose data parts are stripped in place.

Description

Closes: #112568. Its fuzzer stack (evaluatePartialResult / applyPrewhereActions / transformHeader) is this shared filter DAG read inside ReadFromMergeTree::clone while a concurrent lookup's pruning destroys its nodes: 10/10 segfaults on an unpatched amd_debug build, 0/10 on this head.

DirectJoinMergeTreeEntity::getByKeys clones its lookup_plan per lookup, one per pipeline stream, so clones run concurrently while ReadFromMergeTree::clone shared per-plan state with the original. Two facets:

1. Shared filter DAG. clone copied query_info by value, but prewhere_info and row_level_filter are shared_ptrs, so all clones shared one DAG. tryRemoveUnusedColumns (#106438) prunes it in place and rewrites all_column_names/output_header, so one clone leaves a header missing outputs another expects. clone already deep-copied analyzed_result_ptr; this extends that to both filter DAGs.

No sanitizer is needed to see it: 04510_direct_join_merge_tree_prewhere_clone.sql fails 25/25 on a plain RelWithDebInfo build of the merge-base (b702eb6e2932) and 0/25 on this head, with SIGSEGV, NOT_FOUND_COLUMN_IN_BLOCK and Required output position N is out of range. Found by the stress test on a fuzzed 03712_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%29

2. Shared StorageSnapshot. When the parts strip is armed, initializePipeline resets storage_snapshot->data in place, so two clones resetting one unique_ptr double-free it. clone now gives a stripping step its own StorageSnapshot, preserving sharing otherwise so enable_shared_storage_snapshot_in_query still 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() is enable_remove_parts_from_snapshot_optimization || query_info.isStream(). The planner calls disableMergeTreePartsSnapshotRemoval on every direct-join lookup step (PlannerJoinTree.cpp, pre-existing master behaviour), clearing the first term, and the only other trigger, STREAM on 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_threads 4 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 = 0 moved 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

  • Merged into: 26.8.1.827 (included in 26.8 and later)
  • Backported to: 26.7.3.15, 26.6.5.98

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]>
@groeneai

groeneai commented Jul 9, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Check Result
a Deterministic repro? Yes. Under CI-randomized settings (join_algorithm=direct, query_plan_remove_unused_columns=1, optimize_move_to_prewhere=1, max_threads=3, split-ranges injection) the query crashes ~15% per run; a 60-iteration loop reproduces reliably (9/60 on the pre-fix binary).
b Root cause explained? ReadFromMergeTree::clone() copies query_info by value, but prewhere_info/row_level_filter are shared_ptrs, so clones share the same filter DAGs. tryRemoveUnusedColumns (#106438) mutates prewhere_info->prewhere_actions in place. DirectJoinMergeTreeEntity::getByKeys clones+re-optimizes the MergeTree lookup plan per lookup, corrupting the shared PrewhereInfo -> crash in pruneFilterDAGOutputsByPosition / evaluatePartialResult.
c Fix matches root cause? Yes. clone() now deep-copies prewhere_info and row_level_filter (as it already does for analyzed_result_ptr), so each clone owns independent DAGs that the optimizer can mutate safely.
d Test intent preserved / new tests? Added a PREWHERE-on-direct-join case to 03712_nested_loop_join_merge_tree.sql exercising the shared-clone path. Existing assertions unchanged.
e Demonstrated in both directions? Pre-fix binary: 9/60 crashes. Post-fix binary (same repro): 0/120 crashes. Results identical to the WHERE baseline (correctness preserved).
f Fix general, not narrow patch? The same shared-DAG hazard applies to both prewhere_info and row_level_filter; both are deep-copied. clone() is the single point every plan clone flows through.
g Generalizes across inputs? The corruption is independent of key type / wrapper; the fix operates on the DAG containers regardless of column types. Verified with LowCardinality(Nullable) key + PREWHERE.
h Backward compatible? N/A. Internal query-plan cloning; no setting/format/behavior change (results unchanged).
i Invariants preserved? Restores the invariant that a cloned ReadFromMergeTree owns its mutable optimization state independently of the source, matching the existing analyzed_result_ptr deep-copy.

Session id: cron:clickhouse-worker-slot-1:20260709-182200

@groeneai

groeneai commented Jul 9, 2026

Copy link
Copy Markdown
Collaborator Author

cc @antaljanosbenjamin @KochetovNicolai — this fixes a crash from the position-based column pruning in #106438 interacting with shared PrewhereInfo on cloned MergeTree lookup plans (direct JOIN + PREWHERE). Could you review?

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Jul 9, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a253e24]

Summary: ✅


AI Review

Summary

This PR deep-copies prewhere_info and row_level_filter when ReadFromMergeTree is cloned, which fixes the plain shared-DAG corruption behind the direct-JOIN crash. One blocker still remains, though: the cloned filters still alias the same FutureSetFromSubquery for IN (subquery), so concurrent getByKeys lookups can still consume the shared subquery plan and leave a sibling clone with an unready set.

Findings

❌ Blockers

  • [src/Processors/QueryPlan/ReadFromMergeTree.cpp:3729] [dismissed by author -- https://github.com/Fix crash in direct JOIN over MergeTree with PREWHERE (shared PrewhereInfo corrupted by column pruning) #109932#discussion_r3555068463] PrewhereInfo::clone() only makes the lookup-plan filters structurally separate; it does not make subquery-backed IN sets independent. ActionsDAG::clone() shallow-copies the constant ColumnConst(ColumnSet(...)), so all direct-join clones still share one FutureSetFromSubquery. On current master, ReadFromMergeTree::applyFilters() builds PREWHERE / row-policy sets synchronously during optimization, and FutureSetFromSubquery::buildSetInplace() still consumes the shared build plan with std::move(source). That means one concurrent DirectJoinMergeTreeEntity::getByKeys() lookup can steal the subquery plan while a sibling lookup sees source == nullptr and continues with an unready set, preserving the Not-ready Set is passed / similar logical-error path for right-side PREWHERE ... IN (subquery). Suggested fix: either deep-clone or otherwise privatize the FutureSetFromSubquery payload when cloning these DAGs, or force every subquery-backed IN in prewhere_info / row_level_filter to become ready before the shared lookup_plan is stored in DirectJoinMergeTreeEntity.
Tests
  • ⚠️ Add a focused reproducer for the right-side PREWHERE ... IN (subquery) shape under join_algorithm = 'direct' where at least two getByKeys lookups optimize concurrently before the first set build finishes. The current 04510 query 2 is not sufficient proof for this path because the surviving alias is on the shared FutureSetFromSubquery, not on the already-fixed DAG node list.
Final Verdict

Changes requested.

LLVM Coverage Report

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

Changed lines: Changed C/C++ lines covered: 20/21 (95.24%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 9, 2026
/// 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());

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 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?

@groeneai

groeneai commented Jul 9, 2026

Copy link
Copy Markdown
Collaborator Author

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 PreparedSets, so the plan is topped by CreatingSets (Create sets before main query execution):

CreatingSets (Create sets before main query execution)
  Expression -> Aggregating -> ... -> FilledJoin (DirectKeyValueJoin) -> ...

That step builds the subquery set once, before DirectKeyValueJoin::joinBlock (and therefore before any getByKeys lookup) runs. getByKeys clones lookup_plan and later reaches ReadFromMergeTree::applyFilters -> VirtualColumnUtils::buildSetsForDAG -> FutureSetFromSubquery::buildSetInplace, but by then the shared FutureSetFromSubquery is already created:

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 std::move(source) never runs from the cloned lookups; they cannot steal the build plan, and there is no "Not-ready Set" path here. Set::is_created is std::atomic<bool>, so the guard is also safe for the concurrent lookups a filled join can issue.

Verified on this branch: SELECT ... events INNER JOIN attributes ON ... PREWHERE t1.Attribute IN (SELECT a FROM allowed) with join_algorithm='direct', query_plan_remove_unused_columns=1, run single (many iterations) and 30x concurrent, plus with use_index_for_in_with_subqueries on/off and max_rows_to_transfer=5, transfer_overflow_mode='break': all correct, no logical error, server stable.

Deep-cloning the FutureSet payload would also defeat the up-front CreatingSets build (each clone would rebuild its own subquery), so it is not desirable here.

Added a regression test for this exact shape in 03712_nested_loop_join_merge_tree (commit 1f9ee5b).

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 1f9ee5b

CI fully finished (Finish Workflow + Mergeable Check pass; 0 failed, 0 pending). No failures on this head; nothing to own.

Check / test Reason Owner / fixing PR
(all functional/integration/build/stress/unit checks) pass none needed
Sync — CH Inc sync (private, not actionable)

Session id: cron:our-pr-ci-monitor:20260710-030000

@antaljanosbenjamin antaljanosbenjamin self-assigned this Jul 10, 2026
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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do not modify the old tests if possible, create a new one

Comment on lines +3457 to +3460
/// 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).

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The comment is too long: "Filter DAGs can be modified by optimizations." is enough.

@groeneai
groeneai force-pushed the fix-direct-join-mergetree-prewhere-clone branch from 1f9ee5b to ad509e8 Compare July 10, 2026 08:41
@groeneai

Copy link
Copy Markdown
Collaborator Author

@antaljanosbenjamin Done. Reverted 03712_nested_loop_join_merge_tree to its original content and moved the regression coverage into a new dedicated test 04510_direct_join_merge_tree_prewhere_clone (direct JOIN over MergeTree right table with pushed-down PREWHERE, including the IN(subquery) shape, run with query_plan_remove_unused_columns=1). Parallel-safe (per-test database, no no-parallel). New head ad509e8.

@groeneai
groeneai force-pushed the fix-direct-join-mergetree-prewhere-clone branch from ad509e8 to a64efac Compare July 10, 2026 09:12
@groeneai

Copy link
Copy Markdown
Collaborator Author

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]>
@groeneai
groeneai force-pushed the fix-direct-join-mergetree-prewhere-clone branch from a64efac to c47f238 Compare July 10, 2026 09:53
@groeneai

Copy link
Copy Markdown
Collaborator Author

Added a focused row-policy reproducer to 04510_direct_join_merge_tree_prewhere_clone (head c47f238). It creates a PERMISSIVE row policy on the direct-join right MergeTree table (USING EventId < 300), so query_info.row_level_filter is populated and pruned across the per-lookup clones through the same shared-pointer path tryRemoveUnusedColumns mutates.

Verified both directions on a debug server (max_threads=16, join_algorithm='direct', query_plan_remove_unused_columns=1):

  • Without the fix: the row-policy query segfaults — DirectJoinMergeTreeEntity::getByKeys -> executePlan -> tryRemoveUnusedColumns -> ReadFromMergeTree::removeUnusedColumns -> SourceStepWithFilter::applyPrewhereActions, i.e. the row_level_filter carrier, exactly the branch you flagged.
  • With the fix: 25/25 iterations return 300\t300, server stable.

The policy is scoped to a per-test table (attributes_rp) and dropped at the end, so it stays parallel-safe and does not affect the PREWHERE / IN(subquery) cases above it.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — c47f238

Every 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 CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Upgrade check (amd_release) / Error message in clickhouse-server.log (DatabasePostgreSQL::getTablesIterator Code 614 connection timeout) error-message leak (harness) #109350 (ours, open)
Stateless tests (arm_asan_ubsan, azure, sequential) / Server died + AddressSanitizer (STID 1367-2e8c) ASan allocator heap corruption (String .size subcolumn family) #109020 (ours, open)
CH Inc sync — CH Inc sync (private, not actionable)

Not PR-caused: this PR only touches src/Processors/QueryPlan/ReadFromMergeTree.cpp (direct-JOIN PREWHERE clone) + the new 04510 regression test. Neither the PostgreSQL upgrade-check connection-error leak nor the arm/azure ASan allocator corruption relates to that diff.

Session id: cron:our-pr-ci-monitor:20260710-140000

groeneai and others added 2 commits July 18, 2026 19:46
…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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

This adds a second fix to the same DirectJoinMergeTreeEntity clone family: the shared StorageSnapshot double-free (AST fuzzer (arm_asan_ubsan), STID 3942-460f on master). Pre-PR validation gate for this commit:

Pre-PR validation gate (click to expand)
# Check Result
a Deterministic repro? Yes. ASAN, 40-part concurrent direct join, enable_shared_storage_snapshot_in_query=0, max_threads=32. Symbolized stack identical to STID 3942-460f.
b Root cause explained? Yes. Concurrent getByKeys clones share one StorageSnapshot; initializePipeline's in-place storage_snapshot->data = std::move(...) strip races -> double-free of StorageSnapshot::Data.
c Fix matches root cause? Yes. clone() gives each stripping clone its own StorageSnapshot, so the in-place strip never touches a shared object. Not a band-aid.
d Test intent preserved / new test added? Yes. Added the storage_snapshot case to 04510 (concurrent direct join, strip armed); existing cases unchanged; reference updated.
e Demonstrated both directions? Yes. RED (no fix) double-frees with the exact CI stack; GREEN (fix) 50/50 pass. Differ only by the clone() change.
f Fix general, not a narrow patch? Yes. Keyed on the full strip condition (enable_remove_parts_from_snapshot_optimization OR query_info.isStream()) via one helper used by both clone() and initializePipeline. Blast radius checked across all clone() callers; non-stripping path unchanged (still shares).
g Generalizes across inputs? Yes. Covers both strip triggers; non-MergeTree snapshot falls back to a fresh empty SnapshotData, never shares-when-stripping.
h Backward compatible? Yes. No setting/format change. When the strip cannot fire (enable_shared_storage_snapshot_in_query=1, the default) behavior is identical.
i Invariants preserved? Yes. Upholds MergeTreeData::getStorageSnapshot's invariant (strip-armed <=> per-read own snapshot). Copied SnapshotData shares the same parts/mutations shared_ptrs, so the read model is identical; only the owning unique_ptr is private.

Note on the regression test: the shipped planner defense (PlannerJoinTree.cpp disableMergeTreePartsSnapshotRemoval) masks this for standard direct-join shapes, so the 04510 case is a no-crash + correctness guard rather than a fail-without-fix repro. The deterministic proof is the AddressSanitizer A/B above (with that defense disabled to hit the concurrent-strip race window); the fuzzer's defense-bypass query shape was not isolated locally.

Session id: cron:clickhouse-author-slot-1:20260718-204700

@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (click to expand)

An independent second-model diff review was run on this commit. Findings and dispositions:

⚠️ Majors

  1. Regression test does not fail-without-fix — Agree (mitigated). Confirmed: with the shipped planner defense intact, the concurrent direct-join workload runs clean even without the fix (the defense forces the lookup not to strip). No plain .sql test can fail-without-fix while that defense holds, and the AST-fuzzer defense-bypass shape could not be isolated. The 04510 case is therefore a no-crash + correctness guard; the deterministic proof is the AddressSanitizer A/B (defense disabled: RED double-frees with the exact CI stack, GREEN 50/50 pass). A synchronization failpoint to make the timing race deterministic was considered but not added (substantial production + test-infra scope for a tiny-window race; conflicts with keeping the fix minimal). Noted as a possible future enhancement.

  2. Generated runtime artifacts in the change — Disagree (evidence). git show --stat HEAD shows the commit contains only the 4 intended files; .meta.json, access/, and preprocessed_configs/ are untracked local server-runtime state from in-worktree test runs, were never staged, and cannot enter the PR. Cleaned from the worktree regardless.

Session id: cron:clickhouse-author-slot-1:20260718-204700

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @antaljanosbenjamin — pushed a second fix to the same clone family: clone() now gives a stripping clone its own StorageSnapshot, fixing a concurrent double-free (master AST-fuzzer STID 3942-460f) where per-lookup clones shared one snapshot and both ran the in-place storage_snapshot->data strip. Also merged current master (branch was far behind). Details in the two comments above.

@groeneai

Copy link
Copy Markdown
Collaborator Author

New sighting of facet 1 (shared PrewhereInfo corrupted by column pruning): STID 3294-4ab2, AST fuzzer (amd_debug, targeted), surfaced on unrelated PR #110105 (clickhouse-proxy), and the same signature on unrelated PR #109407 (STID 3294-4af5, AST fuzzer (amd_debug)). Not PR-caused in either case.

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 = 0

Crash: SIGSEGV in ActionsDAG::removeUnusedActions (ActionsDAG.cpp:750) reached via removeUnusedColumns -> pruneFilterDAGOutputsByPosition(query_info.prewhere_info->prewhere_actions, ...) (ReadFromMergeTree.cpp:4958 / FilterStep.cpp:148) inside DirectJoinMergeTreeEntity::executePlan. A twin abort fired on a second thread with the same query_id (3 threads in getByKeys concurrently) - the concurrent per-lookup clones mutating one shared prewhere_actions.

Same mechanism as facet 1, hit through the query_plan_remove_unused_columns pass (this PR's regression test already exercises that pass with PREWHERE). Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110105&sha=b4b5f4163720e37a36f80244b4aa4f0b5dfa5e07&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%29

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — a668f9f

CI 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 ReadFromMergeTree::clone() storage-snapshot deep-copy for the concurrent direct-join lookup path). Every line has an owner.

Check / test Reason Owner / fixing PR
AST fuzzer (amd_debug, targeted, old_compatibility) / ScatterExchangeStep should have one source shard (STID 4636-3f0c) chronic trunk fuzzer finding in distributed-plan ScatterExchange (15+ unrelated PRs, 1 master, 30d; unrelated to MergeTree snapshot clone) #108401 (ours, open)
Integration tests (amd_tsan, 3/6) / test_replicated_database::test_replicated_table_structure_alter chronic flaky replicated-DB DDL structure-alter (98 master hits / 452 PRs / 30d) #110030 (open)
Mergeable Check / PR derivative rolls up the two above

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

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (2 gate rounds, 10 findings adjudicated)

An independent model reviewed this commit cold against the ClickHouse review checklist, in two
rounds. Verdicts and the evidence behind each are below. Nothing was accepted or rejected on
assertion; every rejection cites code or a measurement.

❌ Fixed before publishing

PR description had dropped the CI provenance links. The draft cited STID 3434-4c9f and
STID 3942-460f as bare text. Both canonical report URLs are restored, and a per-signature
failure histogram that was not backed by a recorded run was replaced with the signature list that
is.

⚠️ Raised and rejected, with evidence

"The test can pass if unused-column pruning is silently bypassed" (raised twice). The premise
is inverted: query_plan_remove_unused_columns is what enables the pruning that corrupts the
shared DAG, so at 0 the unfixed build passes and at 1 it fails 25/25. The result counts are
therefore the most direct available detector of whether pruning ran. It is pinned per statement on
all three queries, and Optimizations.h:181 gates the pass on that setting, so it cannot silently
stop. The suggested remedies are not available for the object under test: the corrupted plan is a
runtime clone created per lookup inside DirectJoinMergeTreeEntity::getByKeys
(lookup_plan.clone(), then plan.optimize), which EXPLAIN never reaches, so a plan pin would
assert on the outer plan instead; and no ProfileEvent for the pruning exists. The optimizer's own
pruning behaviour already has plan-level coverage elsewhere, for example
02514_analyzer_drop_join_on.sql and 03652_explain_input_header.sql.

"The StorageSnapshot half has no reviewable before/after sanitizer evidence" (raised twice).
The mechanism analysis is correct, and this commit agrees with it: that is why the fourth query was
deleted rather than kept. The requested artifact exists. With the clone fix absent, an ASan build
double-frees at the storage_snapshot->data reset with a stack identical to the master report
linked above; with the fix present the same workload is clean over 50 runs, and over 60 with the
planner defense intact. Instrumentation at the strip observes a shared snapshot (use count 3)
without the fix and a private one (use count 1) with it, which is the "two concurrent stripping
clones reach the reset" condition directly. The description now states that this half rests on that
reproduction rather than on a stateless test.

"clone guarantees more than it can" (raised by the reviewer's own pass). Five further
ReadFromMergeTree constructions pass a shared StorageSnapshot straight to the constructor,
which recomputes the strip flag from settings, so the concern was whether they bypass the
guarantee. They cannot: the constructor arms the strip only when
enable_shared_storage_snapshot_in_query is false, and in exactly that case
MergeTreeData::getStorageSnapshot bypasses the per-query snapshot cache, so a shared snapshot and
an armed strip are mutually exclusive for a constructor-built step. The two closest paths are also
single-lane by construction (pipeline.resize(1), and a single source).

💡 Noted, not blocking

SET max_block_size = DEFAULT restores the declared default rather than the value CI injected.
That is deliberate isolation: no assertion depends on max_block_size, only on the left table's
block count, which is fixed at insert time.

The three field assignments that copy SnapshotData were left as they are. Replacing them with
copy construction does not compile: -Weverything is on with no deprecated-copy exemption, and
StorageSnapshot::Data declares a virtual destructor, so both the copy-constructor and
copy-assignment forms fail on -Wdeprecated-copy-with-dtor. Making them compile means adding copy
semantics to a polymorphic base header included by 27 files, which is out of scope for this fix.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. <bin> local --path=$(mktemp -d) --queries-file 04510_direct_join_merge_tree_prewhere_clone.sql < /dev/null on the stock build_amd_release binary for this PR's merge-base b702eb6e2932: 25/25 FAIL. Same command on the PR head's binary: 0/25. No sanitizer, no server, no randomization needed.
b Root cause explained? Yes. getByKeys clones the lookup plan per lookup, one lookup per pipeline stream, so clones are concurrent. clone copied query_info by value while prewhere_info/row_level_filter are shared_ptrs, so all clones shared one filter DAG; tryRemoveUnusedColumns prunes that DAG in place and rewrites all_column_names/output_header, so one clone leaves a header missing outputs another clone still expects. Logic corruption, not a UAF, hence visible without a sanitizer.
c Fix matches root cause? Yes. The source fix (already published) deep-copies both filter DAGs, i.e. it removes the sharing that is the cause. This commit fixes the test's liveness at the trigger: concurrency (max_threads) and left-table block count. Nothing was widened or relaxed; no no-random-settings tag was added.
d Test intent preserved / new tests added? Yes, and strengthened. All three facet-1 cases kept, each now 25/25 unfixed instead of 7-11/20. Rows drop 1000 to 320, which raises the failure rate because block count, not row count, is the amplifier. One query was deleted because it is measured inert in both directions (0/25 unfixed even on the amplified fixture, at max_threads 4 and 16), i.e. it would pass with half the fix reverted; its setting moved onto a query that does fail without the fix.
e Both directions demonstrated? Yes. Edited file: 25/25 FAIL unfixed / 0/25 fixed. Per query standalone, unfixed vs fixed: PREWHERE 25/25 vs 0/25, row policy 25/25 vs 0/25. Plus 4 mutations: removing the max_threads pins and forcing max_threads = 1 drops coverage to 0/25 (the pin is load-bearing); reverting to the 2-block fixture drops to 19/25; query_plan_join_swap_table = 'false' stays 25/25 (so it needs no pin); flipping the snapshot setting to 1 stays 25/25 unfixed / 0/25 fixed (so that pin is an added exercise, not the trigger).
f Fix is general across code paths? Carriers re-derived: prewhere_info covered, row_level_filter covered, storage_snapshot not SQL-reachable by design (the planner clears enable_remove_parts_from_snapshot_optimization for every direct-join lookup, and isStream() on the right side hangs) so it is documented rather than covered by a query that cannot fail. Verified that planner behaviour is unchanged from master (git diff <merge-base>..HEAD -- src/Planner/PlannerJoinTree.cpp is empty).
g Fix generalizes across inputs (params/datatypes/wrappers)? Settings matrix measured rather than assumed: max_threads in {1 (the losing draw), 4 (pinned)}, enable_shared_storage_snapshot_in_query in {0, 1} both 25/25 unfixed and 0/25 fixed, query_plan_join_swap_table in {auto, false} both at least 24/25. Fixture boundary checked: max_block_size = 10 over 320 rows yields exactly 32 blocks, and SET max_block_size = DEFAULT restores 65409, so the join queries do not run under the reduced block size.
h Backward compatible? Yes. No setting defaults, no SettingsChangesHistory.cpp, no format or serialization surface. A test plus reference change cherry-picks cleanly, so the v26.6-must-backport label is unaffected.
i Invariants and contracts preserved? Yes. This commit changes no source behaviour. Test-level: the reference is generated from the fixed binary and each of its three numbers independently re-derived from the fixture (320 rows joined 1:1 gives 320 320; allowed_attrs holds Attribute_0..159 giving 160 160; row policy EventId < 100 gives 100 100). The test stays parallel-safe: per-database tables, and the row policy is the one global object, dropped inline and now also defensively at the top so the test reruns after an abort.

Randomized verification: clickhouse-test --test-runs 50 with randomization on, 50/50 pass. Because the runner prints drawn settings only on failure, the pin-beats-injection property was proven directly instead of by waiting for a draw: forcing both hostile values into the session (--client-option max_threads=1 --client-option enable_shared_storage_snapshot_in_query=1) gives 20/20 pass, and inside a pinned statement getSetting('max_threads') returns 4 while the session value is 1.

Session id: cron:clickhouse-review-slot-53:20260729-102200

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 7ab33ae

Every 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 CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) / 01666_merge_tree_max_query_limit trunk regression, not caused by this diff (fires on master and on many unrelated PRs in the same window) #112385 (mine, merged 2026-07-29 15:37Z); this build predates it, so a rerun after the next master merge picks it up
Stress test (arm_tsan) / Possible deadlock on shutdown (see gdb.log) chronic trunk shutdown-deadlock class: 35 hits over 27 unrelated PRs and 7 release/master runs in 30 days. The enclosing Stress test (arm_tsan) job is green on this head, so this is a sub-row rather than a job failure #111909 (external, merged 2026-07-27); this build predates it, so a rerun after the next master merge picks it up. A master-side residual of the same class remains under investigation at full effort
Sync - CH Inc sync (private, not actionable)

Session id: cron:our-pr-ci-monitor:20260729-180000

@clickhouse-gh

clickhouse-gh Bot commented Aug 1, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.70% +0.00%

Changed lines: Changed C/C++ lines covered: 36/37 (97.30%) · Uncovered code

Full report · Diff report

@groeneai

groeneai commented Aug 2, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 494eb18

Every 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 CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
AST fuzzer (amd_debug, targeted) / Logical error: Cannot serialize FutureSetFromSubquery with no query plan (STID 2678-3c21) pre-existing trunk bug, reached through a fuzzed PREWHERE id IN (subquery) shape. 30 hits across 21 unrelated PRs in 30 days, 0 on master. The merged #112443 covers the plain ordered-builder half only; a non-key PREWHERE ... IN still reaches the unordered buildSetInplace builder it does not cover, so this residual shape is a distinct defect a fix task owns it (investigating at full effort - fixing PR link to follow here)
Stress test (amd_msan) / Cannot start clickhouse-server + Check failed (two rows, one event) not PR-caused: the server aborts during metadata load because a stored CONSTRAINT CHECK (SELECT id FROM t1) IN (test_5.conversation) persisted the table's own column as a qualified table reference, so ATTACH TABLE t2__fuzz_27 fails with Missing columns: 'id'. Root-caused deterministically on pristine master; 2 hits / 2 unrelated authors in 30 days a fix task owns it, already root-caused and in implementation (fixing PR link to follow here)

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 ReadFromMergeTree StorageSnapshot rebinding in the direct-JOIN/PREWHERE path plus its own regression test.

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]>
@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - a253e24

Every 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 CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
AST fuzzer (amd_debug, targeted) / Logical error: Cannot serialize FutureSetFromSubquery with no query plan (STID 2678-3c21) pre-existing trunk bug, reached through a fuzzed PREWHERE id GLOBAL IN (subquery) shape over merge() + remoteSecure. The plan is consumed by the speculative in-place set build and never restored, so QueryPlan::serializeSets finds a null plan when sending the plan to a shard (SetsSerialization.cpp:125). 67 hits across 31 unrelated PRs in 30 days, 0 on master #102308 (external, open)
AST fuzzer (amd_debug, targeted, old_compatibility) / same assertion, same STID 2678-3c21 same defect, same frame chain (serializeSets <- QueryPlan::serialize <- MultiplexedConnections::sendQueryPlan); one event surfaced by two fuzzer parametrizations #102308 (external, open)

The other 172 checks are green (155 success, 17 skipped) and both aggregators, Config Workflow and
Finish Workflow, completed successfully.

Neither failure is caused by this PR's diff, which is 3 files: the ReadFromMergeTree::clone
PrewhereInfo/row-level-filter deep copy plus its own regression test. It touches nothing in
prepared-set construction or plan serialization. #102308 covers both the unordered buildSetInplace
and the ordered buildOrderedSetInplace halves, which is why it owns this shape rather than the
already-merged #112443 (ordered builder only).

Session id: cron:our-pr-ci-monitor:20260804-190000

@diegomestre2
diegomestre2 added this pull request to the merge queue Aug 5, 2026
Merged via the queue into ClickHouse:master with commit 3140a8c Aug 5, 2026
524 of 527 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Aug 5, 2026
@robot-ch-test-poll robot-ch-test-poll added pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-synced-to-cloud The PR is synced to the cloud repo labels Aug 5, 2026
clickhouse-gh Bot pushed a commit that referenced this pull request Aug 5, 2026
…h PREWHERE (shared PrewhereInfo corrupted by column pruning)
clickhouse-gh Bot added a commit that referenced this pull request Aug 5, 2026
Backport #109932 to 26.7: Fix crash in direct JOIN over MergeTree with PREWHERE (shared PrewhereInfo corrupted by column pruning)
PedroTadim added a commit that referenced this pull request Sep 10, 2026
Backport #109932 to 26.6: Fix crash in direct JOIN over MergeTree with PREWHERE (shared PrewhereInfo corrupted by column pruning)
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Sep 11, 2026
…geTree with PREWHERE (shared PrewhereInfo corrupted by column pruning)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.6-must-backport

Projects

None yet

8 participants