Repository navigation
Fix NOT_FOUND_COLUMN_IN_BLOCK in query_plan_convert_join_to_in with arrayJoin JOIN key - #104809
Conversation
… `arrayJoin` JOIN key When `tryConvertJoinToIn` rewrote `INNER JOIN ON arrayJoin(L.col) = R.col` and the SELECT (or any post-JOIN expression) referenced the source array column `L.col` or `arrayJoin(L.col)` again, the cloned post-JOIN expression DAG referenced an INPUT (`__table1.tags`) that the rewritten plan no longer exposed. `left_pre_join_actions` only forwards the JOIN key expressions, so the downstream `cloneSubDAGWithHeader` left a dangling INPUT, which threw `Code: 10 ... Not found column __table1.tags in block ... (NOT_FOUND_COLUMN_IN_BLOCK)` at execution. Decline the conversion in `tryConvertJoinToIn` whenever an input of the `join_output_actions` sub-DAG is not present in the outputs that `left_pre_join_actions` forwards. The bail-out happens before any plan mutation. The query then runs through the regular JOIN path and produces the correct result. Same root-cause family as PR ClickHouse#96989, PR ClickHouse#97239 and PR ClickHouse#104785: a plan-transformation pass merges or clones an ARRAY_JOIN-bearing DAG into a context whose stream header does not provide the required INPUT. Each prior fix took a call-site bail-out or post-merge cleanup; this PR follows the bail-out pattern (matching PR ClickHouse#97239). A more invasive follow-up could forward the missing left-side columns through `left_pre_join_actions` so the optimization stays on; left for a separate PR once we have data on how often the bail-out fires. The setting `query_plan_convert_join_to_in` is off by default, so the bug is reachable only when explicitly enabled. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
Workflow [PR], commit [7308723] Summary: ✅
AI ReviewSummaryThis PR makes Final Verdict✅ No new findings. LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 16/16 (100.00%) · Uncovered code |
…ail-out The `tryConvertJoinToIn` bail-out added in this PR computes `JoinExpressionActions::getSubDAG(join_output_actions)` before mutating the plan. For queries where the conversion is still applied (the `system.query_log` EXPLAIN in `03355_join_to_in_optimization`), this extra `cloneSubDAG` perturbs node-allocation order, which only changes how the merged `ExpressionStep` actions are grouped in the EXPLAIN description (`Join output actions` is now described in the outer projection rather than the inner expression). The conversion still fires (`CreatingSets` is still present) and the query executes with the same result, so the plan is semantically unchanged. Only the EXPLAIN text needs to be refreshed. Verified locally: reverting the bail-out reproduces the previous reference byte-for-byte, confirming this build's EXPLAIN description ordering matches CI's and that the diff is attributable solely to the bail-out.
The flaky check (which re-runs changed tests under randomized settings) fails `03355_join_to_in_optimization` because its `EXPLAIN` output is sensitive to randomized query-plan settings (parallel replicas, join rewrites, etc.): under those settings the optimizer produces a different but equally valid plan (e.g. `ReadFromSystemOneBlock` instead of the expected shape), which does not match the reference. This test became a "changed test" — and therefore subject to the flaky check — because the JOIN-to-IN bail-out in this PR changes its default `EXPLAIN` output (the reference was regenerated accordingly). Pin the test to deterministic settings, as 37 other EXPLAIN `.sql` tests already do, so the flaky check exercises it under the settings it was written for. CI: ClickHouse#104809
The test exercises `query_plan_convert_join_to_in` with `arrayJoin` in `JOIN ON`, which are new-analyzer features. In CI shards that run with the old analyzer (e.g. `amd_llvm_coverage, old analyzer, s3 storage, DatabaseReplicated`), the old analyzer rejects `arrayJoin` in `JOIN ON` with `INVALID_JOIN_ON_EXPRESSION` before the optimization is ever reached, so the test failed there. Add `SET enable_analyzer = 1` so the test always runs under the analyzer the fix targets (`03355` in this PR already does the same and passes that shard). CI: ClickHouse#104809
# Conflicts: # tests/queries/0_stateless/03355_join_to_in_optimization.sql
…rt-join-to-in-not-found-column
…ession header in `tryConvertJoinToIn` The bail-out guard compared inputs of `join_output_actions` against a name set of `left_pre_join_actions` outputs. That was too loose for duplicate names (a second same-named input could pass while `mergeInplace` leaves it dangling) and too strict for columns that `ActionsDAG::updateHeader` forwards unconsumed (safe projections of non-key left columns silently disabled the optimization). Compare against the real post-expression header with per-name counts instead, mirroring the multiplicity-aware matching in `mergeInplace`. Add `EXPLAIN` assertions for both the converted and declined plans, and revert the `03355_join_to_in_optimization` reference edit that was an artifact of the old guard's spurious bail-out. Co-Authored-By: Claude Fable 5 <[email protected]>
The test's case (1) comment wrongly said the SELECT references the JOIN key column; it references `id`, a non-key column forwarded by the post-expression stream. The test header implied `left_pre_join_actions` forwards only the JOIN keys; the stream also forwards unconsumed left-header columns. Tighten the guard comment in `tryConvertJoinToIn` and use inline code formatting consistently. Co-Authored-By: Claude Fable 5 <[email protected]>
| /// Decline the conversion if the rewritten plan could not resolve some | ||
| /// input of `join_output_actions`: `mergeInplace` with | ||
| /// `remove_dangling_inputs = true` would drop the unmatched INPUT (e.g. | ||
| /// source `L.col` whose only forwarded form is `arrayJoin(L.col)`), |
There was a problem hiding this comment.
Does issue reproduce only with arrayJoin in JOIN ON? Couldnt' we check it explicitly then (e.g. by ActionsDAG::hasArrayJoin)?
There was a problem hiding this comment.
Good question — I checked, and ActionsDAG::hasArrayJoin() unfortunately can't gate this. hasArrayJoin() scans for ActionType::ARRAY_JOIN nodes, but an arrayJoin in a JOIN ON key is not represented as an ARRAY_JOIN node in the key sub-DAG here, so it returns false — I verified empirically that gating the check on it lets the NOT_FOUND_COLUMN_IN_BLOCK case (SELECT ... lt.tags with ON arrayJoin(lt.tags) = ...) slip straight through. The issue also isn't strictly arrayJoin-specific in principle: the real trigger is a join-key expression that consumes a source column so it no longer appears in the post-expression header, and the header-resolution check detects exactly that (and keeps the conversion when the consumed column isn't referenced after the JOIN, e.g. the just_id case). I added a comment recording why hasArrayJoin doesn't work here so it isn't retried later.
An `arrayJoin` in a JOIN ON key is not represented as an `ARRAY_JOIN` DAG node in the key sub-DAG, so `ActionsDAG::hasArrayJoin()` returns false and cannot be used to gate the dangling-input check (verified: gating on it lets the `NOT_FOUND_COLUMN_IN_BLOCK` case through). The header-resolution check is what actually detects a source column consumed by the key expression. Co-Authored-By: Claude Fable 5 <[email protected]>
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 16/16 (100.00%) · Uncovered code |
vdimir
left a comment
There was a problem hiding this comment.
By the way, back in the days there was a suggestion to forbid JOIN ON with arrayJoin: #56807 (comment)
But now it's probably too late
…dangling The style check rejects "new analyzer" / "new-analyzer" wording since `35e4d200cf3`. This branch was cut before that commit, so the check that ran on it used a version of `various_checks.sh` without the rule and stayed green; the rule fires as soon as the branch sees current master. Reword the two comment lines. No behaviour change.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction. Compile time of recompiled translation units7 translation units recompiled, 11 s compile time in total, 7 of them have a recent master baseline. |
|
📊 Cloud Performance Report 🟢 AI verdict: This PR is a narrow correctness fix in the JOIN-to-IN plan optimization: it only declines the conversion when an arrayJoin JOIN-ON key would drop a dangling input, and it does not change the hot path for array-free joins or single-table scans. Yet all 10 flagged queries are improvements across ClickBench single-table aggregations and array-free TPC-H joins — neither of which reaches the changed code — so the deltas read as environment/run-to-run variance, consistent with source having far fewer samples (6 vs 30 base runs). The six non-locked ClickBench improvements are downgraded to not_sure; ClickBench Q23/Q31 and TPC-H Q7/Q8 are left as improvements because their large, consistent magnitude locks them in, but their attribution to this PR is doubtful and should not be credited to the change. clickbench🟢 2 improved · Flagged queries (8 of 43)
Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. tpch_adapted_1_official🟢 2 improved Flagged queries (2 of 22)
Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. Debug info
|
1d2de4b
ReproducerSET enable_analyzer = 1;
CREATE TABLE lt (id UInt64, tags Array(String)) ENGINE = MergeTree ORDER BY id;
CREATE TABLE rt (tag_id String) ENGINE = MergeTree ORDER BY tag_id;
INSERT INTO lt VALUES (1, ['a','b','c']), (2, ['d','e']);
INSERT INTO rt VALUES ('a'), ('d');
SELECT lt.id, lt.tags FROM lt INNER JOIN rt ON arrayJoin(lt.tags) = rt.tag_id
SETTINGS query_plan_convert_join_to_in = 1;
-- 26.2..26.7: Code: 10. DB::Exception: Not found column __table1.tags: in block arrayJoin(__table1.tags) String, __table1.id UInt64. (NOT_FOUND_COLUMN_IN_BLOCK)
-- 25.8 and master (post-#104809): returns 1 ['a','b','c'] / 2 ['d','e']
-- EXPLAIN description=0 on the same SELECT throws too, so no data is needed to see it.Results:
Backport the fix to CC component owner: @davenger @KochetovNicolai Analysis metadata
Introducing change: not identified
|
Master merged 03918_convert_join_to_in_arrayjoin_dangling with ClickHouse#104809, and its case (5) asserts that the conversion fires. It expressed that through an implicit ALL INNER JOIN, which the strictness gate on this branch declines, so after merging master the test reported explain_just_id 0 0 against a reference of 1 1. The six join sites become SEMI LEFT JOIN, which is what this branch still converts, and the file pins join_algorithm plus the four join and transfer limits because the conversion also declines on a non-hash algorithm listed first or on any active limit, and the standard test profile sets those limits. The reference is unchanged: each left row matches at most once in this fixture, so SEMI LEFT returns the same rows the ALL INNER form did. Both plan arms still discriminate, measured on the merged binary: case (5) gives Join 0 and CreatingSets 1, case (6) gives Join 1 and CreatingSets 0, so the forwarded column guard master added is still exercised on the declining side. Found by the second-model re-review of the master merge, which walks the whole PR change rather than only the merge delta. Co-Authored-By: Claude Fable 5 <[email protected]>
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix
NOT_FOUND_COLUMN_IN_BLOCKexception inINNER JOIN ... ON arrayJoin(...) = ...queries whenquery_plan_convert_join_to_inis enabled and the SELECT references the source array column.Documentation entry for user-facing changes
Problem
With
SET query_plan_convert_join_to_in = 1(off by default), the optimizer rewrites a hashINNER JOIN ON arrayJoin(L.col) = R.colinto[Expression("Calculate join left keys"), Filter("IN"), DelayedCreatingSets, Expression("Join output actions")]. If the SELECT projection (or any post-JOIN expression) references the source array columnL.colitself, orarrayJoin(L.col)again, the rewritten plan throwsat execution (and at
EXPLAIN actions = 1planning time).Minimal repro:
Root cause
tryConvertJoinToInbuildsleft_pre_join_actions = JoinExpressionActions::getSubDAG(<left join keys>). The output set is only the JOIN-key expressions —arrayJoin(__table1.tags)and__table1.idin the repro — not the source__table1.tagsarray column.Later,
cloneSubDAGWithHeader(output_header, JoinExpressionActions::getSubDAG(join_output_actions))clones the post-JOIN expressions onto a new DAG seeded fromoutput_header.cloneSubDAGWithHeadercallsmergeInplace(..., remove_dangling_inputs=true), which remapsINPUTnodes by name to the corresponding inputs inoutput_header. Whenjoin_output_actionsreferences__table1.tags(because SELECT did), the source__table1.tagsINPUT insecond_daghas no match inoutput_header—mergeInplace'sremove_dangling_inputsonly removes input nodes that collide withfirst's inputs, not input nodes that have no counterpart at all. The non-INPUT nodes that depend on it (the cloned ARRAY_JOIN node when SELECT hadarrayJoin(lt.tags), or the column reference itself when SELECT hadlt.tags) survive, and the resultingExpressionStepcannot find the column at execution.Fix
Decline the conversion in
tryConvertJoinToInwhenever any input ofjoin_output_actionsis not among the outputs thatleft_pre_join_actionsforwards. The check runs immediately afterleft_pre_join_actions/right_pre_join_actionsare computed and before any plan mutation (makeExpressionNodeOnTopOfetc.), so the bail-out is safe — the query then runs through the normal JOIN path and produces the correct result.{ auto join_output_actions_subdag = JoinExpressionActions::getSubDAG(join_output_actions); std::unordered_set<std::string_view> forwarded_columns; for (const auto * out : left_pre_join_actions.getOutputs()) forwarded_columns.insert(out->result_name); for (const auto * input : join_output_actions_subdag.getInputs()) if (!forwarded_columns.contains(input->result_name)) return 0; }The check mirrors the established
appendInputsForUnusedColumnsstyle (ActionsDAG.cpp:1453-1461), which is the idiomatic "verify every input is present in a sample block" pattern in this codebase.Related fixes for the same root cause
This is the third bug in 12 months rooted in
mergeInplace/cloneof an ARRAY_JOIN-bearing DAG being merged into a context whose stream header does not provide a required INPUT column. The prior two are:ARRAY_JOINin the pushdown eligibility check).ARRAY_JOINafter the merge and abandon the optimization).arrayJoinexecution in JOIN ON with new logical join step #104785 (post-hoc cleanup strategy: snapshot the merged-inARRAY_JOINpointers and drop them after the merge via a newActionsDAG::removeNodeshelper).This PR follows the bail-out pattern of #97239 —
tryConvertJoinToInis an optional optimization, so declining the rewrite is safe and the query falls back to the regular JOIN path. A more invasive follow-up could forward the missing left-side columns throughleft_pre_join_actionsso the optimization stays on even in these cases; left for a separate PR once we have evidence that real workloads hit the bail-out frequently.The setting
query_plan_convert_join_to_inis off by default, so the bug is reachable only when explicitly enabled.Regression test
tests/queries/0_stateless/03918_convert_join_to_in_arrayjoin_dangling.{sql,reference}— co-located with #96989's03918_arrayjoin_function_with_join_and_where. Four queries:SELECT lt.id ... INNER JOIN ... ON arrayJoin(lt.tags) = rt.tag_id— the optimization stays on, returns the correct rows (validates the fix's "no-regression" guarantee for the cases it does not bail out on).SELECT lt.id, lt.tags ...— before fix: NOT_FOUND_COLUMN_IN_BLOCK; after fix: correct result via the fallback JOIN path.SELECT lt.id, arrayJoin(lt.tags) ...— same shape as (2).query_plan_convert_join_to_in = 0. Confirms the fallback path returns the same answer the fix produces in (3).Repro-first verified: queries (2) and (3) were observed to fail with NOT_FOUND_COLUMN_IN_BLOCK on un-fixed upstream master (
7bd0fa28146) before the reference was locked.Version info
26.8.1.1674(included in26.8and later)