Skip to content

Fix NOT_FOUND_COLUMN_IN_BLOCK in query_plan_convert_join_to_in with arrayJoin JOIN key - #104809

Merged
tiandiwonder merged 13 commits into
ClickHouse:masterfrom
tiandiwonder:fix-arrayjoin-convert-join-to-in-not-found-column
Aug 19, 2026
Merged

tiandiwonder merged 13 commits into
ClickHouse:masterfrom
tiandiwonder:fix-arrayjoin-convert-join-to-in-not-found-column

Conversation

@tiandiwonder

@tiandiwonder tiandiwonder commented May 13, 2026 •

Copy link
Copy Markdown
Contributor

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 NOT_FOUND_COLUMN_IN_BLOCK exception in INNER JOIN ... ON arrayJoin(...) = ... queries when query_plan_convert_join_to_in is enabled and the SELECT references the source array column.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Problem

With SET query_plan_convert_join_to_in = 1 (off by default), the optimizer rewrites a hash INNER JOIN ON arrayJoin(L.col) = R.col into [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 column L.col itself, or arrayJoin(L.col) again, the rewritten plan throws

Code: 10. DB::Exception: Not found column __table1.tags in block ... (NOT_FOUND_COLUMN_IN_BLOCK)

at execution (and at EXPLAIN actions = 1 planning time).

Minimal repro:

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');

-- Throws NOT_FOUND_COLUMN_IN_BLOCK:
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;

-- Same with arrayJoin in the projection -- also throws:
SELECT lt.id, arrayJoin(lt.tags) FROM lt INNER JOIN rt ON arrayJoin(lt.tags) = rt.tag_id
SETTINGS query_plan_convert_join_to_in = 1;

Root cause

tryConvertJoinToIn builds left_pre_join_actions = JoinExpressionActions::getSubDAG(<left join keys>). The output set is only the JOIN-key expressions — arrayJoin(__table1.tags) and __table1.id in the repro — not the source __table1.tags array column.

Later, cloneSubDAGWithHeader(output_header, JoinExpressionActions::getSubDAG(join_output_actions)) clones the post-JOIN expressions onto a new DAG seeded from output_header. cloneSubDAGWithHeader calls mergeInplace(..., remove_dangling_inputs=true), which remaps INPUT nodes by name to the corresponding inputs in output_header. When join_output_actions references __table1.tags (because SELECT did), the source __table1.tags INPUT in second_dag has no match in output_header — mergeInplace's remove_dangling_inputs only removes input nodes that collide with first'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 had arrayJoin(lt.tags), or the column reference itself when SELECT had lt.tags) survive, and the resulting ExpressionStep cannot find the column at execution.

Fix

Decline the conversion in tryConvertJoinToIn whenever any input of join_output_actions is not among the outputs that left_pre_join_actions forwards. The check runs immediately after left_pre_join_actions / right_pre_join_actions are computed and before any plan mutation (makeExpressionNodeOnTopOf etc.), 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 appendInputsForUnusedColumns style (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 / clone of an ARRAY_JOIN-bearing DAG being merged into a context whose stream header does not provide a required INPUT column. The prior two are:

This PR follows the bail-out pattern of #97239 — tryConvertJoinToIn is 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 through left_pre_join_actions so 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_in is 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's 03918_arrayjoin_function_with_join_and_where. Four queries:

  1. 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).
  2. SELECT lt.id, lt.tags ... — before fix: NOT_FOUND_COLUMN_IN_BLOCK; after fix: correct result via the fallback JOIN path.
  3. SELECT lt.id, arrayJoin(lt.tags) ... — same shape as (2).
  4. Control: same as (3) with 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

  • Merged into: 26.8.1.1674 (included in 26.8 and later)

… `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]>
@clickhouse-gh

clickhouse-gh Bot commented May 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [7308723]

Summary: ✅


AI Review

Summary

This PR makes tryConvertJoinToIn bail out before rewriting when the post-JOIN output DAG would still depend on left-side inputs that the rewritten left-key ExpressionStep no longer exposes, and it adds focused regression coverage plus plan-shape assertions for the arrayJoin case. I did not find a remaining correctness issue in the current revision.

Final Verdict

✅ No new findings.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.80% 86.80% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 79.10% 79.20% +0.10%

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

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label May 13, 2026
@tiandiwonder tiandiwonder added the can be tested Allows running workflows for external contributors label Jun 15, 2026
…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.
tiandiwonder and others added 6 commits June 17, 2026 00:53
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
…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]>
@tiandiwonder
tiandiwonder requested review from KochetovNicolai and vdimir and removed request for KochetovNicolai July 8, 2026 11:41
@vdimir vdimir self-assigned this Jul 8, 2026
/// 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)`),

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.

Does issue reproduce only with arrayJoin in JOIN ON? Couldnt' we check it explicitly then (e.g. by ActionsDAG::hasArrayJoin)?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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

clickhouse-gh Bot commented Jul 14, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.80% 85.90% +0.10%
Functions 92.70% 92.70% +0.00%
Branches 78.00% 78.00% +0.00%

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

Full report · Diff report

@vdimir vdimir left a comment

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.

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

clickhouse-gh Bot commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 730872369 with master d4655dda5 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 695.12 MiB 692.10 MiB -3.02 MiB (-0.43%)

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 units

7 translation units recompiled, 11 s compile time in total, 7 of them have a recent master baseline.

Job report

@clickhouse-gh

clickhouse-gh Bot commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

🟢 AI verdict: improvement — 4 query(s) improved out of 34 analysed

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 · ⚠️ 6 inconclusive

Flagged queries (8 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
🟢 23 improvement 164 76 ×2.2 faster <0.0001 Q23 shows a large ×2.2 faster shift confirmed by both tests and locked in by the trust override; the magnitude is real, though this narrow JOIN-to-IN guard doesn't execute on this single-table query.
🟢 31 improvement 408 305 -25.2% <0.0001 Q31's -25.2% shift is large and consistent enough to be locked in by the trust override; the delta is trustworthy even though this single-table query doesn't exercise the changed JOIN-to-IN path.
⚠️ 13 not_sure 422 343 -18.7% <0.0001 ClickBench Q13 is a single-table aggregation with no JOIN; this PR only guards convertJoinToIn for arrayJoin JOIN-ON keys, so it can't cause the -18.7% shift, which reads as run-to-run variance.
⚠️ 15 not_sure 192 163 -15.1% <0.0001 Q15 is single-table with no JOIN, so this PR's narrow JOIN-to-IN arrayJoin guard doesn't execute here; the -15.1% delta is not attributable to the change.
⚠️ 16 not_sure 734 610 -16.8% <0.0001 Q16 has no JOIN; the changed convertJoinToIn path is never reached, so the -16.8% improvement is environment/variance, not a PR effect.
⚠️ 18 not_sure 1244 1082 -13.1% <0.0001 Q18 is a single-table scan with no JOIN and noisy measurements; this PR's arrayJoin JOIN-to-IN guard can't touch it, so the -13.1% delta reads as variance.
⚠️ 30 not_sure 279 228 -18.3% <0.0001 Q30 is single-table with no JOIN; the changed code path isn't reached, so the -18.3% delta is not attributable to this PR.
⚠️ 33 not_sure 1250 1176 -5.9% <0.0001 Q33 is single-table with no JOIN and only a -5.9% delta; the changed convertJoinToIn path isn't reached, so this reads as run-to-run variance.

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)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
🟢 7 improvement 560 69 ×8.1 faster <0.0001 join_operator: TPC-H Q7 is ×8.1 faster (559.5→69 ms), a very large delta confirmed by both tests and locked in; TPC-H has no arrays, so this PR's arrayJoin JOIN-to-IN guard cannot be the cause, and attribution is doubtful.
🟢 8 improvement 166 80 ×2.1 faster <0.0001 join_operator: TPC-H Q8 is ×2.1 faster (166.5→80 ms), a clear shift locked in by magnitude; TPC-H joins have no arrayJoin keys, so this narrow guard can't drive it — the number is real but not this PR's doing.

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
  • StressHouse run: a239c89d-ba00-4bc8-9633-3fc904e3e48b
  • MIRAI run: 06543eef-bd4a-4e3a-a3ae-ae32edafe615
  • PR check IDs:
    • clickbench_1907974_1787051511
    • clickbench_1907980_1787051511
    • clickbench_1907986_1787051511
    • tpch_adapted_1_official_1907992_1787051511
    • tpch_adapted_1_official_1908030_1787051511
    • tpch_adapted_1_official_1908044_1787051511

@tiandiwonder
tiandiwonder added this pull request to the merge queue Aug 18, 2026
Merged via the queue into ClickHouse:master with commit 1d2de4b Aug 19, 2026
357 of 358 checks passed
@tiandiwonder
tiandiwonder deleted the fix-arrayjoin-convert-join-to-in-not-found-column branch August 19, 2026 00:20
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 19, 2026
@clickgapai

Copy link
Copy Markdown
Contributor
Reproducer
SET 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:

  • Reproduces on: 26.7, 26.6, 26.5, 26.3
  • Does not reproduce on: master, 25.8
  • Tested versions: master, 26.7, 26.6, 26.5, 26.3, 25.8
  • Also tested (unsupported, context only): 26.2 reproduces
  • ✓ Fix is on master — this PR's change fixes the bug on master. The releases listed above still have the bug and need the backport.

Backport the fix to 26.7, 26.6, 26.5, 26.3.

CC component owner: @davenger @KochetovNicolai

Analysis metadata

comp-query-optimizer · Severity P2 · Finding phase_d_pr104809

Introducing change: not identified
  • Secondary components: comp-testing

groeneai added a commit to groeneai/ClickHouse that referenced this pull request Aug 21, 2026
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]>
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-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.

5 participants