Skip to content

Fix quadratic key packing in aggregation in order and DISTINCT in order - #120259

Merged
alexey-milovidov merged 11 commits into
ClickHouse:masterfrom
groeneai:fix-agg-in-order-fixed-keys-quadratic
Oct 10, 2026
Merged

alexey-milovidov merged 11 commits into
ClickHouse:masterfrom
groeneai:fix-agg-in-order-fixed-keys-quadratic

Conversation

@groeneai

@groeneai groeneai commented Sep 15, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #45386
Related: #110159
Related: #118025

Changelog category (leave one):

  • Performance Improvement

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

With optimize_aggregation_in_order = 1, or with the default optimize_distinct_in_order = 1, a GROUP BY or DISTINCT whose keys extend past the table's sorting key no longer re-packs the whole block's grouping key once per run of equal sorting-key values. That cost was quadratic in max_block_size once the sorting prefix is near-unique, so GROUP BY a, b on a table sorted by a is up to 130x faster. Closes #45386.

Description

AggregatingInOrderTransform splits each block into runs of equal sorting-key value and builds a fresh Method::State per run. For a fixed-size key satisfying usePreparedKeys, that constructor batch-packed the grouping key of the whole block: packFixedBatch writes out[i] for every row of the key column and getKeyHolder reads prepared_keys[row], so the array index is the absolute block row. One block therefore cost O(runs * block_size).

A state built over a sub-range (ColumnsHashing::SubRangeState, a template parameter of HashMethodKeysFixed) now packs just that sub-range: a range of at least 256 rows into an array indexed relative to its first row, a shorter one per row on demand, both in the byte layout packFixedBatch produces (one pass per key width, longest first; shuffleKeyColumns makes the output side read it back in that order). A row outside the array is packed on demand too. Every other state compiles master's code, so whole-block callers (IN sets, LIMIT BY, joins, whole-block GROUP BY) keep master's hot loops instruction for instruction. Aggregator::method_chosen_for_in_order already makes this trade for serialized keys.

Three other consumers build one state per sub-range and now use it too: Aggregator::mergeOnBlockSmall, DistinctSortedStreamTransform::buildFilterForRange and MergeTreeIndexAggregatorSet::buildFilter.

Measured (release, ORDER BY a, max_threads = 1, query CPU time, paired geometric mean [95% CI] against master, 9 interleaved reps pinned to one core): a unique, GROUP BY a, b 6.119 s -> 0.046 s; 256 rows per a 0.502 [0.496, 0.508]; 4096 rows 0.933 [0.921, 0.946]; 65536 rows 0.991 [0.976, 1.007]. DISTINCT a, b, c behaves the same way. Both optimisations off are at parity. The in-order copies of the aggregation loops add 443 KB to Aggregator.o.

The array is sized to the sub-range, not its absolute end, so allocated bytes per block stay linear: with jemalloc_enable_global_profiler armed, 256 rows per a measures 0.443 [0.438, 0.448] of master.


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

Version info

  • Merged into: 26.10.1.2025-master (included in 26.10 and later)

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]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-issue PR origin: picked up an external GitHub issue labels Sep 15, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (click to expand)

Two independent reviews ran against this branch before it was published: an automated second-model pass
and a separate code review that did not see the author's evidence. Five rounds; the final round returned
no blockers and no majors from either pass. Everything agreed along the way is in the tree.

Item Verdict
❌ The regression test's max_execution_time guard was calibrated only on a jemalloc build. packFixedBatch sizes prepared_keys to the range's absolute end, so each per-run state requests memory proportional to its position in the block while touching only its own rows - the linear wall clock is therefore a property of the allocator, and jemalloc is disabled under every sanitizer except UBSan. Agreed; the guard was re-measured on an allocator that writes every allocated byte, re-set from that measurement, and both mutation proofs re-run at the new value.
❌ The two identity comparisons that carry the layout coverage (a window starting at a non-zero row; a non-descending key-size order) had no in-order plan assertion, so they would have returned 1 unconditionally the day the optimizer stopped choosing that plan. Agreed; each now carries an EXPLAIN PIPELINE assertion, and each assertion was mutation-checked.
❌ Neither StateNoCache arm had a timed guard: reverting only the range argument at Aggregator.cpp:1118 or :4979 left the suite green. Agreed; each now has one. Reaching them needs is_simple_count, and the guard has to consume the inner count() (sum(n), not count()) or the analyzer prunes it and the query collapses onto the cache-using sibling.
❌ The DISTINCT sibling (DistinctSortedStreamTransform::buildFilterForRange) and the merging in-order path (mergeOnBlockSmall) have the same defect. Agreed; both fixed and measured (122x and 64x), each with its own guard. DISTINCT needed a system.processors_profile_log row-count oracle as well, because the final DistinctTransform above the sorted one absorbs over-emission.
⚠️ The commit message described the residual as "O(1) per run". That is O(1) allocation calls; the requested size is proportional to the row range's absolute end. Agreed; qualified in the commit message.
⚠️ Changelog category. Agreed and matched to #110159, the merged fix for the same defect class one method family over. Downgrade it if you would rather this were not a backport candidate.

Residuals, kept deliberately:

  • 💡 The per-run allocation above. Indexing relative to row_begin would remove it, but measured
    +2.9% / +4.1% on the keys64 whole-block median (two 100-sample A/B runs, non-overlapping quartiles)
    against a +0.00% duration-matched control, and needs pointer arithmetic -fsanitize=pointer-overflow
    rejects. Hoisting the state out of the per-run loop removes it entirely, at the cost of type erasure
    over ~30 variants in the hottest engine path - a different PR if that trade is preferred.
  • 💡 MergeTreeIndexAggregatorSet::buildFilter is the third per-sub-range caller and is left alone:
    update() allocates IColumn::Filter filter(block.rows(), 0) and calls
    column->filter(filter, block.rows()) on every per-granule call, so the range argument alone would
    not make that path linear. Its /// Like DistinctSortedStreamTransform. comment is now incomplete for
    that reason; not amended rather than adding a file to the diff for one line.
  • 💡 The serialized methods keep their whole-block batch serialization - the per-run path already avoids
    them via method_chosen_for_in_order (Fix quadratic aggregation in order with the prealloc-serialized method #110159), so they take the row range and ignore it.
  • 💡 The adaptive slicer's two constructions cannot be given an oracle: every executeOnBlock caller
    passes row_begin = 0, so the range there always equals the default.

Checked rather than assumed, in the final round: prepared_keys is never read outside the declared range
(getKeyHolder is its only reader, and every prefetch look-ahead is bounded by row_end or key_end);
the packed byte layout is master's, restricted to the range, for a non-size-descending key order; the
sanitizer tags do not make Bugfix validation vacuous (amd_debug is last in BUGFIX_BUILD_TYPES and
Result.is_ok() accepts SKIPPED); and the table-level granularity pins survive
--random-merge-tree-settings, since ClientBase::addMergeTreeSettings injects only when the setting is
not already present.

Session id: cron:clickhouse-review-slot-10:20260915-182400

@clickhouse-gh

clickhouse-gh Bot commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [885feab]

Summary: ✅


AI Review

Summary

This PR limits the new sub-range prepared-key path to the three callers that actually build one hashing state per block sub-range — AggregatingInOrderTransform, DistinctSortedStreamTransform, and MergeTreeIndexAggregatorSet — while keeping whole-block consumers on their pre-PR key path. I re-read the current diff, prior inline threads, and the surrounding code, and I did not find remaining correctness, performance-contract, or PR-metadata issues.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Measured on commit 885feab.

Metric Baseline Current Δ
Lines 88.20% 88.20% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 79.60% 79.60% +0.00%

Changed lines: Changed C/C++ lines covered: 115/115 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 15, 2026
@groeneai groeneai changed the title Closes: https://github.com/ClickHouse/ClickHouse/issues/45386 Fix quadratic key packing in aggregation in order and DISTINCT in order Sep 15, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-aggregation GROUP BY / aggregation framework (hash tables, spilling, external aggregation). label Sep 15, 2026
Every CI server installs tests/config/config.d/jemalloc_enable_global_profiler.yaml, so
jemalloc samples every allocation past its 512 KiB sampling interval and takes a backtrace
for it. Both the fixed and the broken path allocate one block-sized array per run of equal
sorting-key value, so all 800000 runs of the first table are sampled: with that config an
idle release build spends 10.25 s, 10.36 s and 8.33 s on the three guards over that table
and 52.56 s on the file through the stateless runner, against 4.88 s for the file without
it (1409431 samples over 3.34 TiB of sampled allocations for the first guard alone, against
374 samples for the same query with optimize_aggregation_in_order = 0).

The fast test kills a test at 60 s (ci/jobs/fast_test.py, --timeout 60 with
--jobs 3/4*nproc), which is what turned this file red: 17.35 s, 17.70 s and 12.50 s for
those same three guards on a 32-vCPU runner, then the kill inside the fourth. No fixture
size fits that. A guard allows the fixed path 120 s because a linear path stretches that
far on the slow flavours, and the broken side exceeds the limit by re-packing a whole block
per run, which costs O(runs * block_rows) against the fixed path's O(runs), so shrinking
the fixture cuts the margin quadratically and cutting the limit takes back the headroom the
slow flavours need.

The tag keeps the file out of the fast test, out of the llvm_coverage flavours that pass
--no-long, and out of the flaky check's 180 s "runs too long" verdict, and leaves every
other stateless flavour running it unchanged, including the amd_debug run that validates
the bugfix (ci/jobs/functional_tests.py adds --no-long for llvm_coverage only).

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Fast test was red on the previous head because of the new test in this PR, not the fix:
05217_aggregation_in_order_fixed_keys was killed at that job's 60 s per-test cap after spending
17.4 s, 17.7 s and 12.5 s on its first three timed guards. I tagged it long (ca60688); the guards,
their sizes and their limits are unchanged, and I corrected two header statements my measurements
falsified.

Why no fixture size fits that cap: a guard allows the fixed path 120 s because a linear path stretches
that far on the slow flavours, and the broken side exceeds the limit by re-packing a whole block per
run, which costs O(runs * block_rows) against the fixed path's O(runs), so shrinking the fixture cuts
the margin quadratically. The tag keeps the file out of the fast test, out of the llvm_coverage
flavours that pass --no-long, and out of the flaky check's 180 s "runs too long" verdict; every other
stateless flavour still runs it, including the amd_debug run that validates the bugfix.

What makes the fixed path cost 10 s per guard here (measured)

Every CI server installs tests/config/config.d/jemalloc_enable_global_profiler.yaml, so jemalloc
samples every allocation past its 512 KiB interval and takes a backtrace for it, and both the fixed and
the broken path allocate one block-sized array per run of equal sorting-key value. One idle release
build, same binary, only that config differing: the file takes 4.9 s with the profiler off and 52.4 s
with it on, and the first guard 0.56 s against 10.25 s, the latter with 1409431 jemalloc samples over
3.34 TiB of sampled allocations, against 374 samples for the same query with
optimize_aggregation_in_order = 0.

Session id: cron:clickhouse-maint-slot-13:20260915-214900

groeneai and others added 2 commits September 16, 2026 09:06
`HashMethodKeysFixed`'s constructor batch-packs the grouping key of the whole
column when `usePreparedKeys(key_sizes)` holds: `packFixedBatch` writes `out[i]`
for every row of the key column, and `getKeyHolder` reads `prepared_keys[row]`,
so the array index is the absolute block row. Four callers build one state per
sub-range of a block, so a block costs `runs * block_rows` key packs.

A state whose `RowRange` does not cover the whole column now skips the batch
instead of shrinking it, and packs each key on demand. That is the trade
`Aggregator::method_chosen_for_in_order` already makes for serialized keys: a
method whose state construction is proportional to the whole block falls back to
a lazy per-row path on the per-run path to keep it linear. Whole-block callers
pass the default range and keep the previous code path, including the batched
read and the SSSE3 mask construction.

The range plumbing `packFixedBatch` and `fillFixedBatch` gained is reverted, so
those two are again what master has. Sizing the array to the range's last
absolute row left allocated bytes per block quadratic, which the jemalloc global
profiler every CI test server enables charges per allocated byte: release, 800000
rows, `max_block_size = 200000`, `GROUP BY a, b` in order, min of 5, that arm
measured 0.71 s with the profiler off and 10.17 s with it on. A non-batching
state allocates nothing, and measures 0.37 s either way.

The per-row packer has to reproduce the batch layout byte for byte.
`packFixedBatch` lays keys out longest first, one pass per width, while
`packFixed` and `packFixedShuffle` lay them out in clause order, and the output
side keys off `usePreparedKeys` alone: `shuffleKeyColumns` reorders the output key
columns into longest-first order whenever it holds, batched or not. Hence
`packFixedLongestFirst`, which mirrors `packFixedBatch`'s pass order. It is
`NO_INLINE`: inlining it into every `getKeyHolder` instantiation grew `.text` by
6,302,464 bytes, against 18,688 out of line, with no measurable difference on the
path that uses it.

The whole-block path is unchanged and measures so. Release, 40M rows, two UInt32
keys, `max_threads = 1`, 12 aggregations per sample, arms interleaved: taking the
mean of the two arm orders, min +0.25%, p10 +0.78%, median +0.69% against
`origin/master` built in the same directory. An A/A control that runs the baseline
binary in both arms reports min -2.09% and median +0.77%, so those deltas are
inside the harness noise.

`05217_aggregation_in_order_fixed_keys` moves its two aggregation guards to an
800000-row block, which raises the broken cost from about 116 s to about 465 s
against their 120 s limit, and drops `no-asan, no-msan, no-tsan`: the slowest
single guarded query measures 0.48 s on a debug build with the CI profiler config
armed, so even a 20x sanitizer multiplier stays far under the limit. Forcing the
batch back on makes all five timed guards fail with `TIMEOUT_EXCEEDED`, four at
about 120 s and the DISTINCT one at 338.59 s, while every plan assertion and
identity check still passes.

`MergeTreeIndexAggregatorSet::buildFilter` is the fourth per-sub-range caller and
now passes its range. `gtest_columns_hashing_prepared_keys.cpp` is rewritten
around the new contract, including a mixed-width key set whose clause order is not
longest-first order, which is what pins the layout.

Co-Authored-By: Claude Opus 5 <[email protected]>
`tests/clickhouse-test:1692` randomizes `aggregation_in_order_max_block_bytes` as
`random.randint(0, 50000000)` for every test not tagged `no-random-settings`, and
`AggregatingInOrderTransform::consume` uses it at
`src/Processors/Transforms/AggregatingInOrderTransform.cpp:227` to finalize the
output block and save the input remainder into a new chunk. A drawn value near 0
makes that cut fire after the first key interval of every block, so the transform
sees a sequence of small blocks instead of one 800000-row block, which collapses
the `runs * block_rows` term the four timed aggregation and merge guards exist to
detect. The guards stay green either way, so what the draw compromises is their
ability to fail: a future regression would pass them on any run that drew a small
value.

Those four guards and their four `EXPLAIN PIPELINE` mirrors now pin the setting.
The pinned value is its own default, 50000000 (`src/Core/Settings.cpp:4503`), so
the negative control that proved all five guards redden still describes the
configuration they run in, and no limit is recalibrated. Measured over 404
executions, all four resolve to 50000000 while the DISTINCT guard, left
randomized in the same runs, drew values from 244779 up. That guard and the
identity checks keep the randomization: `DistinctSortedStreamTransform` has no
such threshold, and a cut changes neither an identity's result nor whether
sub-range states occur.

The mechanism paragraph in the file's header is replaced by a shorter one that
states the scenario and the coverage design and leaves the mechanism to this
commit message. The `long` justification and the five numbered sizing rules stay:
they are the calibration record for limits that went red twice here.

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (click to expand)

Two independent reviews ran against this branch before publication: an automated second-model pass and
a separate code review that did not see the author's evidence. Seven rounds, and the mechanism was
replaced mid-review, so the branch's first commit argues for a representation this tree no longer
implements. The final commit message is the one that describes what ships.

Item Verdict
❌ Storing the packed keys for a sub-range was wrong in every form tried: indexing relative to row_begin cost +4.1% on the whole-block keys64 read that unaffected callers share, biasing the base pointer formed a pointer outside the array (undefined behaviour), and sizing the array to the range's absolute end left allocated bytes per block quadratic, which the jemalloc global profiler every CI test server enables charges per allocated byte. Agreed. The representation is gone: a sub-range state skips the batch and packs each key on demand, so it allocates nothing (10.17 s with the profiler armed became 0.37 s). packFixedBatch and fillFixedBatch are byte-identical to master again.
❌ A per-row packer must reproduce the batch byte layout. packFixedBatch lays keys out longest first, packFixed and packFixedShuffle in clause order, and the output side keys off usePreparedKeys alone, so shuffleKeyColumns permutes the output columns for the longest-first layout whether or not the state batched. A clause-order packer would return wrong GROUP BY key values. Agreed. packFixedLongestFirst mirrors the batch pass order, and the test pinning it uses a key set whose clause order is not longest-first, with an ASSERT_NE against the clause-order packer as its negative control. Reversing the pass order, or making one pass clause-order, reddens exactly that case.
❌ The unit tests did not prove getKeyHolder actually consumes the prepared array, so batching could become dead while every assertion stayed green. Agreed, and measured rather than asserted: replacing the prepared read with the per-row fallback reddens that case and leaves the others green.
❌ Once the allocation residual was gone, the regression test's no-asan, no-msan, no-tsan exclusions had lost their stated reason. Agreed. The slowest guarded query measures well under a second on a debug build with the CI profiler config armed, so all three were dropped and the file now runs under every sanitizer.
❌ Neither StateNoCache arm had a timed guard, and the two identity comparisons carrying the layout coverage had no in-order plan assertion, so they would have passed unconditionally the day the optimizer stopped choosing that plan. Agreed. Each ranged construction a query can select now has its own timed guard, and every timed and identity statement has an EXPLAIN PIPELINE mirror. Forcing the batch back on makes all five guards fail on TIMEOUT_EXCEEDED while every mirror and identity check still passes.
❌ The timed guards inherited a randomized aggregation_in_order_max_block_bytes, which the in-order transform uses to finalize a block and cut the input remainder. A small drawn value cuts after the first key interval of every block and collapses the very quadratic term those guards exist to detect. Agreed, fixed last round. Pinned to its own default in the four aggregation and merge guards and their mirrors, which is the value the broken-side control was validated at, so no limit moved. Over 404 executions the pinned guards resolved to it 404/404 while the DISTINCT guard, left randomized on purpose in the same runs, drew down to 244779; it keeps the randomization because DistinctSortedStreamTransform has no such threshold.
⚠️ The new set-index call site has no test that would fail if its range argument were removed. Correct, and I could not close it inside this PR's review budget, so it is a question for you rather than a decision of mine. What I did verify: MergeTreeIndexAggregatorSet::update allocates a whole-block IColumn::Filter on every per-granule call, so that path keeps a whole-block term either way and this change cannot make it linear; and the property whose violation could be a correctness bug, the per-row layout equalling the batch layout, is what the unit test pins, so the argument only ever removes work. I kept the line because it is the same defect at a fourth carrier. Two levers, your call: I add a focused guard in a follow-up, or I drop that one line from this PR.

Residuals, disclosed rather than fixed:

  • 💡 Two stale figures in the regression test's header, both inside a block the previous round froze
    byte-identical. It says the slowest guarded query measured 0.48 s, so a 20x sanitizer multiplier stays
    "12x under 120 s"; re-measured on the same binary over 101 executions of each guard the slowest median
    is 0.576 s, so the same arithmetic gives ~10x under, and the worst single observation of 4.39 s is 27x
    under. It also says "nine EXPLAIN PIPELINE mirrors" where there are eight, which is what its own
    sizing rule implies (one per timed guard and one per identity check). The mirror set is complete; only
    the count is wrong.
  • 💡 That whole-block IColumn::Filter per index granule. Removing it is a different change with a
    different blast radius.
  • 💡 The serialized methods keep their whole-block batch serialization; the per-run path already avoids
    them by substituting the lazy variant (Fix quadratic aggregation in order with the prealloc-serialized method #110159), so they take the row range and ignore it.
  • 💡 The new packer is NO_INLINE on purpose. Inlined into every getKeyHolder instantiation it grew
    .text by 6,302,464 bytes, against 18,688 out of line, with no measurable difference on the path
    that uses it.

Checked this round independently of the author's notes: every hashing-state construction in src/ was
enumerated before reading the plan, and exactly the four building one state per sub-range pass a range
while the other 31 build one per whole chunk and are untouched; the whole-block read and constructor
call are byte-identical to master; a state that packs per row never reaches the SSSE3 branch, whose mask
arrays it does not build; and a caller asking about a row outside its declared range gets a slow answer,
not a wrong one. The changelog category stays Bug Fix: it is the one category whose check can validate
this change, and it does, since the regression test fails on master without the fix.

Session id: cron:clickhouse-review-slot-10:20260916-115300

@clickhouse-gh

clickhouse-gh Bot commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit 885feab99b28bd0b7ac0afe796080eb23ddf94a5 was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception).

See the job log for details.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - f9ab407

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
Integration tests (amd_asan_ubsan, db disk, 7/8) infra: Failed to pre-pull Docker images needed by the test batch, after 3 attempts at pull access denied for minio/mc, repository does not exist (that Docker Hub repository was deleted upstream) #119999 (mine, merged 2026-09-16 14:42:43Z), merged master @ 813b226edcc0cf0cf77dadfa528945f62f35ff08
Finish Workflow / Post Hooks cascade of the row above same owner, #119999
Mergeable Check / PR aggregator cascade of the row above same owner, #119999

The failing job ran before that fix merged, so master is merged here to pick it up. The mirrored clickhouse/minio-mc tag was pushed at 14:39Z and pulls fine now. Only shard 7/8 is affected, because its batch is the one that pulls minio/mc.

Session id: cron:our-pr-ci-monitor:20260916-153030

MergeTreeIndexAggregatorSet::buildFilter builds one hashing state per index
granule while its columns span the whole insert block, so before the range
argument the batched key pack ran once per granule over the whole block. The
argument cannot change any result, because the state is only ever asked about
rows [pos, pos + limit), so no functional test can distinguish the two
behaviours and the only oracle that can is a measurement.

Order-balanced A/B of origin/master dc050cf against this branch, both
RelWithDebInfo out of the same build dir, one INSERT of 5M rows with default
block and granule settings, single insert thread, arms interleaved per
repetition: master 1.711 s against 0.302 s here, 5.66x, n=16 each. Two negative
controls hold the mechanism rather than the speedup: a single index column
hashes through HashMethodOneNumber, which never batched, and measures 1.05x
over 14 interleaved repetitions, which is the test's control query; an index
granule as large as the block makes the range cover the whole block, so both
binaries batch, 0.93x. Master in both arms measures 0.99x, so the harness has
no position bias.

The effect is the number of index granules per block, one run each at 5M rows:
6.0x at the default 8192, 15.8x at 2048, 18.9x at 1024, 25.6x at 512. The test
keeps the default, because tests/performance/scripts/perf.py applies
max_execution_time = 15 to every measured query on the reference server as well
as on the pull request's, so a benchmark whose old side exceeds that limit
fails the job on a correct pull request. Replaying the committed statements
with that setting, the reference side passes at 8.1x under the limit and this
branch at 48x. That also means the test reports rather than gates: one slower
query stays under the job's own threshold of ten.

The mutant is master rather than this branch with the one line reverted,
because an INSERT with a set index reaches no other code this branch changes.
Both controls measuring at parity is what shows the two binaries do not
otherwise differ on that path.

The test is a separate file because it needs SYSTEM STOP MERGES, which would
neutralise the OPTIMIZE TABLE FINAL fill query of the aggregation test.
The file has eight EXPLAIN PIPELINE mirrors, one for each of the five timed
guards and the three identity checks, not nine. The slowest single guarded
query re-measured 0.576 s server-side over 101 executions on the same build,
not 0.48 s, which leaves 10x rather than 12x of headroom under the 120 s guard
after a 20x sanitizer multiplier. Both statements were frozen for the previous
round and disclosed as residuals; neither changes the sizing conclusions.
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 554f8e2

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
Upgrade check (amd_release) / Error message in clickhouse-server.log log scan: a background mutation retries forever with Code 47 UNKNOWN_IDENTIFIER b in MutatePlainMergeTreeTask (27 legs / 25 unrelated PRs / 0 master rows in 7 days) #118499 (mine, open)
Build profile diff infra: CI logs cluster query failed raised in has_pr_data (build_profile_diff_job.py:723), a fresh recurrence on trees that already carry the merged user fix #118618 (215 legs / 172 unrelated PRs yesterday, 0 master) #120121 (mine, open)
Mergeable Check / PR aggregator cascade of the Upgrade check (amd_release) row above #118499 (mine, open)
CH Inc sync - CH Inc sync (private, not actionable by me)

Session id: cron:our-pr-ci-monitor:20260917-003056

@snelheidai

Copy link
Copy Markdown

This fixes the quadratic cases, but long runs are now slower than on master: with 65,536 rows per value of the sorting prefix, in-order GROUP BY takes 8.7% longer and DISTINCT 4.2% longer (optimize_distinct_in_order is on by default). Batch-packing sub-ranges of at least 256 rows removes the regression, but the form I measured is not mergeable as it is (see the last paragraph).

Setup: master 83a6d57ed224 against master plus this PR's src/ changes; x86_64 (4 vCPU Xeon 8375C), release build, clickhouse local, max_threads = 1. The "this PR" and "range batch" columns are one binary, with the range batch enabled by an environment variable. That binary also carried an unrelated local patch that adds an optional row-selector argument to the HashMethodKeysFixed constructor for parallel_hash join builds; aggregation and DISTINCT pass no selector. Table of 2,097,152 rows, ORDER BY a, with G rows per value of a:

CREATE TABLE t (a UInt64, b UInt64, c UInt64) ENGINE = MergeTree ORDER BY a;
INSERT INTO t SELECT intDiv(number, G), number * 7, number * 11 FROM numbers(2097152);
SELECT a, b, count() FROM t GROUP BY a, b SETTINGS optimize_aggregation_in_order = 1, max_threads = 1 FORMAT Null;
SELECT DISTINCT a, b, c FROM t SETTINGS optimize_distinct_in_order = 1, max_threads = 1 FORMAT Null;

One warm-up and 7 runs per arm, arm order rotated per run. Medians in ms; ratios are paired geometric means with 95% CI.

G query master this PR range batch (>= 256 rows)
256 GROUP BY 1129 477 446
4096 GROUP BY 485 488 436
65536 GROUP BY 445 486 442
256 DISTINCT 655 286 278
4096 DISTINCT 301 293 275
65536 DISTINCT 293 303 286
1 GROUP BY not run (quadratic) 797 791
16 GROUP BY not run 485 499
  • At G=65536 this PR is slower than master: GROUP BY 1.087 [1.058, 1.116], DISTINCT 1.042 [1.027, 1.058]. At G=4096 GROUP BY only matches master (1.000 [0.959, 1.042]). When a block holds one or a few runs, master's whole-block batch pack per run costs little, while this PR packs each row of a sub-range separately with packFixedLongestFirst.
  • The range batch matches master at G=65536 (0.997 [0.971, 1.023]) and is 0.895 [0.865, 0.926] of this PR at G=4096 for GROUP BY (DISTINCT 0.941 [0.933, 0.948]). Shorter sub-ranges stay per row, so G=1 and G=16 show no significant change (0.999 [0.987, 1.011] and 1.024 [0.984, 1.066]).
  • count() and sum(cityHash64(a, b, c)) of both queries are identical across arms for every G, with the setting on and off (master was run only at G=256, 4096 and 65536). With both settings off, no arm differs significantly from master.

The range batch is only a measurement: it sizes prepared_keys to the sub-range's absolute end, the form round 7 dropped. The 256-row threshold is essential: without it, one-row states make GROUP BY 2.9x slower than this PR at G=1. With it, short runs stay per row and allocate nothing, which covers every timed guard in 05217 (runs of 1 and 8 rows). Longer runs still allocate about N²/(2L) keys per block of N rows in runs of L rows (128 MiB of 16-byte keys for a 65,536-row block of 256-row runs), and a row before the range reads an unset key. A separate range-relative array, read only on the pack_keys_per_row branch and falling back to the per-row packer outside the range, should avoid both without changing the whole-block read. I have not built that, and have not run the measured variant with the jemalloc profiler armed or under sanitizers.

Measured variant as a delta on this PR's head (threshold hardcoded to 256)
diff --git a/src/Common/ColumnsHashing/HashMethod.h b/src/Common/ColumnsHashing/HashMethod.h
index e47f3f6..3ed60b2 100644
--- a/src/Common/ColumnsHashing/HashMethod.h
+++ b/src/Common/ColumnsHashing/HashMethod.h
@@ -471,10 +471,14 @@ struct HashMethodKeysFixed
 
     PaddedPODArray<Key> prepared_keys;
 
-    /// Set when this state covers only a sub-range of the block: `prepared_keys` stays empty and keys
-    /// are packed one row at a time instead.
+    /// Set when this state covers only a short sub-range of the block: `prepared_keys` stays empty and
+    /// keys are packed one row at a time instead.
     bool pack_keys_per_row = false;
 
+    /// A sub-range at least this long is batch-packed on its own rows, which is cheaper than packing each
+    /// row separately; for a shorter one, allocating the row-indexed array does not pay off.
+    static constexpr size_t min_rows_to_batch_pack_range = 256;
+
     static bool usePreparedKeys(const Sizes & key_sizes)
     {
         if (has_low_cardinality || has_nullable_keys || sizeof(Key) > 16)
@@ -510,12 +514,15 @@ struct HashMethodKeysFixed
 
         if (usePreparedKeys(key_sizes))
         {
-            /// Batch-packing costs one pass over the whole column, so a state that will be asked about
-            /// only a sub-range does not batch at all: one state per run of a sorted prefix would
-            /// otherwise pay for the whole block each time. Same trade as `Params::aggregation_in_order`.
+            /// Batch-packing costs one pass over the packed rows, so a state that will be asked about only
+            /// a sub-range packs just that sub-range: one state per run of a sorted prefix would otherwise
+            /// pay for the whole block each time. A short sub-range is packed per row.
             const size_t block_rows = key_columns.empty() ? 0 : key_columns[0]->size();
+            const size_t range_end = std::min(rows.end, block_rows);
             if (rows.begin == 0 && rows.end >= block_rows)
                 packFixedBatch(keys_size, Base::getActualColumns(), key_sizes, prepared_keys);
+            else if (range_end > rows.begin && range_end - rows.begin >= min_rows_to_batch_pack_range)
+                packFixedBatchRange(keys_size, Base::getActualColumns(), key_sizes, prepared_keys, rows.begin, range_end);
             else
                 pack_keys_per_row = true;
         }
diff --git a/src/Interpreters/AggregationCommon.h b/src/Interpreters/AggregationCommon.h
index 487089d..7b9cf9d 100644
--- a/src/Interpreters/AggregationCommon.h
+++ b/src/Interpreters/AggregationCommon.h
@@ -88,6 +88,49 @@ void packFixedBatch(size_t keys_size, const ColumnRawPtrs & key_columns, const S
     fillFixedBatch<UInt8>(keys_size, key_columns, key_sizes, out, offset);
 }
 
+/// Same as fillFixedBatch, for rows [begin, end) only; `out` is addressed by row.
+template <typename T, typename Key>
+void fillFixedBatchRange(
+    size_t keys_size, const ColumnRawPtrs & key_columns, const Sizes & key_sizes, size_t begin, size_t end, PaddedPODArray<Key> & out, size_t & offset)
+{
+    for (size_t i = 0; i < keys_size; ++i)
+    {
+        if (key_sizes[i] == sizeof(T))
+        {
+            const T * source = reinterpret_cast<const T *>(static_cast<const ColumnFixedSizeHelper *>(key_columns[i])->getRawDataBegin<sizeof(T)>());
+            T * dest = reinterpret_cast<T *>(reinterpret_cast<char *>(out.data()) + offset);
+            fillFixedBatch<T, sizeof(Key) / sizeof(T)>(end - begin, source + begin, dest + begin * (sizeof(Key) / sizeof(T)));
+            offset += sizeof(T);
+        }
+    }
+}
+
+/// Same as packFixedBatch, for rows [begin, end) only: `out` is sized to `end` and addressed by row, and only
+/// the elements of [begin, end) are written, so a state for one run of a block packs just that run.
+template <typename T>
+void packFixedBatchRange(size_t keys_size, const ColumnRawPtrs & key_columns, const Sizes & key_sizes, PaddedPODArray<T> & out, size_t begin, size_t end)
+{
+    if (keys_size == 0 || end <= begin)
+        return;
+
+    out.resize(end);
+
+    size_t packed_size = 0;
+    for (size_t i = 0; i < keys_size; ++i)
+        packed_size += key_sizes[i];
+
+    /// The unused tail of a key must be zero, as in the zero-filled array of packFixedBatch.
+    if (packed_size < sizeof(T))
+        memset(static_cast<void *>(&out[begin]), 0, (end - begin) * sizeof(T));
+
+    size_t offset = 0;
+    fillFixedBatchRange<UInt128>(keys_size, key_columns, key_sizes, begin, end, out, offset);
+    fillFixedBatchRange<UInt64>(keys_size, key_columns, key_sizes, begin, end, out, offset);
+    fillFixedBatchRange<UInt32>(keys_size, key_columns, key_sizes, begin, end, out, offset);
+    fillFixedBatchRange<UInt16>(keys_size, key_columns, key_sizes, begin, end, out, offset);
+    fillFixedBatchRange<UInt8>(keys_size, key_columns, key_sizes, begin, end, out, offset);
+}
+
 template <typename Key, size_t ELEMENT_SIZE>
 static inline void ALWAYS_INLINE fillFixedLongestFirst(
     size_t row, size_t keys_size, const ColumnRawPtrs & key_columns, const Sizes & key_sizes, char * bytes, size_t & offset)

A hashing state built over a sub-range of a block skipped batch packing
entirely and packed every key on demand. That is the right trade for the
short runs a near-unique sorting prefix produces, but not for long ones:
with 65536 rows per value of the sorting prefix a block holds one or two
runs, so a state covers nearly the whole block and pays per row for the
work the single whole-block batch pack used to do in one pass.

A sub-range of at least 256 rows is now batch-packed over its own rows,
into an array indexed relative to the range's first row. The packing cost
per block is then linear in the block's rows however many runs it holds,
and so is the array: sizing it to the range's absolute end instead would
put the allocated bytes back to quadratic, which is what CI's
jemalloc_enable_global_profiler charges for. A shorter sub-range still
allocates nothing and packs per row, and a row outside a batched
sub-range is packed on demand rather than read from the array.

Measured on a 2097152-row table sorted by `a`, release, max_threads = 1,
query CPU time, 9 interleaved reps per arm pinned to one core, as a
paired geometric mean [95% CI] against master:

  rows per `a`  GROUP BY a, b         DISTINCT a, b, c
  65536         1.057 [1.047,1.067]   1.088 [1.055,1.121]   before
  65536         0.991 [0.976,1.007]   1.022 [0.989,1.055]   after
  4096          0.997 [0.986,1.009]   0.970 [0.944,0.997]   before
  4096          0.933 [0.921,0.946]   0.900 [0.863,0.939]   after
  256           0.538 [0.531,0.545]   0.389 [0.380,0.398]   before
  256           0.502 [0.496,0.508]   0.363 [0.354,0.373]   after

At 1 and 16 rows per value the runs stay below the threshold and the
per-row path is kept: 0.996 [0.984,1.007] and 1.002 [0.981,1.024] of the
per-row-only build. Queries with the in-order optimisations off are at
parity in every arm. With the jemalloc profiler armed, the GROUP BY at 256 rows
per value is 0.443 [0.438,0.448] of master, so the range arrays do not
reintroduce the allocation cost.

Reported on the pull request by snelheidai.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Confirmed, and fixed in this PR at 338bdf4e.

I reproduced the long-run regression on the published head (554f8e2d) before changing anything: master 44a2a51a against that head, both RelWithDebInfo out of one build dir, 2097152-row table ORDER BY a, max_threads = 1, metric = query CPU time (UserTimeMicroseconds), 9 to 15 interleaved reps per arm pinned to one core, paired geometric mean [95% CI]. At 65536 rows per value of a the published head is 1.057 [1.047, 1.067] of master for GROUP BY a, b and 1.088 [1.055, 1.121] for DISTINCT a, b, c, so the effect is real and larger on DISTINCT here than the 4.2% you measured. Wall clock agreed (1.071 and 1.089, 9 reps) with CIs about three times wider, which is why I switched metric rather than adding reps.

The fix is the range-relative form, not the one you measured: a sub-range of at least 256 rows is batch-packed over its own rows into an array indexed from the range's first row, so the allocated bytes per block stay linear in the block instead of the N^2/(2L) that absolute-end sizing gives, and a row outside the range is packed on demand instead of reading an unset key. Same host and harness, arm against master:

rows per a GROUP BY, head GROUP BY, now DISTINCT, head DISTINCT, now
65536 1.057 [1.047, 1.067] 0.991 [0.976, 1.007] 1.088 [1.055, 1.121] 1.022 [0.989, 1.055]
4096 0.997 [0.986, 1.009] 0.933 [0.921, 0.946] 0.970 [0.944, 0.997] 0.900 [0.863, 0.939]
256 0.538 [0.531, 0.545] 0.502 [0.496, 0.508] 0.389 [0.380, 0.398] 0.363 [0.354, 0.373]

At 1 and 16 rows per value the runs stay under the threshold and nothing changes (0.996 [0.984, 1.007] and 1.002 [0.981, 1.024] against the per-row-only build), which is the case your 2.9x warned about. Both optimisations off are at parity in every arm. With jemalloc_enable_global_profiler armed the 256-rows case is 0.443 [0.438, 0.448] of master, so the range arrays do not bring back the allocation cost that sizing to the absolute end did. count() and sum(cityHash64(a, b, c)) are identical across all three binaries at every row count tested, setting on and off.

Coverage: three gtests pin the batched sub-range (its layout, the threshold's two sides, and a row outside the range), each proven to redden by mutation (packing the range from row 0, and returning a zero key outside the range); the performance test gained two long-run queries, which is the shape it was missing.

The PR is also recategorised as Performance Improvement: what it fixes is a cost, not a wrong result.

GitHub could not compute a merge ref for the previous head, so praktika
never dispatched any CI for it.

The only conflict is in `AggregationCommon.h`: ClickHouse#116569 (External
`DISTINCT`) added `unpackFixedKeyIntoColumns` at the same anchor where
this branch adds its range packing helpers. Both blocks are kept, with
master's first so that its "the inverse of the fixed-size key packing
above" keeps referring to `packFixedBatch`.

That pull request also factored `packedKeysOrder` out of
`shuffleKeyColumns`. It keeps the descending-size order that this
branch's `packFixedLongestFirst` reproduces, so the per-row and the
batched key layouts still agree.

The branch delta against master is byte-identical before and after the
merge, apart from one context line moved by the resolution above.
@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements and removed pr-bugfix Pull request with bugfix, not backported by default labels Sep 24, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 366d3f7

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
Performance Comparison (amd_release, master_head, 1/6) false red of the dashboard gate. The shard's own report says 4 too long, 1 unstable; 1 confirmed regression(s) on the performance dashboard: it names no slower query at all, so the dashboard verdict was the only red-maker, and its single unstable query codecs_int_insert #10 measures unstable on 17 distinct pull requests over 14 days. 54 red perf shards over 39 pull requests carry this shape today. #121847 (merged 2026-09-23 23:29Z) is measured PRESENT in the tree this job built (3ef6d2ff1e46, the job's confirmed checkout; 4 hits of a symbol it introduces against 0 before it), and the two mechanisms it fixes are UTC timestamps in CIDB and the 10 s threshold-fetch timeout, neither of which is this red, so it does not own this row ClickHouse/performance-comparison#5 (external): the dashboard's confidence scoring, which #121847's own description names as where noisy confirmed_regression verdicts are handled. That repository is not publicly readable, so its state cannot be measured from here
Mergeable Check, PR rollup rows, red only because of the shard above, with no independent failure of their own ClickHouse/performance-comparison#5 (external), the same dashboard-side owner as the red-maker above

All 176 check-runs completed (159 pass, 14 not selected, 3 red), Finish Workflow green with the last
completion at 08:53:19Z, CH Inc sync green, and CIDB carries no FAIL or ERROR test row on this head.

One non-green measurement disclosed here rather than left in the report: columns_hashing #1 goes
210 ms to 257 ms (+22.4%) inside the GREEN amd_release 3/6 shard, and that fixture does sit on this
PR's changed path. The counter-evidence is measured too: the same head's arm_release 6/6 run of the
same query is 187 ms to 196 ms and green, two earlier heads of this same diff measured 215 to 213 ms and
208 to 208 ms, and the same amd shard simultaneously flagged timeseries_to_grid_aggregation_functions #2,
which measures slower on 32 pull requests over 14 days. That reads as one noisy shard rather than a
regression, and it is worth a single re-run before anyone reads the report.

Session id: cron:our-pr-ci-monitor:20260924-090214

@snelheidai

Copy link
Copy Markdown

The columns_hashing #1 slowdown is real on this head, not noise. In a paired A/B of master 83a6d57 against 83a6d57 plus this PR's diff at 366d3f7e, that query shape is 10.9% slower by server time (95% CI 9.6 to 12.2%; the PR was faster in 0 of 30 pairs), and 7.0% slower with max_threads = 1 (5.3 to 8.8%). The table is synthetic, since hits_10m_single is not on that host: 10M rows with 2M distinct (UInt64, UInt32) pairs, on a 4-vCPU Xeon 8375C. Both are release builds without ThinLTO, and nothing on this path changed in master after 83a6d57. On the CI amd shard, this query's user CPU time also rose 11.6%.

The slowdown is specific to the IN set. Two-key keys128 GROUP BY (2M and 7K groups) and a keys128 hash JOIN show no significant change, single-threaded, 20 pairs each. DISTINCT on the same two columns is +1.8% (CI -0.1 to +3.7%).

perf annotate of the single-threaded query shows the cause. In the PR build's Set::insertFromBlockImplCase for keys128, all three key sources deliver the key in a general-purpose register pair (r12:r13): the sub-range prepared_keys load, the whole-block prepared_keys[row] load, and the NO_INLINE packFixedLongestFirst call, which returns in rax:rdx. The key is then stored to the stack as two 8-byte halves and reloaded as one 16-byte vector. That load cannot be store-forwarded, and 16% of the function's samples land on the instruction right after it. On master the key stays in xmm0 throughout.

I'm now measuring the one-line candidate fix, which keeps the fallback from returning through registers, against the regressed queries and the in-order queries in aggregation_in_order_partial_key. I'll post the numbers here.

--- a/src/Interpreters/AggregationCommon.h
+++ b/src/Interpreters/AggregationCommon.h
@@ -205,7 +205,7 @@ static inline void ALWAYS_INLINE fillFixedLongestFirst(
 /// lays out the same key set: one pass per key width, longest first. That order is load-bearing,
 /// because shuffleKeyColumns makes the output side read the blob back in it when usePreparedKeys holds.
 template <typename Key>
-static NO_INLINE Key packFixedLongestFirst(
+static inline Key ALWAYS_INLINE packFixedLongestFirst(
     size_t row, size_t keys_size, const ColumnRawPtrs & key_columns, const Sizes & key_sizes)
 {
     Key key{};

@groeneai

Copy link
Copy Markdown
Collaborator Author

I verified this locally and I am keeping NO_INLINE: the mechanism reproduces, but the proposed change does not pay for itself.

Mechanism confirmed, with one correction. Compiling src/Interpreters/Set.cpp with the build's own flags (clang-22, RelWithDebInfo, ENABLE_THINLTO=0, x86-64) and extracting Set::insertFromBlockImplCase<SetMethodKeysFixed<UInt128, UInt128HashCRC32, ...>, false, false>. That file is untouched by this PR, so the whole delta is the inlined getKeyHolder:

variant instructions 128-bit key
master 572520ce 279 stays in %xmm0: vpxor+vptest for the last-element cache, vptest for the zero test
this head 366d3f7e 320 vmovq/vpextrq into %r12:%r13, both tests scalarized into cmpq pairs
head + ALWAYS_INLINE 513 back in %xmm0

The correction: no stack round trip in this translation unit. getKeyHolder now has three definitions of the returned key, one of them a call returning a 16-byte class in rax:rdx, so the merged value lands in general purpose registers and the single-instruction 128-bit compare becomes two cmpq plus a branch. Same conclusion as yours about the key leaving the vector domain, different last step.

Why the one-liner does not ship. It buys %xmm0 back by inlining a five-branch packer into every hash table inner loop:

  • .text grows by 6,177,216 bytes (+1.36%) on the release binary. That is why NO_INLINE is there; the same flip measured +6,302,464 bytes earlier this month.
  • On the whole-block paths it is slower than master, not faster: +5.5% and +4.7% on your columns_hashing #1 shape, +5.2% and +5.6% on a plain two-key GROUP BY, over two disjoint core placements, 40 paired runs each.
  • It does not help the queries that really are slower here: -0.4% and -1.4%, both inside noise.

The 10.9% is not resolvable on my host, so I am not contradicting it. This box has 6 NUMA nodes and 384 CPUs. Unpinned, two 40-pair rounds of your shape gave -2.4% and then +19.9%; pinned to one node with disjoint physical core sets, the sign still flips between placements (+1.8%, then -1.1%). Your Ice Lake number stands as far as I can measure, and a vector-to-GP cost differing between Ice Lake and Granite Rapids is plausible. What is stable here is the plain two-key GROUP BY on the whole-block path at +2.1% and +2.8%, consistent with the 41 extra instructions.

One thing I did reproduce that is not in your report. The two long-run queries this PR's own perf test carries are slower than master on this host in all four of my rounds: DISTINCT in order at +14.4% (faster in 1 of 40 pairs) and in-order GROUP BY at +4.4%, at 65536 rows per sorting-prefix value. CI marks aggregation_in_order_partial_key #0 through #5 as success on both amd and arm, so its threshold does not flag them. That is the trade this PR makes, and ALWAYS_INLINE leaves it untouched.

If the whole-block cost is worth removing properly rather than trading it for code size, the shape that works is to gate the sub-range machinery on a template parameter, so every caller that never passes a row range instantiates master's code exactly. Probed that way the hot loop returns to 282 instructions with vptest restored, at no .text cost. That is larger than what this PR does today, so I have not done it unprompted.

@snelheidai

Copy link
Copy Markdown

A runtime restructuring recovers about 60% of the IN slowdown but not all of it, so a template parameter that compiles master's code for whole-block callers looks necessary to remove it. The variant I tried keeps whole-block states on master's path without one: getKeyHolder checks prepared_keys[row] first, sub-range batches live in a separate sub_range_keys array, and the per-row pack writes into a member, so no call returns the key by value. Paired server time, same setup as before (95% CI):

Query Variant vs this PR Variant vs master
IN shape, 4 threads -6.1% (-8.1 to -4.1) +4.4% (+2.8 to +6.0)
IN shape, max_threads = 1 -6.7% (-7.6 to -5.8) +2.7% (+1.3 to +4.2)
DISTINCT UserID, RegionID -1.2% (-2.4 to 0.0) +2.4% (+1.1 to +3.6)

Against this PR, the six in-order queries (single-threaded, 20 pairs) are unchanged: runs of 1, 16 and 65,536 rows, GROUP BY and DISTINCT, ratios 0.988 to 1.006, every CI including 1. Query results match master's. The gtest compiles with the renamed members, but I have not run it. The diff is below in case a smaller change is preferred for this PR.

The long-run slowdown does not reproduce here. Master against this head, single-threaded as in the perf test, 30 pairs:

  • in-order GROUP BY at 65,536 rows per value: +0.7% (-1.3 to +2.6)
  • DISTINCT in order: -0.6% (-2.4 to +1.2)
  • whole-block control #3: +0.7% (-0.2 to +1.6)

The stack round trip is in our clang-21 release build: the r12/r13 halves are stored to the stack, then reloaded with one 16-byte vmovdqu. Your clang-22 build scalarizes the compares instead. In both builds the key leaves xmm0.

Variant diff against 366d3f7
diff --git a/src/Common/ColumnsHashing/HashMethod.h b/src/Common/ColumnsHashing/HashMethod.h
index c4089b114a0..6d150132500 100644
--- a/src/Common/ColumnsHashing/HashMethod.h
+++ b/src/Common/ColumnsHashing/HashMethod.h
@@ -472,11 +472,16 @@ struct HashMethodKeysFixed
 
     PaddedPODArray<Key> prepared_keys;
 
-    /// Set when this state covers only a sub-range of the block. `prepared_keys` then holds that
-    /// sub-range, starting at `prepared_keys_begin`, or is empty; a row it does not hold is packed on
-    /// its own.
+    /// Set when this state covers only a sub-range of the block. `sub_range_keys` then holds that
+    /// sub-range, starting at `sub_range_begin`, or is empty; a row it does not hold is packed on its
+    /// own into `packed_key`. This is kept apart from `prepared_keys` so that a whole-block state reads
+    /// its keys exactly as before, and the per-row pack returns through memory: a 16-byte `Key` returned
+    /// by value from a call comes back in a register pair, and the compiler then carries every key of
+    /// `getKeyHolder` that way, which costs a store-forwarding stall per row in the `Set` loops.
     bool covers_sub_range = false;
-    size_t prepared_keys_begin = 0;
+    size_t sub_range_begin = 0;
+    PaddedPODArray<Key> sub_range_keys;
+    mutable Key packed_key{};
 
     /// A sub-range shorter than this is packed per row: the array would cost more to allocate and fill
     /// than the rows it saves packing.
@@ -531,8 +536,8 @@ struct HashMethodKeysFixed
                 covers_sub_range = true;
                 if (rows_end > rows.begin && rows_end - rows.begin >= min_rows_to_batch_pack_sub_range)
                 {
-                    prepared_keys_begin = rows.begin;
-                    packFixedBatchRange(keys_size, Base::getActualColumns(), key_sizes, prepared_keys, rows.begin, rows_end);
+                    sub_range_begin = rows.begin;
+                    packFixedBatchRange(keys_size, Base::getActualColumns(), key_sizes, sub_range_keys, rows.begin, rows_end);
                 }
             }
         }
@@ -603,17 +608,18 @@ struct HashMethodKeysFixed
                 return packFixed<Key, true>(row, keys_size, low_cardinality_keys.nested_columns, key_sizes,
                                             &low_cardinality_keys.positions, &low_cardinality_keys.position_sizes);
 
+            if (!prepared_keys.empty())
+                return prepared_keys[row];
+
             if (covers_sub_range)
             {
-                const size_t index = row - prepared_keys_begin;
-                if (index < prepared_keys.size())
-                    return prepared_keys[index];
-                return packFixedLongestFirst<Key>(row, keys_size, Base::getActualColumns(), key_sizes);
+                const size_t index = row - sub_range_begin;
+                if (index < sub_range_keys.size())
+                    return sub_range_keys[index];
+                packFixedLongestFirst<Key>(packed_key, row, keys_size, Base::getActualColumns(), key_sizes);
+                return packed_key;
             }
 
-            if (!prepared_keys.empty())
-                return prepared_keys[row];
-
 #if defined(__SSSE3__) && !defined(MEMORY_SANITIZER)
             if constexpr (sizeof(Key) <= 16)
             {
diff --git a/src/Interpreters/AggregationCommon.h b/src/Interpreters/AggregationCommon.h
index c83202fa8ec..82ef0eae76a 100644
--- a/src/Interpreters/AggregationCommon.h
+++ b/src/Interpreters/AggregationCommon.h
@@ -205,10 +205,10 @@ static inline void ALWAYS_INLINE fillFixedLongestFirst(
 /// lays out the same key set: one pass per key width, longest first. That order is load-bearing,
 /// because shuffleKeyColumns makes the output side read the blob back in it when usePreparedKeys holds.
 template <typename Key>
-static NO_INLINE Key packFixedLongestFirst(
-    size_t row, size_t keys_size, const ColumnRawPtrs & key_columns, const Sizes & key_sizes)
+static NO_INLINE void packFixedLongestFirst(
+    Key & key, size_t row, size_t keys_size, const ColumnRawPtrs & key_columns, const Sizes & key_sizes)
 {
-    Key key{};
+    key = Key{};
     char * bytes = reinterpret_cast<char *>(&key);
     size_t offset = 0;
 
@@ -217,8 +217,6 @@ static NO_INLINE Key packFixedLongestFirst(
     fillFixedLongestFirst<Key, 4>(row, keys_size, key_columns, key_sizes, bytes, offset);
     fillFixedLongestFirst<Key, 2>(row, keys_size, key_columns, key_sizes, bytes, offset);
     fillFixedLongestFirst<Key, 1>(row, keys_size, key_columns, key_sizes, bytes, offset);
-
-    return key;
 }
 
 /// Pack into a binary blob of type T a set of fixed-size keys. Granted that all the keys fit into the
diff --git a/src/Interpreters/tests/gtest_columns_hashing_prepared_keys.cpp b/src/Interpreters/tests/gtest_columns_hashing_prepared_keys.cpp
index 89d05ce3689..a6a68a0b929 100644
--- a/src/Interpreters/tests/gtest_columns_hashing_prepared_keys.cpp
+++ b/src/Interpreters/tests/gtest_columns_hashing_prepared_keys.cpp
@@ -202,8 +202,9 @@ TEST(ColumnsHashingPreparedKeys, LongMixedWidthSubRangeIsBatchedInTheSameLayout)
 
     ASSERT_EQ(batched.prepared_keys.size(), num_long_rows);
     ASSERT_TRUE(ranged.covers_sub_range);
-    ASSERT_EQ(ranged.prepared_keys.size(), range_end - range_begin);
-    ASSERT_EQ(ranged.prepared_keys_begin, range_begin);
+    ASSERT_TRUE(ranged.prepared_keys.empty());
+    ASSERT_EQ(ranged.sub_range_keys.size(), range_end - range_begin);
+    ASSERT_EQ(ranged.sub_range_begin, range_begin);
 
     for (size_t row = range_begin; row < range_end; ++row)
     {
@@ -228,7 +229,8 @@ TEST(ColumnsHashingPreparedKeys, RowOutsideBatchedSubRangeIsPackedOnItsOwn)
     PreparedState whole_block(keys.columns, keys.sizes, nullptr);
     PreparedState ranged(keys.columns, keys.sizes, nullptr, {range_begin, range_end});
 
-    ASSERT_EQ(ranged.prepared_keys.size(), range_end - range_begin);
+    ASSERT_TRUE(ranged.prepared_keys.empty());
+    ASSERT_EQ(ranged.sub_range_keys.size(), range_end - range_begin);
     for (size_t row : {size_t{0}, range_begin - 1, range_end, num_long_rows - 1})
         ASSERT_EQ(ranged.getKeyHolder(row, arena), whole_block.getKeyHolder(row, arena)) << "row " << row;
 }
@@ -245,8 +247,8 @@ TEST(ColumnsHashingPreparedKeys, SubRangeShorterThanTheThresholdIsNotBatched)
     PreparedState at_threshold(keys.columns, keys.sizes, nullptr, {range_begin, range_begin + min_batched_rows});
     PreparedState below_threshold(keys.columns, keys.sizes, nullptr, {range_begin, range_begin + min_batched_rows - 1});
 
-    ASSERT_EQ(at_threshold.prepared_keys.size(), min_batched_rows);
-    ASSERT_TRUE(below_threshold.prepared_keys.empty());
+    ASSERT_EQ(at_threshold.sub_range_keys.size(), min_batched_rows);
+    ASSERT_TRUE(below_threshold.sub_range_keys.empty());
 
     for (size_t row = range_begin; row < range_begin + min_batched_rows - 1; ++row)
     {

@snelheidai

Copy link
Copy Markdown

With this PR applied, in-order GROUP BY over a sorting key with few rows per value still pays for two kinds of work that AggregatingInOrderTransform::consume does once per run of equal sorting-key values:

  1. It finds the end of the run with std::upper_bound over the rest of the block: about 16 virtual compareAt calls per run in a 65k-row block.
  2. When the GROUP BY key extends past the sorting key, it calls executeOnBlockSmall (or mergeOnBlockSmall) once per run, although all runs go into the same hash table until the next flush. This PR makes building the hashing state cheap for prepared fixed-size keys; the per-run calls remain for every key type.

The patch below changes only the transform. It finds the run end with one less check plus IColumn::getEqualRangeEndAssumeSorted, as DistinctSortedStreamTransform and LimitByTransform already do. When the GROUP BY key extends past the sorting key, it collects consecutive runs into a pending span and aggregates the span with one call: at the end of the chunk, before a flush, or when the pushed-down LIMIT could be reached. For the limit count from #117573, the hash-table entries plus the pending rows are an upper bound on the number of groups. When that bound reaches the limit at a boundary of the ORDER BY prefix, the span is aggregated and the groups are counted exactly, so the stream stops at the same run as without the patch.

Server query_duration_ms medians with G rows per value of the sorting key a, and the ratio patched / this PR (geometric mean, 95% CI):

query, G = 1 this PR, ms + patch, ms ratio
GROUP BY a 213.5 104 0.489 [0.481, 0.497]
GROUP BY a, b (two UInt64) 778.5 303 0.386 [0.380, 0.392]
GROUP BY a, f (FixedString(3)) 840 247.5 0.296 [0.293, 0.299]
GROUP BY a, s (String) 877.5 482.5 0.558 [0.541, 0.576]
GROUP BY a, s ORDER BY a, s LIMIT 1000000 446.5 255.5 0.578 [0.565, 0.591]
GROUP BY a, f ORDER BY a LIMIT 1000000 426 137 0.327 [0.308, 0.347]
this PR's perf test, GROUP BY a, b, 100k rows 46 23 0.506 [0.480, 0.534]
this PR's perf test, GROUP BY a 13 8 0.629 [0.590, 0.670]
new perf test, GROUP BY a, 10M rows 958 486.5 0.508 [0.503, 0.514]
new perf test, GROUP BY a, s, 10M rows 4197 2181.5 0.518 [0.509, 0.528]

With more rows per value the gain shrinks (ratio, 95% CI; – not measured):

query G = 4 G = 16 G = 256 G = 4096 G = 65536
GROUP BY a 0.607 [0.586, 0.630] 0.663 [0.646, 0.680] too short too short –
GROUP BY a, b – 0.865 [0.851, 0.880] 0.990 [0.967, 1.013] 1.015 [0.994, 1.036] 1.005 [0.970, 1.040]
GROUP BY a, f 0.657 [0.640, 0.675] 0.888 [0.869, 0.909] 0.973 [0.945, 1.001] 1.003 [0.985, 1.021] –
GROUP BY a, s 0.864 [0.851, 0.876] 0.789 [0.767, 0.811] 0.834 [0.819, 0.850] 0.826 [0.807, 0.846] –
this PR's perf test, GROUP BY a, b, long runs – – – – 0.976 [0.957, 0.995]

GROUP BY a at G = 256 and 4096 takes 3 to 4.5 ms, too short for the 1 ms timer.

This is complementary to the PR. Measured the same way, this PR alone against master changes only the two-UInt64 key: 1167.5 to 480 ms at G = 256 (0.412 [0.397, 0.428]). The other shapes at G = 1 and 16 stay within 0.997 to 1.032, and every interval includes 1. So for two UInt64 keys from G = 256 on, the patch adds nothing: the per-run cost there was the key repack, which this PR removes. The patch removes the run handling itself, so its gains are largest with few rows per value. At G = 1, in-order aggregation now costs about the same as hash aggregation (optimize_aggregation_in_order = 0): 104 against 93 ms for GROUP BY a, 247.5 against 221 ms for GROUP BY a, f, and 482.5 against 512 ms for GROUP BY a, s. We have not explained one result: GROUP BY a, s stays 17% faster even at G = 4096, with about a third of the peak memory. perf shows the same top functions in both binaries, with less time in memset.

Trade-offs:

  • aggregation_in_order_max_block_bytes is checked after each aggregated span instead of after each run. When the GROUP BY key extends past the sorting key, a block can therefore overshoot it by up to one input chunk of groups. Flushes for max_block_size and the pushed-down limit happen at the same run boundaries as before.
  • Peak memory (clickhouse local --memory-usage, 3 runs per binary) is the same except in two cases. GROUP BY a, s drops from 189 to 67 MiB at G = 16 and from 191 to 67 MiB at G = 4096. Two UInt64 keys use 1.0 MiB more at G = 1, 16 and 256 (17.8 vs 18.8 MiB at G = 1): one state per span batch-packs the chunk's keys (65,536 × 16 bytes), while this PR packs runs shorter than 256 rows one row at a time.

Paths the patch does not touch stay within 0.987 to 1.013: in-order aggregation turned off, DISTINCT in order, and the whole-block IN, DISTINCT and GROUP BY from the earlier discussion. The values are in the details below.

Correctness, on the same two binaries: 1,847 differential queries give byte-identical output, including order-sensitive groupArray, and in-order results match optimize_aggregation_in_order = 0. Every group returned under a LIMIT is checked against its true count. The dataset has runs of 1 to 70,000 rows in 3-part and 1-part layouts, with Nullable, NaN, DESC, LowCardinality, String, DateTime and Decimal columns, two-column and two-UInt64 keys, and an aggregate projection read through mergeOnBlockSmall. The queries use max_block_size 1, 7 and 100, aggregation_in_order_max_block_bytes = 1000, max_threads 1 and 4, and LIMIT 1 to 65537, so spans start in the middle of a chunk and are both shorter and longer than this PR's 256-row threshold. The 164 stateless tests that mention aggregation in order have the same outcomes on both binaries, including this PR's 05217 and 05218 and the new 05257; the 19 that fail on both need test.hits, S3, row-policy storage or parallel replicas.

Setup, controls and reproduction

One x86_64 host (Xeon Platinum 8375C, 4 vCPU). A is master 36ce602e4b96 plus this PR's diff at 366d3f7e; B is A plus the patch. Both are ThinLTO builds with the CI release flags (-DCMAKE_BUILD_TYPE=None -DENABLE_THINLTO=1 -DENABLE_TESTS=0, clang 21) from one build tree, run with clickhouse-server and max_threads = 1: one warm-up, then 10 interleaved pairs per query. AggregatingInOrderTransform, the hashing states, executeOnBlockSmall, mergeOnBlockSmall and getEqualRangeEndAssumeSorted are unchanged on current master bbba881bccd, and the patch applies there as well.

Controls (ratio, 95% CI):

  • In-order aggregation off: GROUP BY a G = 1 1.002 [0.988, 1.016]; a, f G = 1 1.007 [0.972, 1.043]; a, s G = 1 0.997 [0.987, 1.007] and G = 4096 1.006 [0.996, 1.016]; a, b G = 65536 1.000 [0.986, 1.013].
  • DISTINCT a, b, c in order: G = 1 1.013 [1.000, 1.026], G = 65536 0.992 [0.969, 1.017]. This PR's two DISTINCT perf queries: 0.999 [0.966, 1.034] (100k rows) and 1.006 [0.985, 1.028] (long runs).
  • Whole-block paths, on the same 10M-row table with 2M distinct (UInt64, UInt32) pairs: tuple IN 1.002 [0.983, 1.022] with 4 threads and 0.995 [0.967, 1.025] with 1 thread; DISTINCT UserID, RegionID 0.987 [0.975, 0.999]; GROUP BY UserID, RegionID 0.994 [0.981, 1.008]. This PR's whole-block perf control: 1.006 [0.980, 1.032].
  • GROUP BY a, s ORDER BY a, s LIMIT 1000 at G = 1 takes 4 ms on both binaries.
  • With jemalloc sampling allocations in every thread (MALLOC_CONF=prof_thread_active_init:true, which is what jemalloc_enable_global_profiler turns on in CI) the ratios stay the same: a, f G = 1 0.305 [0.294, 0.317], a, s G = 1 0.542 [0.520, 0.566], a, b G = 1 0.388 [0.380, 0.396], G = 16 0.874 [0.848, 0.902], G = 256 0.974 [0.953, 0.995], G = 65536 1.002 [0.978, 1.027].
-- G in 1, 4, 16, 256, 4096
CREATE TABLE u (a UInt64, s String, f FixedString(3)) ENGINE = MergeTree ORDER BY a;
INSERT INTO u SELECT intDiv(number, G), toString(number * 7), toFixedString(substring(reinterpretAsString(toUInt32(number)), 1, 3), 3) FROM numbers(2097152);
-- G in 1, 16, 256, 4096, 65536
CREATE TABLE t (a UInt64, b UInt64, c UInt64) ENGINE = MergeTree ORDER BY a;
INSERT INTO t SELECT intDiv(number, G), number * 7, number * 11 FROM numbers(2097152);
OPTIMIZE TABLE u FINAL; OPTIMIZE TABLE t FINAL;

SELECT a, count() FROM u GROUP BY a SETTINGS optimize_aggregation_in_order = 1 FORMAT Null;
SELECT a, f, count() FROM u GROUP BY a, f SETTINGS optimize_aggregation_in_order = 1 FORMAT Null;
SELECT a, s, count() FROM u GROUP BY a, s SETTINGS optimize_aggregation_in_order = 1 FORMAT Null;
SELECT a, b, count() FROM t GROUP BY a, b SETTINGS optimize_aggregation_in_order = 1 FORMAT Null;

The perf-test rows use the tables and queries of this PR's tests/performance/aggregation_in_order_partial_key.xml and of tests/performance/aggregation_in_order_unique_key.xml from the patch.

Patch (applies on top of 366d3f7 and on master)
diff --git a/src/Processors/Transforms/AggregatingInOrderTransform.cpp b/src/Processors/Transforms/AggregatingInOrderTransform.cpp
index 8d54fe24445..09186a19c43 100644
--- a/src/Processors/Transforms/AggregatingInOrderTransform.cpp
+++ b/src/Processors/Transforms/AggregatingInOrderTransform.cpp
@@ -11,7 +11,6 @@
 #include <Common/MemoryTracker.h>
 #include <Interpreters/Context.h>
 #include <Interpreters/sortBlock.h>
-#include <base/range.h>
 
 namespace DB
 {
@@ -182,6 +181,23 @@ void AggregatingInOrderTransform::consume(Chunk chunk)
 
     size_t interval_index = 0;
 
+    /// In the partial-key mode (group_by_key) all runs are aggregated into the same hash table until the next
+    /// flush, so the rows of consecutive runs are aggregated with one call per span instead of one call per run:
+    /// every call builds the hashing state and other per-call data, which would otherwise be paid for every
+    /// distinct value of the sorting key. The memory limit of the current block is then checked once per span.
+    size_t span_begin = key_begin;
+    auto aggregate_span = [&](size_t span_end)
+    {
+        if (span_begin == span_end)
+            return;
+        if (params->params.only_merge)
+            params->aggregator.mergeOnBlockSmall(variants, span_begin, span_end, aggregate_columns_data, key_columns_raw);
+        else
+            params->aggregator.executeOnBlockSmall(variants, span_begin, span_end, key_columns_raw, aggregate_function_instructions.data());
+        span_begin = span_end;
+        current_memory_usage = std::max<Int64>(getCurrentMemoryUsage() - initial_memory_usage, 0);
+    };
+
     /// Will split block into segments with the same key
     while (key_end != rows)
     {
@@ -205,36 +221,45 @@ void AggregatingInOrderTransform::consume(Chunk chunk)
         }
         ++interval_index;
 
-        /// Find the first position of new (not current) key in current chunk
-        auto indices = collections::range(key_begin, rows);
-        auto it = std::upper_bound(indices.begin(), indices.end(), cur_block_size - 1,
-            [&](size_t lhs_row, size_t rhs_row)
+        /// Find the first position of new (not current) key in current chunk. The input is sorted, so if the
+        /// row at `key_begin` holds the current key, the interval ends where its run of equal sorted-key
+        /// values ends, which the columns find cheaply (one comparison for a run of one row); otherwise the
+        /// chunk starts with a new key and the interval is empty.
+        if (less(res_key_columns, key_columns, cur_block_size - 1, key_begin, group_by_description))
+        {
+            key_end = key_begin;
+        }
+        else
+        {
+            key_end = rows;
+            for (const auto & elem : group_by_description)
             {
-                return less(res_key_columns, key_columns, lhs_row, rhs_row, group_by_description);
-            });
-
-        key_end = (it == indices.end() ? rows : *it);
+                key_end = key_columns[elem.column_number]->getEqualRangeEndAssumeSorted(key_begin, key_end, elem.base.nulls_direction);
+                if (key_end <= key_begin + 1)
+                    break;
+            }
+        }
 
         /// Add data to aggr. state if interval is not empty. Empty when haven't found current key in new block.
-        if (key_begin != key_end)
+        /// In the partial-key mode the interval joins the pending span, which is aggregated before the groups
+        /// are counted for the limit, before a flush, or at the end of the chunk.
+        if (group_by_key)
+        {
+            if (key_end == rows)
+                aggregate_span(rows);
+        }
+        else
         {
-            if (params->params.only_merge)
+            if (key_begin != key_end)
             {
-                if (group_by_key)
-                    params->aggregator.mergeOnBlockSmall(variants, key_begin, key_end, aggregate_columns_data, key_columns_raw);
-                else
+                if (params->params.only_merge)
                     params->aggregator.mergeOnIntervalWithoutKey(variants, key_begin, key_end, aggregate_columns_data, is_cancelled);
-            }
-            else
-            {
-                if (group_by_key)
-                    params->aggregator.executeOnBlockSmall(variants, key_begin, key_end, key_columns_raw, aggregate_function_instructions.data());
                 else
                     params->aggregator.executeOnIntervalWithoutKey(variants, key_begin, key_end, aggregate_function_instructions.data());
             }
-        }
 
-        current_memory_usage = std::max<Int64>(getCurrentMemoryUsage() - initial_memory_usage, 0);
+            current_memory_usage = std::max<Int64>(getCurrentMemoryUsage() - initial_memory_usage, 0);
+        }
 
         /// We finalize last key aggregation state if a new key found.
         if (key_end != rows)
@@ -246,16 +271,32 @@ void AggregatingInOrderTransform::consume(Chunk chunk)
             /// `ORDER BY` prefix, so the rest of the input cannot be needed (see `limit_prefix_columns`).
             /// With `group_by_key`, `cur_block_size` counts runs of the sorted key columns rather than
             /// groups; the groups accumulated for the current block are the entries of the hash table.
-            size_t cur_block_groups = group_by_key ? variants.size() : cur_block_size;
-            if (limit_hint && cur_block_groups + res_rows >= limit_hint && isLimitPrefixBoundary(key_columns, key_end))
-                limit_reached = true;
+            /// Each row of the pending span adds at most one entry, so the span is aggregated only when
+            /// it could reach the limit, and the entries are then counted exactly.
+            if (limit_hint)
+            {
+                if (group_by_key)
+                {
+                    if (variants.size() + (key_end - span_begin) + res_rows >= limit_hint && isLimitPrefixBoundary(key_columns, key_end))
+                    {
+                        aggregate_span(key_end);
+                        if (variants.size() + res_rows >= limit_hint)
+                            limit_reached = true;
+                    }
+                }
+                else if (cur_block_size + res_rows >= limit_hint && isLimitPrefixBoundary(key_columns, key_end))
+                    limit_reached = true;
+            }
 
             /// If max_block_size or limit_hint is reached we have to stop consuming and generate the block. Save the extra rows into new chunk.
             if (cur_block_size >= max_block_size || cur_block_bytes + current_memory_usage >= max_block_bytes || limit_reached)
             {
                 if (group_by_key)
+                {
+                    aggregate_span(key_end);
                     group_by_chunk
                         = params->aggregator.prepareChunkAndFillSingleLevel</* return_single_block */ true>(variants, /* final= */ false).chunk;
+                }
                 cur_block_bytes += current_memory_usage;
 
                 /// When limit is reached, don't save leftover rows — we're done.
diff --git a/tests/performance/aggregation_in_order_unique_key.xml b/tests/performance/aggregation_in_order_unique_key.xml
new file mode 100644
index 00000000000..75e1716902d
--- /dev/null
+++ b/tests/performance/aggregation_in_order_unique_key.xml
@@ -0,0 +1,12 @@
+<test>
+    <!-- Aggregation in order over a sorting key with one row per value: the transform looks for the end of
+         every run of equal keys, so the cost of that search is paid once per row. -->
+    <create_query>CREATE TABLE agg_in_order_unique_key (a UInt64, s String) ENGINE = MergeTree ORDER BY a</create_query>
+    <fill_query>INSERT INTO agg_in_order_unique_key SELECT number, toString(number * 7) FROM numbers_mt(10000000)</fill_query>
+    <fill_query>OPTIMIZE TABLE agg_in_order_unique_key FINAL</fill_query>
+
+    <query>SELECT a, count() FROM agg_in_order_unique_key GROUP BY a SETTINGS optimize_aggregation_in_order = 1 FORMAT Null</query>
+    <query>SELECT a, s, count() FROM agg_in_order_unique_key GROUP BY a, s SETTINGS optimize_aggregation_in_order = 1 FORMAT Null</query>
+
+    <drop_query>DROP TABLE IF EXISTS agg_in_order_unique_key</drop_query>
+</test>
diff --git a/tests/queries/0_stateless/05257_aggregation_in_order_span_limit.reference b/tests/queries/0_stateless/05257_aggregation_in_order_span_limit.reference
new file mode 100644
index 00000000000..2ddcb18ebb3
--- /dev/null
+++ b/tests/queries/0_stateless/05257_aggregation_in_order_span_limit.reference
@@ -0,0 +1,45 @@
+limit, ORDER BY all keys
+499	0	2
+499	2	2
+500	1	2
+499	0	2
+499	2	2
+500	1	2
+499	0	2
+499	2	2
+500	1	2
+499	0	2
+499	2	2
+500	1	2
+9998	1	2
+9998	2	2
+9999	0	2
+499	3	2
+499	4	2
+500	0	2
+499	3	2
+499	4	2
+500	0	2
+limit, ORDER BY the sorting key
+1
+1
+1
+1
+1
+1
+1
+1
+1
+no limit
+20000	99990000	19999	2	2	3152190980451542255
+20000	99990000	19999	2	2	3152190980451542255
+20000	99990000	19999	2	2	3152190980451542255
+20000	99990000	19999	2	2	3152190980451542255
+pushdown
+1
+1
+1
+1
+1
+1
+PUSHDOWN_FIRES
diff --git a/tests/queries/0_stateless/05257_aggregation_in_order_span_limit.sql b/tests/queries/0_stateless/05257_aggregation_in_order_span_limit.sql
new file mode 100644
index 00000000000..c25b3a84712
--- /dev/null
+++ b/tests/queries/0_stateless/05257_aggregation_in_order_span_limit.sql
@@ -0,0 +1,66 @@
+-- Tags: no-random-settings, no-random-merge-tree-settings, no-parallel-replicas
+-- no-random-settings: the block sizes, thread count and the in-order settings are pinned per statement
+-- no-random-merge-tree-settings: the granule size decides how early the pushed-down limit stops reading
+-- no-parallel-replicas: `read_rows` is accounted per reading node
+
+-- With `GROUP BY` keys past the sorting key, in-order aggregation keeps all runs of the sorting key in one hash
+-- table until the next flush and aggregates consecutive runs with one call. The pushed-down `LIMIT` must still
+-- count complete groups: every value of `a` below holds two groups of two rows, so the number of rows not yet
+-- aggregated overestimates the number of groups. Flushes on `max_block_size` or
+-- `aggregation_in_order_max_block_bytes` must not lose or split groups. The `LIMIT 3 OFFSET n` queries check
+-- the groups around the limit at the top level, where the limit is pushed down.
+
+DROP TABLE IF EXISTS t_agg_in_order_span;
+
+CREATE TABLE t_agg_in_order_span (a UInt64, b UInt64, s String) ENGINE = MergeTree ORDER BY a SETTINGS index_granularity = 64;
+
+-- 4 rows per value of `a`: 2 groups of (a, b) and 2 groups of (a, s), with 2 rows each.
+INSERT INTO t_agg_in_order_span SELECT intDiv(number, 4), intDiv(number, 2) % 3, toString(intDiv(number, 2) % 5) FROM numbers(40000);
+OPTIMIZE TABLE t_agg_in_order_span FINAL;
+
+SET optimize_aggregation_in_order = 1, optimize_aggregation_in_order_limit = 1, enable_parallel_replicas = 0;
+
+SELECT 'limit, ORDER BY all keys';
+SELECT a, b, count() FROM t_agg_in_order_span GROUP BY a, b ORDER BY a, b LIMIT 3 OFFSET 998 SETTINGS max_threads = 1;
+SELECT a, b, count() FROM t_agg_in_order_span GROUP BY a, b ORDER BY a, b LIMIT 3 OFFSET 998 SETTINGS max_threads = 1, max_block_size = 7;
+SELECT a, b, count() FROM t_agg_in_order_span GROUP BY a, b ORDER BY a, b LIMIT 3 OFFSET 998 SETTINGS max_threads = 1, max_block_size = 1;
+SELECT a, b, count() FROM t_agg_in_order_span GROUP BY a, b ORDER BY a, b LIMIT 3 OFFSET 998 SETTINGS max_threads = 1, aggregation_in_order_max_block_bytes = 1000;
+SELECT a, b, count() FROM t_agg_in_order_span GROUP BY a, b ORDER BY a, b LIMIT 3 OFFSET 19996 SETTINGS max_threads = 4;
+SELECT a, s, count() FROM t_agg_in_order_span GROUP BY a, s ORDER BY a, s LIMIT 3 OFFSET 998 SETTINGS max_threads = 1, max_block_size = 7;
+SELECT a, s, count() FROM t_agg_in_order_span GROUP BY a, s ORDER BY a, s LIMIT 3 OFFSET 998 SETTINGS max_threads = 2, max_block_size = 100;
+
+SELECT 'limit, ORDER BY the sorting key';
+SELECT count() = 2 FROM t_agg_in_order_span GROUP BY a, b ORDER BY a LIMIT 3 OFFSET 998 SETTINGS max_threads = 1;
+SELECT count() = 2 FROM t_agg_in_order_span GROUP BY a, b ORDER BY a LIMIT 3 OFFSET 998 SETTINGS max_threads = 1, max_block_size = 3;
+SELECT count() = 2 FROM t_agg_in_order_span GROUP BY a, s ORDER BY a LIMIT 3 OFFSET 998 SETTINGS max_threads = 4;
+
+SELECT 'no limit';
+SELECT count(), sum(a), sum(b), min(c), max(c), sum(cityHash64(a, b, c, g)) FROM (SELECT a, b, count() AS c, groupArray(s) AS g FROM t_agg_in_order_span GROUP BY a, b) SETTINGS max_threads = 1;
+SELECT count(), sum(a), sum(b), min(c), max(c), sum(cityHash64(a, b, c, g)) FROM (SELECT a, b, count() AS c, groupArray(s) AS g FROM t_agg_in_order_span GROUP BY a, b) SETTINGS max_threads = 1, max_block_size = 1;
+SELECT count(), sum(a), sum(b), min(c), max(c), sum(cityHash64(a, b, c, g)) FROM (SELECT a, b, count() AS c, groupArray(s) AS g FROM t_agg_in_order_span GROUP BY a, b) SETTINGS max_threads = 1, aggregation_in_order_max_block_bytes = 1000;
+SELECT count(), sum(a), sum(b), min(c), max(c), sum(cityHash64(a, b, c, g)) FROM (SELECT a, b, count() AS c, groupArray(s) AS g FROM t_agg_in_order_span GROUP BY a, b) SETTINGS max_threads = 4, max_block_size = 100;
+
+SELECT 'pushdown';
+-- The pushed-down limit stops reading early, so the checks above run on that path.
+SELECT count() = 2 FROM t_agg_in_order_span GROUP BY a, b ORDER BY a LIMIT 3 OFFSET 98
+SETTINGS max_threads = 1, max_block_size = 16, optimize_aggregation_in_order_limit = 1, log_comment = '05257_span_pushdown_on';
+SELECT count() = 2 FROM t_agg_in_order_span GROUP BY a, b ORDER BY a LIMIT 3 OFFSET 98
+SETTINGS max_threads = 1, max_block_size = 16, optimize_aggregation_in_order_limit = 0, log_comment = '05257_span_pushdown_off';
+
+SYSTEM FLUSH LOGS query_log;
+
+SELECT if(on_reads < off_reads, 'PUSHDOWN_FIRES', format('FAIL: on={} off={}', on_reads, off_reads))
+FROM
+(
+    SELECT
+        anyIf(read_rows, log_comment = '05257_span_pushdown_on') AS on_reads,
+        anyIf(read_rows, log_comment = '05257_span_pushdown_off') AS off_reads
+    FROM system.query_log
+    WHERE current_database = currentDatabase()
+      AND log_comment IN ('05257_span_pushdown_on', '05257_span_pushdown_off')
+      AND type = 'QueryFinish'
+      AND event_date >= yesterday()
+      AND event_time >= now() - 600
+);
+
+DROP TABLE t_agg_in_order_span;

@groeneai the patch touches only the transform, so it can go into this PR or into a separate one after this merges, whichever you prefer.

One conflict in src/Common/ColumnsHashing/HashMethod.h: master added
`estimatePreparedKeysMemory` right above the `HashMethodKeysFixed`
constructor whose signature this branch extends with `RowRange rows = {}`.
Kept both. The estimate models the whole-block `packFixedBatch`, which the
constructor still runs for the default range; its callers
(`DistinctSetFilter`, `gtest_distinct_set_filter`) build whole-block states.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Common/ColumnsHashing/HashMethod.h Resolved
The sub-range branch in `HashMethodKeysFixed::getKeyHolder` was compiled
into every fixed-key state, including those that only ever cover whole
blocks (`Set` / `IN`, `LIMIT BY`, `JOIN`, whole-block `GROUP BY`). It merges
a key returned in general-purpose registers into the hot loop, so the
128-bit key leaves `%xmm0` there too. Performance Comparison on the arm
release build flagged it as blocking: `set_packed_keys ClickHouse#1` +15.8% and
`limit_by_in_pk_order ClickHouse#1` +21.5%, both slower on this PR only in 14 days
of CIDB.

The sub-range logic now sits behind a `for_sub_range` template parameter.
Only `ColumnsHashing::SubRangeState<State>` turns it on, and only for
states that can batch-pack their keys. Its users are the three callers
that build one state per run of a block: `executeOnBlockSmall` and
`mergeOnBlockSmall` (in-order aggregation, single-level variants only),
`DistinctSortedStreamTransform::buildFilterForRange` and
`MergeTreeIndexAggregatorSet::buildFilter`. Every other state compiles
master's code; the adaptive aggregator's slices go back to master's
whole-block state too.

Verified on the release configuration (clang-22, -O2, no ThinLTO) by
compiling Set.cpp, LimitByTransform.cpp and Aggregator.cpp against master's
headers and against this tree, then comparing every fixed-key function:
all whole-block hot loops (`Set::insertFromBlockImplCase` /
`executeImplCase`, `LimitByTransform::consumeImpl`,
`Aggregator::executeImplBatch*`) are instruction-identical to master
except two instructions per state construction that pass the default
`RowRange`. The previous head differed in 36 of 48 `Set` and 21 of 37
`LIMIT BY` functions. The in-order copies add 443 KB to Aggregator.o
.text. The headline query still runs in 0.049 s (6.2 s on master).
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 10, 2026
Merged via the queue into ClickHouse:master with commit 9e04b98 Oct 10, 2026
149 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 10, 2026
huldarchen pushed a commit to huldarchen/ClickHouse that referenced this pull request Oct 13, 2026
feiyunwill pushed a commit to feiyunwill/ClickHouse that referenced this pull request Oct 16, 2026
`HashMethodKeysFixed` batch-packs a block's keys only when `usePreparedKeys` holds, which excludes
every key set with a Nullable column, so `GROUP BY` / `DISTINCT` over nullable fixed-width keys
(`nullable_keys128` / `nullable_keys256`, e.g. TPC-DS q65) builds the NULL bitmap and packs the key
row by row.

For a row without NULLs the nullable per-row layout is a zero bitmap followed by the keys in clause
order, which a strided batch copy produces. Nullable states now batch-pack that layout
(`packFixedBatchOrdered`) and re-pack with the per-row code only the rows that have a non-zero
null-map byte; null maps that are all zero over the range are skipped with `memoryIsZero`. A row
whose null-map bytes are all zero gets no bit from `createBitmap` whether a set byte is tested for
`== 1` or for non-zero, so the result is the per-row key either way. The only allocation stays
`prepared_keys`, so `estimatePreparedKeysMemory` (now true for these key sets) stays exact.

Nullable states also get a sub-range variant (`SubRangeStateOf`), so aggregation in order, DISTINCT
in order and the set skip index pack only the run they are built for, with the same 256-row
threshold as the non-nullable keys (ClickHouse#120259). Without it, a whole-block pack per run of the sorting
prefix made `GROUP BY a, nb` in order 0.045 s -> 17.5 s on 131072 rows with unique `a`.
The range selection is shared by both batching branches (`rowsToBatchPack`).

Non-nullable key sets keep their path: `keys256` is shared with the hash join, and its measured gain
was small.

Release A/B vs master (4 threads, 9 interleaved runs, paired geometric mean):
nullable pair 60M groups 0.80x, 7.7K groups 0.39x; group_by_fixed_keys.xml a,d 0.80x, e,i 0.88x,
e,f,i 0.74x; (Nullable(Int64), Int64) 40M rows with 50% NULL 0.74x, all NULL 0.89x; DISTINCT e,i
0.42x; non-nullable controls 0.96x-1.05x. In order (1 thread): unique-`a` arms 0.99x-1.03x, runs of
300 0.40x-0.87x, runs of 65536 0.76x.

Based on the patch in issue ClickHouse#120100.

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-aggregation GROUP BY / aggregation framework (hash tables, spilling, external aggregation). groeneai-origin-issue PR origin: picked up an external GitHub issue 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.

partial GROUP BY key for optimize_aggregation_in_order is really slow

5 participants