Repository navigation
Fix Bad cast for a qualified asterisk over a JOIN USING key nested under a PASTE/CROSS join - #108043
Conversation
…der a PASTE/CROSS join Follow-up to the merged fix for the qualified-asterisk JOIN USING bad cast. That fix correctly types t.* from the explicit reference t.col, but only when the top join node of the query scope is the USING join itself. When the USING join is nested below a non-USING top join (a PASTE/CROSS/comma join, or an outer ON join), the top node is not a USING JoinNode, so the whole type-correction block was skipped: the qualified matcher kept its non-Nullable table-storage type while the planner produces a Nullable column (and the explicit t.col reference resolves to Nullable too). An aggregate over the matcher then aborts with "Bad cast from type DB::ColumnNullable to DB::ColumnVector<...>". Repro (debug, deterministic): CREATE TABLE t2 (id UInt64, b UInt64) ENGINE=Memory; CREATE TABLE t3n (id Nullable(UInt64), c Nullable(UInt64)) ENGINE=Memory; INSERT INTO t2 VALUES (1,20),(2,30); INSERT INTO t3n VALUES (2,40),(3,50); SELECT anyHeavy(sipHash64(t2.*)) FROM t2 RIGHT JOIN t3n USING (id) PASTE JOIN numbers(5) AS a SETTINGS join_use_nulls = 0; The USING join t participates in can live anywhere in the join tree, so for a qualified matcher every USING join is examined, not only the top one. The unqualified matcher (*) is unchanged: there the matched column is the merged USING key, which only applies at the top join. Found by the AST fuzzer (CIDB STID 1499-1a38, Stress test (azure, amd_tsan), master). Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pre-PR validation gate
Session id: cron:clickhouse-worker-slot-0:20260620-191600 |
|
cc @vdimir @novikd — follow-up to the merged #107129. That fix types a qualified |
|
Workflow [PR], commit [4467688] Summary: ✅
AI ReviewSummaryThis PR fixes qualified matcher ( PR Metadata
Final VerdictStatus: ✅ Approve |
Follow-up within ClickHouse#108043. The qualified-matcher type-correction walks every JOIN USING node in the tree (collectUsingJoinNodes) so a nested USING key can be found below a PASTE/CROSS/comma join or an outer ON join. But it matched a key purely by column name, so for `(a JOIN b USING(id)) CROSS JOIN t` resolving `t.*` also matched the inner `USING(id)` even though `t` does not participate in it. The matched column then kept the correct (explicit-identifier) type, but `join_columns_with_changed_types[t.id] = a.id` was still registered against the unrelated key. That map drives PREWHERE replacement (ReplaceColumnsVisitor) and identifier equality (resolvedIdenfiersFromJoinAreEquals), so `t.* ... PREWHERE t.id = 1` was rewritten against `a.id` (wrong rows), and a later unqualified `id` could be treated as equal instead of ambiguous. Before retyping or registering, require that the matched column's source is one of the merged contributors of the USING key. Non-participating keys are skipped, and the matcher's column is left untouched. The original nested-USING crash fix is unchanged: when `t` genuinely participates, the key still type-corrects. Extends 04329_qualified_asterisk_join_using_nullable_key with the `(a JOIN b USING(id)) CROSS JOIN t` / comma-join shapes and PREWHERE filtering; the new cases give wrong PREWHERE results before this change. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Good catch, fixed in 8414d88. Confirmed exactly as described: with SET enable_analyzer = 1;
CREATE TABLE a (id Int32) ENGINE=MergeTree ORDER BY tuple();
CREATE TABLE b (id UInt32) ENGINE=MergeTree ORDER BY tuple();
CREATE TABLE t (id UInt64, v String) ENGINE=MergeTree ORDER BY tuple();
INSERT INTO a VALUES (1); INSERT INTO b VALUES (1);
INSERT INTO t VALUES (1,'one'),(2,'two'),(5,'five');
SELECT t.* FROM a INNER JOIN b USING (id) CROSS JOIN t PREWHERE t.id = 5 SETTINGS join_use_nulls = 0;
-- before: empty (rewritten to a.id = 5); WHERE gives (5,five)
SELECT t.* FROM a INNER JOIN b USING (id) CROSS JOIN t PREWHERE t.id = 1 SETTINGS join_use_nulls = 0;
-- before: all 3 rows (rewritten to a.id = 1)
Fix: before retyping or registering, the iterated USING key must have the matched column's Validated both directions on the extended Session id: cron:clickhouse-worker-slot-1:20260620-213800 |
41622cd to
5eefe4f
Compare
The flaky-check job runs each changed test ~50x under randomized settings; a single run over the 180s budget is marked FAIL unless the test carries the `long` tag (tests/clickhouse-test). After the USING-participation regression cases were added in this PR, 04329 covers many distinct multi-join shapes and one debug run under the flaky check's concurrent load exceeded 180s. The data is already minimal (1-3 rows per table) and every query exercises a distinct type-correction / participation path, so there is nothing to shrink without dropping coverage. `long` exempts the 180s flaky-check gate and reduces the repeat count to ~10%; the deterministic participation-gate bug is still caught on the first run, and the normal Stateless jobs keep running the test in full. MergeTree is retained because the regression cases assert PREWHERE rewriting, which only applies to MergeTree-family engines. Co-Authored-By: Claude Opus 4.8 <[email protected]>
5eefe4f to
ea348a5
Compare
|
CI finished on
The Session: cron:our-pr-ci-monitor:20260621-053000 |
| /// just the top one: with a PASTE/CROSS/comma join or an outer ON join wrapping the USING join, | ||
| /// the top node is not a USING JoinNode, yet `t` still participates in the nested USING join. | ||
| /// Walking the whole tree lets the qualified matcher find that nested key. | ||
| static void collectUsingJoinNodes( |
There was a problem hiding this comment.
Can't we infer correct type when walking tree in main flow of resolving identifier? We should reach anyway to get matcher/identifier resolved anyway, I suppose
There was a problem hiding this comment.
Yes, the type is already computed in the main flow. When t.col resolves as an identifier it goes through tryResolveIdentifierFromJoin -> convert_resolved_result_type_if_needed (IdentifierResolver.cpp:1285), which finds the USING key, checks participation by node-equality (isEqual, 1298-1299), retypes, and registers join_columns_with_changed_types (1324). That path already does everything correctly, participation check included.
The post-pass exists only because resolveQualifiedMatcher (QueryAnalyzer.cpp:1979) resolves just the qualifier t (2047) and then expands its columns straight from the storage snapshot / projection (2099-2111). Those nodes never pass through tryResolveIdentifierFromJoin, so the USING correction is never applied to them, hence the fix-up.
The current pass actually already delegates the type to the main flow per column: it resolves the explicit t.col via tryResolveIdentifier (1943-1954) and adopts its type. So the type itself is correct; the redundant part is the surrounding machinery, collectUsingJoinNodes + the name-match loop + the participation gate + the manual registration at 1963.
So your direction is the cleaner one: for the qualified matcher, resolve each matched t.col through the normal identifier flow and adopt the resolved node, dropping the tree walk + name match + gate + manual registration (the main flow registers the replacement itself).
One thing I'd validate before committing to it: matcher expansion is not 1:1 with per-identifier resolution today, because of ALIAS columns (taken from the table_expression_data column-node map, 1763), subcolumn/getSubcolumn cases, and the APPLY/EXCEPT/REPLACE transformers. Resolving every t.* column as an identifier is a broader behavioral change, so I'd re-run the original nested-USING crash cases (PASTE/CROSS/comma/ON) and the existing matcher tests for regressions.
Want me to pursue that refactor in this PR, or land the current targeted fix (proven both-directions, participation gate restored) and do the main-flow consolidation as a follow-up?
There was a problem hiding this comment.
do not introduce many adhoc solutions or bandaid
There was a problem hiding this comment.
Done in 900d8ef. The qualified matcher now resolves each t.col through the normal identifier flow and adopts its type; the ad-hoc post-pass (the collectUsingJoinNodes tree walk, the name-match loop, the participation gate and the manual join_columns_with_changed_types registration) is gone. Net -60 lines, and the unqualified matcher path is byte-identical to before.
The main flow does everything: tryResolveIdentifierFromJoin -> convert_resolved_result_type_if_needed follows only the joins t participates in, applies the supertype/join_use_nulls correction, and registers the change. No separate participation check is needed, because a USING key that t.col only matches by name in a join t does not take part in is never reached by the resolver.
EXPLAIN QUERY TREE for the (a JOIN b USING(id)) CROSS JOIN t_c / PREWHERE t_c.id = 5 case now shows the PREWHERE arg as COLUMN id, result_type: UInt64, source_id: 3 (= t_c.id), not a.id, so PREWHERE filters t_c correctly.
Both directions verified locally: with the type adoption disabled, 04329 fails (the anyHeavyOrNull(t2.*) aggregate aborts with the original Bad cast and the PREWHERE rows are wrong); with it, 04329 passes. The matcher/compat regression tests (02382, 02518, 03522, 03716, 03512, 02989, 03811, 04002, 00916, 00800, 03327) all pass.
The qualified matcher (`t.*`) over a JOIN USING key took the type from a dedicated post-pass that walked every USING join in the tree, matched a key by name, then applied an ad-hoc participation gate and registered the changed type by hand. That duplicated the resolver and matched a key only by name, so a key that `t.col` matched in a join `t` did not participate in (e.g. `(a JOIN b USING(id)) CROSS JOIN t`) could still be registered and later rewrite `t.col` to the unrelated column during PREWHERE replacement. Resolve each matched `t.col` through the normal identifier flow instead and adopt its type. That flow (IdentifierResolver::tryResolveIdentifierFromJoin) follows only the joins `t` participates in, wherever the USING join sits in the tree, applies the same type correction, and registers the change. The participation check, the tree walk and the manual registration are no longer needed. The unqualified matcher path is unchanged. Co-Authored-By: Claude Opus 4.8 <[email protected]>
The qualified matcher (`t.*`) resolves each expanded column through the identifier flow only to adopt the type a JOIN USING key gives it. The guard for that loop was `joins_count == 0`, which skips only single-table selects, so `t.*` over an ON, CROSS or PASTE join with no USING key still resolved every column once (O(number of columns) full join-tree resolution) even though no USING key could change a type there. `join_use_nulls` nullability for the matcher is applied later in resolveMatcher, not here. Track a USING-join count in the scope (set in the same join-tree walk that fills joins_count) and gate the per-column resolution on it, so the loop runs only when a USING key can actually retype a matched column. Co-Authored-By: Claude Opus 4.8 <[email protected]>
…uard The qualified-matcher guard added in the previous commit skips the per-column identifier resolution when scope.using_joins_count is 0, but that count is filled in initializeQueryJoinTreeNode from isUsingJoinExpression(), which is still false for a NATURAL JOIN at that point. A NATURAL JOIN synthesizes its USING key later, in resolveJoin, after the count has been taken. So SELECT anyHeavy(sipHash64(t1.*)) FROM t1 NATURAL RIGHT JOIN t2 SETTINGS join_use_nulls = 0 expanded t1.* with the storage (non-Nullable) type while explicit t1.id resolved through the synthesized USING key as Nullable, reintroducing the Bad cast this PR fixes. Increment using_joins_count where the NATURAL JOIN is converted to a USING join, after the empty-key CROSS-degrade early-return, so the guard sees the synthesized key. Extend 04329 with the NATURAL JOIN shape. Co-Authored-By: Claude Opus 4.8 <[email protected]>
…bdas The qualified-matcher USING guard read scope.using_joins_count, but the join tree it corrects against is taken from the nearest query scope. A matcher in a lambda body (arrayMap(x -> t.*, ...)) resolves through a fresh child scope whose counter is zero, so the guard skipped the correction and t.* kept the table type while the explicit reference resolved through the synthesized/real USING key as the supertype/Nullable. Aggregating over the matcher then aborted with a Bad cast. Read nearest_query_scope->using_joins_count so the check matches the scope whose join tree is inspected. getNearestQueryScope walks up to the enclosing query, so arbitrarily nested lambda scopes are covered. Non-lambda resolution is unchanged (nearest query scope is the current scope there).
CI finish ledger — ab40761Every failure below has an owner. This PR is an analyzer-only fix (
STID 2508-34af is a chronic trunk RefreshTask scheduling crash: 24 master hits across dozens of unrelated PRs in 30d. Tracked at Issue #106737. Session id: cron:our-pr-ci-monitor:20260624-173000 |
…d-under-paste-cross-1499-1a38
The qualified-matcher type mismatch surfaces as a Bad cast LOGICAL_ERROR (an exception), not a release-build server crash, so the regression test comments now say the aggregate throws the Bad cast exception rather than crashes, per ClickHouse convention. Co-Authored-By: Claude Opus 4.8 <[email protected]>
CI finish ledger — 0a17f69Every failure below has an owner. Both are chronic trunk failures unrelated to this PR's analyzer-only diff; each is owned by an open fixing PR of ours.
Neither failure touches Session id: cron:our-pr-ci-monitor:20260625-130000 |
…d-under-paste-cross-1499-1a38
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered by tests: 39/42 (92.86%) | Lost baseline coverage (was covered on master, now uncovered in this PR): 3 line(s) · Uncovered code |
Backport #108043 to 26.6: Fix Bad cast for a qualified asterisk over a JOIN USING key nested under a PASTE/CROSS join
…risk over a JOIN USING key nested under a PASTE/CROSS join
Follow-up within ClickHouse#108043. The qualified-matcher type-correction walks every JOIN USING node in the tree (collectUsingJoinNodes) so a nested USING key can be found below a PASTE/CROSS/comma join or an outer ON join. But it matched a key purely by column name, so for `(a JOIN b USING(id)) CROSS JOIN t` resolving `t.*` also matched the inner `USING(id)` even though `t` does not participate in it. The matched column then kept the correct (explicit-identifier) type, but `join_columns_with_changed_types[t.id] = a.id` was still registered against the unrelated key. That map drives PREWHERE replacement (ReplaceColumnsVisitor) and identifier equality (resolvedIdenfiersFromJoinAreEquals), so `t.* ... PREWHERE t.id = 1` was rewritten against `a.id` (wrong rows), and a later unqualified `id` could be treated as equal instead of ambiguous. Before retyping or registering, require that the matched column's source is one of the merged contributors of the USING key. Non-participating keys are skipped, and the matcher's column is left untouched. The original nested-USING crash fix is unchanged: when `t` genuinely participates, the key still type-corrects. Extends 04329_qualified_asterisk_join_using_nullable_key with the `(a JOIN b USING(id)) CROSS JOIN t` / comma-join shapes and PREWHERE filtering; the new cases give wrong PREWHERE results before this change. Co-Authored-By: Claude Opus 4.8 <[email protected]>
…fied-matcher-using-nested-under-paste-cross-1499-1a38 Fix Bad cast for a qualified asterisk over a JOIN USING key nested under a PASTE/CROSS join
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix a
Bad cast from type DB::ColumnNullable to DB::ColumnVector<...>crash (logical error) when a qualified asterisk (t.*) selects aJOIN USINGkey and that join is nested below aPASTE/CROSS/comma join or an outerONjoin, withjoin_use_nulls = 0.Description
Follow-up to #107129 (merged). That PR fixes the qualified-asterisk
JOIN USINGbad cast by typingt.*from the explicit referencet.col, but only when the top join node of the query scope is theUSINGjoin itself. When theUSINGjoin is nested below a non-USINGtop join, the top node is not aUSINGJoinNode, so the whole type-correction block was skipped: the qualified matcher kept its non-Nullable table-storage type while the planner produces aNullablecolumn (and the explicitt.colreference resolves toNullabletoo). An aggregate over the matcher then aborts with the bad cast.Deterministic repro on master (which already contains #107129):
Before this PR
sipHash64(t2.*)is typedUInt64whilesipHash64(t2.id, t2.b)(and the runtime column) isNullable(UInt64). The aggregate is built forUInt64andSingleValueDataFixed<UInt64>::setdoesassert_cast<ColumnVector<UInt64>>on aColumnNullable, aborting. The same failure reproduces withCROSS JOIN, a comma join, an outerONjoin, and deeper nesting.Fix: the
USINGjoin a qualified matcher participates in can live anywhere in the join tree, so for a qualified matcher everyUSINGjoin is examined (collectUsingJoinNodeswalksJoinNode/CrossJoinNode/ArrayJoinNode), not only the top node. The type is still taken from the explicit-identifier resolution, exactly as in #107129. The unqualified matcher (*) is unchanged: there the matched column is the mergedUSINGkey, which only applies at the top join.The regression test
04329_qualified_asterisk_join_using_nullable_keyis extended with thePASTE/CROSS/comma/ON-wrap shapes. It crashes the server without this change and passes with it.Found by the AST fuzzer. CIDB STID
1499-1a38, checkStress test (azure, amd_tsan), master commite4b9fe781ecacb6928fec6334f54a4710576f4df.Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=e4b9fe781ecacb6928fec6334f54a4710576f4df&name_0=MasterCI&name_1=Stress%20test%20%28azure%2C%20amd_tsan%29
Version info
26.7.1.134(included in26.7and later)26.6.2.97