Repository navigation
Stop unwrapping injective LIMIT BY keys past a GROUP BY key - #120070
alexey-milovidov merged 3 commits into
Conversation
`OptimizeLimitByInjectiveFunctionsPass` rewrote `LIMIT BY f(x)` to `LIMIT BY x` for every injective `f`, without regard for aggregation. `LIMIT BY` is evaluated after aggregation, where only the `GROUP BY` keys and the aggregates exist, so with `GROUP BY toString(c0) ... LIMIT 1 BY toString(c0)` the rewritten key `c0` was gone and the query failed with `NOT_FOUND_COLUMN_IN_BLOCK`. #117137 made `plus`/`minus` with an integer constant injective as well, which turned `03710_analyzer_limit_by_aggregate_validation` red on `master` whenever the test runner drew `optimize_injective_functions_in_group_by = 0` (the `GROUP BY` counterpart then keeps `c0 + 1` as the key while `LIMIT BY` was unwrapped to `c0`). The unwrapping now treats the `GROUP BY` keys (including those of every grouping set) as terminal: a `LIMIT BY` key that wraps a `GROUP BY` key is still unwrapped down to that key, but never past it. CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?REF=master&sha=7f4f875596fbd83ed50d7cbc73864d624041164c&name_0=MasterCI&name_1=Stateless%20tests%20%28amd_release%2C%20parallel%2C%202%2F2%29 Co-Authored-By: Claude Fable 5.1 <[email protected]>
|
Workflow [PR], commit [ad0c4f0] Summary: ✅
AI ReviewSummaryThis PR fixes Final VerdictStatus: ✅ Approve LLVM Coverage ReportMeasured on commit ad0c4f0.
Changed lines: Changed C/C++ lines covered: 26/26 (100.00%) · Uncovered code |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units11 translation units recompiled, 19 s compile time in total, 11 of them have a recent master baseline. |
|
📊 Cloud Performance Report ✅ AI verdict: no significant changes detected. K_source=6 K_base=30 flagged=0/65 clickbench🟢 No significant changes tpch_adapted_1_official🟢 No significant changes Debug info
|
…ive-unwrap-through-group-by-keys
…l too
With `group_by_use_nulls = 1` and `WITH ROLLUP` / `WITH CUBE` / `GROUPING SETS`, everything that is
resolved after `GROUP BY` sees the grouping keys promoted to `Nullable`: `QueryAnalyzer` replaces
such an expression with a clone of the key converted to `Nullable`, see `registerNullableGroupByKeys`.
Node comparison includes the result type, so the keep-set built from the original keys did not match
the shape that arrives in `LIMIT BY`, and the unwrapping walked past the key again:
SET group_by_use_nulls = 1, optimize_injective_functions_in_group_by = 0;
SELECT toString(c0) AS s FROM t GROUP BY toString(c0) WITH ROLLUP ORDER BY s LIMIT 1 BY s;
still failed with `NOT_FOUND_COLUMN_IN_BLOCK`. Register the converted shape as well. Only a
`FunctionNode` needs it, because `unwrapInjectiveFunctionsInKeys` keeps every other kind of node
anyway.
All five new cases of `05213_limit_by_injective_unwrap_stops_at_group_by_key` fail with
`NOT_FOUND_COLUMN_IN_BLOCK` on the previous head of this branch (441b019, CI binary of the merge
commit be91561) and pass now.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`isInjectiveFunction` in the query-plan optimizations decided injectivity
from a hardcoded name list (`plus`, `minus`, `negate`, `tuple`) with no
look at the operand types. Measured on master, per-partition vs merged
group counts:
d + INTERVAL 1 MONTH 19 vs 13 end-of-month collapse
t + INTERVAL 1 DAY 6 vs 4 DST fold, DateTime('Europe/Moscow')
f + 1.0 3 vs 2 Float64 mantissa rounding near 1e16
x + toDate(0) 6 vs 1 the constant narrows the result to Date
x + toDecimal32(0, 1) 4 vs 1 the constant rescales the varying operand
Causal chain: the name list claims injectivity, so
`removeInjectiveFunctionsFromResultsRecursively` peels the function off
the key; the five per-partition rewrites in `useDataParallelAggregation`
(aggregation, LIMIT BY, DISTINCT, window, set building, all enabled by
default) and `StorageDistributed::isShardingKeySuitsQueryTreeNodeExpression`
then conclude the partition or shard key is determined by the group key and
skip the cross-partition merge. Where the expression collapses distinct
values onto one key and those values live in different partitions, the
merge that would have combined them never runs, so the query returns one
row or window frame per partition instead of one per group.
The predicate lives in `FunctionHelpers`, next to the other operand-type
predicates, and recognizes injectivity only for integer operands with an
integer, non-NULL fixed operand: the result type widens and integer
wrap-around is a bijection, while every other operand class contains cases
that map distinct arguments to one result and is indistinguishable by type
from the safe cases beside it.
Only the query-plan consumer consults it. The virtual
`IFunctionBase::isInjective` answer is left exactly as master has it,
because two analyzer consumers of that answer cannot currently take a
truthful one: `OptimizeGroupByInjectiveFunctionsPass` declines to unwrap
`GROUP BY f(x)` when its setting is off, when `group_by_use_nulls = 1`, or
under any GROUP BY modifier, while `OptimizeLimitByInjectiveFunctionsPass`
mirrors neither of the last two guards. Whenever the GROUP BY pass declines
and the LIMIT BY pass does not, the rewritten LIMIT BY key asks for a
column aggregation has consumed. That asymmetry is pre-existing (`toString`
has always answered injective and fails the same way), and it is why the
previous attempt at this fix was reverted.
Measured on the best base available for the function-level shape: with
ClickHouse#120070 cherry-picked, `SELECT c0 + 1 AS e FROM t GROUP BY c0 + 1 WITH
ROLLUP ORDER BY e LIMIT 1 BY e SETTINGS group_by_use_nulls = 1` still
fails with NOT_FOUND_COLUMN_IN_BLOCK at default
`optimize_injective_functions_in_group_by`, on a query that returns rows on
master today. `ClickHouse#120070` builds its keep-set as a `QueryTreeNodePtrWithHashSet`
whose node equality includes the result type, so under `group_by_use_nulls`
the re-resolved `Nullable(Int64)` clone misses the set and the unwrap
proceeds. Confining the change to the query-plan consumer makes the whole
pass family structurally unreachable, which a 40-cell base-vs-fix sweep
over modifier x `group_by_use_nulls` x setting x key confirms cell by cell.
`negate` and `tuple` leave the name list because branch 1 already answers
them: `FunctionUnaryArithmetic::isInjective` returns its `is_injective`
template argument and `negate` instantiates it `true`, while `tuple`
returns `true` unconditionally. Two plan-shape arms assert that the
optimization keeps firing for both.
This re-lands ClickHouse#117137, which was reverted by ClickHouse#120118 (`ad770fc2a68ae`) for
`03710_analyzer_limit_by_aggregate_validation`. That test passes here at
both values of `optimize_injective_functions_in_group_by` and in all four
cells of the `optimize_injective_functions_in_group_by` x
`optimize_injective_functions_in_limit_by` matrix.
Closes: ClickHouse#116268
Closes: ClickHouse#118729
Co-Authored-By: Claude Opus 5 <[email protected]>
Related: #117137
Related: #119222
OptimizeLimitByInjectiveFunctionsPassrewroteLIMIT BY f(x)toLIMIT BY xfor every injectivef, without regard for aggregation.LIMIT BYis evaluated after aggregation, where only theGROUP BYkeys and the aggregates exist, so a query such ashad its
LIMIT BYkey rewritten toc0, which no longer exists after the aggregation, and failed withNOT_FOUND_COLUMN_IN_BLOCK. Since #117137plus/minuswith an integer constant report injectivity too, so03710_analyzer_limit_by_aggregate_validationfails onmasterwhenever the test runner drawsoptimize_injective_functions_in_group_by = 0(theGROUP BYcounterpart then keepsc0 + 1as the key whileLIMIT BYis unwrapped toc0). Fleet-wide red since 2026-09-14, for example https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?REF=master&sha=7f4f875596fbd83ed50d7cbc73864d624041164c&name_0=MasterCI&name_1=Stateless%20tests%20%28amd_release%2C%20parallel%2C%202%2F2%29The unwrapping now treats the
GROUP BYkeys (including those of every grouping set) as terminal: aLIMIT BYkey that wraps aGROUP BYkey is still unwrapped down to that key, but never past it. Keys that wrap an aggregate keep being unwrapped to the aggregate, and queries without aggregation are unaffected.With
group_by_use_nulls = 1andWITH ROLLUP/WITH CUBE/GROUPING SETSthe same rewrite still happened, because everything resolved afterGROUP BYsees the grouping keys promoted toNullableand node comparison includes the result type, so the original key did not match the shape that arrives inLIMIT BY. The keys are therefore registered in theirNullableshape too.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix
NOT_FOUND_COLUMN_IN_BLOCKforLIMIT BYon an injective function of aGROUP BYkey, such asGROUP BY toString(c0) LIMIT 1 BY toString(c0): theLIMIT BYkey was rewritten to the function argument, which does not exist after aggregation.🤖 Generated with Claude Code
Workflow [PR]
Sync PR [sync-upstream/pr/120070]
Version info
26.10.1.362-master(included in26.10and later)