Skip to content

Do not claim injectivity for a function that collapses varying arguments to Nothing - #117894

Merged
fm4v merged 6 commits into
ClickHouse:masterfrom
groeneai:fix-injective-claim-collapsed-nothing-result
Nov 18, 2026
Merged

fm4v merged 6 commits into
ClickHouse:masterfrom
groeneai:fix-injective-claim-collapsed-nothing-result

Conversation

@groeneai

@groeneai groeneai commented Sep 3, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #117767
Related: #117197
Related: #117210
Related: #117238
Related: #117239
Related: #117357

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 wrong results when a GROUP BY or LIMIT BY key, or an ORDER BY expression, was a function call whose result type collapses to Nullable(Nothing) because an argument is a NULL constant, such as concatAssumeInjective(s, NULL). Such a call was still treated as injective and replaced by its argument in the key, so GROUP BY and LIMIT BY produced one group or row per distinct argument value, and optimize_truncate_order_by_after_group_by_keys dropped a still-needed ORDER BY tiebreaker.

Description

Reported for UUIDStringToNum(<column>, NULL), whose claim #117210 has since dropped. The class still reproduces on master and on 26.8.28.14: GROUP BY f(<column>, NULL) returns one group per distinct argument value instead of a single group.

CREATE TABLE t (fs FixedString(2)) ENGINE = MergeTree ORDER BY tuple();
INSERT INTO t VALUES ('aa'),('aa'),('aa'),('bb'),('bb'),('cc'),('cc');
SELECT concatAssumeInjective(fs, NULL) AS k, count() FROM t GROUP BY k;
-- three rows, must be a single \N 7

The overload resolver replaces the result type before getReturnTypeImpl runs: Nullable(Nothing) when useDefaultImplementationForNulls meets a NULL constant argument, bare Nothing for a Nothing argument. The built function's isInjective still describes the un-collapsed function and answers true, so consumers rewrite f(x) to x. A function mapping its whole domain onto one value is injective only over a single-valued domain.

The fix answers false when the result type admits at most one value and some argument type is not Nothing or Nullable(Nothing). With every argument of those types the domain is one tuple wide, the claim holds, and the rewrite master's 04805_group_by_injective_function_of_constant pins is kept. Declining is monotonically safe: the claim is a permission to rewrite, never an obligation.

The per-function fixes above do not close the class: they remove claims that are false in general, while concatAssumeInjective is a documented user opt-in that must be respected and still collapses for a NULL argument.


Workflow [PR]
Sync PR [sync-upstream/pr/117894]

Version info

  • Merged into: 26.11.1.2784-master (included in 26.11 and later)
  • Backported to: 26.10.7.21

…hing

`GROUP BY f(<column>, NULL)` returned one group per distinct argument value
instead of a single group, silently. `LIMIT BY` dropped rows the same way, and
`optimize_truncate_order_by_after_group_by_keys` removed a still-needed
`ORDER BY` tiebreaker.

The overload resolver replaces the result type with one that admits at most a
single value, before `getReturnTypeImpl` ever runs: `Nullable(Nothing)` when
`useDefaultImplementationForNulls` meets a NULL constant argument
(`src/Functions/IFunction.cpp:901-908`), and bare `Nothing` for a `Nothing`
argument (`:892-899`). The implementation's `isInjective` still describes the
un-collapsed function and answers `true`, so consumers treat `f(x)` and `x` as
inducing the same partition and rewrite `f(x)` to `x`. A function mapping its
whole domain onto one value is injective only over a single-valued domain, so
that rewrite changes the answer. This is why the reported query lost its
grouping while `SELECT DISTINCT` over the same expression stayed correct: the
function is gone from the key before the aggregator runs.

`FunctionToFunctionBaseAdaptor::isInjective` now declines when the built result
type admits at most one value. The predicate is complete over both collapse
paths, whose entire output set is `{Nothing, Nullable(Nothing)}`;
`LowCardinality(Nothing)` cannot be constructed, because
`IDataType::canBeInsideLowCardinality` defaults to false and `DataTypeNothing`
does not override it. Declining is monotonically safe: `isInjective() == true`
is a permission to rewrite, never an obligation, so every consumer becomes more
conservative and no optimization worth keeping is lost, the expression being a
constant NULL.

The definition moved out of line into `IFunctionAdaptors.cpp` so that
`IDataType.h` is not pulled into `IFunctionAdaptors.h`, which is included
across `src/Functions/` and today sees only `IDataType_fwd.h`.

The class cannot be closed function by function: `concatAssumeInjective` is an
explicit user opt-in that must be honoured, and `toFixedString` of a
`FixedString` is genuinely injective, yet both still collapse to
`Nullable(Nothing)` for a NULL argument.

`FunctionToOverloadResolverAdaptor` is deliberately unchanged. A resolver has
no result type, so the old analyzer's AST-level rewrite cannot express this
guard, and its arm is out of scope.

`gtest_functions_stress.cpp` cross-checks that the resolver and the built
function agree about injectivity. That check now legitimately diverges for a
collapsed result, so the `Nothing` case is whitelisted beside the existing
Dynamic/Variant/Object one, narrowed to the collapsed result type so a genuine
mismatch is still reported.

Related: ClickHouse#117767
The guard declines injectivity for both types the overload resolver can
substitute, but every assertion in the test used a literal `NULL`, which only
reaches the `Nullable(Nothing)` path (`src/Functions/IFunction.cpp:901-908`).
Two assertions now cover the other path, bare `Nothing` from an argument that
is already typed `Nothing` (`:892-899`), reached with
`assumeNotNull(materialize(NULL))`.

That branch is asserted on the query tree rather than on a result because a
non-empty column of type `Nothing` cannot be created (`:428`), so every query
that evaluates such an expression throws `ILLEGAL_COLUMN` on both a pristine
and a guarded build. The rewrite decision is the only observable difference:
a pristine build unwraps the key, a guarded build retains it, and with
`optimize_injective_functions_in_group_by = 0` both retain it, which is the
oracle arm beside it.

Related: ClickHouse#117767
The test asserts that a function whose result type collapses to Nothing or
Nullable(Nothing) is no longer treated as injective, so it needs a carrier that
keeps claiming injectivity. toFixedString is a poor choice for that: several open
PRs are removing false isInjective claims function by function, and ClickHouse#117238
rewrites FunctionToFixedString::isInjective to consult its width argument. For
toFixedString(fs, assumeNotNull(materialize(NULL))) that argument column is
nullptr, so the function would start declining on its own and the two bare-Nothing
arms would pass whether or not the guard exists.

concatAssumeInjective cannot be silenced that way. Its claim is an explicit user
opt-in rather than an assertion about the function's mathematics: ConcatImpl
returns the flag it was constructed with and never inspects its arguments. It also
overrides neither useDefaultImplementationForNulls nor
useDefaultImplementationForNothing, so both collapse paths are reachable through
this one function and the whole test becomes a single-function A/B - a NULL
argument against a non-NULL one.

Both narrowness controls move to concatAssumeInjective(fs, 'x') for the same
reason, which also removes the last dependency on a function whose claim is being
corrected elsewhere. The reference was regenerated by running the test.

Discrimination is unchanged: against a build without the guard, exactly four
assertions flip (the keyed GROUP BY, the bare-Nothing query tree, the LIMIT BY and
the ORDER BY tiebreaker) while every pass-disabled oracle arm and both narrowness
controls hold.

Related: ClickHouse#117767
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Sep 3, 2026
@groeneai

groeneai commented Sep 3, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: 3 rounds, 0 open findings

Every round was reviewed cold by me and then adversarially by an independent second model.
Round 3 (02b1201d5bc0b3d): 0 findings from the second model, 0 blockers and 0 majors from my
own pass.

Closed in the earlier rounds:

  • ⚠️ the bare Nothing collapse branch had no fixture. Agreed, one EXPLAIN QUERY TREE
    case was added: a column of type Nothing cannot be non-empty, so the rewrite decision is the
    only observable difference for that half.
  • ⚠️ the test's carrier could stop claiming injectivity on its own once Stop claiming injectivity for toString of a folding date-time and toFixedString of a String #117238 lands,
    which would leave those assertions passing vacuously. Agreed, every arm moved to
    concatAssumeInjective, whose claim is a user opt-in and so cannot be removed.
  • ❌ "the {plus, minus, negate, tuple} fallback in isInjectiveFunction overrides this
    guard". FunctionBinaryArithmetic declares no isInjective, so plus already answered
    false before this change and that fallback already discarded it. The wrong result is real
    but pre-existing, and Fix wrong results for plus/minus keys with a non-integer operand #117137 removes the fallback.

Against a build without the guard, exactly four assertions of the new test flip, while every
oracle arm, both ground-truth arms and both narrowness controls hold.

@clickhouse-gh clickhouse-gh Bot closed this Sep 3, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 3, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [372e985]

Summary: ✅


AI Review

Summary

The PR prevents incorrect key rewrites when a function's result collapses to Nothing or Nullable(Nothing) while its arguments can vary. No remaining findings. The previous legacy-analyzer finding no longer applies: current query execution always uses the analyzer, and enable_analyzer = 0 is normalized to 1; the existing bot thread was resolved. The regression test 05090_injective_function_collapsed_to_nothing passes in Fast test for commit 372e9857806fffcde5ccb45c156386067874555c.

Final Verdict

Status: ✅ Approve

@groeneai

groeneai commented Sep 3, 2026

Copy link
Copy Markdown
Collaborator Author

cc @rschu1ze @vdimir, could you review this? The overload resolver collapses a function call's result type to Nullable(Nothing) for a NULL constant argument before getReturnTypeImpl runs, but the built function still answers isInjective for the un-collapsed function, so the analyzer unwrapped f(x) to x in a GROUP BY, LIMIT BY or ORDER BY key and produced one group per distinct argument value.

groeneai and others added 2 commits September 3, 2026 17:34
The guard in the previous commit declined injectivity for every function whose result
type is `Nothing` or `Nullable(Nothing)`. One case too many: when every argument type
also holds at most one value the argument domain is a single tuple, so any function
over it is injective and declining there only loses a valid rewrite.

Master's 04805_group_by_injective_function_of_constant pins that rewrite. In
`GROUP BY materialize(NULL), k` the constant-derived key is dropped because
`materialize` is injective over its single-valued argument, leaving `GROUP BY k`. The
blanket guard kept the redundant key, so the test's query-tree assertion went from 0 to
1 and `Fast test` reported a mismatch with the reference.

Decline only when an argument type can hold more than one value, which is what makes
the claim false. An empty sample carries no argument types and still declines, so the
call sites that pass none behave as before.

Three builds, both directions: pristine master fails 05090 and passes 04805, the
blanket guard passes 05090 and fails 04805, this commit passes both. The 18 tests of
the injective and truncate_order_by family pass, and both tests pass 50 runs at -j 8.

Co-Authored-By: Claude Opus 5 <[email protected]>
The skip was added alongside a guard that declined injectivity for every collapsed
result type, so its note read "mapping a whole domain onto one value is not injective".
That is false where the domain holds a single tuple, which the guard now allows. Give
the reason that survives: the result type is known only after `build`, so the resolver
can still claim injectivity the built function declines. The condition is unchanged;
it stays deliberately broad, since a skip only ever suppresses a mismatch report.

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai groeneai changed the title Do not claim injectivity for a function whose result collapses to Nothing Do not claim injectivity for a function that collapses varying arguments to Nothing Sep 3, 2026
Comment thread src/Functions/IFunctionAdaptors.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 372e98578 with master 58077c99f (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes

98 object files changed (-2.42 MiB total), 0 added.

Object file Master PR Δ
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/transform.cpp.o 1.69 MiB 1.64 MiB -43.61 KiB (-2.53%)
src/CMakeFiles/dbms.dir/Functions/if.cpp.o 11.51 MiB 11.47 MiB -38.40 KiB (-0.33%)
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/bitOr.cpp.o 2.98 MiB 2.95 MiB -32.04 KiB (-1.05%)
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/bitXor.cpp.o 2.98 MiB 2.95 MiB -32.04 KiB (-1.05%)
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/bitAnd.cpp.o 2.97 MiB 2.94 MiB -32.02 KiB (-1.05%)
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/bitBoolMaskAnd.cpp.o 3.24 MiB 3.21 MiB -31.86 KiB (-0.96%)
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/bitBoolMaskOr.cpp.o 3.24 MiB 3.21 MiB -31.86 KiB (-0.96%)
src/Functions/array/CMakeFiles/clickhouse_functions_array.dir/arrayElement.cpp.o 10.19 MiB 10.16 MiB -31.84 KiB (-0.31%)
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/concat.cpp.o 495.80 KiB 464.08 KiB -31.72 KiB (-6.40%)
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/moduloOrZero.cpp.o 3.97 MiB 3.94 MiB -31.67 KiB (-0.78%)
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/lcm.cpp.o 3.11 MiB 3.08 MiB -31.56 KiB (-0.99%)
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/initializeAggregation.cpp.o 332.92 KiB 301.45 KiB -31.47 KiB (-9.45%)
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/gcd.cpp.o 2.99 MiB 2.96 MiB -31.34 KiB (-1.02%)
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/bitHammingDistance.cpp.o 3.41 MiB 3.38 MiB -31.10 KiB (-0.89%)
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/modulo.cpp.o 17.43 MiB 17.39 MiB -31.08 KiB (-0.17%)
src/CMakeFiles/dbms.dir/Functions/multiIf.cpp.o 865.33 KiB 834.25 KiB -31.07 KiB (-3.59%)
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/bitRotateLeft.cpp.o 2.62 MiB 2.59 MiB -31.07 KiB (-1.16%)
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/bitTest.cpp.o 2.47 MiB 2.44 MiB -30.83 KiB (-1.22%)
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/intDiv.cpp.o 11.61 MiB 11.58 MiB -30.66 KiB (-0.26%)
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/reverse.cpp.o 319.48 KiB 288.85 KiB -30.62 KiB (-9.59%)

719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

264 translation units recompiled, 2628 s compile time in total, 264 of them have a recent master baseline.

Job report

@groeneai

groeneai commented Sep 4, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - a7a97e0

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
Bugfix validation (unit tests) harness, expected and disclosed in the description. The job needs a touched unit test to FAIL on the merge-base binary; the touched file here is src/Functions/tests/gtest_functions_stress.cpp, whose change only narrows a report that cannot fire without the source fix, so it passes there (fail: 0, passed: 1) and the job reports Failed to reproduce the bug. The reproducer is the SQL test 05090_injective_function_collapsed_to_nothing. Non-blocking: Mergeable Check is green, and the binding per-arch arms Bugfix validation (functional tests, aarch64) and (functional tests, amd64) are both OK. Nothing on this branch can make it green, because filter_job.py has no "no unit-test updates" skip for this job a fix task is created (investigating at full effort, fixing-PR link to follow on this pull request)

Session id: cron:our-pr-ci-monitor:20260904-020000

@clickhouse-gh clickhouse-gh Bot added the comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... label Sep 4, 2026
@groeneai

groeneai commented Sep 4, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the Bugfix validation (unit tests) row of the finish ledger above: #118108.

It adds the missing arm to filter_job.should_skip_job, so the unit validator is not scheduled
when the PR carries a functional or integration test. new_tests_check.check returns inside its
has_ft or has_it branch before it ever reads the unit verdict, so on this PR the job was
building a merge-base unit_tests_dbms to produce a verdict nothing consults. The four cases
where the unit arm really is the gate keep running and keep refuting.

…-collapsed-nothing-result

# Conflicts:
#	src/Functions/IFunctionAdaptors.h
@fm4v
fm4v added this pull request to the merge queue Nov 18, 2026
Merged via the queue into ClickHouse:master with commit 0bed3f1 Nov 18, 2026
179 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 Nov 18, 2026
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Nov 18, 2026
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Nov 18, 2026
clickhouse-gh Bot added a commit that referenced this pull request Nov 19, 2026
Backport #117894 to 26.10: Do not claim injectivity for a function that collapses varying arguments to `Nothing`
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 comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.10-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

GROUP BY does not collapse a Nullable(Nothing) key produced by UUIDStringToNum(<col>, NULL) — one group per input row

5 participants