Skip to content

Fix Bad cast crash for an explicit JOIN USING key with a Dynamic supertype - #107289

Merged
Avogar merged 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/fix-join-using-dynamic-key-aggregate-bad-cast
Jun 23, 2026
Merged

Avogar merged 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/fix-join-using-dynamic-key-aggregate-bad-cast

Conversation

@groeneai

Copy link
Copy Markdown
Collaborator

Related: #107129

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::ColumnDynamic to DB::ColumnNullable logical error (server crash in debug builds) when an explicit reference to a JOIN ... USING key whose common supertype is Dynamic is passed to an aggregate function, for example count(t.key) IGNORE NULLS with allow_dynamic_type_in_join_keys = 1.

Description

Found by the AST fuzzer (STID 3520-4a13).

An explicit reference t.key to a JOIN ... USING key adopts the merged key type (the common supertype of the joined keys) in IdentifierResolver::tryResolveIdentifierFromJoin. When the current column was Nullable from a previous OUTER JOIN but the merged supertype was not Nullable, the code re-derived the type from the current column rather than from the supertype, discarding the supertype's value type.

For a key whose supertype is Dynamic (for example Nullable(String) joined with a Dynamic key under allow_dynamic_type_in_join_keys = 1), this left the query tree typed Nullable(String) while the planner casts the key to Dynamic. An aggregate over the explicit reference (count(t.key) IGNORE NULLS) was then built with the Null combinator from the declared Nullable type, and its assert_cast<const ColumnNullable*> aborted on the runtime ColumnDynamic.

The fix keeps the merged key's value type and re-applies nullability from the current column, using makeNullableOrLowCardinalityNullableSafe so a supertype that cannot be wrapped in Nullable (such as Dynamic) is left as-is. This is the explicit-reference counterpart of the qualified-matcher fix in #107129 (QueryAnalyzer::updateMatchedColumnsFromJoinUsing), addressing the same "USING can cast to any supertype, not just nullability" class of bug.

Reproducer:

SET allow_dynamic_type_in_join_keys = 1;
CREATE TABLE t_nt (x Nullable(String)) ENGINE = Memory;
INSERT INTO t_nt VALUES ('id'), (NULL), ('1');
CREATE TABLE t_dyn (x Dynamic) ENGINE = Memory;
INSERT INTO t_dyn VALUES ('id'), (NULL), ('1');
SELECT count(t1.x) IGNORE NULLS FROM t_nt AS t1 INNER JOIN t_dyn USING (x);

…rtype

An explicit reference t.key to a JOIN USING key adopts the merged key type
(the common supertype of the joined keys) in
IdentifierResolver::tryResolveIdentifierFromJoin. When the current column was
Nullable from a previous OUTER JOIN but the merged supertype was not Nullable,
the code re-derived the type from the current column instead of the supertype,
discarding the supertype's value type.

For a key whose supertype is Dynamic (e.g. Nullable(String) joined with a
Dynamic key under allow_dynamic_type_in_join_keys = 1), this left the query
tree typed Nullable(String) while the planner casts the key to Dynamic. An
aggregate over the explicit reference (count(t.key) IGNORE NULLS) was then built
with the Null combinator from the declared Nullable type, and its
assert_cast<const ColumnNullable*> aborted on the runtime ColumnDynamic with
"Bad cast from type DB::ColumnDynamic to DB::ColumnNullable".

Keep the merged key's value type and re-apply nullability from the current
column. Use makeNullableOrLowCardinalityNullableSafe so a supertype that cannot
be wrapped in Nullable (Dynamic) is left as-is. This matches the qualified
matcher path in QueryAnalyzer::updateMatchedColumnsFromJoinUsing. Found by the
AST fuzzer.

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

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. On a debug build, with allow_dynamic_type_in_join_keys = 1: SELECT count(t1.x) IGNORE NULLS FROM t_nt AS t1 INNER JOIN t_dyn USING (x) where t_nt.x is Nullable(String) and t_dyn.x is Dynamic aborts the server every run with Bad cast from type DB::ColumnDynamic to DB::ColumnNullable.
b Root cause explained? The merged USING key supertype of Nullable(String) and Dynamic is Dynamic. IdentifierResolver::tryResolveIdentifierFromJoin (convert_resolved_result_type_if_needed) typed the explicit reference t1.x from the current column when it was Nullable but the supertype was not, discarding the supertype value type and leaving t1.x typed Nullable(String). The planner casts the key to the merged Dynamic and aliases it under x, so the runtime column is ColumnDynamic. count(...) IGNORE NULLS built the Null combinator (AggregateFunctionCountNotNullUnary) from the declared Nullable type; its assert_cast<const ColumnNullable*> aborts on the ColumnDynamic. Confirmed by EXPLAIN QUERY TREE (arg typed Nullable(String)) vs EXPLAIN header (runtime column Dynamic).
c Fix matches root cause? Yes. Keep the merged key's value type and re-apply nullability from the current column, instead of re-deriving the type from the current column. Safe variant leaves a type that cannot be inside Nullable (Dynamic) as-is. After the fix the query tree types t1.x as Dynamic, matching the runtime column.
d Test intent preserved / new tests added? New regression test 04335_join_using_dynamic_key_aggregate (the crash query, the explicit-vs-unqualified type equality, plain count, and LEFT JOIN). No existing test weakened.
e Both directions demonstrated? Yes. Without the fix (master debug binary): Bad cast LOGICAL_ERROR, server dies (test fails, server connection drops). With the fix on the same master: the test passes 20/20 with settings randomization and the server stays up.
f Fix is general, not a narrow patch? Yes. It corrects the type derivation for all value-type axes (the supertype width is preserved, not just nullability), mirroring the qualified-matcher fix in #107129. Verified no regression: 04329 (the #107129 test) passes; benign widening (UInt8/Int64, Decimal(9,2)/Decimal(18,4)), chained outer joins under join_use_nulls 0 and 1, and LowCardinality cases all produce correct types. Variant/sum/avg over a Dynamic key error cleanly (no crash).

Session id: cron:clickhouse-worker-slot-3:20260611-202000

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @vdimir @novikd — could you review this? It is the explicit-reference (IdentifierResolver::tryResolveIdentifierFromJoin) counterpart of #107129: an explicit t.key over a JOIN USING key whose common supertype is Dynamic was typed from the current column's value type instead of the supertype, so the query tree declared Nullable(String) while the planner produced Dynamic, and count(t.key) IGNORE NULLS aborted with a Bad cast. The fix keeps the supertype's value type and re-applies nullability (Safe variant for Dynamic), directly addressing the "USING can cast to any supertype" point from #107129.

@nikitamikhaylov nikitamikhaylov 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 [f7cdcc1]

Summary: ✅


AI Review

Summary

This PR fixes the explicit-reference JOIN ... USING path in IdentifierResolver::tryResolveIdentifierFromJoin so a resolved table-qualified key keeps the merged key supertype, then only re-applies nullable wrapping where the result type supports it. That matches the planner path that casts USING keys to the common type, and the added 04335_join_using_dynamic_key_aggregate regression covers the original Dynamic/Nullable type mismatch behind the ColumnDynamic to ColumnNullable LOGICAL_ERROR. I did not find a current-code correctness issue.

Missing context / blind spots
  • ⚠️ I could not run 04335_join_using_dynamic_key_aggregate locally because this checkout has no build directory or clickhouse binary. The PR CI report had no failed jobs at review time; a completed green PR run closes the runtime-validation gap.
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
@clickhouse-gh

clickhouse-gh Bot commented Jun 12, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.60% 84.60% +0.00%
Functions 92.30% 92.30% +0.00%
Branches 77.30% 77.30% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 5/5 (100.00%) | Lost baseline coverage: none · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI summary for HEAD f7cdcc167bb8: all praktika gating checks green (Finish Workflow + Mergeable Check passed); AI review already Approved on this commit. Only non-green context is external CH Inc sync (non-gating). No PR-caused failures. Ready for review.

Session: cron:our-pr-ci-monitor:20260612-033000

@rschu1ze

Copy link
Copy Markdown
Member

@Avogar Would you check this one please?

@Avogar Avogar self-assigned this Jun 22, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 22, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 38 queries analysed

This PR is a narrow analyzer correctness fix: it changes how a JOIN USING key's type is resolved when one side is Nullable from a prior OUTER JOIN and the merged supertype is a Dynamic type (using the safe nullability wrapper instead of throwing). ClickBench Q4 is a single-table aggregate with no joins, so this code path is never exercised by it. The flagged -16.17% on Q4 cannot plausibly come from this change and is downgraded to not-sure as run-to-run variance. No genuine performance impact is expected from this fix.

clickbench

⚠️ 1 inconclusive

Flagged queries (1 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 4 not_sure 266 223 -16.2% <0.0001 PR only fixes JOIN USING analyzer resolution for Dynamic keys; ClickBench Q4 has no joins. Off-path, treat as variance.

q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: c4cf9c28-a53a-4f99-bf7a-e346d52574f6
  • MIRAI run: 60220eab-ffb9-4f45-951f-1f0e41273674
  • PR check IDs:
    • clickbench_50260_1782140764
    • clickbench_50267_1782140764
    • clickbench_50277_1782140764
    • tpch_adapted_1_official_50283_1782140764
    • tpch_adapted_1_official_50297_1782140764
    • tpch_adapted_1_official_50311_1782140764

@Avogar
Avogar added this pull request to the merge queue Jun 23, 2026
Merged via the queue into ClickHouse:master with commit 2c83343 Jun 23, 2026
166 checks passed
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 23, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…using-dynamic-key-aggregate-bad-cast

Fix Bad cast crash for an explicit JOIN USING key with a Dynamic supertype
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.

5 participants