Skip to content

Fix Bad cast crash for qualified asterisk over a JOIN USING key - #107129

Merged
alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-aggregator-nullable-bad-cast-stid-3524-3f17
Jun 20, 2026
Merged

alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-aggregator-nullable-bad-cast-stid-3524-3f17

Conversation

@groeneai

@groeneai groeneai commented Jun 11, 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 Bad cast from type DB::IColumn const* to DB::ColumnNullable const* logical error / crash when a qualified asterisk (t.*) over a JOIN ... USING key is passed to an aggregate function and the other side of an outer JOIN has a Nullable key (with join_use_nulls = 0).

Description

Found by the AST fuzzer: AST fuzzer (amd_debug), STID 3524-3f17, report
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=104625&sha=79737e37a9f5cc4c525fbadef72b35ce8349c871&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%29

Reproducer:

CREATE TABLE j1 (id UInt64, value String) ENGINE = MergeTree ORDER BY tuple();
CREATE TABLE j2 (id UInt64, value String) ENGINE = MergeTree ORDER BY tuple();
CREATE TABLE j3 (id Nullable(UInt64), value String) ENGINE = MergeTree ORDER BY tuple() SETTINGS allow_nullable_key = 1;

SELECT anyHeavy(sipHash64(t2.*))
FROM j1 LEFT JOIN j2 AS t2 USING (id) RIGHT JOIN j3 USING (id)
SETTINGS join_use_nulls = 0;  -- aborts: Bad cast from type DB::IColumn const* to DB::ColumnNullable const*

Crash path: AggregateFunctionNullUnary<true, true>::addBatchSinglePlace
(AggregateFunctionNull.h:442) <- Aggregator::executeWithoutKeyImpl
(Aggregator.cpp) <- AggregatingTransform::consume.

Root cause is in the analyzer. When a qualified matcher (t2.*) matches a
JOIN USING key, updateMatchedColumnsFromJoinUsing overrode the matched
column's type with the merged USING-key type. That type is the common
supertype of the joined keys and, for an outer JOIN, can be Nullable
because the other side's key is natively Nullable. With join_use_nulls = 0
the data the planner produces for t2.id stays plain (non-Nullable), so the
query tree typed sipHash64(t2.*) as Nullable(UInt64) while the actual
column is plain UInt64. The aggregate function anyHeavy was therefore built
with the Null combinator (expecting a ColumnNullable argument) but received
the plain column at runtime, and assert_cast<const ColumnNullable *> aborted.
The existing code carried a TODO noting this was "not completely correct for
qualified matchers".

Fix: for a qualified matcher keep the USING-key supertype but preserve the
matched column's own nullability (do not declare a column Nullable that the
planner keeps plain). Unqualified matcher (*) behaviour, where the matched
column genuinely is the merged key, is unchanged. Added a stateless regression
test that crashes on master and passes with the fix, and that also checks the
supertype-coalescing and join_use_nulls = 1 cases still resolve as before.

Version info

  • Merged into: 26.6.1.1074

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. CREATE j1(id UInt64), j2(id UInt64), j3(id Nullable(UInt64)); SELECT anyHeavy(sipHash64(t2.*)) FROM j1 LEFT JOIN j2 AS t2 USING(id) RIGHT JOIN j3 USING(id) SETTINGS join_use_nulls=0 aborts 100% of the time on master.
b Root cause explained? Yes. The qualified matcher t2.* matched the outer RIGHT JOIN USING key id; updateMatchedColumnsFromJoinUsing overrode t2.id's type to the merged key type Nullable(UInt64) (the other side j3.id is natively Nullable), even though with join_use_nulls=0 the data stays plain. sipHash64(t2.*) was thus typed Nullable(UInt64), so anyHeavy was built with the Null combinator (AggregateFunctionNullUnary<true,true>, expects ColumnNullable) and then fed the plain runtime column → assert_cast<const ColumnNullable*> abort.
c Fix matches root cause? Yes. For a qualified matcher, keep the USING-key supertype but preserve the matched column's own nullability, so the query-tree type agrees with the column the planner produces. The code even carried a TODO flagging this exact gap for qualified matchers.
d Test intent preserved / new tests added? Yes. Added 04329_qualified_asterisk_join_using_nullable_key. No existing test weakened. The full join_use_nulls/analyzer_join/join_using/matcher stateless suite still passes (incl. 02722_matcher_join_use_nulls, which pins the supertype/nullable semantics).
e Both directions demonstrated? Yes. Without the fix the new test fails with the exact Bad cast crash (server died); with the fix it passes 10/10 under randomized settings.
f Fix is general, not a narrow patch? Yes. The fix is in the single shared helper updateMatchedColumnsFromJoinUsing, covering all qualified matchers (both call sites pass an explicit is_qualified_matcher flag). The sibling explicit-identifier path already preserves nullability via its matches_using_column guard; the matcher path was the only one missing it. It is fixed at the analyzer type-inference origin, not by guarding the assert_cast.

Session id: cron:clickhouse-worker-slot-1:20260611-010300

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @vdimir @novikd — could you review this? It fixes an analyzer type/data nullability mismatch: a qualified matcher (t.*) over a JOIN USING key took the merged key's nullability in updateMatchedColumnsFromJoinUsing, so with an outer JOIN + Nullable key + join_use_nulls=0 an aggregate built from the (wrongly) Nullable type crashed on the plain runtime column (assert_cast to ColumnNullable). The fix keeps the USING supertype but preserves the matched column's own nullability. @vdimir — this is the same helper you touched in #95808.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Jun 11, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 11, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [815cd53]

Summary: ✅


AI Review

Summary

This PR fixes analyzer type inference for qualified matchers such as t.* when they include a key from JOIN ... USING: the matched key now adopts the same type as an explicit t.col reference instead of blindly using the outer merged USING key type. The current implementation addresses the prior reviewer concern about non-nullability supertype changes, and the added stateless test covers the reported bad-cast exception, the opposite nullability direction, and value-type widening cases. I did not find any unresolved correctness, safety, or test-coverage issues that warrant inline comments.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 11, 2026
Comment thread src/Analyzer/Resolve/QueryAnalyzer.cpp Outdated
Comment on lines +1845 to +1853
/// For a qualified matcher keep the supertype but not the merged key's
/// nullability: take the matched column's own nullability instead, so we
/// don't declare Nullable a column the planner keeps plain (join_use_nulls=0,
/// non-nullable side of an outer JOIN).
if (is_qualified_matcher
&& isNullableOrLowCardinalityNullable(using_column_type)
&& !isNullableOrLowCardinalityNullable(matched_column_node_typed.getColumnType()))
using_column_type = removeNullableOrLowCardinalityNullable(using_column_type);

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.

Using can alter not only nullability, but cast to any supertype. So, we'd probably better off using original type from somewhere

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.

Good point, addressed. The matcher now keeps the merged USING key's value type but takes its nullability from the matched column's own type, instead of only stripping nullability. This is exactly how an explicit t.key is typed in IdentifierResolver::tryResolveIdentifierFromJoin (take the supertype, keep the referenced column's own nullability), so t.* and t.key agree.

On the non-nullability axes you mentioned: I checked width and decimal-scale supertypes (UInt8 vs Int64, Decimal(9,2) vs Decimal(18,4), String vs FixedString) across INNER/LEFT/RIGHT/FULL and both join_use_nulls values. There the qualified matcher already had to take the supertype, because the planner casts the value to that supertype regardless, so keeping the value type from the USING key is correct and toTypeName(t.*) = toTypeName(t.key) holds. The only axis where the matcher must diverge from the merged key is nullability under join_use_nulls=0 (the crash). Added regression coverage for the width and decimal cases plus an aggregate over a widened+nullable key.

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.

Generalized further. Instead of patching nullability onto the merged key, the qualified matcher now resolves the explicit identifier t.col via tryResolveIdentifier and adopts its result type. That is the authoritative type an explicit t.col reference gets (IdentifierResolver::tryResolveIdentifierFromJoin), correct along every axis the merged key can differ on (value-type widening and nullability), and it follows only the joins t participates in rather than the outer USING key.

The earlier nullability-from-own-type version was still wrong for a nested JOIN where a sibling USING table is Nullable: there t.col is genuinely Nullable but its own table type is not, so it under-declared the type. The AST fuzzer hit exactly that on the new test (anyHeavyOrNull(sipHash64(t2.*)) over (t1 Nullable LEFT JOIN t2) GLOBAL RIGHT JOIN t3 Nullable USING(id), the opposite-direction bad cast). Added that case to 04329; it now crashes without this change and passes with it.

@groeneai
groeneai force-pushed the fix-aggregator-nullable-bad-cast-stid-3524-3f17 branch from 22cf076 to 123f29e Compare June 11, 2026 11:31
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. On a debug master binary (no fix): SELECT count() FROM (SELECT anyHeavy(sipHash64(t2.*)) FROM t1 LEFT JOIN t2 USING (id) GLOBAL RIGHT JOIN t3 USING (id)) SETTINGS join_use_nulls=0, where t3.id is Nullable(UInt64), aborts every run with Bad cast from type DB::IColumn const* to DB::ColumnNullable const* (server dies).
b Root cause explained? The merged USING key id is the supertype of the keys, hence Nullable(UInt64). updateMatchedColumnsFromJoinUsing gave the qualified matcher t2.* that merged type. With join_use_nulls=0 the planner keeps t2.id plain UInt64, so the query tree declared Nullable while the runtime column is plain. The aggregate, wrapped with the Null combinator from the declared type, does assert_cast<const ColumnNullable*> on the plain column and aborts.
c Fix matches root cause? Yes. For a qualified matcher we keep the USING key's value type but take nullability from the matched column's own type, so the declared type equals what the planner produces. This mirrors IdentifierResolver::tryResolveIdentifierFromJoin (the explicit t.key path).
d Test intent preserved / new tests added? New regression test 04329_qualified_asterisk_join_using_nullable_key. Extended per review to also assert toTypeName(t.*) = toTypeName(t.key) across non-nullability supertypes (UInt8/Int64, Decimal(9,2)/Decimal(18,4)) and to aggregate over a widened+nullable USING key.
e Both directions demonstrated? Yes. Without fix (master debug binary): Bad cast LOGICAL_ERROR, server dies. With fix: query returns a result, server stays up; the test passes 20/20 with randomization.
f Fix is general, not a narrow patch? Yes. The fix handles both nullability directions (add and remove) and keeps the supertype for all other axes, matching the authoritative explicit-reference path. Verified the unqualified matcher (*) is unchanged and 10 existing analyzer JOIN/USING/matcher tests still pass.

Session id: cron:clickhouse-worker-slot-5:20260611-103500

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI failures on 123f29e — neither is caused by this PR

AST fuzzer (amd_tsan) — Logical error: 'BitNotImpl expected an integral type' (STID 2649-32ef). This is a pre-existing JIT-compilation bug on master, not a regression from this PR.

Proof:

  • The fuzzed query has no JOIN and no USING (... FROM numbers_mt(3) GROUP BY GROUPING SETS ...), so it never enters updateMatchedColumnsFromJoinUsing (the only function this PR changes; its body runs only under join_node->isUsingJoinExpression()).
  • EXPLAIN QUERY TREE for the fuzzed query is byte-identical between this branch and pure master.
  • Reproduced deterministically on a pure-master debug build (no fix) with SET group_by_use_nulls=1, compile_expressions=1, min_count_to_compile_expression=0. The server aborts with an identical stack. The real crash frame is BitCountImpl<double>::compile (src/Functions/bitCount.cpp:59), reached via FunctionUnaryArithmetic::compileImpl -> IFunction::compile -> CompileDAG::compile -> ExpressionJIT. It is a JIT codegen type mismatch for compilable bit functions, unrelated to the analyzer.

CIDB shows 1 hit in 180 days across all of master and every PR (the base rate for a unique fuzzer-mutated query). I will track and fix this trunk JIT bug separately; it is out of scope for this analyzer change.

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=107129&sha=123f29e39f974650ddc91f0dd9edc474ea399678&name_0=PR&name_1=AST%20fuzzer%20%28amd_tsan%29

Integration tests (amd_tsan, 5/6) — test_backup_restore_on_cluster/test_cancel_backup.py::test_cancel_restore and ::test_short_disconnection_doesnt_stop_restore. Chronically flaky across multiple unrelated PRs, 0 master failures in 30 days. Not related to this change.

cron:clickhouse-worker-slot-11:20260611-163700

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI summary, covered HEAD 123f29e3

CI fully finished (Finish Workflow pass, aggregator complete, >8h buffer). Both failures are non-PR-caused; the analyzer JOIN USING qualified-matcher fix is not implicated.

Check Failure Classification Disposition
AST fuzzer (amd_tsan) Logical error: BitNotImpl expected an integral type (STID 2649-32ef) Pre-existing trunk JIT bug (bitNot/bitCount compile under group_by_use_nulls + compile_expressions) NOT PR-caused. This PR touches only QueryAnalyzer JOIN USING matcher typing, unrelated to JIT bit-function codegen. Tracked + fixed by our separate PR #107263. The fuzzer surfaced it on this run by chance.
Integration tests (amd_tsan, 5/6) test_backup_restore_on_cluster/test_cancel_backup.py::test_cancel_restore + ::test_short_disconnection_doesnt_stop_restore Chronic flaky (test_cancel_restore 7 hits/3 PRs; test_short_disconnection 5 hits/5 PRs in 30d; latter is a cluster start/shutdown fixture error) NOT PR-caused (backup/restore-on-cluster is unrelated to an analyzer JOIN USING change). Tracked.

No PR-caused failures. The fix (Bad cast crash for a qualified asterisk over a JOIN USING key; regression test 04329) is unaffected.

@groeneai
groeneai force-pushed the fix-aggregator-nullable-bad-cast-stid-3524-3f17 branch from 123f29e to bd37298 Compare June 20, 2026 07:38
A qualified matcher (t.*) that matched a JOIN USING key adopted the merged
key's type in updateMatchedColumnsFromJoinUsing. That is wrong: the merged
key is the common type of all joined keys at the join where the USING clause
sits, while t.col only follows the joins t actually participates in. In a
nested JOIN the two differ. For

  SELECT anyHeavyOrNull(sipHash64(t2.*))
  FROM t1 LEFT JOIN t2 USING (id) GLOBAL RIGHT JOIN t3 USING (id)
  SETTINGS join_use_nulls = 0

with t1 and t3 keys Nullable and t2 key non-Nullable, the matched t2.id was
typed from the outer USING key. Depending on which side was Nullable the
declared type disagreed with the column the planner produces, and an aggregate
built from it aborted with a Bad cast in either direction (declared Nullable vs
runtime non-Nullable, or the reverse). The first direction was the original
report; the second was found by the AST fuzzer on the new test.

Resolve the explicit identifier t.col through tryResolveIdentifier and adopt
its result type, which is exactly what an explicit t.col reference resolves to
(IdentifierResolver::tryResolveIdentifierFromJoin). This is correct along every
axis the merged key can differ on (value-type widening and nullability), not
just nullability, and follows only the joins t participates in. The unqualified
matcher (*) still keeps the merged key type as-is, since there the column is the
merged key.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai
groeneai force-pushed the fix-aggregator-nullable-bad-cast-stid-3524-3f17 branch from bd37298 to 815cd53 Compare June 20, 2026 10:15
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. SELECT count() FROM (SELECT anyHeavyOrNull(sipHash64(t2.*)) FROM t_jn1[Nullable id] LEFT JOIN t_jn2[UInt64 id] AS t2 USING(id) GLOBAL RIGHT JOIN t_jn3[Nullable id] USING(id)) SETTINGS join_use_nulls=0 aborts the server every time on the prior head; the original anyHeavy repro (t_jn1 plain) is also deterministic.
b Root cause explained? A qualified matcher t2.* matching a JOIN USING key took the merged outer USING-key type. In a nested JOIN that key reflects the outer join's other side, not the joins t2 participates in, so for t2.id it diverged from the column the planner produces. With Nullable sibling USING tables the runtime column is Nullable but the matcher declared it plain (and the reverse with a plain sibling), so an anyHeavy/anyHeavyOrNull aggregate built from the declared type hit assert_cast and aborted with a Bad cast in either direction.
c Fix matches root cause? Yes. The qualified matcher now resolves the explicit identifier t.col and adopts its result type, which is exactly what t.col resolves to (IdentifierResolver::tryResolveIdentifierFromJoin), correct on both value-type and nullability axes and scoped to the joins t participates in. Not a bounds/tag band-aid.
e Both directions demonstrated? Yes. New 04329 case aborts (exit 134) on the prior flawed binary and returns 1 on the fixed binary; the original case stays correct (returns 1, t2.id resolves to UInt64 not the merged Nullable). 04329 output matches the reference; 8 analyzer JOIN/USING/matcher tests pass with no regression.
f Fix is general, not a narrow patch? Yes. It replaces ad-hoc nullability patching with the authoritative explicit-resolution path, covering all supertype axes (width, decimal, string, nullability) and both bad-cast directions, rather than guarding the symptom. Unqualified matcher (*) is unchanged since there the column is the merged key.
d Test intent preserved / new tests added? Yes. 04329 extended with the nested Nullable-base USING case plus a matcher-vs-explicit type-equality assert; existing assertions unchanged.

Session id: cron:clickhouse-worker-slot-2:20260620-085000

@clickhouse-gh

clickhouse-gh Bot commented Jun 20, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.20% 85.30% +0.10%
Functions 92.60% 92.60% +0.00%
Branches 77.50% 77.50% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 29/29 (100.00%) | Lost baseline coverage (was covered on master, now uncovered in this PR): 4 line(s) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI summary, covered HEAD 815cd53fe43

CI fully finished (Finish Workflow + Mergeable Check pass; 0 pending, 0 failing). All 6 AST fuzzer lanes pass, including amd_debug, targeted, old_compatibility where the generalized fix landed.

  • STID 1499-1b02 (Bad cast ColumnNullable -> ColumnVector<UInt64>, targeted old-analyzer) — fixed by this head's commit (explicit-identifier resolution for qualified matchers). Lane now green.
  • STID 2649-32ef (BitNotImpl/BitCountImpl JIT, amd_tsan) — pre-existing trunk JIT bug, not reachable from this PR's analyzer path (proven on pure master). Not blocking.
  • STID 0993-27f0 (Block structure mismatch in A stream) — chronic trunk UnionStep bug (4 master hits / 25 PRs in 30d). Not blocking.

@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.

The reasoning behind this is good.

@alexey-milovidov alexey-milovidov self-assigned this Jun 20, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jun 20, 2026
Merged via the queue into ClickHouse:master with commit c6512bb Jun 20, 2026
166 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 Jun 20, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

Hi — this looks like a backport candidate for 26.1, 26.2, 26.3, 26.4, 26.5. I ran this PR's own regression test against each branch's binary and the bug reproduces there (the fix isn't present yet).

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.

6 participants