Skip to content

Fix Block structure mismatch in JoinStep for decorrelated correlated subquery with duplicate column name - #109114

Merged
alexey-milovidov merged 10 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-runtime-filter-dup-column-decorrelation
Jul 17, 2026
Merged

alexey-milovidov merged 10 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-runtime-filter-dup-column-decorrelation

Conversation

@groeneai

@groeneai groeneai commented Jul 2, 2026 •

Copy link
Copy Markdown
Collaborator

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 Block structure mismatch in JoinStep logical error (server abort in debug/sanitizer builds) when a correlated subquery is decorrelated into a join and the source relation carries a column name more than once, e.g. WITH t AS (SELECT number, * FROM numbers(3)) SELECT *, (SELECT t.number WHERE t.number >= 0) FROM t with correlated_subqueries_default_join_kind = 'right'.

Description

Found by the AST fuzzer (Stress test (amd_debug), STID 0993-386d, CI report). Also observed as 0993-308a on tsan and 2228-453d on ubsan.

Closes: #109215

Reproducer:

WITH t AS (SELECT number, * FROM numbers(3))
SELECT *, (SELECT t.number WHERE t.number >= 0) AS r FROM t
ORDER BY 1
SETTINGS correlated_subqueries_default_join_kind = 'right',
         correlated_subqueries_use_in_memory_buffer = 0;

Aborts with:

Logical error: 'Block structure mismatch in JoinStep: [__table3.number, __table3.number] and [__table3.number] ...'

Root cause. The CTE t = SELECT number, * FROM numbers(3) legitimately produces a relation whose header carries the column name __table3.number twice. The correlated scalar subquery is decorrelated into an ANY RIGHT JOIN over that relation. When join runtime filters are enabled (enable_join_runtime_filters = 1, the default), tryAddJoinRuntimeFilter builds a filter on the duplicated key column and inserts filter/key expressions addressed by column name. Because that machinery is name-keyed (findInOutputs, BuildRuntimeFilterStep on the key name, name-keyed permutations), it cannot represent the duplicated column: applying the filter changes the physical stream's column multiplicity so a downstream join step's declared header no longer matches its pipeline, tripping assertBlocksHaveEqualStructure. Plain right joins over such relations do not hit this because their surrounding plan does not contain the nested join whose declared header desyncs.

Fix. Skip the runtime-filter optimization for a join whose input header contains a duplicate column name. A runtime filter is a pure optimization, so skipping it only forgoes the filter and never changes results. This mirrors the existing JoinStepLogical::canRemoveUnusedColumns(), which likewise disables an optimization when a join condition input column is duplicated by name ("dealing with duplicate columns by name instead of positions ... breaks HashJoin"). Normal joins are unaffected: EXPLAIN still shows BuildRuntimeFilter for joins without duplicated column names.

Verified the added test 04493_correlated_subquery_join_runtime_filter_dup_column fails (server abort) without the fix and passes with it, and that existing correlated-subquery tests continue to pass.

Closes #109215

Version info

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

@groeneai

groeneai commented Jul 2, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. WITH t AS (SELECT number, * FROM numbers(3)) SELECT *, (SELECT t.number WHERE t.number >= 0) AS r FROM t ORDER BY 1 SETTINGS correlated_subqueries_default_join_kind='right', correlated_subqueries_use_in_memory_buffer=0; aborts 100% of the time on a debug build. Isolated the two triggers by binary search over settings: it needs join_kind='right' AND the join-runtime-filter path (setting enable_join_runtime_filters=0 makes it disappear).
b Root cause explained? Yes. The CTE SELECT number, * yields a relation whose header carries __table3.number twice. The correlated subquery is decorrelated into an ANY RIGHT JOIN over it. tryAddJoinRuntimeFilter then builds a filter on the duplicated key column and inserts filter/key expressions addressed by column NAME (findInOutputs, BuildRuntimeFilterStep on the key name, name-keyed permutations). That machinery cannot represent the duplicated name, so applying the filter changes a downstream join step's physical stream to carry 2 __table3.number columns while its declared header has 1 -> assertBlocksHaveEqualStructure fails in JoinStep::updatePipeline.
c Fix matches root cause? Yes. The fix skips the runtime-filter optimization exactly when a join input header contains a duplicate column name -- the precise unsafe condition. It removes the trigger at the optimization that introduces the inconsistency, not at the assertion.
d Test intent preserved / new tests added? New test 04493_correlated_subquery_join_runtime_filter_dup_column added: the crashing query (right + buffer=0), the left variant, a triple-duplicate variant, and a check that a normal join still gets BuildRuntimeFilter (guards against over-restriction).
e Both directions demonstrated? Yes. Stashed the fix, rebuilt: the test aborts the server (SIGABRT). Restored the fix, rebuilt: the test passes 5/5 with randomization. Both on Build-ID-verified binaries built off master.
f Fix is general across code paths? Yes. The guard sits at the single entry point tryAddJoinRuntimeFilter and checks both join inputs, so it covers per-column and tuple runtime-filter branches and every join kind that reaches this optimization. Verified left/right, triple-dup, and larger data. Not a symptom guard: it disables the unsafe optimization rather than patching the downstream assertion.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. The condition is purely "a column name appears more than once in an input header", independent of column type/wrapper, join kind, or key count. Verified plain UInt64; the mechanism is name-based so type wrappers are irrelevant.
h Backward compatible? (maintainer-approved exception only) Yes, fully compatible. No setting default, on-disk/wire format, or validation change. A runtime filter is a pure optimization; skipping it for a pathological input only forgoes the filter and never changes results.
i Invariants and contracts preserved? Yes. Restores the invariant that a JoinStep's declared output header matches its physical pipeline (block-structure consistency). Mirrors the existing JoinStepLogical::canRemoveUnusedColumns() guard, which likewise disables an optimization when a join condition input is duplicated by name ("dealing with duplicate columns by name instead of positions ... breaks HashJoin").

Session id: cron:clickhouse-worker-slot-2:20260702-032400

@groeneai

groeneai commented Jul 2, 2026

Copy link
Copy Markdown
Collaborator Author

cc @davenger @novikd — could you review this? A correlated subquery decorrelated into an ANY RIGHT JOIN over a relation with a duplicated column name (from SELECT number, *) makes the name-keyed join-runtime-filter machinery change a downstream join step's stream shape, aborting with Block structure mismatch in JoinStep. The fix skips the runtime filter when a join input header has a duplicate column name (a pure optimization, so results are unchanged), mirroring the existing JoinStepLogical::canRemoveUnusedColumns() guard.

@clickhouse-gh

clickhouse-gh Bot commented Jul 2, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [8fdd52e]

Summary: ✅


AI Review

Summary

This PR narrows the tryAddJoinRuntimeFilter guard to the duplicated build-side join-key case that actually breaks the name-keyed runtime-filter machinery, and it adds focused stateless coverage for the original correlated-subquery reproducer plus the over-restriction cases raised in review. After reconciling the existing discussion with the current code and tests, I did not find a remaining correctness, safety, or coverage issue in the diff.

Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 2, 2026
…subquery with duplicate join key

A correlated scalar subquery over a relation whose header carries the join
KEY column name more than once (e.g. `WITH t AS (SELECT number, * FROM
numbers(3))` yields two columns named `number`) is decorrelated into an ANY
RIGHT JOIN. With join runtime filters enabled the filter is built on that
duplicated key column. The runtime-filter machinery is name-keyed
(BuildRuntimeFilterStep on the key name, findInOutputs, name-keyed
permutations) and cannot disambiguate two identically-named key columns, so
applying the filter changes a downstream join step's stream multiplicity and
aborts with 'Block structure mismatch in JoinStep' (a LOGICAL_ERROR, i.e. a
handled exception in release builds, a server abort in debug/sanitizer builds).

Skip the runtime-filter optimization only when a BUILD-side join KEY column
name is duplicated in the build input header. A duplicated non-key build
column, or a duplicated key on the probe side (where the filter is only
applied and preserves the header), is harmless and must keep the filter -
narrowing the guard to the build keys avoids stripping legitimate runtime
filters (see 03777_join_runtime_filter_duplicate_columns). The runtime filter
is a pure optimization, so skipping it only forgoes the filter and never
changes results. Mirrors JoinStepLogical::canRemoveUnusedColumns(), which
disables a sibling optimization on duplicated join-condition inputs.

Found by the AST fuzzer (Stress test (amd_debug), STID 0993-386d).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai
groeneai force-pushed the groeneai/fix-runtime-filter-dup-column-decorrelation branch from 5d57b30 to ff52fbd Compare July 2, 2026 08:12
@groeneai

groeneai commented Jul 2, 2026

Copy link
Copy Markdown
Collaborator Author

Update (narrowed the guard). The initial version skipped the runtime filter whenever any input header had a duplicate column name. That was too broad: it stripped a legitimate runtime filter in the pre-existing test 03777_join_runtime_filter_duplicate_columns (whose build side has a duplicated non-key column while the join key is unique), which failed the Fast test (03777 result differs with reference). The guard is now scoped to the actual trigger: skip the filter only when a build-side join KEY column name is duplicated in the build header. 03777 again matches its committed reference (RF preserved), and the crash is still fixed.

Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. WITH t AS (SELECT number, * FROM numbers(3)) SELECT *, (SELECT t.number WHERE t.number >= 0) AS r FROM t ORDER BY 1 SETTINGS correlated_subqueries_default_join_kind='right', correlated_subqueries_use_in_memory_buffer=0; aborts 100% of the time without the fix.
b Root cause explained? The CTE SELECT number, * legitimately yields two columns both named __table3.number. The correlated scalar subquery is decorrelated into an ANY RIGHT JOIN whose build (right) side carries that duplicated key column. enable_join_runtime_filters then builds a runtime filter on the key; the RF machinery is name-keyed (BuildRuntimeFilterStep on the key name, findInOutputs, name-keyed permutations / cloneSubdagWithInputs) and cannot disambiguate two identically-named key columns, so the filter re-roots a downstream join input's stream to carry the key twice while its declared header still expects one column → assertBlocksHaveEqualStructure → Block structure mismatch in JoinStep: [__table3.number, __table3.number] and [__table3.number] (a LOGICAL_ERROR: a handled exception in release, a server abort in debug/sanitizer).
c Fix matches root cause? Yes. Skip the runtime-filter optimization only when a build-side join KEY column name is duplicated in the build input header — exactly the condition the name-keyed RF machinery cannot represent. Mirrors the existing JoinStepLogical::canRemoveUnusedColumns() guard, which disables a sibling optimization on duplicated join-condition inputs.
d Test intent preserved / new tests added? Yes. New 04493_correlated_subquery_join_runtime_filter_dup_column covers the crash (right/left/triple-dup) and asserts the RF is still built both for a normal join and for a build side with a unique key + duplicated non-key column (guards against re-broadening). 03777 is unchanged and again matches its reference.
e Both directions demonstrated? Yes. Fails without the guard (SIGABRT on the reproducer; and the blanket-guard build strips 03777's RF), passes with the narrowed guard (reproducer returns correct rows; 03777 RF preserved; 04493 passes). All on Build-ID-verified binaries.
f Fix is general across code paths? The trigger is the name-keyed RF build path (tryAddJoinRuntimeFilter). A sibling path (makeDistributed.cpp) also calls preCalculateKeys + cloneSubdagWithInputs and shares the same name-keyed assumption; I could not reproduce a crash there locally (needs distributed / parallel-replica planning), so I did not speculatively patch it. Flagging for reviewers.
g Fix generalizes across inputs? Verified right/left join kind, buffer on/off, triple duplicate (SELECT number, *, *), larger data, and parallel replicas — all correct, no crash. LowCardinality-typed duplicate key yields a clean AMBIGUOUS_COLUMN_NAME exception (pre-existing analyzer behavior), not a crash.
h Backward compatible? Yes. No setting default, format, or validation change. The runtime filter is a pure optimization; skipping it for this pathological input only forgoes the filter and never changes results.
i Invariants and contracts preserved? Yes. The join step's block-structure invariant (declared header == physical stream) is what was being violated; the fix upholds it by not introducing a filter the name-keyed machinery cannot represent. No lock/ownership/lifetime contracts touched.

Session id: cron:clickhouse-worker-slot-3:20260702-074200

@groeneai

groeneai commented Jul 2, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — ff52fbd

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
Stress test (amd_tsan) / Not-ready Set is passed as the second argument for function 'notNullIn' (STID 0250-41a5) logical error (chronic IN-family trunk bug, 132 distinct PRs + 25 master hits in 30d; unrelated to this PR's decorrelation fix) #107924 (external, open) — "Fix 'Not-ready Set' exception by making in-place set build non-destructive"
CH Inc sync — CH Inc sync (private, not actionable)

All other 168 checks green (Build ×all, Stateless, Integration, Stress ×11, AST fuzzer ×6, BuzzHouse ×4, Unit, Upgrade, Performance, Fast test, Mergeable Check, Finish Workflow). The PR-caused Fast-test 03777 failure on the prior head 5d57b30 was fixed here by narrowing the runtime-filter duplicate-name guard.

Session id: cron:our-pr-ci-monitor:20260702-120000

@alexey-milovidov alexey-milovidov left a comment

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.

Yes, very reasonable. Thank you!

@alexey-milovidov alexey-milovidov self-assigned this Jul 12, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

@groeneai, the "Not-ready Set" has been fixed in master. Please update the branch.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Branch updated: merged latest master (now including the Not-ready Set fix). Head is now 76bcc25.

The two EXPLAIN assertions in 04493_correlated_subquery_join_runtime_filter_dup_column
check that a BuildRuntimeFilter step is present. The runtime filter is only added for
hash-family join algorithms (supportsRuntimeFilter: hash, parallel_hash, grace_hash).
CI randomizes join_algorithm, so runs that pick full_sorting_merge/partial_merge built
no filter and the assertions returned 0 instead of 1, making the new test flap in the
flaky check. Pin join_algorithm='hash' at query level in those two EXPLAIN subqueries.

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

Copy link
Copy Markdown
Member

@groeneai, the failure of the "distributed plan" is what we fixed in master. Please update the branch.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Branch updated: merged latest master (now includes the distributed-plan fix), head is now 8fdd52e.

@clickhouse-gh

clickhouse-gh Bot commented Jul 16, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.90% 85.90% +0.00%
Functions 92.70% 92.70% +0.00%
Branches 78.10% 78.10% +0.00%

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

Full report · Diff report

@alexey-milovidov
alexey-milovidov merged commit 5e9c1f3 into ClickHouse:master Jul 17, 2026
176 of 177 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 17, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Jul 29, 2026
Picks up ClickHouse#109114 (merge 5e9c1f3, 2026-07-17), which owns the
Stress test (amd_debug) 'Block structure mismatch in JoinStep' failure
recorded on the previous head's CI ledger, and gets a current-base run.
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…me-filter-dup-column-decorrelation

Fix Block structure mismatch in JoinStep for decorrelated correlated subquery with duplicate column name
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.

Logical error: Block structure mismatch in A stream: different number of columns: (STID: 0993-308a)

4 participants