Skip to content

Stop claiming injectivity for toString of a folding date-time and toFixedString of a String - #117238

Merged
nihalzp merged 20 commits into
masterfrom
fix-injective-claims-tostring-tofixedstring
Oct 8, 2026
Merged

nihalzp merged 20 commits into
masterfrom
fix-injective-claims-tostring-tofixedstring

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 31, 2026 •

Copy link
Copy Markdown
Member

Closes: #120106
Closes: #116931
Closes: #116935
Closes: #116828
Closes: #103686
Related: #117197
Related: #117137
Related: #117210

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 wrong results for uniq*, GROUP BY, LIMIT n BY, ORDER BY after GROUP BY, and window
PARTITION BY over toString of a DateTime/DateTime64 in a time zone with a daylight-saving
transition, and over toFixedString of a String. Both functions claimed to be injective while
mapping distinct arguments onto the same result, and the default-on optimizations that take that
claim as a proof then eliminated the wrapper.

Description

Two false claims, both unconditional:

  • toString of a date-time is not injective in a time zone that has a UTC offset transition: in a
    fall-back hour two distinct instants print the same wall-clock string. It stays injective for a
    fixed-offset zone such as UTC, which is what DateLUTImpl::hasFixedOffset reports.
  • toFixedString NUL-pads a String to the target width, so 'a' and 'a\0' both become the same
    FixedString(2). A FixedString argument is fine: all its values have the same length, so
    padding appends the same suffix to every one of them.

isInjective is consumed as a proof by a growing set of default-on rewrites, so the two claims were
wrong in several places at once — one issue per consumer:

consumer symptom
optimize_injective_functions_inside_uniq uniqExact(toString(dt)) counted fold duplicates separately (#116931)
optimize_truncate_order_by_after_group_by_keys an explicit ORDER BY s, m DESC tiebreaker was dropped (#116931)
optimize_injective_functions_in_group_by one logical group came back as several (#103686)
optimize_injective_functions_in_limit_by LIMIT 1 BY returned more than one row per key (#116935)
allow_window_partitions_independently the scatter was skipped, so a frame aggregate saw a fraction of its partition (#116828)

Both answers depend on the argument types, so a caller that supplies none gets no claim. Three
query-plan call sites passed {} while holding an ActionsDAG node whose children know their result
types (and constant columns) — isInjectiveFunction, optimizeReadInOrder and
convertOuterJoinToInnerJoin now pass them through the new getFunctionArgumentColumns. That keeps
toString of an integer injective, which 04238_limit_by_in_pk_order relies on.

UniqInjectiveFunctionsEliminationPass likewise passed {} and now passes the argument columns it
already has.

Test 05227_injective_claims_tostring_datetime_and_tofixedstring covers all five consumers plus the
fixed-offset zone that must stay injective.

After review, the claim was narrowed further:

  • only the single-argument toString is claimed at all. The rendering time zone comes from the
    second argument, so toString(dt, 'Europe/Amsterdam') folds even for a DateTime('UTC'), and
    toString(x, NULL) maps every row onto NULL. This subsumes Fix wrong result from optimize_injective_functions_in_group_by on toString(x, NULL) #117197, which restricts the same
    method to the single-argument form for the toString(x, NULL) case.
  • toString(Date32) collapses too: day numbers out of the type range are saturated to 0000-01-01
    and 9999-12-31 when formatted, as ToStringMonotonicity already documents.
  • the type-erased Variant, Dynamic and Object collapse: their alternatives render into a
    common text space.
  • a Bool collapses when bool_true_representation and bool_false_representation coincide in
    the query's format settings, which toString captures.
  • toFixedString(FixedString(M), N) is claimed only when the target width is a known constant and
    M <= N. Otherwise execution throws String too long for type FixedString(N), and eliminating
    the call would turn a query that must fail into one that succeeds.

optimizeGroupBy and the uniq* rewrite in TreeOptimizer - the old-analyzer counterparts of two
of the consumers above - also passed {}, and now resolve what the AST alone decides through the
new tryGetASTFunctionArgumentColumns: an identifier that names a source column, and a literal.
An argument that stays unresolved leaves the function unclaimed.


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

Version info

  • Merged into: 26.10.1.1847-master (included in 26.10 and later)
  • Backported to: 26.9.18.10, 26.8.26.10

…toFixedString` of a `String`

Both claims were unconditional and both are false:

- `toString` of a date-time in a time zone with a UTC offset transition is many-to-one: in a
  fall-back hour two distinct instants print the same wall-clock string.
- `toFixedString` NUL-pads a `String` to the target width, so 'a' and 'a\0' both become the
  same `FixedString(2)`. A `FixedString` argument is fine - all its values have the same
  length, so padding appends the same suffix to every one of them.

An increasing number of default-on rewrites take `isInjective` as a proof, so the two claims
produced wrong results in several places at once: `uniqExact` counted fold duplicates
separately, `optimize_truncate_order_by_after_group_by_keys` dropped an explicit `ORDER BY`
tiebreaker, `GROUP BY` and `LIMIT n BY` over such a key split one logical group, and
`allow_window_partitions_independently` skipped the scatter and evaluated one logical window
partition per table partition.

Both answers depend on the argument types, so a caller that passes none gets no claim. Three
query-plan call sites passed nothing while holding an `ActionsDAG` node that knows its
children's types; they now pass them, which keeps `toString` of an integer injective for
read-in-order and for the outer-to-inner join conversion.

Closes: #116931
Closes: #116935
Closes: #116828
Closes: #103686
@clickhouse-gh

clickhouse-gh Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f2c42ee]

Summary: ✅


AI Review

Summary

This PR narrows the injectivity claims for toString, toFixedString, and the single-argument concat wrapper, and threads real argument metadata through the query-plan and legacy AST optimizers so the affected uniq*, GROUP BY, LIMIT BY, ORDER BY-truncation, and window-partition rewrites stop dropping wrappers whose text rendering can fold distinct values. After reading the current diff, the updated regression file, the top-level discussion, and every inline thread, I did not find a remaining correctness hole in the touched paths.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Measured on commit f2c42ee.

Metric Baseline Current Δ
Lines 88.30% 88.30% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 79.70% 79.70% +0.00%

Changed lines: Changed C/C++ lines covered: 75/116 (64.66%) · 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 31, 2026
Comment thread src/Functions/FunctionsConversion.h Resolved
Comment thread src/Functions/FunctionsConversion.h Resolved
@zlareb1

zlareb1 commented Aug 31, 2026

Copy link
Copy Markdown
Member

Two observations from reading the new type-dependent isInjective against the execution path, one of which is a live gap on this PR's head:

The two-argument form toString(dt, tz) is still claimed injective while its rendering folds. The new isInjective consults only each argument's type via renderingCollapsesTimePoints, but the DateTime→String execution takes the rendering zone from the second argument (extractTimeZoneFromFunctionArguments(..., 1, 0) in the DateTime serialization branch of FunctionsConversion.h). So for toString(dt_utc, 'Europe/Amsterdam') the check sees DateTime('UTC') (fixed offset, no collapse) plus String and answers true, while two distinct instants render identically:

SELECT toString(toDateTime(1540686600,'UTC'),'Europe/Amsterdam')
     = toString(toDateTime(1540690200,'UTC'),'Europe/Amsterdam');  -- 1

CREATE TABLE t (dt DateTime('UTC')) ENGINE=MergeTree ORDER BY tuple();
INSERT INTO t VALUES (1540686600),(1540690200);
SELECT count() FROM (SELECT 1 FROM t GROUP BY toString(dt,'Europe/Amsterdam'));
-- 2 at defaults, correct: 1 (verified on current master; survives this PR since the
-- argument columns passed by the new call sites answer true for this shape)

Since the argument columns are now available in sample_columns, the check could consult argument 1 when present: a constant string → that zone's hasFixedOffset; a non-constant timezone column → no claim.

A smaller note for completeness: text rendering of Variant/Dynamic also collapses distinct values across alternatives (toString(1::Variant(Int64,String)) = toString('1'::Variant(Int64,String))), and Dynamic is invisible to the forEachChild walk (no override), so a Dynamic holding folding DateTime values reports no collapse. I could not construct a consumer misfire for these today — GROUP BY toString(x) over a Variant column is not eliminated at defaults on master — so this only matters if a consumer starts engaging for those types; guarding unknown/type-erased types as "collapses" would keep the claim conservative.

`ConcatOverloadResolver::isInjective` returned `arguments.size() == 1` unconditionally, on the
comment "concat delegates to toString which is injective". Now that `toString` answers per
argument type, the resolver and the function it builds disagreed for a date-time argument -
`FunctionsStress.stress` reports the mismatch. Ask `toString` instead.
Comment thread src/Functions/toFixedString.h Resolved
@clickhouse-gh

clickhouse-gh Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing f2c42eec6 with master 6a1d7a267 (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

13 object files changed (+69.60 KiB total), 1 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Interpreters/getASTFunctionArgumentColumns.cpp.o new 50.35 KiB +50.35 KiB

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

62 translation units recompiled, 461 s compile time in total, 61 of them have a recent master baseline.

Job report

@alexey-milovidov

Copy link
Copy Markdown
Member Author

@rschu1ze — tagging you on this one as JOIN-related, as requested. Review request sent too.

… claims further

Three cases still overclaimed injectivity on the previous head:

- Multi-argument `toString`. The rendering time zone comes from the second argument, not from the
  type of the first, so `toString(dt, 'Europe/Amsterdam')` folds even when `dt` is
  `DateTime('UTC')`, and `toString(x, NULL)` maps every row onto `NULL`. Only the single-argument
  form is claimed now.
- `toString(Date32)`. Day numbers out of the type range are saturated to `0000-01-01` and
  `9999-12-31` when formatted, exactly as `ToStringMonotonicity` already documents, so two distinct
  `Date32` values can render into the same text.
- `toFixedString(FixedString(M), N)` with `M > N`. Execution throws `String too long for type
  FixedString(N)`, so eliminating the call would turn a query that must fail into one that
  succeeds. The claim now requires a constant target width with `M <= N`.

Also treat the type-erased `Variant`, `Dynamic` and `Object` as collapsing: their alternatives
render into a common text space, so `toString(1::Variant(Int64, String))` equals
`toString('1'::Variant(Int64, String))`. `renderingCollapsesTimePoints` is renamed to
`renderingCollapsesDistinctValues` accordingly.
`optimizeGroupBy` and the `uniq*` rewrite in `TreeOptimizer` passed `{}` to `isInjective`, which is
undecidable now that the answer depends on the arguments, so `GROUP BY toString(number)` stopped
being rewritten and `01244_optimize_distributed_group_by_sharding_key` lost the sharding-key
aggregation it asserts. Both call sites now resolve what the AST alone decides - an identifier that
names a source column, and a literal - through the new `tryGetASTFunctionArgumentColumns`, and claim
nothing when an argument stays unresolved.

Also cover the three cases from the review in
`05064_injective_claims_tostring_datetime_and_tofixedstring`: an explicit folding time zone and a
`NULL` time zone argument, an out-of-range `Date32` that saturates when formatted, and the
`toFixedString(FixedString(3), 2)` exception that must not be optimized away.
`EXPLAIN QUERY TREE` in the test now asks for the analyzer explicitly - it is `NOT_IMPLEMENTED` in
the old-analyzer job.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Pushed 374b3ca (and 6fcdbeb) addressing the three blockers of the AI review and @zlareb1's report.

toString(dt, tz) / toString(x, NULL) — isInjective now claims only the single-argument form. @zlareb1's repro is in the test verbatim: two instants in DateTime('UTC') rendered in Europe/Amsterdam are one group again.

toString(Date32) — the helper (renamed renderingCollapsesDistinctValues) reports Date32 as collapsing, because out-of-range day numbers saturate to 0000-01-01 / 9999-12-31 when formatted, exactly as ToStringMonotonicity already documents. It also reports the type-erased Variant, Dynamic and Object as collapsing, which is @zlareb1's smaller note — toString(1::Variant(Int64, String)) equals toString('1'::Variant(Int64, String)), and Dynamic is invisible to the forEachChild walk, so it needs an explicit answer rather than an implicit "no collapse".

toFixedString(FixedString(M), N) with M > N — the claim now requires a constant target width with M <= N. toFixedString(f, 2) over a FixedString(3) keeps raising TOO_LARGE_STRING_SIZE through GROUP BY, LIMIT BY and uniqExact instead of being optimized away.

The three regressions the review asked for are in 05064_injective_claims_tostring_datetime_and_tofixedstring. The out-of-range Date32 values go in through format(RowBinary, 'd Date32', unhex(...)) because a CAST wraps them back into range.

Two CI reds on the previous head are fixed here as well:

  • 05064 failed in the old-analyzer job with EXPLAIN QUERY TREE is only supported with the analyzer; those two queries now ask for enable_analyzer = 1 explicitly.
  • 01244_optimize_distributed_group_by_sharding_key was a real regression of mine, not a flake. optimizeGroupBy and the uniq* rewrite in TreeOptimizer passed {} to isInjective, which is undecidable now that the answer depends on the arguments, so GROUP BY toString(number) was no longer rewritten to GROUP BY number and the old analyzer stopped recognizing the sharding key. Both call sites now resolve what the AST alone decides — an identifier naming a source column, and a literal — through the new tryGetASTFunctionArgumentColumns, and claim nothing when an argument stays unresolved. Verified locally with EXPLAIN SYNTAX under enable_analyzer = 0: GROUP BY toString(number) becomes GROUP BY number again, while GROUP BY toString(dt) over a folding DateTime keeps the wrapper.

The remaining reds are unrelated: the two integration shards died on Container memory budget exceeded (/docker), and the AST fuzzer TLP WHERE oracle mismatch is over a nondeterministic LIMIT subquery with no ORDER BY (and no toString / toFixedString anywhere in it) — that oracle is being reverted in #117200.

Comment thread src/Functions/toFixedString.h Resolved
@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
alexey-milovidov and others added 2 commits September 10, 2026 03:21
…lving compound identifiers

Three findings of the review on the previous head.

`FunctionToFixedString::isInjective` read the target width with `getUInt` before
knowing that the second argument is an unsigned integer. For a call site that
passes AST-derived arguments, `toFixedString(f, -1)` over a `FixedString(3)`
wrapped the literal around to a huge `UInt64`, the claim was made, and `GROUP BY`
/ `LIMIT BY` / `uniq*` eliminated a call that `getReturnTypeImpl` has to reject
with `Second argument for function toFixedString must be unsigned integer`. The
claim now requires an unsigned width type first.

`tryGetASTFunctionArgumentColumns` resolved an identifier by its short name. It
runs before `collectJoinedColumns`, so `source_columns` describes only the source
side of a `JOIN`, and a qualified right-hand key such as `r.dt` - or a subcolumn
such as `tuple.dt` - was resolved against an unrelated source column of the same
short name. With `l.dt UInt32` and `r.dt DateTime('Europe/Amsterdam')` the old
analyzer could still treat `toString(r.dt)` as injective and drop it, even though
that rendering folds across a UTC offset transition. A compound identifier is now
undecidable here and gives no claim at all.

`ReadInOrderOptimizer::getFixedPoint` was the last caller passing `{}` to
`isInjective`. It now resolves the argument columns from
`TreeRewriterResult::source_columns` the same way the `TreeOptimizer` rewrites
do, so a wrapper that stays injective for its actual arguments can be peeled
again when inferring a fixed sorting-key prefix.

The first two regressions are in
`05064_injective_claims_tostring_datetime_and_tofixedstring` and were verified to
be load-bearing: with the fixes reverted, the negative width is optimized away
instead of throwing, and the qualified `JOIN` key gives 2 groups instead of 1.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Pushed 86599e6, addressing the two blockers and the major of the AI review, plus a merge of master.

toFixedString(f, -1) — isInjective now requires isUInt(sample_columns[1].type) before it reads the constant width, so a negative or a NULL width gives no claim and the Second argument for function toFixedString must be unsigned integer exception survives GROUP BY, LIMIT BY and uniq*.

A qualified JOIN key — tryGetASTFunctionArgumentColumns no longer resolves an identifier by its short name. A compound identifier - a right-hand key such as r.dt, or a subcolumn such as tuple.dt - is undecidable before collectJoinedColumns runs, so it gives no claim instead of picking up the type of an unrelated source column with the same short name.

Both are regressions in 05064_injective_claims_tostring_datetime_and_tofixedstring, and both were verified to be load-bearing by reverting the fix and rebuilding: the negative width is then optimized away instead of throwing, and the folding right-hand DateTime gives 2 groups instead of 1.

ReadInOrderOptimizer::getFixedPoint — it no longer passes {} to isInjective; it resolves the arguments from TreeRewriterResult::source_columns like the TreeOptimizer rewrites do. I did not add a test for it, because I could not construct a query where that call site decides the outcome: for ORDER BY (tenant, ts) with WHERE toString(tenant) = '2' ORDER BY ts under enable_analyzer = 0, EXPLAIN PLAN shows Read type: InOrder with Prefix sort description: ts ASC both with and without the change, because the query-plan optimizeReadInOrder path infers the same fixed column from the filter ActionsDAG. Details in the thread.

Locally: the whole 05064 test passes, EXPLAIN SYNTAX SELECT count() FROM numbers(2) GROUP BY toString(number) still folds to GROUP BY number under the old analyzer, and 75 of 91 injective / read_in_order / 01244 tests pass against a hand-started server, with every one of the 16 failures explained by the local setup (single-node cluster shape, no test.hits, a stale installed client) rather than by a value or plan difference.

Comment thread src/Storages/ReadInOrderOptimizer.cpp Resolved
pull Bot pushed a commit to Spencerx/ClickHouse that referenced this pull request Sep 14, 2026
`k IN (tuple(...), ...)` over a `Tuple`-typed key column arrives at key analysis
unpacked, one set column per tuple element. `tryPrepareSetIndexForIn` re-packed
that layout into a single `Tuple` column only when the key expression's own
result type was a tuple of the same arity, so a key wrapped in a transform that
returns something else (`ORDER BY toString(k)`) never matched: the set columns
were then cast to the key expression result type one at a time, and `CAST AS
Tuple` threw `TYPE_MISMATCH`. Where an element happened to parse as a tuple
literal the cast succeeded with an unrelated value instead and pruned the granule
holding the matching row, losing it silently.

Match the layout against the type the set elements are actually compared at,
which is the transform chain's input type when there is a transform and the key
expression result type otherwise. Partition pruning, the `minmax` skip index and
the `set` skip index build their conditions through the same function and threw
the same way.

Such a newly admitted layout is not exact. The transform preserves the set
semantics only if it maps distinct key values onto distinct transformed ones, and
`toString` does not: it renders every NaN payload as `nan` while `IN` compares
floats bitwise, and it renders the two instants of a fall-back hour as one local
time. So for the layouts admitted here for the first time, decline the atom under
the negated forms, where an over-approximating set would exclude rows that
satisfy the predicate, and mark it relaxed otherwise. Declining rather than
relaxing does not depend on every present and future consumer applying relaxation
before it negates the atom, and it is the disposition
`tryPrepareSetIndexForHas` already takes for the same merge.

A layout whose key expression result type is already a tuple of the set's arity
was re-packed before this change and is left exactly as it was, so nothing that
worked before can regress: `ORDER BY identity(k)` still yields an exact atom, and
so does a scalar key, which never reaches the re-pack at all. The pre-existing
exactness of a set that already arrives packed as one `Tuple` column, and of a
scalar key under a conversion that claims injectivity without being injective,
is unchanged here; that family belongs to ClickHouse#117238, whose narrowed `isInjective`
reaches this path through `out_relaxed`.
Merged via the queue into master with commit 4189f85 Oct 8, 2026
154 checks passed
@nihalzp
nihalzp deleted the fix-injective-claims-tostring-tofixedstring branch October 8, 2026 15:41
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 8, 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 Oct 12, 2026
alexey-milovidov added a commit that referenced this pull request Oct 13, 2026
Resolve the conflicts of the 26.8 backport of #117238:

- `actionsDAGUtils.h` / `actionsDAGUtils.cpp`: keep only the new
  `getFunctionArgumentColumns`; the lineage tracing, `mapHeaderColumnsToInputs`
  and `findReachableNodes` around it are master-only and not part of this change.
- `FunctionsConversion.h`: take the new `isInjective` of `FunctionConvert`.
  26.8 still has `IDataType::forEachChild` and no `DataTypes/TypeTree.h`, so
  `renderingCollapsesDistinctValues` walks the type with `check(*type)` and
  `forEachChild` as in the original version of the PR, instead of
  `forEachInTypeTree`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
robot-ch-test-poll added a commit that referenced this pull request Oct 13, 2026
Cherry pick #117238 to 26.8: Stop claiming injectivity for `toString` of a folding date-time and `toFixedString` of a `String`
robot-clickhouse added a commit that referenced this pull request Oct 13, 2026
… a folding date-time and `toFixedString` of a `String`
alexey-milovidov added a commit that referenced this pull request Oct 13, 2026
Resolve conflicts of the cherry-pick of #117238 onto 26.9:
- `actionsDAGUtils.h/.cpp`: keep the release-branch code (it has no
  `HeaderColumnsToInputs` / `findReachableNodes`) and add only
  `getFunctionArgumentColumns` from the PR.
- `FunctionsConversion.h`: take the PR's `isInjective`; the release branch
  still has `IDataType::forEachChild` and no `DataTypes/TypeTree.h`, so
  `renderingCollapsesDistinctValues` walks the type tree with `forEachChild`
  as in the original version of the PR.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
robot-clickhouse-ci-1 added a commit that referenced this pull request Oct 13, 2026
Cherry pick #117238 to 26.9: Stop claiming injectivity for `toString` of a folding date-time and `toFixedString` of a `String`
robot-clickhouse added a commit that referenced this pull request Oct 13, 2026
… a folding date-time and `toFixedString` of a `String`
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Oct 13, 2026
clickhouse-gh Bot added a commit that referenced this pull request Oct 13, 2026
Backport #117238 to 26.8: Stop claiming injectivity for `toString` of a folding date-time and `toFixedString` of a `String`
clickhouse-gh Bot added a commit that referenced this pull request Oct 13, 2026
Backport #117238 to 26.9: Stop claiming injectivity for `toString` of a folding date-time and `toFixedString` of a `String`
amogiska pushed a commit to amogiska/ClickHouse that referenced this pull request Nov 18, 2026
… type-aware

ClickHouse#118899 relaxed `IN` and declined `NOT IN` for every transformed Tuple key
re-packed against the transform input, because `toString` then claimed
injectivity for every type while it folds NaN payloads and fall-back hours.
ClickHouse#117238 made that claim type-aware, so `analyzeKeyExpressionForSetIndex`
already relaxes those atoms through `is_injective`, and a relaxed `NOT IN`
atom never prunes on its own. Removing the block lets an injective
transform such as `toString` of `Tuple(Int64, String)` keep an exact atom.

Follow-up to ClickHouse#118899 (comment)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
subkanthi pushed a commit to subkanthi/ClickHouse that referenced this pull request Nov 18, 2026
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... 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.8-must-backport

Projects

None yet

7 participants