Skip to content

Follow-up to radix partitioned uniqExact: spilling and fixes - #127252

Merged
alexey-milovidov merged 11 commits into
ClickHouse:masterfrom
Algunenano:radix-spill-wip
Oct 25, 2026
Merged

alexey-milovidov merged 11 commits into
ClickHouse:masterfrom
Algunenano:radix-spill-wip

Conversation

@Algunenano

@Algunenano Algunenano commented Oct 21, 2026 •

Copy link
Copy Markdown
Member

Follow-up to #123552, cc @nihalzp.

  • Memory limit on unchecked flushes. ~MemoryTrackerSwitcher adds a thread's untracked memory to its trackers without checking limits, and each switched scope restarts the untracked counter, so work split into many short scopes never hit max_memory_usage: the radix path buffered ~30 GiB under a 200 MiB limit. The thread now counts these bytes and checks the limits on its next allocation. query_log.memory_usage now also shows memory used past the limit, which it used to skip.
  • Frequent keys. A few frequent values that aren't consecutive made the radix path keep a copy of every row. A buffer that gets many more keys than its share is now deduplicated on its own, with a scratch set sized for its distinct keys, and the routing skips recently routed keys through a small direct-mapped cache, as it already did for consecutive duplicates. The issue's query takes 49 ms instead of 77 ms (56 ms without radix).
  • Spilling. Keyless uniqExact couldn't spill: without GROUP BY the ordinary aggregation has no two-level form. With max_bytes_before_external_group_by, each stream now writes its deduplicated keys to a temporary file of its own (no locks), in frames that the build reads through TemporaryFileFrameReader. It honors min_bytes_before_external_group_by and aggregation_memory_efficient_merge_threads, and it skips the statistics' preallocation when it has to spill.
  • Statistics with many streams. After Compute a single keyless uniqExact by radix partitioning #123552, ClickBench Q4/Q5 regressed 2–3x on 192-core machines. With many streams, the hint started streams of distinct keys in per-stream sets that only missed the cache, and doubled the bucket count, leaving buffers of a few hundred keys. Streams now start in a set only if their keys repeat at least 8 times, the bucket count leaves at least two pages of keys per buffer, and a hint applies across nearby stream counts, so runs no longer alternate between modes. On a 192-core machine, Q4 is now ~3x faster and Q5 ~2x faster than before Compute a single keyless uniqExact by radix partitioning #123552.

Closes: #127020
Related: #123552

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

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

Version info

  • Merged into: 26.11.1.777-master (included in 26.11 and later)

Algunenano and others added 5 commits October 21, 2026 17:23
`flushUntrackedMemory` adds the untracked memory of a thread to its trackers without checking the limits, because it
runs in destructors such as `~MemoryTrackerSwitcher`. A switcher also resets the untracked memory of the thread when it
starts, so work done in many short switched scopes, each allocating less than `max_untracked_memory`, never reached a
limit check. The radix partitioned `uniqExact` routes every block in such a scope, and a query with
`max_memory_usage = '200Mi'` buffered about 30 GiB before a single 16 GiB allocation was refused.

The thread now counts the bytes flushed without a check, and once they exceed `untracked_memory_limit`, its next
allocation checks the limits. The counter stays pending while the limit of the query cannot be checked: in the scope of
a blocker of the memory tracker or of a lock of the memory exceptions, or when the thread is switched to a tracker that
does not reach its query, such as the server tracker of a connection pool.

The peak of a tracker was not updated by allocations that exceeded the limit without a check, so
`query_log.memory_usage` did not show the memory used past the limit. It was skipped because the size of the tracker may
include the allocations being refused at the same time. These are now counted while they are refused, and the peak of
such an allocation is the size of the tracker without them, read at its commit.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…uffers of frequent keys

A few frequent values that are not consecutive made the radix partitioned `uniqExact` keep a copy of every row: the
deduplication of a stream decides by the median of a sample of buffers, which ignores the buffers of these values. A
buffer that receives many more keys than its share is now deduplicated on its own, and the scratch set of a
deduplication no longer allocates for all the buffered keys.

With `max_bytes_before_external_group_by` (or its ratio), the same settings as the ordinary aggregation, a stream whose
state exceeds the threshold drops the repeated keys of its buffers and writes them to a temporary file of its own, in
uncompressed frames of the keys of one bucket, so that spills take no lock. A stream spills only once it holds at least
`min_bytes_before_external_group_by`. The build of a bucket reads its frames from the files of all the streams through
`TemporaryFileFrameReader`, as the set of `IN` on disk does, and deduplicates the parts of a spilled bucket as they
grow, because the spills write the same keys again. The builds run in `aggregation_memory_efficient_merge_threads`
threads, and the sets of the statistics of hash tables are not preallocated when the query has to spill. The ordinary
aggregation never spills this query, because without `GROUP BY` it has no two-level form.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A few frequent keys that alternate, such as `number % 3`, are never consecutive, so the skip of consecutive duplicates
does not see them, and each of their copies was routed and deduplicated later. When consecutive duplicates are rare, the
routing now looks for each key in a direct-mapped cache of the recent keys and skips it if it is there, while this skips
at least a quarter of the keys. String keys use their 128-bit hash, so they are compared as fixed-size values.

The scratch set of the deduplication of a hot buffer now starts at its known distinct keys: one sized for all its keys
was cleared and probed out of the cache at each deduplication.

On the frequent keys of 40 million rows with 2 threads, the query takes 49 ms instead of 77 ms, and 56 ms without the
radix partitioning.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…keys were repeated

With the statistics of hash tables, a stream started in a set if most streams of the previous run ended in a set, or if
the set of its distinct keys fit into `MAX_UNBOUNDED_SET_BYTES`. With many streams, each one has few distinct keys, so
streams of keys that are not repeated, such as `UserID` with 192 threads, started in sets that only cost inserts that
miss the cache, ended in them, and kept the next runs in sets too: `count(DISTINCT UserID)` on `hits` took 2-3 times
longer on machines with 192 cores.

A stream now starts in a set by the same rule as the switch during the routing: its keys were mostly repeated and the
set fits. Otherwise it starts in the bounded set if its distinct keys fit there, and routes them if not. Whether the
streams ended in a set is no longer recorded.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ns and stream counts

With the statistics, the number of buckets made each bucket set fit into half of the L2 cache, whatever the number of
streams. With many streams, the buffer of each stream then held a few hundred keys, and the build walked many tiny
scattered buffers and missed the TLB: `count(DISTINCT WatchID)` with 111 streams took 4096 buckets and was about 25%
slower than without the statistics. The number of buckets is now capped so that the buffer of a stream holds at least
two pages of keys, so 111 streams take 2048 buckets and 16 streams still take 4096.

A stream started in its set when the keys routed since the start were mostly repeated, by the bound of the switch during
the routing. The distinct keys of a stream are estimated from a sample, so a stream near the bound, such as `EventTime`
with 64 streams, moved between the set and the routing from run to run, twice as slow in the set. A stream now starts in
its set only if each of its keys was routed at least 8 times.

The number of streams of a source varies between the runs, e.g. from 88 to 90 for 192 threads, and a hint applied only
to the same number, so the runs alternated between two modes. A hint now applies with up to twice or half as many
streams, with the numbers of a stream scaled to them, and the statistics are updated only when the number of streams
changes as much.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [e26e860]

Summary: ✅


AI Review

Summary

This PR adds disk spilling for radix uniqExact and fixes memory-limit enforcement, buffering of frequent keys, and statistics reuse. The current revision addresses the previous findings; no new actionable findings remain.

Final Verdict

Status: ✅ Approve.

@clickhouse-gh clickhouse-gh Bot added pr-not-for-changelog This PR should not be mentioned in the changelog comp-aggregation GROUP BY / aggregation framework (hash tables, spilling, external aggregation). labels Oct 21, 2026
…xact`

The fast tests limit `max_rows_to_read` to 20 million rows. Each test still fails without its fix with these inputs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The query can be stopped by the very allocation that crosses the limit, so its peak stays below the
limit (Fast test: `would use 32.20 MiB`, peak 31.71 MiB). The test still fails without the fix: the
query succeeds instead of exceeding the limit.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=127252&sha=958d57c55518a56d79b03bd23c0f59644bd46114&name_0=PR&name_1=Fast%20test
ClickHouse#127252

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing e26e8608a with master 58077c99f (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

47 object files changed (+120.89 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/Transforms/RadixUniqExactTransform.cpp.o 322.09 KiB 441.07 KiB +118.99 KiB (+36.94%)

719 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

478 translation units recompiled, 4037 s compile time in total, 477 of them have a recent master baseline.

Translation units without a recent master baseline:

  • programs/keeper/Keeper.cpp (clickhouse-keeper): 7.4 s

Job report

Algunenano and others added 2 commits October 22, 2026 17:23
…e keys in the spill checks

A stream in `BoundedSet` never spilled, so many streams with sets below the cutoff exceeded the memory limit. A stream
that `spill` skipped because its arena was half free checked again only once the arena grew, and the arena is half free
right after every growth, so it never spilled. The checks now follow the buffered keys.

The preallocation guard compares the rounded sets of the streams that start in `UnboundedSet` with the threshold, and a
stream does not switch to `UnboundedSet` when the set would cross the threshold. A stream converted from a set by `spill`
always writes its keys.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… of skipping a spill

After a deduplication, the keys of a bucket fit into its smaller blocks, and the blocks it outgrew stay free: a stream
held 1.6 MB of keys in an arena of 5.2 MB, and `spill` skipped it because half of the arena was free, so the state
stayed over the threshold. Such a stream now moves its keys to a new arena, if that brings the state under the
threshold, and writes them otherwise. The spill check starts again from the keys left after the move, as after a write.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Algunenano and others added 2 commits October 22, 2026 23:29
The spills compared `max_bytes_before_external_group_by` with the memory of the state only, so the memory of the rest
of the query was not seen: with large blocks, `05450_radix_uniq_exact_spill_rounded_size_hint` used 44 MiB for a
threshold of 25 MiB, and a hash join holding 19 MiB made the query exceed its limit before the first spill. As in
`Aggregator`, the spills, the switch to the unbounded set and the move to a new arena now compare the threshold with
the memory of the query. The minimum memory of a stream before it spills is still its own.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The streams check the threshold once per block, so when all of them run at once the query goes over it by up to a
block and an arena chunk per stream: the test failed once at its limit of 44 MiB, after five streams spilled within a
millisecond, while its peaks were usually 37 MiB in CI. With 131073 distinct keys, rounding makes the sets of the
streams twice their keys (32 MiB instead of 16), so the threshold and the limit are further apart: the old guard keeps
the hint below the threshold of 17 MiB and fails at the start under the limit of 31 MiB, while the fix peaks at
25 MiB. Small blocks keep the memory of the rest of the query small.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov pushed a commit to RinChanNOWWW/ClickHouse that referenced this pull request Oct 30, 2026
…ache

With temporary data in the distributed cache the test still exceeds its
32Mi limit after ClickHouse#127837 raised it from 24Mi. That peak cannot be
measured in public CI, so another raise would be a guess, and the limit
must stay below the peak of the code before ClickHouse#127252 for the test to keep
catching it. Spilling radix uniqExact to the distributed cache stays
covered by the untagged tests 05443, 05444, 05445, 05450 and 05451.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-aggregation GROUP BY / aggregation framework (hash tables, spilling, external aggregation). pr-not-for-changelog This PR should not be mentioned in the changelog pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Radix uniqExact keeps every copy of hot values, memory grows with rows

3 participants