Skip to content

Stop unwrapping injective LIMIT BY keys past a GROUP BY key - #120070

Merged
alexey-milovidov merged 3 commits into
masterfrom
fix/limit-by-injective-unwrap-through-group-by-keys
Sep 21, 2026
Merged

alexey-milovidov merged 3 commits into
masterfrom
fix/limit-by-injective-unwrap-through-group-by-keys

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Sep 14, 2026 •

Copy link
Copy Markdown
Member

Related: #117137
Related: #119222

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 a query such as

SELECT toString(c0) AS s FROM t GROUP BY toString(c0) LIMIT 1 BY s

had its LIMIT BY key rewritten to c0, which no longer exists after the aggregation, and failed with NOT_FOUND_COLUMN_IN_BLOCK. Since #117137 plus/minus with an integer constant report injectivity too, so 03710_analyzer_limit_by_aggregate_validation fails on master whenever the test runner draws optimize_injective_functions_in_group_by = 0 (the GROUP BY counterpart then keeps c0 + 1 as the key while LIMIT BY is unwrapped to c0). 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%29

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. Keys that wrap an aggregate keep being unwrapped to the aggregate, and queries without aggregation are unaffected.

With group_by_use_nulls = 1 and WITH ROLLUP / WITH CUBE / GROUPING SETS the same rewrite still happened, because everything resolved after GROUP BY sees the grouping keys promoted to Nullable and node comparison includes the result type, so the original key did not match the shape that arrives in LIMIT BY. The keys are therefore registered in their Nullable shape too.

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 NOT_FOUND_COLUMN_IN_BLOCK for LIMIT BY on an injective function of a GROUP BY key, such as GROUP BY toString(c0) LIMIT 1 BY toString(c0): the LIMIT BY key 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

  • Merged into: 26.10.1.362-master (included in 26.10 and later)

`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]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [ad0c4f0]

Summary: ✅


AI Review

Summary

This PR fixes OptimizeLimitByInjectiveFunctionsPass so LIMIT BY unwrapping stops at GROUP BY keys, including the Nullable shapes that appear with group_by_use_nulls under WITH ROLLUP, WITH CUBE, and GROUPING SETS. I did not find any remaining correctness, metadata, or test-coverage issues in the current diff.

Final Verdict

Status: ✅ Approve

LLVM Coverage Report

Measured on commit ad0c4f0.

Metric Baseline Current Δ
Lines 88.50% 88.50% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 80.70% 80.70% +0.00%

Changed lines: Changed C/C++ lines covered: 26/26 (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 Sep 14, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). label Sep 14, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing ad0c4f03a with master a78f42eea (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.

Compile time of recompiled translation units

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

Job report

@clickhouse-gh

clickhouse-gh Bot commented Sep 18, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 37 queries analysed

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
  • StressHouse run: 9798eb95-25b2-4352-8e4f-7caf77a1e1b2
  • MIRAI run: fef74949-7816-45e0-af80-dd24c44d0d0b
  • PR check IDs:
    • clickbench_1093287_1789955374
    • clickbench_1093293_1789955374
    • clickbench_1093299_1789955374
    • tpch_adapted_1_official_1093310_1789955374
    • tpch_adapted_1_official_1093320_1789955374
    • tpch_adapted_1_official_1093357_1789955374

@alexey-milovidov alexey-milovidov added the blocker This issue / pr blocks a new release label Sep 20, 2026
alexey-milovidov and others added 2 commits September 20, 2026 21:56
…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]>

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok.

@alexey-milovidov alexey-milovidov self-assigned this Sep 21, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 21, 2026
Merged via the queue into master with commit 03f0b2c Sep 21, 2026
177 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix/limit-by-injective-unwrap-through-group-by-keys branch September 21, 2026 16:13
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 21, 2026
pull Bot pushed a commit to sowelswl/ClickHouse that referenced this pull request Sep 22, 2026
`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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

blocker This issue / pr blocks a new release comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants