Repository navigation
Compute aggregation hash-table cache key from the query plan - #107643
Conversation
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]>
|
Workflow [PR], commit [f8fd221] Summary: ✅
AI ReviewSummaryThis PR moves aggregation Findings
Tests
Final VerdictStatus: Minimum required actions: make the aggregation key include all semantics-affecting source/filter/grouping inputs, restore or intentionally handle |
|
|
||
| /// 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); |
There was a problem hiding this comment.
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.
|
📊 Cloud Performance Report 🔴 AI verdict: 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)
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_officialFlagged queries (1 of 22)
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
|
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]>
| /// 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); |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered by tests: 63/67 (94.03%) | Lost baseline coverage: none · Uncovered code |
|
@novikd is there coverage from performance tests for this optimization? |
…from-query-plan Compute aggregation hash-table cache key from the query plan
The analyzer's
buildSelectQueryInfoeagerly 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 commonSELECT ... FROM <MergeTree>path. This computes the key from the query plan instead — a newsetAggregationHashTableCacheKeyspass stamps everyAggregatingStepwith its bottom-up plan-node hash, reusing the samecalculateHashTableCacheKeysinfrastructure 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):
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
Version info
26.7.1.513(included in26.7and later)