Skip to content

Fix LOGICAL_ERROR when both join children emit __join_result_dummy - #112205

Merged
PedroTadim merged 5 commits into
ClickHouse:masterfrom
groeneai:fix-join-child-input-attribution
Jul 31, 2026
Merged

PedroTadim merged 5 commits into
ClickHouse:masterfrom
groeneai:fix-join-child-input-attribution

Conversation

@groeneai

Copy link
Copy Markdown
Collaborator

Related: #108787

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):

Fixes a LOGICAL_ERROR exception (Block structure mismatch in joined block stream) on a multi-table join whose two sub-joins both produce no output columns, for example SELECT count() FROM t1, t2, t3, t4 WHERE (t1.b = t2.b) AND (t3.a = t4.a) with query_plan_optimize_join_order_limit set to 0 or 1.

Description

No related open issue found: the failure was detected by CI monitoring (Stress test (amd_msan), STID 0993-3a3c).

Root cause

A JoinStepLogical with no required output columns (for example the sub-joins of a count() query) mints a 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 a column with the identical name __join_result_dummy.

The enclosing join's JoinExpressionActions correctly creates two distinct ActionsDAG INPUT nodes for them, one tagged source-relation 0 (left) and one tagged 1 (right). But buildPhysicalJoinImpl mapped 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, leaving used_expressions with the left node only.

Because left_dag/right_dag are split by source relation, right_dag ended up with zero outputs, so right_sample_block was an empty block. The right pipeline still physically carried its marker column: the "Right Pre Join Actions" ExpressionStep built from an empty DAG performs no projection, since ActionsDAG::updateHeader passes through header columns not matched to a DAG input. At run time ConstantJoin::addBlockToJoin therefore compared a 1-column block against a 0-column sample:

Logical error: 'Block structure mismatch in joined block stream: different number of columns:

__join_result_dummy UInt8 Const(size = 2, UInt8(size = 1))'.

JoinCommon::materializeColumnsFromRightBlock iterates the sample's columns, so with an empty sample it is a no-op, which is why the marker column is still reported as Const rather than materialized.

The same empty right schema was also handed to TableJoin::setInputColumns and to chooseJoinAlgorithm, so required-column bookkeeping and algorithm choice were computed from it as well; and ConstantJoin::trySpillRightBlock schemas 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 JoinExpressionActions constructor 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_dag and right_dag are split by each node's recorded source relation (fromLeft / fromRight), which JoinExpressionActions assigns 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

CREATE TABLE t1 (a UInt64, b UInt64) ENGINE = Log; INSERT INTO t1 VALUES (1,2),(3,4),(5,6);
CREATE TABLE t2 (a UInt64, b UInt64) ENGINE = Log; INSERT INTO t2 VALUES (3,4),(5,6),(7,8);
CREATE TABLE t3 (a UInt64, b UInt64) ENGINE = Log; INSERT INTO t3 VALUES (5,6),(7,8),(9,10);
CREATE TABLE t4 (a UInt64, b UInt64) ENGINE = Log; INSERT INTO t4 VALUES (7,8),(9,10),(11,12);

SELECT count() FROM t1, t2, t3, t4 WHERE (t1.b = t2.b) AND (t3.a = t4.a)
SETTINGS query_plan_optimize_join_order_limit = 0;

No fuzzing is required. The abort is deterministic at query_plan_optimize_join_order_limit 0 and 1, the values at which the join-order optimizer leaves both children dummy-only; at 5 and at the default 10 the tree is reshaped and the same query already answers 4. 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

  • Added 04648_join_dummy_only_both_children, covering the primary case at both triggering values, a five-table variant, SELECT 1 and SELECT 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 explicit CROSS JOIN chain, derived tables), measured with EXPLAIN input_headers = 1.
  • On a master-HEAD build the new test aborts the server with the signature above; with the fix it passes, and 50 runs under randomized settings pass.
  • Reverting only the hoist reproduces the abort on the new test, so the added assertions are not vacuous.

Scope

The duplicate-name precondition is also carried by the three-argument JoinExpressionActions constructor 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 HashJoin never 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 only ConstantJoin surfaced this planner bug. The three assertions in ConstantJoin are 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.

groeneai and others added 3 commits July 27, 2026 17:46
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.
@groeneai

Copy link
Copy Markdown
Collaborator Author
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
re-read of the resulting code by a reviewer that did not write it, plus a second model reviewing the
same diff, with every finding adjudicated against the code or a measurement. 8 findings were
accepted and fixed, 2 were rejected with evidence recorded below, and 4 were withdrawn by the
reviewer who raised them after re-measuring. Two accepted findings turned out to
correct claims that earlier rounds of this PR had made incorrectly, and both corrections are visible
in the commit history rather than hidden by an amend.

Round tally: r0 7 findings (5 accepted / 2 rejected), r1 3 (1 accepted / 2 withdrawn by the reviewer
after re-measuring), r2 4 (2 accepted / 2 withdrawn). The final round's second-model pass returned no
findings.

The mapping fix itself was never disputed. All three rounds independently re-derived the same root
cause and the same single-carrier conclusion, and rounds r1 and r2 changed no line of
src/Processors/QueryPlan/JoinStepLogical.cpp at all: their deltas are comment-only, verified by a
comment-stripped sha256 that is identical across the three commits while differing from master.

❌ Accepted, fixed

# Finding Fix
r0 The comment justifying the hoist credited the order in which the input-node queue is drained for the left/right attribution. That is not the mechanism: the split at JoinStepLogical.cpp:1364-1365 filters on each node's recorded source relation (fromLeft() / fromRight()), which JoinExpressionActions stamps when the node is created. Distinctness, not order, is what was missing. Comment rewritten to state the recorded-source-relation mechanism. The corrected statement is also in the follow-up commit message.
r0 The same comment asserted an [left header columns..., right header columns...] input layout as a fact, while preCalculateKeys can append inputs and break that order. Positional claim removed entirely; the fix does not need it.
r0 The PR body promised that plans for queries with no shared column name do not change, but the control backing that promise was incomplete. Backed two ways: a structural proof that each header column has exactly one input node, so a single-element queue returns the same node rebuilt or hoisted; and a full join-suite run on a master-HEAD binary and on the fixed binary, 896 tests selected each, failing sets identical, no .reference file touched.
r2 The negative controls' comment claimed no marker column is minted for outer joins. Both mint sites are join-kind-unconditional (:142 gates on outputs.empty(), :437 on required_nodes.empty()); only the nullability conversion nearby depends on join kind. Measured with EXPLAIN input_headers = 1, keep_logical_steps = 1: the outer-join and explicit-cross shapes do mint the marker, into the left child header only; the derived-table shape mints none. Comment now names the property the defect actually needs, that the two child headers share no column name.
r2 A second claim in the same block named the derived-table columns x.c / y.c. Measured __table1.c / __table4.c; reworded, and the PR body's matching sentence re-frozen to the measured reason.

Plus three smaller accepted items: a changelog sentence that described the LOGICAL_ERROR as
crashing the server (it is an exception, handled in release builds), a provenance line that sat inside
the template HTML comment and rendered as nothing, and non-ASCII punctuation in the PR description.

⚠️ Rejected, with evidence

# 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 = 0 aborts 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.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (a-i)
# Question Answer
a Deterministic repro? Yes. SELECT count() FROM t1, t2, t3, t4 WHERE (t1.b = t2.b) AND (t3.a = t4.a) SETTINGS query_plan_optimize_join_order_limit = 0 over four three-row Log tables aborts the server on a master-HEAD debug build with RC=134, no fuzzing and no randomization involved. Message and stack frames (Block.cpp:863 <- ConstantJoin.cpp:230 <- JoiningTransform.cpp:373) are byte-identical to the CI report, including the Const(size = 2, UInt8(size = 1)) dump. Reproduced 6 further shapes (limit = 1, five-table, SELECT 1, SELECT toTypeName(...), any_join_distinct_right_table_keys = 1) and 3 non-reproducing negative controls.
b Root cause explained? Yes. A dummy-only join mints the constant marker __join_result_dummy; when two such joins are the two children of one enclosing join, both child headers carry that name. buildPhysicalJoinImpl rebuilt its per-name input-node queue inside the per-child loop, so the right child's lookup returned the left child's node again, the following dedup pass dropped the repeat, right_dag ended with zero outputs, and right_sample_block was empty while the right pipeline still carried the marker column (ActionsDAG::updateHeader passes through unmatched header columns). ConstantJoin::addBlockToJoin then compared a 1-column block against a 0-column sample.
c Fix matches root cause? Yes. The queue is hoisted above the child loop so it is consumed across both children, which repairs the input attribution at its source. An earlier design that projected the incoming right block inside ConstantJoin was rejected: it would have silenced the assertion by discarding the right side's marker column while leaving a malformed physical plan whose TableJoin::setInputColumns and chooseJoinAlgorithm still receive an empty right schema. No assertion is relaxed, no tag added, no dataset reduced.
d Test intent preserved / new tests added? New test 04648_join_dummy_only_both_children added; no existing test weakened or deleted. The test asserts concrete result values, taken from what the reordered plan already returns today, so it is a correctness assertion rather than a crash-absence assertion.
e Demonstrated in both directions? Yes. On a master-HEAD build the new test aborts the server (observed twice: once standalone, once mid-suite); with the fix it passes, and 50 runs under randomized settings pass. Reverting only the hoist and rebuilding reproduces the abort, so the new assertions are load-bearing.
f General across code paths? Yes. git grep over JoinStepLogical.cpp confirms this is the only site mapping child header columns to ActionsDAG input nodes; the other getOutputHeader() uses are header plumbing. The producing side (the two-argument JoinExpressionActions constructor) is already correct: producer correct, consumer collapsing, which is the defect. The same duplicate-name precondition on the distributed deserialize path fails differently and is addressed by #108787, deliberately not bundled. HashJoin's identical assertion never trips only because it projects onto its own sample block, i.e. it masks an empty sample; it is not a carrier and is untouched. The three assertions in ConstantJoin and trySpillRightBlock's temporary-stream schema all become correct transitively.
g Generalizes across inputs? Yes, within the relevant axis. This is a column-set attribution defect, not a type defect, so type wrappers are not carriers. The tested matrix instead varies the axes that matter: the triggering setting (0, 1, 5, default), table count (four and five), projection shape (count(), a constant, a constant-folded expression), join strictness (any_join_distinct_right_table_keys), analyzer (new and old produce identical output), plus three structurally different non-colliding shapes.
h Backward compatible? Yes. No setting added or defaulted, no serialization or protocol change, so no SettingsChangesHistory.cpp entry is required; Settings.cpp is untouched. 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.
i Invariants and contracts preserved? Yes, and one is newly established: each child header column now resolves to a distinct ActionsDAG input node, so left/right source attribution survives a name shared by both child headers. The existing throw in the same loop remains the tripwire for a header column with no matching input. Nothing is added to or removed from the DAG; only which existing node each child header column maps to changes, and only when a name is duplicated across children, a case in which the previous mapping was unusable by construction (the dedup pass discarded the duplicate).

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @CurtizJ @KochetovNicolai - could you review this? buildPhysicalJoinImpl rebuilt its child-header-to-ActionsDAG-input map inside the per-child loop, so when both children of a join are dummy-only (two count() sub-joins each emitting __join_result_dummy) the right child re-resolved that shared name to the left child's node and right_dag ended up empty, aborting in ConstantJoin::addBlockToJoin; the fix hoists the map above the loop so each child gets its own node.

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

clickhouse-gh Bot commented Jul 28, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [cfd2a9d]

Summary: ✅


AI Review

Summary

This PR fixes the local buildPhysicalJoinImpl attribution bug for sibling dummy-only joins and adds a focused stateless regression. That local fix looks correct, but the PR is still not merge-ready because the serialized/distributed-plan round-trip still rejects the same duplicated __join_result_dummy header shape, so the title and changelog currently overstate the fix.

Findings

❌ Blockers

  • [src/Processors/QueryPlan/JoinStepLogical.cpp:1724-1727, src/Interpreters/JoinExpressionActions.cpp:127-131] [dismissed by author -- https://github.com/Fix LOGICAL_ERROR when both join children emit __join_result_dummy #112205#discussion_r3683331725] JoinStepLogical::deserialize still reconstructs JoinExpressionActions with the unchanged 3-argument constructor, and that constructor still throws as soon as the left and right headers share a name. For this query shape both sides can still deserialize with the same __join_result_dummy, so distributed / serialize_query_plan=1 execution remains broken even after the local buildPhysicalJoinImpl fix. Suggested fix: fold the JoinExpressionActions(left_header, right_header, actions_dag) change from Fix LOGICAL_ERROR on duplicate __join_result_dummy when deserializing a distributed join plan #108787 into this PR or merge them together, then add a regression that exercises the serialized-plan path for the same four-table count() repro.
Tests
  • ⚠️ The new stateless test covers only the local planner path. Add a smallest-possible regression that forces a serialized-plan round-trip for the same dummy-only sibling-join shape, for example with serialize_query_plan = 1 on a remote/distributed query or with make_distributed_plan = 1 plus distributed_plan_execute_locally = 1.
Final Verdict

❌ Changes requested: the local planner path is fixed, but the same duplicated-header join still fails after JoinStepLogical serialization/deserialization.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 28, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 66f93bf

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

CI is fully finished on this head: Finish Workflow = success (2026-07-28T14:25:00Z), Config Workflow = success, 174 check-runs, 0 queued or in progress, ingestion buffer elapsed.

Check / test Reason Owner / fixing PR
AST fuzzer (amd_debug) / Logical error: '!predicates.empty()' (STID 2508-3c85) fuzzer self-abort, not a ClickHouse engine defect: the stack is entirely inside the fuzzer (QueryFuzzer.cpp:3919 permutePredicateClause <- :3991 addOrReplacePredicate <- fuzzExpressionList <- fuzzExplainQuery), tripped by a degenerate zero-argument logical call such as and(), for which extractPredicates returns nothing. Nothing in the join-plan code this PR touches participates. fixing PR #112139 (mine, merged 2026-07-28T08:16:07Z). The failure is expected on this head: Build (amd_debug) completed at 08:12:36Z, ~4 minutes before that merge, and the fix is not an ancestor of 66f93bf (verified with git merge-base --is-ancestor), so the tested binary predates it.
Upgrade check (amd_release) / Download script failed + Check failed one event, one owner: the job never downloaded the previous release, so no upgrade path was exercised and the red says nothing about this PR. job.log shows tests/ci/get_previous_release_tag.py:92 get_release_by_tag -> build_download_helper.py:66 get_gh_api exhausting its 5 fixed-3s retries against a GitHub API 504 Gateway Time-out on releases/tags/v26.7.1.1315-stable, all inside a ~12 second window. 2 hits / 2 unrelated PRs / 0 master over 30 days. a fix task is created (investigating at full effort - fixing PR link to follow here)

Not caused by this PR. Its diff is src/Processors/QueryPlan/JoinStepLogical.cpp and the new 04648_join_dummy_only_both_children test; CIDB records zero join-header or __join_result_dummy failures on this PR on any head. Fast test, Style check, Build (arm_tidy) and all Stateless, Integration and Unit test jobs are green on this head.

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`),

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.

@groeneai trim the comments

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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();

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.

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The body already scopes this, under #### Scope:

The duplicate-name precondition is also carried by the three-argument JoinExpressionActions constructor 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]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 30, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.40% 86.50% +0.10%
Functions 91.80% 91.90% +0.10%
Branches 78.50% 78.70% +0.20%

Changed lines: Changed C/C++ lines covered: 9/9 (100.00%) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - cfd2a9d

CI is fully finished on this head: all 174 check-runs completed, Config Workflow and Finish
Workflow both green, and no check reports a failure.

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

CIDB records no FAIL or ERROR test row against this commit either, so there is nothing to own.

Session id: cron:our-pr-ci-monitor:20260730-233000

@PedroTadim

Copy link
Copy Markdown
Member

@vdimir LGTM! Can you give a final look? The PR is very small

@PedroTadim

Copy link
Copy Markdown
Member

I trust this

@PedroTadim
PedroTadim added this pull request to the merge queue Jul 31, 2026
Merged via the queue into ClickHouse:master with commit 87b1b1d Jul 31, 2026
178 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 31, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Aug 21, 2026
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
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Aug 21, 2026
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
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Aug 21, 2026
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
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 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.

3 participants