Skip to content

Weigh the adaptive aggregation's thaw by staged bytes and add the freeze-bytes settings - #115755

Merged
nihalzp merged 23 commits into
ClickHouse:masterfrom
nihalzp:harden-adaptive-aggregator
Aug 25, 2026
Merged

nihalzp merged 23 commits into
ClickHouse:masterfrom
nihalzp:harden-adaptive-aggregator

Conversation

@nihalzp

@nihalzp nihalzp commented Aug 21, 2026 •

Copy link
Copy Markdown
Member

Memory regression fix:
image
image

Related: #111459
Related: #115480

The behavioral half of #115480, split out so it can merge independently of the restructuring: one behavioral improvement to the adaptive aggregation's thaw, one new setting, and a latent initialization bug fix.

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; heavy-column streams stand down early in proportion to the damage.

Only the keys and the variable-width argument columns count toward a record's bytes. Fixed-width arguments are deliberately excluded: the drain applies them with the same batch executor the scan would have used, so their staging costs about what their consumption saves — a five-UInt64-argument stream at repeat 10 stays engaged and is a clear adaptive win, while a bare repeat rule (or counting its fixed bytes) would thaw it away.

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)
  • Full ClickBench GROUP BY sweep within noise; winning shapes unchanged.

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). The plan-serialization side rides version 7, since all the adaptive settings ship in the same release.

HashTable Statistics

Adaptive Aggregator no longer uses previous run hash tables sizes to resize it's small buffer tables. First, buffer tables are very small so any save in runtime is negligible. Second, if buffer table is resized above adaptive_aggregator_freeze_threshold_bytes, it will freeze after first block instead storing all frequent keys eventually.

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).


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

Version info

  • Backported to: 26.8.1.2000

@clickhouse-gh

clickhouse-gh Bot commented Aug 21, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [2e78fe2]

Summary: ✅


AI Review

Summary

This PR makes adaptive GROUP BY thaw based on staged-byte waste, adds adaptive_aggregator_freeze_threshold_bytes, hardens warm-run initialization, and adds focused regression coverage. The adaptive-aggregation fixes themselves look solid now, but two release-compatibility gaps remain: mixed 26.8/26.9 distributed plans can still reject the new setting on the wire, and compatibility = '26.8' does not restore the pre-26.9 behavior.

Findings

❌ Blockers

  • [src/Processors/QueryPlan/AggregatingStep.cpp:1146-1151] [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/115755#discussion_r3829648836] QueryPlanSerializationSettings is a strict named schema, but this branch still writes adaptive_aggregator_freeze_threshold_bytes under the old adaptive-aggregator gate. Now that the byte threshold is recorded as a 26.9 addition while 26.8 already ships query-plan version 9, a 26.9 initiator can send this unknown setting name to a 26.8 worker and make distributed aggregation with serialize_query_plan = 1 fail during readBinary. This needs a new per-setting query-plan-serialization gate/version, or an explicit older-peer fallback that does not send an unreadable name.

⚠️ Majors

  • [src/Core/SettingsChangesHistory.cpp:46] [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/115755#discussion_r3829343897] The new 26.9 history entry keeps adaptive_aggregator_freeze_threshold_bytes at 4194304 for both previous_value and new_value, so SET compatibility = '26.8' still enables the new byte-triggered freeze even though 26.8 had no such setting. That breaks the explicit compatibility contract for the new setting; the compatibility value needs to restore the pre-26.9 behavior, i.e. 0 / “setting absent”.
Final Verdict

❌ Not ready to merge until the 26.8 compatibility default and the mixed-version query-plan serialization gate for adaptive_aggregator_freeze_threshold_bytes are fixed.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 87.20% 87.20% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 79.30% 79.30% +0.00%

Changed lines: Changed C/C++ lines covered: 210/211 (99.53%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Aug 21, 2026

@clickhouse-gh clickhouse-gh Bot left a comment

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.

Inline findings attached.

Comment thread src/Interpreters/Aggregator.cpp Resolved
Comment thread src/Core/SettingsChangesHistory.cpp Outdated
{"enable_adaptive_aggregator", false, true, "New setting to enable adaptive `GROUP BY` aggregation that freezes each thread's local hash table once it reaches `adaptive_aggregator_freeze_threshold` keys, so frequent keys keep aggregating in the small local tables while rare keys are routed by their hash into per-bucket backlogs and aggregated exactly once, inside the bucket-parallel merge; this stores and processes rare keys once instead of once per thread."},
{"adaptive_aggregator_freeze_threshold", 16384, 16384, "New setting to set the number of keys at which the adaptive aggregator (`enable_adaptive_aggregator`) freezes a thread's local hash table."},
{"adaptive_aggregator_freeze_threshold_bytes", 4194304, 4194304, "New setting bounding the adaptive aggregator's frozen local tables in bytes, whichever of it and the key-count threshold is reached first; 0 disables the byte bound."},
{"query_plan_aggregation_bucket_top_k", false, true, "New setting to toggle the plan optimization that materializes only each two-level bucket's best n groups when a final aggregation feeds ORDER BY over its outputs with LIMIT n and the per-bucket selection is provably exact."},

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.

These compatibility defaults do not match the pre-PR behavior.

  • adaptive_aggregator_freeze_threshold_bytes did not exist before this change, so older compatibility versions should see 0, not 4 MiB, otherwise they still opt into the new byte-triggered freeze.
  • query_plan_aggregation_bucket_top_k is only a dedicated toggle for an existing rewrite that used to be always on under query_plan_enable_optimizations, so older compatibility versions should keep it enabled instead of flipping it to false.

As written, compatibility against an older version changes both features away from what that older version actually did.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

There is no older version in release that has Adaptive Aggregator at all. So, adaptive_aggregator_freeze_threshold_bytes and Adaptive Aggregator will come in the same release.

query_plan_aggregation_bucket_top_k feature is not present in any release. query_plan_aggregation_bucket_top_k feature will be shipped in the upcoming release and this setting just gates the optimization.

@nickitat nickitat self-assigned this Aug 21, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 21, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 2e78fe220 with master f7901a482 (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
Binary Master PR Δ
programs/clickhouse-stripped 709.92 MiB 706.88 MiB -3.03 MiB (-0.43%)

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.

Compile time of recompiled translation units

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

Job report

@nickitat nickitat left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Looks ok

Comment thread src/Core/Settings.cpp
- 0 - Disable
- 1 - Enable
)", 0) \
DECLARE(Bool, query_plan_aggregation_bucket_top_k, true, R"(

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I'd prefer us to not mix this change into the main fix

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Okay, removed it.

for (const auto & column : std::get<StagedChunk::AggregatePayload>(block->payload).argument_columns)
if (column && !column->valuesHaveFixedSize())
batch_bytes += column->byteSize();
batch_bytes += total * 16;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

If I'm not mistaken

Suggested change
batch_bytes += total * 16;
batch_bytes += total * (sizeof(UInt64) + (adaptive_key_stages_bytes<SharedKey> ? sizeof(UInt64) : 0));

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Yes, it would be more accurate.

@nihalzp nihalzp changed the title Weigh the adaptive aggregation's thaw by staged bytes and add the freeze-bytes and bucket top-K settings Weigh the adaptive aggregation's thaw by staged bytes and add the freeze-bytes settings Aug 23, 2026
@nihalzp
nihalzp requested a review from nickitat August 24, 2026 11:48
@nihalzp

nihalzp commented Aug 24, 2026

Copy link
Copy Markdown
Member Author

@groeneai Investigate the CI failure.

@groeneai

Copy link
Copy Markdown
Collaborator

The only red is BuzzHouse (amd_debug), and it is not caused by this PR.

It is the chronic trunk Not-ready Set family (STID 0250-4e52): 109 rows across 94 distinct PRs in the last 30 days, including 5 runs on genuine master (head_ref = 'master', pull_request_number = 0), first seen 2026-07-25, about a month before this branch existed. This PR touches 31 files, all adaptive-aggregation, and none of the set-building machinery (PreparedSets, FutureSet, CreatingSets, Functions/in).

I reproduced the identical stack on pristine master today (49e1373adb63), frame for frame with the CI report (in.cpp:128 -> IFunction.cpp:433/537/570/675 -> ExpressionActions.cpp:693/837 -> FilterTransform.cpp:227/167), using none of your code:

EXPLAIN ANALYZE indexes = 0, actions = 1, projections = 1
SELECT (SELECT YYYYMMDDToDate(yyyymmdd)) FROM (
  SELECT 19840121 AS yyyymmdd UNION ALL SELECT 20230911 AS yyyymmdd
  QUALIFY exists((SELECT toDateOrZero(isZeroOrNull(NULL), NULL, toNullable(NULL))
                  UNION ALL SELECT toDateOrZero(isZeroOrNull(NULL), NULL, toNullable(NULL))))
) ORDER BY yyyymmdd ASC
SETTINGS allow_experimental_correlated_subqueries = 1, correlated_subqueries_use_in_memory_buffer = 0,
         execute_exists_as_scalar_subquery = 0, correlated_subqueries_default_join_kind = 'left'

Your failing query has the same shape (a QUALIFY exists((SELECT ...)) correlated subquery), and the run had allow_experimental_correlated_subqueries = true, correlated_subqueries_use_in_memory_buffer = false, execute_exists_as_scalar_subquery = false. The route is a correlated subquery body being materialized with a nested IN: the set is built into a clone that is then discarded, so FunctionIn later sees an unbuilt set and raises the logical error (an exception, caught in release builds, aborting only under debug and sanitizers). My open fix for this route is #115868.

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=115755&sha=fc2765954650183c62bc5b32f2c6c37618f782f2&name_0=PR&name_1=BuzzHouse%20%28amd_debug%29

@nickitat

Copy link
Copy Markdown
Member

If I'm not mistaken, the release branch is already created - you'll need to backport it.

@nihalzp
nihalzp added this pull request to the merge queue Aug 25, 2026
Merged via the queue into ClickHouse:master with commit 24dc825 Aug 25, 2026
351 of 352 checks passed
@nihalzp
nihalzp deleted the harden-adaptive-aggregator branch August 25, 2026 08:44
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Aug 25, 2026
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 25, 2026
clickhouse-gh Bot added a commit that referenced this pull request Aug 25, 2026
Backport #115755 to 26.8: Weigh the adaptive aggregation's thaw by staged bytes and add the freeze-bytes settings
nihalzp added a commit that referenced this pull request Aug 25, 2026
…8/115755

Revert "Backport #115755 to 26.8: Weigh the adaptive aggregation's th…
clickhouse-gh Bot added a commit that referenced this pull request Aug 25, 2026
…3-backport/26.8/115755

Revert "Revert "Backport #115755 to 26.8: Weigh the adaptive aggregation's th…"
@robot-clickhouse robot-clickhouse added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Aug 26, 2026
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Aug 28, 2026
…thaw by staged bytes and add the freeze-bytes settings
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Aug 28, 2026
…ation's thaw by staged bytes and add the freeze-bytes settings"
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Aug 28, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-improvement Pull request with some product improvements pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.8-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants