Repository navigation
Fix zero-capacity hash-table statistics cache seeded by lazy FINAL - #114597
Conversation
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. #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]>
|
Workflow [PR], commit [4c79890] Summary: ✅
AI ReviewSummaryThis PR fixes the Final Verdict✅ No further findings. LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 56/56 (100.00%) · Uncovered code |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
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 units9 translation units recompiled, 31 s compile time in total, 9 of them have a recent master baseline. |
The guard added in `setAggregationHashTableCacheKeys` only covered the aggregation side. The join callers - `RuntimeHashStatisticsContext::getCachedHint` in `optimizeJoin.cpp`, `buildPhysicalJoinImpl` in `JoinStepLogical.cpp` and `getBuildSideDistinctKeys` in `joinRuntimeFilter.cpp` - build `StatsCollectingParams` straight from the server setting, so an administrator setting `max_entries_for_hash_table_stats = 0` still created a permanently empty join statistics cache on first use instead of cleanly disabling the feature. Move the invariant to where the cache is created: `HashTablesStatistics::getHashTableStatsCache` no longer creates the cache for a caller that keeps no entries, and `getSizeHint`/`update` report "no statistics" for such a caller. The capacity of the process-wide cache is fixed by whoever creates it, so this is the single place that can guarantee a caller with `max_entries_for_hash_table_stats = 0` cannot poison it - for both the aggregation and the join statistics, whatever built the params. The new `gtest_hash_tables_statistics` covers both entry types: a caller that keeps no entries must leave the statistics usable for later callers. Both cases fail on the unfixed code. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The test asserted preallocation without forcing the path that produces the bug. Verified on the built binary: with `enable_analyzer = 0` the lazy `FINAL` optimization is not built at all (no `LazyFinalKeyAnalysisTransform` in the trace log), so the poisoning query never runs and the test passes on the unfixed binary. `clickhouse-local` does not pick up `CLICKHOUSE_CLIENT_OPT`, which is why this went unnoticed, but the setting must not be left to the default of the day. Pin `enable_analyzer = 1` (as every other lazy `FINAL` test does) and `optimize_aggregation_in_order = 0` so the victim query is guaranteed to aggregate through a hash table, and assert the `Lazy FINAL enabled` trace message of `LazyFinalKeyAnalysisTransform`, so the query that is supposed to poison the cache cannot silently stop being one. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Related: #101647
Related: #113333
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed hash-table statistics — and with them aggregation hash-table preallocation — being silently and permanently disabled for the whole server when a query using the lazy
FINALoptimization (query_plan_optimize_lazy_final) was the first aggregation to run after server startup.Description
The
FINAL-replacing dedup aggregation of the lazyFINALoptimization (LazyReadReplacingFinalSource, #101647) built itsAggregatingStepwith default-constructedStatsCollectingParams, i.e.max_entries_for_hash_table_stats = 0. The query-plan optimization passsetAggregationHashTableCacheKeysstamps a cache key onto every keyedAggregatingStep, which enables statistics collection. The process-wide statistics cache is created lazily by the first query that touches it, withmax_entries_for_hash_table_stats * sizeof(Entry)as its capacity — so when a lazyFINALquery 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 preallocation) for the whole server lifetime. In the affected CI run's server log the aggregation statistics cache had 3515Statistics updatedentries and zerofound in cachehits over the entire lifetime, while the join statistics cache (a separate instance created with proper parameters) worked normally.This stayed unnoticed while keyless aggregations, which carry properly constructed params, also touched the cache and almost always created it first. #113333 (merged 2026-08-12 19:00 UTC) stopped keyless aggregations from touching the cache, after which the lazy
FINALtests started to win the first-toucher race, and04625_hash_table_sizes_stats_table_expression_modifiersbegan to fail withfinal-prealloc 0/no-final-prealloc 0across unrelated jobs (amd_msan,amd_asan_ubsan, distributed plan,Fast test,Fast test (arm_darwin)) starting 2026-08-12 22:39 UTC — 6 failures, no failures of this kind before that date. Because the poisoned cache is server-instance state, the flaky-check diagnosis reproduced the failure 5/5 within the affected run while adjacent master commits passed.CI reports:
The fix:
HashTablesStatistics::getHashTableStatsCacheno longer creates the process-wide cache for a caller whosemax_entries_for_hash_table_statsis zero, andgetSizeHint/updatereport "no statistics" for such a caller. The capacity of that cache is fixed by whoever creates it, so this is the single place that can guarantee a caller keeping no entries cannot poison it — for the aggregation statistics and for the join statistics alike, whatever built the params. It also makes an administrator-configuredmax_entries_for_hash_table_stats = 0a clean disable instead of a zero-capacity cache: before this, the join callers (RuntimeHashStatisticsContext::getCachedHint,buildPhysicalJoinImpl,getBuildSideDistinctKeys) went straight from the server setting to a non-zero key.LazyReadReplacingFinalSourcenow constructs realStatsCollectingParams(same pattern asPlanner), so the dedup aggregation also benefits from size hints on repeatedFINALqueries.setAggregationHashTableCacheKeysskips steps whose builder leftstats_collecting_paramsunconfigured, so no query collects statistics that are guaranteed to be thrown away.Tests, both of which fail on the unfixed code:
gtest_hash_tables_statisticscovers the invariant directly for both entry types (AggregationEntryandHashJoinEntry): a caller that keeps no entries must leave the statistics usable for every later caller.04869_lazy_final_hash_table_stats_cacheruns the first-toucher scenario deterministically inclickhouse-local(a fresh process owns a fresh statistics cache): the lazyFINALquery runs first, then a 650000-group victim aggregation twice; the second run must preallocate, observed through theAggregationPreallocatedElementsInHashTablesevent insystem.events. On the unfixed binary this deterministically reports nothing; with the fix it reports 650000. Every setting that decides which path runs is pinned (enable_analyzer,optimize_aggregation_in_order, the spill thresholds), and theLazy FINAL enabledtrace message is asserted so the query that is supposed to poison the cache cannot silently stop being one.Verified locally against a patched build: the new test and the unit test flip from failing to passing, and
04625_hash_table_sizes_stats_table_expression_modifiers,02151_hash_table_sizes_stats*,04357_join_runtime_filter_size_from_hash_table_stats,04509,04516,04518and the lazyFINALfamily (03988,03990,03991,04092,04093,04095,04105,04207,04493,04517,04539) pass.🤖 Generated with Claude Code
Version info
26.8.1.1381(included in26.8and later)