Repository navigation
Batch the -ForEach aggregate combinator's accumulation - #121137
alexey-milovidov merged 14 commits into
Conversation
…t and batch streaming
|
Workflow [PR], commit [6c8e0f1] Summary: ✅
AI ReviewSummaryThis PR batches TestsFinal Verdict✅ No new findings. No inline review comments were posted. LLVM Coverage ReportMeasured on commit 6c8e0f1.
Changed lines: Changed C/C++ lines covered: 88/92 (95.65%) · Uncovered code |
|
📊 Cloud Performance Report ✅ AI verdict: This PR adds batch versions of the add functions for the -ForEach combinator and batch grouped paths for multi-argument -If with a Nullable argument or condition. No ClickBench or TPC-H query uses -ForEach, and ClickBench columns are not Nullable, so none of the flagged queries runs the changed code. The Q30 regression (+21.0%) is inside master's current range, and the Q34 improvement (-10.8%) comes from a thin baseline after a recent master shift. Both are downgraded to not_sure, and Q28 stays borderline. To see this PR's real effect, look at the new aggregate_function_for_each performance test, not these benchmarks. clickbenchFlagged queries (3 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🟢 No significant changes Debug info
|
Build (arm_tidy) failed on both new overrides: AggregateFunctionForEach.h:293:10: error: default arguments on virtual or override methods are prohibited [google-default-arguments,-warnings-as-errors] AggregateFunctionForEach.h:331:10: same `if_argument_pos = -1` has to stay, because the base declaration carries it and every caller relies on it. `IAggregateFunction` annotates its own `addBatch` and `addBatchSinglePlace` with `/// NOLINT` for this reason, and the Null, OrFill, Tuple and UniqCombined overrides all follow it. This does the same. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01QtEKPyQDMCBZfJkiJcs789
The row-at-a-time `add` rejects a row whose array arguments do not share boundaries, throwing SIZES_OF_ARRAYS_DONT_MATCH. Both new batch paths read `begin` and `end` from the first argument's offsets and then feed that slice to every nested column without checking the others, so a mismatched row like `corrForEach([1, 2], [3])` stopped being rejected and silently read the second argument through the first argument's range instead. The existing coverage could not catch it: every aggregate in the test is single-argument, where there is nothing to disagree with. The new case uses a two-argument `-ForEach` and asserts the error on both batch entry points, the ungrouped one and the grouped one. Verified against a build without this branch: both queries throw error 190, and with the expected code changed to a wrong one the harness reports "Expected server error code: 43 but got: 190", so the assertions are enforced rather than silently accepted. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01QtEKPyQDMCBZfJkiJcs789
`Aggregator` sends the ordinary grouped case through `addBatchWithNonNullPlaces` as soon as the hash table has materialized every state, and `IAggregateFunctionHelper` overrides that with a row-at-a-time loop over `add`. Since this class did not override it, the new batch path never ran for a plain GROUP BY, which is the case the PR is aimed at. Delegating to `addBatch` is what the base declaration in `IAggregateFunction` already does; only the helper's loop stood in the way. The null-place check inside `addBatch` is harmless here, since no place is null on this path, and the array-size guard now covers the grouped case as well. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01QtEKPyQDMCBZfJkiJcs789
`sizeOfData()` returns `sizeof(Data)` and `alignOfData()` returns `alignof(Data)`, so `alignas(64)` took the state from 16 bytes to 64. That is the opposite of the memory improvement this PR claims, and the cost does not stop at this function. `Aggregator` takes a single max over every function's `alignOfData()` for the whole per-key block and pads each state up to the next one's alignment, so one 64-aligned state inflates its neighbours too: sumForEach(a), sum(b), count() 32 -> 80 bytes per key sum(b), count(), sumForEach(a) 32 -> 128 bytes per key `Arena::alignedAlloc` then re-rounds the arena head to 64 for every key. Because the external-group-by and two-level thresholds are driven by real query memory, they trip at roughly a quarter of the distinct keys they used to. The padding also prevents nothing. Every transform aggregates into its own `AggregatedDataVariants` and its own arena, so two threads never write states that could share a line. And the padded object is a 16-byte header: the hot per-element writes go through its pointer into a separate arena block, which the padding never touches. The spelling was wrong as well. The codebase's constant is `CH_CACHE_LINE_SIZE`, which is 128 on ppc64 and 256 on s390x, and no aggregate function state in the tree is padded at all. The arena allocation goes back to the nested function's own alignment for the same reasons. The batch streaming work is untouched; that part is measurable. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01QtEKPyQDMCBZfJkiJcs789
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes4 object files changed (+40.57 KiB total), 0 added.
716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units8 translation units recompiled, 12 s compile time in total, 8 of them have a recent master baseline. |
The outer column was renamed from `time_series` to `samples` for tables of version 3 and later, so the INSERT no longer resolved and the test failed with NO_SUCH_COLUMN_IN_TABLE. Co-Authored-By: Claude Opus 5 <[email protected]>
No test in tests/performance exercised -ForEach, so the benchmark suite had no way to show the batch paths. A Memory source keeps the wide Array column read from dominating, which it does on MergeTree. Co-Authored-By: Claude Opus 5 <[email protected]>
`-If` wraps `-ForEach`, so it always hands the batch methods a valid if_argument_pos, and bailing out to the row-at-a-time helper meant the whole `-If` surface skipped the fast path. Honour the condition column in the loops instead, split in two so the unfiltered path keeps no per-row flag test. Co-Authored-By: Claude Opus 5 <[email protected]>
|
@groeneai , I suppose these CI failures are not caused by my changes here? |
|
@valerypetrov Correct, none of them can reach your diff, and the reason is structural rather than statistical. In
Three measurements agree with that. Every gated row is single-arch with the identical query flat on the other arch: For the two preimage queries that is just their own band. Over 14 days of Your change does measure what it should, and unlike the reds it reproduces on both arches: One number on your own path, since it is the only movement in the run your diff can actually reach: |
|
One thing I should have linked above: the false-positive half of this is already being fixed in #121090, which makes a It also predicts your two shards differently, which is a cheap way to check the reasoning above. arm 4/6 reported |
A `*ForEachIf` with a `Nullable` condition goes through `AggregateFunctionIfNullVariadic`, which folds the condition into a null map and calls `addBatchSinglePlaceNotNull` on the nested `-ForEach`. Without an override that fell back to the row-at-a-time `add` loop of `IAggregateFunctionHelper`, so the ungrouped nullable-condition case missed the batch path. Add the override and cover it, including a NULL condition. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
`AggregateFunctionIfNullVariadic` overrode only `addBatchSinglePlace`, so a grouped `sumForEachIf(arr, toNullable(cond))` (and any other multi-argument `-If` with a `Nullable` argument) went through `IAggregateFunctionHelper::addBatch`, one `add` per row. Fold the condition and the argument null maps into one `UInt8` column and pass the batch to the nested `-If`, which already forwards it to the nested function's `addBatch`. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
The earlier overflow case aggregated a single Memory block, so every key got a place. One-row blocks under `group_by_overflow_mode = 'any'` leave a later key without one, which is the only way `Aggregator` reaches `addBatch` rather than `addBatchWithNonNullPlaces`. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Rerun CI on current master: the last run's reds were master-side, and master has since changed the Nullable -If batch paths next to this branch's grouped ones. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes to CHANGELOG.md):
Speed up
-ForEachaggregate functions (sumForEach,avgForEach, ...) and grouped multi-argument-Ifaggregate functions with aNullableargument or condition, by processing rows in batches instead of callingaddfor each row.Detailed Description:
Scope
This PR changes two combinators:
-ForEach(AggregateFunctionForEach): all-ForEachfunctions, e.g.sumForEach,avgForEach,quantilesForEach,sumForEachIf.Nullableadapter of-If(AggregateFunctionIfNullVariadic, commit e384de9), used withGROUP BY. It is used for every-Ifaggregate with aNullableargument or condition, except one case: a single argument that is itselfNullable, likesumIf(nullable_x, cond). That case usesAggregateFunctionIfNullUnaryand is not changed. So the change coverssumForEachIf(arr, toNullable(cond)), and also functions unrelated to-ForEach, such assumIf(x, nullable_cond),covarPopIf(nullable_x, y, cond)andcorrIf(...). Before, these went throughaddrow by row inGROUP BY. Now they are batched.Both changes only affect how rows are fed to the nested function. The state layout, serialization and merge are unchanged, and results are identical. Commit e384de9 is self-contained, so the
-Ifpart can be reviewed, or split out, on its own.What is batched
AggregateFunctionForEachoverridesaddBatchSinglePlace,addBatchSinglePlaceNotNull,addBatchandaddBatchWithNonNullPlaces. Before, all four went to theIAggregateFunctionHelperloop, which callsaddonce per row, and each call rebuilt the nested column list and looked up the offsets again. Now that setup happens once per batch. The per-row array-size check (SIZES_OF_ARRAYS_DONT_MATCH) is still done. So are-Ifflags, null maps and null places.AggregateFunctionIfNullVariadic(a multi-argument-Ifwith aNullableargument or condition, e.g.sumForEachIf(arr, toNullable(cond))orcovarPopIf(nullable_x, y, cond)) already batched the single-place case. It now also overridesaddBatch/addBatchWithNonNullPlaces. They fold the condition and the argument null maps into oneUInt8condition column and pass the batch to the nested-If, which forwards it to the nested function'saddBatch. Before,GROUP BYwent throughaddrow by row.nested_func->add), so gains are small, around 5-20%, not a multiple. Merge, serialization and the state layout are untouched, and results are identical (see Testing).Cache-line padding was tried and removed.
alignas(64)on the state grew it from 16 to 64 bytes.Aggregatorpads each state to the largest alignment in the per-key block, sosum(b), count(), sumForEach(a)went from 32 to 128 bytes per key. The padding also did not target a phase where states share cache lines: each aggregating thread has its own arena. Nothing in the state layout changes in this PR.Measurement
Release build on macOS arm64. Master is the merge base
365470f5aba. Data:Memorytable, 2M rows,k UInt32(1000 keys),arr Array(Float64)with 32 elements,narrthe same with ~9% NULL elements,cond UInt8,ncond Nullable(UInt8).max_threads = 1, best of 2 medians of 9 runs, ms:sumForEach(arr)avgForEach(arr)sumForEachIf(arr, cond)sumForEachIf(arr, ncond)sumForEach(narr)k, sumForEach(arr) GROUP BY kk, avgForEach(arr) GROUP BY kk, sumForEachIf(arr, cond) GROUP BY kk, sumForEachIf(arr, ncond) GROUP BY kk, sumForEach(narr) GROUP BY kOnly the
sumForEachIf(arr, ncond)row exercises the-Ifadapter change. Other functions that now take the batched-Ifpath (covarPopIf,corrIf, ...) were checked for identical results but not timed.With default
max_threads(18 cores; 8M rows so the times are not near the ms resolution), the numbers are noisier:sumForEach21 -> 19 ms,avgForEach23 -> 21, groupedsumForEachIf(arr, ncond)18 -> 14, the other queries within 1-2 ms.CI
tests/performance/aggregate_function_for_each.xmlon the previous head:#0-#36-13% faster on amd and 2.5-12% on arm,quantilesForEachgrouped (#4) -7% amd and -1% arm. None were flagged, because each move is below its threshold.End to end,
prometheusQueryRange('ts', 'sum by (dc) (m)', ...)over 2000 series x 2880 samples (max_threads = 1) takes the same time (150 ms) before and after. ThesumForEachaccumulation is a small part of that query, so this PR is not a PromQL speedup. It makes the combinator itself faster.Testing
05234_foreach_streaming_aggregation_batch: single-place and grouped paths, empty arrays,Nullableelements, mismatched array sizes,-IfwithUInt8andNullable(UInt8)conditions, null places (group_by_overflow_mode = 'any'), and a grouped multi-argument nullable-If(covarPopIf,corrIf) checked against the same aggregate over rows filtered inWHERE.05234_promql_streaming_aggregation_memorycovers PromQL aggregations.sum/avg/min/max/count/any/anyLast/groupArray/groupUniqArray/quantile(s)Exact/corr/covarPop-ForEach,-ForEachIf(UInt8andNullableconditions),sumArrayForEachoverArray(Array),Array(LowCardinality(String)),-State/-Mergeround trip, grouped multi-argument nullable-If, overflow mode, small blocks and 8 threads. The output is byte-identical (413 rows).ForEach, plus-If/Nullablecombinator tests). All pass except ones that need ZooKeeper or127.0.0.2. Theremote()ones pass once pointed at127.0.0.1.🤖 Generated with Claude Code
Workflow [PR]
Sync PR [sync-upstream/pr/121137]
Version info
26.10.1.1235-master(included in26.10and later)