Skip to content

Fix wrong results for plus/minus keys with a non-integer operand - #117137

Merged
nihalzp merged 15 commits into
ClickHouse:masterfrom
groeneai:fix-injective-plus-minus-type-gate
Sep 14, 2026
Merged

nihalzp merged 15 commits into
ClickHouse:masterfrom
groeneai:fix-injective-plus-minus-type-gate

Conversation

@groeneai

@groeneai groeneai commented Aug 30, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #116268
Closes: #118729
Related: #114783
Related: #114981

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 when a GROUP BY, DISTINCT, LIMIT BY or window PARTITION BY key was plus or
minus of a partition column with a non-integer constant, for example x + 1.0 on Float64 or
d + INTERVAL 1 MONTH on Date. Such a key was assumed injective, so each table partition was
evaluated independently without the cross-partition merge; where the key collapses distinct values
onto one (float rounding, end-of-month arithmetic, a DST transition) the query returned one row or
window frame per partition instead of one per group. Affects the default-enabled
allow_aggregate_partitions_independently, allow_distinct_partitions_independently,
allow_limit_by_partitions_independently, allow_creating_set_partitions_independently,
allow_window_partitions_independently and optimize_distributed_group_by_sharding_key.

Description

Asked for by @ nihalzp on #114783. isInjectiveFunction decided injectivity from a hardcoded name
list with no type and no value check, bypassing IFunctionBase::isInjective. It fails five ways:

Measured on master, per-partition vs merged
Key expression got expected
d + INTERVAL 1 MONTH (Date, end-of-month collapse) 19 13
d - INTERVAL 123 YEAR (Date, saturation at the type bound, #118729) 18 1
t + INTERVAL 1 DAY (DateTime('Europe/Moscow'), DST) 6 4
f + 1.0 (Float64 near 1e16, rounding) 3 2
x + toDate(0) (constant narrows the result to Date) 6 1
x + toDecimal32(0, 1) (constant rescales the operand) 4 1

With one operand fixed, injectivity is recognized here only for integer operands with an
integer, non-NULL constant: the result type widens, and wrap-around is a bijection.

The fix states that in the function instead of re-deriving it in a query-plan consumer.
FunctionBinaryArithmeticWithConstants already holds both operands and the result type. negate
and tuple declare isInjective themselves, so the list only spoke for plus and minus.
BinaryArithmeticOverloadResolver gets the same predicate, as gtest_functions_stress requires.

Injective expressions are given up, none covered by a test. Date + INTERVAL 1 DAY,
Date + 1 and Decimal64(2) + 1 because every type that would readmit them also readmits a
non-injective row above. Same-type temporal minus (Date - Date, DateTime - DateTime,
DateTime64(s) - DateTime64(s)) and IPv4/IPv6 through their UInt32/UInt128 arithmetic
carrier are separable by type, but the deleted name list was the only injectivity fallback among
the 11 query-layer isInjective call sites, so admitting them here would newly claim injectivity
in the other 10, KeyCondition included.

Making integer plus honest can also unwrap GROUP BY materialize(1) + 1 to an empty key list, which
merged #114981 guards; a backport needs it too. #116828 reports the other branch of this helper
(toString(DateTime), toFixedString), which already goes through isInjective and is not
widened here.


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

Version info

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

groeneai and others added 7 commits August 23, 2026 20:49
…operands

isInjectiveFunction decided injectivity from a hardcoded name list,
{"plus", "minus", "negate", "tuple"}, with no type and no value check, so it
bypassed IFunctionBase::isInjective() entirely and declared Date + INTERVAL 1
MONTH injective exactly like UInt32 + UInt32. removeInjectiveFunctionsFromResults
Recursively then peeled the function off the key, isPartitionKeyFunctionOfKeys
concluded the partition key was functionally determined by the grouping key, and
the cross-partition merge was skipped. Key values that collapse together but live
in different partitions were therefore never merged, and the query returned one
row per partition instead of one per group.

That claim is false in five independent ways, all measured (per-partition vs
merged group count):

  d + INTERVAL 1 MONTH   Date, end-of-month collapse            19 vs 13
  t + INTERVAL 1 DAY     DateTime('Europe/Moscow'), DST          6 vs 4
  f + 1.0                Float64 near 1e16, mantissa rounding    3 vs 2
  x + toDate(0)          constant narrows the result to Date     6 vs 1
  x + toDecimal32(0, 1)  constant rescales the varying operand   4 vs 1

With one operand fixed, plus/minus is injective only for integer operands with an
integer, non-NULL constant: there the result type is widened and even wrap-around
is a bijection.

State that in the function rather than re-deriving it in a query-plan consumer.
IFunction.h documents isInjective as "function could be injective with some
arguments fixed to some constant values" and gives plus(const, x) as its first
example, and FunctionBinaryArithmeticWithConstants already holds both operands,
the constant's column and the result type. Once it answers honestly the name list
has no reason to exist, so isInjectiveFunction collapses to
node->function_base->isInjective({}). Removing negate and tuple from the list is a
no-op: both already report isInjective() == true themselves, which is why they
reached the honest first line before the list was ever consulted. This mirrors
9aa0341, which marked materialize monotonic at the function level and
deleted the same kind of special case from this file.

BinaryArithmeticOverloadResolver gets the same predicate. Without it the resolver
and the built function disagree for the same concrete arguments, which
gtest_functions_stress reports as an error; it caught two real defects here,
first an override that ignored the sample columns it was asked about, then a call
to getReturnTypeImpl, which throws on Nullable and LowCardinality because the
public getReturnType wrapper is what applies those default implementations.

Three injective expressions are given up on, because every type that would
readmit them also readmits one of the rows above and the two cannot be told
apart: Date + INTERVAL 1 DAY (an interval on Date is not separable from one on
DateTime by kind), Date + 1 (a Date operand readmits the narrowing constant) and
Decimal64(2) + 1 (a Decimal operand readmits the rescaling constant). No existing
test depends on any of them, and the new test asserts the declines explicitly
next to a bare-key control, so a lost optimization is distinguishable from a
fixture that never reached the optimizer.

Affects allow_aggregate_partitions_independently,
allow_distinct_partitions_independently, allow_limit_by_partitions_independently,
allow_creating_set_partitions_independently, and the sharding-key check behind
optimize_distributed_group_by_sharding_key. Results were compared base versus
fixed across 20 query shapes covering the other isInjective consumers (uniq
elimination, ORDER BY truncation, KeyCondition index analysis, join-key analysis,
set building, GROUP BY modifiers) and are identical; only plan shape changes,
which is why 02969_analyzer_eliminate_injective_functions.reference is updated.

Co-Authored-By: Claude Fable 5 <[email protected]>
Review round 1.

The changelog entry names five settings that ride the injectivity predicate, but the test only
pinned three. Add arms for the other two.

Per-partition set building shares the entry point in useDataParallelAggregation.cpp, so its arm is a
decline plus an integer-key control on its own table (the collapsing key's table partitions by the
Date column, where an integer key is not a function of the partition key and the arm would never
arm). It gets no value arm: the set fill deduplicates across partitions anyway, so the count, the
set cardinality and a max_rows_in_set probe are identical with and without the optimization on both
builds. The defect there is visible only in the plan.

StorageDistributed is separate code with its own rejection loop and its own call, and it turned out
to be a wrong-results surface of its own: over two shards sharded by toUInt64(toYYYYMMDD(d)),
GROUP BY d + INTERVAL 1 MONTH returned the collapsed key twice, once per shard, because dropping the
merge step leaves each shard's partial group unmerged. It returns one row now. The arm counts
MergingAggregated steps rather than reading Keys: lines, because a single-shard Distributed over a
local table is served by a plain ReadFromMergeTree and emits no Keys: line at all, in either
direction. No bare-key value arm: both remote() shards return the same rows, so a bare key differs
with and without the optimization on both builds, which is the fixture and not injectivity.

Also narrow the resolver's guard to catch (const Exception &) so a throw that is not a ClickHouse
exception is not silently reported as non-injective, and correct the predicate's header comment,
which claimed every non-integer operand class collapses. It does not: some are declined because the
unsafe cases within the class cannot be separated from the safe ones by type.
The distributed arms declared a sharding key but ran the same unfiltered view on
both shards, so every row existed twice and the integer control asserted a merge
drop that doubles the answer under its own fixture. Each view now filters itself
by shardNum(), which also lets that control assert its value for the first time.
The collapsed interval key still spans both shards under the correct layout, so
the regression witness is unaffected.

The predicate is symmetric in the operation and in which operand is constant, but
every preservation arm was a right-constant plus, so narrowing it to that case
would have passed the whole file. Adds a safe-integer minus arm, whose result type
is signed and therefore takes a different branch of the integer test, and two
constant-left arms.

Moving the fact into the function makes plus and minus answer true for integer
arithmetic at five consumers beyond the two the change is about. Three have a
user-visible output and are now armed with both a positive and a non-injective
control: the ORDER BY tail after a covered grouping key is truncated, an ANY OUTER
JOIN whose key is an injective function of the aggregation key converts to INNER,
and an equality atom over an injective key transform stays exact so the
exact-count projection remains available. Each keeps its result identical.

Also states the contract the resolver override actually delivers, since it
declines rather than falling back to captured operands when it is not given both
arguments, and prints the collapse factor the float, narrowing and rescaling arms
depend on so a fixture edit cannot make them agree by accident.
The three ORDER BY-truncation arms assert on EXPLAIN QUERY TREE, which is
analyzer-only: InterpreterExplainQuery throws NOT_IMPLEMENTED when
allow_experimental_analyzer is 0. The test pinned neither the setting nor the
no-old-analyzer tag, so on the CI jobs that install
tests/config/users.d/analyzer.xml those arms would error and redden the whole
file on a cause unrelated to what it tests.

The pin is preferred over the tag because every other arm in the file is
analyzer-agnostic and keeps its coverage under the old analyzer; the tag would
skip the file entirely there. It is a no-op wherever the analyzer is already on,
which is why the reference does not move.
allow_window_partitions_independently arrived after this branch was written, in
ClickHouse#114783 (ec46c0e), so the window consumer of isPartitionKeyFunctionOfKeys
had no arm of its own. It has one now, in the test file that already covers the
aggregation, DISTINCT, LIMIT BY, set-building and sharding-key consumers.

The carrier is Date + INTERVAL 1 MONTH rather than the float shape issue ClickHouse#116268
reports, because a floating point partition key is rejected outright (Code: 36),
so a float carrier has to reach its partition through an integer valued
indirection such as toInt64(x * 1e21), and that shape never satisfies
isPartitionKeyFunctionOfKeys. Measured on a pre-fix build, every line of the
float window arm is identical with and without this change, including a bare
column control, so it would have asserted nothing. A Date is a legal partition
key and needs no indirection. The float half of that issue is a GROUP BY, does
reproduce, and is covered by the existing t_float arms.

Measured on a pre-fix build of master, the forced arm and the arm that sets
nothing at all both return three distinct window counts where one is correct, and
both plan tokens the optimization prints read 1; with this change all three value
arms return a single count and both tokens read 0. The arm that sets no setting
matters most: the cost heuristic accepts these 39 partitions at the max_threads
the file already pins, so the wrong answer needs no opt in. The integer control
next to it is unchanged in every arm, which is what attributes the section to the
operand type rather than to the fixture or the window shape. Both plan tokens are
asserted because the change has to decline at both decision sites, the
per-partition read request and the scatter skip above it.

The reference line for the empty key arm is no longer red. It asserted the value
that needs the guard from ClickHouse#114981, which merged as ab9ebb0 and arrives
here through a master merge, so the whole file now passes as committed, 50 runs
out of 50, with no reference edited.

For the record, the precedent for deleting a name based injectivity list in this
helper is 9aa0341 (Nikolai Kochetov), which did exactly this for
materialize.

Co-Authored-By: Claude Opus 5 <[email protected]>
…valuation

The stateless CI server installs tests/config/users.d/limits.yaml into the default
profile unconditionally (install.sh:287), and it sets max_rows_to_group_by,
max_rows_to_sort and max_bytes_to_sort to 10G. A nonzero value of any of them does
not merely constrain the optimization this test is about, it disables it outright:
useDataParallelAggregation.cpp:156 returns early unless max_rows_to_group_by is 0,
applyStreamDisjointness.cpp:157 requires the same, and both the per-partition
window read (useDataParallelAggregation.cpp:269) and the scatter skip
(applyStreamDisjointness.cpp:185) require an empty SizeLimits, which
SortingStep.cpp:153 builds from exactly the two sort limits.

So the file had two defects in CI that it does not have on a bare server. The two
t_win_int marker arms assert that both window plan tokens read 1, and under the
profile they read 0, which fails the test. Less visibly, all seven GROUP BY
correctness arms were vacuous: the optimization never ran, so both halves of each
pair printed the merged count whether this change was present or reverted.

Measured on a server built with tests/config/install.sh, with the profile observed
in force on a fresh connection, probing each arm group with an injective integer
key so the optimization fires unless something suppresses it. Before these three
pins both GROUP BY markers and both window markers count 0; after them all four
count 1. Deleting the three pins again reddens exactly the two window marker arms
and nothing else. LIMIT BY, the set building arms and the sharding key arms have no
suppressor, measured at the profile's values rather than argued. Intersecting the
93 settings the installed users.d files place in a profile with the 117 read by the
seven plan and optimizer files that gate these paths leaves ten candidates: these
three, the two max_rows_in_distinct pins the file already had for the same reason,
and five that are not binding here (a 20M read limit against a 5100 row fixture, a
1000 stream clamp against 8 partitions, two read pool selectors, and initiator side
distributed index analysis).

Query level SET beats profile injection, which is why this is three SET lines
rather than a no-random-settings tag. The serialized plan path takes the same
values through QueryPlanSerializationSettings (SortingStep.cpp:196 to :177), so the
pins hold with serialize_query_plan = 1 as well.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Aug 30, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review - 7 review rounds, 6 independent gate passes

Every finding below was raised by an independent reviewer or a second model against this diff,
then adjudicated against the code. AGREE means it was fixed in this PR; DISAGREE carries the
measurement that refutes it.

# Finding Verdict
❌ GROUP BY materialize(1) + 1 unwraps to an empty key list and stops aggregating AGREE - this is why the PR waits on #114981, which adds the guard; not worked around here
❌ the stateless CI profile sets max_rows_to_group_by to 10G, and a nonzero value disables independent aggregation outright, so all seven wrong-results witnesses would have passed in CI with the fix reverted AGREE - the test now pins the limit to 0 and the arms were re-executed with that profile installed
❌ the same profile sets max_rows_to_sort / max_bytes_to_sort to 10G, which disables per-partition window reading and the scatter skip, so the two integer window controls asserted plan markers CI cannot produce AGREE - both limits pinned to 0; removing the pins is the negative control that reddens those arms
⚠️ the two remote shards ran the same unfiltered view, so the distributed arms did not describe a real shard layout AGREE - views now filtered by shardNum(), and the integer control gained the value assertion the old fixture could not support
⚠️ every keep-firing arm was right-constant plus, so half the implemented contract (minus, constant-left) had no preservation arm AGREE - arms added, liveness proved by narrowing the predicate and confirming they go silent
⚠️ moving the fact into isInjective flips the answer at five consumers beyond the two described AGREE - enumerated all 12 call sites, measured the reachable ones, armed those that discriminate
⚠️ catch (...) in the resolver override swallowed LOGICAL_ERROR in release builds AGREE - narrowed to catch (const Exception &)
⚠️ the changelog named five settings but the test pinned three AGREE - the creating-set and distributed consumers now have their own arms
⚠️ the new EXPLAIN QUERY TREE arms would error on old-analyzer jobs, where that statement is not supported AGREE - the test now pins enable_analyzer = 1
⚠️ the changelog entry named a DST fall-back, but the collapse the fixture measures is a spring-forward: Moscow's 2010 transition is 03-28 02:00 to 03:00, so 02:00 and 02:30 do not exist on the target day and clamp together, 6 distinct sources to 4 results AGREE - restated as a DST transition, accurate in either direction
⚠️ a backport to a release branch without #114981 compiles and resolves cleanly but re-opens the empty-key path AGREE - the description now says the backport needs #114981 too
💡 the "must agree" comment on the resolver override asserted more than the code delivers AGREE - reworded to the actual contract
💡 the Float64 arm's expected value was a rounding artifact a fixture edit could silently make vacuous AGREE - the pre-collapse cardinality is now printed
💡 the predicate's header comment overclaimed that every non-integer class collapses AGREE - restated as recognition scope
💡 the description wrote IFunctionBase::isInjective(), and did not say what happened to negate and tuple when the name list was deleted AGREE - parentheses dropped per the repository style rule, and the description now states that both already declare isInjective themselves
💡 isInjectiveFunction passes {}, so the resolved function answers from the operands captured at build() rather than from the node's children; KeyCondition builds its sample columns from the children instead DISAGREE, noted as a possible later simplification - not reachable: the only mutation that rewires a surviving FUNCTION node's children is ActionsDAG::mergeInplace, and it substitutes INPUT children only; a header's const-ness is derived by running the producing DAG, so it cannot disagree with it, and ActionsDAG::split's in-place write retypes the node to ALIAS
💡 the catch (const Exception &) in the resolver override is a fallback path the repository style rule discourages DISAGREE - false is the documented answer for "no information" (IFunction.h), so an undecidable input forgoes an optimization rather than substituting behaviour; and it is unreachable, since all three resolver-level callers pass no arguments and the override declines before the try

The three ❌ rows are settled by measurement rather than inspection. The server was built with an
unflagged tests/config/install.sh (25 users.d, 100 config.d), the profile was read back on a
fresh connection with none of the test's SETs applied (all three limits 10000000000,
changed=1), and both test files then passed against the references exactly as committed. Deleting
only the three new SET lines reddens exactly the two t_win_int marker arms and nothing else.
Each arm group was additionally probed with an injective integer key, to show which of them the
profile had been suppressing, and the 93 settings the profile carries were intersected with the 117
read by the seven plan and optimizer files that gate these paths, leaving no unaccounted suppressor.

One earlier claim of mine was wrong and is corrected in the record: an initial round asserted the
distributed sharding-key consumer only gained coverage and was never wrong on master. It is
wrong on master - the collapsed key leaves each shard's partial group unmerged, so the same key is
returned twice. The PR body already listed that setting as affected, so the correction strengthens
the claim rather than changing it.

@groeneai groeneai added the groeneai-origin-request PR origin: a maintainer pinged or directed groeneai label Aug 30, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 30, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [aaf9acd]

Summary: ✅


AI Review

Summary

This PR correctly fixes the wrong-results bug from treating non-integer plus and minus partition/sharding keys as injective, and the new stateless coverage is thorough across the affected optimizations. The remaining issue is that the new function-level predicate is still narrower than the old behavior for two separable safe families, so it regresses existing optimization coverage on master even though those mappings stay injective.

Findings

⚠️ Majors

  • [src/Functions/FunctionBinaryArithmetic.h:3719] [dismissed by author -- https://github.com/Fix wrong results for plus/minus keys with a non-integer operand #117137#discussion_r3937338580] The new integer-only gate still turns same-type temporal subtraction (Date - Date, DateTime - DateTime, DateTime64 - DateTime64) from injective into non-injective even though a fixed temporal operand preserves a one-to-one mapping. That drops the existing per-partition and sharding-key optimizations for a query shape that already worked on master, so this is a real performance regression, not just a missed new optimization.
    Suggested fix: either admit the separable same-type temporal minus family in plusMinusWithConstantsIsInjective and add focused coverage for the newly reached consumers, or keep the function-level helper intentionally narrow and restore the old actionsDAGUtils-only fallback for this family so the regression stays out of master.

  • [src/Functions/FunctionBinaryArithmetic.h:3719] [dismissed by author -- https://github.com/Fix wrong results for plus/minus keys with a non-integer operand #117137#discussion_r3950089842] IPv4 and IPv6 arithmetic is executed through unsigned integer carriers, but the new gate checks the original operand types and therefore answers false for ip +/- const even when the mapping stays bijective. That silently removes the same injective-key optimizations this PR preserves for plain integers (GROUP BY, per-partition DISTINCT/LIMIT BY, sharding-key aggregation) on existing IP queries.
    Suggested fix: treat IPv4/IPv6 through their arithmetic carrier here, with cross-consumer tests matching the integer cases, or keep the broader function-level claim out of these types by restoring the historical fallback only where it was already in use.

Final Verdict

The wrong-results fix itself looks sound, but I would still keep the review in a non-green state until the two measured false-negative regressions above are either restored or intentionally isolated from the new function-level isInjective contract.

LLVM Coverage Report

Measured on commit aaf9acd.

Metric Baseline Current Δ
Lines 88.80% 88.80% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.20% 81.20% +0.00%

Changed lines: Changed C/C++ lines covered: 17/18 (94.44%) · 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 30, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Every arm pins force_*_partitions_independently = 1 against allow_*_independently = 0, so nothing depends on randomization or on the default split engaging: d + INTERVAL 1 MONTH gives 19 groups per-partition vs 13 merged, on demand, every run.
b Root cause explained? Yes. isInjectiveFunction (actionsDAGUtils.cpp:553-564) declared plus/minus injective from a name list with no type and no value check, bypassing IFunctionBase::isInjective(). removeInjectiveFunctionsFromResultsRecursively then peeled the function off the key, isPartitionKeyFunctionOfKeys concluded the partition key was determined by the key, and the cross-partition merge was skipped, so collapsed values living in different partitions were never merged.
c Fix matches root cause? Yes. The injectivity fact moves into the function that owns it (IFunction.h names plus(const, x) as its first example) and the name list is deleted, following 9aa0341d899ac90 which did the same for materialize in this file. No setting, no guard at the symptom site; the helper loses 9 lines.
d Test intent preserved / new tests added? New 04833_injective_plus_minus_type_gate.{sql,reference}: 13 correctness arms, 9 preservation arms (both operations, both operand positions), 5 declined arms each with a positive control, 3 empty-key arms, 3 per-partition set-building arms, 6 distributed sharding-key arms over a real shardNum()-filtered layout, 3 newly-reached-consumer sections (ORDER BY truncation, ANY OUTER to INNER conversion, key-condition exactness) each with a positive and a non-injective control, and a window section for allow_window_partitions_independently (arming witness, forced / disabled / default-settings value arms, both plan-level EXPLAIN tokens, integer control). No test weakened or deleted, no no-parallel tag. 02969_analyzer_eliminate_injective_functions.reference updated for a plan-dump-only change whose data lines were verified byte-identical on both builds. The arms are live under the real stateless CI settings profile, not just on a bare server: the profile's max_rows_to_group_by / max_rows_to_sort / max_bytes_to_sort = 10G (tests/config/users.d/limits.yaml, installed unconditionally at install.sh:287) each disable a per-partition path outright, so the test pins all three to 0 alongside the two max_*_in_distinct pins it already had. Verified by running the committed test against a server built with tests/config/install.sh, with the profile observed in force on a fresh connection; deleting the three pins reddens the two window marker arms.
e Both directions demonstrated? Yes, base vs fix on the same fixture and server config: the full test yields 36 attributed value disagreements. Nine correctness arms flip (19/13 -> 13/13, 6/4 -> 4/4, 3/2 -> 2/2, 6/1 -> 1/1, 4/1 -> 1/1); the set-building arm wrongly fires on base and declines on the fix; the distributed interval pair reads 0/0 on base and 1/1 on the fix while its integer control is unchanged; the three newly-reached consumers read 2 / 0 / 0 on base and 1 / 1 / 1 on the fix. The two-column x + y contrast arm agrees on both (109/109); every preservation plan-line pair is byte-identical; the declined arms stop firing while their controls keep firing. Because the preservation arms cannot be proved by a base A/B (base is over-permissive), liveness was proved with a deliberately narrowed probe build: the pre-existing right-constant plus arm keeps printing while all three new minus / constant-left arms go silent. The window section was A/B'd the same way against a pre-fix master build: its forced arm and its default-settings arm each return 100, 200, 300 before the fix and a single 300 after, and both plan tokens read 1 before and 0 after, while every integer-control arm reads identically on both. Both directions also hold under the CI settings profile and, separately, with serialize_query_plan = 1.
f Fix is general across code paths? Yes, and the surface was enumerated rather than assumed: the 11 decision sites among the 17 isInjective call sites were read individually (the other 6 are the unrelated IDictionary overload and the stress gtest). Fixing the function reaches the five settings behind isPartitionKeyFunctionOfKeys; four have committed arms and the fifth, allow_window_partitions_independently, now has its own window section rather than a by-construction claim - on a pre-fix binary that section's forced arm and its default-settings arm both return three distinct window counts instead of one, and both plan tokens (Read each partition through separate port, Skip scatter by partition) fire, while its integer control is unchanged in every arm. The separate direct caller StorageDistributed.cpp:652 (optimize_distributed_group_by_sharding_key) has its own arms - it is a wrong-results surface in its own right: over two shards sharded by toUInt64(toYYYYMMDD(d)), GROUP BY d + INTERVAL 1 MONTH returned the same key twice before the fix and once after, because each shard's partial group for the collapsed key was emitted unmerged. Five further consumers newly answer true for the integer case; each was judged sound and the three with a user-visible output are armed (TruncateOrderByAfterGroupByKeysPass, convertOuterJoinToInnerJoin, KeyCondition exactness), four are unreachable behind arity guards, and ExpressionJIT forwards its members' answers rather than deciding. Both plus and minus, both operand positions.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. Wrapper matrix covers Nullable(T), LowCardinality(T) and LowCardinality(Nullable(T)), stripped as removeNullable(recursiveRemoveLowCardinality(t)) because the other order is a no-op on LC(Nullable(T)). Widths UInt32, Int64, Int128, UInt256. Boundary cases measured: integer wrap at the type bound is a bijection, Date + 60000 does not saturate. The NULL leg is tested both ways: a NULL constant declines, a Nullable column keeps the optimization.
h Backward compatible? (maintainer-approved exception only) Yes. No setting added, no default changed, no serialization format touched, so no SettingsChangesHistory.cpp entry. The change is an unsound optimization ceasing to fire. Three injective expressions are deliberately given up on (Date + INTERVAL 1 DAY, Date + 1, Decimal64(2) + 1), each because the type that would readmit it also readmits a measured wrong-results case; each breaks zero existing tests, and the test asserts the declines explicitly.
i Invariants and contracts preserved? Yes. isInjective is a const query with no state, so no lifetime, concurrency or error-path obligation. The one real contract risk was resolver-versus-resolved agreement, which gtest_functions_stress.cpp:2127-2136 enforces: it failed twice during this work and now passes with zero isInjective mismatch reports, with plus/minus absent from its unexpected_error and broken_injectivity lists. Both overrides return false on any input they cannot decide, so an undecidable case can never re-open the bug, and the resolver narrows its guard to catch (const Exception &) so a non-ClickHouse throw is not silently reported as non-injective.

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @Ergus @CurtizJ, could you review this? isInjectiveFunction declared plus and minus injective from a hardcoded name list with no type check, so a key like d + INTERVAL 1 MONTH was assumed injective and each MergeTree partition was evaluated without the cross-partition merge, returning one row per partition instead of one per group. The fact now lives in FunctionBinaryArithmeticWithConstants::isInjective, which recognizes integer arithmetic with a non-NULL integer constant and nothing else.

@nihalzp nihalzp self-assigned this Aug 30, 2026
`Fast test` failed on `04058_explain_pretty_aggregation_sorting`: for
`GROUP BY a + 1` on a `UInt64` column the plan prints `Keys: a` where the
reference expected `Keys: a + 1`. That is this change taking effect. Once
`FunctionBinaryArithmeticWithConstants` reports integer `plus` with an
integer constant as injective, `optimize_injective_functions_in_group_by`
drops it from the key, the same rewrite this branch already recorded in
`02969_analyzer_eliminate_injective_functions.reference`. `x + 1` on
`UInt64` is a bijection, so the groups are unchanged and the `SELECT` list
still computes `a + 1` from the grouped column.

Measured against a pre-fix binary built from this branch's merge base
9593cfa under the same settings profile:
the query returns a byte-identical result set on both arms, and over rows
holding 0, 1, 2^64-2 and 2^64-1 both spellings give the same four groups
with the same counts, so wrap-around merges and splits nothing. The new
line fails on the pre-fix arm with the inverse diff, so it pins the new
behaviour instead of accepting either.

Unlike the old one, the new line is settings-dependent, so two pins are
added in the header's existing style. The pass returns early for
`optimize_injective_functions_in_group_by = 0`, which the stateless runner
picks 5% of the time, and for `group_by_use_nulls = 1`, which the stress
script sets on every odd worker. Injecting either through `--client-option`
reverts the line without the pins and is defeated by them; 50 randomized
runs of the test are green. `02969` is deliberately left alone: measured,
`master`'s own reference for it already fails under `group_by_use_nulls = 1`,
that setting is not in the stateless runner's randomization list, and CIDB
records no stress failure for it in 90 days, so that gap is pre-existing and
not this change's to close.

Of 560 candidate tests, every stateless test whose reference carries a
plan or query-tree `plus`/`minus`/`negate` node plus every test that
combines `EXPLAIN` with integer arithmetic, this is the only one whose
verdict differs between the two arms.

Co-Authored-By: Claude Opus 5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Aug 30, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing aaf9acde8 with master 53a05837c (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

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

Job report

`Stateless tests (amd_debug, flaky check)` and `(amd_binary, flaky check)` failed
on `04833_injective_plus_minus_type_gate` with `Test runs too long (> 180s). Make
it faster.` All 13 legs failed and the fastest was 215.6s, so no re-run can pass.
The gate is per test FILE (`tests/clickhouse-test:3630-3634`, with
`TEST_MAX_RUN_TIME_IN_SECONDS` at `:207`), so splitting removes no assertion.

Cause: the flaky check enables the thread fuzzer
(`ci/jobs/functional_tests.py:982` calling `enable_thread_fuzzer_config`), which
sleeps on every `pthread_mutex` lock and unlock. Under it the cost is dominated by
`INSERT` at about 0.56s per part created, so the four fixtures that build 39
one-day partitions cost 19-25s each; the failing legs' own `query_log.tsv.zst`
accounts for 208s of the 220s median run. That also explains the inverted
ordering: the sanitizer legs are 5-9x faster (`amd_tsan` 24.5s, `amd_msan` 41.1s)
because their own pthread interception defeats the fuzzer's hooks.

Split three ways along the consumers exercised, with no arm changed:

    04833 ..._type_gate                      aggregation, DISTINCT, LIMIT BY
    05053 ..._type_gate_sets_shards_windows  set building, sharding key, window
    05054 ..._type_gate_plan_shape           preservation, narrowings, others

Each part is a byte-identical slice, so every arm keeps its query text and its
expected value and no reference was regenerated. Audited mechanically: the 180
(echoed query, result) pairs are preserved with 0 missing and 0 extra; every
echoed source line lands in exactly one part, the only gain being the
`-- { echo }` banner twice; each part creates, uses and drops only its own tables.
On the pre-fix binary at this branch's merge base every part FAILS and its 44
differing reference lines are the same multiset as the single file's, so the
mutation footprint is preserved per file, which `Bugfix validation` needs because
it inverts FAIL and OK.

Measured on one debug binary with the fuzzer on, solo, two interleaved rounds with
the pre-split file re-run as the baseline: the single file took 612.4s and 658.8s,
the parts 224.7/229.6/187.8s and 235.0/235.9/194.0s. The worst part share is
37.5%, which against the failing leg's measured maximum of 233.8s predicts 88s, a
2.05x margin. The parts sum to 1-5% above the single file, so this buys the
per-file budget and leaves total suite cost essentially unchanged. Also 250/250
across 50 randomized runs of all five changed tests.

Rejected: `-- Tags: long` clears the gate but also divides `--test-runs` by ten
(`tests/clickhouse-test:4457-4482`), which hides the signal on a brand new test;
`no-flaky-check` removes the only mode that enforces the ceiling; trimming row
counts saves nothing, because the cost is per part created and the arms' expected
values are those counts.

Three settings are dropped from a part only where they are provably inert:
`distributed` where the part has no `remote` arm, since
`ci/jobs/functional_tests.py:157` and `ci/jobs/fast_test.py:385` both always pass
`--shard`; `explain_query_plan_default` where the part has no `EXPLAIN`; and
`allow_suspicious_low_cardinality_types` where it has no `LowCardinality` table.

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 754e68d387405fc12737e61e8c4c7278c63becb2

CI has finished on this head. Every failure below has an owner: a fixing PR, or a full-effort fix
task whose fixing-PR link will be posted here when it opens.

Check / test Reason Owner / fixing PR
Upgrade check (amd_release) (job-level verdict) carries the two rows below; no independent failure of its own #117172 (ours, open)
Upgrade check (amd_release) / Cannot start clickhouse-server CI harness on master, not this diff: tests/config/install.sh links silk.xml unconditionally, so the previous-release server rejects enable_silk_runtime with Code: 137 ... UNKNOWN_ELEMENT_IN_CONFIG and never starts #117172 (ours, open)
Upgrade check (amd_release) / Check failed the same job-level abort row, sharing one task_url #117172 (ours, open)
Stress test (amd_debug) / Logical error: Join is supported only for pipelines with one output port, got 2 and 1 (STID 4488-4e11) pre-existing trunk defect. The stack resolves the throw to QueryPipelineBuilder.cpp:373 inside QueryPipelineBuilder::joinPipelinesYShaped, reached from JoinStep::updatePipeline at JoinStep.cpp:159: when primary-key sharding is planned but the two join sides end up with different stream counts, the fallback rejects the pipeline #109393 (ours, open)

All other 166 check runs on this head pass. Config Workflow, Style check and Finish Workflow
are all success, so this is a real run rather than a dropped one. Both earlier PR-caused reds on
this PR (the Fast test failure and the flaky-check 180 s overrun) are fixed and no longer present.

Neither remaining failure is caused by this diff:

  • The Upgrade check condition is fleet-wide, with a clean onset on 2026-08-30 13:48:57Z shortly
    after v26.8.1.2041-lts became the previous release. Measured over three days it is 80 rows across
    79 distinct pull requests with zero true-master runs.
  • The Join ... one output port signature first appears on 2026-06-17, more than two months before
    this branch existed, and over 30 days it is 42 rows across 39 distinct pull requests including
    three true-master runs
    , so it reproduces without any pull request. Its carriers include
    documentation-only and compression-default changes that touch no query-planning code, which is why
    it is not attributable to the plan-optimization change here. This PR contributes exactly one row.

Counts are given rather than links to avoid cross-referencing unrelated pull requests.

Report:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=117137&sha=754e68d387405fc12737e61e8c4c7278c63becb2&name_0=PR&name_1=Stress%20test%20%28amd_debug%29

Session id: cron:our-pr-ci-monitor:20260830-200000

auto is_integer_type = [](const DataTypePtr & type)
{ return type && isInteger(*removeNullable(recursiveRemoveLowCardinality(type))); };

if (!is_integer_type(left.type) || !is_integer_type(right.type) || !is_integer_type(return_type))

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.

IPv4/IPv6 get normalized to UInt32/UInt128 for plus/minus in both getReturnTypeImplStatic and executeImpl2, so ip +/- const is still injective in the varying argument. This integer-only gate now answers false for those keys because the original operand type is IPv4/IPv6, which silently drops the same injective-key optimizations this PR preserves elsewhere (GROUP BY, per-partition DISTINCT / LIMIT BY, sharding-key aggregation). Please treat IP types through their arithmetic carrier here as well, and add a focused preservation arm.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Measured this against both binaries before answering, and the fact holds. The types are the same on
master and at this head: IPv4 +/- int is UInt64/Int64, IPv4 - IPv4 is Int64, IPv6 +/- int
is UInt128/Int128. IPv6 keeps the carrier width instead of widening, so it wraps:
ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff + 1 is 0 and - 1 is -2, which is a bijection, not a
collapse. Over sets of 1000 values at each end of both domains, uniqExact is 2000 of 2000 for
ip + 1, ip - 1, ip - toIPv4('255.255.255.0'), ip6 + 1, ip6 - 1, ip6 - toIPv6('ffff::')
and ip6 + toUInt256(1), and 256 of 256 for a UInt8 column plus an IPv6 constant. The negative
control toUInt32(ip) % 3 gives 3 of 1000.

The loss is real and narrower than stated. Counting Skip stream merging and Read each partition through separate port in EXPLAIN actions = 1, master to this head:

  • per-partition DISTINCT: ip + 1 2 to 0, ip - toIPv4('0.0.0.1') 2 to 0, ip6 + 1 2 to 0
  • per-partition GROUP BY (allow_aggregate_partitions_independently): ip + 1 1 to 0
  • controls: DISTINCT/GROUP BY on the partition expression stay at 2 and 1, the integer arms stay
    optimized, and toUInt32(ip) % 3 prints nothing on either binary

The query-tree consumers never had it. ORDER BY ip + 1 after GROUP BY ip keeps 2 SORT nodes on
both binaries and the plus node in a GROUP BY ip + 1 key survives on both, while the integer arms
went 2 to 1 here. So actionsDAGUtils::isInjectiveFunction, that is useDataParallelAggregation and
the StorageDistributed sharding key, is the whole of what the deleted name list served.

One correction to my own earlier reasoning, which grouped IP with Date and Decimal: the IP class
is cleaner than those. plus/minus reject IntervalDay, Date, DateTime, Float64, Decimal,
Enum8, UUID, FixedString, Time and IPv4-with-IPv6 operands with Code: 43, so an IP arm
cannot readmit a non-injective row the way a Date operand readmits Date + INTERVAL 1 DAY. The only
degenerate partner is a NULL constant, and Nullable(Nothing) is already rejected by the integer
return type.

I am still leaving it out of this PR. On master the other 10 isInjective call sites answer false for
IP, so this is an extension past the deleted list rather than a restoration of it, and KeyCondition
index analysis and the JIT would each need their own validation. The PR also carries
v26.8-must-backport now, so whatever sits here ships into a stable release as part of a
wrong-results fix.

If it is wanted, it is one follow-up covering both separable families, this one and same-type temporal
minus from the thread above, with preservation arms across the Nullable and LowCardinality
wrapper matrix. The description now names both. Otherwise the gate stays integer-only.

@nihalzp

nihalzp commented Sep 8, 2026

Copy link
Copy Markdown
Member

@groeneai 04833_injective_plus_minus_type_gate.sql timed out in the sync PR. Consider adding long tag or trimming the test.

Both files build two tables of 39 one-day partitions from 3900 rows, and the
runtime of a stateless test of this shape is dominated by the number of data
parts each INSERT creates, not by the row count. 04833 timed out in the private
sync run; 05053 carries the same two fixtures and the same cost.

Two non-leap years of January 29-31 give the identical collapse (three
partitions per year mapping to one key) with 6 partitions and 60 rows instead
of 39 and 3900, so the arms keep their discriminating power:

- every arm that detects the missing type gate still detects it. On a pre-fix
  binary 04833 differs from its reference on 18 lines and 05053 on 14, the same
  arms and the same counts as before the trim; only the magnitudes shrink
  (per-partition 6 against merged 2, where it was 39 against 13).
- the cost heuristic still accepts both fixtures: 6 partitions is above
  max_threads / 2 = 4, and 10 rows per partition is below twice the average
  (60 / 8), so the arms that deliberately do not force the optimization keep
  reaching it.

Measured on one debug build with the flaky-check thread fuzzer armed, one test
at a time: 04833 185.2s to 109.4s, 05053 211.2s to 115.5s. 05054, which is not
touched, moves 188.4s to 186.8s over the same rounds.
@groeneai

groeneai commented Sep 8, 2026

Copy link
Copy Markdown
Collaborator Author

Trimmed, in aaf9acd. I did not add long: it clears the 180s gate, but it also divides the flaky check's --test-runs by ten, which removes the repetition that check exists for.

What costs time in these files is the number of data parts each INSERT creates, not the row count: under the flaky-check thread fuzzer an INSERT costs roughly 0.8s + 0.56s per extra part (fitted earlier from the failing legs' own query_log). Both files built two tables of 39 one-day partitions out of 3900 rows. Two non-leap years of January 29-31 produce the same collapse, three partitions per year mapping to one key, with 6 partitions and 60 rows, so 04833 goes from 107 parts to 41 and 05053 from 102 to 36. I trimmed 05053 as well because it carries the same two fixtures at the same cost (81.0s against 04833's 84.8s in the slowest CI leg at the previous head), so it would have reached you next.

Measured on one debug build with the fuzzer armed, one test at a time:

test before after
04833_injective_plus_minus_type_gate 185.2s 109.4s
05053_injective_plus_minus_type_gate_sets_shards_windows 211.2s 115.5s
05054_injective_plus_minus_type_gate_plan_shape (untouched control) 188.4s 186.8s

Negative control, both trees run against pre-fix master (794800200): before the trim 04833 differed from its reference on 18 lines across 9 arms and 05053 on 14; after the trim, 18 and 14 again, the same arms. So every arm that catches the missing type gate still catches it, and only the magnitudes shrink: per-partition 6 against merged 2, where it was 39 against 13. The LIMIT 1 BY arm is one of the 9. The cost heuristic still accepts both fixtures (6 partitions is above max_threads / 2 = 4, and 10 rows per partition is below twice the average), so the arms that deliberately do not force the optimization still reach it.

If this is not enough, one line from the sync log would help: the public legs run 04833 in 0.5-1.9s without the thread fuzzer and 81-85s with it, so a per-test timeout there rather than the 180s limit would point at a per-part cost in that environment. Cutting parts is the right lever either way, and I can cut further.

@groeneai

groeneai commented Sep 9, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - aaf9acd

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (arm_asan_ubsan, azure, sequential) / 04648_distributed_plan_task_error_propagation flaky, master-wide since 2026-09-06: the recorded CANNOT_SCHEDULE_TASK (439) is lost on the way out and the client is given POCO_EXCEPTION (1000) instead #118417 (external, open), plus #118390 (mine, open)
Stateless tests (arm_asan_ubsan, azure, sequential) / 04340_distributed_plan_status_reenqueue_fault cascade of the row above inside the same job: 04648 is a .sql test, so it stops at that unexpected error before reaching its own SYSTEM DISABLE FAILPOINT distributed_plan_record_failure_while_starting_tasks, the fail point stays armed server-wide, and 04340 then never starts a task and prints reenqueue fault handled: 0 #118863 (external, open), which documents this exact cascade, plus #118417 (external, open) upstream of it

PR is the workflow aggregator of the two rows above and carries no failure of its own.

Neither test is reachable from this diff, which is confined to the isInjectiveFunction name list, the integer gate in FunctionBinaryArithmetic.h and two stateless test files. Both failures reproduced 0 out of 3 reruns in the same job, and the pair is a master-wide regression: on 2026-09-08 alone CIDB records 7 and 2 true-master hits across 33 and 28 distinct pull requests.

Session id: cron:our-pr-ci-monitor:20260909-033114

@nihalzp
nihalzp added this pull request to the merge queue Sep 14, 2026
Merged via the queue into ClickHouse:master with commit 8055c45 Sep 14, 2026
344 of 345 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 14, 2026
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Sep 14, 2026
@robot-clickhouse robot-clickhouse added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Sep 14, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

@groeneai @nihalzp — ClickGap found the following in this PR:

Close anything that's wrong or already addressed.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Checked it. The finding is real and still reproduces on master 2615840f763d5, but it does not belong to this PR: the claim comes from FunctionConvert::isInjective in FunctionsConversion.h, which this PR did not touch, and the site this PR rewrote only forwards it.

It is also already tracked (#116931, plus #116828 and #116935 for two more consumers) and already being fixed by #117238, which I applied on top of current master to confirm that it turns the reproducer green. So there is nothing to change here.

Details, including one correction to the suggested fix and a confirmed fifth consumer (ANY LEFT JOIN becoming ALL INNER JOIN in convertOuterJoinToInnerJoin.cpp:119), are on #120106. I am not closing that issue, since master is still affected.

alexey-milovidov added a commit that referenced this pull request Sep 15, 2026
Edited following .claude/skills/edit-changelog/SKILL.md. Manual catch-up run of
the NightlyChangelog edit step, verified with `verify_edit` of
`ci/jobs/changelog_nightly.py`.

Changelog-revert: 119284 119279 Revert "Revert "Print file offsets in the bare fatal stack traces and build the release binary as PIE""
Changelog-revert: 120118 117137 Revert "Fix wrong results for `plus`/`minus` keys with a non-integer operand"
Changelog-revert: 120119 119305 Revert "Convert `OUTER` join to `INNER` join by null-rejecting join conditions" again
Changelog-deleted-entry: 114817 [Performance Improvement] [section] * Convert `OUTER JOIN` to `INNER JOIN` when a later `JOIN` condition filters out its `NULL`-extended rows, and filter `NULL` join keys directly at the table scan when column statistics show it is selective. Only conditions of the form `expr1` OP `expr2` are considered, where OP is one of `=`, `<`, `<=`, `>`, `>=`. Each side can be a column or an expression that propagates `NULL`s. Controlled by the new settings `query_plan_derive_not_null_filters_from_joins` (enabled by default), `query_plan_allow_derived_not_null_filters_execution` (enabled by default) and `query_plan_max_selectivity_for_not_null_filters_execution` (0.7 by default). [#114817](#114817) ([Hechem Selmi](https://github.com/m-selmi)). [#119305](#119305) ([Alexey Milovidov](https://github.com/alexey-milovidov)).
Changelog-deleted-entry: 117137 [Bug Fix (user-visible misbehavior in an official stable release)] [section] * Fix wrong results when a `GROUP BY`, `DISTINCT`, `LIMIT BY` or window `PARTITION BY` key was `plus` or `minus` of a partition column with a non-integer constant, for example `x + 1.0` on `Float64` or `d + INTERVAL 1 MONTH` on `Date`. Such a key was assumed injective, so each table partition was evaluated independently without the cross-partition merge; where the key collapses distinct values onto one (float rounding, end-of-month arithmetic, a DST transition) the query returned one row or window frame per partition instead of one per group. Affects the default-enabled `allow_aggregate_partitions_independently`, `allow_distinct_partitions_independently`, `allow_limit_by_partitions_independently`, `allow_creating_set_partitions_independently`, `allow_window_partitions_independently` and `optimize_distributed_group_by_sharding_key`. [#117137](#117137) ([Groene AI](https://github.com/groeneai)).

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
pull Bot pushed a commit to admariner/ClickHouse that referenced this pull request Sep 21, 2026
`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`. ClickHouse#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]>
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

can be tested Allows running workflows for external contributors comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... groeneai-origin-request PR origin: a maintainer pinged or directed groeneai 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