Repository navigation
Fix quadratic key packing in aggregation in order and DISTINCT in order - #120259
alexey-milovidov merged 11 commits into
Conversation
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]>
Internal second-model review (click to expand)Two independent reviews ran against this branch before it was published: an automated second-model pass
Residuals, kept deliberately:
Checked rather than assumed, in the final round: Session id: cron:clickhouse-review-slot-10:20260915-182400 |
|
Workflow [PR], commit [885feab] Summary: ✅
AI ReviewSummaryThis PR limits the new sub-range prepared-key path to the three callers that actually build one hashing state per block sub-range — Final Verdict
LLVM Coverage ReportMeasured on commit 885feab.
Changed lines: Changed C/C++ lines covered: 115/115 (100.00%) · Uncovered code |
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]>
|
Fast test was red on the previous head because of the new test in this PR, not the fix: Why no fixture size fits that cap: a guard allows the fixed path 120 s because a linear path stretches What makes the fixed path cost 10 s per guard here (measured)Every CI server installs Session id: cron:clickhouse-maint-slot-13:20260915-214900 |
`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]>
Internal second-model review (click to expand)Two independent reviews ran against this branch before publication: an automated second-model pass and
Residuals, disclosed rather than fixed:
Checked this round independently of the author's notes: every hashing-state construction in Session id: cron:clickhouse-review-slot-10:20260916-115300 |
Build profile diff (arm_release)Commit See the job log for details. |
CI finish ledger - f9ab407Every 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
The failing job ran before that fix merged, so master is merged here to pick it up. The mirrored 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.
CI finish ledger - 554f8e2Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20260917-003056 |
|
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 Setup: master 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.
The range batch is only a measurement: it sizes 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.
|
Confirmed, and fixed in this PR at I reproduced the long-run regression on the published head ( 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:
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 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 |
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.
CI finish ledger - 366d3f7Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose
All 176 check-runs completed (159 pass, 14 not selected, 3 red), One non-green measurement disclosed here rather than left in the report: Session id: cron:our-pr-ci-monitor:20260924-090214 |
|
The The slowdown is specific to the
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 --- 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{}; |
|
I verified this locally and I am keeping Mechanism confirmed, with one correction. Compiling
The correction: no stack round trip in this translation unit. Why the one-liner does not ship. It buys
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 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: 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 |
|
A runtime restructuring recovers about 60% of the
Against this PR, the six in-order queries (single-threaded, 20 pairs) are unchanged: runs of 1, 16 and 65,536 rows, The long-run slowdown does not reproduce here. Master against this head, single-threaded as in the perf test, 30 pairs:
The stack round trip is in our clang-21 release build: the Variant diff against 366d3f7diff --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)
{ |
|
With this PR applied, in-order
The patch below changes only the transform. It finds the run end with one Server
With more rows per value the gain shrinks (ratio, 95% CI; – not measured):
This is complementary to the PR. Measured the same way, this PR alone against master changes only the two- Trade-offs:
Paths the patch does not touch stay within 0.987 to 1.013: in-order aggregation turned off, Correctness, on the same two binaries: 1,847 differential queries give byte-identical output, including order-sensitive Setup, controls and reproductionOne x86_64 host (Xeon Platinum 8375C, 4 vCPU). A is master Controls (ratio, 95% CI):
-- 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 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]>
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).
`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]>
Closes: #45386
Related: #110159
Related: #118025
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
With
optimize_aggregation_in_order = 1, or with the defaultoptimize_distinct_in_order = 1, aGROUP BYorDISTINCTwhose 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 inmax_block_sizeonce the sorting prefix is near-unique, soGROUP BY a, bon a table sorted byais up to 130x faster. Closes #45386.Description
AggregatingInOrderTransformsplits each block into runs of equal sorting-key value and builds a freshMethod::Stateper run. For a fixed-size key satisfyingusePreparedKeys, that constructor batch-packed the grouping key of the whole block:packFixedBatchwritesout[i]for every row of the key column andgetKeyHolderreadsprepared_keys[row], so the array index is the absolute block row. One block therefore costO(runs * block_size).A state built over a sub-range (
ColumnsHashing::SubRangeState, a template parameter ofHashMethodKeysFixed) 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 layoutpackFixedBatchproduces (one pass per key width, longest first;shuffleKeyColumnsmakes 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 (INsets,LIMIT BY, joins, whole-blockGROUP BY) keep master's hot loops instruction for instruction.Aggregator::method_chosen_for_in_orderalready makes this trade for serialized keys.Three other consumers build one state per sub-range and now use it too:
Aggregator::mergeOnBlockSmall,DistinctSortedStreamTransform::buildFilterForRangeandMergeTreeIndexAggregatorSet::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):aunique,GROUP BY a, b6.119 s -> 0.046 s; 256 rows pera0.502 [0.496, 0.508]; 4096 rows 0.933 [0.921, 0.946]; 65536 rows 0.991 [0.976, 1.007].DISTINCT a, b, cbehaves the same way. Both optimisations off are at parity. The in-order copies of the aggregation loops add 443 KB toAggregator.o.The array is sized to the sub-range, not its absolute end, so allocated bytes per block stay linear: with
jemalloc_enable_global_profilerarmed, 256 rows perameasures 0.443 [0.438, 0.448] of master.Workflow [PR]
Sync PR [sync-upstream/pr/120259]
Version info
26.10.1.2025-master(included in26.10and later)