Skip to content

Cache statistics per data part and column instead of per set of parts - #120758

Merged
alexey-milovidov merged 35 commits into
masterfrom
statistics-cache-per-part
Oct 16, 2026
Merged

alexey-milovidov merged 35 commits into
masterfrom
statistics-cache-per-part

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Sep 18, 2026 •

Copy link
Copy Markdown
Member

Closes: #120693

The statistics of the columns of MergeTree data parts are now cached per data part and column in a new StatisticsCache (a CacheBase, like PrimaryIndexCache), 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:

  • The background refresh task and the merge-tree setting refresh_statistics_interval are 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.
  • The session setting use_statistics_cache is obsolete: the cache is always on and is sized by the new server settings statistics_cache_size (1 GiB by default), statistics_cache_policy, statistics_cache_size_ratio. It can be cleared with SYSTEM DROP STATISTICS CACHE, observed through StatisticsCacheBytes, StatisticsCacheCells, StatisticsCacheHits, StatisticsCacheMisses, and LoadedStatisticsMicroseconds is now non-zero only on a genuine miss.
  • An optional prewarm with the same shape as prewarm_mark_cache: the merge-tree setting prewarm_statistics_cache (off by default) loads the statistics of new parts and of all parts at startup into the cache, bounded by statistics_cache_prewarm_ratio.
  • ConditionSelectivityEstimatorBuilder no 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.
  • The EXPLAIN WHATIF estimator and the per-part getEstimates load through the same cache.
  • An entry is weighted by the memory retained by the statistics objects (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):

  • Performance Improvement

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Column statistics of MergeTree data parts are cached per data part and column in a new statistics cache (server settings statistics_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 settings refresh_statistics_interval and use_statistics_cache are obsolete. A new merge-tree setting prewarm_statistics_cache optionally prewarms the cache for new parts and on startup.

🤖 Generated with Claude Code


Workflow [PR]
Sync PR [sync-upstream/pr/120758]

Version info

  • Merged into: 26.11.1.98-master (included in 26.11 and later)
  • Backported to: 26.10.2.71

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

clickhouse-gh Bot commented Sep 18, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [16a1e3a]

Summary: ✅


AI Review

Summary

The 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
  • ⚠️ No built clickhouse binary is available in this checkout, so runtime reproduction and a fresh performance-metrics fetch were unavailable. The findings below follow concrete source traces; performance measurements are available in the existing discussion.
Findings

⚠️ Majors

  1. Composite values can exceed the configured statistics-cache memory limit. Statistics.cpp:203–207: IStatistics::fieldAllocatedBytes counts only top-level strings. A supported basic statistic for Tuple(FixedString(65536)) retains a tuple containing a separately allocated 65536-byte default string, but reports zero for that entire field. Across many part/column entries, actual memory can therefore exceed statistics_cache_size many times while eviction and prewarm consider it below the limit. Count container storage and recursively retained fields, or avoid retaining the default field. Existing open thread.

  2. Copying the first part changes older statistics and discards subsequent compatible parts. ConditionSelectivityEstimator.cpp:627–628: cloneEmpty reconstructs collectors from their descriptions. An older basic blob without DefaultCount deserializes with has_default_count = false, whereas the new accumulator starts with it set to true; StatisticsBasic::merge never adopts the source flag. A column containing only zeros can consequently acquire a fabricated exact default count of zero. A second old part then fails structureEquals, dropping its min/max and distinct-value statistics as well. This regresses join-order, PREWHERE, and EXPLAIN WHATIF estimates for existing parts. Preserve the deserialized capabilities when copying, or adopt them on the first merge. Existing open thread.

Tests
  • ⚠️ Extend cache-weight coverage to basic statistics on a composite type: increasing the nested FixedString length must increase the reported retained memory accordingly.
  • ⚠️ Add a valid older basic blob lacking DefaultCount; verify the first-part estimate and accumulation of a second such part.
Final Verdict

Status: ⚠️ Request changes. Account for composite allocations and preserve deserialized statistics capabilities, with the focused regression coverage above. Both findings already have open inline threads; no duplicate comments were posted.

@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Sep 18, 2026
alexey-milovidov and others added 2 commits September 18, 2026 10:52
…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]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit 16a1e3a774913eb13960a4e0f630555075e1390d was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception).

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]>
alexey-milovidov and others added 3 commits September 27, 2026 03:34
…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]>
alexey-milovidov and others added 4 commits October 3, 2026 12:37
# 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]>
alexey-milovidov and others added 5 commits October 5, 2026 03:57
…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]>
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 16, 2026
Merged via the queue into master with commit 45ccaa5 Oct 16, 2026
179 checks passed
@alexey-milovidov
alexey-milovidov deleted the statistics-cache-per-part branch October 16, 2026 19:18
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 16, 2026
@arsenmuk arsenmuk removed their assignment Oct 17, 2026
alexey-milovidov pushed a commit to JayPokale/ClickHouse that referenced this pull request Oct 19, 2026
…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]>
alexey-milovidov added a commit to groeneai/ClickHouse that referenced this pull request Oct 20, 2026
…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]>
@robot-ch-test-poll robot-ch-test-poll added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Oct 21, 2026
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Oct 21, 2026
clickhouse-gh Bot added a commit that referenced this pull request Oct 21, 2026
Backport #120758 to 26.10: Cache statistics per data part and column instead of per set of parts
@hanfei1991 hanfei1991 self-assigned this Nov 11, 2026
@groeneai

Copy link
Copy Markdown
Collaborator

@alexey-milovidov, this PR made query planning about 100x slower on tables whose parts still carry the legacy uniq statistics. That covers tables created on 26.4-26.6 with the default auto_statistics_types = 'minmax, uniq' and not rewritten since, a profile compatibility <= 26.6, or an explicit uniq in that setting. #120693 already notes that combining on the fly is cheap only for uniq_v2. Here is what it costs for the old type.

Setup: ReplacingMergeTree with 120 parts of 80,000 rows (written by 26.8), SELECT count() with a WHERE on 6 high-cardinality columns, run in clickhouse local with a warm statistics cache. Each number is the median of 8 runs after 2 warm-ups. QPO is QueryPlanOptimizeMicroseconds.

minmax, uniq basic, uniq_v2
26.8.38.10 QPO 3.2 ms, query 18 ms 3.0 ms, 17 ms
26.10.5.25 333 ms, 348 ms 6.5 ms, 20 ms
master 4553bee2f6f (*) 363 ms, 379 ms 4.3 ms, 17 ms

(*) With min_marks_per_part_to_load_statistics = 0, so the statistics are loaded. With the default, master skips loading them for this small read (#126627), but only while they are not cached: after one query loads them, every default-settings query plans in 325-363 ms. It is the same through a view with ARRAY JOIN (26.10: 389 ms vs 5 ms).

perf: UniquesHashSet::merge under ConditionSelectivityEstimatorBuilder::addStatistics takes 39% of all samples over 10 runs, and 89% of that is the scan of the source buffer. A saturated state has a 512 KiB buffer (2^17 slots), so each query scans about 300 MiB. StatisticsCacheBytes is 414 MB for these 600 cells. A standalone benchmark of the same loop runs at 100-250 microseconds per state, with or without branches, so a faster loop cannot get back to 26.8.

Upgrading alone does not help existing tables. After MODIFY SETTING auto_statistics_types = 'basic, uniq_v2' plus 120 new parts, the first part is still an old one: the estimator merges the 120 legacy states, skips the new ones, and planning takes 316 ms. Adding MATERIALIZE STATISTICS ALL brings 26.10 down to 5.9 ms planning and 19 ms per query.

Which one do you want?

  1. thin: when a legacy uniq state enters the statistics cache, raise its skip degree until it holds at most ~4096 hashes (about 1.6% error, the same as uniq_v2). A merge then reads 32 KiB instead of 512 KiB. The files on disk stay unchanged.
  2. cache: keep a merged estimate per set of parts, for legacy uniq columns only.
  3. docs: no code. The remedy for such tables is MODIFY SETTING auto_statistics_types = 'basic, uniq_v2' plus MATERIALIZE STATISTICS ALL.

I would do 1.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

The legacy uniq statistics is a design mistake, and I warned about this mistake multiple times. No need to change anything for it.

subkanthi pushed a commit to subkanthi/ClickHouse that referenced this pull request Nov 18, 2026
… 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
@clickhouse-gh clickhouse-gh Bot added comp-statistics Column statistics: statistics kept per part on a column (tdigest, uniq, count-min sketch, minmax)... and removed comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Nov 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-statistics Column statistics: statistics kept per part on a column (tdigest, uniq, count-min sketch, minmax)... pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo v26.10-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Rewrite the statistics cache: cache per data part on demand, instead of caching combined statistics per set of parts

8 participants