Skip to content

Fix LOGICAL_ERROR on duplicate __join_result_dummy when deserializing a distributed join plan - #108787

Open
groeneai wants to merge 4 commits into
ClickHouse:masterfrom
groeneai:fix-4752-join-result-dummy-deserialize-collision
Open

groeneai wants to merge 4 commits into
ClickHouse:masterfrom
groeneai:fix-4752-join-result-dummy-deserialize-collision

Conversation

@groeneai

Copy link
Copy Markdown
Collaborator

Related: #89166

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 ("Left and right columns have same names: [__join_result_dummy], ...") when a distributed query plan (make_distributed_plan = 1, serialize_query_plan = 1) contains a join whose two inputs are both joins with no required output columns (for example count() over a CROSS join of two such joins). In debug and sanitizer builds this aborted the server on the worker that deserialized the plan.

Description

JoinStepLogical adds a constant marker column __join_result_dummy to its output whenever a join has no required output columns (e.g. a count() that needs no join keys). When such a join is itself an input to another join (e.g. count() over a CROSS join of two count-pruned joins), both of the parent join's input headers carry __join_result_dummy.

The in-process planner builds this with the two-argument JoinExpressionActions(left_header, right_header) constructor, which assigns each input's source side positionally and is fine with the duplicate name. A distributed-plan worker, however, reconstructs the same step with the three-argument constructor (a serialized ActionsDAG plus the two child output headers) in JoinStepLogical::deserialize. That constructor mapped each input to its source side by name and rejected any name present in both headers with a LOGICAL_ERROR, even though the structure is valid and was produced by the initiator.

Found by the AST fuzzer mutating tests/queries/0_stateless/03394_distributed_shuffle_join.sql (a comma join whose predicate the fuzzer neutralized into a CROSS join), Stress test (arm_tsan). Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108088&sha=39a5968c228d6a28a04328e39f27470f077d2e24&name_0=PR&name_1=Stress%20test%20%28arm_tsan%29

The fix keeps name-based source mapping for the common (unambiguous) case so unrelated callers are unaffected, and only for a name present in both headers falls back to positional mapping: the DAG inputs are ordered [left header columns..., right header columns...] (an invariant already relied on elsewhere in JoinStepLogical, which reads the first right input as getInputs().at(number_of_left_inputs)). Each input still maps to exactly one side, so downstream source-relation checks are unchanged.

Regression test: src/Interpreters/tests/gtest_join_expression_actions.cpp exercises the three-argument constructor directly with two headers that both contain __join_result_dummy (fails with the LOGICAL_ERROR before the fix, passes after) and a control case asserting distinct names still map to their own side.

… a distributed join plan

JoinStepLogical emits a constant __join_result_dummy marker column when a join
has no required output columns. A parent join over two such joins (e.g. count()
over a CROSS join of two count-pruned joins) gets __join_result_dummy on both
input headers. The in-process planner builds this via the two-argument
JoinExpressionActions constructor (positional source mapping, no name check),
but a distributed-plan worker reconstructs it via the three-argument
constructor in JoinStepLogical::deserialize, which mapped sources by name and
rejected the duplicate name with a LOGICAL_ERROR, aborting the server in debug
and sanitizer builds.

Keep name-based mapping for the unambiguous case and fall back to positional
mapping only for a name present in both headers (DAG inputs are ordered
[left columns..., right columns...], an invariant JoinStepLogical already relies
on). Add a unit test exercising the three-argument constructor with the
duplicate dummy column.

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. Unit test JoinExpressionActions.DuplicateDummyColumnInBothHeaders constructs the three-argument JoinExpressionActions ctor with two headers both containing __join_result_dummy plus a matching ActionsDAG, deterministically triggering the exact crash. (The end-to-end fuzzed SQL needs the multi-host distributed stage split that does not fire on a single host, so the repro targets the precise crashing code path the worker hits on deserialize.)
b Root cause explained? Yes. JoinStepLogical emits a const __join_result_dummy marker when a join has no required output columns; a parent join over two such joins gets that name on both input headers. The in-process planner builds it via the 2-arg JoinExpressionActions ctor (positional source mapping, no name check); the distributed-plan worker rebuilds it via the 3-arg ctor in JoinStepLogical::deserialize, which mapped sources by name and threw LOGICAL_ERROR on the duplicate name, aborting the server in debug/sanitizer builds.
c Fix matches root cause? Yes. The 3-arg ctor now keeps name-based mapping for the unambiguous case and, only for a name present in both headers, falls back to positional mapping (DAG inputs are ordered [left cols..., right cols...], the same invariant JoinStepLogical already relies on via getInputs().at(number_of_left_inputs)). It removes the false collision check rather than masking the symptom.
d Test intent preserved / new tests added? New unit test src/Interpreters/tests/gtest_join_expression_actions.cpp: one case reproduces the regression (the duplicate-dummy ctor), one control case asserts distinct names still map to their own side. No existing test weakened.
e Both directions demonstrated? Yes. With the collision check reverted (fix stashed, test kept) the regression test fails with the exact Left and right columns have same names: [..., __join_result_dummy], [..., __join_result_dummy] LOGICAL_ERROR at JoinExpressionActions.cpp:131; with the fix it passes. Build IDs verified distinct between runs.
f Fix is general across code paths? Yes. Both 3-arg-ctor call sites were checked: JoinStepLogical::deserialize (the crash) and optimizeJoin.cpp (join reordering). Name-based mapping is preserved for the common case so the reordering path is unaffected (verified: a pure-positional rewrite broke it with NOT_FOUND_COLUMN_IN_BLOCK, the surgical version does not).
g Fix generalizes across inputs? Yes. Verified distributed-vs-baseline result parity for 2/3/4-way comma joins, the broken-link CROSS shape, JOIN ... ON, LEFT JOIN, and sum() aggregations; all match the non-distributed baseline. The dummy is a UInt8 const independent of column datatypes/wrappers.
h Backward compatible? Yes. No setting default, on-disk/wire/replication format, or new data validation changed. Pure in-memory plan-reconstruction logic; no SettingsChangesHistory.cpp change needed.
i Invariants and contracts preserved? Yes. Each input still maps to exactly one source side, upholding JoinStepLogical's `chassert(ref.fromLeft()

Session id: cron:clickhouse-worker-slot-0:20260629-023900

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @KochetovNicolai @davenger — could you review this? It fixes a LOGICAL_ERROR ("Left and right columns have same names: [__join_result_dummy]") that aborts a distributed-plan worker (make_distributed_plan=1, serialize_query_plan=1) when deserializing a join whose two inputs are both count-pruned joins that each emit the __join_result_dummy marker. JoinStepLogical::deserialize's 3-arg JoinExpressionActions ctor mapped input sources by name and rejected the duplicate; the fix falls back to positional mapping only for a name present in both headers, matching the 2-arg ctor the in-process planner already uses.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Jun 29, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 29, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [9d4b465]

Summary: ❌

job_name test_name status info comment
Stress test (amd_debug) FAIL
Logical error: Query context must be created after authentication (STID: 3197-391f) FAIL cidb
AST fuzzer (arm_asan_ubsan) FAIL
Logical error: Can't determine table for parallel replicas (STID: 3634-41e5) FAIL cidb

AI Review

Summary

This PR fixes the __join_result_dummy deserialize failure by letting the three-argument JoinExpressionActions constructor accept duplicated names only when the serialized inputs still match [left header columns..., right header columns...]. That covers the dummy-marker case, but the fix is not complete: distributed shuffle joins with computed equality keys and overlapping user column names now fail with LOGICAL_ERROR during plan deserialization, so I cannot approve it as-is.

Findings

❌ Blockers

  • [src/Interpreters/JoinExpressionActions.cpp:163] makeDistributedJoin calls preCalculateKeys before serializing a shuffled logical join (src/Processors/QueryPlan/Optimizations/makeDistributed.cpp:282), and preCalculateKeys appends computed key INPUTs with expression_actions.addInput while widening both input headers (src/Processors/QueryPlan/JoinStepLogical.cpp:1613-1616). If the two child headers also share an ordinary name like id, the serialized inputs become non-canonical ([left id, left x, right id, right y, left key, right key] with left_header.columns() == 3), inputs_match_headers_by_position flips to false, and the constructor now throws Cannot determine the source side of duplicated input column 'id' for a plan that the in-process two-argument constructor already accepted. This regresses valid distributed shuffle joins with overlapping column names from “works” to LOGICAL_ERROR.
    Suggested fix: serialize the input-side/source mapping (or another unambiguous per-input side tag) with the join DAG and reuse it on deserialization instead of inferring duplicate inputs from the widened headers.
Tests
  • ⚠️ Add a regression that goes through make_distributed_plan shuffle-key pre-calculation with overlapping child-column names plus computed equi-keys; the current gtests only cover __join_result_dummy and synthetic ambiguous duplicates, so they miss the valid distributed plan that still throws here.
Final Verdict

Request changes.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 29, 2026
…ation

Code review on the previous commit pointed out that the positional fallback
for a duplicate-named input is unsafe in general: JoinStepLogical::preCalculateKeys
appends computed join-key inputs via addInput and expands both input headers, so a
serialized shuffle join can have inputs like [left id, left k, right id, right k,
left key, right key] while left_header.columns() is already 3. Slicing such a list at
number_of_left_inputs would mark the second header-named input as left even though it
belongs to the right side, corrupting source attribution.

The only duplicate name that actually reaches this constructor is the const
__join_result_dummy marker emitted by a count-pruned join. A join carrying it has no
equality keys, so preCalculateKeys never runs and the inputs keep their canonical
[left header columns..., right header columns...] order. Rather than silently trust
position, verify that the input names match the concatenated headers position by
position, and only then resolve a both-headers name by position. If the layout is not
canonical (the interleaved-keys case from the review), the side is genuinely ambiguous
and we throw instead of guessing.

The other three-argument constructor caller (optimizeJoin.cpp, foldActionsByProjection)
has disjoint left/right names, so has_shared_name is false and the positional path is
never taken there; its behavior is unchanged.

Adds gtest coverage: unique interleaved inputs still map by name; a duplicate name with
a non-canonical layout is rejected (death test in debug/sanitizer builds where
LOGICAL_ERROR aborts, throw in release).

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

Copy link
Copy Markdown
Collaborator Author

Updated pre-PR validation gate for 505ad9e (addresses the positional-fallback review).

Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. gtest JoinExpressionActions.DuplicateDummyColumnInBothHeaders reconstructs the deserialize-path inputs [left_key, __join_result_dummy, right_key, __join_result_dummy] and aborts on master code with the exact CI error. The interleaved-keys concern is covered deterministically by DuplicateNameWithNonCanonicalLayoutThrows.
b Root cause explained? A count-pruned JoinStepLogical emits the const __join_result_dummy marker; a parent join over two such joins (count() over a CROSS join) carries it on both inputs. The in-process 2-arg ctor maps sources positionally and tolerates this; the 3-arg deserialize ctor mapped by name and threw on the shared name. The review added: a blind positional fallback is unsafe because preCalculateKeys appends computed key inputs and breaks the [left.., right..] order.
c Fix matches root cause? Yes. The 3-arg ctor now resolves a both-headers name by position ONLY after verifying the inputs match the concatenated headers position-by-position; otherwise it throws (genuinely ambiguous). Unique names still map by name.
d Test intent preserved / new tests added? New gtests added: DuplicateDummyColumnInBothHeaders (repro), DistinctColumnNamesMapToTheirSide (common case), InterleavedInputsWithUniqueNamesMapByName (post-preCalculateKeys unique inputs), DuplicateNameWithNonCanonicalLayoutThrows (the review's interleaved-duplicate case is rejected, not mis-attributed).
e Both directions demonstrated? Yes. Master code: DuplicateDummyColumnInBothHeaders aborts SIGABRT with 'Left and right columns have same names: [...__join_result_dummy], [...__join_result_dummy]'. With fix: all 4 gtests pass. Build IDs verified across the revert/restore cycle.
f Fix is general across code paths? The other 3-arg caller (optimizeJoin.cpp, foldActionsByProjection) has disjoint left/right names, so has_shared_name is false and the positional path is never taken there; DistributedQueryTest.ShuffleHashJoin still passes. Not a symptom guard: the change fixes the source-attribution logic itself.
g Fix generalizes across inputs? The disambiguation is name/position based and type-agnostic, so it holds for any column type/wrapper. The shared name in practice is only the __join_result_dummy UInt8 marker; the validation handles any shared name and rejects the ambiguous (non-canonical) layout for all of them.
h Backward compatible? Yes. No wire/serialization format change, no setting change. The fix only relaxes/validates reconstruction logic on the worker; it is strictly more permissive than master for the canonical-layout case and identical to master (reject) for the ambiguous case.
i Invariants and contracts preserved? Yes. Every input still maps to exactly one side (upholds `chassert(fromLeft()

Session id: cron:clickhouse-worker-slot-1:20260629-051600

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 505ad9e

Every failure below has an owner: a fixing PR (ours 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.

Check / test Reason Owner / fixing PR
Stateless tests (amd_msan, WasmEdge, parallel, 2/2) / 03365_column_ttl_should_rebuild_skp_idx_and_proj flaky (600s timeout, slowest MSan+WasmEdge shard; 0 master, 3 unrelated PRs/30d; unrelated to this PR's JoinExpressionActions diff) a fix task is created (investigating at full effort — fixing-PR link to follow here)

Mergeable Check and the top-level PR rollup are red only because they aggregate the single Stateless shard above; they carry no independent failure.

Session id: cron:our-pr-ci-monitor:20260629-100000

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for 03365_column_ttl_should_rebuild_skp_idx_and_proj amd_msan/WasmEdge timeout created: #108805

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 8d2749d

Every failure below has an owner: a fixing PR (ours 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.

Check / test Reason Owner / fixing PR
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) / 01666_merge_tree_max_query_limit flaky, trunk — under parallel replicas one statement becomes several reads of the same table on this server, each with a different query id, so the long-running holder query competes against itself for the single max_concurrent_queries slot and is rejected instead of holding it #112385 (ours, open)

The earlier partial fix #111528 (pin max_threads = 1 on the holder query) is present on this
head and does not cover the parallel-replicas route, so #112385 disables parallel replicas for
this test outright.

Session id: cron:our-pr-ci-monitor:20260729-103000

pull Bot pushed a commit to sonvt1710/ClickHouse that referenced this pull request Jul 31, 2026
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]>
/// Duplicate name present on both sides: resolvable only by position, and only when the
/// canonical input layout was verified above.
if (!inputs_match_headers_by_position)
throw Exception(ErrorCodes::LOGICAL_ERROR,

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.

makeDistributedJoin can still send a valid plan into this exception. In the shuffle path we call join_step->preCalculateKeys before serializing the logical join (src/Processors/QueryPlan/Optimizations/makeDistributed.cpp:282). When an equi-key is computed, preCalculateKeys appends new INPUTs with expression_actions.addInput and widens both headers (src/Processors/QueryPlan/JoinStepLogical.cpp:1613-1616), so a join whose child headers are [id, x] and [id, y] becomes [left id, left x, right id, right y, left key, right key] while left_header.columns() == 3. That makes inputs_match_headers_by_position false, and this branch now throws on the original duplicate id even though the plan is valid and the in-process two-arg constructor already mapped those inputs positionally. So distributed shuffle joins over overlapping column names regress from “works” to LOGICAL_ERROR as soon as a computed equality key is present. The source-side mapping needs to survive serialization instead of being re-derived from the widened headers.

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.

I checked this on the current head (9d4b465) with instrumentation rather than by reading, and the shape does not reach the throw: the analyzer qualifies every source column, so has_shared_name is never true for an ordinary user column.

I logged the 3-arg ctor's actual arguments and ran your exact example ([id, x] / [id, y], computed equi-key so preCalculateKeys runs) as a real shuffle join across two replicas, make_distributed_plan=1, serialize_query_plan=1, distributed_plan_max_rows_to_broadcast=0:

JEAPROBE 3arg ctor: inputs=4 left=[__table1.id, plus(__table1.id, 1_UInt8)] right=[__table2.id, plus(__table2.id, 1_UInt8)] has_shared_name=false

inputs=4 confirms preCalculateKeys did run and did widen both headers, so the non-canonical layout you describe is real. But the names arriving at the ctor are __table1.id and __table2.id, not id and id: the Expression (Change column names to column identifiers) step rewrites every source column to a __tableN.-qualified identifier before the join, so the left and right name sets are disjoint and the duplicate-name branch is never entered.

That holds for the cases designed to force a collision. A self-join gives __table1.id / __table2.id, and two subqueries both aliasing to k give __table1.k / __table3.k:

JEAPROBE ... left=[__table1.id] right=[__table2.id]                 has_shared_name=false
JEAPROBE ... left=[__table1.k]  right=[__table3.k]                  has_shared_name=false
JEAPROBE ... left=[__table2.id, plus(...)] right=[__table3.id, plus(...)] has_shared_name=false

Across that sweep (2-table, self-join, identical aliases, 3-way), all queries returned the correct 200, has_shared_name=true was observed 0 times, and neither the new "Cannot determine the source side" exception nor the original "Left and right columns have same names" ever fired.

So the only name that reaches this branch is still the unqualified __join_result_dummy marker, and a join carrying it has no equi-keys, so preCalculateKeys returns early at the left_keys.empty() check and the layout stays canonical. The positional resolution is only used where it is verified, and the throw covers a shape I could not construct.

I would rather not serialize the source mapping on the strength of a shape that does not currently occur, since that changes the plan serialization format for every join. If you have a query that produces two identically-named columns in the two child headers of a serialized join, I will take it and fix it: the throw is deliberately loud so such a case is a clear error and not a silent mis-attribution.

No code change in this round. Instrumentation was temporary and is not in the diff.

@clickhouse-gh

clickhouse-gh Bot commented Aug 1, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.70% +0.00%

Changed lines: Changed C/C++ lines covered: 81/83 (97.59%) · Uncovered code

Full report · Diff report

@groeneai

groeneai commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 9d4b465

Every failure below has an owner: a fixing PR (ours 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.

Check / test Reason Owner / fixing PR
AST fuzzer (arm_asan_ubsan) / Can't determine table for parallel replicas (STID 3634-41e5) trunk bug in parallel-replicas table resolution, unrelated to this diff fixing PR #110020 (ours, open)
Stress test (amd_debug) / Query context must be created after authentication (STID 3197-391f) trunk bug: pre-auth query context on the PostgreSQL wire port, not reachable from this diff a fix task is moved to pending (investigating at full effort, fixing-PR link to follow here)

Session id: cron:our-pr-ci-monitor:20260801-230000

@groeneai

groeneai commented Aug 2, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the pre-auth Query context must be created after authentication abort in the Stress test (*) failures ledgered above: #112940.

That PR reapplies #110760 (reverted in #112935) together with the fix: PostgreSQLHandler::cancelRequest no longer builds a query context from the unauthenticated session, cancelling through the new ProcessList::sendCancelToQueryOfAnyUser instead. Verified at its head bfc13929ce68df79, where the signature no longer appears in CIDB while the same Stress flavours ran.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Superseded by #125071, which serializes the side of every join input instead of inferring it from the input names. The positional fallback here is wrong for a join whose inputs were swapped.

This branch has not been deployed

No deployments
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 comp-joins JOINs end-to-end (planning hooks + runtime join operators/algorithms). Single bucket to avoid pla... groeneai-origin-unknown PR origin: unclassified (legacy task) pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants