Skip to content

Compute aggregation hash-table cache key from the query plan - #107643

Merged
nickitat merged 3 commits into
masterfrom
aggregation-key-from-query-plan
Jul 4, 2026
Merged

nickitat merged 3 commits into
masterfrom
aggregation-key-from-query-plan

Conversation

@novikd

@novikd novikd commented Jun 16, 2026 •

Copy link
Copy Markdown
Member

The analyzer's buildSelectQueryInfo eagerly converted the whole query tree to an AST so the aggregation hash-table-statistics preallocation key could be derived from it, which showed up as a noticeable cost during query analysis even though that AST is otherwise unused on the common SELECT ... FROM <MergeTree> path. This computes the key from the query plan instead — a new setAggregationHashTableCacheKeys pass stamps every AggregatingStep with its bottom-up plan-node hash, reusing the same calculateHashTableCacheKeys infrastructure that already keys join hash tables — so the planner no longer builds the AST for this. The pass runs before join runtime filters are added, because a runtime filter injects a per-execution-random constant that would otherwise make the key non-deterministic across runs of the same query.

Changelog category (leave one):

  • Performance Improvement

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

Avoid building the full query AST during analysis of aggregating queries by computing the aggregation hash-table size-statistics cache key from the query plan instead of the AST.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.7.1.513 (included in 26.7 and later)

The analyzer planner seeded the aggregation hash-table-statistics
preallocation key with calculateCacheKey(select_query_info.query),
which forced an eager full-query toAST in buildSelectQueryInfo.

Compute the key during query-plan optimization instead, reusing the
existing calculateHashTableCacheKeys infrastructure that already keys
join hash tables. A new setAggregationHashTableCacheKeys pass stamps
every AggregatingStep from its bottom-up plan hash. This matches the
intent already noted in AggregatingStep::serialize and removes the
aggregation path's dependence on the AST.

The pass runs before join runtime filters are added: a runtime filter
injects a per-execution-random constant into the probe-side Filter, so
hashing a plan that contains it would make an aggregation's key differ
across executions of the same query and defeat the size-stats cache.
Join steps rely on the same invariant.

Verified with 02151_hash_table_sizes_stats (all four variants).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jun 16, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f8fd221]

Summary: ✅


AI Review

Summary

This PR moves aggregation HashTablesStatistics key creation from the AST to query-plan optimization. The direction removes a real analyzer cost and the performance evidence shows wins, but the current plan-derived key omits semantics-affecting inputs and drops modifier aggregation stats, so I would not merge until the key is made aggregation-specific and covered by focused tests.

Findings

⚠️ Majors

  • [src/Processors/QueryPlan/Optimizations/calculateHashTableCacheKeys.cpp:34] The aggregation cache key must separate all inputs that affect aggregation cardinality, but calculateHashFromStep(const SourceStepWithFilter &) only hashes the source identity and prewhere_info. Absorbed WHERE filters in getFilterActionsDAG, row-level filters, and source parameters such as the bounded range of numbers(N) do not contribute. Two queries over the same source with different effective row sets can share one HashTablesStatistics entry, causing over-preallocation or premature two-level aggregation from another query. Suggested fix: include getFilterActionsDAG, getRowLevelFilter, and source-specific cardinality/range serialization in the source hash, or compute the key before those predicates are absorbed into the source.
  • [src/Processors/QueryPlan/Optimizations/calculateHashTableCacheKeys.cpp:53] [dismissed by author -- https://github.com/Compute aggregation hash-table cache key from the query plan #107643#discussion_r3423090641] The aggregation key still ignores row-preserving ExpressionSteps, but grouping-key distinctness depends on the expressions that produce the key, not only on input row count. For example, number % 10 AS k and number % 100000 AS k with the same output name k hash the same while requiring very different hash-table sizes. I still consider this real because calculateHashFromStep(const ITransformingStep &) returns 0 for row-preserving transforms and AggregatingStep serialization only records key names. Suggested fix: use an aggregation-specific hash that includes the ActionsDAGs producing the grouping keys.
  • [src/Planner/Planner.cpp:877] [dismissed by author -- https://github.com/Compute aggregation hash-table cache key from the query plan #107643#discussion_r3423090635] RollupStep and CubeStep still receive StatsCollectingParams with key 0, and setAggregationHashTableCacheKeys only stamps AggregatingStep. Before this PR they received the AST-derived key through getAggregatorParams, so modifier aggregation stages no longer collect/use size statistics. I still consider this real because RollupStep and CubeStep store their own Aggregator::Params and there is no later setter. Suggested fix: stamp those steps too with keys that include modifier semantics, or preserve their old key path.
Tests
  • ⚠️ Please add focused coverage that proves distinct cache entries for different absorbed filters/source ranges and for different grouping-key ActionsDAGs with the same key name. The existing 02151_hash_table_sizes_stats cases prove basic preallocation still happens, but not that these plan-derived keys are separated correctly.
Final Verdict

Status: ⚠️ Request changes

Minimum required actions: make the aggregation key include all semantics-affecting source/filter/grouping inputs, restore or intentionally handle RollupStep/CubeStep statistics, and add the focused regression tests above.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Jun 16, 2026

/// Compute every node's bottom-up hash first, then stamp AggregatingStep nodes. The hash is
/// computed while all keys are still unset, so it never depends on the key we are about to set.
const auto cache_keys = calculateHashTableCacheKeys(root);

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.

The aggregation cache key is now stamped here after first-pass filter pushdown. One concrete path loses the predicate before this point: tryPushDownFilter pushes a FilterStep into ReadFromMerge via addFilter, optimizePrimaryKeyConditionAndLimit applies it as SourceStepWithFilter::filter_actions_dag, and the original FilterStep is no longer in the plan. But calculateHashFromStep(const SourceStepWithFilter &) only hashes the source identity and prewhere_info, so two queries over the same merge source with different WHERE predicates can share the same AggregatingStep key and reuse the wrong HashTablesStatistics size hint. That can over-preallocate or initialize two-level aggregation from another predicate's cardinality. Please include getFilterActionsDAG (and the row-level filter, which also affects source cardinality) in the source hash, or move this pass before predicates are absorbed into source steps.

@clickhouse-gh

clickhouse-gh Bot commented Jun 17, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

🔴 AI verdict: degradation — 1 regressed, 3 improved out of 38 analysed

This PR moves aggregation hash-table preallocation from an AST-based cache key to one computed from the query plan, enabling size preallocation for GROUP BY/DISTINCT queries. That directly explains the cluster of clickbench improvements (Q4 -15.6%, Q15 -13.7%, Q28 -6.5%), which avoid rehashing when group cardinality is well estimated. The one regression, Q31 at +11.9%, is the expected flip side: preallocation can overshoot and cost cache locality when the estimate is off. The tpch_adapted Q4 delta (+5.3%) is borderline with noisy measurements and stays not_sure. No downgrades — all five flagged queries are aggregations sitting squarely on the path this PR changes.

clickbench

🔴 1 regressed · 🟢 3 improved

Flagged queries (4 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
🔴 31 regression 306 342 +11.9% <0.0001 aggregation: +11.9% GROUP BY regression: plausibly preallocation overshoot hurting cache locality for this key set
🟢 4 improvement 263 222 -15.6% <0.0001 aggregation: COUNT(DISTINCT) hash set now preallocated via plan-derived key; -15.6% consistent with this PR's path
🟢 15 improvement 238 205 -13.7% <0.0001 aggregation: GROUP BY hash table preallocation directly on this query's path; -13.7% plausible
🟢 28 improvement 6997 6544 -6.5% <0.0001 aggregation: Heavy GROUP BY/aggregation; preallocated hash table cuts rehashing, -6.5% fits the change

q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

⚠️ 1 inconclusive

Flagged queries (1 of 22)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 4 not_sure 2341 2465 +5.3% 0.0449 aggregation: GROUP BY query on the changed path; +5.3% borderline with noisy measurements, left as not_sure

q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

Debug info
  • StressHouse run: 8d8e2a6d-c1da-4dd4-825c-920773f02970
  • MIRAI run: cbaf4073-617b-4bf9-9643-175b01c02aa8
  • PR check IDs:
    • clickbench_84277_1782420475
    • clickbench_84283_1782420475
    • clickbench_84291_1782420475
    • tpch_adapted_1_official_84300_1782420475
    • tpch_adapted_1_official_84313_1782420475
    • tpch_adapted_1_official_84329_1782420475

setAggregationHashTableCacheKeys called calculateHashTableCacheKeys on
the whole plan for every query (the setting is on by default), which
serializes plan steps to hash them. Some steps are not serializable
(ORDER BY ... WITH FILL throws in serializeSortDescription, INSERT ...
FROM INFILE plans throw "Both table name and UUID are empty"), so the
pass aborted otherwise-valid queries.

Fix, scoped to the aggregation pass:
- Skip entirely when the plan has no AggregatingStep, so non-aggregating
  queries (e.g. INSERTs) never serialize anything.
- Hash only each aggregation's own input subtree, excluding the steps
  above it (LIMIT, ORDER BY ... WITH FILL) that do not affect the number
  of groups and may not be serializable.
- Compute all keys before stamping any of them, and treat a key as a
  best-effort hint: if a step inside the input subtree is not
  serializable, skip preallocation for that aggregation instead of
  failing the query.

Verified with 02151_hash_table_sizes_stats (all four variants) and with
GROUP BY + WITH FILL and INSERT ... FROM INFILE queries.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@nickitat nickitat self-assigned this Jun 18, 2026
/// aggregation's key differ across executions of the same query and defeat the size-stats cache.
/// Join steps avoid this for exactly the same reason by computing their key before the filter is
/// added. The plan here is already deterministic (post first pass and subplan materialization).
setAggregationHashTableCacheKeys(optimization_settings, root);

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.

Let's do it after all modifying passes are finished, as the very last step. I assume it will work out of the box after #106137, or at least it shouldn't be too difficult to 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.

It doesn't work out of the box yet. #106137 made the runtime-filter name deterministic, but the rendezvous value (id.key) is still random per plan build and is included in the plan-step hash (serializeConstant writes the const value, and Node::updateHash hashes it). So computing the aggregation key after the filter is added makes it differ across executions of the same query, and the size-stats cache never hits.

Independently, hashing the full final plan also serializes steps that aren't serializable — e.g. ORDER BY ... WITH FILL (WITH FILL is not supported in serialized sort description) and INSERT ... FROM INFILE — which throws.

So doing it at the end needs two small fixes: skip the non-deterministic constant's value in the cache-key hash (the deterministic name is enough now), and hash only each aggregation's input subtree (skipping unserializable steps). Happy to go that way if you prefer it to computing before the filter.

@clickhouse-gh

clickhouse-gh Bot commented Jun 25, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.40% 85.40% +0.00%
Functions 92.60% 92.60% +0.00%
Branches 77.60% 77.60% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 63/67 (94.03%) | Lost baseline coverage: none · Uncovered code

Full report · Diff report

@nickitat
nickitat added this pull request to the merge queue Jul 4, 2026
Merged via the queue into master with commit 49dc83c Jul 4, 2026
167 checks passed
@nickitat
nickitat deleted the aggregation-key-from-query-plan branch July 4, 2026 16:02
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 4, 2026
@PedroTadim

Copy link
Copy Markdown
Member

@novikd is there coverage from performance tests for this optimization?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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.

4 participants