Skip to content

Speed up aggregation batches with non-null states - #117009

Merged
alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
bobrik:ivan/add-batch-no-nulls
Sep 13, 2026
Merged

alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
bobrik:ivan/add-batch-no-nulls

Conversation

@bobrik

@bobrik bobrik commented Aug 29, 2026 •

Copy link
Copy Markdown
Contributor

Aggregations with lots of buckets can get expensive. Here's an excerpt from a profile:

ROUTINE ======================== DB::IAggregateFunctionHelper<DB::AggregateFunctionSum<unsigned long, unsigned long, DB::AggregateFunctionSumData<unsigned long>, (DB::AggregateFunctionSumType)0> >::addBatch(unsigned long, unsigned long, char**, unsigned long, DB::IColumn const**, DB::Arena*, long) const in src/AggregateFunctions/IAggregateFunction.h
     1.79s      2.32s (flat, cum) 15.07% of Total
         .          .    549:            }
         .          .    550:        }
         .          .    551:        else
         .          .    552:        {
         .          .    553:            for (size_t i = row_begin; i < row_end; ++i)
     1.79s      1.79s    554:                if (places[i])
         .   526.32ms    555:                    static_cast<const Derived *>(this)->add(places[i] + place_offset, columns, i, arena);
         .          .    556:        }
         .          .    557:    }
         .          .    558:
         .          .    559:    void serializeBatch(const PaddedPODArray<AggregateDataPtr> & data, size_t start, size_t size, WriteBuffer & buf, std::optional<size_t> version) const final // NOLINT
         .          .    560:    {

We can get some of this back by specializing the common non-null version.

For a big query doing a very wide aggregation (with improvements from #115925):

  • 1 thread: 77.7s -> 74.3s (both wall and cpu)
  • 64 threads: 17.0s -> 16.0s (wall), 99.5s -> 92.4s (cpu)

Before:

image

After:

image

With a synthetic benchmark:

  • Baseline: 1.24s
$ ../bench.py --clickhouse=/tmp/clickhouse-baseline --path=$HOME/clickhouse-no-nulls --runs=3 --query="SELECT toUInt16(bitAnd(number, 8191)) AS key, sum(number) FROM numbers(500000000) GROUP BY key FORMAT Null SETTINGS max_threads = 1"
wall:   1.24s, cpu:   1.23s, memory:   0.00GiB
wall:   1.25s, cpu:   1.24s, memory:   0.00GiB
wall:   1.23s, cpu:   1.23s, memory:   0.00GiB
  • Patched: 1.10s
$ ../bench.py --clickhouse=/tmp/clickhouse-no-nulls --path=$HOME/clickhouse-no-nulls --runs=3 --query="SELECT toUInt16(bitAnd(number, 8191)) AS key, sum(number) FROM numbers(500000000) GROUP BY key FORMAT Null SETTINGS max_threads = 1"
wall:   1.10s, cpu:   1.09s, memory:   0.00GiB
wall:   1.10s, cpu:   1.09s, memory:   0.00GiB
wall:   1.11s, cpu:   1.10s, memory:   0.00GiB

Changelog category (leave one):

  • Performance Improvement

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Speed up aggregation batches with non-null states.


Workflow [PR]
Sync PR [sync-upstream/pr/117009]

Version info

  • Merged into: 26.9.1.1381 (included in 26.9 and later)

@bobrik

bobrik commented Aug 31, 2026

Copy link
Copy Markdown
Contributor Author

@alexey-milovidov good to test? This one is tiny unlike the others.

@cv4g cv4g added pr-performance Pull request with some performance improvements can be tested Allows running workflows for external contributors labels Sep 1, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [e4bbb92]

Summary: ✅


AI Review

Summary

This PR adds an addBatchWithNonNullPlaces fast path in Aggregator and propagates it through the touched combinators so batches that already have aggregate states can skip the redundant places[i] null check. I re-checked the previously reported combinator regressions against the current head, and I did not find any remaining correctness, safety, or performance blockers in the current diff.

Final Verdict

✅ No blocking or major issues found in the current head of this PR.

LLVM Coverage Report

⚠️ No coverage measurement for commit e4bbb92: incomplete coverage measurement: 1 of 21 shard profiles are missing: LLVM_COVERAGE_FILE_it_7.profdata.

@bobrik
bobrik force-pushed the ivan/add-batch-no-nulls branch from 4e8db4b to e395857 Compare September 1, 2026 15:34
@clickhouse-gh

clickhouse-gh Bot commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 42 queries analysed

no significant changes detected. K_source=6 K_base=30 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: d4fd3b4f-b482-44c1-8f0e-9ba90fc17387
  • MIRAI run: e3cee05f-e6ba-4134-9b84-5ea8c2242205
  • PR check IDs:
    • clickbench_1110772_1788488376
    • clickbench_1110903_1788488382
    • clickbench_1111000_1788488386
    • tpch_adapted_1_official_1111107_1788488390
    • tpch_adapted_1_official_1111218_1788488412
    • tpch_adapted_1_official_1111320_1788488424

@clickhouse-gh

clickhouse-gh Bot commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing e4bbb92ba with master dfde23932 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

⚠️ Significant changes: object file sizes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 714.21 MiB 713.51 MiB -721.40 KiB (-0.10%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes ⚠️

129 object files changed (+3.94 MiB total), 0 added.

Object file Master PR Δ
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionsArgMinArgMax… 15.47 MiB 15.85 MiB +388.58 KiB (+2.45%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionAvgWeighted.c… 12.46 MiB 12.77 MiB +318.14 KiB (+2.49%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionUniq.cpp.o 10.59 MiB 10.80 MiB +222.21 KiB (+2.05%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionSparkbar.cpp.o 5.03 MiB 5.18 MiB +150.85 KiB (+2.93%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionQuantileExact… 6.48 MiB 6.62 MiB +147.49 KiB (+2.22%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionGroupArray.cp… 4.38 MiB 4.52 MiB +141.74 KiB (+3.16%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionDeltaSumTimes… 3.35 MiB 3.48 MiB +134.88 KiB (+3.93%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionCorr.cpp.o 6.45 MiB 6.58 MiB +129.31 KiB (+1.96%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionCovar.cpp.o 6.28 MiB 6.40 MiB +116.57 KiB (+1.81%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionGroupArrayMov… 5.40 MiB 5.50 MiB +107.61 KiB (+1.95%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionQuantile.cpp.o 3.50 MiB 3.59 MiB +97.38 KiB (+2.72%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionGroupUniqArra… 2.37 MiB 2.46 MiB +90.34 KiB (+3.72%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionQuantileDeter… 2.65 MiB 2.74 MiB +88.94 KiB (+3.28%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionGroupNumericI… 7.19 MiB 7.28 MiB +88.06 KiB (+1.20%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionQuantileGK.cp… 3.14 MiB 3.21 MiB +73.98 KiB (+2.30%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionQuantileInter… 3.30 MiB 3.37 MiB +70.22 KiB (+2.08%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/TimeSeries/AggregateFunctionTi… 4.98 MiB 5.04 MiB +64.65 KiB (+1.27%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionAny.cpp.o 2.39 MiB 2.45 MiB +59.55 KiB (+2.43%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionsMinMax.cpp.o 2.38 MiB 2.43 MiB +56.14 KiB (+2.31%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionBitwise.cpp.o 2.09 MiB 2.14 MiB +54.27 KiB (+2.54%)

716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

350 translation units recompiled, 2743 s compile time in total, 350 of them have a recent master baseline.

Job report

@bobrik
bobrik force-pushed the ivan/add-batch-no-nulls branch from e395857 to f23a944 Compare September 2, 2026 16:10
Comment thread src/Interpreters/Aggregator.cpp Resolved
@bobrik

bobrik commented Sep 2, 2026

Copy link
Copy Markdown
Contributor Author

Updated to extend this to combinators. It helped sumOrDefault (1.64s -> 1.50s), but no change for sumIf (1.35s).

@bobrik
bobrik force-pushed the ivan/add-batch-no-nulls branch from afe64f2 to ba0e79f Compare September 3, 2026 05:34
@bobrik

bobrik commented Sep 3, 2026

Copy link
Copy Markdown
Contributor Author

Rebased some more to hopefully please the CI gods.

@cv4g if you could review, that would be greatly appreciated. It seems like a clear and simple win to me.

@bobrik
bobrik force-pushed the ivan/add-batch-no-nulls branch from ba0e79f to 22999c5 Compare September 3, 2026 06:23
Aggregations with lots of buckets can get expensive. Here's an excerpt from a profile:

```
ROUTINE ======================== DB::IAggregateFunctionHelper<DB::AggregateFunctionSum<unsigned long, unsigned long, DB::AggregateFunctionSumData<unsigned long>, (DB::AggregateFunctionSumType)0> >::addBatch(unsigned long, unsigned long, char**, unsigned long, DB::IColumn const**, DB::Arena*, long) const in src/AggregateFunctions/IAggregateFunction.h
     1.79s      2.32s (flat, cum) 15.07% of Total
         .          .    549:            }
         .          .    550:        }
         .          .    551:        else
         .          .    552:        {
         .          .    553:            for (size_t i = row_begin; i < row_end; ++i)
     1.79s      1.79s    554:                if (places[i])
         .   526.32ms    555:                    static_cast<const Derived *>(this)->add(places[i] + place_offset, columns, i, arena);
         .          .    556:        }
         .          .    557:    }
         .          .    558:
         .          .    559:    void serializeBatch(const PaddedPODArray<AggregateDataPtr> & data, size_t start, size_t size, WriteBuffer & buf, std::optional<size_t> version) const final // NOLINT
         .          .    560:    {
```

We can get some of this back by specializing the common non-null version.

For a big query doing a very wide aggregation:

* 1 thread: 77.7s -> 74.3s (both wall and cpu)
* 64 threads: 17.0s -> 16.0s (wall), 99.5s -> 92.4s (cpu)

With a synthetic benchmark:

* Baseline: 1.24s

```
$ ../bench.py --clickhouse=/tmp/clickhouse-baseline --path=$HOME/clickhouse-no-nulls --runs=3 --query="SELECT toUInt16(bitAnd(number, 8191)) AS key, sum(number) FROM numbers(500000000) GROUP BY key FORMAT Null SETTINGS max_threads = 1"
wall:   1.24s, cpu:   1.23s, memory:   0.00GiB
wall:   1.25s, cpu:   1.24s, memory:   0.00GiB
wall:   1.23s, cpu:   1.23s, memory:   0.00GiB
```

* Patched: 1.10s

```
$ ../bench.py --clickhouse=/tmp/clickhouse-no-nulls --path=$HOME/clickhouse-no-nulls --runs=3 --query="SELECT toUInt16(bitAnd(number, 8191)) AS key, sum(number) FROM numbers(500000000) GROUP BY key FORMAT Null SETTINGS max_threads = 1"
wall:   1.10s, cpu:   1.09s, memory:   0.00GiB
wall:   1.10s, cpu:   1.09s, memory:   0.00GiB
wall:   1.11s, cpu:   1.10s, memory:   0.00GiB
```
Move the non-null batch implementation to `IAggregateFunctionHelper`
and propagate the guarantee through `AggregateFunctionIf`,
`AggregateFunctionOrFill`, and `AggregateFunctionTuple`.

Preserve specialized timeseries batching.

For `sumOrDefault` over 500 million rows and 8192 groups: 1.64s -> 1.5s.

No measurable change was observed for `sumIf`.
@bobrik
bobrik force-pushed the ivan/add-batch-no-nulls branch from 22999c5 to e4bbb92 Compare September 3, 2026 16:09
@bobrik

bobrik commented Sep 4, 2026

Copy link
Copy Markdown
Contributor Author

CI is finally all green ✅

@clickhouse-gh clickhouse-gh Bot added the comp-aggregation GROUP BY / aggregation framework (hash tables, spilling, external aggregation). label Sep 4, 2026

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is great!

@alexey-milovidov alexey-milovidov self-assigned this Sep 13, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 13, 2026
Merged via the queue into ClickHouse:master with commit ace35a5 Sep 13, 2026
174 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 13, 2026
yackushevas pushed a commit to yackushevas/ClickHouse that referenced this pull request Nov 15, 2026
The 2048- and 4096-group entries of uniq_multi_place.xml (query indexes
5, 6, 12, 13, 19, 20) take 1.03-2.96 s on MasterCI amd and 1.15-2.58 s
on arm; the three 4096-group ones are above report.py's 2 s single-run
limit. Each group gets 16384 distinct values, so the time is the
groups x 16384 single-threaded state insertions.

No existing query number or text changes: the one query (21 entries) is
disabled, and the same query over 64 to 1024 groups is appended as
21-35, byte-identical to entries 0-4, 7-11 and 14-18.

The batched hash-and-prefetch insert of ClickHouse#119594 that the file measures
already shows at 1024 groups. On the 457 master commits of
2026-09-12..24, with that path (before ClickHouse#117009 or after ClickHouse#120578) and
without it (between the two), 1024 groups keep 95-128% of the
2048/4096-group speedup on amd, and on arm 91-97% of the 2048-group one
and 69-88% of the 4096-group one (bootstrap p5 0.64, arm
uniqCombined64).

About 1 minute less query time per master perf job on each architecture.

Related: ClickHouse#129258

Co-Authored-By: Claude Opus 5.5 <[email protected]>
zvonand added a commit to Altinity/ClickHouse that referenced this pull request Nov 18, 2026
Antalya 26.8: Backport of ClickHouse#117009 Speed up aggregation batches with non-null states
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-aggregation GROUP BY / aggregation framework (hash tables, spilling, external aggregation). pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants