Repository navigation
Cache statistics per data part and column instead of per set of parts - #120758
Conversation
The condition selectivity estimator cached the combined statistics of the whole set of active parts, refreshed it from a background task, and loaded the statistics of every part synchronously in the query whenever the part set did not match, so a query over a pruned part set never hit the cache. Now the statistics of a column of a data part are cached in a new `StatisticsCache` (a `CacheBase`, like `PrimaryIndexCache`), loaded on demand by the first query that needs them and evicted by size. A data part is immutable, so an entry never becomes stale: a new part is a miss and a removed part has its entries removed. Every query merges the cached statistics of its parts on the fly, into a fresh copy, so the shared entries are never modified. The background refresh task and the setting `refresh_statistics_interval` are gone (obsolete), as is the session setting `use_statistics_cache`. The cache is configured by the server settings `statistics_cache_size`, `statistics_cache_policy`, `statistics_cache_size_ratio`, cleared by `SYSTEM DROP STATISTICS CACHE`, and observed through `StatisticsCacheBytes`, `StatisticsCacheCells`, `StatisticsCacheHits`, `StatisticsCacheMisses`. The merge-tree setting `prewarm_statistics_cache` optionally loads the statistics of new parts and of all parts at startup into the cache. Closes: #120693 Co-Authored-By: Claude Fable 5.1 <[email protected]>
|
Workflow [PR], commit [16a1e3a] Summary: ✅
AI ReviewSummaryThe PR replaces the combined statistics snapshot and background refresh with a bounded, on-demand cache per data part and column, plus optional prewarming. Request changes: retained memory is still undercounted for composite values, and the new estimator accumulator changes the capabilities of older statistics. Missing context / blind spots
Findings
Tests
Final VerdictStatus: |
…r 26.10 Report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=120758&sha=05ee00a9ccffcccebeef9e4622f75100ec12f83a&name_0=PR&name_1=Style%20check PR: #120758 - clang-tidy: `StatisticsCacheCell::memory_bytes` was not initialized. - The style check requires `prewarm_statistics_cache` to be recorded in the `26.10` block of `SettingsChangesHistory.cpp` after the version bump on master. - Renumber the new test to `05227`, since master already has tests with `05218`. Co-Authored-By: Claude Fable 5.1 <[email protected]>
Build profile diff (arm_release)Commit See the job log for details. |
…r-part Resolve the conflict with the move of the settings changes history into the setting declarations (ee6b44f): the history records this PR added to `SettingsChangesHistory.cpp` now live as trailing arguments of the `DECLARE` of each setting. Also resolved conflicts in: - `src/Storages/StorageMergeTree.cpp` Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…LAIN WHATIF`, isolate the global cache drop - `forcefullyMovePartToDetachedAndRemoveFromMemory` now clears the caches of the part, which are keyed by the path of the active part, so a later part with the same name does not see stale statistics. - `tryEstimateWithStatistics` counts every analyzed part towards the baseline row count, like `getConditionSelectivityEstimator`, not only the parts with statistics for the filter columns. - Remove the outdated sentence about `refresh_statistics_interval` from `table_readonly`. - Move `SYSTEM DROP STATISTICS CACHE` out of `05227_statistics_cache_per_part` (it clears a server-wide cache and made the test flaky in the flaky check) into a new `no-parallel` test `05259_statistics_cache_drop`, which also checks `ACCESS_DENIED` for the local and the `ON CLUSTER` spellings; add the command to the `ON CLUSTER` access mapping test. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
With randomized `query_plan_optimize_prewhere = 0` the query does not build the selectivity estimator, so it loads no statistics at all. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
# Conflicts: # src/Storages/MergeTree/MergeTreeData.cpp # src/Storages/MergeTree/MergeTreeSettings.cpp # tests/queries/0_stateless/04516_join_order_estimation_pruned_parts.sql # tests/queries/0_stateless/05182_prewhere_partition_statistics.sql # tests/queries/0_stateless/05183_prewhere_statistics_throwing_partition.sql
The prewarm runs after the part is committed (insert, merge, fetch), so a failure to read the statistics must not fail an `INSERT` that has already made its part visible: a client retry would duplicate the data. Log the error and leave the statistics to be loaded on demand. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Checks that the first query after an insert and after attaching the table reads no statistics from disk when the prewarm is enabled. Co-Authored-By: Claude Opus 5.5 <[email protected]>
`03707_statistics_cache`: `ALTER TABLE ... MATERIALIZE STATISTICS` is asynchronous by default, so the join query could run before the parts had statistics and load nothing. Set `mutations_sync = 2`. `05227_statistics_cache_per_part`: a randomized `max_insert_threads` can split an insert into several parts, and a merge between the queries makes a new part, which is a cache miss for the "warm" query. Set `max_insert_threads = 1`. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=120758&sha=b03bc24fd6363be7daad14e1ccd2f6b57082bcc5&name_0=PR #120758 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…rectly When `loadStatistics` is called with a non-empty set of required columns, build the statistics file name of each required column (and of the parent column for a `<col>.null` subcolumn) and probe the packed archive index or the checksums, instead of scanning and unescaping the statistics file list of every column of the part. The full scan remains only for loading all columns. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…he_prewarm` Both tests expect the statistics cache to keep the entries between two queries. In CI, a concurrent test dropped tables of an `Ordinary` database (tables without UUID) in between, and `MergeTreeData::dropAllData` calls `Context::clearCaches` for such tables, which clears the whole statistics cache. The insert prewarmed the cache (`StatisticsCacheMisses` = 2 for the insert), but the following query loaded everything from disk. Mark the tests `no-parallel`, like the other tests of cache prewarming. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=120758&sha=097b17c2b42b7167220b65defff9d966faebbca2&name_0=PR&name_1=Stateless%20tests%20%28arm_asan_ubsan%2C%20targeted%29 #120758 Co-Authored-By: Claude Opus 5.5 <[email protected]>
The cache keys are derived from `getFullRootPath` of the part storage, which `renameToDetached` changes to the `detached` directory, so calling `clearCaches` after the rename computed keys that never matched the entries inserted while the part was active. Evict before the rename: the part is already `Deleting` there. Co-Authored-By: Claude Opus 5.5 <[email protected]>
`clearCaches` is one-shot, but `loadStatistics` still inserted into the `StatisticsCache` afterwards, so a query holding a force-detached part could repopulate entries under the active-part key that nothing evicts later. Bypass the cache once `cleared_data_in_caches` is set, and re-check the flag after the insertion to close the race with a concurrent `clearCaches`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ight-table column The hash join probe loops called the out-of-line AddedColumns::appendFromBlock for every matched row. When the join outputs no column of the right table, record_row_refs is false and the callee returned immediately, but the call stayed in the loop, and its cost depended on where the linker placed the loop and the callee: join_squashing_blocks #0/ClickHouse#1 ran 17-20% slower in about one build in 64 (the amd_release reds on ClickHouse#122184 and ClickHouse#120758), and 1.4x slower in some process starts. Make appendFromBlock ALWAYS_INLINE so the record_row_refs test happens in the loop, and keep the recording part, LazyOutput::addRef, out of line with NO_INLINE: inlining its body into every probe loop made hashjoin_low_cardinality_key #0 5-10% slower and pushed processMatch out of line, even in loops where addRef never runs. Joins that record row refs keep one call per match, to the same body as before. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…and `cloneEmpty` structure Address two review comments left on ClickHouse#120758 after it was last updated: - `IStatistics::fieldAllocatedBytes` returned zero for `Array`, `Tuple`, `Map`, `Object` and `AggregateFunctionState` fields. The `basic` statistics of a `Tuple(FixedString(N))` column retain the column default, a tuple with an N-byte string, so the statistics cache could hold many times its limit. Count the container storage and the nested values recursively. - `ColumnStatistics::cloneEmpty` recreated the statistics from their descriptions, so the empty accumulator of the selectivity estimator did not keep the structure of `basic` statistics loaded from an older format without a default-value count: it got a fabricated exact count of zero defaults (`x = 0` estimated to match no rows), and every following such part was discarded as incompatible. Add `IStatistics::copyStructureFrom` and use it in `cloneEmpty`, so that the clone is always compatible with the original. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Backport #120758 to 26.10: Cache statistics per data part and column instead of per set of parts
|
@alexey-milovidov, this PR made query planning about 100x slower on tables whose parts still carry the legacy Setup:
(*) With
Upgrading alone does not help existing tables. After Which one do you want?
I would do 1. |
|
The legacy uniq statistics is a design mistake, and I warned about this mistake multiple times. No need to change anything for it. |
… 26.6 `auto_statistics_types` was `minmax, uniq` in 26.4 to 26.6 and `basic, uniq_v2` since 26.7. Instances pinned to `compatibility` 26.4 to 26.6 keep building `uniq` statistics in newer versions, and since ClickHouse#120758 every query merges the large `uniq` state of each part, so query plan optimization is about 20x slower (reproduced on plain `ReplacingMergeTree`: 27-43 ms on 26.8, 505-961 ms on 26.10 with 120 parts). With `basic, uniq_v2` there is no regression. Record the 26.7 change at 26.4, so `compatibility` with 26.4 to 26.6 gives `basic, uniq_v2`. Statistics affect only query planning, not results. Existing parts are converted by merges, which rebuild the statistics of a source part whose statistics differ from the table's. Related: ClickHouse/clickhouse-private#88364
Closes: #120693
The statistics of the columns of
MergeTreedata parts are now cached per data part and column in a newStatisticsCache(aCacheBase, likePrimaryIndexCache), instead of caching the combined statistics of the whole set of active parts. A data part is immutable, so an entry never becomes stale: a new part is a miss, and the entries of a removed part are removed. Every query merges the cached statistics of its parts on the fly, which is cheap (a few registers per column per part), so a query over the parts left after partition or primary-key pruning hits the cache exactly as a full-scan query does, and the statistics of a part are read from disk once, by the first query that needs them.Consequently:
refresh_statistics_intervalare gone (the setting is kept as obsolete). Nothing loads all statistics of all columns of all parts anymore; a query loads only the missing parts for the columns it needs.use_statistics_cacheis obsolete: the cache is always on and is sized by the new server settingsstatistics_cache_size(1 GiB by default),statistics_cache_policy,statistics_cache_size_ratio. It can be cleared withSYSTEM DROP STATISTICS CACHE, observed throughStatisticsCacheBytes,StatisticsCacheCells,StatisticsCacheHits,StatisticsCacheMisses, andLoadedStatisticsMicrosecondsis now non-zero only on a genuine miss.prewarm_mark_cache: the merge-tree settingprewarm_statistics_cache(off by default) loads the statistics of new parts and of all parts at startup into the cache, bounded bystatistics_cache_prewarm_ratio.ConditionSelectivityEstimatorBuilderno longer merges the parts into the first part's statistics in place (which would have corrupted a shared cache entry): it accumulates into a fresh copy.EXPLAIN WHATIFestimator and the per-partgetEstimatesload through the same cache.IStatistics::allocatedBytes: arenas, aggregate function states, centroids, counters), not by their serialized size, and statistics loaded into the cache are not charged to the query's or user's memory tracker, like marks and the primary index.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Column statistics of
MergeTreedata parts are cached per data part and column in a new statistics cache (server settingsstatistics_cache_size,statistics_cache_policy,statistics_cache_size_ratio;SYSTEM DROP STATISTICS CACHE), loaded on demand and merged on the fly for every query. Queries over a pruned set of parts no longer re-read statistics from disk on every execution, and there is no background task that loads the statistics of all columns of all parts. The settingsrefresh_statistics_intervalanduse_statistics_cacheare obsolete. A new merge-tree settingprewarm_statistics_cacheoptionally prewarms the cache for new parts and on startup.🤖 Generated with Claude Code
Workflow [PR]
Sync PR [sync-upstream/pr/120758]
Version info
26.11.1.98-master(included in26.11and later)26.10.2.71