Repository navigation
Fix duplicate arrayJoin execution in JOIN ON with new logical join step - #104785
tiandiwonder merged 1 commit into
Conversation
|
Workflow [PR], commit [9517222] Summary: ❌
AI ReviewSummaryThis PR fixes duplicate Final Verdict
|
…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]>
052cad0 to
9517222
Compare
LLVM Coverage Report
Changed lines: 38.24% (13/34) · Uncovered code |
| /// 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); |
There was a problem hiding this comment.
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.
72562a1
|
Hi @tiandiwonder @antaljanosbenjamin — a couple of suggestions to make this PR easier for reviewers and the changelog reader. Description (currently
Ignore this if the current title/body is intentional. |
Cherry pick #104785 to 26.3: Fix duplicate `arrayJoin` execution in JOIN ON with new logical join step
… ON with new logical join step
Cherry pick #104785 to 26.4: Fix duplicate `arrayJoin` execution in JOIN ON with new logical join step
… ON with new logical join step
Cherry pick #104785 to 26.5: Fix duplicate `arrayJoin` execution in JOIN ON with new logical join step
… ON with new logical join step
Backport #104785 to 26.3: Fix duplicate `arrayJoin` execution in JOIN ON with new logical join step
Backport #104785 to 26.4: Fix duplicate `arrayJoin` execution in JOIN ON with new logical join step
Backport #104785 to 26.5: Fix duplicate `arrayJoin` execution in JOIN ON with new logical join step
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]>
Cherry pick #104785 to 25.8: Fix duplicate `arrayJoin` execution in JOIN ON with new logical join step
… ON with new logical join step
Backport #104785 to 25.8: Fix duplicate `arrayJoin` execution in JOIN ON with new logical join step
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]>
…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]>
… `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]>
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix wrong row count from
arrayJoin()used insideJOIN ON: the result was multiplied by the array length an extra time.Documentation entry for user-facing changes
Problem
With
query_plan_use_new_logical_join_step = 1(the default), this query returns|tag_ids|² × N_itemsrows instead of the expected|tag_ids| × N_items. On an array of size 300 the result is300×larger than correct. Workaround:SET query_plan_use_new_logical_join_step = 0.Root cause
When a WHERE filter is pushed below a
JoinStepLogicalwhose ON clause containsarrayJoin(...),fix_predicate_for_join_logical_stepinfilterPushDown.cppmergespre_filter_dag(which carries the ON-sideARRAY_JOINnode) into the pushed-down filter.removeUnusedActionspreserves thatARRAY_JOINunconditionally because of the row-changing carve-out inActionsDAG.cpp(removeUnusedActionstreats everyARRAY_JOINnode as a root since removing it would silently change row count). The sameARRAY_JOINis then independently cloned into the per-side "Pre Join Actions"ExpressionStepbyJoinStepLogical::buildPhysicalJoinImpl, so each input row is expanded by|array|twice.EXPLAIN actions = 1on the buggy plan shows twoARRAY JOIN __table1.tag_idsactions on the items side (one inRight Pre Join Actions, one in the pushed-down filter). The fix collapses them to one.Fix
Snapshot the
ARRAY_JOINnode pointers inpre_filter_dagbefore the merge.ActionsDAG::mergeis implemented asmergeInplace, which usesstd::list::spliceto movesecond.nodesintofirst.nodes, so addresses stay valid infilter_dagafter the merge and the snapshot lets us identify the merged-in nodes by pointer rather than byresult_name(correctly handling nested forms likeJOIN ON toString(arrayJoin(a)) = b).After the merge +
removeUnusedActions, drop those nodes via a new narrow APIActionsDAG::removeNodes(std::unordered_set<const Node *>). The new helper computes its own transitive-required closure fromoutputs(without the row-changing carve-out) so any node still required by the filter predicate is kept regardless ofto_remove; ghostARRAY_JOINs that fell out of the filter's transitive closure are removed.Safety:
splitActionsForJOINFilterPushDownrejectsARRAY_JOINfromallowed_nodes, so thefilter_dagarriving atfix_predicate_for_join_logical_stepis guaranteed not to contain anyARRAY_JOINof its own. EveryARRAY_JOINwe see after the merge must have come frompre_filter_dag.JoinStepLogical::buildPhysicalJoinImplindependently materialises the same JOIN-side expression DAG into the per-side "Pre Join Actions"ExpressionStepabove 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 withmergeInplace/cloneofARRAY_JOIN-bearing DAGs. The prior two are #96989 (prevention strategy: blacklistARRAY_JOINin the pushdown eligibility check) and #97239 (bail-out strategy: detect ghostARRAY_JOINafter the merge and abandon the optimization). This PR uses a third strategy -- post-hoc cleanup -- becausefix_predicate_for_join_logical_stepis a mandatory plan transformation (the merge is required to propagatejoin_use_nullstype 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 test03918_arrayjoin_function_with_join_and_whereso the two related fixes share a number prefix. 12 queries covering:toString(arrayJoin(...)), runtime-filter off, disjunction-push-down off.EXPLAIN actions = 1substring count of'ARRAY JOIN '-- buggy plan has one extra ghost action.JOIN ON arrayJoin(L) = arrayJoin(R)with WHERE on left only, right only, and both sides simultaneously, so both left-side and right-sidefix_predicate_for_join_logical_stepinvocations are exercised symmetrically.AND arrayJoin(...)conjunct -- validates that the upstreamsplitActionsForJOINFilterPushDownrejection keeps the WHERE-sidearrayJoinabove the JOIN while the ON-side ghost is removed.query_plan_use_new_logical_join_step = 0baseline 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
26.5.4.15,26.4.5.69,26.3.16.9,25.8.29.3