Skip to content

Skip missed rows that repeat the previous row in the adaptive aggregator's frozen loop when the aggregates ignore repeated values - #131793

Draft
groeneai wants to merge 8 commits into
ClickHouse:masterfrom
groeneai:adaptive-aggregator-skip-repeated-misses
Draft

groeneai wants to merge 8 commits into
ClickHouse:masterfrom
groeneai:adaptive-aggregator-skip-repeated-misses

Conversation

@groeneai

@groeneai groeneai commented Nov 15, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #131738
Related: #127940
Related: #130269

Changelog category (leave one):

  • Performance Improvement

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

GROUP BY with uniq, uniqExact (COUNT(DISTINCT)), uniqHLL12, uniqTheta, groupUniqArray, and uniqUpTo, min and max of anything but one floating-point argument (also with -If) is faster and uses less memory when consecutive rows repeat the key and the arguments, as in data stored in an order correlated with them: the adaptive aggregator no longer stages such a row. SELECT ClientIP, uniq(UserID) FROM hits GROUP BY ClientIP is 1.4x faster with 4 threads and uses 72% less memory.

Description

Once a thread's adaptive hash table freezes, each row whose key misses it is staged as a record with its arguments and looked up at the merge. A row with the keys and arguments of the previous missed row adds nothing when every aggregate function ignores repeated values (IAggregateFunction::ignoresRepeatedValues, #127940). ClickBench hits is stored by (CounterID, EventDate, UserID, ...), so GROUP BY ClientIP with uniq(UserID) staged 99.2M of its 100M rows; now 23.0M.

The argument-record loop now compares such a miss with the previous row (bytes of fixed-width columns, String contents; any other column, an ineligible function or the top-K pruning keeps the old loop) and does not stage it:

  • a block stops comparing when under half of its first 256 comparisons find a repeat, or under 32 comparisons were made by its 256th staged row;
  • a skipped row still counts in the thaw evidence as the record it repeats, with that record's bytes, so thaw decisions are unchanged;
  • uniqUpTo gets the property, except with one floating-point argument (each NaN counts), and -If forwards it. Keyless uniqUpTo of a LowCardinality(String) or LowCardinality(FixedString) argument therefore now adds each used dictionary value once.

#130269 folds more misses for min/max; the two compose.

Validation: a new test compares every case with enable_adaptive_aggregator = 0 and checks the skip and thaw parity. Xeon 6975P-C, release builds, 5 paired rounds, 4 threads, ratio = PR / master [95% CI]: uniq 0.71 [0.68, 0.75] (1292 -> 357 MB), uniqExact 0.75, uniqUpTo 0.74 to 0.82, uniqExact(UserID, SearchPhrase) 0.74, max 0.82, groupUniqArray 0.69, uniqIf 0.75; 16 threads, 3 rounds: uniq 0.70, uniqExact 0.74. Controls (ineligible functions, non-repeating data, a key-ordered table): 0.89 to 1.12, every interval contains 1. Results identical. The CI queries are the ClientIP rows of uniq.xml. Analysis and patch: #131738.


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

groeneai and others added 2 commits November 15, 2026 12:38
…tor's frozen loop

Once a thread's adaptive hash table is frozen, the argument-record loop of
`executeFrozenImpl` staged every row whose key missed it. A row with the keys
and arguments of the missed row before it cannot change a state when every
aggregate function ignores repeated values (`ignoresRepeatedValues`): the
previous row's record reaches the same state with the same values. On
ClickBench `hits`, stored by (CounterID, EventDate, UserID, ...),
`GROUP BY ClientIP` with `uniq(UserID)` staged 99.2M of its 100M rows; now
23.0M.

Such a row is now compared with the previous one (raw bytes of fixed-width
columns, contents of `String` columns; any other column, an ineligible
function or the top-K pruning keeps the old loop) and is not staged:
- a block stops comparing when under half of its first 256 comparisons find
  a repeat, or when under 32 comparisons were made by its 256th staged row
  (the 256-row/50% rule of the grouped `uniqExact` repeat skip); the rest of
  the block runs the old loop;
- a skipped row still counts in `frozen.staged_records/staged_bytes` as the
  record it repeats, with that record's bytes, so `adaptiveStagingRepeats`
  sees what it saw before (without this, key-ordered data never thaws and
  gets 1.27-1.46x slower, per ClickHouse#131738; at the batch's mean cost, long
  repeated `String` values lost master's thaw);
- `uniqUpTo` gets the property, except with one floating-point argument
  (its state compares values with `==`, so each NaN counts); `-If` forwards
  it, the condition being one of the compared arguments. Keyless `uniqUpTo`
  of a `LowCardinality(String)` or `LowCardinality(FixedString)` argument
  therefore now adds each used dictionary value once, which is exact by the
  same idempotence.

`chassert(scratch)` before the scratch copy in `appendDelayedRecords` states
an invariant the static analyzer cannot derive (a value serialized into the
scratch implies the scratch was set); without it clang-analyzer reports a
null `memcpy` source on an infeasible path of the larger `executeFrozenImpl`.

Xeon 6975P-C, release builds (None, no LTO), server pinned to one NUMA node,
5 paired rounds, 4 threads, ratio = PR / master [95% CI]:
  uniq(UserID) by ClientIP              0.711 [0.679, 0.745]  1292 -> 357 MB
  uniqExact(UserID)                     0.752 [0.705, 0.803]
  uniqUpTo(3) / uniqUpTo(100)           0.820 / 0.737
  uniqExact(UserID, SearchPhrase)       0.738 [0.592, 0.920]
  max(UserID)                           0.822
  length(groupUniqArray(UserID))        0.690
  uniqIf(UserID, IsRefresh = 0)         0.753 [0.576, 0.984]
  controls (uniqCombined, sum, top-K, keys or arguments that never repeat,
  key-ordered table)                    0.893 .. 1.124, every CI contains 1
16 threads, 3 rounds: uniq 0.698, uniqExact 0.737, uniqExact(2 args) 0.697,
controls 1.029 .. 1.074. Thaw counts identical in every query; results
identical to master and to `enable_adaptive_aggregator = 0`; stripped
binary +172 KiB.

The analysis and the patch are from ClickHouse#131738.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Delete the comments that restate the new helpers' names and shorten two design comments to one line each.

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; 7 findings over 3 runs) plus my own review.

# Sev Finding Verdict Evidence / action
1 ⚠️ The keyless LowCardinality side effect applies only to String/FixedString dictionaries AGREE description narrowed
2 ⚠️ The keyless LowCardinality line checks results, not that the dictionary path ran DISAGREE no speed-up is claimed for it; same results-only check as the path's own test 05453; the path has no ProfileEvent
3 💡 The changelog lists uniqUpTo without the single floating-point argument exclusion AGREE entry qualified
4 ⚠️ Skipped String rows were charged the batch's mean record cost, so long repeated values lost master's thaw (measured 1.13x-1.19x slower) AGREE fixed: a skipped row is charged as the record it repeats; master's and this PR's thaw counts overlap on all 128 sweep configs; new String thaw cell
5 💡 The 2-byte, 4-byte and wide fixed-width comparisons were not exercised AGREE fixed: UInt16, UInt32, FixedString(16) cells
6 💡 The thaw trace line reports the skipped repeats as staged records AGREE noted, not blocking: trace only, the values are the thaw evidence; ProfileEvents count real records
7 💡 No test reaches a repeat right after a mid-block staging of a serialized-key batch AGREE noted, not blocking: results are identical either way; only serialized keys that are not batch-serialized (for example over 128 bytes per row on x86) reach it

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

Session id: cron:clickhouse-review-slot-8:20261115-124300

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes: the new test's liveness line is 1 1 0 on master (20/20 randomized runs) and 1 1 1 with the change; SELECT ClientIP, uniq(UserID) FROM hits GROUP BY ClientIP runs at 0.71x.
b Root cause explained? The frozen argument-record loop staged every miss, including a row whose keys and arguments equal the previous missed row's, which cannot change a state that ignores repeated values.
c Fix matches root cause? Yes: such a row is no longer turned into a record; nothing is tuned or widened.
d Test intent preserved / new tests added? New test compares every case with enable_adaptive_aggregator = 0 and checks the skip, the float uniqUpTo exclusion, -If, String, keyless LowCardinality and thaw parity; eleven mutations each turn a line.
e Both directions demonstrated? Master fails only on the liveness line, the change passes (also 50/50 randomized runs); release A/B over 5 paired rounds.
f Fix is general across code paths? Both callers of the argument-record loop (bypassed probe and places path) use it; the constant-key, lone count() and top-K paths are unchanged by design.
g Fix generalizes across inputs (params/datatypes/wrappers)? Fixed-width columns compare by bytes, String by contents; Nullable, LowCardinality, sparse and nested columns keep the old loop; a differential type matrix (incl. NaN, signed zeros) matches the ordinary aggregation.
h Backward compatible? (maintainer-approved exception only) Yes: no setting, format or protocol change; results identical.
i Invariants and contracts preserved? A skipped row is not applied and counts in the thaw evidence as the record it repeats, so master's and the change's thaw counts overlap on all 128 sweep configs.

Session id: cron:clickhouse-impl-slot-6:20261115-061000

@clickhouse-gh

clickhouse-gh Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [953c4b0]

Summary: ✅


AI Review

Summary

Reviewed #131793 at 953c4b0cd3bd5e425e31cd449c3545774e52bc31. The change skips consecutive identical missed rows for aggregates that ignore repeated values, preserves thaw accounting, and extends the property to eligible uniqUpTo variants and the -If combinator. No actionable findings remain. The supplied paired benchmarks support the performance claim, and 05770_adaptive_aggregator_repeated_rows passes in Fast test on this head.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements can be tested Allows running workflows for external contributors comp-aggregation GROUP BY / aggregation framework (hash tables, spilling, external aggregation). labels Nov 15, 2026
@nihalzp nihalzp self-assigned this Nov 15, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 953c4b0cd with master 80806f2a4 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

⚠️ Significant changes: object file sizes.

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 ⚠️

7 object files changed (+341.47 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Interpreters/AdaptiveAggregation/Producer.cpp.o 2.78 MiB 3.09 MiB +324.02 KiB (+11.39%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionUniqUpTo.cpp.o 1.31 MiB 1.33 MiB +16.57 KiB (+1.23%)

711 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

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 20e68b0

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
AST fuzzer (amd_release, oracle) / OOM in dmesg OOM, not from this PR: the server was killed by the container's memory cgroup on the fuzzed SELECT DISTINCT toFixedString(..., 1048577) FROM clusterAllReplicas(..., system.text_log) ... LIMIT -2147483648, whose query memory reached 28.56 GiB within about 12 ms with no limit refusal. The query has no GROUP BY and no aggregate function, so the adaptive aggregator this PR changes is not involved a fix task is created (investigating at full effort, fixing-PR link to follow here)
Mergeable Check, PR praktika rollups of the row above a fix task is created (same as above)

CIDB has no other FAIL or ERROR row on this head (the Config Workflow / Pre Hooks rows are the runs before the can be tested label).

Session id: cron:our-pr-ci-monitor:20261115-170017

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for AST fuzzer (amd_release, oracle) / OOM in dmesg created: #131870

@nihalzp

nihalzp commented Nov 17, 2026

Copy link
Copy Markdown
Member

@groeneai Fix conflicts.

groeneai and others added 2 commits November 17, 2026 04:11
…-skip-repeated-misses

Resolve the conflict in AdaptiveAggregationImpl.h: keep master's [[nodiscard]]
on the batch getters and add it to the new getRepeatedRecords().

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Master enabled modernize-use-nodiscard, which marks these const overrides,
the same as the other overrides in AggregateFunctionUniqUpTo.cpp.

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

Copy link
Copy Markdown
Collaborator Author

Merged master in 50ca8a5. The only conflict was in AdaptiveAggregationImpl.h: master's modernize-use-nodiscard change touched the getters next to the new getRepeatedRecords(), which now gets [[nodiscard]] too. e288559 adds it to the two new uniqUpTo ignoresRepeatedValues overrides, which that check now requires. On the merged debug build, 05770 and the adaptive aggregator tests pass, and clang-tidy is clean on the touched files.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - e288559

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
Build profile diff infra, not from this PR (no ci/ file in the diff): all 8 readiness probes to the CI logs cluster hit Read timed out. (read timeout=3), so has_pr_data raised LogClusterNotReady: the endpoint never became ready. The same job errored on 49 PRs in the last 24 hours #129675 (mine, open)
PR praktika rollup of the row above #129675 (mine, open)

All five Stateless tests (*, flaky check) jobs passed. Mergeable Check and CH Inc sync are green.

Session id: cron:our-pr-ci-monitor:20261117-073017

groeneai and others added 3 commits November 18, 2026 15:03
…-skip-repeated-misses

# Conflicts:
#	src/Interpreters/AdaptiveAggregation/Producer.cpp
…String keys

The merge of master brought ClickHouse#129180's shortcut into the frozen loop of argument records: a key of fixed-width values
and an empty String that repeats the last missed key is staged with that key's hash, without being hashed or probed.
The shortcut staged the row before the repeat check, so with the `keysN_packed_string` methods the repeats of such a
key were staged even when every aggregate ignores repeated values.

The repeat check is now a lambda that both paths call. A row on the shortcut takes the last missed key's hash, so the
check compares it with the previous row exactly as on the probed path.

The test gains a `GROUP BY k, e` case whose String key is empty in the first half of each key: results equal
`enable_adaptive_aggregator = 0`, and it stages less than half the records of a `sum` query. Measured on the debug
build: 40768 staged records with the change, 120736 without it, 200704 for `sum`; the binary without the change fails
only that check (`1 0`).

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

# Conflicts:
#	src/Interpreters/AdaptiveAggregation/Producer.cpp
@groeneai

Copy link
Copy Markdown
Collaborator Author

Merged master again in d7b8bdd and 301efba. The conflicts were in the frozen argument-record loop, with #129180 and #131551; the loop now returns AdaptiveLocalProbes as on master.

e0f528a also applies the repeat skip to the empty-string shortcut of #129180, which otherwise staged every repeat of a key of fixed-width values and an empty String. A new GROUP BY k, e case in the test checks it: 40768 staged records with the change, 120736 without, results equal to enable_adaptive_aggregator = 0.

…stable

The case read 500000 rows in 8192-row blocks, so each producer reached its
first thaw check with about 8 sampled keys behind its distinct-key estimate,
and the true repeat factor (32) sits close to the thaw bound.
Under CPU contention all four producers could miss it: `Stateless tests
(amd_debug, flaky check)` failed 1 of 50 with `1 0`. The same noise let the
mean-cost accounting mutant thaw in 40% of runs, so the case caught it only
part of the time.

With 2000000 rows in 65536-row blocks, measured on a debug build (4 threads,
server pinned to 2-4 CPUs, 12-16 queries at once, part of the runs with the
failing CI run's settings):
- this PR: at least 3 of 4 producers thaw in 600/600 runs (old case: only 1
  of 4 in 48/600);
- master (no skip): at least 2 of 4 in 300/300;
- mean-cost mutant: no producer thaws in 400/400 (old case: 81/200 thawed).

Whole test: 300/300 with random settings; 60/60 red on the mean-cost mutant
(this line only); 30/30 red on the mutant that drops the skipped rows from the
evidence (both thaw lines). Wall time 0.65 s without random settings.

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

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

2 participants