Repository navigation
Conversation
setAggregationHashTableCacheKeys admitted every AggregatingStep and then serialized that node's input subtree to derive a hash-table-size cache key. ActionsDAG::serialize writes the full binary content of constant columns, so a constant-folded range(5000000) literal materializes about 40 MB into a WriteBufferFromOwnString on every execution of the query. For an aggregation without GROUP BY keys that work can never pay off. AggregatedDataVariants::chooseMethod returns without_key whenever keys_size == 0, and AggregatedDataVariants::init discards the size_hint for without_key; without_key is also absent from APPLY_FOR_VARIANTS_CONVERTIBLE_TO_TWO_LEVEL, so the two-level path is a no-op too. Such aggregations additionally polluted the shared HashTablesStatistics cache: updateStatistics records data_variants[i]->size(), which for without_key is the constant 1, evicting useful entries. Admit an AggregatingStep only when it has GROUP BY keys. The rest of the pass is unchanged: the early return when no aggregation is present (hashing a plan with non-serializable steps would throw), the per-node try/catch treating the key as a best-effort preallocation hint, and the compute-all-then-stamp-all ordering. The two other consumers of these hashes, considerEnablingParallelReplicas and optimizeJoin, call calculateHashTableCacheKeys directly rather than the stamping function, so they observe identical values. Measured on x86_64, release build, against pristine master with verified distinct build IDs. QueryPlanOptimizeMicroseconds for the reported query, median of 9: 63000 to 154; wall clock, min of 15: 275 ms to 214 ms. Controls behave as expected: materialize(), which defeats constant folding, and collect_hash_table_stats_during_aggregation = 0 are already low on master. Keyed aggregations keep preallocating: 04509_hash_table_sizes_stats_table_functions still reports 650000 and 520000 for its local and distributed sections, and HashTableStatsCacheEntries grows by 12 for 12 distinct keyed aggregations on both branches, while for 12 keyless ones it grows by 12 on master and by 0 with this change. Queries from hash_table_sizes_stats, hash_table_sizes_stats_small and group_by_consecutive_keys are unchanged (ratios 0.93 to 1.02), and the full aggregat/group_by stateless suite (460 tests) gives identical per-test verdicts. Constant serialization remains costly for keyed aggregations, measured at about 62 ms for the same literal and unchanged here; that is left to a separate fix. Closes: ClickHouse#113037
Internal second-model review (4 findings: 2 accepted and fixed in the description, 2 declined with evidence)Before opening this PR I ran an independent cold review of the resulting code plus a second-model
|
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-44:20260804-082300 |
|
cc @nickitat @antaljanosbenjamin, could you review this? |
|
Workflow [PR], commit [3fbc05c] Summary: ❌
AI ReviewSummaryThis PR narrows Final Verdict✅ No new findings. LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 7/7 (100.00%) · Uncovered code |
|
📊 Cloud Performance Report ✅ AI verdict: This PR narrows the aggregation hash-table size-hint cache to only aggregations that have GROUP BY keys, skipping keyless (without_key) aggregations whose init discards the hint. Both flagged ClickBench queries (Q31, Q33) use GROUP BY, so their execution path is unchanged by the diff; their small median improvements (-10.8% and -5.3%) fall within master's current variance band and are accompanied by flat CPU time, so the deterministic within-envelope suppression is correct. No regressions, and no work-backed improvement attributable to this change on the flagged queries. clickbench🟢 No significant changes tpch_adapted_1_official🟢 No significant changes Debug info
|
CI finish ledger - 3fbc05cEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Neither Session id: cron:our-pr-ci-monitor:20260804-203000 |
be92c91
ReproducerShell reproducer — run against a local ClickHouse build ( # 26.7.3.19 — keyless aggregation over a 40 MB constant-folded literal
clickhouse local --print-profile-events --query \
"SELECT count() FROM (SELECT arrayJoin(range(5000000)) AS x)"
# QueryPlanOptimizeMicroseconds: 58896 MemoryTrackerPeakUsage: 96024496
# same query with SETTINGS collect_hash_table_stats_during_aggregation = 0:
# QueryPlanOptimizeMicroseconds: 92 MemoryTrackerPeakUsage: 30522070
# => 640x plan-optimization time and +65 MB peak per execution, for a cache
# key a without_key aggregation can never consume.Results:
Backport the fix to CC introducing PR author: @novikd CC component owner: @davenger @KochetovNicolai Analysis metadata
|
The FINAL-replacing dedup aggregation of the lazy FINAL optimization (LazyReadReplacingFinalSource) built its AggregatingStep with default-constructed StatsCollectingParams, i.e. max_entries_for_hash_table_stats = 0. The query-plan optimization pass setAggregationHashTableCacheKeys stamps a cache key onto every keyed AggregatingStep, which enables statistics collection. The process-wide statistics cache is created lazily by the first query that touches it, with max_entries_for_hash_table_stats * sizeof(Entry) as its capacity, so when a lazy FINAL query was the first aggregation in a freshly started server, the cache was created with zero capacity: every insertion was evicted immediately and every lookup missed, permanently disabling hash-table statistics (and with them preallocation) for the whole server lifetime. This stayed unnoticed while keyless aggregations, which carry properly constructed params, also touched the cache and almost always created it first. ClickHouse#113333 stopped keyless aggregations from touching the cache, after which the lazy FINAL tests started to win the first-toucher race and 04625_hash_table_sizes_stats_table_expression_modifiers began to fail with 'final-prealloc 0' / 'no-final-prealloc 0' across unrelated jobs: https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=2790ac4a68cf412d05db2d1573685a1a8467ecdb&name_0=MasterCI&name_1=Stateless%20tests%20%28amd_msan%2C%20WasmEdge%2C%20parallel%2C%201%2F3%29 https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=86363e819f9cb704a892063da9998e4c1281eb76&name_0=MasterCI&name_1=Stateless%20tests%20%28amd_msan%2C%20WasmEdge%2C%20parallel%2C%201%2F3%29 Fix: pass real StatsCollectingParams in LazyReadReplacingFinalSource (the dedup aggregation now also benefits from size hints), and make setAggregationHashTableCacheKeys skip steps whose builder left the params unconfigured, so a stamped key can never enable collection with a zero-capacity configuration. The new test runs the first-toucher scenario deterministically in clickhouse-local (a fresh process owns a fresh statistics cache). Co-Authored-By: Claude Fable 5 <[email protected]>
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed a performance regression where an aggregation without
GROUP BYkeys serialized its whole input plan subtree, including the full contents of constant-folded literals, on every execution to compute a hash-table-size cache key it can never use. A query such asSELECT quantileMerge(arrayJoin(arrayMap(x -> state, range(5000000))))spent about 63 ms per execution in query-plan optimization and now spends 0.15 ms.Description
Closes: #113037
Related: #107643 (introduced the pass)
setAggregationHashTableCacheKeysadmitted everyAggregatingStepand serialized its input subtree to derive a cache key.ActionsDAG::serializewrites the full binary content of constant columns, so a foldedrange(5000000)literal materialized about 40 MB into a buffer on every execution.A keyless aggregation cannot use that key.
AggregatedDataVariants::chooseMethodstarts withif (keys_size == 0) return Type::without_key;,initdiscards thesize_hintforwithout_key, andwithout_keyis absent fromAPPLY_FOR_VARIANTS_CONVERTIBLE_TO_TWO_LEVEL. Such aggregations also wrote a meaningless entry (median_size= 1) into the shared statistics cache, evicting useful ones.The fix admits an
AggregatingSteponly when!getParams().keys.empty(). The early return when no aggregation is present, the per-nodetry/catchand the compute-all-then-stamp-all ordering are unchanged, and the key stays an optional flagged field inAggregatingStep::serialize, so no format or setting default changes.Validated on x86_64 (the issue reports aarch64), release, against pristine master with distinct build IDs.
QueryPlanOptimizeMicrosecondsfor the reported query, median of 9: 63000 to 154. Keyed aggregations keep preallocating, and the existing keyed tests are the regression guard here; a keyless assertion would need a process-global asynchronous metric or a timing counter, both flaky.Validation matrix
04509_hash_table_sizes_stats_table_functionsstill reports 650000 and 520000 on both branches.HashTableStatsCacheEntriesgrows by 12 for 12 distinct keyed aggregations on both branches; for 12 keyless ones it grows by 12 on master and by 0 with this change.hash_table_sizes_stats,hash_table_sizes_stats_smallandgroup_by_consecutive_keysqueries: ratios 0.93 to 1.02.aggregat/group_bystateless suite, 460 tests: identical per-test verdicts.04506and04507: 100 OK, 0 FAIL on both branches.optimizeJoinandconsiderEnablingParallelReplicasreuse these subtree hashes and run after this pass, so with a keyless aggregation under a join their key values shift: the flag bit recording whether a key was stamped now differs.HashTablesStatisticsis process-local, so the cost is one un-preallocated execution.Constant serialization is still costly for keyed aggregations, about 62 ms here, and is left to a separate fix.
Version info
26.8.1.1275(included in26.8and later)