Repository navigation
Do not value-initialise the merged flag buffers in batch aggregation - #118025
Algunenano merged 4 commits into
Conversation
…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]>
The first oracle compares in-order aggregation against hash aggregation, but it only requested the optimization with a session-level SET; it never checked that the optimizer selected it. If in-order declines, both temporary tables hold the same plan's output and the EXCEPT is vacuously 0, so the test stays green while measuring nothing. Assert the plan instead of assuming it, via a subquery over EXPLAIN PIPELINE filtered with ILIKE, and repeat the same query with the optimization off as a negative control so the assertion is shown to discriminate. The marker AggregatingInOrderTransform covers both thread regimes: the single-stream path creates it directly and the multi-stream path creates it alongside FinishAggregatingInOrderTransform, whose name contains it. Also record why the cross-plan comparison is exact. The two sides accumulate in different orders, and they agree bit-for-bit only because the fixture values are integer-valued Float64 and the groups are small, so widening either later would make the test flaky with no other warning. Measured: the assertion holds across optimize_read_in_order, the old analyzer, max_threads 1 to 32, and parallel replicas with a local plan; 50 randomized runs pass.
Internal second-model reviewAn independent model reviewed the diff cold, three times. The final round found nothing.
💡 Three nits left alone: the result comparison is one-directional (a mis-rebase changes values, not |
|
Workflow [PR], commit [ef6a52d] Summary: ❌
AI ReviewSummaryThis PR removes redundant value-initialization from temporary merged null/ Final Verdict✅ No findings. LLVM Coverage ReportMeasured on commit ef6a52d.
Changed lines: Changed C/C++ lines covered: 52/55 (94.55%) · Uncovered code |
|
cc @rschu1ze @KochetovNicolai, 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 units21 translation units recompiled, 116 s compile time in total, 21 of them have a recent master baseline. |
|
📊 Cloud Performance Report 🟢 AI verdict: 1 improved query(s). K_source=6 K_base=30 flagged=1/65 clickbenchFlagged queries (1 of 43)
Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. tpch_adapted_1_official🟢 1 improved Flagged queries (1 of 22)
Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. Debug info
|
…/117947-span-size-agg-if-flag-buffer
`std::make_unique<UInt8[]>(row_end)` value-initialises `row_end` bytes to build a merged null/condition flag buffer, while only `[row_begin, row_end)` is ever written or read. Callers that walk one block in increasing sub-ranges, aggregation in order (once per sorting-key interval) and window frames (monotonically non-decreasing frame start, no setting needed), therefore zero about `N*(g+1)/2` bytes per block of `N` rows cut into `g` intervals to produce `N` bytes of useful flags. `std::make_unique_for_overwrite` drops the zeroing; the merge loop assigns every byte of the span before anything reads it. Results are unchanged. Sizing stays `row_end` at every site here, because each of these buffers goes to a consumer that indexes it by absolute row. `AggregateFunctionNullVariadic::addBatchSinglePlace` needed more than the swap. Its second buffer is merged with `|=` starting at filter 0, so it reads the buffer before writing it and relied on the zeroing. I now seed the span from filter 0 with an assignment and OR filters 1 to n-1 into it. That is equivalent in all three reachable cases (buffer already pushed as `nullable_filters[0]`, buffer built but not pushed and therefore all-zero over the span, buffer freshly allocated) and the pass count is identical. Measured on a Debug build, 10M rows, groups of 8, `optimize_aggregation_in_order = 1`, median of 11 interleaved runs per arm. `SelectedRows` and `ReadCompressedBytes` are identical between arms, so the removed work is CPU and not I/O: minIf(x, cond) 910 ms -> 645 ms 29.1% faster sumIf(y, nullable_cond) 937 ms -> 708 ms 24.4% faster argMinIf(y, x, cond) 1187 ms -> 733 ms 38.3% faster corr(x, w), two Nullable arguments 871 ms -> 760 ms 12.8% faster timeSeriesGroupArrayIf 6730 ms -> 3338 ms 50.4% faster minIf over a 100-row window frame 43.3 s -> 25.1 s 42.1% faster Seven shapes that reach none of these buffers stay between 5.7% slower and 3.5% faster, which is the noise band I measured on this box. `AggregateFunctionNullVariadic`'s first buffer is converted together with its neighbour in the same function, but I could not reach it from SQL: the generic null adapter is always the outermost wrapper, and every path that would hand it a real `if_argument_pos` is intercepted by `AggregateFunctionIf::getOwnNullAdapter`. I tried 17 combinator shapes. I left the two buffers in `AggregateFunctionBitwise` and `AggregateFunctionStatisticsSimple` alone: `new UInt8[row_end]` default-initialises, so there is no zeroing to remove there. Right-sizing their allocation is worth a further 6.9% to 16.0% on the same shapes, which refutes the reasoning I first had for excluding them, but that is a different mechanism (allocation size, not value-initialisation) and it is not part of this change. Validation. A poison arm that fills `[0, row_end)` with `0xAA` before every merge loop produces byte-identical results across a 23-shape matrix, and the same arm applied to one site at a time changes results at every site I could reach, so the check is not blind. The same buffer without the seed-then-OR restructure returns wrong results with and without the poison fill. 331 aggregate-function, window and aggregation-in-order tests have the same outcome on both arms, and the new coverage in `05060_agg_if_null_map_span` passes 50 of 50 runs with randomised settings. Analysis and patch by @ snelheidai in ClickHouse#117947 and ClickHouse#117511.
sum and avg with -If over Nullable
Internal second-model reviewAn independent model reviewed the consolidated diff cold. No blockers, one nit, which I had also
💡 One nit left alone: that site is the only converted allocation without the shared |
CI finish ledger - ef6a52dEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20260905-030000 |
10bec7b
When a table is sorted by a prefix of the GROUP BY keys, AggregatingInOrderTransform splits each block into runs of equal sorting-key values and calls executeOnBlockSmall once per run, and Aggregator::executeImpl builds a fresh Method::State for every call. For a fixed-size key that satisfies usePreparedKeys (the prepared-capable keys* variants) that state's constructor batch-packs the grouping key of the whole block, because packFixedBatch sized its work from the key column rather than from the row range being aggregated. One block therefore cost O(runs * block_size) instead of O(block_size), which is quadratic in max_block_size once the sorting prefix is near-unique. Give the hashing state the row range it will be asked about, and pack exactly those rows. packFixedBatch sizes prepared_keys to row_end and writes only [row_begin, row_end), so prepared_keys[row] still holds the packed key of row row: getKeyHolder is untouched, the state class gains no data member, and the per-row path of every fixed-key GROUP BY in the server is unchanged. Every caller that covers a whole block passes the whole block and reproduces the previous resize_fill(block_rows) exactly, so the batch pack is kept wherever it wins, including the adaptive aggregator's slices, which deliberately share one state across sub-ranges of a block. The zero fill moves out of fillFixedBatch into packFixedBatch because it must happen once, before any width pass: a per-pass fill would erase the previous pass's bytes. Only the range's end is clamped to the block, because that is the side carrying a sentinel for "the whole block"; the begin is always a row of the block, so it states the precondition with a chassert rather than silently repairing a caller. Indexing the packed array absolutely rather than relative to row_begin is deliberate. Relative indexing puts an extra operation on the per-row path and measured +2.9% and +4.1% on the keys64 whole-block median across two independent 100-sample release A/B runs, with non-overlapping quartiles, while a duration-matched control that never reads prepared_keys moved +0.00%. Absolute indexing moves the residual cost onto the path being fixed instead: one allocation call per run, sized row_end. That is O(1) allocations rather than O(rows) writes, and it measures flat in max_block_size - but the requested size is O(row_end), so the bytes a block asks for stay quadratic even though the bytes it writes do not. Under jemalloc, which official builds use, the difference never becomes work. An allocator that touches every allocated byte keeps the quadratic term: with MALLOC_CONF=junk:true the same query measures 107.6 s against 0.59 s, and broken-versus-fixed separates by ~4x instead of ~99x. jemalloc is disabled under every sanitizer except UBSan, so the regression test excludes those builds by tag rather than widening its limit. Two cheaper-looking alternatives are wrong rather than slower. Letting a sub-range state fall through to packFixed / packFixedShuffle returns wrong column values: packFixedBatch writes the key size-descending while those two write it in GROUP BY order, and HashMethodKeysFixed::shuffleKeyColumns already permuted the output columns for the size-descending layout whenever usePreparedKeys holds. Substituting keys256 for the prepared-capable variants in method_chosen_for_in_order, as the serialized fix did, leaves keys16 uncovered (it is prepared-capable and has no keys256-shaped counterpart, its table being a direct-address FixedImplicitZeroHashMap) and depends on the sizeof(Key) > 16 test in usePreparedKeys that ClickHouse#120100 proposes to widen. DISTINCT in order carries the same defect and gets the same argument. DistinctSortedStreamTransform walks the equal-ranges of the sorted prefix and builds one ClearableSetVariants state per range over whole-chunk columns in buildFilterForRange. With two non-prefix UInt64 columns, which select the prepared-capable keys128 set method, a 200000-row DISTINCT went from 13.165 s to 0.108 s at max_block_size 65409, growing 8.6x over an 8x block-size range before and 1.2x after. optimize_distinct_in_order is enabled by default, so that shape was pessimised out of the box: before the change it ran 329x slower than the same query with the setting off. Passing the range there requires HashMethodHashed to take the defaulted RowRange parameter the other five method classes already have, because APPLY_FOR_SET_VARIANTS instantiates that call for every set variant; like the four others that precompute nothing, it ignores the range. The merging in-order path was measured as well. mergeOnBlockSmall reaches mergeStreamsImpl once per run for a pre-aggregated input, which an aggregate projection keyed on a superset of the query's keys produces: 12.927 s against 0.202 s at max_block_size 65409, growing 8.1x before and 1.4x after. The regression test guards that shape, so the two range arguments there are pinned rather than merely consistent. MergeTreeIndexAggregatorSet::buildFilter is the third caller with this shape and is deliberately left alone: it allocates an IColumn::Filter per index granule, so the range argument alone would not make that path linear. Measured on a release build (RelWithDebInfo, clang++-22), 65536 rows with one distinct sorting-key value per row, max_threads = 1, at the default max_block_size: GROUP BY a, b over two UInt64 columns goes from 4.360 s to 0.046 s, against 0.022 s for the same query whose second key is a FixedString(3) - identical aggregation method and run count, but key sizes that fail usePreparedKeys and so pack row by row. That control isolates the packing term from the per-run hash table. The fixed arm is flat in max_block_size (0.037 / 0.043 / 0.046 s at 8192 / 32768 / 65409, against 0.518 / 1.935 / 4.360 s before), and max_threads = 16 gives the same numbers. Queries with optimize_aggregation_in_order = 0 are unchanged. The serialized methods keep their whole-block batch serialization: the per-run in-order path already avoids them by substituting the plain serialized variant, and their non-batch fallback indexes a whole-block row_sizes array filled by a per-column virtual, so range-scoping it would reach every column implementation. The regression coverage is per call site rather than per path. 05217 puts a timed guard with max_execution_time = 120 on each of the five ranged state constructions a query can select: the use_cache pair in executeImpl, the same pair in mergeStreamsImpl, and the DISTINCT transform. Reverting any one of those five arguments alone reddens exactly its own guard and leaves every other assertion in the file passing. Reaching either StateNoCache arm needs is_simple_count, that is, exactly one count() and nothing else, and the outer aggregate has to consume that count: left unused it is pruned, and the query collapses onto the cache-using sibling. The adaptive slicer's pair cannot be guarded at all, because every executeOnBlock caller passes row_begin = 0, so the range there always equals the default and reverting it changes neither results nor timing. Measured on a debug build, the DISTINCT shape runs in 0.574 s fixed against 654.98 s broken, the limit firing at 316.8 s. Its block size is 400000 rather than the 200000 the other two guards use, because max_execution_time is only evaluated when the reader hands over the next block while DistinctSortedStreamTransform packs every range of a block inside one transform() call. At 200000 the broken query finishes in 378.9 s, under the margin the other guards keep, and at 800000 the whole table is one block, where nothing evaluates the limit at all and the query ran past 1200 s. A unit test covers what no SQL test can observe, since usePreparedKeys has no ProfileEvent and no system table and the column reordering it enables is undone before results: gtest_columns_hashing_prepared_keys asserts that a whole-block caller still batches, that a ranged one writes exactly [begin, end) at absolute row indexes agreeing with the independent per-row packFixed, and that a key outside the batching class batches nothing. Closes ClickHouse#45386 Related: ClickHouse#110159 Related: ClickHouse#118025 Co-Authored-By: Claude Opus 5 <[email protected]>
…ce test With groups of 8 rows about 75% of each query is per-group work (the group-end search of in-order aggregation, the `-If`/`-Null` adapters, state create and finalize). Its speed depends on how a build lays out these small hot functions: 73 of 2667 amd builds since 2026-10-26 run one of the six queries 16-35% slower than the rest of the same build, with the same instruction count and one more branch miss per group. That made the test fail on unrelated PRs (ClickHouse#120906: ClickHouse#3 +35%, #0 +27%) with a different query each time. Disable the six queries (their history keys stay) and append them on three new tables: `sumIfOrDefault`, `avgIfOrDefault` and `sumIf` on groups of 1024 rows, `corr` and `argMinIf` on groups of 128 rows and `minIf` on groups of 256 rows. `corr` has the smallest per-group penalty and needs the smaller groups to keep its ClickHouse#118025 guard (~1.10 at 1024 rows). `argMinIf` and `minIf` keep a guard of ClickHouse#122505: reverting its change to the variadic and unary `-If` null adapters slows them 1.21x and 1.28x, while the other `-If` queries move +0.9% to +13.2%. Measured locally with perf.py against the CI reference build: the ClickHouse#120906 build runs the old #0/ClickHouse#3 at 1.31x/1.39x and the new copies at 1.016x/1.020x in the same processes (`sumIf` 1.067x in another run); 7 slow CI builds stay within 6.7% on the new queries (A/A 2.5%), below the 15% minimum change threshold. Restoring the value-initialised `row_end`-sized buffer at each ClickHouse#118025 site master still reaches (`AggregateFunctionSum.h:669`, `AggregateFunctionAvg.h:539`, `SingleValueData.cpp:39`, `AggregateFunctionNull.h:769`) slows its queries 1.2x-1.8x, with identical results. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Closes: #116952
Closes: #117511
Closes: #117947
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Improved performance of aggregate functions that merge a null map with an
-Ifcondition into a temporary flag buffer, when a block is consumed in increasing sub-ranges asoptimize_aggregation_in_orderand window frames do. The buffer is no longer value-initialized, and insumandavgit is also sized to the rows actually processed instead of to the end of the block. This affectssum,avg, the-Ifcombinator overNullablearguments,min/max/argMin/argMaxwith-If, aggregate functions with two or moreNullablearguments such ascorrandquantileExactWeighted, and thetimeSeries*functions with-If.Description
Two callers walk one block in increasing sub-ranges: aggregation in order, once per sorting-key interval, and window frames, which need no setting. Ten places in
src/AggregateFunctionsbuild a merged null/condition flag buffer for them withstd::make_unique<UInt8[]>(row_end), which value-initialisesrow_endbytes although only[row_begin, row_end)is ever written or read. A block ofNrows cut intogintervals therefore zeroes aboutN*(g+1)/2bytes to produceNuseful ones.sumandavgare right-sized to the span and rebase the value pointer. The other eight buffers go to a consumer that indexes them by absolute row, so their size staysrow_endand only the value-initialisation goes, viastd::make_unique_for_overwrite.AggregateFunctionNullVariadicalso needed its|=merge reworked into an assignment for filter 0 followed by the OR of the rest, because it read the buffer before writing it.Measured on a Debug build, 10M rows, groups of 8, median of 11 interleaved runs per arm, with
SelectedRowsandReadCompressedBytesidentical between arms:minIf29% faster,sumIfover aNullablecondition 24%,argMinIf38%,corrover twoNullablearguments 13%,timeSeriesGroupArrayIf50%, a 100-row window frame 42%. Seven shapes that reach none of these buffers stay between 5.7% slower and 3.5% faster, which is the noise band on this box.Results are unchanged. A poison arm that fills every one of these buffers with
0xAAbefore its merge loop is byte-identical over a 23-shape matrix, and reddens per site when applied to one site at a time, so the check is not blind. 331 aggregate-function, window and aggregation-in-order tests have the same outcome with and without the change.Which buffers changed, which did not, and why
AggregateFunctionSum.h,AggregateFunctionAvg.hsumIfOrDefault,avgIfOrDefaultCombinators/AggregateFunctionIf.cpp,AggregateFunctionIfNullUnarymake_unique_for_overwriteminIf(x, cond),varSampIf(x, cond), the same in a window frameCombinators/AggregateFunctionIf.cpp,AggregateFunctionIfNullVariadicmake_unique_for_overwritesumIf(y, nullable_cond),avgWeightedIf,argMinIf,corrIfCombinators/AggregateFunctionNull.h, first buffermake_unique_for_overwriteif_argument_posis intercepted byAggregateFunctionIf::getOwnNullAdapter. Changed with its neighbourCombinators/AggregateFunctionNull.h, second buffermake_unique_for_overwriteplus seed-then-ORcorr(x, w),covarPop,quantileExactWeightedover twoNullablearguments, the same in a window frameSingleValueData.cpp,mergeIfAndNullFlagsmake_unique_for_overwriteargMinIf,argMaxIfTimeSeries/kernelsmake_unique_for_overwritetimeSeriesRateToGridIf,timeSeriesGroupArrayIf,timeSeriesLastTwoSamplesIf, behindallow_experimental_time_series_aggregate_functionsAggregateFunctionBitwise.cpp,AggregateFunctionStatisticsSimple.hnew UInt8[row_end]default-initialises, so there is nothing to remove. Right-sizing their allocation is worth a further 6.9% to 16.0% ongroupBitOrIfandvarSampIf, a different mechanism that is not part of this changeTwo
SingleValueDataconsumers also return the absolute index, so rebasing there would be out of bounds, and the twotimeSeries*kernels share a path that is given a raw column pointer.Analysis and patch by @ snelheidai.
Version info
26.9.1.1036(included in26.9and later)