Skip to content

Fix JIT crash on Nullable argument with non-nullable declared type - #107263

Closed
groeneai wants to merge 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-jit-nullable-arg-type-mismatch-2649-32ef
Closed

groeneai wants to merge 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-jit-nullable-arg-type-mismatch-2649-32ef

Conversation

@groeneai

Copy link
Copy Markdown
Collaborator

Related: #107129 (the AST fuzzer run on that PR surfaced this crash; the crash is a pre-existing trunk bug, not caused by #107129). No related open issue found.

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 (BitCountImpl compilation expected native integer or floating-point type) and server abort in debug builds when a JIT-compiled expression combined group_by_use_nulls with GROUPING SETS, causing a compilable function to receive a Nullable argument that its resolved signature treated as non-nullable.

Description

Found by the AST fuzzer (AST fuzzer (amd_tsan)) on PR #107129, STID 2649-32ef. 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 . Reproduces on pure master (no dependency on #107129).

Reproducer:

SET group_by_use_nulls = 1, compile_expressions = 1, min_count_to_compile_expression = 0;
SELECT (SELECT bitNot(bitCount(number)) / toInt128(-2147483649)
        QUALIFY equals(number, bitCount(bitCount(plus(-inf, number))) * materialize(2147483647)))
FROM numbers_mt(3) GROUP BY GROUPING SETS ((), (), (*)) QUALIFY 255;

Root cause: group_by_use_nulls + GROUPING SETS makes grouping keys Nullable, but the plus/bitCount/equals function_base nodes were resolved against the non-nullable types and never re-resolved, so a node ends up with a non-nullable declared argument/result type wired to a Nullable child. IFunction::compile's default-implementation-for-nulls path inspects the actual argument and emits a nullable LLVM value { double, i1 }, but CompileDAG::compile labels it with the stale non-nullable getResultType(). A downstream compiled function (bitCount) then matches the value to the scalar Float64 branch and BitCountImpl<double>::compile aborts on the struct type. The interpreter (compile_expressions = 0) re-derives nullability at runtime and returns the correct NULL row, so this is JIT-only.

Fix: in isCompilableFunction, decline to JIT-compile a function node when a non-skipped argument's declared (function_base) nullability disagrees with the actual child's nullability, deferring that node to the interpreter. This is the conservative isCompilableFunction bail pattern already used for other non-compilable cases and cannot change results (worst case: a rare malformed expression is not JIT-accelerated). Verified the guard is surgical: it fires only for the malformed nodes in the reproducer and not for normally-resolved nullable arguments (JIT output stays bit-identical to the interpreter across the reproducer and 11 variants; existing JIT tests 01072_nullable_jit, 01852_jit_if, 01855_jit_comparison_constant_result, 01457_compile_expressions_fuzzer, 00745_compile_scalar_subquery still pass).

Question for reviewers: the deeper fix would be in the analyzer, so a plus (etc.) function_base wired to a Nullable child is re-resolved to a nullable signature rather than left inconsistent, which would also make CompileDAG's type labelling honest. That has a much wider blast radius. Is the JIT-layer guard here the preferred fix, or would you rather pursue the analyzer-side re-resolution? Happy to follow up either way.

Regression test: tests/queries/0_stateless/04330_jit_nullable_arg_type_mismatch.sql (crashes on master, passes with this change).

group_by_use_nulls together with GROUPING SETS makes grouping keys
Nullable, but the function_base nodes (plus/bitCount/equals) were resolved
against the original non-nullable types and not re-resolved, leaving a node
whose declared argument/result type is non-nullable while its actual child
column is Nullable.

In the JIT path IFunction::compile's default-implementation-for-nulls
inspects the actual argument and emits a nullable LLVM value { T, i1 },
but CompileDAG::compile labels it with the stale non-nullable
getResultType(). A downstream compiled function (bitCount) then matches the
value to its scalar branch and BitCountImpl<double>::compile aborts with
LOGICAL_ERROR "BitCountImpl compilation expected native integer or
floating-point type" on the struct type. The interpreter re-derives
nullability at runtime and returns the correct NULL row, so the bug is
JIT-only.

Decline to JIT-compile a function node when a non-skipped argument's
declared nullability disagrees with the actual child's nullability, so the
node falls back to the interpreter. This follows the existing
isCompilableFunction bail pattern and cannot change query results.

Found by the AST fuzzer (amd_tsan) on PR ClickHouse#107129, STID 2649-32ef;
reproduces on pure master.

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. The query in the description aborts the server on every run with compile_expressions=1, min_count_to_compile_expression=0, group_by_use_nulls=1. Verified on pristine master (build 04446CE0, git f1fc3319).
b Root cause explained? Yes. group_by_use_nulls+GROUPING SETS makes a grouping key Nullable, but plus/bitCount/equals function_base nodes stay resolved for non-nullable types. IFunction::compile's default-impl-for-nulls emits a nullable {double,i1} value, while CompileDAG::compile labels it with the stale non-nullable getResultType(); the downstream compiled bitCount matches the scalar Float64 branch and BitCountImpl<double>::compile aborts on the struct. Confirmed by instrumenting CompileDAG::compile (plus arg#1 declType UInt64 vs child Nullable(UInt64); compiled value {double,i1} labeled Float64).
c Fix matches root cause? Yes. The fix declines to JIT-compile exactly the malformed nodes (declared-arg nullability != actual-child nullability) and defers them to the interpreter, which handles nullability correctly at runtime. Not a band-aid: the alternative deeper analyzer fix is raised explicitly in the PR description for reviewer preference.
d Test intent preserved / new tests added? New regression test 04330_jit_nullable_arg_type_mismatch.sql added; it crashes on master and passes with the fix. No existing test weakened.
e Both directions demonstrated? Yes, same tree via git stash: pristine ExpressionJIT (build 04446CE0) aborts; with the fix (build AE9F27BC) the test produces the reference output and the server stays up.
f Fix is general, not a narrow patch? Yes. The guard is on the generic declared-vs-actual nullability mismatch in isCompilableFunction, so it covers every compilable function (not just bitCount). It is surgical: JIT output stays bit-identical to the interpreter across the reproducer and 11 variants, 0 spurious declines on normally-resolved nullable arguments, and 01072_nullable_jit/01852_jit_if/01855_jit_comparison_constant_result/01457_compile_expressions_fuzzer/00745_compile_scalar_subquery still pass. The fix targets the JIT bookkeeping inconsistency rather than guarding the bitCount symptom site.

Session id: cron:clickhouse-worker-slot-0:20260611-165800

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @novikd @KochetovNicolai — could you review this? It fixes a debug-build server abort (BitCountImpl compilation expected native integer or floating-point type) when group_by_use_nulls+GROUPING SETS leaves a compilable function's function_base resolved for non-nullable args while wired to a Nullable child: the JIT then emits a {T,i1} value that CompileDAG mislabels as non-nullable. The fix makes isCompilableFunction decline such nodes to the interpreter. There's a design question in the description about whether you'd prefer the deeper analyzer-side re-resolution instead.

@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 [7459d26]

Summary: ✅


AI Review

Summary

This PR prevents ExpressionJIT from compiling an ActionsDAG function node when the resolved function_base argument nullability no longer matches the actual child node nullability, so the inconsistent node is evaluated by the interpreter. The fix is narrow, follows the existing JIT bail-out pattern, and the added stateless regression covers the group_by_use_nulls plus GROUPING SETS path that produced the stale type.

Missing context / blind spots
  • ⚠️ I could not run the new stateless test locally because this checkout has no build directory. At review time, GitHub still had Fast test, Build (arm_tidy), and Bugfix validation (functional tests) in progress; the available PR report showed no failures and Style check passed.
Final Verdict

Status: ✅ Approve

No code-review changes requested; wait for pending CI to finish before merge.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 11, 2026
The CI old-analyzer stateless job ran this regression test with
enable_analyzer=0, where the correlated scalar subquery / QUALIFY /
GROUPING SETS query cannot be resolved at all (Code 47 UNKNOWN_IDENTIFIER,
"Missing columns: 'number'"). The JIT crash being regressed only exists in
the new analyzer's group_by_use_nulls nullable-rewrite path, so the test
must always run there. Add SET enable_analyzer = 1; which overrides the
runner's session-level injection.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@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.40% 92.40% +0.00%
Branches 77.30% 77.30% +0.00%

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

Full report · Diff report

@Algunenano Algunenano self-assigned this Jun 12, 2026

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

Are you sure we are fixing this in the right place? If the function declared a type and then passed a different one that's a bug that needs to be fixed in the function, not in the callee.

@groeneai

Copy link
Copy Markdown
Collaborator Author

@Algunenano you're right, thanks. This is a query-tree consistency bug, not a JIT issue.

With group_by_use_nulls=1 + GROUPING SETS, the grouping key becomes Nullable, but the consuming function's IFunctionBase keeps its non-nullable signature: an instrumented dump shows plus resolved as (Float64, UInt64) -> Float64 while its second argument child is Nullable(UInt64). The interpreter tolerates the mismatch via default null handling, but the JIT bakes the declared type and aborts. So the function declared one type and is fed another, exactly as you say.

I'll move the fix to where that inconsistency is produced (re-resolve the function so its declared argument/result types match the Nullable argument) and drop the JIT-side guard. There is already precedent for this concern in the analyzer (the aggregate-function handling around pushExpressionNode in QueryAnalyzer that avoids feeding a Nullable group-by key to a function resolved for the non-nullable input). Will update the PR.

@groeneai

Copy link
Copy Markdown
Collaborator Author

@Algunenano I traced where the inconsistent type is introduced. It is the planner (decorrelation), not the analyzer, and the subquery is actually consistent in isolation.

Evidence for SELECT (SELECT bitCount(plus(1.0, number))) FROM numbers(3) GROUP BY GROUPING SETS ((), (number)) with group_by_use_nulls=1:

  • EXPLAIN QUERY TREE: the correlated number in the subquery is UInt64, and plus/bitCount are resolved for non-nullable args. The subquery tree is internally consistent, so the function is built correctly there.
  • The non-correlated form SELECT bitCount(plus(1.0, number)) ... GROUP BY GROUPING SETS ((), (number)) already works: the analyzer wraps number to Nullable(UInt64) and rebuilds plus -> Nullable(Float64), bitCount -> Nullable(UInt8).
  • EXPLAIN actions of the final plan for the correlated form: after decorrelation the subquery input number becomes Nullable(UInt64) (fed from the outer Nullable group-by key via the decorrelation join), but plus stays Float64 and bitCount stays UInt8. Decorrelation changed the argument type without rebuilding the consuming functions.

There is already a rebuild for exactly this group_by_use_nulls mismatch in PlannerActionsVisitorImpl::visitFunction, but it runs during initial DAG construction, before decorrelation, so it does not catch this.

Two ways to fix the function:

  1. Planner: after decorrelation reconciles the correlated input type, rebuild any function node whose child types no longer match its function_base argument types. Extends the existing visitFunction rebuild to the post-decorrelation DAG. Surgical, correlated-subquery only.
  2. Analyzer: when a correlated reference resolves to an outer group-by key that becomes Nullable, wrap it to Nullable at resolution time so the subquery functions are rebuilt there. The nullable-key scope walk currently stops at the subquery QUERY boundary. Makes the tree honest but touches the shared resolve path with broader blast radius.

I lean to (1). Which do you prefer before I implement?

@Algunenano

Copy link
Copy Markdown
Member

@groeneai Please investigate if this is reported and open an issue if it's not, then involve the experts in the analyzer/planner. They should be the ones deciding how to address this better. And let's close this PR since it turned out to be the wrong way forward

@groeneai

Copy link
Copy Markdown
Collaborator Author

@Algunenano you're right, this is the wrong layer. Closing it.

It is already reported: #106377, assigned to the analyzer/planner experts, with @ novikd's diagnosis and a candidate fix in #102597. Same decorrelation type-mismatch you pointed at: decorrelation injects Nullable into the correlated subquery input, but the consuming function_base nodes keep their non-nullable declared types. Our case is just a worse downstream symptom (the mismatch reaches JIT codegen and aborts in BitCountImpl::compile instead of the ActionsDAG assertion).

I added our fuzzer reproducer and EXPLAIN traces to #106377 so the experts have the full picture. Closing this PR in favor of that issue.

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants