Repository navigation
Fix a logical error when a cross-type JOIN key predicate is pushed to a side that join_use_nulls widens - #120109
Conversation
…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]>
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
Severity: ❌ blocker / Session id: cron:clickhouse-review-slot-49:20260915-030600 |
Pre-PR validation gate (click to expand)
|
|
Workflow [PR], commit [0cd3f55] Summary: ✅
AI ReviewSummaryThis PR fixes a Final VerdictStatus: ✅ Approve LLVM Coverage ReportMeasured on commit 0cd3f55.
Changed lines: Changed C/C++ lines covered: 21/21 (100.00%) · Uncovered code |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units7 translation units recompiled, 14 s compile time in total, 7 of them have a recent master baseline. |
797e1fd
ReproducerSET 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 \NResults:
Backport the fix to CC introducing PR author: @raimannma CC component owner: @davenger Analysis metadata
|
…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]>
Changelog category (leave one):
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 thatjoin_use_nullswidens toNullable.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 raisesLOGICAL_ERROR: Unexpected return type from _CAST. Expected UInt64. Got Nullable(UInt64). Debug andsanitizer builds abort on it, which is how
Stress test (arm_tsan)found it; elsewhere it reaches the clientas
Code: 49(Exception::handleErrorCodeaborts onLOGICAL_ERRORonly in debug and sanitizer builds).#103478 was backported to 26.6, 26.7 and 26.8 (#117027, #117028, #117029).
Reproducer
Root cause.
tryPushDownOverJoinStepsubstitutes the opposite side of a cross-type equi key into thepredicate it pushes below the join, under that key's own name when it already has the supertype. That name is
ambiguous:
join_use_nullsmakes the join republish its input names at the widened output type, and thepushed predicate binds its inputs to those outputs by name, so an already built
_CASTends up with aNullable(UInt16)child while keepingresult_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 theambiguous name is corrected where it is created.
propagatePredicateAcrossEquiJoinsubstitutes the same waybut 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)/Stringpair, ajoin_use_nulls = 0control and two push-down guardswith 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]