Repository navigation
Conversation
The GROUP BY top-K heap of `enable_group_by_top_k_optimization` was disabled when a matched `ORDER BY`
key had `COLLATE`. It now ranks such keys in the collation order of the final sort:
- `Aggregator::Params::TopKParams` holds the collators as `std::shared_ptr`; the heap compares collated
keys with `compareAtWithCollation` (no typed numeric fast path for them), and a trim keeps every key
that ties with the boundary under the collation (distinct strings can compare equal).
- Version 2 of the `Aggregating` step writes the locale of each top-K key and recreates the collator on
read; the query plan serialization version goes to 21, and towards an older peer a collated top-K is
omitted (the peer aggregates without the heap, which is correct).
- The dynamic filter's threshold tracker compares under the same collator, and the locale is part of the
query condition cache salt of its filter.
- A `COLLATE` on a key that cannot be collated stays on the sort, which rejects it.
A collated heap tests every row with a locale comparison, which costs more than the hash-table work it
saves unless the rows keep inserting new keys (one comparison per row instead of one per group in the
final sort). So such a heap waits: an aggregation stream starts it once its table holds 32768 keys and
the last block inserted new keys for at least 99.5% of its rows, re-checked after every block. A heap
still waiting at the adaptive aggregator's between-blocks freeze gives up, so the table freezes as with
a frozen heap. The two constants were chosen on a release-build grid (T in {4096, 16384, 32768}, share in
{0.95 .. 0.995}; 20M rows, 1/16/64 threads, LIMIT 10/100/1000, a composite key with the collation on the
second key, 8192-row blocks, input sorted by the key): every lower share starts the heap at 1M-3M
distinct keys with one thread, where it is 1.2x-1.5x slower, and a smaller table size starts it on small
blocks too early.
Measured with the constants (release build, 20M rows, `ORDER BY s COLLATE 'en' LIMIT 10`, median of 5,
off -> on, with the `ucol_strcollUTF8` comparator and an emulation of the adaptive freeze fix that keeps an
undecided heap from freezing): 16 threads 12.6M keys 322 -> 180 ms, 992 -> 95 MiB; 6M keys 229 -> 158 ms;
1 thread 12.6M keys 2003 -> 1315 ms; 1 thread 1M keys 616 -> 612 ms; 16 threads 1e3..3e6 keys and
input sorted by the key unchanged (within 3%).
Closes ClickHouse#126735
Co-Authored-By: Claude Opus 5.5 <[email protected]>
The 4-stream case read `t_05407`, whose 33792 starter keys are split between the streams, so no stream was guaranteed to reach the 32768-key start floor and the case passed with every heap waiting. It now reads 160000 unique starters from `numbers_mt` before the a/á/Z tail, so at least one of the 4 streams sees 40000 of them and starts its heap, and the tail is ranked across streams that did and did not start. The case is added to the `engaged` check (pruned = 1). Co-Authored-By: Claude Opus 5.5 <[email protected]>
Drop the doc of topKCollationLocales (its body says it) and the give-up line at the adaptive freeze (stated at the constants), and shorten two version/predicate docs to one line. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Internal second-model review: adjudication log (click to expand)Pre-publication review by an independent model (engine: codex; 4 findings on 709b322, 0 on the fix round 7123faf) plus my own review.
Severity: ❌ blocker / Session id: cron:clickhouse-review-slot-8:20261020-033800 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-4:20261019-231000 |
|
Workflow [PR], commit [19b1bbf] Summary: ❌
AI ReviewSummaryThe PR enables Findings❌ Blockers
Missing context / blind spots
Final VerdictStatus: ❌ Block Prevent the default-enabled repeated-key regressions and validate both skipped-key and retained-key workloads. Restore the malformed grouping-set rejection or provide the concrete separate fix/tracking link. Keep the deliberately dismissed discussions closed; the outstanding concerns are recorded here. |
|
cc @nihalzp, could you review this and add the |
The flaky check runs 8 copies at once with the thread fuzzer on, and there the test took 226-267 s per run against the 180 s limit (amd_binary and amd_debug). Its query_log shows the time going to pipeline chunks: about 5 ms per 128-row block, whatever the data. Use larger blocks (128 -> 1024; 100 -> 800 for the ties case; 64 -> 512 for the query condition cache table) and less data where the size is not the point: 100 tie cycles instead of 1000, and 4096 spill payload rows instead of 8192 (2 spills instead of 4-5). The heap still starts at the same rows: 32768 and the 33792 starters are multiples of 1024, and 800-row blocks end exactly at the 32800th tie starter. Only the tie counts change in the reference. Every engaged row is the same, and each mutation used to validate the original change still fails the test at the same cells. Priced on this PR's amd_binary build against a thread-fuzzer server and the failing job's query_log: about 84 s per run instead of 238 s. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes55 object files changed (+316.63 KiB total), 0 added.
716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units204 translation units recompiled, 1480 s compile time in total, 204 of them have a recent master baseline. |
The per-row skip test of a `String` or composite key (`shouldSkip`) went through `compareColumns`, which now reads `collators[i]` before every comparison. That added a dependent load chain and a register spill to the innermost loop of every non-collated heap, and `Performance Comparison (arm_release)` reported `optimize_trivial_group_by_limit` ClickHouse#6/ClickHouse#7 (`GROUP BY lower(toString(number % 10000000)) LIMIT 10`) 17% slower (amd: 11%, under its threshold). The heap now records whether any ranked column has a collation, and only such a heap takes the collation-aware skip test, out of line in the .cpp. The other heaps compile to the same skip test as before this PR. The per-block new-key count is taken only while a collated heap waits. Release build, query ClickHouse#7 shape, median of 120-240 runs, ratio vs the base without this PR (A/A noise 0.99-1.01): 1 thread 1.054 -> 0.997, 8 threads 1.042 -> 1.001, 32 threads 1.029 -> 0.991. The collated heap itself stays within 1%. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…repeat A heap with a COLLATE key starts once a stream's table is large and a block still inserts almost only new keys. Cyclic input passes that check in its first cycle, and after it the heap spends one locale comparison per row on keys it has already skipped, where the hash lookup it saves is cheap: 100K keys repeated over 20M rows were 1.8x slower with the heap (2.5x on the ARM CI binary). Input whose every row is a new best key is worse (2.6x at 8M keys), since nothing is skipped and every row is inserted and evicted. Once the heap has filled, it now hashes the GROUP BY keys of each block (`computeHashInto`) and estimates the share of rows that bring new keys in two ways: over 1 key in 64 by hash, whose skipped rows count as new when the sample has not seen the key, and as the rows whose key did not occur earlier in the same block (a few hot keys are usually all outside the 1-in-64 sample: 5 keys after 100K unique ones were 2.4x slower). A window where either estimate is below one half extends a run of repeats, and the heap freezes once the run reaches half a row per key skipped so far, because freezing inserts those keys after all; without that length, streams that read a contiguous slice with a short repeat tail (16 threads, 1M keys in cycles) gave up a 2.6x gain (40 -> 106 ms). At 32768 sampled keys (about 2M skipped) the stream stops sampling: past that point the heap keeps millions of keys out of the table, and a repeating tail still came out ahead (5 keys after 3M unique ones 588 -> 389 ms, 1M keys in cycles after them 815 -> 418 ms). `group_by_top_k_optimization_observation_rows = 0` disables it like the other profitability freeze. Release build, 20M rows, `LIMIT 10`, 'en', heap off / before / after (ms), medians of alternating runs: 1 thread: 100K keys in cycles 268 / 494 / 274, 1M 315 / 466 / 340, 1M in descending order 328 / 740 / 324, 8M descending 1033 / 2680 / 1039, 5 keys after 100K unique 140 / 331 / 106; uniform 12.6M keys 1777 / 732 / 750, 4M in cycles 757 / 459 / 468. 16 threads with the adaptive aggregator off: 100K in cycles 25 / 39 / 28, 1M in cycles 106 / 40 / 48, uniform 12.6M 172 / 58 / 70 (the hashing while sampling). The table of recent hashes is kept across blocks: with a per-block table, 3 alternating hot keys read in 3-row blocks were never detected. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…when it never fills Two cases where a started heap with a `COLLATE` key kept paying a locale comparison per row without keeping new keys out of the hash table: - Once the 1-in-64 hash sample of skipped keys reached its cap (about 2M skipped keys), the repeat check stopped for the rest of the stream, so a long tail of one key ran with the heap: 3M unique keys then 97M rows of one key took 1632 ms with the heap and 890 ms without (x86 release, 1 thread; 2.1x on the ARM CI binary). Past the cap the check now keeps the direct-mapped table of recent hashes, which sees a few hot keys, over a slice of 1/8 of every block that moves through the block from block to block, with its counts weighted by 8 and its windows covering whole rotations of the slice, so it costs about 1% on the streams the heap wins (uniform 12.6M keys 746 -> 756 ms). The tail above now takes 596 ms (896 ms off). A tail of many keys still keeps the heap, as a lookup into the large table costs more than the comparison (1M keys in cycles after 3M unique ones: 844 ms off, 419 ms on). - A heap starts late and only tracks keys inserted after that, so when the rows after the start hit existing keys it never fills, gets no boundary, and `shouldFreeze` (which wanted a full heap) never froze it; the aggregation then stayed on the top-K path to the end (+31% on the ARM CI binary for 32768 unique keys then one existing key, +2-3% on x86), and with the adaptive freeze fix such an undecided heap would also hold the adaptive freeze. A heap with a `COLLATE` key now freezes after its observation window even when it has not filled. 05407 covers both: `05407_run_never_fills` (heap froze, nothing pruned) and `05407_run_after_sample` (after 2.2M unique keys, one key with unique keys in the first eighth of every block; heap froze); each row is red with its part of the change reverted. Co-Authored-By: Claude Opus 5.5 <[email protected]>
On Darwin `UInt64` is `unsigned long long` while `size_t` is `unsigned long`, so `std::min` could not deduce one type for the post-sample slice start (`blocks_after_sample` is `UInt64`). Name the type, as the line above does. On Linux both are `unsigned long`; the object code is unchanged. Co-Authored-By: Claude Opus 5.5 <[email protected]>
… check `Stateless tests (amd_asan_ubsan, flaky check)` failed one of 50 runs with "Test runs too long (> 180s)" (186.6 s; the other runs averaged 148 s). Under the thread fuzzer the cost follows the number of chunks and granules a query passes through, not its rows. Its query log points at three sources: - `t_05407` used `index_granularity = 128`, so every read of its 63792 rows went through 500 granules. 1024 matches the queries' block size and keeps the dynamic filter able to drop rows of the later granules once the heap publishes its boundary (with 8192 the read runs ahead of the boundary and the tracker-without-collator mutation no longer shows). The spill table takes 8192. - The off twin of every pair read in the small blocks of the on run, and the off twin of the spill case spilled. The off run only computes the expected result, which depends on neither, so it now reads in 65536-row blocks and aggregates in memory. - `05407_run_after_sample` read 3.5M rows in 8192-row blocks; 16384-row blocks (unique keys in the first eighth of each block, as before) still make the heap give up after its sample fills, at nearly the same row. The reference is unchanged. Thread fuzzer, debug build, 16 runs x 8 jobs side by side: 477 -> 303 s mean per run; per-statement ratios applied to the failing job's query log give about 78 s of query time per run instead of 128. Mutations M1 (heap compare ignores the collator), M2 (serialized plan without locales), M4 (dynamic filter tracker without the collator), the start floor raised to 1e6, and the three post-sample give-up mutations still turn the test red at the same cells; 50 of 50 randomized runs pass. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…larity 1024 `Stateless tests (amd_asan_ubsan, db disk, distributed plan, targeted)` failed 1 of 42 runs with `05407_spill 0 1 1`: the spill query spilled, but its heap never pruned. A MergeTree read returns a whole granule as one block. With the spill table at `index_granularity = 8192` and a small random `index_granularity_bytes` (936615, compact part), the granules were 7543 rows, so the block that brought the table to 32768 keys (rows 30172..37714) also carried 3923 of the 4096 2000-byte payloads. The heap was allowed to start only after that block, the same block pushed the table over the two-level byte threshold and spilled, and the recreated table waits again, so the heap never ranked a row. At 1024, like `t_05407`, a block of this read holds fewer than 2048 rows, so the block that reaches 32768 keys carries at most about 1000 payloads (2 MB) and the heap starts before the rest arrive, in every layout. Measured on the failing run's exact settings (all except two not in this build): before 4/4 runs `05407_spill 0 1 1`, after 4/4 green. Spill case only, `index_granularity_bytes` 1024..30M x const granularity x compact/wide (+ the columns cache): at 8192 the compact 936615 cells prune nothing, at 1024 all 32 prune (>= 1119 keys evicted) and spill. 50/50 randomized runs green. Thread fuzzer, 8 parallel: the spill statements cost 29.2 -> 32.5 s per run locally (the rig is about 3x slower than CI). The reference is unchanged. Co-Authored-By: Claude Opus 5.5 <[email protected]>
CI finish ledger - f95795fEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
CIDB has no other Session id: cron:our-pr-ci-monitor:20261022-013033 |
|
@groeneai no improvements are visible in CI. |
|
Right, and the missing freeze fix is not the only reason. The The cause is my start condition: it needs a block in which at least 99.5% of the rows insert new keys, but URLs repeat within blocks. In I'll measure a started heap on |
|
@thevar1able here are the numbers I promised, and one decision before I change the PR. Release build on CI's
Options:
I would take 1: 2 is the heuristic you scoped out, and I cannot yet show it keeps the cyclic cases neutral. Which do you prefer? |
|
🕵️ The perf CI shows no change for this PR because the new query never ran, and with default settings the collated heap can't run anyway. What I found:
Changes to make:
|
Master enabled the modernize-use-nodiscard clang-tidy check, which flags these two const getters that this branch adds. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Resolved the new conflict by merging master in c7e4049. Master added The review still blocks on the repeated pruned keys regression (#126878 (comment)). I'm taking the poke as a go-ahead for option 1 from that comment: I'm implementing it now and will post the |
Since the lookup-first change, a collated heap compares only rows whose key is not in the table, but a key the heap
skipped or pruned is never in the table, so each of its repeats still pays the locale comparison, and `shouldFreeze`
never fires because nearly every row is skipped. With 20M rows of `concat('k', toString(number % N))`, one thread, the
heap was 5.7x slower than the optimization off at N = 1K, 5.2x at 10K and 1.5x at 100K.
A collated heap that ranks all `GROUP BY` keys now keeps a 1/64 hash sample of the distinct keys it skipped and
freezes after the profitability window once its skipped rows reach 32 per estimated distinct key, as long as the sample
holds fewer than 4096 keys (about 262K distinct) and 4M skipped rows; past either cap the heap stays. The bar is 32
because `hits` `URL` streams repeat a key 8-48 times early on, and a lower bar (8, 16) froze 3-8 of their 12 heaps and
gave back a third of the gain. Sampling a block in four, or a row in four, undercounts the rare keys of such streams
and froze 6 of 12 heaps, so every skipped row is hashed, with CityHash for a plain `String` key.
Release build (no LTO), 20M rows, `COLLATE 'en' LIMIT 10`, medians, ms, before -> after (off):
- N = 1K: 1 thread 425 -> 75 (73), 8 threads 58 -> 14 (13), default 19 -> 9 (7)
- N = 10K: 426 -> 89 (82), 56 -> 23 (16), 20 -> 15 (10)
- N = 100K: 422 -> 322 (280), 59 -> 70 (60), 20 -> 23 (27)
- N = 1M: 431 -> 451 (365); 20M unique: 8 threads 53 -> 56 (229), default 19 -> 24 (77)
- `hits_100m_single` `URL`, defaults: 12 threads 804 -> 818 (1317), 8 threads 1178 -> 1232 (1816); 1 heap of 12 freezes,
as before.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
1K keys in cycles at the default number of threads and 100K keys in cycles in one thread, each against the optimization off. Release build, 12 threads, 50M rows of 1K keys: 135 ms before the freeze of a collated heap whose skipped rows repeat few keys, 52 ms after, 56-69 ms with the optimization off. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The sample took the keys whose CityHash64 has its top 6 bits zero, which is `cityHash64(s)` in SQL, so a table sharded or filtered on those bits could have no sampled key: 2M unique keys outside that range froze a profitable heap (232 ms, 55 ms after the change). `intHash64` of the hash picks the sample instead. The description of `AggregationTopKHeapsFrozen` gets the new reason, and the setting's sentence on the hash-table lookup before the comparison gets the exception of the serialized method of a composite key. Co-Authored-By: Claude Opus 5.5 <[email protected]>
With `group_by_top_k_optimization_observation_rows = 0` the heap never freezes for its skip rate, so the sample was pure cost: `hits` `URL` at 12 threads 754 -> 785 ms. The comment next to the constants now gives the final 10K range. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Pushed option 1 in 15a9660 to 2603fd1. A collated heap that ranks all Release, 20M rows of
|
…ple fills A collated GROUP BY top-K heap stopped sampling its skipped keys for good once the sample reached a cap, so a stream that turns into a few repeated keys after many distinct ones paid a collation comparison per row for the rest of the query. Now a full sample is dropped and a new one starts 8M skipped rows later; a later sample freezes the heap at 256 skipped rows per distinct key instead of 32, because later stretches of clustered data repeat keys more (hits_100m_single URL samples reach 128-256 at 12 threads: 64 froze 3 of 12 heaps, 128 froze 2, 256 froze 1 like before). A sample that already shows the repeats when it reaches the row cap is kept until the freeze check after the block, so a block larger than the cap no longer loses that evidence (5M-row blocks of one repeated key never froze). Release build, max_threads = 1, on / off, ms: - 5M distinct keys then 95M rows of one key (the reviewer's query): before 2417 / 1857, after 1173 / 1849 - the same with a 101-char tail key equal to the boundary up to case: before 43318 / 2288, after 3412 / 2304 - tails of 1K / 10K keys after the 5M distinct: before 1693 / 1689, after 460 / 570 (off 1339 / 1642) - hits_100m_single URL ASC COLLATE 'en' LIMIT 10: 12 threads 874 -> 841, 8 threads 1288 -> 1277 (off 1303 / 1888), 1 heap frozen before and after; 1 thread 8408 -> 8630 (off 11900+); a 2M pause cost 3-4% at 12 threads (the re-armed samples hash every skipped URL) - 20M rows in 1K/10K/100K/1M-key cycles and unique, 1/8/default threads: within noise Tests: 05407 cases 05407_skip_unique_then_repeats (300K distinct keys, then 9.7M rows of one key) and 05407_skip_repeats_large_block (5M-row blocks of one key) freeze now and did not before. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
@groeneai poke |
…ation Master moved applyTopKPushdownToPartialAggregation from Planner.cpp to PlannerSteps.cpp and switched the TopKParams directions to VectorWithMemoryTracking; the collations follow both. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Master is at 26.12 now, and this branch bumps the version to 22, so the line names the release of the bump, as the rule above it asks. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The collated top-K look-up in executeImplBatchNoAggregates instantiates findKey for the set of fixed-width keys and a String, whose find returns const void *, and clang-tidy then flags 'auto it' in findKeyImpl (ColumnsHashingImpl.h:572, readability-qualified-auto). The same 'it' is a lookup-result class for other tables, so 'auto' is the right spelling. Master's Aggregator.cpp is clean; this branch's was rc 1 before, rc 0 after. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Merged master in e3976b1 and pushed 09b7a9f. The PR is mergeable again, so CI can run. The conflicts were master's
Locally: debug build, the top-K gtests and 81 top-K and collation stateless tests pass. |
When the `ORDER BY` covers only a prefix of the `GROUP BY` keys, the heap ranks the prefix and only skips rows. Its
skipped-key sample hashes the ranked columns, which do not identify a group, so it cannot tell whether the groups it
skips repeat and never gives up on them. A skipped group is never inserted, so every one of its rows misses the
look-up and pays a locale comparison, while the optimization off only updates a small hash table.
Release, 20M rows (10 winners, then 2000 groups of `concat('z', toString(number % 1000))` x `number % 2`),
`GROUP BY s, b ORDER BY s COLLATE 'en' LIMIT 10`, medians, ms, on / off: 360 / 111 at 1 thread and 47 / 18.5 at
8 threads before; 107 / 106 and 17 / 17.5 after.
`canTopKRankSortKey` now accepts a `COLLATE` only for a heap that ranks every `GROUP BY` key, in both the plan
optimization and the pushdown to remote partial aggregation. `05407` checks that neither path ranks a collated prefix.
Related: ClickHouse#126878 (comment)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Per ClickHouse#133718, `run_all_queries` is for standard benchmarks only; CI samples 10 queries of this test per job. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ation Master added a heap over all grouping keys for `GROUP BY ... LIMIT` without `ORDER BY` (`applyTopK`, `topKByAllKeys` in optimizeGroupByTopK.cpp). The merge is textually clean, but that new code does not compile against this branch: `tryAttachDynamicFilter` takes the collators, and `TopKParams` has a `collators` field. Pass the collators in `applyTopK` and leave them empty in `topKByAllKeys` (that heap never collates). Co-Authored-By: Claude Opus 5.5 <[email protected]>
The planner never applies the GROUP BY top-K to grouping sets, but the `Aggregating` reader accepted such a payload, checking `key_columns` only against the outer key count. `transformPipeline` copies `top_k` into the aggregation of each grouping set via `cloneWithKeys`, so a set with fewer keys made the heap read key column pointers past the end of that set's key columns. Reject the combination with INCORRECT_DATA, as is already done for in-order aggregation. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
@groeneai The main goal of this change is the memory saving, and the core already delivers it. In the perf run at Keep
Remove
Also
|
|
Acknowledged. I'm trimming the PR to the core you listed, measuring the look-up-first path against the optimization off and checking the observation-window freeze on a collated heap, and moving the grouping-sets check to a separate PR. I'll follow up here with the push and the numbers. |
As asked in review: the point of the change is the memory saving, so everything that traded it back for CPU, or that only tuned CPU, is removed. - The skipped-key sampling freeze (`collated_skip_sample*`, `sampleCollatedSkip`, `collatedSkipsRepeat` and the pause/resume logic) is removed, and with it its doc paragraph, the `AggregationTopKHeapsFrozen` wording and the 05407 cases that tested it. - `collated_min_trim_slack` is removed: a collated heap trims at `k + k / 2` like any other. - The look-up-first path in the aggregation loops is removed (and the `NOLINT` it needed in `ColumnsHashingImpl.h`). Without it no measured collated query is slower than with the optimization off where it was not already slower with it, and it cost time on `hits`. Release build, `hits_100m_single` (CI's), medians of 5, ms: | Query | off | with look-up-first | without | |---|---|---|---| | `URL` ASC, 12 threads | 1260 | 716 | 606 | | `URL` DESC, 12 threads | 1242 | 700 | 584 | | `URL` ASC, 1 thread | 13005 | 12782 | 6920 | | 20M unique keys, 12 threads | 163 | 40 | 42 | | 1M keys in descending cycles, 12 threads | 69 | 66 | 62 | | 1K keys in cycles, 50M rows, 12 threads | 63 | 153 | 121 | | 20 keys in cycles, 50M rows, 12 threads | 51 | 89 | 142 | - The grouping-sets check in `AggregatingStep::deserialize` goes to a separate PR. Kept: `TopKParams::collators`, the collated compare and trim in the heap with the boundary tie handling, `Aggregating` step version 2 (plan version 22, top-K omitted towards older peers), ranking a `COLLATE` key only when the `ORDER BY` covers every `GROUP BY` key, no dynamic filter on a collated first key, and the collations in `EXPLAIN`. On `hits` at default settings no heap freezes any more at 12, 32 or 64 threads: 61-155 MB, the same as with `group_by_top_k_optimization_observation_rows = 0`, against 5.7-6.2 GB with the optimization off. Related: ClickHouse#126735 Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Done in 095e3114b255: the sampling freeze,
The description is rewritten without the per-commit tables. I'll replace its numbers with the perf run's. |
`Performance Comparison (arm_release, master_head, 4/8)` on 095e311 marked `optimize_trivial_group_by_limit` ClickHouse#6 and ClickHouse#7 (`String` key, no `COLLATE`) as confirmed regressions: 50 -> 59 ms (+18%). The loops of the methods without a typed key called `shouldSkipTyped` out of line on every row; master fixed that the same way in ClickHouse#133805 (`shouldSkip` forced inline and called directly), which the previous merge brings in. What remains of this PR in those loops is the `has_collators` branch of the force-inlined `shouldSkip`. It inlined both collated comparators into every loop. They now live in an out-of-line `shouldSkipCollated` (`NO_INLINE`, so that ThinLTO does not import it either), so the loops get a branch and a cold call, the shape the PR had at 1a5e9ec, where arm measured ClickHouse#6/ClickHouse#7 at 52 -> 51 ms. Local release builds (no ThinLTO/PGO), 8 threads, medians of 42 runs, ms, master 290fa0d / merge without this / with this: - ClickHouse#6: 56.5 / 59 / 59 - ClickHouse#7: 58 / 58.5 / 59 - ClickHouse#7 without `count()`: 57.5 / 56.5 / 56 - numeric key: 39 / 37 / 37 Before the merge, 095e311 measured ClickHouse#7 at 64 ms against master's 61. The collated queries do not change: 1K keys in cycles at 12 threads 115 -> 114 ms, 20M unique keys 38 -> 38 ms; `hits` `URL ... COLLATE 'en' LIMIT 10` at 12 threads, measured on 095e311 before the merge: 598-608 -> 579-622 ms, 61 MB both. Related: ClickHouse#126735 Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
@thevar1able The perf run on 095e311 has the numbers (amd, master where the optimization is off -> this PR, default settings):
The description now has these numbers. The same run flagged One decision is yours.
|
|
The grouping-sets check is in #134316. |
Closes: #126735
Related: #126829
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
The
GROUP BYtop-K optimization (enable_group_by_top_k_optimization) now also applies when theORDER BYcovers everyGROUP BYkey and sorts some of them withCOLLATE, e.g.GROUP BY s ORDER BY s COLLATE 'en' LIMIT 10.Description
The optimization was disabled for a
COLLATEon a matched key. NowTopKParamsowns the collators, the heap compares collated keys withcompareAtWithCollationand keeps keys tied with the boundary, andAggregatingstep v2 serializes each key's locale (plan version 22; older peers get no collated top-K). ACOLLATEkey is ranked only when theORDER BYcovers everyGROUP BYkey, and a collated first key gets no dynamic filter.The gain is memory: the heap keeps the hash table near
LIMITkeys.Performance Comparison (amd_release), master (where the optimization is off) -> this PR, default settings:hits_100m_single(18M distinctURL)GROUP BY URL ORDER BY URL COLLATE 'en' LIMIT 101.93 s and 5.6 GB -> 0.87 s and 43 MB,DESCthe same; 20M unique keys 277 ms and 457 MB -> 76 ms and 9 MB; 1M keys in descending cycles 127 -> 128 ms, 399 MB -> 8 MB.Where it loses: every row of a collated key is compared with the boundary, and a skipped key is not in the table, so a key that keeps repeating while skipped pays a locale comparison each time. 50M rows of 1K keys in cycles: 92 -> 229 ms (arm 63 -> 149 ms), 7 MB either way; 20M rows of 100K keys, 1 thread: 459 -> 672 ms, 12 -> 1 MB.
05407_group_by_top_k_collationchecks every case against off.Workflow [PR]
Sync PR [sync-upstream/pr/126878]