Skip to content

Fix LOGICAL_ERROR in join order optimizer for a join step with duplicate-named inputs - #110717

Closed
groeneai wants to merge 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-4752-5ad8-join-reorder-duplicate-input
Closed

groeneai wants to merge 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-4752-5ad8-join-reorder-duplicate-input

Conversation

@groeneai

Copy link
Copy Markdown
Collaborator

Related: #110227

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 a LOGICAL_ERROR (Input nodes size mismatch in dag) in the join order optimizer that could be triggered by a correlated scalar subquery referencing the same outer column more than once.

Description

Chronic trunk LOGICAL_ERROR surfaced by the AST/BuzzHouse/stress fuzzers (STID 4752-5ad8), server abort in debug/sanitizer builds. 20 hits across 16 unrelated PRs in the last 30 days (0 on master). Reported on PR #108721 by @ alexey-milovidov.

Report (Stress test, amd_msan):
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108721&sha=bfeef0e4f26d24a5c1eef3c7389d7b689c1a5ece&name_0=PR&name_1=Stress%20test%20%28amd_msan%29

Root cause: the join order optimizer reconstructs join steps with JoinExpressionActions, whose 3-argument constructor maps every input to a join side by name and requires the input count to equal the two sides' column counts (JoinExpressionActions.cpp:124). A JoinStepLogical whose expression DAG already contains two INPUT nodes with the same qualified name (e.g. __table3.number twice) cannot be represented, so chooseJoinOrder -> optimizeJoinLogicalImpl -> QueryPlan::optimize aborted the server. Such a step arises when a correlated scalar subquery that references the same outer column twice (e.g. (SELECT number + number)) is decorrelated into a join.

This is distinct from the cross-side overlap handled by #110227: there the two sides expose the same name (Left and right columns have same names); here a single side's DAG carries a duplicate INPUT for one name (size mismatch, one guard earlier). #110227 does not cover it (verified: the reproducer still aborts with #110227 applied).

Fix: mirror the existing joinGraphHasOverlappingColumnNames guard. Before building the query graph (buildQueryGraph is destructive, so the check must be up front), walk the join steps the optimizer would flatten and skip reordering when any of them exposes duplicate-named inputs. The unoptimized plan handles the query. The guard is targeted: normal reorderable joins are unaffected.

The join order optimizer reconstructs join steps with JoinExpressionActions,
which maps each input to a join side by name and requires the input count to
equal the two sides' column counts. A JoinStepLogical whose expression DAG
already contains two INPUT nodes with the same qualified name cannot be
represented, and reconstruction aborted the server with a LOGICAL_ERROR
(Input nodes size mismatch in dag) in debug/sanitizer builds. Such a step
arises when a correlated scalar subquery referencing the same outer column
twice is decorrelated.

Detect duplicate-named inputs across the flattened join set up front and skip
reordering, mirroring the existing overlapping-column-names guard. The
unoptimized plan handles the query.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SET compatibility='24.3', enable_analyzer=1, allow_experimental_correlated_subqueries=1, group_by_use_nulls=1, query_plan_merge_expressions=1, query_plan_merge_expression_into_join=1, query_plan_optimize_join_order_limit=16, query_plan_optimize_join_order_algorithm='greedy'; SELECT number, (SELECT number + number) AS val FROM numbers(4) GROUP BY number WITH ROLLUP ORDER BY number ASC NULLS FIRST; aborts the server every time on clean master.
b Root cause explained? The correlated subquery (SELECT number + number) references number twice; decorrelation produces a JoinStepLogical whose expression DAG has two INPUT nodes named __table3.number. chooseJoinOrder reconstructs the reordered join with JoinExpressionActions, whose constructor maps inputs to a side by name and asserts inputs.size() == left_cols + right_cols (JoinExpressionActions.cpp:124). 3 inputs != 1+1 → LOGICAL_ERROR → server abort in debug/sanitizer. Confirmed by an instrumented probe: the top join step's DAG shows inputs=3 dup=[__table3.number(x2)] with children headers L=[__table3.number] R=[__table2.dummy].
c Fix matches root cause? Yes. Detects the duplicate-named inputs (the exact unrepresentable condition) across the flattened join set and skips reordering, deferring to the unoptimized plan — mirroring the existing joinGraphHasOverlappingColumnNames guard for the sibling cross-side case. Not a symptom band-aid.
d Test intent preserved / new tests added? New regression test 04517_join_reorder_duplicate_input_correlated_subquery asserts the server no longer aborts (handled exception instead of LOGICAL_ERROR). No existing test weakened.
e Both directions demonstrated? Yes. Clean master (Build ID 5f2044b5): server DEAD (LOGICAL_ERROR at JoinExpressionActions.cpp:124). With fix (Build ID 6c345491): server ALIVE, query handled normally.
f Fix is general across code paths? Yes. The guard walks the same flattened join set (buildQueryGraph mirror) the optimizer builds, so it covers duplicate-named inputs in any participating join step, not just the top one. #110227 (cross-side overlap) does NOT cover this size-mismatch case — verified the reproducer still aborts with #110227 applied — so this is a distinct, complementary guard.
g Fix generalizes across inputs? Verified the abort reproduces with multiple correlated shapes (number+number, number*2+number, tuple(number, number+1), with/without ORDER BY); all take the new skip path. Normal (non-duplicate) 3-way joins still reorder and return correct results, so the guard is input-targeted.
h Backward compatible? Yes. No setting default, format, or validation change. Only removes an incorrect abort; the reordering is skipped only for a query shape the reconstruction could never represent (the unoptimized plan handles it).
i Invariants and contracts preserved? Yes. The guard is a read-only pre-check run BEFORE the destructive buildQueryGraph; it only calls setOptimized() + returns (the same escape the existing overlap guard uses). It upholds the JoinExpressionActions reconstruction invariant (unique per-side input names) by not entering reconstruction when it cannot hold.

Session id: cron:clickhouse-worker-slot-1:20260716-143400

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @vdimir @novikd — could you review? This skips join reordering when a JoinStepLogical's expression DAG already has two INPUT nodes with the same qualified name (from a correlated scalar subquery referencing the same outer column twice, e.g. (SELECT number + number)), which the JoinExpressionActions reconstruction can't represent and which aborted the server with Input nodes size mismatch in dag (STID 4752-5ad8). It mirrors the existing overlapping-column-names guard and is distinct from #110227 (that covers the cross-side Left and right columns have same names case; this one is the size-mismatch guard a line earlier).

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Jul 16, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 16, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [195032a]

Summary: ✅


AI Review

Summary

This PR adds a pre-check in optimizeJoin.cpp to skip join-order reordering when a participating JoinStepLogical already carries duplicate-named INPUT nodes, and adds a stateless regression test for the correlated-subquery reproducer. I reviewed the current diff, the surrounding buildQueryGraph / chooseJoinOrder flow, the existing inline thread, and the current PR discussion; the earlier budget-accounting false positive was fixed in 1e5cfb5, and I did not find a remaining correctness, safety, or coverage issue in the current head.

Missing context / blind spots
  • ⚠️ I did not execute the new stateless test locally because this checkout has no prepared build directory or binary. A local run of 04517_join_reorder_duplicate_input_correlated_subquery would close that gap.
Final Verdict

✅ No new findings.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 16, 2026
The duplicate-input pre-check gave both children join_steps_limit - 1, but
buildQueryGraph flattens the left first and gives the right side only the
leftover budget (join_steps_limit - lhs_count). The asymmetry let the check
inspect, and disable reordering for, a right-side duplicate-input join the
real reorder would never flatten, turning the guard into a false-positive
optimization regression.

Thread the relation count through the traversal and spend the budget
left-first, matching buildQueryGraph and the sibling overlap guard
(collectJoinGraphRelationHeadersForJoin), so the guard only fires for steps
the real reorder would reconstruct.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

The amd_debug stress failure on 1e5cfb5 (STID 0993-386d, "Block structure mismatch in JoinStep: [__table3.number, __table3.number] and [__table3.number]") was not this PR's reorder path. The crash query is the first statement of 04493_correlated_subquery_join_runtime_filter_dup_column.sql, and the stack is JoinStep::updatePipeline -> checkBlockStructure with no buildQueryGraph/chooseJoinOrder frame: it is the runtime-filter duplicate-key crash already fixed on master by #109114 (joinRuntimeFilter.cpp guard + test 04493, merged 2026-07-14). This branch was 442 commits behind and predated that fix, so the stress build lacked it.

Merged master (195032a) to pick up #109114. Verified on a debug build (Build ID F9C9CA7B): 04493, 04517, and 04327 all match their references; the three crash-query variants (right/left/double-star) return correct rows with no LOGICAL_ERROR. No source change in this PR beyond the merge.

@clickhouse-gh

clickhouse-gh Bot commented Jul 17, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.00% 86.00% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 78.20% 78.20% +0.00%

Changed lines: Changed C/C++ lines covered: 46/47 (97.87%) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 195032a

CI fully finished (aggregator complete, >20 min buffer). No failed checks on this commit — every job is pass or skipped.

Check / test Reason Owner / fixing PR
(none) — —

Session id: cron:our-pr-ci-monitor:20260717-153000

@fm4v
fm4v added this pull request to the merge queue Aug 6, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Aug 7, 2026
@groeneai

groeneai commented Aug 7, 2026

Copy link
Copy Markdown
Collaborator Author

Closing this: the defect it guards against was fixed upstream at its source, so the change here is now dead code and its regression test can no longer be satisfied.

What changed

Commit 8e933885198fa3c ("Deduplicate expression from correlated subqueries", merged 2026-07-24 in PR 108289) rewrote projectOnlyUsedColumns in src/Planner/Utils.cpp to emit one output per used identifier, resolved to the first same-named column. A decorrelated subplan's projection can therefore no longer expose the same qualified identifier twice, and the compensating pop_front in JoinStepLogical.cpp buildPhysicalJoinImpl was dropped in the same commit. That removed the producer of duplicate-named inputs; this PR added a consumer-side veto in the join reorderer for a state that can no longer be produced. Upstream also shipped its own regression test, 04612_constant_join_decorrelated_duplicate_columns.

Measurements

Debug build at this branch merged with master 16bd8e4947a0:

  • The test's own query now returns 5 rows and raises nothing, so the serverError NOT_FOUND_COLUMN_IN_BLOCK expectation is stale.
  • Anti-vacuity mutant: reverting the guard call site (separate Build ID, verified) produces byte-identical output. Re-baselining the expectation to "succeeds" would ship a test that passes with or without the change.
  • I instrumented the guard's traversal and tried to rebuild a witness. Across 400 stateless tests matching correlated|join, the traversal was entered 1173 times in 168 tests and the duplicate-input predicate fired 0 times. Positive control: a plain three-way join at query_plan_optimize_join_order_limit=16 enters it twice, so the probe is live. Six hand-built shapes (the original repro, SELECT number, *, the upstream 04612 shape, star-plus-join, scalar over system.one, WITH CUBE) also never fire it.

Local sweeps cannot cover fuzzer mutations, which is where the original reports came from, so for that I used CIDB: Input nodes size mismatch in dag has zero occurrences on any build containing 8e933885. The last row overall is 2026-07-27, and its commit 16df783713d2 is dated 2026-07-19 and does not contain the fix. As a control, Logical error across AST fuzzer and Stress test returned 1201 rows in the same window, so the zero is a real absence and not a broken query.

Why not keep it

Besides being unreachable, 04517_join_reorder_duplicate_input_correlated_subquery is failing deterministically in the merge queue and ejecting whole batches, which took an unrelated PR out with it on 2026-08-06. Removing the test and keeping an unreachable branch in a hot optimizer path is not worth it, and weakening the test would defeat its purpose.

If the shape reappears on a build that does contain 8e933885, the right fix is at the producing layer rather than a veto in the reorderer, and I will open a fresh PR with that report.

@groeneai

groeneai commented Aug 7, 2026

Copy link
Copy Markdown
Collaborator Author

Superseded by the upstream fix in 8e93388 (PR 108289); details in the comment above.

@groeneai groeneai closed this Aug 7, 2026
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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants