Repository navigation
Fix wrong results for plus/minus keys with a non-integer operand - #117137
Conversation
…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.
…ctive-plus-minus-type-gate
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.
Internal second-model review - 7 review rounds, 6 independent gate passesEvery finding below was raised by an independent reviewer or a second model against this diff,
The three ❌ rows are settled by measurement rather than inspection. The server was built with an One earlier claim of mine was wrong and is corrected in the record: an initial round asserted the |
|
Workflow [PR], commit [aaf9acd] Summary: ✅
AI ReviewSummaryThis PR correctly fixes the wrong-results bug from treating non-integer Findings
Final VerdictThe 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 LLVM Coverage ReportMeasured on commit aaf9acd.
Changed lines: Changed C/C++ lines covered: 17/18 (94.44%) · Uncovered code |
Pre-PR validation gate (click to expand)
|
|
cc @Ergus @CurtizJ, could you review this? |
`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]>
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units34 translation units recompiled, 432 s compile time in total, 34 of them have a recent master baseline. |
`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]>
CI finish ledger -
|
| 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 checkcondition is fleet-wide, with a clean onset on 2026-08-30 13:48:57Z shortly
afterv26.8.1.2041-ltsbecame 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 portsignature 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.
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)) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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 + 12 to 0,ip - toIPv4('0.0.0.1')2 to 0,ip6 + 12 to 0 - per-partition
GROUP BY(allow_aggregate_partitions_independently):ip + 11 to 0 - controls:
DISTINCT/GROUP BYon the partition expression stay at 2 and 1, the integer arms stay
optimized, andtoUInt32(ip) % 3prints 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.
|
@groeneai |
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.
|
Trimmed, in aaf9acd. I did not add 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 Measured on one debug build with the fuzzer armed, one test at a time:
Negative control, both trees run against pre-fix master ( If this is not enough, one line from the sync log would help: the public legs run |
CI finish ledger - aaf9acdEvery 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
Neither test is reachable from this diff, which is confined to the Session id: cron:our-pr-ci-monitor:20260909-033114 |
8055c45
|
@groeneai @nihalzp — ClickGap found the following in this PR:
Close anything that's wrong or already addressed. |
|
Checked it. The finding is real and still reproduces on master 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 ( |
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]>
`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]>
`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]>
Closes: #116268
Closes: #118729
Related: #114783
Related: #114981
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix wrong results when a
GROUP BY,DISTINCT,LIMIT BYor windowPARTITION BYkey wasplusorminusof a partition column with a non-integer constant, for examplex + 1.0onFloat64ord + INTERVAL 1 MONTHonDate. Such a key was assumed injective, so each table partition wasevaluated 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_independentlyandoptimize_distributed_group_by_sharding_key.Description
Asked for by @ nihalzp on #114783.
isInjectiveFunctiondecided injectivity from a hardcoded namelist with no type and no value check, bypassing
IFunctionBase::isInjective. It fails five ways:Measured on master, per-partition vs merged
d + INTERVAL 1 MONTH(Date, end-of-month collapse)d - INTERVAL 123 YEAR(Date, saturation at the type bound, #118729)t + INTERVAL 1 DAY(DateTime('Europe/Moscow'), DST)f + 1.0(Float64near 1e16, rounding)x + toDate(0)(constant narrows the result toDate)x + toDecimal32(0, 1)(constant rescales the operand)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.
FunctionBinaryArithmeticWithConstantsalready holds both operands and the result type.negateand
tupledeclareisInjectivethemselves, so the list only spoke forplusandminus.BinaryArithmeticOverloadResolvergets the same predicate, asgtest_functions_stressrequires.Injective expressions are given up, none covered by a test.
Date + INTERVAL 1 DAY,Date + 1andDecimal64(2) + 1because every type that would readmit them also readmits anon-injective row above. Same-type temporal
minus(Date - Date,DateTime - DateTime,DateTime64(s) - DateTime64(s)) andIPv4/IPv6through theirUInt32/UInt128arithmeticcarrier are separable by type, but the deleted name list was the only injectivity fallback among
the 11 query-layer
isInjectivecall sites, so admitting them here would newly claim injectivityin the other 10,
KeyConditionincluded.Making integer
plushonest can also unwrapGROUP BY materialize(1) + 1to an empty key list, whichmerged #114981 guards; a backport needs it too. #116828 reports the other branch of this helper
(
toString(DateTime),toFixedString), which already goes throughisInjectiveand is notwidened here.
Workflow [PR]
Sync PR [sync-upstream/pr/117137]
Version info
26.9.1.1459(included in26.9and later)