Skip to content

Modularize the adaptive aggregation, weigh its thaw by staged bytes, and add the freeze-bytes and bucket-top-K settings - #115480

Closed
nihalzp wants to merge 24 commits into
ClickHouse:masterfrom
nihalzp:refactor-adaptive-aggregator
Closed

nihalzp wants to merge 24 commits into
ClickHouse:masterfrom
nihalzp:refactor-adaptive-aggregator

Conversation

@nihalzp

@nihalzp nihalzp commented Aug 19, 2026 •

Copy link
Copy Markdown
Member

Related: #111459

Restructuring of the adaptive aggregation, plus one behavioral improvement the new structure enabled and two new settings.

Refactoring (no behavior change)

  • The block-to-staged-chunk conversion is a separate component: StagedChunkBuilder in AdaptiveAggregationStaging.{h,cpp} owns the recorded misses, the counting sort into bucket slices, the count dedup, and the seal coalescing, and emits through an IStagedChunkSink. The builder knows nothing about the aggregator, so a future consumer of bucket-grouped records (e.g. a grace-style join) can reuse the representation without pulling in the aggregation machinery.
  • Staged chunks travel as pipeline data instead of side-channel state: each producing AggregatingTransform emits sealed chunks through its output port, and a new AdaptiveAggregationMergeTransform (its own processor files) absorbs them as the backlogs' only writer, uses the closed producer ports as the finish barrier, and assembles the merge. The flow is now visible in EXPLAIN PIPELINE and pinned by a test.
  • The drain side mirrors the build side: StagedChunkDrainer (merge-time and pressure-time consumption, bucket retirement) consumes chunks through a StagedSliceApplier — a narrow inline contract (create states, apply instructions to a contiguous slice) that is the drain's entire dependency on the aggregator.
  • The adaptation decisions are rule objects that own their state and constants: LearningState::decide (freeze / give-up), FrozenState::recordProbeSample (probe bypass), ThawSampler (the global thaw). Aggregator::executeOnBlock shrinks to phase hooks; adding an adaptation no longer grows the kernels.
  • One entity per file: AdaptiveAggregationSession.{h,cpp}, AdaptiveAggregationProducer.h, AdaptiveAggregationDrain.{h,cpp}, the processor files, and an updated architecture comment describing the pipeline topology.

Behavioral change: the thaw verdict is weighted by bytes

The thaw previously fired on the staged stream's repeat factor alone (> 12). That misses streams that repeat keys only a few times but drag wide payloads with every staged record. The verdict is now wasted staged bytes per distinct key: (repeat factor − 1) × bytes per record > 300 — a key's first record is the price of storing-it-once; every repeat is bytes the baseline would have absorbed as an in-place update. Near-unique streams measure ~0 by construction and cannot fire; light count records tolerate high repeats; heavy-column streams stand down early in proportion to the damage. Renamed the verdict vocabulary accordingly (adaptive_staging_wasteful, WastefulStagedStream).

Measured on hits (100M) (off → on, 16/64 threads):

  • SELECT URL, min(Title) GROUP BY URL (90-byte string key): 0.83×/0.73× → 0.99×/1.01×
  • SELECT UserID, min(URL) GROUP BY UserID (heavy argument, +121% peak RSS before): 0.83×/0.59× → 0.97×/1.00×, peak RSS 14.5 → 6.3 GB (matching the ordinary path)

New settings

  • adaptive_aggregator_freeze_threshold_bytes (default 4 MiB): the byte twin of the key-count freeze threshold — a thread's local table freezes at whichever bound is reached first. Measured as the local table's own allocated bytes (hash-table buffer plus arenas), checked between blocks like the baseline's conversion thresholds; deliberately not the query-wide tracked memory, which would freeze all the locals off each other's growth. At the default it is a guardrail: calibration on the heaviest shapes shows ordinary tables keep freezing by key count (e.g. WatchID, min(URL): 14 of 16 locals unchanged, two freeze earlier by bytes, at 15582 and 8192 keys), and a full ClickBench GROUP BY sweep of default vs 0 is noise (geomeans 1.001 / 1.007 at 16 / 64 threads).
  • query_plan_aggregation_bucket_top_k (default true): a dedicated toggle for the bucket top-K conversion. The contract is worded generally (ORDER BY over the aggregation's outputs with LIMIT n, gated on provable exactness) so the planned generalization beyond the lone count() and a single sort column extends the rule, not the setting.

Changelog category (leave one):

  • Improvement

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

The adaptive GROUP BY aggregation (enable_adaptive_aggregator) now measures whether deferring rare keys pays off and returns to the ordinary algorithm when their keys or aggregate arguments are too wide to copy profitably, so aggregations over heavy string columns (e.g. min(URL) per user) run at the ordinary algorithm's speed and memory. Adds adaptive_aggregator_freeze_threshold_bytes to bound each thread's frozen table in bytes (whichever of it and the key-count threshold is reached first freezes the table), and query_plan_aggregation_bucket_top_k to toggle the top-N aggregation optimization.


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

@clickhouse-gh

clickhouse-gh Bot commented Aug 19, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [d6c67d7]

Summary: ❌

job_name test_name status info comment
Stress test (arm_tsan) FAIL
Logical error: No host found for exchange stream A (STID: 3994-5da6) FAIL cidb
AST fuzzer (amd_tsan) ERROR

AI Review

Summary

This PR modularizes adaptive aggregation, adds the byte-based freeze/thaw behavior, and introduces the query_plan_aggregation_bucket_top_k toggle. The refactor itself is coherent, but I do not think it is merge-ready yet: the new adaptive-bytes setting is versioned as if older query-plan version-9 peers already knew its setting name, and the new thaw/performance claims are still under-proven by the tests and CI evidence attached to this PR.

Findings
❌ Blockers
  • [src/Processors/QueryPlan/AggregatingStep.cpp:1141] adaptive_aggregator_freeze_threshold_bytes is serialized under the old adaptive-aggregator gate even though DBMS_QUERY_PLAN_SERIALIZATION_VERSION stays 9. Pre-PR servers also advertise version 9, but their strict QueryPlanSerializationSettings schema does not know this new name, so mixed-version distributed or parallel-replica queries can start throwing during readBinary instead of falling back to the pre-byte-threshold behavior. Bump the query-plan serialization version and gate the new setting on that new version before writing it.
Tests
  • ⚠️ [tests/performance/adaptive_aggregation_heavy_payload.xml:2] The new bytes-weighted thaw contract still lacks a focused regression test. 04654_adaptive_aggregator_profile_events.sh already proves that adaptive aggregation can thaw on a repeat-dominated stream; what changed here is that a heavy staged payload should thaw while a light control with the same repeat shape should not. Please add a small functional test that checks AdaptiveAggregationThaws (or an equivalent observable effect) for both sides of that distinction.
  • ⚠️ [tests/performance/adaptive_aggregation_heavy_payload.xml:9] The PR body claims 0.83x/0.59x -> 0.97x/1.00x runtime improvements and 14.5 -> 6.3 GB memory improvement, but the PR's Performance Comparison (amd_release, master_head, 1/6) through 6/6 checks are all skipped because the PR only has the pr-improvement label, and this SQL perf benchmark records client_time only, not RSS or peak_memory_usage. Please attach the manual artifact that produced those numbers or run a perf/memory path that actually measures the claimed RSS drop.
Final Verdict

Changes requested.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.90% 86.90% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 79.20% 79.30% +0.10%

Changed lines: Changed C/C++ lines covered: 989/1276 (77.51%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Aug 19, 2026
@@ -0,0 +1,14 @@
<test>
<!-- The heavy-payload shapes of the adaptive aggregation: aggregations whose staged

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

04654_adaptive_aggregator_profile_events.sh already proves that adaptive aggregation can thaw on a repeat-dominated stream. What this PR changes is narrower: wide staged payloads should thaw while a light payload with the same repeat shape should not. None of the added stateless tests assert that distinction, and this XML never fails if the new bytes weighting regresses.

Please add a focused functional test that runs a heavy string shape and a light control under the same repeat distribution and checks AdaptiveAggregationThaws (or an equivalent observable effect) stays 0 for the latter and fires for the former.

string key (URL) and the mildly skewed key with a heavy argument (UserID, whose top
16K keys cover only ~7% of rows) are the known weak shapes these tests track. The
light-argument control on the same scan isolates the payload cost from the scan. -->
<query>SELECT WatchID, min(URL) FROM hits_100m_single GROUP BY WatchID FORMAT Null</query>

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As evidence for the 0.83x/0.59x -> 0.97x/1.00x and 14.5 -> 6.3 GB claims in the PR body, this is still incomplete. On this PR the Performance Comparison (amd_release, master_head, 1/6) through 6/6 checks are all skipped because the PR only has the pr-improvement label, so CI never ran the new benchmark. Even if they had run, the SQL perf harness records client_time only, not RSS or peak_memory_usage, so the memory claim is still unproven.

Please either run the perf comparison for this PR (or attach the manual artifact that produced those numbers) and add a memory measurement path if the RSS drop is part of the contract.

{
settings[QueryPlanSerializationSetting::enable_adaptive_aggregator] = params.enable_adaptive_aggregator;
settings[QueryPlanSerializationSetting::adaptive_aggregator_freeze_threshold] = params.adaptive_aggregator_freeze_threshold;
settings[QueryPlanSerializationSetting::adaptive_aggregator_freeze_threshold_bytes]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

QueryPlanSerializationSettings is a strict named schema, so this new entry cannot reuse the old adaptive-aggregator gate. Servers from the previous build already advertise DBMS_QUERY_PLAN_SERIALIZATION_VERSION == 9, but they do not know adaptive_aggregator_freeze_threshold_bytes; sending this name to them makes readBinary fail instead of falling back to the pre-byte-threshold behavior. In a rolling upgrade this breaks distributed or parallel-replica aggregation plans as soon as query-plan serialization is used. This needs a fresh query-plan serialization version bump and a new DBMS_MIN_QUERY_PLAN_SERIALIZATION_VERSION_WITH_* gate before the new setting is written.

/// Version 7 registers the `enable_adaptive_aggregator` and `adaptive_aggregator_freeze_threshold` plan
/// settings. As with version 5, an older peer rejects the unknown names, so they are written only towards a
/// peer at this version or above; a peer below it has no adaptive aggregation to drive anyway.
/// Version 7 registers the `enable_adaptive_aggregator`, `adaptive_aggregator_freeze_threshold` and

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

adaptive_aggregator_freeze_threshold_bytes is a new QueryPlanSerializationSettings name, but this PR does not bump DBMS_QUERY_PLAN_SERIALIZATION_VERSION. Pre-PR builds already advertise version 9, so a mixed-version cluster still negotiates version == 9; with this change the sender now emits the new name under the old >= 7 gate, and the older peer's strict readBinary path throws on the unknown setting instead of falling back to the ordinary aggregation path.

Please either bump the query-plan serialization version (and gate this setting on that new value) or keep this name off the wire until the negotiated version actually distinguishes peers that know it.

@clickhouse-gh

clickhouse-gh Bot commented Aug 19, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing d6c67d71b with master 581c15c46 (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
Binary Master PR Δ
programs/clickhouse-stripped 702.08 MiB 699.12 MiB -2.96 MiB (-0.42%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Object file sizes ⚠️

44 object files changed (+350.47 KiB total), 4 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Interpreters/AdaptiveAggregationDrain.cpp.o new 476.66 KiB +476.66 KiB
src/CMakeFiles/dbms.dir/Interpreters/AdaptiveAggregationKernels.cpp.o 1.34 MiB 972.14 KiB -397.46 KiB (-29.02%)
src/CMakeFiles/dbms.dir/Processors/Transforms/AdaptiveAggregationMergeTransform.cpp.o new 135.21 KiB +135.21 KiB
src/CMakeFiles/dbms.dir/Interpreters/AdaptiveAggregationStaging.cpp.o new 77.51 KiB +77.51 KiB
src/CMakeFiles/dbms.dir/Interpreters/AdaptiveAggregationSession.cpp.o new 52.18 KiB +52.18 KiB
src/CMakeFiles/dbms.dir/Interpreters/AdaptiveAggregation.cpp.o 142.88 KiB 93.79 KiB -49.09 KiB (-34.36%)
src/CMakeFiles/dbms.dir/Processors/Transforms/AggregatingTransform.cpp.o 486.79 KiB 517.60 KiB +30.81 KiB (+6.33%)
src/CMakeFiles/dbms.dir/Processors/QueryPlan/AggregatingStep.cpp.o 518.40 KiB 540.65 KiB +22.25 KiB (+4.29%)

737 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

135 translation units recompiled, 1412 s compile time in total, 131 of them have a recent master baseline.

Translation units without a recent master baseline:

  • src/Interpreters/AdaptiveAggregationDrain.cpp: 6.9 s
  • src/Processors/Transforms/AdaptiveAggregationMergeTransform.cpp: 5.6 s
  • src/Interpreters/AdaptiveAggregationStaging.cpp: 5.4 s

Job report

@nihalzp

nihalzp commented Sep 16, 2026

Copy link
Copy Markdown
Member Author

Closing in favor of

@nihalzp nihalzp closed this Sep 16, 2026
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-improvement Pull request with some product improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant