Skip to content

Fix zero-capacity hash-table statistics cache seeded by lazy FINAL - #114597

Merged
alexey-milovidov merged 3 commits into
masterfrom
fix-lazy-final-hash-table-stats-cache
Aug 14, 2026
Merged

alexey-milovidov merged 3 commits into
masterfrom
fix-lazy-final-hash-table-stats-cache

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 13, 2026 •

Copy link
Copy Markdown
Member

Related: #101647
Related: #113333

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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 FINAL optimization (query_plan_optimize_lazy_final) was the first aggregation to run after server startup.

Description

The FINAL-replacing dedup aggregation of the lazy FINAL optimization (LazyReadReplacingFinalSource, #101647) 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 preallocation) for the whole server lifetime. In the affected CI run's server log the aggregation statistics cache had 3515 Statistics updated entries and zero found in cache hits 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 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 (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::getHashTableStatsCache no longer creates the process-wide cache for a caller whose max_entries_for_hash_table_stats is zero, and getSizeHint / update report "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-configured max_entries_for_hash_table_stats = 0 a 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.
  • LazyReadReplacingFinalSource now constructs real StatsCollectingParams (same pattern as Planner), so the dedup aggregation also benefits from size hints on repeated FINAL queries.
  • setAggregationHashTableCacheKeys skips steps whose builder left stats_collecting_params unconfigured, so no query collects statistics that are guaranteed to be thrown away.

Tests, both of which fail on the unfixed code:

  • gtest_hash_tables_statistics covers the invariant directly for both entry types (AggregationEntry and HashJoinEntry): a caller that keeps no entries must leave the statistics usable for every later caller.
  • The stateless test 04869_lazy_final_hash_table_stats_cache runs the first-toucher scenario deterministically in clickhouse-local (a fresh process owns a fresh statistics cache): the lazy FINAL query runs first, then a 650000-group victim aggregation twice; the second run must preallocate, observed through the AggregationPreallocatedElementsInHashTables event in system.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 the Lazy FINAL enabled trace 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, 04518 and the lazy FINAL family (03988, 03990, 03991, 04092, 04093, 04095, 04105, 04207, 04493, 04517, 04539) pass.

🤖 Generated with Claude Code

Version info

  • Merged into: 26.8.1.1381 (included in 26.8 and later)

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]>
@clickhouse-gh

clickhouse-gh Bot commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [4c79890]

Summary: ✅


AI Review

Summary

This PR fixes the lazy FINAL first-touch regression that could seed the process-wide hash-table statistics cache with zero capacity and silently disable later aggregation preallocation. The current head addresses that centrally in HashTablesStatistics, wires real StatsCollectingParams into LazyReadReplacingFinalSource, avoids stamping aggregation cache keys for steps that cannot retain stats, and adds focused unit and stateless coverage. I did not find any remaining correctness, safety, or test-evidence issues in the current diff.

Final Verdict

✅ No further findings.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.70% 86.70% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 79.10% 79.10% +0.00%

Changed lines: Changed C/C++ lines covered: 56/56 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 13, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 4c7989010 with master fb565a7db (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 691.76 MiB 688.75 MiB -3.01 MiB (-0.44%)

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

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

Job report

robot-clickhouse and others added 2 commits August 13, 2026 18:31
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]>

@alexey-milovidov alexey-milovidov left a comment

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.

LGTM

@alexey-milovidov alexey-milovidov self-assigned this Aug 13, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 13, 2026
Merged via the queue into master with commit be34416 Aug 14, 2026
182 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-lazy-final-hash-table-stats-cache branch August 14, 2026 00:51
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 14, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Aug 14, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-bugfix Pull request with bugfix, not backported by default 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.

2 participants