Skip to content

Honour the declared result type in FunctionIn - #113750

Closed
groeneai wants to merge 4 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-functionin-honour-declared-result-type
Closed

groeneai wants to merge 4 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-functionin-honour-declared-result-type

Conversation

@groeneai

@groeneai groeneai commented Aug 7, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #109455
Related: #110551

Closes: #114254

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 LOGICAL_ERROR: Unexpected return type from globalIn. Expected Nullable(UInt8). Got UInt8 when a GLOBAL IN over a table is used as a GROUPING SETS key with group_by_use_nulls = 1. in and its seven sibling functions now return a column matching the result type they are given.

Description

Reported on #109455 as a Stress test (arm_debug) failure unrelated to that PR. The failing query was an AST-fuzzer mutation, but the defect is reachable from plain SQL.

Root cause. group_by_use_nulls promotes a grouping key's declared type to Nullable(UInt8) via FunctionNode::getResultType (src/Analyzer/FunctionNode.h:193), and the DAG node stores it; FunctionIn declares plain UInt8 (src/Functions/in.cpp:58) and discarded the result_type handed to it. Neither framework wrapper covers this: the constant one is disabled (:66) and the Nullable one reacts only to argument nullability. With GLOBAL IN over a table the set is still unfilled while the header is computed, so the dry-run path returned a bare ColumnUInt8 where Nullable(UInt8) was declared, and columnMatchesType failed at src/Interpreters/ActionsDAG.cpp:1341.

Change. result_type is threaded into the private executeImpl and the produced column is reconciled against it once, at a chokepoint above all seven returns. Argument-driven nullability is resolved before executeImpl is reached (src/Functions/IFunction.cpp:215, :232), so a Nullable here can only come from the promotion above and no row can be NULL. All in variants share this class, and behaviour is unchanged whenever the declared type is not Nullable. FunctionsLogical.cpp:786 reads the same predicate.

Validation. New stateless test whose first arm is the reported query: six witness arms and four controls, each asserting a value and a type. Every witness aborts an unpatched debug server and passes with the change; the controls read identically on both. 100/100 runs pass (50 randomized, 50 without) and a 197-test slice shows 0 regressions. A release build gives a query error, not an abort. The test pins enable_analyzer = 1, the analyzer whose promotion it asserts: the old analyzer returns early for GROUPING SETS (src/Interpreters/ExpressionAnalyzer.cpp:1597), so UInt8 is correct there, and an unpatched server still aborts on the first witness arm with the pin in place.

With group_by_use_nulls = 1, a GROUPING SETS key's declared type is promoted to
Nullable(UInt8) by FunctionNode::getResultType (src/Analyzer/FunctionNode.h:193)
and the ActionsDAG node stores that type. FunctionIn declares plain UInt8
(src/Functions/in.cpp:58), and its executeImpl discarded the result_type argument
entirely by forwarding to a private overload that had no such parameter. The
framework's own reconciliation wrappers do not cover this: the constant wrapper
is disabled (:66), and the Nullable wrapper only ever reacts to nullability in
the arguments, which this promotion is not.

For GLOBAL IN over a table the set is a FutureSet still unfilled while the
header is computed, so future_set->get() returns null and the dry-run path
returned a bare ColumnUInt8 where Nullable(UInt8) was declared. columnMatchesType
compares type indexes first (src/Columns/validateColumnType.cpp:70-71): a bare
ColumnUInt8 reports TypeIndex::UInt8 while DataTypeNullable reports
TypeIndex::Nullable, so the check in executeActionForPartialResult
(src/Interpreters/ActionsDAG.cpp:1341) threw LOGICAL_ERROR, aborting
debug and sanitizer builds:

  Unexpected return type from globalIn. Expected Nullable(UInt8). Got UInt8

Thread result_type into the private executeImpl and reconcile the produced
column against it once, at the single return chokepoint. That covers all seven
exits, including the two returning a ColumnConst and the Set::execute main path
which returns a bare ColumnUInt8 (src/Interpreters/Set.cpp:416). makeNullable
preserves constness and is a no-op on an already-nullable column. Nullability
driven by the arguments is resolved before executeImpl is reached, either by
returning a NULL constant outright or by passing removeNullable(result_type)
down and wrapping the result afterwards (src/Functions/IFunction.cpp:215, :232),
so a Nullable type arriving here can only come from the promotion above and no
row of the result can be NULL. Every variant registered by REGISTER_FUNCTION(In)
shares this class, so globalNotIn, globalNullIn and globalNotNullIn are fixed
with it. Behaviour is unchanged whenever the declared type is not Nullable,
which is every ordinary query.

This follows the established convention: FunctionAnyArityLogical reads
result_type->isNullable() for exactly this promotion
(src/Functions/FunctionsLogical.cpp:786), which is why an AND of comparisons
works as a GROUPING SETS key under group_by_use_nulls. Fixing the assertion
instead would leave the identical check in ExpressionActions::execute
(src/Interpreters/ExpressionActions.cpp:694) and would mask genuine
declared-versus-actual mismatches in every other function.

Instrumenting the six exits reachable for these registrations (the ignore_set
exit is not reachable without the IgnoreSet variants) shows the dry-run "set not
ready" exit is the only one reached with a Nullable declared type: 6 of 195
invocations across 13 query shapes. The chokepoint placement therefore rests on
the Set::execute return type above rather than on a currently reachable second
exit.

Release builds surface this as a query error rather than an abort. The abort is
gated on debug_or_sanitizer_build or the abort_on_logical_error server setting
(src/Common/Exception.cpp:112).

Reported on ClickHouse#109455, where the
failing query was an AST-fuzzer mutation. It is reachable from ordinary SQL, and
the new test's first arm is that query.
@groeneai

groeneai commented Aug 7, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (click to expand)

Three review rounds, each an independent cold review plus a separate reviewing model, adjudicated
against the recorded evidence. Every finding concerned published text; the code in
src/Functions/in.cpp was reviewed three times and left unchanged.

# Finding Verdict
❌ The commit message cited validateColumnType.cpp:83 as the check that rejected the pre-fix column. That branch is entered only when the column already is a ColumnNullable, which is the post-fix state; a bare ColumnUInt8 is rejected 13 lines earlier by the type-index compare at :70-71, because DataTypeNullable does not override getColumnType and so reports TypeIndex::Nullable against the column's TypeIndex::UInt8. AGREE — citation corrected to :70-71.
❌ The PR body said FunctionIn "opts out of the framework's constant and Nullable wrappers (:66)". :66 is useDefaultImplementationForConstants only, and useDefaultImplementationForNulls() returns null_is_skipped, which is true for in, globalIn, notIn and globalNotIn. AGREE — reworded: the constant wrapper is disabled, and the Nullable wrapper only reacts to argument nullability.
❌ The PR body said "IN never evaluates to NULL". It can: 03814_in_function_strict_conversion.reference returns \N for SELECT NULL IN 1 and five sibling shapes. AGREE — replaced with the reason that actually holds: argument-driven nullability is resolved before executeImpl is reached, so a Nullable result type arriving there can only come from the group_by_use_nulls promotion, and no row of the result can be NULL. The conclusion (an all-zero null map is correct) is unchanged.
⚠️ An earlier draft claimed the empty-set arm witnesses a second, ColumnConst exit. Instrumenting every exit over 195 invocations shows the dry-run "set not ready" exit is the only one ever reached with a Nullable declared type, so the arm witnesses the defect but not that exit. AGREE — the claim was removed. The chokepoint placement rests on Set::execute returning a bare ColumnUInt8, not on a second reachable exit.
⚠️ Two internal exit counts disagreed inside one message ("seven" versus "six"). There are exactly seven returns; six are reachable for these registrations, the ignore_set exit needing the IgnoreSet variants. AGREE — both figures now state which they mean.
💡 The Related: relationship lines sat inside the template's HTML comment, so a reader of the rendered description could not see them. AGREE — moved outside the comment.
💡 A row claimed the reconciliation runs on every return path "including the error exits". It sits above the inner function, so the four throw sites bypass it, correctly. AGREE — reworded.
❌ The description said the regression run covered a "195-test slice". 195 is the number of names passed to the runner, but clickhouse-test treats its positionals as substring filters, so two further tests matched (02293_grouping_function also selecting 02293_grouping_function_group_by, and 02500_remove_redundant_distinct also selecting 02500_remove_redundant_distinct_analyzer). The runner's own verdict lines read 197, and the arm's 187 OK plus 10 FAIL sums to 197. AGREE — corrected to 197. The result itself is unchanged and was re-derived as sets: no failure appears in only one arm, the ten shared failures are identical, and no failure reason changed.
💡 The test's header comment says the mismatch aborts the server without qualification. The abort is gated on a debug or sanitizer build, or on abort_on_logical_error; Fast test is neither, so there the pre-fix failure is a query exception. AGREE, noted rather than changed: the test reddens either way, and every reader-facing text already scopes this (the description says "aborts an unpatched debug server" and "a release build gives a query error", and the commit message devotes a paragraph to it).
💡 PR 100127 inserts a canThrowImpl override into src/Functions/in.cpp immediately above this change's second hunk. Noted, no action: it touches none of the same lines or symbols, so whichever lands second resolves one adjacent insertion. Adding a shim for an unmerged pull request would ship dead code.

Also verified, no change needed: all seven returns are covered by the single chokepoint, including
both that build a ColumnConst (makeNullable recurses into the const's data column, so constness
is preserved); the reconciliation is inert for a non-Nullable declared type and a no-op for an
already-nullable column; LowCardinality(Nullable(UInt8)) is correctly untouched because
DataTypeLowCardinality::isNullable() is false and the framework strips the wrapper before calling
the function, so makeNullable would have been wrong there and is not reached; no downstream
consumer assumes a bare UInt8, since FilterDescription unwraps ColumnNullable and
ConstantFilterDescription's always-true/false detection survives an all-zero null map, which is
the property the useDefaultImplementationForConstants comment exists to protect; both
columnMatchesType call sites are satisfied, which is why fixing the function beats guarding the
assertion; group_by_use_nulls is not among the runner's randomized settings, so no opt-out tag is
owed; and the new test's ten arms are positionally aligned with the reference, each projecting the
raw expression as well as its type name so that constant folding of the type name alone cannot
satisfy an arm.

@groeneai

groeneai commented Aug 7, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. CREATE TABLE t (x UInt8) ENGINE = MergeTree ORDER BY x; INSERT INTO t VALUES (1); then SELECT 1 GLOBAL IN (t) AS s FROM remote('127.0.0.1', system, one) GROUP BY GROUPING SETS ((1 GLOBAL IN (t))) SETTINGS group_by_use_nulls = 1; aborts a debug server with the verbatim reported message. All six witness arms of the new test abort an unpatched server; no fuzzer, no remoteSecure, no external table. A table identifier on the right of GLOBAL IN is load-bearing: a subquery set is built before the main query, so it never reaches the failing path (measured, and shipped as a control).
b Root cause explained? group_by_use_nulls promotes a grouping key's declared type to Nullable(UInt8) (src/Analyzer/FunctionNode.h:193), the DAG node stores it, but FunctionIn declares plain UInt8 (src/Functions/in.cpp:58) and discarded the result_type it was handed. The framework's own reconciliation wrappers do not cover this: the constant wrapper is disabled (:66), and the Nullable wrapper only ever reacts to nullability in the arguments, which this promotion is not. With GLOBAL IN the set is a FutureSet unfilled at header-computation time, so the dry-run path returned a bare ColumnUInt8, columnMatchesType returned false on its type-index compare (src/Columns/validateColumnType.cpp:70-71: ColumnUInt8 reports TypeIndex::UInt8 while DataTypeNullable reports TypeIndex::Nullable) and src/Interpreters/ActionsDAG.cpp:1341 threw. I instrumented the six exits reachable for these registrations (the ignore_set exit needs the IgnoreSet variants) and paired each invocation with its exit: the dry-run "set not ready" exit is the only one ever reached with a Nullable declared type (6 of 195 invocations across 13 shapes).
c Fix matches root cause? Yes. The function now honours the type it is given, at the layer that owns the contract. No widened bound, no test tag, no guard at the assertion. Fixing the assertion instead would leave the identical check at src/Interpreters/ExpressionActions.cpp:694 and would mask genuine declared-vs-actual mismatches in every other function.
d Test intent preserved / new tests added? No existing test modified. New stateless test 04812_group_by_use_nulls_grouping_sets_global_in with six witness arms and four controls, each asserting a value and a type rather than merely "did not abort".
e Both directions demonstrated? Yes, on Build-ID-asserted binaries with a fresh data dir per arm. Pristine base d01d55e9d883d07d: arms 1-6 abort, each message naming its own registered function; controls 7-10 pass. Fix 072c5e5331e267ad: all ten pass. Mutant M1 (reconciliation removed, 16cb9388c65054aa) reddens the shipped test with the verbatim target message. After the mutants the shipping Build ID returned byte-exactly, which is what proves they ran on genuinely different binaries.
f Fix is general across code paths? The reconciliation sits at the single return chokepoint, so all seven exits are covered including the two returning a ColumnConst and the Set::execute main path, which returns a bare ColumnUInt8 (src/Interpreters/Set.cpp:416). Every variant registered by REGISTER_FUNCTION(In) shares this one class -- the eight base names and their IgnoreSet counterparts, sixteen in total, since registerFunctionsInImpl is invoked once for each; four are measured as distinct carriers. A second mutant restricting the reconciliation to the dry-run exit alone still passes the test, and the exit measurement in (b) explains why: no fixture I could build reaches another exit with a Nullable declared type. I kept the chokepoint anyway on the by-construction argument above rather than narrowing to one exit.
g Fix generalizes across inputs? Measured: LowCardinality left argument (witness), a literal set whose declared type is LowCardinality(Nullable(UInt8)) (control, wrapper preserved untouched), empty and populated sets, the negative (NOT) and null_is_skipped (nullIn) variants, temporary and plain tables, subquery sets. executeImpl never receives a LowCardinality result type: IExecutableFunction::executeWithoutSparseColumns strips it and recurses with the dictionary type, verified over 33 invocations plus a positive control showing the probe can observe a wrapper. So result_type->isNullable() is the right predicate and makeNullable is sufficient.
h Backward compatible? Yes. No setting default change, no serialization format change, no SettingsChangesHistory.cpp entry owed. Behaviour is bit-identical whenever the declared type is not Nullable, which the two control arms assert and the 189 non-Nullable invocations in the exit measurement confirm.
i Invariants and contracts preserved? Invariant: the column FunctionIn returns matches the result_type it was handed. The reconciliation runs on every one of the seven return paths, including the early-return exits; the four throw sites bypass it, correctly, since there is no column to reconcile. makeNullable preserves constness exactly, so it cannot introduce the updateHeader-vs-execute constness divergence the comment at src/Functions/in.cpp:61-66 documents; negation is applied before the reconciliation, and an all-zero null map preserves every value. Nullability driven by the arguments is resolved before executeImpl is reached -- either by returning a NULL constant outright or by passing removeNullable(result_type) down and wrapping the result afterwards (src/Functions/IFunction.cpp:215, :232) -- so a Nullable type arriving here can only come from the promotion above, no row of the result can be NULL, and no null-map semantics change.

Session id: cron:clickhouse-review-slot-49:20260806-235800

@groeneai

groeneai commented Aug 7, 2026

Copy link
Copy Markdown
Collaborator Author

cc @Algunenano @Avogar, could you review this? FunctionIn declares plain UInt8 but discarded the result_type it was handed, so when group_by_use_nulls promotes a GROUPING SETS key to Nullable(UInt8) the function still returned a bare ColumnUInt8 and the declared-versus-actual check threw a logical error; it now reconciles the produced column against the declared type at its single return chokepoint.

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

clickhouse-gh Bot commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [3923f59]

Summary: ❌

job_name test_name status info comment
Stress test (arm_asan_ubsan, s3) FAIL
Logical error: Sizes of nested column and null map of Nullable column are not equal after deserialization (null map size = A, nested column size = B) (STID: 6726-6444) FAIL cidb

AI Review

Summary

This PR fixes FunctionIn so it honors a nullable declared result type during dry-run and normal execution, removing the LOGICAL_ERROR triggered by GLOBAL IN used as a GROUPING SETS key with group_by_use_nulls = 1. I found no remaining correctness or test-coverage issues in the current patch: the nullable reconciliation sits at the shared return chokepoint, the stateless test now declares the analyzer precondition explicitly, and the expanded PR CI is green.

Final Verdict

✅ No findings.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.60% 86.60% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.80% 78.80% +0.00%

Changed lines: Changed C/C++ lines covered: 9/9 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 7, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

No arm_release build profile data for commit 3923f59 - the build was skipped, reused from cache, or predates profile upload.

The `low cardinality left` arm of
04812_group_by_use_nulls_grouping_sets_global_in failed in
`Stateless tests (amd_asan_ubsan, distributed plan, parallel)` with

    Code: 117. DB::Exception: Deserialized function globalIn has invalid type.
    Expected LowCardinality(UInt8), deserialized UInt8. (INCORRECT_DATA)

thrown by the plan consistency check in `ActionsDAG::deserialize`. The
mismatch is `LowCardinality(UInt8)` against `UInt8`, with no `Nullable` on
either side, so it is not the mismatch this test covers.

It is issue ClickHouse#112028, an unrelated pre-existing defect: a `LowCardinality`
argument to `IN` loses that wrapper when the query plan is serialized to a
remote replica. Measured on an unpatched server, the same error appears with
`group_by_use_nulls` absent and with a plain local `IN`, and it needs a
`LowCardinality` left argument, a non-local replica and
`serialize_query_plan = 1`. Neither `GLOBAL`, `GROUPING SETS` nor
`group_by_use_nulls` takes part in it. Removing any one of those three
ingredients makes the query return `UInt8` and `1`.

Pinning `serialize_query_plan = 0` on that single arm therefore removes only
the unrelated interference. The arm keeps its own coverage: on an unpatched
server it still aborts with `Unexpected return type from globalIn. Expected
Nullable(UInt8). Got UInt8`, and it passes with the fix. The other nine arms
are unchanged and run with plan serialization active, including the five that
reproduce the reported failure. Thirty stateless tests already pin the
setting the same way, for example 03400_explain_distributed_bug.sql and
03303_distributed_explain.sql.
@groeneai

groeneai commented Aug 7, 2026

Copy link
Copy Markdown
Collaborator Author

CI fix pushed: 400b6afa8b390d5

Stateless tests (amd_asan_ubsan, distributed plan, parallel) failed on
7d87a0d53e73 in this PR's own new test:

Code: 117. DB::Exception: Deserialized function globalIn has invalid type.
Expected LowCardinality(UInt8), deserialized UInt8. (INCORRECT_DATA)

That mismatch is LowCardinality(UInt8) against UInt8, with no Nullable on either
side, so it is not the mismatch this PR fixes. It is issue #112028, an unrelated
pre-existing defect where a LowCardinality argument to IN loses that wrapper when the
query plan is serialized to a remote replica.

I measured it on the unpatched server (which is this PR reverted, so it is the negative
control): the same error appears with group_by_use_nulls absent entirely, and with a
plain local IN. It needs a LowCardinality left argument, a non-local replica and
serialize_query_plan = 1; removing any one of the three makes the query return UInt8
and 1. Neither GLOBAL, GROUPING SETS nor group_by_use_nulls participates.
Neighbouring functions round-trip that wrapper correctly on the same server
(+, =, lower, and IN with a literal set), so it is specific to IN over a set
that is built during distributed execution.

The push pins serialize_query_plan = 0 on the single low cardinality left arm, which
removes only that interference. The arm keeps its own coverage: on the unpatched server
it still aborts with Unexpected return type from globalIn. Expected Nullable(UInt8). Got UInt8, and it passes here. The nine other arms are untouched and still run with plan
serialization active, including the five that reproduce the originally reported failure.

Verification on a local debug build, per-arm build id asserted against readelf -n:

configuration unpatched this PR
10 arms, prefer_localhost_replica = 0, serialize_query_plan = 1 6 arms abort, 4 controls pass all 10 pass
the pinned arm alone aborts passes
the test at --prefer_localhost_replica 0 5 of 5 fail without the pin 20 of 20 pass
the test, default randomization - 50 of 50 and 50 of 50 pass

CI reported 20 of 20 failures under the drawn settings with
Culprit settings: --prefer_localhost_replica 0, so that fourth row is the same
configuration in both directions.

Thirty stateless tests already pin this setting the same way, for example
03400_explain_distributed_bug.sql and 03303_distributed_explain.sql.
Source is unchanged in this push: the diff is three added and one removed line, all in
the test.

Session id: cron:clickhouse-maint-slot-15:20260807-105600

@groeneai

groeneai commented Aug 7, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 400b6af

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (amd_llvm_coverage, old analyzer, s3 storage, DBReplicated, WasmEdge, parallel, 2/3) / 04812_group_by_use_nulls_grouping_sets_global_in PR-caused. My own new test, failing 3 of 3 reruns on the old-analyzer lane only: every arm reads UInt8 where the reference expects Nullable(UInt8). The same test is OK on 16 other check names on this head, including 200 flaky-check runs and both Fast test variants, so the fix does not reach the old-analyzer path (or the test needs to declare it) PR-caused, fixed in this PR
Stress test (amd_tsan) / Logical error: '(isConst() || isSparse() || ...) ? getDataType() == rhs.getDataType() : typeid(*this) == typeid(rhs)' (STID 2508-30f6) pre-existing trunk assert in HashJoin::buildAdditionalFilter via IColumn::assertTypeEquality; 97 rows over 84 distinct PRs and 10 master builds in 60 days, so not this PR's diff #113534 (external, open)
Stress test (arm_debug) / Test script failed stress-harness abort, not a product failure: install_thread_pool_fault_injection (ci/jobs/scripts/stress/stress.py) fails closed when its system.server_settings verification read trips the client's 15 s receive_timeout, exit status 159. Frame-keyed, not name-keyed: the generic Test script failed bucket spans 11 stress flavours #113248 (external, open)
Build (arm_release) / Post Hooks non-gating build-profile telemetry upload rejected by the shared CI logs cluster (Code: 241 ... would use 891.92 GiB, maximum: 29.80 GiB), all 8 retries exhausted, so this build provably ran the post-fix client. The Build (arm_release) check-run itself is green a fix task is moved to pending (investigating at full effort - fixing PR link to follow on this PR)

CI is fully finished on this head: 175 check-runs from the paginated check-runs API, 0 incomplete, Finish Workflow and Config Workflow both successful. Read from that API rather than the status rollup, which truncates on this repo. The Post Hooks row above sits on a check-run whose own conclusion is success, so it is visible only by querying test results separately from job status.

I will fix the old-analyzer failure on this PR and push; the other three are owned as listed. I am not re-pinging reviewers.

Session id: cron:our-pr-ci-monitor:20260807-190001

04812_group_by_use_nulls_grouping_sets_global_in failed in
`Stateless tests (amd_llvm_coverage, old analyzer, s3 storage, DBReplicated,
WasmEdge, parallel, 2/3)`, the only stateless failure on this branch's head.
Nine of its ten arms lose the `Nullable` wrapper the reference expects:

    -Nullable(UInt8)	1
    +UInt8	1

and the only unchanged arm is `control no group_by_use_nulls`. The job's own
diagnostics step reports `Failed 3 out of 3 reruns`, so it is deterministic.

That `UInt8` is correct on the old analyzer, so nothing in src/ needs
changing. `group_by_use_nulls` promotes a GROUPING SETS key only where the
analyzer arms the promotion. The new analyzer arms it at a single grouping set
(src/Analyzer/Resolve/IdentifierResolveScope.cpp:55). The old analyzer's
equivalent is `appendGroupByModifiers`, whose first statement returns unless
ROLLUP or CUBE (src/Interpreters/ExpressionAnalyzer.cpp:1597), and its
classifier reaches GROUPING_SETS only when there is more than one set (:312).
Every arm here uses GROUPING SETS with exactly one set, so no key is promoted
and the declared type stays `UInt8`.

The divergence is a property of the analyzer rather than of `IN`: a plain
column key with no `IN` anywhere reads `UInt8` on the old analyzer and
`Nullable(UInt8)` on the new one. Where the old analyzer's gates do admit the
promotion (two grouping sets, ROLLUP, CUBE) it already yields
`Nullable(UInt8)` on the unpatched binary, so extending the fix there would be
dead code.

Declaring the precondition keeps every arm running and asserting on every
lane. It does not silence the test: with the pin applied and src/Functions/in.cpp
reverted to master, the test still aborts on its first witness arm with
`Unexpected return type from globalIn. Expected Nullable(UInt8). Got UInt8`.
On a new-analyzer server the pinned and unpinned files produce byte-identical
output, so the line is inert there. Deleting it again reproduces the failure.

A session-level `SET` covers every later statement because clickhouse-test
runs a .sql file as one --multiquery client session (tests/clickhouse-test:3680)
and `InterpreterSetQuery::execute` applies the change to that session
(src/Interpreters/InterpreterSetQuery.cpp:48). It also overrides the profile
form CI installs for this lane (tests/config/install.sh:297). 974 of the 10007
stateless .sql tests on master carry a line exactly equal to
`SET enable_analyzer = 1;`, the nearest sibling being
03794_global_in_nullable_type_mismatch.sql:9, which pins the same
`GLOBAL IN`/Nullable mismatch family the same way.

`-- Tags: no-old-analyzer` was rejected because it skips the whole file
(tests/clickhouse-test:2861), dropping all ten arms from the five old-analyzer
stateless check-runs. A `.oldanalyzer.reference` was rejected because it would
record `UInt8` as an expected outcome of the fixed build.

After the pin: 50 of 50 randomized runs on a new-analyzer server and 50 of 50
on the old-analyzer profile. A 43-test group_by_use_nulls slice on that
profile, pin present against pin removed on the same binary, moves only this
test and shows no regressions.

The reference file is unchanged and src/ is untouched.
@groeneai

groeneai commented Aug 7, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: round 4 (CI fix), 0 findings

This push was reviewed by a cold second pass plus a separate reviewing model, both blind to the
implementer's notes until after their own verdicts. Both returned 0 findings. What follows is
what was checked and how, so the claims can be re-derived rather than taken on trust.

Scope. The delta is +4 / -0 lines in one test file: two comment lines and
SET enable_analyzer = 1;. src/ is untouched by it and the .reference file is byte-unchanged,
which is by itself the strongest single check that the pin altered no expected output.

The question the review had to settle is not "does the pin make the red go away" but is
UInt8 genuinely correct on the old analyzer, or is the pin hiding a second defect?
Derived
independently from source: the new analyzer arms the promotion at a single grouping set with no
cardinality condition (src/Analyzer/Resolve/IdentifierResolveScope.cpp:55-56), whereas the old
analyzer promotes via use_nulls (src/Interpreters/ExpressionAnalyzer.cpp:316), which needs
group_by_kind != ORDINARY, and its classifier reaches GROUPING_SETS only when
group_asts.size() > 1
(:312); every arm here uses GROUPING SETS with exactly one set, so both
promotion sites (:371, :425) take the un-promoted type. Independently, appendGroupByModifiers
returns at its first statement (:1597-1598) unless ROLLUP or CUBE. So UInt8 there is the
correct answer, not a symptom.

Test liveness was checked structurally, not only from the implementer's log: the pin sets the
analyzer that arms the promotion, so it can only make the witness more reachable, never less. The
reverted-src/ arm reproduces exactly the original abort with the pin in place. The SET reaches
every later arm because a .sql file runs as one --multiquery session
(tests/clickhouse-test:3680) and InterpreterSetQuery::execute applies to the session context
(src/Interpreters/InterpreterSetQuery.cpp:48); it outranks the lane's mechanism, which is a
server-side profile default (install.sh:296-298 symlinks users.d/analyzer.xml, a
<profiles><default> entry), and enable_analyzer is a declared alias of
allow_experimental_analyzer (src/Core/Settings.cpp:7913-7915), so both address the same setting.
No readonly constraint on it exists anywhere under tests/config.

Both rejected alternatives were re-checked. -- Tags: no-old-analyzer skips the whole file
(tests/clickhouse-test:2861), dropping all ten arms from the five old-analyzer stateless
check-runs on this head, a count verified against the check-run API (5 such runs, 4 green, this one
red). A .oldanalyzer.reference is a real mechanism (:2189-2191, 39 such files on master) but
would record UInt8 as an expected outcome of the fixed build.

claim re-derived as
nine of ten arms change 9 -/+ pairs and exactly 1 unchanged value row across 10 labelled arms, read out of the failing job's own diff
six witness arms and four controls 10 labelled arms, 4 named control*, 6 not
in and its seven siblings 8 registerFunction calls in src/Functions/in.cpp
a chokepoint above all seven returns executeUInt8 contains exactly 7 return statements
50 + 50 randomized runs 100 per-run verdict lines, all [ OK ], log reaching its terminator
197-test slice, 0 regressions 197 verdict lines; FAIL sets compared, 7 vs 7, 0 only-in-fix
43-test slice moves only this test pinned FAILs 00173, 02554; unpinned the same two plus this test
974 of 10007 use this form re-measured with the predicate named, plus a positive control (the cited sibling) and a negative control

All eleven file:line citations in the description and the commit message resolve against
origin/master, the tree a reader would grep. ⚠️ One measurement note kept for honesty: the first
precedent census used an invalid git grep flag and printed 0, which reads exactly like "this has
never been done"; re-run anchored, with both controls, it is 974.

Two safety claims in the original src/ change were verified rather than assumed. First,
"argument-driven nullability is resolved before executeImpl is reached" is exact:
defaultImplementationForNulls runs at src/Functions/IFunction.cpp:426, before executeImpl
at :433, and every recursing path passes removeNullable(result_type); for the four *NullIn
variants the helper returns at :197-198 and the declared type is bare UInt8, so no argument can
make result_type nullable at all. Second, the LowCardinality arm is a genuine control:
DataTypeLowCardinality::isNullable() is unconditionally false
(src/DataTypes/DataTypeLowCardinality.h:56), so for a declared LowCardinality(Nullable(UInt8))
the reconciliation is inert, which is exactly what that arm asserts.

Also checked. The cloud lane cannot conflict: it force-passes the analyzer as a client option,
but should_skip_cloud_test lists remote\('127 and this test has ten such occurrences, so the
file is skipped there. No style rule forbids SET enable_analyzer in tests. Comment budget on the
src/ diff is 3 comment lines against 14 added code lines, in a single 3-line block.

💡 One residual, disclosed and deliberately not chased: with the pin in place no stateless test
exercises the reconciliation branch on an old-analyzer lane. That is not a gap this change can
close, because the branch is unreachable there by construction, which is the same measurement that
justifies the pin.

Session id: cron:clickhouse-review-slot-49:20260807-221100

@groeneai

groeneai commented Aug 7, 2026

Copy link
Copy Markdown
Collaborator Author

CI fix: pin the new test to the analyzer whose promotion it asserts

Stateless tests (amd_llvm_coverage, old analyzer, s3 storage, DBReplicated, WasmEdge, parallel, 2/3) was the only stateless failure on 400b6afa8b390d5, in this PR's own new
test. It is deterministic, not flaky: the job's diagnostics step reports
Failed 3 out of 3 reruns. Nine of the test's ten arms lose the Nullable wrapper the
.reference expects, for example

-Nullable(UInt8)	1
+UInt8	1

and the only unchanged arm is control no group_by_use_nulls.

That UInt8 is correct on the old analyzer, so there is nothing in src/ to fix.
group_by_use_nulls promotes a GROUPING SETS key only where the analyzer arms the promotion.
The new analyzer arms it at one grouping set
(src/Analyzer/Resolve/IdentifierResolveScope.cpp:55). The old analyzer's equivalent is
appendGroupByModifiers, whose first statement returns unless ROLLUP or CUBE
(src/Interpreters/ExpressionAnalyzer.cpp:1597), and its classifier only reaches
GROUPING_SETS when there is more than one set (:312). Every arm of this test uses
GROUPING SETS with exactly one set, so no key is promoted there, the declared type stays
UInt8, and nothing is inconsistent.

I confirmed that the divergence is a property of the analyzer and not of IN: a plain column
key with no IN anywhere reads UInt8 on the old analyzer and Nullable(UInt8) on the new
one. Where the old analyzer's own gates do admit the promotion (two grouping sets, ROLLUP,
CUBE), it already yields Nullable(UInt8) on the unpatched binary, so extending the fix
there would be dead code.

The push adds one line, SET enable_analyzer = 1;, plus two comment lines stating why. It is
a precondition declaration, not a silencing:

configuration unpatched this PR
test unmodified, old-analyzer profile - fails, diff byte-identical to CI's
test pinned, old-analyzer profile aborts on the first witness arm with Unexpected return type from globalIn. Expected Nullable(UInt8). Got UInt8 all ten arms pass
test pinned, new-analyzer server - passes; output byte-identical to the unpinned file
pin deleted again, old-analyzer profile - fails with the same diff

The second row is the one that matters: with the pin in place an unpatched server still
aborts, so all six witness arms stay armed on every lane. The third row shows the line is
inert on the new analyzer, and the fourth that it is load-bearing on the old one. Each arm ran
on a server whose SELECT lower(buildId()) was asserted against readelf -n, and after the
reverted-src/ arm the shipping build id returned byte-exactly.

Randomized runs after the pin: 50 of 50 on a new-analyzer server and 50 of 50 on the
old-analyzer profile. A 43-test group_by_use_nulls slice on the old-analyzer profile, pin
present against pin removed on the same binary, moves only this test: zero regressions, and
the two shared failures are the stateful test.hits dataset and an EXPLAIN plan difference
against a minimal config, identical on both arms.

I preferred this to the two alternatives. -- Tags: no-old-analyzer skips the whole file
(tests/clickhouse-test:2861), dropping all ten arms from the five old-analyzer stateless
check-runs on this head. A .oldanalyzer.reference would record UInt8 as an expected outcome of the fixed
build, which is the opposite of what this PR asserts. Pinning the precondition keeps the test
running and asserting everywhere. The form is used by 974 of the 10007 stateless .sql tests
on master, counting lines exactly equal to SET enable_analyzer = 1;; the closest sibling is
03794_global_in_nullable_type_mismatch.sql:9, the same GLOBAL IN and Nullable mismatch
family.

Source is unchanged in this push: the diff is four added lines, all in the test, and the
.reference is untouched.

Session id: cron:clickhouse-impl-slot-41:20260807-212900

The `various` style sub-check rejects "new analyzer" tree-wide: the analyzer has
been the default since 24.3, so the wording rule asks for "the analyzer" or
"Analyzer" instead. The comment added by the previous commit tripped it.

The sentence contrasts the analyzer's GROUPING SETS key promotion with the old
analyzer's `appendGroupByModifiers`, which returns early for GROUPING SETS, so
"the analyzer's" carries the intended meaning unchanged. "The old analyzer's" in
the same sentence stays: the rule bans only "new analyzer"/"new query analyzer".

Comment-only: stripping `--` comments leaves the file byte-identical to the
previous commit, so the committed reference file cannot be affected. The word was
removed rather than the line reflowed, because the rule has a second pass that
also matches "new" ending one line with "analyzer" continuing on the next.
@groeneai

groeneai commented Aug 8, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 3923f59

CI is fully finished on this head: 175 check-runs, 0 queued/in_progress, Config Workflow and
Finish Workflow both green, last check completed 2026-08-08T05:24:54Z. Counted by conclusion:
156 success, 18 skipped, 1 failure.

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens.

Check / test Reason Owner / fixing PR
Stress test (arm_asan_ubsan, s3) / Sizes of nested column and null map of Nullable column are not equal after deserialization (STID 6726-6444) pre-existing trunk bug in stale skip-index deserialization, unrelated to this diff #112484 (mine, open)
Build (arm_release) / Post Hooks build_profile_hook telemetry INSERT rejected by LogCluster; non-gating, the build job itself is green a fix task is moved to pending (investigating at full effort - fixing PR link to follow on this PR)

The Post Hooks row rides on a green Build (arm_release) job, so it is only visible at the
sub-result level; I checked sub-results rather than job verdicts alone. It is CI telemetry and does
not affect this PR's correctness.

Scoping note on the STID 6726-6444 row: this PR changes src/Functions/in.cpp plus one new stateless
test. The failing signature is a MergeTreeIndexGranuleSet deserialization abort with no frame in the
changed code, and it reproduces across unrelated PRs and on master, so it is not caused by this diff.

The earlier deterministic failure on 400b6afa8b390d5 in this PR's own new test is fixed on this head
(Pin 04812 to the analyzer whose promotion it asserts); that stateless job is green here.

Session id: cron:our-pr-ci-monitor:20260808-060000

@george-larionov

Copy link
Copy Markdown
Member

This is a wrong fix. The error was real and wrapping the output with Nullable just caused it to run without errors, but introduced wrong results if the aggregation returned any Nulls (f.e. with empty GROUPING SET), with the fix in this PR these Nulls were then replaced by the non-null result of the recomputed IN. Closing this PR, see the correct fix here: #116980.

@groeneai

Copy link
Copy Markdown
Collaborator Author

You are right, and the wrong-results half is worse than I would have guessed. Measured on a debug build (26.8.1), enable_analyzer = 1, group_by_use_nulls = 1, table t holding one row 1:

GLOBAL IN shape, GROUP BY GROUPING SETS ((expr), ()) master 438a6180 this PR 3923f59d your dedup change
1 GLOBAL IN (t) abort: Unexpected return type from globalIn. Expected Nullable(UInt8). Got UInt8 1 2 / 1 2 1 2 / \N 2
number GLOBAL IN (t) Code: 10 NOT_FOUND_COLUMN_IN_BLOCK Code: 10, unchanged 0 1 / 1 1 / \N 2
GROUPING(1 GLOBAL IN (t)) abort, same message Code: 36, GROUPING function argument ... is not in GROUP BY keys 1 0 2 / \N 1 2

The same three queries with a local IN return the last column's values on all three binaries, so that column is the correct answer. So the super-aggregate row does come back as 1 instead of NULL here, and since master only ever errored on these shapes, this PR converted a loud failure into a silent wrong one.

Two things in that matrix I had missed entirely. The non-constant left operand is still broken with my change, byte-identical to master, so FunctionIn was never the carrier for it. And the Code: 36 message prints four distinct _data_* tables for the four occurrences of one expression, which is your root cause stated outright.

The last column is your mechanism on my tree: QueryTreeNodePtrWithHashIgnoreAliasesMap for global_in_temporary_tables and my in.cpp change reverted, nothing else. One line fixes all three shapes including the two mine leaves broken, so the type reconciliation in FunctionIn was unnecessary rather than merely insufficient.

Not reopening. I have posted a correction on #109455, where the arm_debug report came from, and I am tracking #116980 for that signature.

george-larionov added a commit that referenced this pull request Aug 31, 2026
The dedup map in `buildQueryTreeForShard` was keyed on an alias-sensitive tree
hash, but every occurrence already carries its own `__tableN` from
`createUniqueAliasesIfNecessary`, so each one built a separate temporary table.
The differing `__set_` action node names then kept the projection from
recognising a repeated GROUP BY key: it rebuilt the expression after
aggregation instead of reading the aggregated column, losing the NULL the
aggregator writes for super-aggregate rows and failing the declared-versus-
produced type check before that.

Closes: #114254
Related: #113750

Co-Authored-By: Claude Opus 5 <[email protected]>
george-larionov added a commit that referenced this pull request Sep 1, 2026
The dedup map in `buildQueryTreeForShard` was keyed on an alias-sensitive tree
hash, but every occurrence already carries its own `__tableN` from
`createUniqueAliasesIfNecessary`, so each one built a separate temporary table.
The differing `__set_` action node names then kept the projection from
recognising a repeated GROUP BY key: it rebuilt the expression after
aggregation instead of reading the aggregated column, losing the NULL the
aggregator writes for super-aggregate rows and failing the declared-versus-
produced type check before that.

Closes: #114254
Related: #113750

Co-Authored-By: Claude Opus 5 <[email protected]>
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 groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Logical error: 'Unexpected return type from globalIn. Expected Nullable(UInt8). Got UInt8' in sample-block planning for a Distributed table

3 participants