Repository navigation
Stop claiming injectivity for toString of a folding date-time and toFixedString of a String - #117238
Conversation
…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
|
Workflow [PR], commit [f2c42ee] Summary: ✅
AI ReviewSummaryThis PR narrows the injectivity claims for Final Verdict
LLVM Coverage ReportMeasured on commit f2c42ee.
Changed lines: Changed C/C++ lines covered: 75/116 (64.66%) · Uncovered code |
|
Two observations from reading the new type-dependent The two-argument form 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 A smaller note for completeness: text rendering of |
`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.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes13 object files changed (+69.60 KiB total), 1 added.
719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units62 translation units recompiled, 461 s compile time in total, 61 of them have a recent master baseline. |
|
@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.
…s-tostring-tofixedstring
`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.
|
🕵 Pushed 374b3ca (and 6fcdbeb) addressing the three blockers of the AI review and @zlareb1's report.
The three regressions the review asked for are in Two CI reds on the previous head are fixed here as well:
The remaining reds are unrelated: the two integration shards died on |
…s-tostring-tofixedstring
…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]>
|
🕵 Pushed 86599e6, addressing the two blockers and the major of the AI review, plus a merge of
A qualified Both are regressions in
Locally: the whole |
`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`.
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]>
Cherry pick #117238 to 26.8: Stop claiming injectivity for `toString` of a folding date-time and `toFixedString` of a `String`
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]>
Cherry pick #117238 to 26.9: Stop claiming injectivity for `toString` of a folding date-time and `toFixedString` of a `String`
Backport #117238 to 26.8: Stop claiming injectivity for `toString` of a folding date-time and `toFixedString` of a `String`
Backport #117238 to 26.9: Stop claiming injectivity for `toString` of a folding date-time and `toFixedString` of a `String`
… 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]>
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
Closes: #120106
Closes: #116931
Closes: #116935
Closes: #116828
Closes: #103686
Related: #117197
Related: #117137
Related: #117210
Changelog category (leave one):
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 BYafterGROUP BY, and windowPARTITION BYovertoStringof aDateTime/DateTime64in a time zone with a daylight-savingtransition, and over
toFixedStringof aString. Both functions claimed to be injective whilemapping 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:
toStringof a date-time is not injective in a time zone that has a UTC offset transition: in afall-back hour two distinct instants print the same wall-clock string. It stays injective for a
fixed-offset zone such as
UTC, which is whatDateLUTImpl::hasFixedOffsetreports.toFixedStringNUL-pads aStringto the target width, so'a'and'a\0'both become the sameFixedString(2). AFixedStringargument is fine: all its values have the same length, sopadding appends the same suffix to every one of them.
isInjectiveis consumed as a proof by a growing set of default-on rewrites, so the two claims werewrong in several places at once — one issue per consumer:
optimize_injective_functions_inside_uniquniqExact(toString(dt))counted fold duplicates separately (#116931)optimize_truncate_order_by_after_group_by_keysORDER BY s, m DESCtiebreaker was dropped (#116931)optimize_injective_functions_in_group_byoptimize_injective_functions_in_limit_byLIMIT 1 BYreturned more than one row per key (#116935)allow_window_partitions_independentlyBoth answers depend on the argument types, so a caller that supplies none gets no claim. Three
query-plan call sites passed
{}while holding anActionsDAGnode whose children know their resulttypes (and constant columns) —
isInjectiveFunction,optimizeReadInOrderandconvertOuterJoinToInnerJoinnow pass them through the newgetFunctionArgumentColumns. That keepstoStringof an integer injective, which04238_limit_by_in_pk_orderrelies on.UniqInjectiveFunctionsEliminationPasslikewise passed{}and now passes the argument columns italready has.
Test
05227_injective_claims_tostring_datetime_and_tofixedstringcovers all five consumers plus thefixed-offset zone that must stay injective.
After review, the claim was narrowed further:
toStringis claimed at all. The rendering time zone comes from thesecond argument, so
toString(dt, 'Europe/Amsterdam')folds even for aDateTime('UTC'), andtoString(x, NULL)maps every row ontoNULL. This subsumes Fix wrong result fromoptimize_injective_functions_in_group_byontoString(x, NULL)#117197, which restricts the samemethod to the single-argument form for the
toString(x, NULL)case.toString(Date32)collapses too: day numbers out of the type range are saturated to0000-01-01and
9999-12-31when formatted, asToStringMonotonicityalready documents.Variant,DynamicandObjectcollapse: their alternatives render into acommon text space.
Boolcollapses whenbool_true_representationandbool_false_representationcoincide inthe query's format settings, which
toStringcaptures.toFixedString(FixedString(M), N)is claimed only when the target width is a known constant andM <= N. Otherwise execution throwsString too long for type FixedString(N), and eliminatingthe call would turn a query that must fail into one that succeeds.
optimizeGroupByand theuniq*rewrite inTreeOptimizer- the old-analyzer counterparts of twoof the consumers above - also passed
{}, and now resolve what the AST alone decides through thenew
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
26.10.1.1847-master(included in26.10and later)26.9.18.10,26.8.26.10