Skip to content

Revert "Fix wrong results for plus/minus keys with a non-integer operand" - #120118

Merged
alexey-milovidov merged 1 commit into
masterfrom
revert-117137-fix-injective-plus-minus-type-gate
Sep 15, 2026
Merged

alexey-milovidov merged 1 commit into
masterfrom
revert-117137-fix-injective-plus-minus-type-gate

Conversation

@alexey-milovidov

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

Copy link
Copy Markdown
Member

Reverts #117137, which broke 03710_analyzer_limit_by_aggregate_validation on master.

OptimizeLimitByInjectiveFunctionsPass (setting optimize_injective_functions_in_limit_by, on by default) replaces an injective function in a LIMIT BY key with its argument. Before the reverted change plus over a captured constant answered isInjective with false, so the pass left such a key alone; the change makes it answer true for integer operands. GROUP BY keys are unwrapped by a separate pass, under optimize_injective_functions_in_group_by, which clickhouse-test randomizes off in 5% of runs. With the GROUP BY pass off and the LIMIT BY pass on, the two key lists disagree, and the column the rewritten LIMIT BY key asks for is not in the aggregation output:

SELECT c0 + 1 AS expr FROM t GROUP BY c0 + 1 ORDER BY expr LIMIT 1 BY expr
SETTINGS optimize_injective_functions_in_group_by = 0;

Code: 10. DB::Exception: Not found column __table1.c0 in block plus(__table1.c0, 1_UInt8) Int64 Int64(size = 0). (NOT_FOUND_COLUMN_IN_BLOCK)

Confirmed against the master binaries CI built on either side of the merge: 1f59f0fc6a388c602b98aa33c070734ca952e9ab (before) answers 2, 3, 8055c45c47d9e43774a88940690c0caa88bd4c90 (after) raises. Setting optimize_injective_functions_in_limit_by = 0 on the later binary also makes it pass, which pins the pass.

A re-land has to keep the two passes in agreement: unwrapping a LIMIT BY key is only safe when the same key survives in GROUP BY. Reverting also reopens the two issues #117137 closed.

Master CI: https://play.clickhouse.com/play?color_modes=%7B%22ppm%22%3A%22none%22%2C%22test_name%22%3A%22categorical%22%7D&tab=Failed%20checks#V0lUSCAodGVzdF9zdGF0dXMgTElLRSAnRiUnIE9SIHRlc3Rfc3RhdHVzIExJS0UgJ0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ja0hvdXNlLycpKQogICAgQU5EIHRlc3Rfc3RhdHVzICE9ICdTS0lQUEVEJwogICAgQU5EICh0ZXN0X3N0YXR1cyBMSUtFICdGJScgT1IgdGVzdF9zdGF0dXMgTElLRSAnRSUnKQogICAgQU5EIGNoZWNrX3N0YXR1cyAhPSAnc3VjY2VzcycKT1JERVIgQlkgY2hlY2tfc3RhcnRfdGltZSBERVNDLCBjaGVja19uYW1lLCB0ZXN0X25hbWU7

Related: #117137
Related: #116268
Related: #118729

Changelog category (leave one):

  • CI Fix or Improvement (changelog entry is not required)

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

Version info

  • Merged into: 26.9.1.1507 (included in 26.9 and later)

…operand"

This reverts commit 8055c45, reversing
changes made to 70a1649.

It broke `03710_analyzer_limit_by_aggregate_validation` on `master`.
`OptimizeLimitByInjectiveFunctionsPass` unwraps an injective function in
a `LIMIT BY` key into its argument. Before this change `plus` over a
captured constant answered `isInjective` with `false`, so the pass left
such a key alone; now it answers `true` for integer operands. `GROUP BY`
is unwrapped by a separate pass, so with
`optimize_injective_functions_in_group_by = 0` - which `clickhouse-test`
randomizes in 5% of runs - `GROUP BY` keeps `plus(c0, 1)` while `LIMIT BY`
is rewritten to `c0`, a column the aggregation does not output:

    Code: 10. DB::Exception: Not found column __table1.c0 in block
    plus(__table1.c0, 1_UInt8) Int64 Int64(size = 0). (NOT_FOUND_COLUMN_IN_BLOCK)

Master CI: https://play.clickhouse.com/play?color_modes=%7B%22ppm%22%3A%22none%22%2C%22test_name%22%3A%22categorical%22%7D&tab=Failed%20checks#V0lUSCAodGVzdF9zdGF0dXMgTElLRSAnRiUnIE9SIHRlc3Rfc3RhdHVzIExJS0UgJ0UlJykgQU5EIGNoZWNrX3N0YXR1cyAhPSAnc3VjY2VzcycgQVMgZmFpbCwgSU5URVJWQUwgMjQgSE9VUiBBUyBwZXJpb2QKU0VMRUNUIHVuaXFFeGFjdElmKGNvbW1pd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nKQogICAgQU5EIGNoZWNrX3N0YXR1cyAhPSAnc3VjY2VzcycKT1JERVIgQlkgY2hlY2tfc3RhcnRfdGltZSBERVNDLCBjaGVja19uYW1lLCB0ZXN0X25hbWU7
@clickhouse-gh

clickhouse-gh Bot commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [ad770fc]


AI Review

Summary

This PR reverts #117137 to stop the analyzer LIMIT BY/GROUP BY mismatch that breaks 03710_analyzer_limit_by_aggregate_validation. I do not think the full revert is safe: restoring the old actionsDAGUtils injectivity whitelist reintroduces previously fixed silent wrong-result bugs in the per-partition planning path, even though the failing analyzer path only depends on the query-tree isInjective changes.

Findings

❌ Blockers

  • [src/Processors/QueryPlan/Optimizations/actionsDAGUtils.cpp:667] This restore of the name-based plus/minus/negate/tuple fallback is broader than the regression being reverted. OptimizeLimitByInjectiveFunctionsPass rewrites keys through unwrapInjectiveFunctionsInKeys, which only consults function->isInjective(arguments), so reverting the FunctionBinaryArithmetic{WithConstants,OverloadResolver}::isInjective additions is enough to fix 03710. Reintroducing the DAG-level fallback also reopens the silent wrong-result cases that #117137 fixed for per-partition GROUP BY, DISTINCT, window, and creating-set planning.
    Suggested fix: keep the actionsDAGUtils change from #117137 and narrow this revert to the query-tree isInjective pieces in FunctionBinaryArithmetic.h.
Final Verdict

Status: ❌ Block

  • Narrow the revert so it only disables the analyzer LIMIT BY unwrapping path; do not restore the old actionsDAGUtils whitelist that reopens default-on wrong-result regressions.

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Sep 15, 2026
if (child->type == ActionsDAG::ActionType::COLUMN)
++fixed_args;
static const std::vector<String> injective = {"plus", "minus", "negate", "tuple"};
return (fixed_args + 1 >= node->children.size()) && (std::ranges::find(injective, node->function_base->getName()) != injective.end());

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This part of the revert is broader than the 03710_analyzer_limit_by_aggregate_validation failure it is trying to fix. The analyzer LIMIT BY rewrite only goes through unwrapInjectiveFunctionsInKeys and function->isInjective(arguments) (OptimizeLimitByInjectiveFunctionsPass.cpp, OptimizeKeyExpressionsUtils.cpp), so dropping the FunctionBinaryArithmetic{WithConstants,OverloadResolver}::isInjective changes is enough to stop that mismatch with GROUP BY. Restoring the old name-based fallback here also reopens the silent wrong-result cases from #116268 and #118729 for per-partition GROUP BY, DISTINCT, window, and IN (subquery) planning. Please keep the actionsDAGUtils half of #117137 and narrow the revert to the query-tree isInjective changes.

@clickhouse-gh clickhouse-gh Bot added the comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... label Sep 15, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 15, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing ad770fc2a with master 8d780d797 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 64f327c50; 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

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

Job report

@alexey-milovidov alexey-milovidov self-assigned this Sep 15, 2026
@alexey-milovidov
alexey-milovidov merged commit 45efaa4 into master Sep 15, 2026
59 of 62 checks passed
@alexey-milovidov
alexey-milovidov deleted the revert-117137-fix-injective-plus-minus-type-gate branch September 15, 2026 07:11
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 15, 2026
nikitamikhaylov added a commit that referenced this pull request Sep 15, 2026
Include the merged upstream revert for the `NOT_FOUND_COLUMN_IN_BLOCK`
exception in `03710_analyzer_limit_by_aggregate_validation` when
`optimize_injective_functions_in_group_by` is disabled. Preserve the
complete `TimeSeries` tags-index diff and all existing PR commits.

CI: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=120083&sha=26c00521dd478c40580fdc59b77ddf46d937d8e6&name_0=PR&name_1=Stateless%20tests%20%28amd_debug%2C%20parallel%29
Related: #120118
Related: #120083
harikrishnan94 added a commit that referenced this pull request Sep 15, 2026
The branch was 542 commits behind and CI kept failing on two tests that master
has already dealt with: `05182_join_order_conflict_detector_cast_null_propagation`
pinned away the statistics randomization in #120084, and the `plus`/`minus`
injectivity that made `03710_analyzer_limit_by_aggregate_validation` fail was
reverted in #120118. Re-running could not pick either up, because a re-run
rebuilds the merge ref computed when the run was created.

Related: #120167
Related: #120151

Co-Authored-By: Claude Fable 5.1 <[email protected]>
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

comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... pr-ci 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.

2 participants