Skip to content

Support COLLATE in the GROUP BY top-K optimization - #126878

Open
groeneai wants to merge 43 commits into
ClickHouse:masterfrom
groeneai:group-by-top-k-collation
Open

groeneai wants to merge 43 commits into
ClickHouse:masterfrom
groeneai:group-by-top-k-collation

Conversation

@groeneai

@groeneai groeneai commented Oct 20, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #126735
Related: #126829

Changelog category (leave one):

  • Performance Improvement

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

The GROUP BY top-K optimization (enable_group_by_top_k_optimization) now also applies when the ORDER BY covers every GROUP BY key and sorts some of them with COLLATE, e.g. GROUP BY s ORDER BY s COLLATE 'en' LIMIT 10.

Description

The optimization was disabled for a COLLATE on a matched key. Now TopKParams owns the collators, the heap compares collated keys with compareAtWithCollation and keeps keys tied with the boundary, and Aggregating step v2 serializes each key's locale (plan version 22; older peers get no collated top-K). A COLLATE key is ranked only when the ORDER BY covers every GROUP BY key, and a collated first key gets no dynamic filter.

The gain is memory: the heap keeps the hash table near LIMIT keys. Performance Comparison (amd_release), master (where the optimization is off) -> this PR, default settings: hits_100m_single (18M distinct URL) GROUP BY URL ORDER BY URL COLLATE 'en' LIMIT 10 1.93 s and 5.6 GB -> 0.87 s and 43 MB, DESC the 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_collation checks every case against off.


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

groeneai and others added 3 commits October 20, 2026 02:07
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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
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.

# Sev Finding Verdict Evidence / action
1 ⚠️ The 4-stream case of 05407 never proves a collated heap starts AGREE, fixed @ 7123faf Unique starters guarantee one started stream; the case asserts pruning
2 💡 The mid-block adaptive freeze leaves a waiting heap waiting instead of giving it up (Aggregator.cpp) DISAGREE While frozen the heap never runs (executeFrozen skips it) and cannot start; a start after a thaw is the intended re-check; with the adaptive freeze fix the split does not freeze a waiting heap
3 ⚠️ The dynamic filter and query condition cache cases could pass with the mechanisms bypassed DISAGREE Mutants turn both red: a tracker without the collator drops á0, á1; a salt without the locale returns B 64 instead of B 896
4 ⚠️ The constants were tuned on top of #126829, not on this tree DISAGREE Tuned for the tree this PR merges into (owner: land after #126829); the description states the base and the merge order

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding.

Session id: cron:clickhouse-review-slot-8:20261020-033800

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? The always-on collated heap was measured slower on fixed data (release, 20M rows, 16 threads: 1e3 keys 42 -> 232 ms); with the start condition every measured point is within 1.10x of off. The start condition itself is deterministic in 05407 (wait_small, wait_repeats, late_start, gave_up).
b Root cause explained? A started collated heap pays one locale comparison per tested row instead of one per group in the final sort; that beats the hash-table work it saves only when rows keep inserting new keys, which the new-key rate of the last block measures.
c Fix matches root cause? The heap waits until its table holds 32768 keys and the last block inserted new keys for at least 99.5% of its rows, re-checked per block, and gives up at the adaptive freeze; constants chosen on an 18-combo release grid.
d Test intent preserved / new tests added? 05407 keeps every earlier case and result row (starter keys make each heap start; 7 earlier mutations still red) and adds start-condition cases; gtest for the step serialization.
e Both directions demonstrated? 12 mutations (ranking, serialization, filter, cache salt, ties, start condition) each turn their assertion red; the tree is green 50/50 randomized; the 4-stream case asserts a started heap (red with the start floor at 1e6 keys).
f Fix is general across code paths? Every executeImpl caller checks the wait; the decision is taken only between blocks; spills re-create a waiting heap; two-level conversion keeps the flag; shards derive the wait from the serialized collators; heaps without a collator are unchanged.
g Fix generalizes across inputs (params/datatypes/wrappers)? Single, composite (collation on the first or second key), prefix, Nullable, LowCardinality keys; ASC/DESC, NULLS FIRST/LAST, ties; 1/2/4 streams, small blocks, spill, remote(); bench over 1e3..12.6M keys, LIMIT 10/100/1000, 1/16/64 threads, sorted input.
h Backward compatible? (maintainer-approved exception only) No setting changes; plan version 21 omits a collated top-K towards older peers; the start condition serializes nothing new.
i Invariants and contracts preserved? A waiting heap leaves the aggregation as without the optimization; a started heap skips only rows strictly worse than K real groups (pre-start keys are never pushed, so never evicted); a heap that never starts gives the adaptive freeze back at the same check as today.

Session id: cron:clickhouse-impl-slot-4:20261019-231000

@clickhouse-gh

clickhouse-gh Bot commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [19b1bbf]

Summary: ❌

job_name test_name status info comment
Performance Comparison (amd_release, master_head, 3/6) FAIL Performance dashboard
topk_aggregation_collate #11 FAIL dashboard
topk_aggregation_collate #9 slower query history
Performance Comparison (arm_release, master_head, 5/8) FAIL Performance dashboard
optimize_trivial_group_by_limit #7 FAIL dashboard
Performance Comparison (arm_release, master_head, 7/8) FAIL Performance dashboard
group_by_limit_dynamic_filter #2 FAIL dashboard
group_by_limit_dynamic_filter #4 FAIL dashboard

AI Review

Summary

The PR enables COLLATE in the GROUP BY top-K heap when all grouping keys are ranked, preserves boundary ties, and serializes the collators with version negotiation. The completed performance run demonstrates substantial memory savings and speedups on high-cardinality inputs. Approval remains blocked by the existing repeated-key regressions and the untracked malformed grouping-set validation issue. Reviewed head: 19b1bbf5585b5b87fb14fe9093f741ece00f3f5f. These concerns already have threads; no duplicate inline findings were posted.

Findings

❌ Blockers

  • Malformed grouping-set plans still reach an out-of-bounds key access. src/Processors/QueryPlan/AggregatingStep.cpp:1692–1731 accepts top-K parameters together with grouping sets. A payload with outer keys [a, b], grouping set [a], only_merge = false, and two ranked columns passes these checks. transformPipeline copies the parameters through cloneWithKeys at line 772 into the one-key aggregation; TopKAggregationHeapBase::initBase then constructs a two-element range from one key-column pointer. A client-supplied QueryPlan can therefore cause an out-of-bounds read and invalid dereference when process_query_plan_packet is enabled. This is a source-based trace of a pre-existing defect, not a local execution. [dismissed by author -- https://github.com/Support COLLATE in the GROUP BY top-K optimization #126878#discussion_r4667204195] The rejection and its test were deliberately removed for a separate PR, but no concrete tracking link was found in the discussion or repository search; the unsafe path remains. Restore the rejection with its malformed-plan test, or link the separate fix/tracking issue as required for a pre-existing defect.

  • Default-enabled collated heaps still impose substantial repeated-key CPU regressions. src/Interpreters/TopKAggregationHeap.cpp:200–203 compares each row under the locale before the hash lookup, while shouldFreeze at lines 133–135 cannot retire a heap with a high skip fraction or at least k lifetime evictions. The completed 095e3114b255 run measures topk_aggregation_collate query 9 at 91.6 → 228.7 ms on AMD and 63.0 → 148.9 ms on ARM, with approximately 7 MB either way. The AMD confidence analysis uses seven samples per version and estimates a 2.31–2.61× ratio; master history is unavailable for this newly added test. Performance evidence. [dismissed by author -- https://github.com/Support COLLATE in the GROUP BY top-K optimization #126878#discussion_r4332631043] Repeat detection was deliberately removed, but repeated skipped keys still pay for ICU on every occurrence, violating the stated requirement that existing queries must not regress.

    The retained-key variant also remains: after a distinct prefix evicts at least k groups, a tail repeating a retained composite key keeps comparing even when it skips nothing, because lifetime evictions prevent freezing. [dismissed by author -- https://github.com/Support COLLATE in the GROUP BY top-K optimization #126878#discussion_r4637672293] The author previously measured approximately 1.93 s enabled versus 0.97 s disabled at 09b7a9f; those are older measurements, while the current source still has the non-retiring path. Removing lookup-first extends this concern beyond serialized composite keys. Bound the repeated-key comparison cost or gate automatic collated ranking where it regresses, while preserving the high-cardinality memory benefit.

Missing context / blind spots
  • ⚠️ The reviewed head's functional, unit, and performance jobs are pending/running in the head CI report. The preceding 095e3114b255 report has 50/50 successful runs of 05407_group_by_top_k_collation in the debug flaky check and eight passing top-K serialization tests. Measurements above belong to that preceding performance run; the retained-key numbers are explicitly older. Completed head results and an off/on retained-key benchmark would close these gaps. No local ClickHouse tests were run in this CI job.
Final Verdict

Status: ❌ 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.

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @nihalzp, could you review this and add the can be tested label so CI runs? The GROUP BY top-K heap now ranks COLLATE keys with compareAtWithCollation (locale per key in Aggregating step v2), and a collated heap starts only once a stream's table holds 32768 keys and its last block inserted at least 99.5% new keys, giving up at the adaptive freeze.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Oct 20, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-aggregation GROUP BY / aggregation framework (hash tables, spilling, external aggregation). label Oct 20, 2026
@thevar1able thevar1able added the can be tested Allows running workflows for external contributors label Oct 20, 2026
@thevar1able thevar1able self-assigned this Oct 20, 2026
Comment thread src/Core/ProtocolDefines.h Resolved
thevar1able and others added 2 commits October 20, 2026 18:37
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]>
@clickhouse-gh

clickhouse-gh Bot commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

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

✅ No significant changes.

Binary sizes

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

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

Object file sizes

55 object files changed (+316.63 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Interpreters/Aggregator.cpp.o 35.10 MiB 35.33 MiB +233.21 KiB (+0.65%)

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

Compile time of recompiled translation units

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

Job report

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]>
Comment thread src/Interpreters/Aggregator.cpp Resolved
…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]>
groeneai and others added 4 commits October 21, 2026 10:44
…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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - f95795f

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
Stateless tests (amd_asan_ubsan, db disk, distributed plan, targeted) / 05407_distributed_plan_exchange_compression_default flaky, not from this PR (the test is not in its diff): it fails with a randomized group_by_two_level_threshold / group_by_two_level_threshold_bytes (the runner's own culprit search names them), the same way on master 8 times and on 26 other PRs since 2026-10-21; the tested merge commit of this run predates the fix #127186 (mine, merged)
Stateless tests (amd_tsan, s3 storage, targeted) / 05407_distributed_plan_exchange_compression_default same failure as the row above, same run #127186 (mine, merged)
Stateless tests (arm_asan_ubsan, targeted) / 05407_distributed_plan_exchange_compression_default same failure as the first row, same run #127186 (mine, merged)
Stateless tests (arm_binary, AsyncInsert, s3 storage, parallel) / 05407_distributed_plan_exchange_compression_default same failure as the first row, same run #127186 (mine, merged)
Mergeable Check, PR praktika rollups of the rows above #127186 (the owner of the rows above)

CIDB has no other FAIL or ERROR row on this head; the Performance Comparison unstable and slower verdicts are on jobs that passed.

Session id: cron:our-pr-ci-monitor:20261022-013033

@thevar1able

Copy link
Copy Markdown
Member

@groeneai no improvements are visible in CI.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Right, and the missing freeze fix is not the only reason. The COLLATE query of topk_aggregation.xml (#8) ran on two heads (each job samples 10 of the test's 35 queries): 1.273 -> 1.298 s on de291d7, 1.154 -> 1.144 s on f6247bb. On the new server AggregationTopKRowsSkipped is 0 and there is no adaptive freeze, so the collated heap never started, while the plain ORDER BY URL ASC query (#7) skips 99.9M of the 100M rows in the same run (0.40 s).

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 default.hits on play, an 8192-row block has 38% distinct URLs at the median and 93.5% at most, so no block can pass. With this PR's CI build on 10M rows of ClickBench hits, the heap does not start with 1 thread, nor with 16 threads and the adaptive aggregator off, while 10M unique keys start it in both. I tuned the 99.5% on uniformly distributed keys only.

I'll measure a started heap on hits, rework the start condition accordingly, and post the numbers here. The freeze fix still waits on your choice for prefix heaps: #126735 (comment)

@groeneai

Copy link
Copy Markdown
Collaborator Author

@thevar1able here are the numbers I promised, and one decision before I change the PR.

Release build on CI's hits_100m_single (one part, 18M distinct URLs), GROUP BY URL ORDER BY URL COLLATE 'en' LIMIT 10, time with the heap on / off (an unchanged arm varies by 0.96-1.03):

Collated heap 1 thread 12 threads, adaptive off 12 threads, defaults
this PR (never starts on hits) 1.00 1.01 1.00
forced start at 32768 keys, this PR's give-up 1.13 0.94 1.01
forced start at 32768 keys, no give-up 0.72 0.63 (5.9 GiB -> 164 MiB) 0.86-0.90
  1. A started heap pays off on hits, but the give-up I added after the cyclic-input and one-key-tail findings stops it. hits is ordered by CounterID, so each stream alternates between stretches of new URLs and stretches that repeat one counter's URLs. The give-up freezes the heap after a run of 0.5 repeating rows per key skipped so far, which is a few hundred rows early on, so the first repeating stretch freezes it. With the start and give-up shares lowered to 0.1, 9 of 12 heaps still freeze (0.86-0.88 at 12 threads, adaptive off), and 1M uniform keys get 1.2x slower at 1 thread.
  2. A give-up loose enough for hits (0.73-0.77) brings back the inputs it exists for: with no freeze after the sample, 3M unique keys followed by one key is 1.84x; with a 1M-row minimum run, 1M descending keys are 2.0x and 100K keys in cycles at 16 threads (adaptive off) are 1.7x. The sampled new-key share, the recent hashes and the run length cannot tell hits from these inputs. The price of the lookup a skip saves can: with the heap off a row costs about 122 ns on hits (long URLs, 18M-key table) against 14-22 ns for short keys in tables of up to 2M keys.
  3. With the defaults, even no give-up stays at 0.86-0.90. Each stream's table reaches the adaptive freeze at 16384 keys before the heap's 32768-key floor, and a heap that skipped rows keeps updateStatistics from caching the repeat-dominated verdict, so every measured run freezes again. A multi-threaded gain in CI needs the freeze fix, which still waits on the prefix-heap question: Support COLLATE in the GROUP BY top-K optimization #126735 (comment)

Options:

  1. Keep the start condition and the give-up as they are, and add a perf query where the heap wins today: 1 thread, 12.6M distinct short keys, about 0.4x on synthetic data. hits does not move.
  2. Make the give-up weigh the lookup a skip saves (key width and table size). That is the cost-aware freeze heuristic you put out of scope on Support COLLATE in the GROUP BY top-K optimization #126735, and it is not built yet. Its bound on hits is the no-give-up row: 0.72 at 1 thread, 0.63 at 12 threads with adaptive off, 0.86-0.90 with the defaults until the freeze fix lands.
  3. Keep COLLATE gated and close this PR.

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?

@thevar1able

thevar1able commented Oct 27, 2026 •

Copy link
Copy Markdown
Member

🕵️ 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:

  1. The COLLATE query wasn't run in CI. perf.py runs only 10 random queries per test unless the test has run_all_queries="1". topk_aggregation.xml has 36 queries, and query Add Dockerfiles for client and server #8 (... ORDER BY URL ASC COLLATE 'en' LIMIT 10) wasn't picked on amd or arm.
  2. With multiple threads the heap always gives up. With more than one stream, enable_adaptive_aggregator is on and freezes at adaptive_aggregator_freeze_threshold = 16384 keys. That is before the 32768-key start threshold, and on that freeze the PR marks the waiting heap frozen. Even a heap that had started would do nothing after the freeze, because executeFrozen never looks at the heap. The 16-thread numbers in the description were measured with the adaptive aggregator off. Support COLLATE in the GROUP BY top-K optimization #126735 is the issue this PR closes, not a freeze fix.
  3. On real data the start gate never passes, even with one thread. The gate needs at least 99.5% new keys in the last block. On hits, split into 65536-row blocks, the share of distinct URL values per block is p50 34%, p90 50%, p99 62%. That share is an upper bound on the new-key share, so only nearly all-unique keys pass.

Changes to make:

  1. Perf tests

    • Remove the COLLATE query from tests/performance/topk_aggregation.xml.
    • Add tests/performance/topk_aggregation_collate.xml with <test run_all_queries="1">.
    • Queries over hits_100m_single, GROUP BY URL:
      • ORDER BY URL ASC COLLATE 'en' LIMIT 10, with default settings;
      • the same with DESC, default settings;
      • the ASC and DESC queries with SETTINGS group_by_top_k_optimization_observation_rows = 0;
      • the ASC query with SETTINGS enable_group_by_top_k_optimization = 0.
    • One all-unique case: SELECT toString(number) AS s, count() FROM numbers_mt(20000000) GROUP BY s ORDER BY s ASC COLLATE 'en' LIMIT 10, with default settings and with enable_group_by_top_k_optimization = 0.
  2. Multi-thread interplay with the adaptive aggregator, in Aggregator::executeOnBlock:

    • Start of each block: if the adaptive producer is learning and the collated heap is neither frozen nor waiting, call adaptive->standDown with a new AdaptiveAggregationProducer::BaselineState::Reason::CollatedTopK. This covers a heap that starts or has started; executeFrozen does not consult the heap, so a started heap must keep the stream off the adaptive path for good.
    • While the heap waits: skip the learning slicer branch (executeImplUntilAdaptiveFreeze) by adding !top_k_waits to its condition. In the between-blocks freeze check, do not call freezeAdaptive while topKHeapWaits holds. This covers both the key-count and the byte thresholds.
    • Start decision, at the first block where the table reaches 32768 keys:
      • If the gate passes, set start_allowed and, if the producer is learning, stand it down with CollatedTopK.
      • If it fails and the producer is learning, set the heap's frozen flag and increment AggregationTopKHeapsFrozen. The adaptive freeze then goes ahead as today, since the table is already over its threshold.
      • Without the adaptive aggregator, keep re-checking after every block as now.
    • Remove the code that marks a waiting heap frozen at the adaptive freeze; the gating above replaces it.
  3. Forcing the heap without a new setting: make group_by_top_k_optimization_observation_rows = 0 also skip the start gate. Add params.top_k->observation_rows != 0 to topKHeapWaits. A zero window then means "never judge the heap": it starts with the first block and never freezes. observation_rows is already serialized, so the Aggregating step format doesn't change. Update the setting's documentation to cover this.

  4. Tests

    • In 05407_group_by_top_k_collation, add a multi-stream case with enable_adaptive_aggregator left at its default, and check in system.query_log ProfileEvents that a collated heap started.
    • Add a case with observation_rows = 0 over repeated keys, which the gate would reject, and check that the heap ran and the result matches the run with the optimization off.
  5. Description

    • Replace the benchmark table with numbers measured with default settings, including enable_adaptive_aggregator.
    • Add hits URL with default settings and with observation_rows = 0, each against enable_group_by_top_k_optimization = 0.
    • Drop "Merge after the adaptive freeze fix".
    • If the forced heap is not faster on URL, say so: then the per-row ICU comparison is the bottleneck, not the start threshold.

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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Resolved the new conflict by merging master in c7e4049. Master added [[nodiscard]] to the TopKAggregationHeap.h declarations this PR changes, so I kept the PR's signatures with the attribute. Master also enabled modernize-use-nodiscard in clang-tidy, which flags hasCollators and ranksUnderCollation, so bd1f986 marks them. The clang-23 debug build, clang-tidy on the touched files, the top-K serialization gtests and 05407_group_by_top_k_collation pass locally.

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 hits_100m_single and repeated-key numbers here with that push. If you'd rather merge it as is, say so and I'll stop.

groeneai and others added 4 commits November 16, 2026 17:51
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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pushed option 1 in 15a9660 to 2603fd1. A collated heap that ranks all GROUP BY keys hashes the keys it skips (a 1/64 sample) and freezes once its skipped rows repeat few keys: at least 32 rows per distinct skipped key, while the sample is under about 262K keys and 4M rows. The bar is 32 because hits streams repeat a key 8 to 48 times early on, and 8 or 16 froze 3 to 8 of the 12 heaps. Sampling one block or one row in four undercounts their rare keys and froze 6 of 12, so every skipped row is hashed.

Release, 20M rows of concat('k', toString(number % N)), COLLATE 'en' LIMIT 10, medians, ms, before -> after (off):

N 1 thread 8 threads default
1K 423 -> 72 (72) 59 -> 14 (12) 21 -> 9 (7)
10K 431 -> 90 (83) 57 -> 22 (14) 20 -> 18 (10)
100K 422 -> 322 (280) 60 -> 72 (61) 21 -> 26 (30)
1M 430 -> 446 (374) 65 -> 63 (77) 22 -> 24 (35)
20M unique 381 -> 393 (2743) 52 -> 55 (226) 21 -> 22 (77)

hits_100m_single URL at defaults: 12 threads 867 -> 873 (1282), 8 threads 1214 -> 1216 (1810), the same with observation_rows = 0. The cost is the hashing before a heap decides, about 5 ns per skipped row, so 100K keys at 8 threads are now 1.2x off. topk_aggregation_collate.xml gets 1K keys at default threads and 100K keys in one thread, each against off, and 05407 checks which heaps freeze.

…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]>
@thevar1able

Copy link
Copy Markdown
Member

@groeneai poke

groeneai and others added 3 commits November 20, 2026 00:14
…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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Merged master in e3976b1 and pushed 09b7a9f. The PR is mergeable again, so CI can run.

The conflicts were master's VectorWithMemoryTracking change of the top-K directions (the collations now use the same type) and the move of applyTopKPushdownToPartialAggregation into PlannerSteps.cpp, where the collation hunk is ported unchanged. Two small commits on top:

  • b25d754: the "Last bumped for release" line in ProtocolDefines.h says 26.12, since master is 26.12 now and this branch bumps the plan version to 22.
  • 09b7a9f: a NOLINT(readability-qualified-auto) on auto it in findKeyImpl. The collated look-up in executeImplBatchNoAggregates now instantiates it for master's new set of fixed-width keys and a String, whose find returns const void *, and clang-tidy flagged it (master's Aggregator.cpp is clean).

Locally: debug build, the top-K gtests and 81 top-K and collation stateless tests pass.

Comment thread src/Interpreters/Aggregator.cpp Resolved
groeneai and others added 3 commits November 20, 2026 03:01
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]>
@thevar1able

Copy link
Copy Markdown
Member

@groeneai The main goal of this change is the memory saving, and the core already delivers it. In the perf run at 1a5e9ec1a9b0, hits URL ... COLLATE 'en' LIMIT 10 dropped from 5.9 GB to 43–64 MB with group_by_top_k_optimization_observation_rows = 0, and the unique-key and descending-cycle cases from 0.6–0.85 GB to 9–13 MB. Faster runtime is a bonus, and existing queries must not regress. Anything beyond that is complication we don't need. Please trim the PR to the core:

Keep

  • TopKParams::collators and the collated compare and trim in the heap, including the boundary tie handling.
  • Aggregating step version 2 serialization (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.
  • The collations in EXPLAIN.

Remove

  • The skipped-key sampling freeze (collated_skip_sample*, sampleCollatedSkip, collatedSkipsRepeat, and the pause/resume logic: commits 15a9660, 8071626, 2603fd1, 3c04834). It trades the memory saving back for CPU, which is the opposite of what we want. It rests on six tuned constants and mutable state written from a const skip check, and perf CI has never measured it.
  • collated_min_trim_slack. It's a CPU tweak that also grows the heap.
  • The look-up-first path in the aggregation loops, unless you can show that without it a collated query is slower than it is today with the optimization off. If so, keep it and say so in the description.
  • The grouping-sets check in AggregatingStep::deserialize (8451624). It's unrelated; please send it as a separate PR.

Also

  • At default settings, hits URL still used 640–890 MB, against 43–64 MB with freezes disabled, because some per-thread heaps freeze. Please check whether the existing observation-window freeze should apply to a collated heap at all, given that memory is the point.
  • Once that's done, the description only needs the memory and time numbers from a fresh perf run; the per-commit benchmark tables can go.

@groeneai

Copy link
Copy Markdown
Collaborator Author

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.

Comment thread src/Interpreters/Aggregator.cpp Resolved
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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Done in 095e3114b255: the sampling freeze, collated_min_trim_slack and the grouping-sets check are gone (that check comes as a separate PR, linked here when it opens). The rest of your keep list is unchanged.

  • Look-up-first: removed. It cost time on hits, and every query that is slower than off without it is slower with it too. Release build, CI's hits_100m_single, medians of 5 or more (1 thread: one run), ms, off / with / without:
    • URL ASC, 12 threads: 1260 / 716 / 606
    • URL ASC, 1 thread: 13005 / 12782 / 6920
    • 50M rows, 1K keys in cycles, 12 threads: 63 / 153 / 121
    • 50M rows, 20 keys in cycles, 12 threads: 51 / 89 / 142
    • 20M rows, 90% of them on 10 kept keys, 12 threads: 61 / 46 / 61 (the one case where it helps)
  • Observation-window freeze: after the trim no heap freezes on hits at default settings with 12, 32 or 64 threads: 61-155 MB, the same as with observation_rows = 0 (off: 5.7-6.2 GB). I could not reproduce the 640-890 MB locally. The freeze still fires when a window's rows mostly hit kept keys. With 11 keys it saves the comparisons (50 vs 135 ms, same memory). If distinct keys follow such a window it costs memory and time (178 ms / 410 MB vs 55 ms / 1 MB), and master does the same without COLLATE. So I left it as it is.
  • Remaining cost: a key that keeps repeating while the heap skips it pays a locale comparison on every row. 1K keys in cycles go from 63 to 121 ms, and 100K keys at 1 thread from 402 to 560 ms. Both are in the perf test, so the new run will show them.

The description is rewritten without the per-commit tables. I'll replace its numbers with the perf run's.

groeneai and others added 2 commits November 24, 2026 23:12
`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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

@thevar1able The perf run on 095e311 has the numbers (amd, master where the optimization is off -> this PR, default settings):

  • hits URL ... COLLATE 'en' LIMIT 10: 1.93 s and 5.6 GB -> 0.87 s and 43 MB, DESC the same. No per-thread heap freezes at default settings any more.
  • 20M unique keys: 277 ms and 457 MB -> 76 ms and 9 MB.

The description now has these numbers.

The same run flagged optimize_trivial_group_by_limit #6 and #7 on arm (String key without COLLATE, 50 -> 59 ms): the loops called shouldSkipTyped out of line on every row. #133805 fixed that on master, and the PR conflicted with it and with #132721, so I merged master (the new Parquet path now also salts its cache key with the locales). 19b1bbf keeps the collated comparison out of the force-inlined shouldSkip, so the loops without COLLATE differ from master by a branch and a cold call.

One decision is yours. topk_aggregation_collate #9 is a confirmed regression: 1K keys in cycles, 92 -> 229 ms (arm 63 -> 149 ms); #11, 100K keys at 1 thread, 459 -> 672 ms. A skipped key that keeps repeating pays a locale comparison on every row, and memory there is small either way (7 MB; 12 -> 1 MB). That is the case the removed sampling freeze handled. Which do you prefer?

  1. Accept it as the cost of the memory saving, and keep both queries in the test.
  2. Remember up to a fixed number of skipped keys per thread (for example 64K) in a small hash set checked before the comparison, so that a repeating skipped key costs a lookup. No freeze, bounded extra memory. Not built yet.

@groeneai

Copy link
Copy Markdown
Collaborator Author

The grouping-sets check is in #134316.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-aggregation GROUP BY / aggregation framework (hash tables, spilling, external aggregation). pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Support COLLATE in the GROUP BY top-K optimization

2 participants