Skip to content

Do not value-initialise the merged flag buffers in batch aggregation - #118025

Merged
Algunenano merged 4 commits into
ClickHouse:masterfrom
groeneai:groeneai/117947-span-size-agg-if-flag-buffer
Sep 9, 2026
Merged

Algunenano merged 4 commits into
ClickHouse:masterfrom
groeneai:groeneai/117947-span-size-agg-if-flag-buffer

Conversation

@groeneai

@groeneai groeneai commented Sep 4, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #116952
Closes: #117511
Closes: #117947

Changelog category (leave one):

  • Performance Improvement

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 -If condition into a temporary flag buffer, when a block is consumed in increasing sub-ranges as optimize_aggregation_in_order and window frames do. The buffer is no longer value-initialized, and in sum and avg it is also sized to the rows actually processed instead of to the end of the block. This affects sum, avg, the -If combinator over Nullable arguments, min/max/argMin/argMax with -If, aggregate functions with two or more Nullable arguments such as corr and quantileExactWeighted, and the timeSeries* 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/AggregateFunctions build a merged null/condition flag buffer for them with std::make_unique<UInt8[]>(row_end), which value-initialises row_end bytes although only [row_begin, row_end) is ever written or read. A block of N rows cut into g intervals therefore zeroes about N*(g+1)/2 bytes to produce N useful ones.

sum and avg are 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 stays row_end and only the value-initialisation goes, via std::make_unique_for_overwrite. AggregateFunctionNullVariadic also 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 SelectedRows and ReadCompressedBytes identical between arms: minIf 29% faster, sumIf over a Nullable condition 24%, argMinIf 38%, corr over two Nullable arguments 13%, timeSeriesGroupArrayIf 50%, 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 0xAA before 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
Site Change Reached from SQL by
AggregateFunctionSum.h, AggregateFunctionAvg.h right-sized to the span, value pointer rebased sumIfOrDefault, avgIfOrDefault
Combinators/AggregateFunctionIf.cpp, AggregateFunctionIfNullUnary make_unique_for_overwrite minIf(x, cond), varSampIf(x, cond), the same in a window frame
Combinators/AggregateFunctionIf.cpp, AggregateFunctionIfNullVariadic make_unique_for_overwrite sumIf(y, nullable_cond), avgWeightedIf, argMinIf, corrIf
Combinators/AggregateFunctionNull.h, first buffer make_unique_for_overwrite none of the 17 combinator shapes I tried: the generic null adapter is always outermost, and every path that would give it a real if_argument_pos is intercepted by AggregateFunctionIf::getOwnNullAdapter. Changed with its neighbour
Combinators/AggregateFunctionNull.h, second buffer make_unique_for_overwrite plus seed-then-OR corr(x, w), covarPop, quantileExactWeighted over two Nullable arguments, the same in a window frame
SingleValueData.cpp, mergeIfAndNullFlags make_unique_for_overwrite argMinIf, argMaxIf
the three TimeSeries/ kernels make_unique_for_overwrite timeSeriesRateToGridIf, timeSeriesGroupArrayIf, timeSeriesLastTwoSamplesIf, behind allow_experimental_time_series_aggregate_functions
AggregateFunctionBitwise.cpp, AggregateFunctionStatisticsSimple.h unchanged new UInt8[row_end] default-initialises, so there is nothing to remove. Right-sizing their allocation is worth a further 6.9% to 16.0% on groupBitOrIf and varSampIf, a different mechanism that is not part of this change

Two SingleValueData consumers also return the absolute index, so rebasing there would be out of bounds, and the two timeSeries* kernels share a path that is given a raw column pointer.

Analysis and patch by @ snelheidai.

Version info

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

groeneai and others added 2 commits September 4, 2026 01:21
…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.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Sep 4, 2026
@groeneai

groeneai commented Sep 4, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review

An independent model reviewed the diff cold, three times. The final round found nothing.

⚠️ It argued the new stateless test is non-discriminating because it also passes on master. Agreed
on the fact and kept the test: the change is bit-identical by construction, so the test guards the
index rebase, and three mutants of that rebase redden it while no existing stateless test catches
even the mildest. What the review was right about is that SET optimize_aggregation_in_order = 1
does not prove the optimizer chose that path, so the test now asserts the plan explicitly, with a
negative control. That assertion is safe under randomization: of the three settings gating the
optimization only that one is randomized, and a session SET overrides the runner.

💡 Three nits left alone: the result comparison is one-directional (a mis-rebase changes values, not
group cardinality), the plan assertion explains the bare SELECT rather than the CREATE ... AS SELECT beside it, and the commit subject does not backtick -If.

@clickhouse-gh clickhouse-gh Bot closed this Sep 4, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 4, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [ef6a52d]

Summary: ❌

job_name test_name status info comment
Docker server image FAIL
clickhouse/clickhouse-server:head-arm64 FAIL cidb IGNORED
clickhouse/clickhouse-server:head-distroless-arm64 FAIL cidb IGNORED
Stress test (amd_debug) FAIL
Logical error: Invalid number of columns in chunk pushed to OutputPort. Expected A, found B (STID: 2270-3258) FAIL cidb, issue ISSUE EXISTS

AI Review

Summary

This PR removes redundant value-initialization from temporary merged null/-If flag buffers in batch aggregation, and it right-sizes the sum/avg buffer where the consumer can work on a rebased span. I reviewed the current diff, the touched aggregate-function paths, the new tests, and the prior discussion, and I did not find a correctness, safety, or evidence gap that warrants an inline review comment.

Final Verdict

✅ No findings.

LLVM Coverage Report

Measured on commit ef6a52d.

Metric Baseline Current Δ
Lines 88.70% 88.70% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 81.10% 81.10% +0.00%

Changed lines: Changed C/C++ lines covered: 52/55 (94.55%) · Uncovered code

Full report · Diff report

@groeneai

groeneai commented Sep 4, 2026

Copy link
Copy Markdown
Collaborator Author

cc @rschu1ze @KochetovNicolai, could you review this? addBatchSinglePlaceNotNull in sum and avg sizes the merged null/condition flag buffer to row_end and value-initializes it, although only [row_begin, row_end) is written or read, so a caller that walks one block in increasing sub-ranges re-zeroes the whole dead prefix on every call: aggregation in order does that once per sorting-key interval, and window frames do it with no setting at all. Sizing the buffer to the written span and passing the value pointer offset by row_begin with start = 0 is bit-identical, because both kernels already begin ptr += start; condition_map += start; count = end - start.

@Algunenano Algunenano self-assigned this Sep 4, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

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

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

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.

Compile time of recompiled translation units

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

Job report

@clickhouse-gh

clickhouse-gh Bot commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

🟢 AI verdict: improvement — 1 query(s) improved out of 40 analysed

1 improved query(s). K_source=6 K_base=30 flagged=1/65

clickbench

⚠️ 1 inconclusive

Flagged queries (1 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 18 not_sure 1064 1120 +5.4% <0.0001

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)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
🟢 17 improvement 100 67 -33.0% <0.0001

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
  • StressHouse run: c0e05bca-acfb-47e8-bdbe-e71f688e4a4b
  • MIRAI run: ea2e376f-1ab9-4844-a2ed-4fff1e2506af
  • PR check IDs:
    • clickbench_1250139_1788568518
    • clickbench_1250241_1788568524
    • clickbench_1250344_1788568557
    • tpch_adapted_1_official_1250471_1788568569
    • tpch_adapted_1_official_1250638_1788568741
    • tpch_adapted_1_official_1250796_1788568824

@clickhouse-gh clickhouse-gh Bot added the comp-aggregate-functions Aggregate function implementations (sum, avg, count, quantile, combinators, etc.). label Sep 4, 2026
`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.
@groeneai groeneai changed the title Do not zero a block-sized flag buffer per batch in sum and avg with -If over Nullable Do not value-initialise the merged flag buffers in batch aggregation Sep 4, 2026
@groeneai

groeneai commented Sep 4, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review

An independent model reviewed the consolidated diff cold. No blockers, one nit, which I had also
found in my own pass, so I am recording it rather than churning a commit for it.

⚠️ The comment above the seed-then-OR merge in AggregateFunctionNullVariadic::addBatchSinglePlace
overstates its invariant. A third case exists beyond the two it names: the buffer was built for the
condition flags but not pushed, because every row passed. The code is right there, since the span is
then all zero and seeding from filter 0 is what the old |= did anyway. Accurately: seed the span
from filter 0 unless the buffer already IS filter 0, because anything it held before is all zero
over the span.

💡 One nit left alone: that site is the only converted allocation without the shared Default-init:
one-liner, because its invariant is the one above rather than the shared one.

@groeneai

groeneai commented Sep 5, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - ef6a52d

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Docker server image / clickhouse/clickhouse-server:head-arm64 apt mirror 503 on the arm64 index fetch (us-east-1.ec2.ports.ubuntu.com), which apt-get update only warns about, so apt-get install then reports Package 'busybox' has no installation candidate #118023 (mine, open)
Docker server image / clickhouse/clickhouse-server:head-distroless-arm64 same apt mirror 503 shape, Dockerfile.distroless #118023 (mine, open)
Stress test (amd_debug) / Invalid number of columns in chunk pushed to OutputPort. Expected 0, found 1 (STID 2270-3258) trunk bug, empty-header divergence in RemoteSource::prepare for a distributed query with no referenced table column #113469 (mine, open)
Sync - CH Inc sync (private, not actionable by me)

Session id: cron:our-pr-ci-monitor:20260905-030000

alexey-milovidov pushed a commit to fastio/ClickHouse that referenced this pull request Oct 10, 2026
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]>
subkanthi pushed a commit to subkanthi/ClickHouse that referenced this pull request Nov 23, 2026
…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]>
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-aggregate-functions Aggregate function implementations (sum, avg, count, quantile, combinators, etc.). groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

3 participants