Repository navigation
Fix wrong results from sumKahanIf and sumKahan over Nullable when the aggregated batch does not start at row 0 - #116990
Conversation
…t row 0 AggregateFunctionSumKahanData::addManyConditionalInternal advances its value pointer to the first row of the batch but never advances the flag map, and the loop then walks the map relatively, so values are read from index `start` while flags are read from index 0: row `start + i` is tested against flag `i`. Every sumKahan spelling carrying a per-row flag map returns a silently wrong number whenever the aggregator hands it a batch that does not begin at row 0. There is no exception and no log line. 767acd5 changed both copies of this kernel from (ptr, map, count) to (ptr, map, start, end) and added `ptr += start` to both, `condition_map += start` to neither. 0754ee4 later added the missing statement to the generic AggregateFunctionSumData copy, as a one-line commit with no test, which is why the surviving copy went unnoticed. This adds the same statement to the Kahan copy, so the two implementations of the interface agree again; a third implementation written independently, AggregateFunctionSumPrometheusData in open PR ClickHouse#114251, also writes it. Fixing the kernel rather than its call sites repairs both entry points (addManyNotNull, addManyConditional) and all three call sites at once, and keeps the contract for future callers. At start == 0 the added statement is `+= 0`, so every correct caller is byte-identical. Three callers pass a non-zero start, two of them with no setting at all. WindowTransform's first_row is block relative, so any frame not beginning at the block's first row reaches it, which is what makes this reachable at stock defaults. Parallel plain GROUP BY reaches it as well: when a block can push the local table past adaptive_aggregator_freeze_threshold, Aggregator::executeImplUntilAdaptiveFreeze aggregates that block in slices, and every slice after the first starts mid-block. An env-gated counter inside the kernel saw 46 of 62 entries with start > 0 there, at the slice boundaries 16383, 16384, 32766, 32767, 49149 and 49150, and a single-key 1000000-row table returns 400 for sumKahanIf where the answer is 100. That route needs enable_adaptive_aggregator, which defaults to true and exists from 26.8, and it needs more than one input stream, because AggregatingStep only creates the adaptive session for parallel aggregation; that is why single-stream fixtures over numbers() report start == 0 and measure nothing about it. The in-order aggregation path reaches it under optimize_aggregation_in_order = 1. Both maps are always at least row_end long, so the misindexed read stays in bounds; this is wrong results, not a memory safety problem. The test has three arms, one per distinct code path: a window frame over the -If combinator, a window frame over a Nullable argument (the null-map instantiation, add_if_zero = true), and the in-order aggregation path. Each arm reddens a disjoint set of reference lines on the unfixed build. One further statement asserts that the in-order arm really gets the in-order pipeline, so the arm cannot pass by silently falling back to hash aggregation; it holds on both builds, and reads 0 with optimize_aggregation_in_order = 0. cond is 1 only for n < 3, so from row 5 the correct answer is a legitimate 0 while the unfixed answer is a non-empty 3, which keeps the oracle from being satisfiable by the empty-set value. x is toFloat64(1), exactly representable, so sum and sumKahan agree bit for bit and the sumIf control column is a sound equality oracle; that column also pins the generic copy, which has had no test since 0754ee4. Validated on a debug build: 50 of 50 runs pass with the fix and 0 of 20 without it. Every arm still reddens the unfixed build with the old analyzer, and the in-order arm reddens it at max_threads 1, 2 and 3, so neither is pinned. The in-order arm does pin aggregation_in_order_max_block_bytes to its default: clickhouse-test randomizes it over 0 to 50000000, and at the draw 0 AggregatingInOrderTransform cuts the chunk at the first key boundary, which restarts key_begin at 0 and hides the defect. Measured on the unfixed build, only the draw 0 does that; 1 and every larger value leave the arm reddening. Of the five pre-existing sumKahan tests, every sumKahan statement returns byte-identical output on both builds; none uses a window frame, in-order aggregation, or a flag map. Reported as an aside by @ snelheidai in ClickHouse#116952. The performance defect described in that issue is left to a separate PR. Co-Authored-By: Claude Opus 5 <[email protected]>
Internal second-model reviewAn independent reviewer and a second model reviewed this change before publication. Two rounds; the second returned no findings. Anything marked fixed is in the diff.
Not changed, with reasons:
|
|
Workflow [PR], commit [a84e396] Summary: ❌
AI ReviewSummaryThis PR fixes the missing Final Verdict✅ No new findings. LLVM Coverage ReportMeasured on commit a84e396.
Changed lines: Changed C/C++ lines covered: 5/5 (100.00%) · Uncovered code |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-self-slot-57:20260829-004700 |
|
cc @alexey-milovidov @nickitat, could you review this? |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units10 translation units recompiled, 48 s compile time in total, 10 of them have a recent master baseline. |
CI finish ledger - 8b8cd0dEvery failure below has an owner.
Two concurrent Session id: cron:our-pr-ci-monitor:20260829-053000 |
|
Fixing PR for the To be plain about what it does and does not do: it fixes the misreporting only. The hook was |
The test pinned the direct `if` flags path and the plain null map path, but not the two wrappers that build a flag map for a Nullable argument, so one of the carriers named in the description stayed untested. Two arms are added over the same window frame: `sumKahanIf(Nullable(Float64), UInt8)` reaches AggregateFunctionIfNullUnary, which merges the null map and the filter into a single map (Combinators/AggregateFunctionIf.cpp:176-183) before calling addBatchSinglePlaceNotNull, hence addManyNotNull. `sumKahanIf(Float64, Nullable(UInt8))` has a non-Nullable first argument, so it routes to AggregateFunctionIfNullVariadic instead, which builds its own map in the same file (:323-347). Both maps are sized for row_end and filled from row_begin, so the unfixed kernel reads them from index 0 and the divergence is a wrong value rather than an empty-frame artifact. In each arm the null map and the filter disagree on some rows, so the merge itself is exercised. Measured on this tree, debug build, test 05048 only: 50 OK / 0 FAIL with the fix. Against a server built from pristine master 38a9ca2 the runner stops at its own --max-failures-chain limit with 0 OK / 20 FAIL, and the two new arms account for four of the differing lines (3 1 1 -> 3 1 2, 4 1 1 -> 4 1 3, 1 1 1 -> 1 1 0, 2 2 2 -> 2 2 0).
CI finish ledger - a84e396Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
All three rows are one cause.
I have not pushed a master merge myself: @ Algunenano is driving this branch (the master merge at Session id: cron:our-pr-ci-monitor:20260902-013000 |
47fd140
Backport #116990 to 26.6: Fix wrong results from `sumKahanIf` and `sumKahan` over `Nullable` when the aggregated batch does not start at row 0
Backport #116990 to 26.3: Fix wrong results from `sumKahanIf` and `sumKahan` over `Nullable` when the aggregated batch does not start at row 0
Backport #116990 to 26.8: Fix wrong results from `sumKahanIf` and `sumKahan` over `Nullable` when the aggregated batch does not start at row 0
…mKahan` over `Nullable` when the aggregated batch does not start at row 0
Backport #116990 to 26.7: Fix wrong results from `sumKahanIf` and `sumKahan` over `Nullable` when the aggregated batch does not start at row 0
…f` and `sumKahan` over `Nullable` when the aggregated batch does not start at row 0
…f` and `sumKahan` over `Nullable` when the aggregated batch does not start at row 0
…f` and `sumKahan` over `Nullable` when the aggregated batch does not start at row 0
…egation `AggregateFunctionSum::addBatchSinglePlaceNotNull` and `AggregateFunctionAvg::addBatchSinglePlaceNotNull` merge the null map and the `-If` condition into a temporary flag buffer built with `std::make_unique<UInt8[]>(row_end)`. The array form of `std::make_unique` value-initializes, and `row_end` is the absolute end row of the sub-range rather than the size of the written span, so a caller that walks one block in increasing sub-ranges zeroes about N*(g+1)/2 bytes per block of N rows cut into g intervals, while only `[row_begin, row_end)` is ever written or read. Two callers do that: aggregation in order, which calls the entry point once per sorting-key interval, and window frames, whose `rows_to_add_start` is monotonically non-decreasing inside a block and which need no setting at all to reach this code. Size the buffer to the written span with `std::make_unique_for_overwrite`, rebase the destination index, and pass the value pointer offset by `row_begin` with `start = 0`. Both kernels already do `ptr += start; condition_map += start; count = end - start`, so the pointers and the count handed to the accumulation loop are byte-identical and no floating-point re-association is possible. On the `sumKahan` instantiation this holds because ClickHouse#116990 added the missing `condition_map += start`. Measured on a 10M row table with 8 row groups, median of 15 interleaved runs: `sumIfOrDefault` 558 ms to 287 ms, `avgIfOrDefault` 563 ms to 295 ms, and a window frame 82 ms to 31 ms. Six shapes that do not reach this code stay within 1.3%, and `SelectedRows`, `ReadCompressedBytes` and `ArenaAllocBytes` are unchanged. Correctness was checked over 320 spelling, type and producer combinations, all byte-equal, with three mutants of this change breaking 105 each. Reachability is wider than the report states: `sumIf` with a non-nullable value and a `Nullable` condition reaches the site through the variadic branch of `AggregateFunctionIf::getOwnNullAdapter` with no extra combinator, while `sumIfOrNull` does not, because both analyzers rewrite that name to `sumOrNullIf`. On the former shape the null map itself is built by a second block-sized buffer in `AggregateFunctionIfNullVariadic::addBatchSinglePlace`, tracked separately by ClickHouse#117511, so this change removes one of two equal buffers there. Analysis and patch by @ snelheidai in ClickHouse#117947. Co-Authored-By: Claude Opus 5 <[email protected]>
AGG: sumKahan/sumKahanIf/Nullable when a batch does not start at row 0 (window frames, parallel GROUP BY) -> wrong (silent). Effect in the production build a394e92: wrong/failing (the upstream test fails on it and passes on official 26.8.8.8; evidence/fix_ci_20260925/upstream_repro/residual/116990.PROD263.txt). Upstream patch unchanged, with its test(s): 05048_sum_kahan_conditional_row_offset. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Related: #116952
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed wrong results from
sumKahanwhen the aggregated batch does not start at the first row of the block.sumKahanIf, andsumKahanover aNullableargument, tested each row against the wrong element of the condition or null map, returning silently incorrect sums inside window frames such asROWS BETWEEN 2 PRECEDING AND CURRENT ROW, in parallelGROUP BY, and underoptimize_aggregation_in_order = 1.Description
AggregateFunctionSumKahanData::addManyConditionalInternaladvances its value pointer to the batch's first row but never advances the flag map, so rowstart + iis tested against flagi. EverysumKahanspelling with a per-row flag map then silently returns a wrong number when the batch does not begin at row 0. Reachable at stock defaults:Three callers pass a non-zero start, two needing no setting: a window frame not beginning at the block's first row, as above; parallel
GROUP BY, where the adaptive aggregator slices a threshold-crossing block so every slice after the first starts mid-block, and a slice covering one key reaches this kernel (one-key 1000000-row table returns 400 where the answer is 100; needsenable_adaptive_aggregator, defaulttrue, so 26.8 onward); and in-orderGROUP BYunderoptimize_aggregation_in_order = 1.DecimalsumKahanis unaffected, using the generic sum data. Both maps are at leastrow_endlong, so the read stays in bounds: wrong results, not memory unsafety.The fix adds the one missing statement, so this copy agrees with the generic copy, which got this line in
0754ee49016bf64, a commit with no test, which is why this copy survived. The tree had nosumKahanIftest and no non-zero-startsumKahantest; the new test adds both, with asumIfcontrol column pinning both copies. Of the eight pointers insrc/advanced by the batch start, this was the only one not advancing its map.Reported as an aside by @ snelheidai in #116952, whose performance defect is a separate PR. Also noticed, not raised: the
make_unique<UInt8[]>(row_end)prefix-fill idiom at ten sites.Workflow [PR]
Sync PR [sync-upstream/pr/116990]
Version info
26.8.3.15,26.7.7.10,26.6.5.27,26.3.29.10