Skip to content

Restore the batched prefetch path for uniq and uniqCombined in GROUP BY - #120578

Merged
nickitat merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-uniq-batch-nonnull-places-120531
Sep 17, 2026
Merged

nickitat merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-uniq-batch-nonnull-places-120531

Conversation

@groeneai

@groeneai groeneai commented Sep 17, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #120531

Changelog category (leave one):

  • Performance Improvement

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

Restored the batched hash-and-prefetch insert path for uniq, uniqCombined and uniqCombined64 in ordinary GROUP BY queries, where they had silently fallen back to a per-row loop and were up to 46% slower. Closes #120531.

Description

a183c7755806e added addBatchUniq (hash a chunk, prefetch the cells, then insert) and wired it into both uniq classes' addBatch.

ace35a5495f43 then added a second entry point, addBatchWithNonNullPlaces, and made Aggregator::addBatch prefer it whenever all_places_are_non_null, which is !top_k, the ordinary GROUP BY. The interface default forwards to addBatch, but IAggregateFunctionHelper overrides that virtual (IAggregateFunction.h:574) with a per-row add() loop, and that is what dispatch resolves to for classes deriving through IAggregateFunctionDataHelper. Neither uniq class overrode it, so addBatchUniq became unreachable there. The two commits crossed without a rebase, so the later branch carried the override only to the four overriders on its base.

This adds the missing override to both, delegating to their existing addBatch. The if constexpr keeps uniqHLL12 and uniqExact on the base's non-null loop, faster for them.

Under gdb the path is not reached on an ordinary GROUP BY before the change and is reached after; a top-k arm shows the probe fires. Magnitude, two binaries from one cmake config differing only by this patch, interleaved, min-of-15, as the extra time master takes over this build:

rows / groups uniq uniqCombined uniqCombined64
8.4M / 512 +23.0% +11.2% +17.9%
33.5M / 512 +34.1% +34.5% +39.4%
67M / 4096 +42.1% +34.2% +46.5%

uniqHLL12, unaffected by design, is the control: at most 1.5%.

No new test: the change is behaviour-preserving, so tests/performance/uniq_multi_place.xml (shipped with a183c7755806e as this guard) is what can distinguish the loops, and should report them as faster here. 05183_uniq_multi_place_prefetch is the correctness oracle, green including 50 randomized runs.

Inverting the Aggregator default so functions opt in would make this omission impossible; I kept the change minimal but can do that instead. 26.9 also contains the dispatch.


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

Version info

  • Merged into: 26.10.1.52 (included in 26.10 and later)

a183c77 added addBatchUniq (hash a 32-row chunk, prefetch the
destination cells, then insert) and wired it into
AggregateFunctionUniq::addBatch, for AggregateFunctionUniqUniquesHashSetData
only, and AggregateFunctionUniqCombined::addBatch.

ace35a5 then added a second batch entry point,
IAggregateFunction::addBatchWithNonNullPlaces, and made Aggregator::addBatch
prefer it whenever all_places_are_non_null, which is set to !top_k, i.e. for
the ordinary GROUP BY. The interface default forwards to addBatch, but
IAggregateFunctionHelper overrides the same virtual at IAggregateFunction.h:574
with its own per-row add() loop, and that override is what dispatch resolves to
for every class deriving through IAggregateFunctionDataHelper. Neither uniq
class overrode it, so their addBatch, and with it addBatchUniq, became
unreachable on the ordinary GROUP BY path.

The two commits crossed without a rebase: a183c77 is an ancestor of
ace35a5 but not of its recorded base, so that branch never saw the two
new overriders. It did carry the companion override to all four overriders that
existed on its base. Of the six addBatch overriders in src/, those four already
have the companion (-If, -OrFill, -Tuple, the timeseries base); these two did
not.

Verified under gdb on two builds that a breakpoint inside addBatchUniq is not
reached on an ordinary GROUP BY before this change and is reached after, with an
ORDER BY ... LIMIT arm that reaches it on both to show the probe can fire.

Measured on two binaries from the same cmake config differing only by this
patch, arms interleaved base/fix three times, 15 samples per shape, min-of-15,
with max_threads=1 and the two-level thresholds and compiled expressions off:

  512 groups,  8.4M rows: uniq +23.0%  uniqCombined +11.2%  uniqCombined64 +17.9%
  512 groups, 33.5M rows: uniq +34.1%  uniqCombined +34.5%  uniqCombined64 +39.4%
  4096 groups,  67M rows: uniq +42.1%  uniqCombined +34.2%  uniqCombined64 +46.5%

uniqHLL12 delegates to the helper on both arms and serves as the control: it
moves at most 1.5%. At 64 groups nothing moves on any function, which is
expected when the states fit in cache and there is nothing to prefetch.

The if constexpr in AggregateFunctionUniq is required. An unconditional
delegation to addBatch would route uniqHLL12 and uniqExact into the helper's
addBatch, which re-tests places[i] per row, and would take the non-null loop
away from them.

No new test: the change is behaviour-preserving, so a functional test cannot
distinguish the two loops. tests/performance/uniq_multi_place.xml, shipped with
a183c77 as this guard, is what can, and 05183_uniq_multi_place_prefetch
is the correctness oracle, green here including 50 runs under randomized
settings.
Restate the if constexpr comment as a bare invariant about the base helper: drop the half that the identical if constexpr in addBatch above already shows, and the relative-speed rationale, which is in the commit message.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Sep 17, 2026
@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): 0 findings, over both changed
headers, the dispatcher, every caller and sibling override, the factories and wrappers, and both
existing tests. The three rows below are from my own cold review, done before reading the
implementation notes. Nothing was found in the diff itself; all three are about this PR's text,
and all were settled before posting.

# Sev Finding Verdict Evidence / action
1 ⚠️ The magnitude table printed bare +23.0% .. +46.5% with no direction. Those figures are (base - fix) / fix, i.e. how much longer the unpatched build takes; the speedup is (base - fix) / base, which is 10 to 32 percent. In a Performance Improvement PR an unlabelled figure reads as the gain and overstates it by up to 15 points. AGREE, fixed before publication The caption now names the direction ("as the extra time master takes over this build"). The changelog entry already had it right ("were up to 46% slower").
2 ⚠️ The validation comment justified excluding Nullable from the census with "arrives via -OrNull/-OrDefault". Both halves are wrong: -OrNull/-OrDefault are the OrFill name-suffix combinator, and a Nullable argument is wrapped by the Null combinator instead. AGREE, fixed before publication Combinators/AggregateFunctionNull.h overrides addBatchSinglePlace, addBatchSparseSinglePlace and addBatchSparse, but neither addBatch nor addBatchWithNonNullPlaces, and neither uniq class customizes getOwnNullAdapter. So a Nullable argument did not reach addBatchUniq before this change either. The census conclusion is unaffected; only the stated reason was wrong, and it is now corrected.
3 💡 std::is_same_v<Data, AggregateFunctionUniqUniquesHashSetData> is now spelled in two adjacent methods; a static constexpr bool member would state it once. AGREE as an observation, not applied Applying it would turn a purely additive diff into one that also rewrites pre-existing lines, for no behaviour change. Noted, not blocking.

Checked and found clean, for the record: the new overrides forward the same arguments to the same
already-live addBatch, so no result can change; addBatchUniq tests places[row] itself, so the
caller's non-null guarantee is strictly weaker than what it already satisfies, and insertion order
inside a chunk stays row order, so serialized states remain byte-identical. I enumerated the batch
entry points independently and reached the same six-overrider census. 05183_uniq_multi_place_prefetch
and tests/performance/uniq_multi_place.xml both use plain GROUP BY, so both exercise the new
path rather than the old one.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding. Findings on hunks unchanged by the fix round are auto-dropped.

Session id: cron:clickhouse-review-slot-48:20260917-111200

@clickhouse-gh clickhouse-gh Bot closed this Sep 17, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 17, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, and not a timing threshold: a gdb breakpoint on UniqBatch.h:35 (362 resolved locations) is deterministically NOT hit on base and IS hit after the change, for the same ordinary GROUP BY. A second arm with ORDER BY k LIMIT 1000 fires on base, proving the probe is capable of firing.
b Root cause explained? Aggregator::addBatch prefers addBatchWithNonNullPlaces when all_places_are_non_null, which is !top_k. The interface default forwards to addBatch, but IAggregateFunctionHelper overrides the same virtual at IAggregateFunction.h:574 with a per-row add() loop, and that override is what dispatch resolves to for every class deriving through IAggregateFunctionDataHelper. Neither uniq class overrode it, so addBatchUniq was dead on the ordinary GROUP BY. Compile-time shadowing, confirmed at runtime by (a).
c Fix matches root cause? Yes: it supplies the missing override at exactly the shadowed virtual. No widened bound, no no-random-* tag, no data reduction, no defensive guard. 17 insertions, 0 deletions, 2 files.
d Test intent preserved / new tests added? No test is modified, so no intent can be lost. No new test on purpose: the change is behaviour-preserving, so a functional test cannot distinguish the two loops. tests/performance/uniq_multi_place.xml (shipped with a183c7755806e as this exact guard) is what can, and should report these queries as faster here. 05183_uniq_multi_place_prefetch is the correctness oracle: green, plus 50/50 under randomized settings. A ProfileEvents counter was rejected per the standing directive in #117841.
e Both directions demonstrated? Twice. Mechanism: not reached on base, reached after (a). Magnitude: min-of-15, arms interleaved base/fix three times, +23.0/+11.2/+17.9% at 512 groups / 8.4M rows, +34.1/+34.5/+39.4% at 512 / 33.5M, +42.1/+34.2/+46.5% at 4096 / 67M for uniq/uniqCombined/uniqCombined64; uniqHLL12 control moves at most 1.5%.
f Fix is general across code paths? Yes, from a complete census rather than a sample: exactly 6 addBatch overriders exist in src/; 4 already carried the companion override (AggregateFunctionIf.h:160, AggregateFunctionOrFill.h:167, AggregateFunctionTuple.h:81, AggregateFunctionTimeseriesBase.h:209) and the 2 bare ones are the 2 fixed here. Excluded after checking: uniqArray and sparse arguments dispatch earlier (addBatchArray / addBatchSparse); a Nullable argument is wrapped by the Null combinator, which overrides neither batch entry point, so it did not reach addBatchUniq before this change either; LowCardinality, Const, Map add no addBatch override; uniqTheta is an IFunction; the single-place entry points have no non-null variant in Aggregator.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes by construction: the override forwards the full argument list unchanged into a path that already handled every input, so it is type-agnostic. if_argument_pos is the one input worth checking and works: AggregateFunctionIf::addBatchWithNonNullPlaces forwards with if_argument_pos = num_arguments - 1, and addBatchUniq honours flags. uniqCombined(K) / uniqCombined64(K) are instantiations of the same class, so every K is covered. 05183 already asserts result and state-byte equality over 7 types, -If, Nullable, both HyperLogLog threshold crossings and interleaved null places.
h Backward compatible? (maintainer-approved exception only) Yes, trivially. No setting, no default change, no serialized format, no aggregate-function state version, so no SettingsChangesHistory.cpp entry is owed. 05183 compares state bytes and passes.
i Invariants and contracts preserved? Yes. addBatchWithNonNullPlaces is contractually a specialization of addBatch for callers that guarantee non-null places, so delegating to addBatch is always sound: it declines to exploit the guarantee, which is the pre-regression state. Nothing is weakened, since addBatchUniq tests places[row] itself and so is correct under both entry points. No lock, allocation, arena ownership or early-return path is added; both classes report allocatesMemoryInArena() == false and the Arena * is forwarded untouched. The one contract needing active protection is uniqHLL12/uniqExact keeping the helper's non-null loop, which the if constexpr enforces.

Session id: cron:clickhouse-impl-slot-40:20260917-092200

@clickhouse-gh

clickhouse-gh Bot commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [4a5c467]

Summary: ✅


AI Review

Summary

This PR restores the intended addBatchWithNonNullPlaces dispatch for AggregateFunctionUniq and AggregateFunctionUniqCombined so ordinary multi-place GROUP BY aggregation reaches the existing batched hash/prefetch path again. I reviewed the changed classes against the Aggregator call site, the IAggregateFunctionHelper shadowing that caused the regression, the sibling wrappers, the existing correctness and performance probes, and the current PR discussion/CI state; I did not find a remaining correctness, safety, coverage, or metadata issue that requires changes.

Final Verdict

Status: ✅ Approve

LLVM Coverage Report

Measured on commit 4a5c467.

Metric Baseline Current Δ
Lines 88.50% 88.40% -0.10%
Functions 91.80% 91.80% +0.00%
Branches 80.70% 80.70% +0.00%

Changed lines: Changed C/C++ lines covered: 6/6 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Sep 17, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-aggregate-functions Aggregate function implementations (sum, avg, count, quantile, combinators, etc.). label Sep 17, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 17, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 4a5c4679f with master f51fa728a (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

11 object files changed (+151.62 KiB total), 0 added.

Object file Master PR Δ
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionUniq.cpp.o 10.88 MiB 10.92 MiB +40.98 KiB (+0.37%)

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

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

Median compile-time ratio to the baselines is ×1.06 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost +4.3 s (+4%) in total before that adjustment.

Job report

@nickitat nickitat self-assigned this Sep 17, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 17, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 38 queries analysed

no significant changes detected. K_source=6 K_base=20 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 44e4beee-5d04-4c0c-8766-60fc1d00ecbd
  • MIRAI run: 787a139b-a455-4307-9312-d422a7b5dfba
  • PR check IDs:
    • clickbench_587040_1789656075
    • clickbench_587054_1789656075
    • clickbench_587060_1789656075
    • tpch_adapted_1_official_587066_1789656075
    • tpch_adapted_1_official_587077_1789656075
    • tpch_adapted_1_official_587110_1789656075

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 4a5c467

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, and on this head it is green.

Check / test Reason Owner / fixing PR
Stress test (amd_debug) / GroupingAggregatedTransform pushed bucket A twice (STID 3994-4c1d) pre-existing trunk logical error, first seen 2026-08-22: 97 rows over 77 PRs and 10 true-master runs in the last 30 days, weeks before this branch existed #119814 (external, open)
Integration tests (amd_msan, 1/8) / test_max_bytes_ratio_before_external_distinct[user] flaky, spreading today: 5 unrelated PRs, 0 true-master runs in 30 days. This diff touches only AggregateFunctionUniq.h and AggregateFunctionUniqCombined.h, which the test never exercises a fix task is created for this test (already in implementation, fixing PR link to follow on this PR)
Mergeable Check, PR praktika rollups of the two rows above, no independent failure #119814 for the stress row, the fix task above for the integration row

Session id: cron:our-pr-ci-monitor:20260917-163222

@nickitat
nickitat enabled auto-merge September 17, 2026 17:32
@nickitat
nickitat added this pull request to the merge queue Sep 17, 2026
Merged via the queue into ClickHouse:master with commit df28fe7 Sep 17, 2026
348 of 523 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 17, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for test_max_bytes_ratio_before_external_distinct[user] created: #120751

yackushevas pushed a commit to yackushevas/ClickHouse that referenced this pull request Nov 15, 2026
The 2048- and 4096-group entries of uniq_multi_place.xml (query indexes
5, 6, 12, 13, 19, 20) take 1.03-2.96 s on MasterCI amd and 1.15-2.58 s
on arm; the three 4096-group ones are above report.py's 2 s single-run
limit. Each group gets 16384 distinct values, so the time is the
groups x 16384 single-threaded state insertions.

No existing query number or text changes: the one query (21 entries) is
disabled, and the same query over 64 to 1024 groups is appended as
21-35, byte-identical to entries 0-4, 7-11 and 14-18.

The batched hash-and-prefetch insert of ClickHouse#119594 that the file measures
already shows at 1024 groups. On the 457 master commits of
2026-09-12..24, with that path (before ClickHouse#117009 or after ClickHouse#120578) and
without it (between the two), 1024 groups keep 95-128% of the
2048/4096-group speedup on amd, and on arm 91-97% of the 2048-group one
and 69-88% of the 4096-group one (bootstrap p5 0.64, arm
uniqCombined64).

About 1 minute less query time per master perf job on each architecture.

Related: ClickHouse#129258

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

can be tested Allows running workflows for external contributors comp-aggregate-functions Aggregate function implementations (sum, avg, count, quantile, combinators, etc.). groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-performance Pull request with some performance improvements 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.

uniq/uniqCombined GROUP BY 18-24% slower: prefetch batch path bypassed

3 participants