Skip to content

Fix a logical error when a cross-type JOIN key predicate is pushed to a side that join_use_nulls widens - #120109

Merged
vdimir merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-cross-type-equi-key-pushdown-use-nulls
Sep 15, 2026
Merged

vdimir merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-cross-type-equi-key-pushdown-use-nulls

Conversation

@groeneai

@groeneai groeneai commented Sep 15, 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):

Fixed a LOGICAL_ERROR (Unexpected return type from _CAST) when a predicate over a JOIN equi key whose two sides have different types was pushed down to a side that join_use_nulls widens to Nullable.

Description

Related: #103478 (added the substitution this corrects)
Related: #117973 (lists this case under "Not fixed here")
Found by CI on an unrelated pull request: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=119230&sha=565ba2654912d3b12f8571d407315112308521fb&name_0=PR&name_1=Stress%20test%20%28arm_tsan%29

What breaks. With join_use_nulls = 1, a query with a well-defined answer raises
LOGICAL_ERROR: Unexpected return type from _CAST. Expected UInt64. Got Nullable(UInt64). Debug and
sanitizer builds abort on it, which is how Stress test (arm_tsan) found it; elsewhere it reaches the client
as Code: 49 (Exception::handleErrorCode aborts on LOGICAL_ERROR only in debug and sanitizer builds).
#103478 was backported to 26.6, 26.7 and 26.8 (#117027, #117028, #117029).

Reproducer
SET enable_analyzer = 1, join_use_nulls = 1;
CREATE TABLE a (id UInt8,  v String) ENGINE = Memory;
CREATE TABLE b (id UInt16, v String) ENGINE = Memory;
CREATE TABLE c (id UInt64, v String) ENGINE = Memory;
INSERT INTO a VALUES (0,'a0'),(1,'a1'),(2,'a2');
INSERT INTO b VALUES (0,'b0'),(1,'b1'),(3,'b3');
INSERT INTO c VALUES (0,'c0'),(1,'c1'),(4,'c4');
SELECT id, b.id FROM a LEFT JOIN b USING (id) RIGHT JOIN c USING (id) WHERE id > 1 ORDER BY ALL;

Root cause. tryPushDownOverJoinStep substitutes the opposite side of a cross-type equi key into the
predicate it pushes below the join, under that key's own name when it already has the supertype. That name is
ambiguous: join_use_nulls makes the join republish its input names at the widened output type, and the
pushed predicate binds its inputs to those outputs by name, so an already built _CAST ends up with a
Nullable(UInt16) child while keeping result_type = UInt64.

Change. Take the bare name only while it denotes a single type there, otherwise use the uniquely named
replacement this function already builds for the cast case, as an alias when nothing needs converting. I did
not type-check ActionsDAG::mergeInplace: its contract is name-based and shared by many callers, so the
ambiguous name is corrected where it is created. propagatePredicateAcrossEquiJoin substitutes the same way
but skips a side whose types the join changes, so it cannot hit this.

Validation. The reproducer aborts on master and passes here. The test adds the mirror substitution
direction, a LowCardinality(String)/String pair, a join_use_nulls = 0 control and two push-down guards
with negative controls. 50 sequential and 50 parallel randomised runs pass, results match with push-down on
and off, and the pinned-plan tests need no reference change.


Workflow [PR]
Sync PR [sync-upstream/pr/120109]

…shes

`tryPushDownOverJoinStep` substitutes the opposite side of a cross-type equi key into a predicate it
pushes below the join, and keeps that key's own name whenever it already carries the two sides' least
supertype, on the grounds that such a key is not cast by the join either.

That name is not unambiguous. `join_use_nulls` makes the join null-extend one side before the join and
alias the widened column back to the original name, so the expression DAG deliberately holds two nodes
called `__tableN.id` with different types: the pre-join input, and the post-join output action. The
pushed-down predicate's inputs are matched to the join's output actions by name alone, and merging the
two DAGs re-points the children of nodes that were already built. A `_CAST` in the predicate therefore
ended up with a `Nullable(UInt16)` child while keeping `result_type = UInt64`, and executing it raised
`LOGICAL_ERROR: Unexpected return type from _CAST. Expected UInt64. Got Nullable(UInt64)`. Release
builds return that to the client for a query with a well-defined answer; debug and sanitizer builds
abort, which is how it was found (`Stress test (arm_tsan)`).

Take the bare name only while it denotes a single type at that point in the plan, and otherwise fall
through to the uniquely named replacement this function already builds for the cast case. The sibling
equal-typed substitution above solves the same problem the same way, by renaming to
`__filterpushdown_src<name>`. The replacement's materializer now adds an alias rather than a cast when
the types already agree, so plans that need only the fresh name do not carry an identity `_CAST`.

`ActionsDAG::mergeInplace`'s name-based binding is left alone on purpose: its contract is name-based
and shared by many callers, so the ambiguous name is corrected where it is created rather than guarded
where it bites.

The substitution was added in ClickHouse#103478. My own ClickHouse#117973 lists this case under "Not fixed here" and leaves
the shortcut untouched.

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding labels Sep 15, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex) over the full diff, plus my own
cold review of the resulting code. 2 findings from the model, 2 residual notes of my own. No
blocker survived adjudication.

# Sev Finding Verdict Evidence / action
1 ❌ Cross-type float keys are still substituted into representation-sensitive predicates, so a join-equal +0.0/-0.0 pair can turn a match into an unmatched outer-join row (filterPushDown.cpp:767-784) DISAGREE The defect is real; it is not reachable through this change and not this change's contract. Both branches of the edited if write equivalent_columns[replaced_name], so the set of substitutions and the value substituted are identical before and after; only the substitute's name changes, plus an identity _CAST becoming an ALIAS. The same wrong result is reachable on unmodified master with join_use_nulls = 0, where the added condition is false and the bare-name branch is taken exactly as before, and it is measured on released 26.8.2.7 and 26.6.4.55. It is the subject of my open #117973, which declines float, Dynamic/JSON, unstable-key and representation-reading conjuncts; that PR reciprocally declines the join_use_nulls-widened shape fixed here, so the two are complementary. Sequence them either way.
2 💡 Relationship lines use #NNNNN shorthand rather than full GitHub URLs AGREE, fixed Both Related: lines now carry full PR URLs. I did not add a relationship line for the pull request whose CI run found this: it is an unrelated bystander, and a bare number would post a back-reference on someone else's PR. The report URL above identifies the run.
3 💡 The join_use_nulls = 0 control asserts rows only, which do not distinguish whether the bare-name substitution was kept AGREE, noted Left as is. Over-firing the guard would add one ALIAS node and nothing else: EXPLAIN actions = 0 is byte-identical before and after for the reproducing query, and no checked-in reference changes.
4 💡 The broad join/push_down family sweep was run on the change but not matched against a pristine baseline AGREE, noted 1142 of 1283 passed; all 137 failures are environmental with a measured cause (98 cluster or connection errors against a port this server does not listen on, 15 missing datasets, 24 external resources), none a logical error or a wrong-result diff. The targeted set is green with no reference change, and the full suite runs here.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding.

Session id: cron:clickhouse-review-slot-49:20260915-030600

@clickhouse-gh clickhouse-gh Bot closed this Sep 15, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 15, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, 100% on pristine master: SET enable_analyzer = 1, join_use_nulls = 1; plus three Memory tables with UInt8 / UInt16 / UInt64 keys and SELECT id, b.id FROM a LEFT JOIN b USING (id) RIGHT JOIN c USING (id) WHERE id > 1. The 663-setting reproduction of the original CI run aborts with a byte-identical message.
b Root cause explained? Yes. add_replacement in tryPushDownOverJoinStep substitutes a cross-type equi key into the pushed-down predicate under the key's bare name when it already carries the supertype. join_use_nulls makes the JOIN republish that same name at the widened type, get_required_pre_actions binds the predicate's inputs to the JOIN outputs by name only, and ActionsDAG::mergeInplace re-points the already-built _CAST node's child with no type check, leaving result_type = UInt64 over a Nullable(UInt16) argument. Confirmed by instrumenting the branch decision, not inferred.
c Fix matches root cause? Yes. The ambiguous name is no longer emitted, at the site that creates it. No widened bound, no no-random-* tag, no dataset reduction, no defensive check at the abort site. Type-checking ActionsDAG::mergeInplace was considered and rejected as guarding the symptom.
d Test intent preserved / new tests added? New SQL stateless test 05217_join_cross_type_equi_key_pushdown_use_nulls, parallel-safe, no no-parallel tag. No existing test was weakened, retagged or slowed.
e Both directions demonstrated? Yes. Pristine f8673055 aborts and the running server dies (StopTesting: ClickHouse server died); fixed fcd4001b returns the correct rows and the test reports [ OK ]. Both mutations of the fix were rebuilt and Build-ID-verified: reverting the guard reddens with the exact LOGICAL_ERROR, reverting the alias branch flips the second guard from 1 to 0.
f Fix is general across code paths? Both add_replacement call sites go through one guard, and the mirror site was measured to register the identical unsafe substitution. The five sibling carriers were read: the equivalent_expressions loop, convertJoinToIn, AggregationPushdown and optimizeJoin already gate on typeChangingSides(); predicateOperandsToCommonType already type-checks its map lookup; propagatePredicateAcrossEquiJoin asks the same question via typeChangingSides(). ActionsDAG::mergeInplace's name-based binding is deliberately untouched and is named in the PR body.
g Fix generalizes across inputs (params/datatypes/wrappers)? Integer widths in both substitution directions and a LowCardinality(String) / String key pair are covered. tryGetLeastSupertype strips LowCardinality (measured: supertype of UInt8 and LowCardinality(UInt16) is UInt16), so an LC key cannot reach the shortcut at all; the comparison is therefore IDataType::equals with no removeNullable / removeLowCardinality stripping, which would reintroduce the defect.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, no default change, no serialized-state change, so no SettingsChangesHistory.cpp entry and no version gate. Affected plans gain one ALIAS node in EXPLAIN; no checked-in reference file changed, including the pinned-plan tests.
i Invariants and contracts preserved? Yes. The pushed predicate runs below the join on the right child's own rows, where toNullable(x) holds exactly x, so the two bindings only ever differed in declared type and the replacement is value-identical. Verified empirically: the whole test file produces byte-identical output with filter push-down on and off. No locking or concurrency surface is touched.
Session id: cron:clickhouse-impl-slot-6:20260914-235200

@clickhouse-gh

clickhouse-gh Bot commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [0cd3f55]

Summary: ✅


AI Review

Summary

This PR fixes a JoinStepLogical filter-pushdown bug where a cross-type equi-key substitution could bind a pushed predicate to a same-named join_use_nulls output with a different type, producing LOGICAL_ERROR from _CAST. The rename-to-unique-replacement fallback is applied at the point where the ambiguity is created, the new alias branch preserves the previous no-op-cast cases without changing semantics, and the added stateless test covers the failing widened-side shape plus the key controls I would expect for this contract.

Final Verdict

Status: ✅ Approve

LLVM Coverage Report

Measured on commit 0cd3f55.

Metric Baseline Current Δ
Lines 89.10% 89.10% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.50% 81.50% +0.00%

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

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 15, 2026
@groeneai
groeneai requested review from nickitat and vdimir September 15, 2026 03:48
@clickhouse-gh clickhouse-gh Bot added the comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... label Sep 15, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 15, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 0cd3f558d with master bc4d16fc9 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

7 translation units recompiled, 14 s compile time in total, 7 of them have a recent master baseline.

Job report

@clickgapai

Copy link
Copy Markdown
Contributor
Reproducer
SET enable_analyzer = 1, join_use_nulls = 1;
CREATE TABLE a (id UInt8,  v String) ENGINE = Memory;
CREATE TABLE b (id UInt16, v String) ENGINE = Memory;
CREATE TABLE c (id UInt64, v String) ENGINE = Memory;
INSERT INTO a VALUES (0,'a0'),(1,'a1'),(2,'a2');
INSERT INTO b VALUES (0,'b0'),(1,'b1'),(3,'b3');
INSERT INTO c VALUES (0,'c0'),(1,'c1'),(4,'c4');
SELECT id, b.id FROM a LEFT JOIN b USING (id) RIGHT JOIN c USING (id) WHERE id > 1 ORDER BY ALL;
-- 26.6.8.7 / 26.7.14.3 / 26.8.11.7: Code: 49. DB::Exception: Unexpected return type from _CAST. Expected UInt64. Got Nullable(UInt64) (debug/sanitizer builds abort)
-- master, 26.9.2.8: 4	\N

Results:

  • Culprit PR: Push equi-key filter into the left input of RIGHT JOIN for cross-type USING keys Push equi-key filter into the left input of RIGHT JOIN for cross-type USING keys #103478
  • Reproduces on: 26.8, 26.7, 26.6
  • Does not reproduce on: master, 26.9, 26.5, 26.4, 26.3
  • Tested versions: master, 26.9, 26.8, 26.7, 26.6, 26.5, 26.4, 26.3
  • Tested for context, not a backport target (outside the supported set): 26.6, 26.5, 26.4
  • Measured on the public release build (no private branch build published): 26.9, 26.8, 26.7, 26.6, 26.5, 26.4, 26.3
  • Bisect anchor (below the supported window, not a backport target): 26.2 clean
  • ✓ Fix is on master — this PR's change fixes the bug on master. The releases listed above still have the bug and need the backport.

Backport the fix to 26.8, 26.7.

CC introducing PR author: @raimannma
CC introducing PR reviewer: @alexey-milovidov

CC component owner: @davenger

Analysis metadata

comp-query-optimizer · Severity P2 · Finding phase_d_pr120109

original-brownbear pushed a commit to original-brownbear/ClickHouse that referenced this pull request Nov 11, 2026
…gh a FULL JOIN ... USING chain

Three empty Memory tables with keys UInt8 / UInt64 / UInt16 and no settings clause were enough to be
rejected:

  SELECT a.k, b.k, c.k FROM a FULL JOIN b USING (k) LEFT JOIN c USING (k) WHERE c.k > 1;
  Code: 10. Not found column firstNonDefault(__table1.k, __table2.k):
  in block __table1.k UInt64, __table2.k UInt64. (NOT_FOUND_COLUMN_IN_BLOCK)

In tryPushDownOverJoinStep, add_replacement makes a name the filter uses substitutable by the opposite
side's key. When the source already carries the least supertype the JOIN does not cast it either, so the
code took a shortcut: put the source in the map under its own name and add nothing to the pre-filter DAG.
That shortcut silently assumed the name denotes a column of the stream the substituted filter binds
against. For the second join of a FULL JOIN ... USING (k) chain the left key is the first join's coalesced
USING column, carried as the join-computed expression firstNonDefault(__table1.k, __table2.k), while that
join's left stream input header holds only __table1.k and __table2.k. The predicate was rewritten onto the
computed name and pushed below the join, where addNewFilterStepOrThrow could not bind it.

The by-name shortcut now also requires the source to be present, at its own type, in its own side's input
header. That header is derived from source.fromLeft() rather than passed in, so it cannot be mis-wired at a
call site: forEachEquiJoinKey admits only side-pure pairs, and the two add_replacement calls pair the right
key with the right-stream vectors and the left key with the left-stream ones, so the source's own side is
always the stream the substituted filter is pushed to. When the requirement does not hold the code falls
through to the existing replacement, which materialises the substitute from the source's inputs, all of
which belong to that stream. Admission is untouched: cross_type_equivalent_columns.insert runs before the
branch and both branches key the same map, so no push-down is newly allowed or declined and only the
substitute's name and the pre-filter DAG change.

The equal-typed sibling path substitutes by name too, but it pushes every source it substitutes into
required_actions_from_join unconditionally, so the name it promises is always provided. The physical-join
path fills both maps straight from the stream input headers. The cross-type shortcut was the only
substitution in this function that promised a name without providing it.

Two shapes were affected, both measured on stock defaults. FULL plus LEFT or INNER was introduced on master
by ClickHouse#117973, which removed the availability gate that had kept those second-join kinds out of this path, and
is unreleased. FULL plus RIGHT also fails on official v26.8.5.13-lts, so that half is pre-existing on
released branches. The guard added in ClickHouse#120109 covers neither: it asks whether the source's own name appears
in the JOIN output at a different type, and here that name is absent from the output altogether.

Beyond the new test, the same 1287 stateless tests matching join, push_down, pushdown and filter_push were
run against the unpatched and the patched binary on one rig: no test regresses, and exactly one changes
state, the new one. 04117 and 05217, which pin this machinery including their EXPLAIN granule assertions,
pass unmodified.

Co-Authored-By: Claude Opus 5 <[email protected]>
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-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding 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.

4 participants