Repository navigation
Add vectorized batch paths for groupBit* and variance-family aggregate functions - #110461
Conversation
`AggregateFunctionBitwise` was the only common numeric aggregate without `addBatchSinglePlace`/`addBatchSinglePlaceNotNull` overrides, so with the `-If` combinator it fell back to the generic per-row branch-guarded loop, paying a branch misprediction per row for unpredictable predicates. Accumulate into a local value and apply the flag as a branchless all-ones/all-zeros mask (OR: `acc |= x & m`, AND: `acc &= x | ~m`, XOR: `acc ^= x & m`), writing back to the state once per block. Wide integers build the mask with `memset`, mirroring the `is_over_big_int` path of `sum`. Dispatch with `MULTITARGET_FUNCTION_X86_V4`, like `sum`. Measured (50M rows, 1 thread, unpredictable 50% predicate, server-side query time): `groupBitOrIf`/`groupBitAndIf`/`groupBitXorIf` -74%, `UInt128`/`UInt256` -51..-57%, `Nullable` -31%, `Nullable` + `-If` -59%. No regressions: predictable predicates and the no-`If` path are unchanged.
Give `AggregateFunctionVarianceSimple` (`varPop`, `varSamp`, `stddevPop`, `stddevSamp`, `skewPop`, `skewSamp`, `kurtPop`, `kurtSamp`, `covarPop`, `covarSamp`, `corr`) the same treatment as `groupBitOr`/`groupBitAnd`/ `groupBitXor`: `addBatchSinglePlace`/`addBatchSinglePlaceNotNull` overrides with vectorized kernels on `VarMoments`/`CovarMoments`/`CorrMoments`. The `-If`/null flag zeroes the value's bit pattern with an integer mask (multiplying by the flag would let NaN/Inf in discarded rows poison the accumulators), and the loops unroll into 16 partial accumulators per moment - FP addition is not associative, so the compiler cannot do this itself. This also breaks the sequential FP dependency chain of the per-row path, so the no-`If` case speeds up as well. `Decimal` inputs keep the generic per-row path. Dispatch with `MULTITARGET_FUNCTION_X86_V4`, like `sum`. Measured (50M rows, 1 thread, unpredictable 50% predicate, server-side query time): `varSampIf`/`stddevSampIf`/`skewSampIf`/`kurtSampIf` -64..-67%, `covarSampIf`/`corrIf` -59..-62%, `Nullable` -57%, and -35..-68% without `-If` (`varSamp`/`kurtSamp`/`corr`). Summation order changes, so float results can differ in the last bits; on integer inputs the moment sums are exact and results are bit-identical (covered by the test).
|
Workflow [PR], commit [d260f36] Summary: ✅
AI ReviewSummaryThis PR adds Final Verdict✅ No blocking findings in the current code. |
The new batch kernel for the variance family sums into 16 partial accumulators, so varPop(toFloat64(c)) now returns the exact 34 instead of the sequential loop's 34.00000000000001. Also suppress the cppcoreguidelines-pro-type-member-init false positive on keep_mask, which is fully assigned by the memset on the next line. Fast test report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110461&sha=6c3bdd8297593dd66e2837e8b2fa85dce706822a&name_0=PR&name_1=Fast%20test PR: ClickHouse#110461 Co-Authored-By: Claude Fable 5 <[email protected]>
… settings The `kurtPop int exact` and `kurtSamp int exact` checks compare a direct aggregation against a merge of partial states and assert the two are bit-identical. For the other moments this holds regardless of summation order, because their power sums stay exactly representable: with values in `[0, 1000)` over 70000 rows, `sum(x^2)` is ~2.3e10 and `sum(x^3)` is ~1.7e13, both well under 2^53. Kurtosis accumulates a sum of 4th powers, which reaches ~1.4e16 and exceeds 2^53, so the sum is inexact and its result depends on the summation order. That order is a function of `max_block_size` and the thread count, which the stateless test runner randomizes: at `max_block_size` >= 70000 the input fits into a single block and the rounding differs, flipping the comparison. The reference therefore froze incidental rounding noise (`0`) rather than a real invariant, and failed once CI picked `--max_block_size 72270`. Keep the values under 100 in these two checks, so that `sum(x^4)` is ~1.4e12 and stays exact. The comparison now asserts a genuine invariant (`1`), like every other function in the test, and holds across block sizes and thread counts. The `f64 approx` checks continue to cover the inexact case. Reproduced with `--max_threads 2 --max_block_size 72270` and verified over a sweep of block sizes, thread counts, two-level `GROUP BY` thresholds, and JIT aggregation.
The test aggregates a constant (0.1 over 1M rows) with the variance family and expected exactly 0. That expectation froze incidental rounding: with sequential accumulation of the raw power sums the error of m[2] - m[1]^2/n happened to land on the negative side, where getPopulation/getSample clamp it to zero. The new unrolled batch kernels change the summation order, the error lands on the positive side (~1e-15 for varSamp, ~3.5e-8 for stddevSamp), and the result now also depends on max_block_size, which the stateless runner randomizes (CI minimized the culprit to --max_block_size 51871). Assert the real invariant instead: the result is non-negative (the clamp works, and sqrt of an unclamped negative would give nan, failing the check) and near zero. The Stable variants use Welford's algorithm, stay sequential and order-independent, and keep the exact-zero expectation. Reproduced locally with the exact CI values and verified across a sweep of block sizes (1024..1000000) and thread counts. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110461&sha=aee51e5be6c001686010fb7da744a2ce1c7c3da8&name_0=PR&name_1=Stateless%20tests%20%28arm_binary%2C%20parallel%29 PR: ClickHouse#110461 Co-Authored-By: Claude Fable 5 <[email protected]>
The test verified the groupBit* batch kernels against an arrayFold with the scalar bit functions. arrayFold evaluates its lambda per element, so the 12 folds over 70000 rows for each of the 12 integer types cost ~10M interpreted lambda invocations. That took 27s in a release build and ~270s under ASan/UBSan, over the 180s limit of the stateless runner. Use arrayReduce with the aggregate function itself instead. arrayReduce goes through addBatchArray, which calls the scalar per-row add, so it still checks the new addBatchSinglePlace kernels against an independent path - and in fact a more relevant one, the function's own scalar implementation rather than the bit functions - but in compiled code instead of a lambda. Runtime drops from 27s to 0.5s, and the reference file is unchanged. Verified that the test still catches batch-kernel bugs: with an off-by-one injected into both the plain and the conditional addBatchSinglePlace paths, all 12 type lines fail. Note that the groupBitOr/groupBitAnd columns saturate to all-ones/all-zeros over 70000 random values, so they are insensitive to row-selection bugs and only catch type-width bugs; groupBitXor covers row selection. That property is unchanged by this commit. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110461&sha=93d8bca929a73e3b2c8cdfedd41be8d534428a89&name_0=PR PR: ClickHouse#110461 Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
📊 Cloud Performance Report ✅ AI verdict: This sync PR adds vectorized batch-aggregation paths for groupBitOr/And/Xor and the variance/stddev/skew/kurtosis/covariance/correlation functions; nothing in the general scan, join, or sum aggregation path changes. Neither flagged query exercises those functions: ClickBench Q18 has no bitwise or statistical aggregates, and TPC-H Q7 is a sum-based join query. Q7's +13.0% was flagged as a high-confidence regression, but it cannot be attributed to this diff and coincides with two source runs landing on the same host, so it is downgraded to not_sure as off-path variance. Q18's -5.2% is a marginal improvement on an unrelated query and is likewise noise. 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_officialFlagged 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
|
The random cross-checks feed 70k rows, so groupBitOr saturates to all-ones and groupBitAnd to all-zeros regardless of which rows each -If kernel's keep_mask selects; a row-selection bug specific to either formula could pass while groupBitXorIf stayed correct. Add a constructed case where bit 0 is set only in kept rows and the top bit only in dropped rows, so the kept subset does not saturate and each -If kernel proves its own masking formula. Covers the scalar path (UInt8) and the wide-integer memset path (UInt256). Co-Authored-By: Claude Opus 4.8 <[email protected]>
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 93/117 (79.49%) · Uncovered code |
Every failure in `Stateless tests (amd_tsan, flaky check)` on `b734075dd9f` was the 180 s per-run budget, not a wrong result: `03168_query_log_privileges_not_empty` (232 s and 199 s, passing at 94-145 s), `03008_optimize_equal_ranges` (185 s, passing at 158 s), `01343_min_bytes_to_use_mmap_io` (182 s, passing at 106 s) and `03735_async_insert_mergetree_count` (186 s, passing at 140-159 s). The three query-log ones failed on `SYSTEM FLUSH LOGS query_log` hitting its own 180 s timeout while the loaded TSan server drained the log queue. None of them is a signal this PR can produce: all three tests it touches are tagged `no-random-detach`, so the feature is off there and the change is the tag line itself; `03735_async_insert_mergetree_count` is not touched by this PR at all and fails the same way on unrelated pull requests (#110395, #110461). Tag them the same way as `03735_async_insert_mergetree` and the three tests tagged in `b734075dd9f`. https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=96130&sha=b734075dd9ff4ad835fa799a594445569fc02613&name_0=PR&name_1=Stateless%20tests%20%28amd_tsan%2C%20flaky%20check%29 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The merge of `master` brought in the vectorized `addBatchSinglePlace` and `addBatchSinglePlaceNotNull` for `AggregateFunctionVarianceSimple` added by #110461, which collided with the override introduced on this branch: AggregateFunctionStatisticsSimple.h:252:10: error: class member cannot be redeclared Every other error in the report cascades from that redeclaration. The implementation from `master` supersedes this branch's for every non-`Decimal` type - it accumulates into `128 / sizeof(T)` lanes rather than 4, dispatches to an AVX-512 variant through `MULTITARGET_FUNCTION_X86_V4`, and also covers the conditional and not-null paths - so keep it and drop this branch's `addManyTyped` along with its override. What `master` does not cover is `Decimal`: it routes those to the scalar per-row fallback, because the values need a per-row conversion with the source scale before they can be accumulated. Keep that part of this branch's work by staging a cache-resident tile of converted values and feeding the tile to the `addMany` kernel from `master`. For `varPop` over `Decimal128` in `00700_decimal_aggregates` this also brings the result back to the reference value, `34` rather than the `34.00000000000001` that the scalar path produces. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108648&sha=f8a5f4281a8d69cc20ce47354d36ec8587a7a413&name_0=PR&name_1=Fast%20test Related: #108648 Related: #110461 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_017MaihqgmEYC2qDoriB8aa3
The new batch kernel for the variance family sums into 16 partial accumulators, so varPop(toFloat64(c)) now returns the exact 34 instead of the sequential loop's 34.00000000000001. Also suppress the cppcoreguidelines-pro-type-member-init false positive on keep_mask, which is fully assigned by the memset on the next line. Fast test report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110461&sha=6c3bdd8297593dd66e2837e8b2fa85dce706822a&name_0=PR&name_1=Fast%20test PR: ClickHouse#110461 Co-Authored-By: Claude Fable 5 <[email protected]>
The test aggregates a constant (0.1 over 1M rows) with the variance family and expected exactly 0. That expectation froze incidental rounding: with sequential accumulation of the raw power sums the error of m[2] - m[1]^2/n happened to land on the negative side, where getPopulation/getSample clamp it to zero. The new unrolled batch kernels change the summation order, the error lands on the positive side (~1e-15 for varSamp, ~3.5e-8 for stddevSamp), and the result now also depends on max_block_size, which the stateless runner randomizes (CI minimized the culprit to --max_block_size 51871). Assert the real invariant instead: the result is non-negative (the clamp works, and sqrt of an unclamped negative would give nan, failing the check) and near zero. The Stable variants use Welford's algorithm, stay sequential and order-independent, and keep the exact-zero expectation. Reproduced locally with the exact CI values and verified across a sweep of block sizes (1024..1000000) and thread counts. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110461&sha=aee51e5be6c001686010fb7da744a2ce1c7c3da8&name_0=PR&name_1=Stateless%20tests%20%28arm_binary%2C%20parallel%29 PR: ClickHouse#110461 Co-Authored-By: Claude Fable 5 <[email protected]>
The test verified the groupBit* batch kernels against an arrayFold with the scalar bit functions. arrayFold evaluates its lambda per element, so the 12 folds over 70000 rows for each of the 12 integer types cost ~10M interpreted lambda invocations. That took 27s in a release build and ~270s under ASan/UBSan, over the 180s limit of the stateless runner. Use arrayReduce with the aggregate function itself instead. arrayReduce goes through addBatchArray, which calls the scalar per-row add, so it still checks the new addBatchSinglePlace kernels against an independent path - and in fact a more relevant one, the function's own scalar implementation rather than the bit functions - but in compiled code instead of a lambda. Runtime drops from 27s to 0.5s, and the reference file is unchanged. Verified that the test still catches batch-kernel bugs: with an off-by-one injected into both the plain and the conditional addBatchSinglePlace paths, all 12 type lines fail. Note that the groupBitOr/groupBitAnd columns saturate to all-ones/all-zeros over 70000 random values, so they are insensitive to row-selection bugs and only catch type-width bugs; groupBitXor covers row selection. That property is unchanged by this commit. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110461&sha=93d8bca929a73e3b2c8cdfedd41be8d534428a89&name_0=PR PR: ClickHouse#110461 Co-Authored-By: Claude Opus 4.8 <[email protected]>
…ngle-place Add vectorized batch paths for groupBit* and variance-family aggregate functions
groupBitOr/groupBitAnd/groupBitXorand the variance family (varPop,varSamp,stddevPop,stddevSamp,skewPop,skewSamp,kurtPop,kurtSamp,covarPop,covarSamp,corr) had noaddBatchSinglePlaceoverride, so the-Ifcombinator fell back to the generic per-row branch-guarded loop. This adds branchless batch kernels that accumulate into local values with the condition applied as an arithmetic mask, mirroringsum. For the floating-point moments the mask zeroes the value's bit pattern (so NaN/Inf in discarded rows cannot poison the result) and the loops unroll into 16 partial accumulators, which also speeds up the no--Ifcase by breaking the sequential FP dependency chain. Float summation order changes, so results can differ in the last bits.Measured with an unpredictable 50% predicate (50M rows, 1 thread):
groupBitOrIf-74% (UInt256: -51%),varSampIf..kurtSampIf-64..-67%,corrIf-59%,varSamp/kurtSamp/corrwithout-If-35..-68%; predictable predicates also improve, no regressions.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Vectorized batch paths for
groupBitOr/groupBitAnd/groupBitXorand the variance family (varPop,varSamp,stddevPop,stddevSamp,skewPop,skewSamp,kurtPop,kurtSamp,covarPop,covarSamp,corr): up to 4x faster with the-Ifcombinator on unpredictable conditions, and up to 3x faster for the variance family without it.Version info
26.7.1.1227(included in26.7and later)