Skip to content

Fix duplicate arrayJoin execution in JOIN ON with new logical join step - #104785

Merged
tiandiwonder merged 1 commit into
ClickHouse:masterfrom
tiandiwonder:fix-arrayjoin-join-on-duplicate-62315
May 27, 2026
Merged

tiandiwonder merged 1 commit into
ClickHouse:masterfrom
tiandiwonder:fix-arrayjoin-join-on-duplicate-62315

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 wrong row count from arrayJoin() used inside JOIN ON: the result was multiplied by the array length an extra time.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Problem

SELECT count() FROM items
INNER JOIN tags ON arrayJoin(items.tag_ids) = tags.id
WHERE items.filter_key = 'target';

With query_plan_use_new_logical_join_step = 1 (the default), this query returns |tag_ids|² × N_items rows instead of the expected |tag_ids| × N_items. On an array of size 300 the result is 300× larger than correct. Workaround: SET query_plan_use_new_logical_join_step = 0.

Root cause

When a WHERE filter is pushed below a JoinStepLogical whose ON clause contains arrayJoin(...), fix_predicate_for_join_logical_step in filterPushDown.cpp merges pre_filter_dag (which carries the ON-side ARRAY_JOIN node) into the pushed-down filter. removeUnusedActions preserves that ARRAY_JOIN unconditionally because of the row-changing carve-out in ActionsDAG.cpp (removeUnusedActions treats every ARRAY_JOIN node as a root since removing it would silently change row count). The same ARRAY_JOIN is then independently cloned into the per-side "Pre Join Actions" ExpressionStep by JoinStepLogical::buildPhysicalJoinImpl, so each input row is expanded by |array| twice.

EXPLAIN actions = 1 on the buggy plan shows two ARRAY JOIN __table1.tag_ids actions on the items side (one in Right Pre Join Actions, one in the pushed-down filter). The fix collapses them to one.

Fix

Snapshot the ARRAY_JOIN node pointers in pre_filter_dag before the merge. ActionsDAG::merge is implemented as mergeInplace, which uses std::list::splice to move second.nodes into first.nodes, so addresses stay valid in filter_dag after the merge and the snapshot lets us identify the merged-in nodes by pointer rather than by result_name (correctly handling nested forms like JOIN ON toString(arrayJoin(a)) = b).

After the merge + removeUnusedActions, drop those nodes via a new narrow API ActionsDAG::removeNodes(std::unordered_set<const Node *>). The new helper computes its own transitive-required closure from outputs (without the row-changing carve-out) so any node still required by the filter predicate is kept regardless of to_remove; ghost ARRAY_JOINs that fell out of the filter's transitive closure are removed.

Safety:

  • splitActionsForJOINFilterPushDown rejects ARRAY_JOIN from allowed_nodes, so the filter_dag arriving at fix_predicate_for_join_logical_step is guaranteed not to contain any ARRAY_JOIN of its own. Every ARRAY_JOIN we see after the merge must have come from pre_filter_dag.
  • JoinStepLogical::buildPhysicalJoinImpl independently materialises the same JOIN-side expression DAG into the per-side "Pre Join Actions" ExpressionStep above the filter, so dropping the ghost copy in the pushed-down filter does not lose the expression -- the row expansion still happens, once, above the JOIN.

Related fixes for the same root cause

This is the third bug in 12 months rooted in removeUnusedActions' row-changing carve-out interacting with mergeInplace / clone of ARRAY_JOIN-bearing DAGs. The prior two are #96989 (prevention strategy: blacklist ARRAY_JOIN in the pushdown eligibility check) and #97239 (bail-out strategy: detect ghost ARRAY_JOIN after the merge and abandon the optimization). This PR uses a third strategy -- post-hoc cleanup -- because fix_predicate_for_join_logical_step is a mandatory plan transformation (the merge is required to propagate join_use_nulls type conversions), so neither prevention nor bail-out is applicable.

Regression test

tests/queries/0_stateless/03918_arrayjoin_join_on_duplicate_execution.{sql,reference} -- co-located with #96989's regression test 03918_arrayjoin_function_with_join_and_where so the two related fixes share a number prefix. 12 queries covering:

  • Result-level fix evidence: baseline, reversed equality direction, nested toString(arrayJoin(...)), runtime-filter off, disjunction-push-down off.
  • Mechanism-level evidence: EXPLAIN actions = 1 substring count of 'ARRAY JOIN ' -- buggy plan has one extra ghost action.
  • Bilateral arrayJoin: JOIN ON arrayJoin(L) = arrayJoin(R) with WHERE on left only, right only, and both sides simultaneously, so both left-side and right-side fix_predicate_for_join_logical_step invocations are exercised symmetrically.
  • Plan-shape invariant check: a query with a WHERE-side AND arrayJoin(...) conjunct -- validates that the upstream splitActionsForJOINFilterPushDown rejection keeps the WHERE-side arrayJoin above the JOIN while the ON-side ghost is removed.
  • Controls: query_plan_use_new_logical_join_step = 0 baseline and subquery rewrite (must keep returning the correct count to detect regression of the unrelated paths).

Repro-first verified: every query that claims to be fixed by this PR was first run on un-fixed master and observed to fail with the exact bug-shape values before the reference was locked.

Version info

  • Backported to: 26.5.4.15, 26.4.5.69, 26.3.16.9, 25.8.29.3

@clickhouse-gh

clickhouse-gh Bot commented May 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [9517222]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_debug, parallel) FAIL
04201_trivial_count_with_additional_filter FAIL cidb IGNORED
Integration tests (amd_tsan, 2/6) FAIL
test_storage_kafka/test_batch_slow_4.py::test_kafka_consumer_failover[generate_new_create_table_query] FAIL cidb IGNORED

AI Review

Summary

This PR fixes duplicate ARRAY_JOIN execution when filter pushdown merges JoinStepLogical pre-join actions into pushed predicates, which could multiply row counts by an extra array cardinality factor. The new cleanup path (ActionsDAG::removeNodes) is correctly scoped to remove only merged-in ghost ARRAY_JOIN nodes that are not required by the pushed filter output, and the added stateless regression test covers baseline, nested expression, plan-shape, and bilateral arrayJoin ON scenarios.

Final Verdict
  • Status: ✅ Approve

@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 May 13, 2026
…step

When the WHERE filter is pushed below a `JoinStepLogical` whose ON clause
contains `arrayJoin`, `fix_predicate_for_join_logical_step` merged an
`ARRAY_JOIN` node from the per-side join expression DAG into the
pushed-down filter. `removeUnusedActions` preserved that `ARRAY_JOIN`
unconditionally because it changes the number of rows. The same
`ARRAY_JOIN` is recomputed later in the per-side "Pre Join Actions"
`ExpressionStep`, multiplying row count by the array length twice -- so
on an array of size 300 the expected 60 000 result rows balloon to
18 000 000.

Snapshot the `ARRAY_JOIN` nodes contributed by `pre_filter_dag` by
pointer identity before the merge (`mergeInplace` splices second's
nodes into first's `nodes` list, preserving addresses) and drop them
after the merge via the new narrow API
`ActionsDAG::removeNodes(unordered_set<const Node *>)`. Safety:
- `splitActionsForJOINFilterPushDown` rejects `ARRAY_JOIN` from
  `allowed_nodes`, so `filter_dag` arriving at this helper is guaranteed
  not to contain any `ARRAY_JOIN` of its own; every `ARRAY_JOIN` we see
  after the merge must have come from `pre_filter_dag`.
- `JoinStepLogical::buildPhysicalJoinImpl` independently clones the same
  JOIN-side expression DAG into the per-side "Pre Join Actions"
  `ExpressionStep`, so the dropped expression is recomputed above this
  filter and the result remains correct.

Related fixes for the same root cause (`removeUnusedActions` row-changing
carve-out interacting with merge/clone of `ARRAY_JOIN`-bearing DAGs):
prevention path in PR ClickHouse#96989, bail-out path in PR ClickHouse#97239. This PR
addresses the remaining cleanup path.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@tiandiwonder
tiandiwonder force-pushed the fix-arrayjoin-join-on-duplicate-62315 branch from 052cad0 to 9517222 Compare May 13, 2026 04:14
@clickhouse-gh

clickhouse-gh Bot commented May 13, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.10% 84.10% +0.00%
Functions 91.10% 91.10% +0.00%
Branches 76.60% 76.50% -0.10%

Changed lines: 38.24% (13/34) · Uncovered code

Full report · Diff report

/// carve-out for ARRAY_JOIN. Nodes still required by any output are kept.
/// Caller MUST ensure removed ARRAY_JOIN is recomputed elsewhere in the plan.
/// Returns count of removed nodes.
size_t removeNodes(const std::unordered_set<const Node *> & to_remove);

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.

I think the logic is correct. The only issue is I don't like the som many different remove functions got another friend. However it is well documented and I don't have a better idea, so I am okay keeping it.

@tiandiwonder
tiandiwonder added this pull request to the merge queue May 27, 2026
Merged via the queue into ClickHouse:master with commit 72562a1 May 27, 2026
163 of 166 checks passed
@tiandiwonder
tiandiwonder deleted the fix-arrayjoin-join-on-duplicate-62315 branch May 27, 2026 00:56
@clickgapai

Copy link
Copy Markdown
Contributor

Hi @tiandiwonder @antaljanosbenjamin — a couple of suggestions to make this PR easier for reviewers and the changelog reader.

Description (currently incomplete):

  • Why: The PR description is empty - it only contains the standard template without any explanation of what changed or why.

  • Suggested addition:

    What this fixes

    When arrayJoin() is used inside JOIN ON, the array join operation was being executed twice - once in the pushed-down filter and once in JoinStepLogical's Pre Join Actions. This caused the row count to be multiplied by the array length an extra time.

    How it works

    Adds a new ActionsDAG::removeNodes method that explicitly removes specified nodes, bypassing removeUnusedActions's carve-out that preserves ARRAY_JOIN nodes (since they change row count). In fix_predicate_for_join_logical_step, we snapshot ARRAY_JOIN nodes from pre_filter_dag before merging, then remove them after the merge since they're already computed by the join step's Pre Join Actions.

Ignore this if the current title/body is intentional.

@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label May 27, 2026
@antonio2368 antonio2368 added the pr-must-backport Pull request should be backported intentionally. Use this label with great care! label Jun 25, 2026
robot-ch-test-poll added a commit that referenced this pull request Jun 25, 2026
Cherry pick #104785 to 26.3: Fix duplicate `arrayJoin` execution in JOIN ON with new logical join step
robot-clickhouse added a commit that referenced this pull request Jun 25, 2026
robot-ch-test-poll added a commit that referenced this pull request Jun 25, 2026
Cherry pick #104785 to 26.4: Fix duplicate `arrayJoin` execution in JOIN ON with new logical join step
robot-clickhouse added a commit that referenced this pull request Jun 25, 2026
robot-ch-test-poll added a commit that referenced this pull request Jun 25, 2026
Cherry pick #104785 to 26.5: Fix duplicate `arrayJoin` execution in JOIN ON with new logical join step
robot-clickhouse added a commit that referenced this pull request Jun 25, 2026
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Jun 25, 2026
tiandiwonder added a commit that referenced this pull request Jun 26, 2026
Backport #104785 to 26.3: Fix duplicate `arrayJoin` execution in JOIN ON with new logical join step
tiandiwonder added a commit that referenced this pull request Jun 26, 2026
Backport #104785 to 26.4: Fix duplicate `arrayJoin` execution in JOIN ON with new logical join step
tiandiwonder added a commit that referenced this pull request Jun 26, 2026
Backport #104785 to 26.5: Fix duplicate `arrayJoin` execution in JOIN ON with new logical join step
tiandiwonder added a commit that referenced this pull request Jun 26, 2026
Resolve conflict in filterPushDown.cpp: on 25.8,
`fix_predicate_for_join_logical_step` takes `const ActionsDAG & side_dag`
and merges `side_dag.clone()`. Re-applied the #104785 ARRAY_JOIN-ghost
removal onto that structure: snapshot ARRAY_JOIN nodes from a named
`side_dag_clone` (so the post-`merge` `list::splice` keeps their node
addresses valid) and `removeNodes` them after `removeUnusedActions`.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
robot-clickhouse added a commit that referenced this pull request Jun 26, 2026
Cherry pick #104785 to 25.8: Fix duplicate `arrayJoin` execution in JOIN ON with new logical join step
robot-clickhouse added a commit that referenced this pull request Jun 26, 2026
@robot-ch-test-poll robot-ch-test-poll added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Jun 26, 2026
tiandiwonder added a commit that referenced this pull request Jul 7, 2026
Backport #104785 to 25.8: Fix duplicate `arrayJoin` execution in JOIN ON with new logical join step
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Aug 1, 2026
A non equi JOIN ON condition that mixes columns from both sides becomes a
residual filter, which buildAdditionalFilter evaluates once per probe batch,
after which joinRightColumnsWithAdditionalFilter indexes the resulting mask
by row position. That requires the condition to preserve the number of rows.

arrayJoin does not. ActionsDAG::ActionType::ARRAY_JOIN is the only
row-count-changing action, and nothing removes it from the residual when the
condition spans both sides. An arrayJoin over an empty array makes the mask
shorter than the batch, which reads past the end of a PaddedPODArray and
raises a logical error, aborting the server in debug and sanitizer builds.
One that multiplies rows makes the mask longer, so flags pair with the wrong
rows and the query silently returns wrong results.

The fix rejects such a condition in
HashJoin::validateAdditionalFilterExpression, which already enforces this
expression's contract, so all fourteen HashJoin construction sites are
covered by construction. A one-sided arrayJoin is hoisted into a pre-join
step and keeps working, as does a plain INNER join, which pushes the
condition down instead of building a residual. The unnest alias resolves to
the same function and is rejected too.

Found by the stress test, STID 2508-224e.

Related: ClickHouse#104785

Co-Authored-By: Claude Fable 5 <[email protected]>
joelynch pushed a commit to aiven/ClickHouse that referenced this pull request Aug 17, 2026
…ettings absent on 25.8

The backport of ClickHouse#104785 (ClickHouse#108444) cherry-picked the master regression test
verbatim. Two of its control queries use settings that do not exist on 25.8 —
`enable_join_runtime_filters` and `use_join_disjunctions_push_down` — so the
test aborts with `UNKNOWN_SETTING` on 25.8. Those optimizations are absent on
25.8, so the "off" controls are redundant with the baseline anyway; drop them
and their reference lines. The core fix assertions (ON-side arrayJoin ghost
removed: count = 6 not 18, ARRAY-JOIN plan count = 1 not 2) and the bilateral
both-side cases are kept. Verified the test passes against a locally-built
25.8 `clickhouse` binary.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
pull Bot pushed a commit to erickirt/ClickHouse that referenced this pull request Aug 19, 2026
… `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]>
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 Pull request should be backported intentionally. Use this label with great care! 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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants