Repository navigation
Fix LOGICAL_ERROR when both join children emit __join_result_dummy - #112205
Conversation
A join with no required output columns (e.g. under `count()`) mints the constant
marker column `__join_result_dummy` so its result blocks still carry a correct row
count. When two such dummy-only joins become the two children of one enclosing
join, both child output headers carry that identical column name.
`buildPhysicalJoinImpl` mapped child header columns back to `ActionsDAG` INPUT
nodes with a per-name queue that was rebuilt INSIDE the per-child loop. The right
child's lookup therefore restarted from the front of the queue and returned the
LEFT child's input node again; the dedup pass that follows dropped the repeat, so
`right_dag` ended up with zero outputs and `right_sample_block` was an empty block
while the right pipeline still physically carried its marker column. At run time
`ConstantJoin::addBlockToJoin` then compared a 1-column block against a 0-column
sample and aborted the server on a LOGICAL_ERROR. The empty right schema was also
handed to `TableJoin::setInputColumns` and `chooseJoinAlgorithm`.
Hoisting the queue above the child loop lets it be consumed across both children,
so a name shared by both child headers resolves to a different input node per
child and the left/right source attribution is preserved. The two-argument
`JoinExpressionActions` constructor appends inputs as
[left header columns..., right header columns...] and `children` is
[left, right], so popping in order gives each child its own node.
The queue was already the mechanism for duplicate columns; it only distinguished
duplicates WITHIN one child. This establishes the cross-child invariant: no
earlier revision had it either, so this is a pre-existing defect rather than a
regression of a particular commit.
The trigger is `query_plan_optimize_join_order_limit` in {0, 1}, at which the
join-order optimizer leaves both children dummy-only. Both values are drawn by
the CI settings randomizer, and the abort is deterministic given the draw.
Related: ClickHouse#108787
Co-Authored-By: Claude Opus 5 <[email protected]>
Review round r1. Comment-only change; the mapping logic itself is unchanged (the source is byte-identical to the previous commit once comments are stripped). The previous comment claimed that inputs are appended as [left header columns..., right header columns...] and that popping them in order is what preserves the left/right attribution. That is not the mechanism, and the positional claim is not one this code needs. Only distinctness is load-bearing. The left/right split reads each node's own recorded source relation via fromLeft() / fromRight(), which JoinExpressionActions records per node when it creates the input, so the order in which the per-name queue is drained cannot affect which side a node lands on. What the per-child rebuild broke was that the second child re-resolved a shared column name to the first child's node, after which the deduplication dropped the repeat and left that side of the join with an empty schema. Also correct the reason given for the derived-table case in the test: those subqueries are distinct not because a derived table materializes its result, but because each output column is renamed to an alias-qualified identifier (x.c / y.c), so the enclosing join sees distinct names.
The comment on the outer-join control claimed that no `__join_result_dummy` marker is minted for those shapes. That is not what the code does: both mint sites are join-kind-unconditional (`JoinStepLogical.cpp:142-148` gates only on `outputs.empty()`, `:437-445` only on `required_nodes.empty()`); the sole join-kind-dependent code nearby is the nullability conversion, which does not gate minting. Measured with `EXPLAIN input_headers = 1, keep_logical_steps = 1` on the fix binary, the enclosing join's per-side input headers are: primary (aborts without the fix) #0 __join_result_dummy ClickHouse#1 __join_result_dummy outer joins #0 __join_result_dummy, __table3.a ClickHouse#1 __table4.a explicit CROSS JOIN #0 __join_result_dummy, __table3.a ClickHouse#1 __table4.a derived tables #0 __table1.c ClickHouse#1 __table4.c So the outer-join and explicit-cross shapes DO mint the marker, into the left child header only. What makes them negative controls is the property the defect actually needs: the two child headers of the enclosing join share no column name, so each name's queue holds exactly one input node and the mapping resolves to the same node whether it is rebuilt per child or hoisted. Only the primary shape has both children reduced to the identical marker name. The derived-table comment named `x.c` / `y.c` as the resulting column names; the measurement shows the table-expression-qualified `__table1.c` / `__table4.c`. Reworded to the measured names. Comment-only: the non-comment content of the test is unchanged (sha256 8d02af43049db436 before and after), `clickhouse format --multiquery --oneline` is identical across both revisions, and the `.reference` file has zero diff lines.
Internal second-model review (3 rounds, 14 findings)Before this PR was opened it went through three independent review rounds. Each round is a cold Round tally: r0 7 findings (5 accepted / 2 rejected), r1 3 (1 accepted / 2 withdrawn by the reviewer The mapping fix itself was never disputed. All three rounds independently re-derived the same root ❌ Accepted, fixed
Plus three smaller accepted items: a changelog sentence that described the
|
| # | Finding | Why rejected |
|---|---|---|
| r0 | The derived-table negative control is not really negative: its two child headers might share a name, and any abort could be masked by HashJoin projecting the right block. |
Refuted twice. FROM x, y is a comma join, which forces ConstantJoin unconditionally (PlannerJoins.cpp:1421-1422), so the HashJoin masking path is unavailable; and each derived table projects exactly one column, so a shared name would have emptied the right side and aborted like the positive case. Measured on the pristine master binary the control returns 1 with zero logical errors, while the positive case on the same binary aborts, so the right side was non-empty before the fix and the names were distinct. Only the comment's stated reason was wrong, and that was corrected. |
| r0 | Say "threw a LOGICAL_ERROR exception" rather than "aborted". |
tests/config/install.sh:228-230 links abort_on_logical_error.yaml unconditionally for every non-fast-test job, so aborting is what the test actually observes. Measured convention in comparable stateless test comments on master is 22 uses of "abort" against 24 of "exception", so neither form is the house style. |
Verification carried into this PR
- Deterministic reproduction, no fuzzer:
SELECT count() FROM t1, t2, t3, t4 WHERE (t1.b = t2.b) AND (t3.a = t4.a) SETTINGS query_plan_optimize_join_order_limit = 0aborts a master-HEAD debug build with a message and stack byte-identical to the CI report. - Both directions on both binaries across 6 aborting shapes and 3 controls, with the values asserted taken from what the reordered plan already returns, so the test asserts correctness rather than the absence of an abort.
- Reverting only the hoist and rebuilding reproduces the abort on the new test, so its assertions are load-bearing.
- 50 runs of the new test under randomized settings pass.
Pre-PR validation gate (a-i)
|
|
cc @CurtizJ @KochetovNicolai - could you review this? |
|
Workflow [PR], commit [cfd2a9d] Summary: ✅
AI ReviewSummaryThis PR fixes the local Findings❌ Blockers
Tests
Final Verdict❌ Changes requested: the local planner path is fixed, but the same duplicated-header join still fails after |
CI finish ledger - 66f93bfEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task CI is fully finished on this head:
Not caused by this PR. Its diff is Session id: cron:our-pr-ci-monitor:20260728-150000 |
| @@ -1322,16 +1322,22 @@ static QueryPlanNode buildPhysicalJoinImpl( | |||
| for (const auto * action : required_residual_nodes) | |||
| used_expressions.emplace_back(action, expression_actions); | |||
|
|
|||
| /// We expect dag inputs to be a subset of child step header columns. | |||
| /// If a child step returns duplicate columns, or the SAME column name appears in BOTH | |||
| /// children's headers (e.g. two dummy-only joins each emitting `__join_result_dummy`), | |||
There was a problem hiding this comment.
Done in cfd2a9d.
JoinStepLogical.cpp: 9 comment lines down to 4, keeping only the invariant needed at that line (dag inputs are a subset of the child header columns; duplicates, within one child or shared between both, resolve to different input nodes; the queue is consumed across children so it must not be rebuilt per child). The failure narrative and the fromLeft/fromRight attribution argument are in the commit messages.
I also trimmed the test since you wrote "comments": 18 lines down to 8, dropping the restated root cause and the measured per-side input headers.
Comment-only: with comments stripped both files are sha256-identical to the previous head, clickhouse format --oneline on the test is unchanged, and the test still passes against a rebuilt binary with no diff to the reference.
| /// and the deduplication below then dropped the repeat, leaving that child's side of the join | ||
| /// with an empty schema. Only distinctness matters here - the left/right split below reads each | ||
| /// node's own recorded source relation (`fromLeft` / `fromRight`), not the order of this queue. | ||
| const auto & dag_inputs = expression_actions.getActionsDAG()->getInputs(); |
There was a problem hiding this comment.
buildPhysicalJoinImpl is only one consumer of these duplicate child headers. When the same logical join is serialized and deserialized for distributed execution, JoinExpressionActions(left_header, right_header, actions_dag) still throws immediately when the two headers share a name (src/Interpreters/JoinExpressionActions.cpp:130-131), so the same __join_result_dummy query shape remains broken on distributed plans.
Since the follow-up in #108787 is still open, merging this PR alone overstates the fix. Please either include that deserialization change here or wait for it to merge before landing this local-path fix.
There was a problem hiding this comment.
The body already scopes this, under #### Scope:
The duplicate-name precondition is also carried by the three-argument
JoinExpressionActionsconstructor on the distributed deserialize path, where it fails differently (Left and right columns have same names: [__join_result_dummy], [__join_result_dummy]). That is a separate defect in a separate file, addressed by #108787, and is deliberately not bundled here.
That names the three-argument constructor, the deserialize path, the exact message the throw at JoinExpressionActions.cpp:130-131 produces, and #108787 as its owner, so the description does not overstate the fix. #108787 is linked in the relationship block as well.
The observation about master is correct: that throw is unconditional. It is also the assertion #108787 replaces. Its diff removes those two lines and resolves a shared name by input position, after verifying the inputs are laid out as [left columns..., right columns...]. That is why the split is by owning file: this PR touches only src/Processors/QueryPlan/JoinStepLogical.cpp, #108787 only src/Interpreters/JoinExpressionActions.cpp. The file sets are disjoint, so neither is blocked on the other's merge order.
I am therefore not bundling the deserialize change here, and not holding this local-path fix behind a separate open PR; that call belongs to a reviewer.
Review feedback: the comments were too verbose. Comment-only change; the code and the test statements are unchanged. src/Processors/QueryPlan/JoinStepLogical.cpp: 9 comment lines down to 4. Kept the invariant a reader needs at that line (dag inputs are a subset of the child header columns; duplicates, whether within one child or shared between both children, resolve to different input nodes; the queue is consumed across children so it must not be rebuilt per child). Dropped the failure narrative and the fromLeft/fromRight attribution argument, both of which are already in the commit messages of a934a5b, e36f6e3 and 66f93bf. tests/queries/0_stateless/04648_join_dummy_only_both_children.sql: 18 comment lines down to 8. Kept why the setting is pinned, why the expected values assert correctness, what makes the last three shapes negative controls, and why the derived-table shape differs. Dropped the restated root cause and the measured per-side input headers; the latter are in 66f93bf. Comment-only: with comments stripped, the source is sha256-identical before and after (e31273b83e4b4e8f), and so are the test's non-comment lines (cec8a6e78fec6017). The .reference file is untouched and still matches byte for byte on a rebuilt binary (build id a673660c03da32ac). Co-Authored-By: Claude Opus 5 <[email protected]>
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 9/9 (100.00%) · Uncovered code |
CI finish ledger - cfd2a9dCI is fully finished on this head: all 174 check-runs completed, Config Workflow and Finish
CIDB records no Session id: cron:our-pr-ci-monitor:20260730-233000 |
|
@vdimir LGTM! Can you give a final look? The PR is very small |
|
I trust this |
Two test-liveness gaps disclosed at the previous round cap, both now closed and each verified by a mutation that reddens only the new row. The fake transport recorded a single boolean per attempt, so nothing proved that caller options survive the shim's extra hop into `GH.api_get`. It now snapshots every request. `test_caller_request_options_survive_delegation` asserts the two live shapes -- `params` plus `timeout` from `get_previous_release_tag.py`, the `Accept` header from `pr_info.py` -- and `test_failover_sends_the_fetched_token` asserts the installed value is `Bearer fetched-token`, not merely that an `Authorization` key appeared. Dropping `**kwargs` from the delegation reddens the first; installing an empty bearer reddens the second, while the pre-existing failover rows stay green, which is what made them blind to it. `test_budget_resets_are_bounded` derived both its expected count and its ceiling from `API_GET_MAX_BUDGET_RESETS`, so raising the constant moved the goalposts with it. The bound is now a literal, and changing the constant to 2 reddens the row. Dropped the `realpath` comment in the download helper: it attributed the path requirement to a `/usr/bin` symlink, but `upgrade_runner.sh` symlinks only the two entry scripts and this module is imported from its repository path, where `abspath` and `realpath` agree. Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112205&sha=66f93bffd6aa9d3b6f038bf7a6b59ac02a5b3f10&name_0=PR&name_1=Upgrade%20check%20%28amd_release%29 PR: ClickHouse#112205
The job this fixes was filtered out by its own change. `upgrade_test_jobs` digested the two entry scripts but not `tests/ci/build_download_helper.py`, which both import at module level, nor `ci/praktika/gh.py`, which the helper now imports for the retry policy. Measured against `Job.is_affected_by` with the four changed paths: `Upgrade check (amd_release)` read False before, True after, and still False for an unrelated `src/` change. Strengthened the delegation oracle, which observed only the first successful request: it now drives the shim through two retries with `sleep=0` and asserts the params, timeout and `Accept` header on every attempt, plus the forwarded sleep sequence. The failover row asserts the same across the budget restart. Dropping `sleep=sleep` from the delegation reddens it, and so does clearing an option after a failure. Corrected the `api_get` docstring formula to `sleep * 2 ** (attempt - 1)`: attempt 1 uses exponent zero, which is what the pinned `[3, 6, 12, 24]` sequence shows. Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112205&sha=66f93bffd6aa9d3b6f038bf7a6b59ac02a5b3f10&name_0=PR&name_1=Upgrade%20check%20%28amd_release%29 PR: ClickHouse#112205
The failover row passed only `params` and inspected headers on the first authenticated request, so losing an option, the bearer or the caller's sleep on a later post-reset attempt stayed invisible. It now drives the persistent `404` with the shapes the callers actually use (`sleep=0`, `params`, the diff `Accept` header, `timeout=10`) and asserts all of them, plus the sleep sequence, on every attempt after the reset. Clearing an option at the reset reddens it, and so does dropping the bearer from the third attempt onward, while the pre-existing failover rows stay green. Corrected two comments that said `report.py` falls back to the run URL after catching `APIException`: `GITHUB_JOB_ID` swallows it by default, so `GITHUB_JOB_URL` returns an empty string without entering that branch. The invariant the test pins is only that the class stays catchable at the existing caller boundary. Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112205&sha=66f93bffd6aa9d3b6f038bf7a6b59ac02a5b3f10&name_0=PR&name_1=Upgrade%20check%20%28amd_release%29 PR: ClickHouse#112205
Related: #108787
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixes a
LOGICAL_ERRORexception (Block structure mismatch in joined block stream) on a multi-table join whose two sub-joins both produce no output columns, for exampleSELECT count() FROM t1, t2, t3, t4 WHERE (t1.b = t2.b) AND (t3.a = t4.a)withquery_plan_optimize_join_order_limitset to0or1.Description
No related open issue found: the failure was detected by CI monitoring (
Stress test (amd_msan), STID0993-3a3c).Root cause
A
JoinStepLogicalwith no required output columns (for example the sub-joins of acount()query) mints a constant marker column__join_result_dummyso its result blocks still carry a correct row count. When two such dummy-only joins become the two children of one enclosing join, both child output headers carry a column with the identical name__join_result_dummy.The enclosing join's
JoinExpressionActionscorrectly creates two distinctActionsDAGINPUT nodes for them, one tagged source-relation 0 (left) and one tagged 1 (right). ButbuildPhysicalJoinImplmapped child header columns back to those input nodes using a per-name queue that was rebuilt inside the per-child loop. The right child's lookup therefore restarted from the front of the queue and returned the left child's node again; the dedup pass that immediately follows dropped the repeat, leavingused_expressionswith the left node only.Because
left_dag/right_dagare split by source relation,right_dagended up with zero outputs, soright_sample_blockwas an empty block. The right pipeline still physically carried its marker column: the "Right Pre Join Actions"ExpressionStepbuilt from an empty DAG performs no projection, sinceActionsDAG::updateHeaderpasses through header columns not matched to a DAG input. At run timeConstantJoin::addBlockToJointherefore compared a 1-column block against a 0-column sample:JoinCommon::materializeColumnsFromRightBlockiterates the sample's columns, so with an empty sample it is a no-op, which is why the marker column is still reported asConstrather than materialized.The same empty right schema was also handed to
TableJoin::setInputColumnsand tochooseJoinAlgorithm, so required-column bookkeeping and algorithm choice were computed from it as well; andConstantJoin::trySpillRightBlockschemas its temporary stream on the same block, a second latent failure mode from the same cause. All of these become correct with the fix.The fix
Hoist the input-node queue above the child loop so it is consumed across both children. The two-argument
JoinExpressionActionsconstructor creates exactly one input node per child-header column, so consuming one queue entry per child-header column hands each child a distinct node and the dedup pass no longer collapses the two.The left/right routing itself does not depend on the order in which the queue is drained:
left_dagandright_dagare split by each node's recorded source relation (fromLeft/fromRight), whichJoinExpressionActionsassigns when the input node is created. Distinctness is the whole property that was missing.The queue was already the mechanism for duplicate columns (its own comment says so); it merely distinguished duplicates within one child because it was refilled between children. This is a pre-existing defect, not a regression: the revision before the current name-keyed lookup restarted per child as well (it used a
dag_inputs.begin()iterator declared inside the same loop), so no earlier version had the cross-child invariant either. The change therefore establishes that invariant rather than restoring one.Whenever no column name is shared across the two child headers the mapping is identical to before, so plans for unaffected queries do not change.
Reproduction
No fuzzing is required. The abort is deterministic at
query_plan_optimize_join_order_limit0and1, the values at which the join-order optimizer leaves both children dummy-only; at5and at the default10the tree is reshaped and the same query already answers4. Both triggering values are drawn by the CI settings randomizer, which is how the failure reached a stress run.The correctness oracle is therefore free: the new test asserts that the affected regimes return exactly the value the reordered plan already returns, not merely that the server no longer aborts.
Verification
04648_join_dummy_only_both_children, covering the primary case at both triggering values, a five-table variant,SELECT 1andSELECT toTypeName(...)projections,any_join_distinct_right_table_keys = 1, the reordered-plan reference values, and three negative controls whose two child headers share no column name (outer joins, an explicitCROSS JOINchain, derived tables), measured withEXPLAIN input_headers = 1.Scope
The duplicate-name precondition is also carried by the three-argument
JoinExpressionActionsconstructor on the distributed deserialize path, where it fails differently (Left and right columns have same names: [__join_result_dummy], [__join_result_dummy]). That is a separate defect in a separate file, addressed by #108787, and is deliberately not bundled here.The identical assertion in
HashJoinnever trips only because that algorithm projects incoming right blocks onto its own sample block, i.e. it masks an empty sample rather than being immune, which is why onlyConstantJoinsurfaced this planner bug. The three assertions inConstantJoinare left untouched: they are correct, and their input is what was wrong.This is a column-set attribution defect rather than a type defect, so type wrappers (
Nullable,LowCardinality,Array,Map,Const) are not separate carriers.