Skip to content

Merge expressions into join during join reordering - #98533

Merged
vdimir merged 21 commits into
masterfrom
vdimir/join_reorder_through_expression
Jul 6, 2026
Merged

vdimir merged 21 commits into
masterfrom
vdimir/join_reorder_through_expression

Conversation

@vdimir

@vdimir vdimir commented Mar 2, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Improvement

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

  • Added the query_plan_merge_expression_into_join setting to allow merging Expression steps into JOIN steps during join reordering optimization. This enables join reordering across subqueries that wrap joins (e.g., when a JOIN is inside a subquery with computed columns), leading to better optimization of complex join trees.

Version info

  • Merged into: 26.7.1.545 (included in 26.7 and later)

@clickhouse-gh

clickhouse-gh Bot commented Mar 2, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [0883b25]

Summary: ✅


AI Review

Summary

This PR adds query_plan_merge_expression_into_join so join reordering can flatten non-trivial ExpressionStep wrappers around child joins, plus follow-up fixes for outer-join predicate handling. The remaining issues are all in that new flattening path: it can still move row-sensitive expressions across join boundaries, it reclassifies final constants as pre-join left expressions, and the duplicate-column preflight no longer matches the actual flattening rule. I would not merge this as-is.

Missing context / blind spots
  • ⚠️ I could not run a local clickhouse repro because the workspace only has the PR merge checkout and no built server/client binary. A quick local repro of the constant-only RIGHT JOIN and stateful-wrapper cases would close that gap, but the findings below follow directly from the current PR-head code.
Findings

❌ Blockers

  • [src/Processors/QueryPlan/Optimizations/optimizeJoin.cpp:707-745] addChildQueryGraph now flattens any non-ARRAY JOIN ExpressionStep when query_plan_merge_expression_into_join = 1. That lets stateful/cardinality-sensitive nodes such as rand or rowNumberInBlock be evaluated before a different join and at a different row multiplicity than in the original plan, which changes both join matching and returned values. Keep such wrappers unflattened unless the DAG is proven safe to move; at minimum reject wrappers with stateful or row-sensitive expressions.
  • [src/Processors/QueryPlan/Optimizations/optimizeJoin.cpp:1316-1320], [src/Processors/QueryPlan/JoinStepLogical.cpp:1404-1416] Final COLUMN outputs are appended to actions_after_join, so they become fromNone nodes in left_dag instead of staying in the post-join projection. For RIGHT and FULL joins that makes constants get default/null-extended with the left side instead of preserving their literal value, and for constant-only projections the empty-used_columns fallback can now pick __join_result_dummy or another constant and throw NOT_FOUND_COLUMN_IN_BLOCK in TableJoin::setUsedColumns. Keep final constants out of the pre-join DAG and use a guaranteed real input column only as the row-count keeper.
  • [src/Processors/QueryPlan/Optimizations/optimizeJoin.cpp:703-745], [src/Processors/QueryPlan/Optimizations/optimizeJoin.cpp:1427-1441] joinGraphHasOverlappingColumnNames is meant to reject duplicate-name join graphs before reconstruction, but its header collector no longer mirrors the new flattening rule. addChildQueryGraph flattens non-trivial expression-wrapped child joins when query_plan_merge_expression_into_join = 1, while collectJoinGraphRelationHeaders only peels trivial passthrough wrappers. A wrapper that aliases away duplicate child column names can therefore pass the preflight and still hit the duplicate-name LOGICAL_ERROR during join reconstruction. Make the collector use the same expression-wrapper handling as addChildQueryGraph.

⚠️ Majors

  • [src/Processors/QueryPlan/Optimizations/optimizeJoin.cpp:818-823] The get_exposed_columns helper still unwraps ExpressionStep with check = check->children[0] but without the children.size() == 1 guard that the main flattening path already uses. If the optimizer sees an intermediate or malformed unary node here, this is unchecked UB instead of a clean exception. Reuse the same arity guard as addChildQueryGraph.
  • [tests/queries/0_stateless/04001_join_reorder_through_expression.sql:24-63] The new setting is still only exercised with query_plan_merge_expression_into_join = 1; there is no matching plan-and-result case with the setting forced to 0 on the same query shape. Since this PR introduces a switchable behavior, the disabled branch should be locked down too.
Final Verdict

❌ Request changes. The new expression-flattening path still has correctness bugs and one reopened safety bug, and the disabled-setting branch is not covered by a companion regression test.

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Mar 2, 2026
@vdimir
vdimir force-pushed the vdimir/join_reorder_through_expression branch from 1ccd131 to 7cba228 Compare March 11, 2026 10:12
@vdimir
vdimir force-pushed the vdimir/join_reorder_through_expression branch from 7cba228 to 19e7334 Compare March 11, 2026 13:40
@vdimir
vdimir force-pushed the vdimir/join_reorder_through_expression branch from 19e7334 to 16d7279 Compare March 11, 2026 13:48

SET enable_parallel_replicas = 0;
SET query_plan_join_swap_table = 'auto';
SET query_plan_optimize_join_order_limit = 64;

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.

Nice coverage for the enabled path. To reduce regression risk for the new switch, please add one companion case with query_plan_merge_expression_into_join = 0 on the same query shape (plan + result), so both enabled and disabled semantics are locked by tests.

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.

I re-checked the current 04001 test and still don't see a companion case with query_plan_merge_expression_into_join = 0 for the same query shape.

Since this PR introduces a switchable behavior, we should lock both branches (1 and 0) with plan+result checks to prevent regressions where the disabled path drifts silently.

@vdimir
vdimir force-pushed the vdimir/join_reorder_through_expression branch from c3d87b4 to 6e16799 Compare March 11, 2026 14:48
@vdimir
vdimir force-pushed the vdimir/join_reorder_through_expression branch from f6bfae3 to 73d2ea8 Compare March 16, 2026 11:53
@vdimir vdimir changed the title wip merge expression into join Merge expressions into join during join reordering Mar 24, 2026
@vdimir
vdimir marked this pull request as ready for review March 24, 2026 16:08
@antaljanosbenjamin antaljanosbenjamin self-assigned this Mar 27, 2026
@vdimir
vdimir force-pushed the vdimir/join_reorder_through_expression branch from 286d053 to 430261c Compare April 1, 2026 11:43
{
bool merge_expression_into_join = query_graph.context->optimization_settings.merge_expression_into_join;
auto * expr = typeid_cast<ExpressionStep *>(check->step.get());
if (expr && check->children.size() == 1 && !expr->getExpression().hasArrayJoin()

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 checking that it has a single child is unnecessary and confusing, as ExpressionStep can only have one child, if I am not mistaken. Or do I miss something here?

Suggested change
if (expr && check->children.size() == 1 && !expr->getExpression().hasArrayJoin()
if (expr && !expr->getExpression().hasArrayJoin()

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.

ExpressionStep is logically unary, but in this optimizer path we dereference node->children[0] and may run before all structural assumptions are guaranteed. Keeping node->children.size() == 1 here is a defensive guard against malformed/intermediate plan nodes and avoids an avoidable exception in this hot path.

/// have the correct row count. When all post-join outputs are constants
/// (e.g. `__join_result_dummy`), residual_dag has no required inputs,
/// and the join would produce blocks with 0 columns
if (!left_dag.getOutputs().empty())

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.

If actions_after_join contains only COLUMN constants (e.g. SELECT 1 FROM t1 CROSS JOIN t2 after reorder), residual_dag.getRequiredColumnsNames() is empty and this fallback takes left_dag.getOutputs().front()->result_name. For that shape, the first output can be __join_result_dummy (a fromNone constant), which is not present in left/right input columns. Then TableJoin::setUsedColumns throws NOT_FOUND_COLUMN_IN_BLOCK instead of executing the query.

Please pick a guaranteed real input column (from left_dag.getInputs()/right_dag.getInputs() or child headers) rather than an arbitrary output node.

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 looks live in the current code.

chooseJoinOrder now explicitly appends COLUMN constants (for example __join_result_dummy) to actions_after_join at optimizeJoin.cpp:1263-1267. In buildPhysicalJoinImpl, when residual_dag.getRequiredColumnsNames() is empty, the fallback still picks left_dag.getOutputs().front()->result_name (JoinStepLogical.cpp:1295-1297). Because used_expressions is seeded from actions_after_join first (JoinStepLogical.cpp:1207-1221), that front output can be the fromNone constant instead of a real input column.

Then TableJoin::setUsedColumns receives a name that is not present in either side and throws NOT_FOUND_COLUMN_IN_BLOCK.

Could we change this fallback to take a guaranteed real input from left_dag.getInputs() / right_dag.getInputs() (or child headers), and skip COLUMN nodes here?

@alexey-milovidov

Copy link
Copy Markdown
Member

The Stress test (arm_msan) failure is fixed by #101239, which should be merged first. After it is merged, please update the branch to include the fix.

@alexey-milovidov

Copy link
Copy Markdown
Member

The MSan stress test failure (MemorySanitizer: use-of-uninitialized-value, STID 4179-5154 or 4148-3044) is a known pre-existing issue unrelated to this PR. Fix: #102158

@vdimir
vdimir force-pushed the vdimir/join_reorder_through_expression branch 2 times, most recently from 3658658 to 78fbe40 Compare May 26, 2026 14:49
if (expr && !expr->getExpression().hasArrayJoin()
&& (isPassthroughActions(expr->getExpression()) || merge_expression_into_join))
{
check = check->children[0];

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 branch unwraps ExpressionStep with check = check->children[0], but unlike addChildQueryGraph above it does not guard check->children.size() == 1 first.

In this optimizer path we can still see intermediate/malformed nodes, and operator[] here is unchecked. A zero-child ExpressionStep would trigger undefined behavior before we fail with a proper exception.

Please add the same defensive arity check used in addChildQueryGraph before dereferencing children[0].

@ClickHouse ClickHouse deleted a comment from clickhouse-gh Bot Jun 1, 2026
Comment thread src/Core/SettingsChangesHistory.cpp Resolved
@vdimir
vdimir enabled auto-merge July 1, 2026 08:08
@vdimir
vdimir disabled auto-merge July 1, 2026 12:46
@vdimir

vdimir commented Jul 2, 2026 •

Copy link
Copy Markdown
Member Author

@groeneai check out fuzzer and stress test issues and create repro if it's new ones

AST fuzzer (amd_debug, targeted, old_compatibility) FAIL
Logical error: 'Inconsistent AST formatting: the original AST: (STID: 1941-1bfa) FAIL cidb
Stress test (arm_debug) FAIL
Logical error: '!part.empty()' (STID: 2508-2ef2) FAIL cidb
AST fuzzer (amd_msan) FAIL
Logical error: Block structure mismatch in A stream: different columns: (STID: 0993-27f0) FAIL cidb, issue

@groeneai

groeneai commented Jul 2, 2026

Copy link
Copy Markdown
Collaborator

@vdimir Triaged all three. All are pre-existing trunk failures, none caused by the expression-merge / join-reordering change, so no new repro is needed. Evidence is 30d CIDB (cross-PR + master) + the exact crash sites.

1. STID 1941-1bfa Inconsistent AST formatting (AST fuzzer amd_debug, targeted, old_compatibility)
Known chronic formatter/parser round-trip family, unrelated to join reordering. 30d: 89 hits across 74 distinct PRs + 8 on master, still firing today (last seen 2026-07-02). Prior exact-STID reports: #106850, #106358 (closed).
Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=98533&sha=d44ac9b1a5a8142aeee52375ffbc6863960233ba&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%2C%20old_compatibility%29

2. STID 2508-2ef2 !part.empty() (Stress test arm_debug)
Known latent engine bug, not join-reordering related. ASTIdentifier ctor asserts on an empty name-part when a backquoted dot-terminated identifier (a lambda arg like `__table1.`) is converted QueryTree -> AST while building an error message. Crash site: ASTIdentifier.cpp:48 <- IdentifierNode::toASTImpl <- LambdaNode::toASTImpl. 30d: 2 unrelated branches, 0 on master; the identical stack reproduces on an unrelated branch too. Fix in flight: #108735 (LambdaNode.cpp, which you approved). It is still open, so this run predates it, which is why the assert still fires here.
Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=98533&sha=d44ac9b1a5a8142aeee52375ffbc6863960233ba&name_0=PR&name_1=Stress%20test%20%28arm_debug%29

3. STID 0993-27f0 Block structure mismatch in A stream (AST fuzzer amd_msan)
The issue you already linked, #108142: a chronic UnionStep/IntersectOrExceptStep bug where one branch constant-folds and the common header diverges. 30d: 174 hits across 135 distinct PRs + 13 on master, last seen 2026-07-02. Fix in flight: #107719.
Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=98533&sha=d44ac9b1a5a8142aeee52375ffbc6863960233ba&name_0=PR&name_1=AST%20fuzzer%20%28amd_msan%29

@vdimir
vdimir enabled auto-merge July 3, 2026 10:15
@clickhouse-gh

clickhouse-gh Bot commented Jul 3, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.60% 85.60% +0.00%
Functions 92.70% 92.70% +0.00%
Branches 77.70% 77.80% +0.10%

Changed lines: Changed C/C++ lines covered: 269/279 (96.42%) · Uncovered code

Full report · Diff report

@vdimir
vdimir added this pull request to the merge queue Jul 6, 2026
Merged via the queue into master with commit 3835588 Jul 6, 2026
343 of 344 checks passed
@vdimir
vdimir deleted the vdimir/join_reorder_through_expression branch July 6, 2026 11:34
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 6, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…er_through_expression

Merge expressions into join during join reordering
zoomxi pushed a commit to zoomxi/ClickHouse that referenced this pull request Oct 30, 2026
An array join multiplies each input row by its array size, which is not
estimated, so since ClickHouse#98533 an `ExpressionStep` with `arrayJoin` gives no row
estimate, and an `ArrayJoinStep` (the lowered `arrayJoin` function and the
`ARRAY JOIN` clause) never gave one. The hash join swap needs an estimate on
both inputs, so a join with an array join input over a read that selects no
rows kept building the other, possibly huge, input.

`RelationStats` now carries `proven_empty`, set only by the read branch whose
exact range analysis selected no rows and kept by steps that cannot add rows.
An array join over such an input is estimated at 0 rows; any other array join
keeps returning no estimate, because a child row count is neither an upper
nor a lower bound and an estimated zero (a keyless aggregation, a truncated
statistics selectivity) is not emptiness.

Related: ClickHouse#126481

Co-Authored-By: Claude Opus 5.5 <[email protected]>
valerypetrov pushed a commit to valerypetrov/ClickHouse that referenced this pull request Nov 17, 2026
…dering

`query_plan_merge_expression_into_join` (ClickHouse#98533) merges the projection
above a child join into the reordered join graph, so a constant of that
projection (`SELECT 123 AS h FROM a JOIN b`) becomes a sourceless COLUMN
node of the group's DAG. When `chooseJoinOrder` rebuilt the last join of
the group it appended every COLUMN output to `actions_after_join`, the
columns the join itself returns; the inclusion was meant for
`__join_result_dummy`. `JoinStepLogical::convertToPhysical` evaluates a
sourceless node in the left pre-join actions, so the constant travelled
through the join as a left column:

- rows that a RIGHT, RIGHT ANTI or swapped LEFT join pads got the type
  default (`0`, `''`, `[]`, `NULL`) instead of the constant;
- a hash join materialized the column while the logical header declares
  it constant: `Code: 44 ... non constant in source stream but must be
  constant in result (ILLEGAL_COLUMN)` for a 3-table INNER/LEFT join.

ClickHouse#120110 made DPsub + the CD-C conflict detector the default, which keeps
the RIGHT / RIGHT ANTI join on top for the shape in ClickHouse#131590, so it is
reachable with default settings on master; 26.10.3.7 shows it with
`query_plan_join_swap_table = 'true'`.

Return only the dummy from the rebuilt join. Every other constant is
computed by the post-join actions, the path a `materialize(123)` output
already takes. When nothing but constants is returned, the existing
fallback keeps one input column in the join for the row count.
`JoinStepLogical::isDummyResultColumn` exposes the dummy-name check that
`isDummyColumnOfThisStep` already used.

Closes ClickHouse#131590

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-improvement Pull request with some product improvements 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