Skip to content

Reuse loaded part statistics within a query - #116348

Closed
groeneai wants to merge 11 commits into
ClickHouse:masterfrom
groeneai:reuse-loaded-part-statistics-within-query
Closed

groeneai wants to merge 11 commits into
ClickHouse:masterfrom
groeneai:reuse-loaded-part-statistics-within-query

Conversation

@groeneai

@groeneai groeneai commented Aug 25, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #116134
Related: #115998

Changelog category (leave one):

  • Performance Improvement

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

A query reading the same MergeTree table many times, such as a UNION ALL of many branches, now collects and merges the column statistics of the table's data parts once instead of once per read. The merged statistics are reused for the rest of the query, keyed on the table, the parts read and the columns required, so estimates are unchanged. The number of entries one query keeps is limited by the new setting statistics_cache_max_entries.

Description

Reported by @ Avogar on #116134 while measuring the #115998 reproducer: planning a 1500-branch UNION ALL got slower because every branch asks for a selectivity estimator over the same part set, and each one loaded the statistics of every part again.

Since this PR was opened, master replaced the table-wide statistics cache with a StatisticsCache of the statistics of each column of each data part (05ee00a). That removes the repeated reads from disk, but each read still collects the statistics of every part and merges them into a new estimator. This PR now removes that repetition.

The change. MergeTreeData::getConditionSelectivityEstimator keeps the merged statistics (the estimator's payload) in a cache owned by the query context. The key is the storage, the ordered part names, and the required columns as a sorted deduplicated set (loadStatistics reads them as a set). Each caller still gets its own estimator, bound to its own context, over the shared payload. Sharing is safe because the builder merges into its own copies of the statistics and nothing modifies a payload once it is built.

The limit. statistics_cache_max_entries (default 1024, 0 disables the reuse) counts entries, not bytes, and the size of an entry grows with the number of columns and the statistics types declared on them. Once full, the cache is not evicted: reads needing statistics it does not hold merge them again. The cache dies with the query.

Tests. 04651_statistics_loaded_once_per_query counts LoadedStatistics, the parts collected for an estimator, which on master grows with the number of reads. It checks that the count stays flat in the number of branches, grows again without reuse and when the limit leaves no room, distinguishes tables with the same part names, part sets of the same size, and column sets given in a different order, and that the join path reuses too. The performance test statistics_load_many_reads measures the planning time of the many-branch query.


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

@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-follow-up PR origin: groeneai's own out-of-scope finding during its PR work labels Aug 25, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review

Reviewed cold against the code on disk, then re-reviewed by an independent model, over five
rounds. Nothing below is outstanding at publication.

# Severity Finding Verdict
1 ⚠️ major The cache inserted every miss without eviction, so a query whose reads never share a key held every merged payload it ever built. ❌ AGREE, fixed. Added statistics_cache_max_entries (default 1024, 0 disables); once full, further keys load as if reuse were off. Nothing is evicted, so an entry a caller already reused cannot vanish mid-query.
2 ⚠️ major The key copied Names verbatim with order-sensitive equality, so two callers naming the same columns in a different order missed each other. ❌ AGREE, fixed. Required columns are held sorted and deduplicated. This is exact, not approximate: IMergeTreeDataPart::loadStatistics already reads that argument as a NameSet.
3 ⚠️ major KeyHash hashed each name vector as its element count followed by raw bytes. SipHash::update for a string appends bytes only, so the count separates vectors of different length but not different splits of one concatenation: {a, bc} and {ab, c} produced an identical byte stream. Estimates stayed correct, since key equality is exact, but colliding keys share a bucket and equality then walks the vectors. ❌ AGREE, fixed. Every hashed name is length-prefixed in both loops, matching the existing pattern in MergeTreeDataSelectExecutor. A unit test pins it, with a same-key control so the assertion is about the split and not about hash instability.
4 ⚠️ major Three separate test-liveness gaps: the capped query repeated one key rather than several, so deleting the bound changed nothing; every repeated branch used identical parts, so removing the part names from the key changed nothing; and the join path's use of the cache had no oracle at all. ❌ AGREE, all three fixed. The limit now has an arm alternating two column sets under a limit of one, compared against an uncapped control by exact load bytes. Part names are pinned by two partitions of equal part count but different row count, so a payload answered from the wrong one prints a visibly wrong estimate. The join path gets a cache-on/cache-off byte pair plus a statistics-off arm proving the measured bytes are statistics and not the EXPLAIN text. Each cell was confirmed to fail when the corresponding enforcement is deleted.
5 ❌ blocker statistics_cache_max_entries was recorded in the 26.8 block of SettingsChangesHistory.cpp, but this tree is 26.9, so check_settings_changes_history would have failed and the rendered settings history would have named the wrong release. ❌ AGREE, fixed. The record moved verbatim into a 26.9 block. Verified with the real check_style.py gate on both arms, which is stronger than a simulation: the gate also flags every setting in a block whose header line changed, and this diff does rewrite a header line. It does not fire; the extractor reports exactly one changed setting.
6 💡 nit Comment literals not wrapped in inline code, against the repository instruction. ❌ AGREE, fixed.

Also checked and found sound: the payload is handed out as shared_ptr<const> and every
statistics method the estimation path calls is const, so one payload cannot be mutated through
two estimators -- which matters here because the merge aliases the first part's statistics object
and mutates it in place, so merging into a published payload twice would double-count. Each caller
keeps its own estimator, because estimation reads settings through the context it is bound to. The
only mutable state anywhere below a shared payload is an atomic memoization of a uniq sketch's
cardinality, so concurrent estimators are safe. isCompatibleStatistics still guards every read,
so a payload merged for one caller cannot leak type-incompatible statistics to another. The cache
is owned by the query context and the accessor returns null where there is none, so it cannot
outlive the query or be created twice per query. The get/load/set sequence is deliberately not
atomic, which can only duplicate a load, never return a wrong payload. The storage pointer in the
key is compare-only and the storage outlives the query context. Reuse is consulted only after the
existing table-wide cached_estimator check and never writes it, so the pruned-scope and
warm-cache behaviour the existing tests pin is unchanged.

@clickhouse-gh clickhouse-gh Bot closed this Aug 25, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Aug 25, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. 1500-branch UNION ALL over a frozen 9-part / 10M-row table, keys that match no row so read_rows = 0: 85573500 bytes and 1119973 us of statistics loading, on demand. Arming is asserted, not assumed: the load fires only while cached_estimator is unpublished, so LoadedStatisticsMicroseconds > 5e5 and ReadCompressedBytes > 8e7 are checked on the pre-fix arm before any number is reported. One run was discarded for reading zero on an unarmed base server.
b Root cause explained? Yes. MergeTreeData::getConditionSelectivityEstimator memoizes only in cached_estimator, which only the background refreshStatistics task writes; until it publishes, the per-query path runs the load loop and stores nothing, and IMergeTreeDataPart::loadStatistics has no cache of its own. Each read of the table reaches this once from optimizePrewhere via ReadFromMergeTree, where analyzed_result_ptr is still null so the full part set is loaded. N reads therefore perform N full loads.
c Fix matches root cause? Yes: memoization at the seam that repeats. No widened bound, no no-random-* tag, no reduced dataset, no guard masking an upstream bug. It changes no estimate, no plan and no result.
d Test intent preserved / new tests added? Yes. New stateless test 04651_statistics_loaded_once_per_query plus a tests/performance case for the many-reads shape. Each of the three key components, and the entry limit, has an arm that stops holding when that piece is removed - proven by running the shipped test against a build with the table identity dropped, one with the column set left unsorted, and one with the limit not enforced; each fails the shipped test in its own cell and nowhere else. The two tables of the table-identity arm carry the same four part names so only row count separates them. Part names are pinned on the join path, where pruning does reach the key: two relations pruned to different single partitions must report their own row counts, and a mutant that replaces every part name with a placeholder fails that arm alone, with both its controls unmoved. The join path's consultation of the reuse is covered separately, because every estimate it prints is correct whether reuse happened or each relation loaded independently: a cache-on / cache-off byte pair on the same-partition join shape reads 3258 against 9774 bytes (three callers collapsing to one, measured), with a statistics-off arm reading 0 to show those bytes are statistics and not the plan text an EXPLAIN also produces. Deleting the consultation reddens that cell; the placeholder-name mutant leaves it unmoved while still reddening the part-name arm, so the two cover different properties. A gtest covers the key hash, whose length prefixes no SQL oracle can observe; its own liveness is proven by removing them and watching it print the collision. No existing statistics test was weakened or removed: the statistics suite (78 tests) was rerun on both binaries and fails identically on each (58 OK / 7 FAIL, no test failing only on the fix).
e Both directions demonstrated? Yes. Same repro, two builds with distinct verified Build-IDs: pre-fix reads 57049 bytes per branch (linear in N across 100 / 400 / 1500), post-fix 57049 bytes in total (flat). The new test passes 50/50 under randomized settings on the fix; on pristine HEAD it fails 20/20 on the memoization properties themselves. Each key component, the entry limit, and the cache consultation additionally has its own mutant that reddens the shipped artifact. The 50/50 run also caught a flake in the new consultation arm and it was root-caused rather than absorbed: clickhouse-test randomizes enable_join_runtime_filters false in 5% of runs, which removes the third caller and makes the ratio 2 (3 failures in 50, all with the setting false). It is now pinned on those three queries, and the pin is proven load-bearing in both directions - with the setting forced false the test passes with the pin and fails without it.
f Fix is general across code paths? Yes. The memo lives in MergeTreeData, the callee that owns every piece of the semantics, so all four estimator callers benefit: optimizePrewhere, optimizeJoin, Cascades/StatisticsDerivation, and the direct IStorage caller. No MergeTree flavour overrides either accessor, so Replicated and Shared inherit it. Fixed at the source, not guarded at one call site.
g Fix generalizes across inputs (params/datatypes/wrappers)? The key is exact by construction: storage identity, ordered part names, and the required columns as a canonical set (the loader reads them as a set, and callers derive their vectors differently, so two orders of one set share an entry while genuinely different sets do not). Verified for a pruned vs full part set, two tables with identical part names, the same table read four times in one query, opposite-order and different-set column lists, and a parts-carry-no-statistics outcome (cached as a null payload so that answer is reached once too). The parts.empty() early return still precedes the memo.
h Backward compatible? Yes. One new setting, statistics_cache_max_entries (UInt64, default 1024), recorded in the SettingsChangesHistory.cpp 26.9 block (the tree's current version, per cmake/autogenerated_versions.txt); setting it to 0 reaches the pre-fix behaviour exactly. No changed default, no serialization or on-disk format change. use_statistics = 0 is unaffected, and use_statistics_cache = 0 keeps its exact current "do not reuse" meaning, which is asserted as a negative control that must stay slow.
i Invariants and contracts preserved? The merged payload is shared_ptr<const> and unreachable from any mutating path once published, which is what keeps the alias-then-mutate merge from double-counting on reuse; asserted by comparing estimates on the first and the last of four readers of one table. The cache mutex is never held across loadStatistics (load first, insert afterwards under a fresh lock), so no lock-ordering edge against stats_mutex or readLockParts. The carrier is owned by the query context and dies with the query, so no query-local part set reaches server-wide state. Entry count is bounded inside QueryStatisticsCache::set under that same mutex, so peak memory on reads that cannot share returns to its former level (measured 8747592 bytes against 8725944 with reuse off); deleting that bound makes the shipped test fail. Key names are length-prefixed when hashed, so two vectors whose names concatenate alike no longer share a bucket; equality was already exact, so this changed no estimate.

Session id: cron:clickhouse-impl-slot-41:20260825-115100

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @hanfei1991 @vdimir, could you review this? MergeTreeData::getConditionSelectivityEstimator memoizes only in cached_estimator, which only the background refreshStatistics task writes, so until it publishes every read of a table re-loads and re-merges every part's statistics during plan optimization. This memoizes the merged payload for the rest of the query, keyed on the table, the ordered part names and the required columns as a set, so estimates are unchanged.

@hanfei1991

Copy link
Copy Markdown
Member

@groeneai We have had StatisticsCache per MergeTree, Why do we need another QueryStatisticsCache?

@groeneai

Copy link
Copy Markdown
Collaborator Author

Different scope, and I checked it rather than assuming: cached_estimator is per table and holds exactly one part set, the full active snapshot as of the last refreshStatistics. getConditionSelectivityEstimator returns it only when isStale says the query reads that same ordered part set (MergeTreeData.cpp:924-936). Any other case falls through to the load loop, which stores nothing, and IMergeTreeDataPart::loadStatistics has no cache of its own, so each caller in a query repeats it.

Measured on this branch's binary, one table, four reads in one query, four parts, ReadCompressedBytes with read_rows = 0 so the bytes are statistics only:

state of the per-table cache reuse off reuse on
warm, query reads the full active set 0 0
stale (one INSERT later) 127320 31830
stale, repeated on a fresh part 152784 38196

Control: use_statistics_cache = 0, which disables both, reads 101856.

So the existing cache already covers the case it is built for, and the query-scoped one only pays where that one has nothing to give: before the first refresh publishes, and after every insert until the next one does. refresh_statistics_interval defaults to 300s, so on a table being written to that window is most of the time. The reuse is consulted after the cached_estimator check and never writes it, so the warm path is byte for byte what it was.

Two properties keep them from being the same object rather than one being redundant: lifetime, since a query-local entry is keyed on a pruned part set that is not the table's active snapshot and must not outlive the query, and bounding, since a query reading many different part sets accumulates entries, which is why statistics_cache_max_entries exists.

The PR description said only "until it publishes", which is what invited the question. I have corrected it to name staleness too.

`MergeTreeData::getConditionSelectivityEstimator` memoizes only in
`cached_estimator`, which holds the active-part snapshot seen by the last
refresh. Every other part set - a pruned one, and any set at all until that
first refresh publishes - loads and merges statistics again, once per caller.
A query that reads the same table many times has that many callers: each
branch of a `UNION ALL`, each relation of a join, and the join runtime
filter. On the 1500-branch `UNION ALL` of ClickHouse#115998 that is 1500 loads of the
same statistics.

The merged statistics are now a `shared_ptr<const Payload>` that estimators
share, and the query context carries a small cache of them keyed on the
storage, the ordered part names, and the required columns in canonical set
form. A part name carries partition and block info but no table identity,
which is why the storage is part of the key, and the loader reads the column
names as a set, which is why they are sorted and deduplicated. Estimators
stay per caller, because estimation reads settings through the context an
estimator is bound to.

The payload is immutable once published: the merge aliases the first part's
statistics object and mutates it in place for the remaining parts, so a
payload a builder could still reach would accumulate row counts and sketches
on every reuse.

`statistics_cache_max_entries` (default 1024) bounds the cache, so a query
whose reads never share statistics holds a bounded number of payloads rather
than every one it ever built; 0 disables the reuse. The existing
`use_statistics_cache` still switches statistics caching as a whole.

Tests: `04651_statistics_loaded_once_per_query` measures
`ProfileEvents['ReadCompressedBytes']` per query and asserts that the load
happens once however many branches ask for it, that it happens per branch
again with reuse off and when the limit leaves no room, and that the key
discriminates the table, the ordered part names and the column set. A gtest
covers the key hash, whose names are length-prefixed so that two vectors
whose names concatenate equally do not collide. `statistics_load_many_reads`
is the matching performance test.
@groeneai
groeneai force-pushed the reuse-loaded-part-statistics-within-query branch from e16ee78 to 49d7c0c Compare August 26, 2026 15:23
@groeneai

Copy link
Copy Markdown
Collaborator Author

Merged master (the branch was 964 commits behind) and collapsed the branch to one commit.
src/Core/SettingsChangesHistory.cpp is marked merge=union in .gitattributes, which is why
GitHub reported a conflict that git resolves on its own; I checked the result rather than trusting
it, and the 26.9 block holds my entry plus all of master's, with no duplicate version.

Two test fixes while re-checking the tree:

  • join_algorithm = 'hash' is now pinned on the three measured join arms. The third estimator
    caller there is the join runtime filter, which is only attached when the algorithm list names a
    hash-family algorithm, and the stress runner passes a random subset. With
    join_algorithm='partial_merge' the cell read 1 0 1 instead of 1 1 1; with the pin,
    partial_merge, full_sorting_merge, auto and ie_join,partial_merge all pass.
  • The oracle now asserts that every measured query produced a system.query_log row. A missing
    log_comment leaves no group, so maxIf(bytes, ...) read 0 for it and an equality between two
    such counts held vacuously.

Re-dispatch CI: the previous head (49d7c0c) acquired zero CI coverage - its only
workflow run was cancelled 33 minutes after the push and never scheduled a job.
This merge also clears the GitHub mergeability conflict, which is drift in
src/Core/SettingsChangesHistory.cpp (merge=union, so git itself sees no textual
conflict) plus 1141 commits of master churn.
@clickhouse-gh

clickhouse-gh Bot commented Aug 29, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [4c57ead]

Summary: ❌

job_name test_name status info comment
Stress test (amd_debug) FAIL
Received signal 6 (internal) (STID: 4362-43f8) FAIL cidb
Stress test (arm_asan_ubsan) FAIL
Received signal 6 (internal) (STID: 4362-43f8) FAIL cidb

AI Review

Summary

This PR reuses merged MergeTree column statistics within a query, keyed by storage, ordered parts, and a canonical column set, while keeping estimators bound to each caller's context. The functional coverage and post-port performance measurements support the reuse, but the default retention policy still carries the previously reported memory regression. ⚠️ Request changes.

Missing context / blind spots
  • ⚠️ Reviewed head 4c57ead2b2ffc38c77ee18f0511f0d41e19e07a7. Its full CI and performance jobs are pending; the completed reports cover 27a73a3524b5dc5447d04ee7e8fcc67d4e72d9af. No local build or clickhouse binary was available for independent execution. Completed head-specific CI would close this validation gap.
Findings

⚠️ Majors

  • src/Interpreters/QueryStatisticsCache.cpp:51 — The default cache retains large merged payloads even when no key is reused. [dismissed by author -- https://github.com/Reuse loaded part statistics within a query #116348#discussion_r3995778475] The author previously measured approximately 643 MiB of additional retention for 1,024 distinct keys with four countmin columns each. The documentation now accurately describes an entry limit, but the current implementation still retains every payload up to that limit. I still consider this material because previously successful queries can exceed max_memory_usage without receiving any reuse benefit; query-scoped accounting limits the damage by failing the query rather than preventing the regression. Add a byte budget covering payloads and keys, or keep reuse disabled by default until that budget exists. The current ColumnStatistics::allocatedBytes interface makes payload accounting possible without adding the statistics interface discussed in the original thread.
Final Verdict

⚠️ Request changes. The minimum requested change is a byte budget for retained statistics and keys, or a disabled default. The author's rejected tradeoff remains recorded here; no duplicate inline finding or thread reply was posted.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Aug 29, 2026
The estimator constructor moved `context_` into `WithContext`, whose parameter
is a `std::weak_ptr`. Converting from `std::shared_ptr` binds a const
reference, so no move happened and clang-tidy rejected it as
`performance-move-const-arg`. The other 89 `WithContext` initializations in
`src/` pass the pointer directly.

04651_statistics_loaded_once_per_query asserted that the join path reads
exactly three times as many statistics bytes without the per-query cache as
with it. That holds only while all three callers ask about the same part set.
A throwing row limit, which the functional-test profile sets
(`max_rows_to_read` in tests/config/users.d/limits.yaml), makes join-order
estimation analyze ranges via `selectRangesToReadForEstimation`, which does not
memoize its result, so a caller reading that memo falls back to the whole part
set and asks about a second entry. On the fixture one partition costs 3258
bytes and both cost 5111, so the arms read 8369 with the cache and 11627
without, instead of 3258 and 9774. Reuse still happens in that configuration
and only the ratio differs, so the three arms pin `max_rows_to_read` and
`max_rows_to_read_leaf` back to their shipped default.

Two more inputs to the same measurements were left to the environment. With
`query_plan_join_swap_table` set to true the plan prints both relations of every
measured join the other way round, contradicting the five asserted
`a[100000] ⋈ b[700]` lines; tests/clickhouse-test randomizes it over auto and
false and the stress profile adds true, so all eight measured join queries pin
it. And a `compatibility` version, which the stress profile gives a fifth of its
workers, rolls back 168 settings including the plan renderer that prints that
symbol and the join-order search itself, so the file pins `compatibility` empty.
Each pin was checked by removing it again: the join symbol lines redden under a
forced swap, and both those lines and the load ratio redden under
`compatibility = '26.3'`.
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI fix for d6f7bb1b, and a memory measurement worth seeing before this merges

Both reds were mine, and the run aborted at the gate, so the other 166 jobs never ran.

Build (arm_tidy). The estimator constructor moved context_ into WithContext, whose parameter
is a std::weak_ptr; converting from std::shared_ptr binds a const reference, so no move happened
and performance-move-const-arg failed the build. 89 of the 90 : WithContext(...) initializations in
src/ pass the pointer directly, mine was the only std::move. Checked with clang-tidy-22 on that
translation unit in both directions, then again with the full .clang-tidy check set: 0 diagnostics.

Fast test / 04651_statistics_loaded_once_per_query. The test asserted that the join path reads
exactly three times as many statistics bytes without the per-query cache as with it. That holds only
while all three callers ask about the same part set. tests/config/users.d/limits.yaml sets
max_rows_to_read for the whole functional-test profile, and a throwing row limit makes optimizeJoin
analyze ranges through selectRangesToReadForEstimation, which deliberately does not memoize, so the
caller that reads that memo falls back to the whole part set and asks about a second key. On the
fixture the pruned set costs 3258 bytes and the whole set 5111, so the arms read 3258 + 5111 against
2 * 3258 + 5111, not 3258 against 3 * 3258. Reuse still happens there, so this was an
over-specified oracle rather than a defect, and the arms pin the limit back to its shipped default.

Checking the rest of the file rather than only the failing line found two more inputs left to the
environment, both of which would have reddened Stress next run: query_plan_join_swap_table = true
prints all five asserted a[100000] ⋈ b[700] lines with the relations reversed, and a random
compatibility version rolls back the plan renderer that prints that symbol. Both are pinned. Each
pin was checked by removing it again, and mutating the cached arm to use_statistics_cache = 0 still
reddens the ratio, so nothing was weakened to make this pass.

The entry cap does not bound memory, and I now have the number. 1024 distinct keys, four
STATISTICS(countmin) columns each, a 1024-branch UNION ALL under EXPLAIN so nothing is read.
Same binary for every arm:

use_statistics_cache / cap peak memory statistics read
0 176.25 MiB 6.15 MiB
1, statistics_cache_max_entries = 0 176.49 MiB 6.15 MiB
1, default cap 1024 819.47 MiB 6.15 MiB

+643 MiB retained, 643 KiB per entry, essentially four 152 KiB sketches plus the basic and uniq
payloads. The bytes read are identical across arms, because with 1024 distinct keys nothing is ever
served: this shape pays the retention and gets none of the benefit. The cap bounds map cardinality
only, while payload size varies by three orders of magnitude with the declared statistics types, so it
does not express a memory bound.

This push does not change that, it touches one provably inert source line plus test settings. Byte
accounting in QueryStatisticsCache::set, or a default that stays safe with large sketches, is a
design call I would rather have your view on than make myself. statistics_cache_max_entries = 0
disables the cache exactly and measures identically to use_statistics_cache = 0, so a mitigation
already exists.

Session id: cron:clickhouse-maint-slot-15:20260829-114300

@clickhouse-gh

clickhouse-gh Bot commented Aug 29, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 31 queries analysed

no significant changes detected. K_source=6 K_base=30 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 42628749-88a8-42c2-829c-a552e63a2e5e
  • MIRAI run: 26a40e35-a7ab-4f39-a5c6-384f99475c1a
  • PR check IDs:
    • clickbench_938928_1791757922
    • clickbench_938934_1791757922
    • clickbench_938940_1791757921
    • tpch_adapted_1_official_938951_1791757922
    • tpch_adapted_1_official_938962_1791757921
    • tpch_adapted_1_official_938999_1791757922

@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Sep 4, 2026
Resolves one conflict in src/Storages/MergeTree/MergeTreeData.cpp: both sides
appended to the same include block. Master added Functions/FunctionFactory.h and
the Planner/* headers for the prepared-sets work; this branch added
Interpreters/QueryStatisticsCache.h. Both are kept, ours ordered after
Interpreters/QueryMetadataCache.h so the Interpreters/ group stays alphabetical.

getConditionSelectivityEstimator is byte-identical to the pre-merge branch head:
master never touched it, so the conflict was purely the include block.

ConditionSelectivityEstimator.cpp auto-merged. Master's IN/NOT IN prepared-set
range sharing lands in extractAtomFromTree, disjoint from this branch's payload
and cache-key changes, and no line of either side was dropped.

The merge is needed to get any CI at all: GitHub stops recomputing
refs/pull/116348/merge while a PR is CONFLICTING, and praktika's PR workflow is a
pull_request workflow, so no run was created for 14 days.
void QueryStatisticsCache::set(Key key, ConditionSelectivityPayloadPtr payload, size_t max_entries)
{
std::lock_guard lock(cache_mutex);
if (cache.size() >= max_entries && !cache.contains(key))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

statistics_cache_max_entries is documented and used here as if it bounded per-query retention, but this only limits the number of cached keys. A ConditionSelectivityPayload can be large and its size depends on the statistics types in it: countmin alone is ~152 KiB per column (StatisticsCountMinSketch.cpp documents that at construction time), so with multiple sketch-backed columns the default 1024 entries can still pin hundreds of MiB to one query. That makes the new default unsafe for wide-statistics workloads and violates the "bounds how much a query holds" contract in the setting and changelog text.

Can we either enforce a byte budget here (or otherwise account for payload size) or keep the default effectively off until the cache has a real memory bound?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed, and already conceded on this PR rather than new. set bounds cache.size() only, and the measured number is worse than your estimate: 1024 distinct keys with four STATISTICS(countmin) columns each, arms differing in nothing but the setting, gave +643.22 MiB retained, 643.2 KiB per entry, with statistics reads identical in every arm, so that shape pays the retention and is served nothing. Fixture and table: #116348 (comment)

The documented contract: agreed, and I will fix it. "Bounds how much a query holds" reads as a byte claim while the cap counts entries. It will say it caps the number of retained entries and that one entry scales with the declared statistics types, and the changelog entry gets the same correction. That rides the next push, not this reply: CI on this head started today after a two-week gap, and I would rather not replace the run for a wording change.

A byte budget: the sound version changes the statistics interface, so that call is yours rather than mine. IStatistics exposes no size, so real accounting needs a new virtual plus overrides in all six implementations (StatisticsBasic, StatisticsCountMinSketch, StatisticsMinMax, StatisticsTDigest, StatisticsUniq, StatisticsUniqV2). The cheap alternative is measured rather than assumed, and it fails: checksums.files already gives each statistics file's size at load time, but the whole 1024-key fixture reads 6.15 MiB of statistics, about 1.5 KiB per sketch, against 152 KiB per sketch once deserialized. On-disk size understates retention by two orders of magnitude, so it cannot serve as the budget.

Keeping the default off: declined, and a mitigation already exists. It removes the reuse this PR was asked for, while statistics_cache_max_entries = 0 is an exact opt-out, measured within 0.14% of use_statistics_cache = 0. Retention is also query-scoped rather than server-lifetime: the cache is owned by the query context, dies with the query, and counts against the query's own peak, so max_memory_usage bounds it today.

Session id: cron:clickhouse-maint-slot-12:20260912-094501

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 776b7b3: the statistics_cache_max_entries description now says the limit counts entries, not bytes.

@clickhouse-gh

clickhouse-gh Bot commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 4c57ead2b with master 4bfc24954 (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

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes

450 object files changed (+90.03 KiB total), 1 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Interpreters/QueryStatisticsCache.cpp.o new 58.51 KiB +58.51 KiB

719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

1367 translation units recompiled, 8837 s compile time in total, 1365 of them have a recent master baseline.

Translation units without a recent master baseline:

  • programs/keeper/Keeper.cpp (clickhouse-keeper): 7.5 s

Job report

alexey-milovidov and others added 2 commits September 26, 2026 23:23
…tatistics-within-query

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.

- retargeted PR record [email protected] to 26.10 (settings-history check rule)

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
The master merge 9058533 brought in two changes that interact with this PR:

- 34b9cd1 finalizes a negated element before flipping it, calling
  `finalize(column_estimators, metadata)` in `estimateRelationProfileImpl`. The estimator keeps
  its statistics in `payload` on this branch, so the line did not compile (Fast test and
  arm_tidy stopped at ConditionSelectivityEstimator.cpp:201). It now reads
  `payload->column_estimators`, like the other `finalize` calls there.

- 17a7f6a makes PREWHERE estimation share part filtering with reading, including the
  statistics-based part pruning that `use_statistics_for_part_pruning` enables by default. The
  keys 04651 uses to keep `read_rows` at 0 lie outside every part's value range, so every part
  was pruned and no statistics were loaded at all: the byte equalities held at zero and only the
  `> 0` guards failed (`loaded once for any branch count 0 1 1 1 1 1`,
  `keyed on the column set 0 1 1 1 0 1`). The test now pins the setting to 0. Measured on the
  merged tree: n2 = n8 = n8_cap1 = 18360 bytes, n8_nocache = n8_cap0 = 8x; without the pin all
  arms read 0, with a non-reusing n8 arm the second field turns red, so the oracle is still
  live. 50/50 randomized runs on a `tests/config/install.sh --fast-test` server pass.

  `statistics_load_many_reads.xml` probes the same kind of keys, so it measured nothing either:
  its query read 0 bytes of statistics with and without reuse. With the same pin it reads 51456
  bytes with reuse against 10291200 without (200 branches over 12 parts). Its comment no longer
  names a C++ function.

  The same change means the PREWHERE path now reads partition-pruned part sets (the `part = 1`
  branch loads one part: 4676 bytes vs 6784 for both partitions), so the `04651_parts` comment
  that said it did not is corrected. The comment on the join arms' row-limit pin claimed a
  whole-part-set fallback that no longer happens: with and without the pin the join arms read
  2381 / 7143 bytes under the CI profile. The pin stays, keeping the default planning path, and
  the comment no longer claims a mechanism.

Also correct the `statistics_cache_max_entries` description, as promised in the review thread:
the limit counts entries, not bytes, and an entry grows with the columns it covers and the
statistics types declared on them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

The latest push adapts this branch to the master merge: a one-line compile fix, and a use_statistics_for_part_pruning = 0 pin in both tests, whose no-match keys are now pruned by statistics before any statistics load.

Note that #120758 (for #120693) loads statistics through a per-part cache and makes use_statistics_cache obsolete, so a second read of the same parts in one query no longer goes to disk there. If it lands, this PR is redundant and I am happy to close it.

groeneai and others added 2 commits October 10, 2026 18:58
The table's statistics cache, published by the background refresh, is
consulted before the per-query cache and is controlled only by
`use_statistics_cache`. So on a table whose refresh has run, a zero limit
still reuses statistics; measured on a 4-branch UNION ALL over 3 parts:
0 loads with `statistics_cache_max_entries = 0`, 12 with
`use_statistics_cache = 0`. The description claimed the limit disables
"the cache" and that reads beyond it behave as if `use_statistics_cache`
were disabled; it now says the limit governs only the cache of one query.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…tatistics-within-query

`master` replaced the table-wide statistics cache with a `StatisticsCache` of
the statistics of each column of each data part (05ee00a), removed the
background refresh, `ConditionSelectivityEstimator::isStale` and the setting
`use_statistics_cache`, and made the builder merge into its own copies instead
of into the statistics it is given. The statistics of a part are no longer read
from disk once per read, but they are still collected and merged into an
estimator once per read, so the reuse within a query is ported on top of it:

- `getConditionSelectivityEstimator` consults the per-query cache before
  collecting the statistics of the parts, and stores the merged payload after.
  It is gated only on `statistics_cache_max_entries`, recorded in 26.11.
- The payload drops `parts_names`, which only served `isStale`. Sharing it is
  safe because the builder no longer merges in place.
- The test counts `LoadedStatistics` (the parts collected for an estimator)
  instead of `ReadCompressedBytes`, which the per-part cache already keeps
  flat, and uses `statistics_cache_max_entries = 0` for "no reuse".

Co-Authored-By: Claude Opus 5.5 <[email protected]>
groeneai and others added 2 commits October 18, 2026 03:40
With automatic parallel replicas the probe query plans twice, and both
planning paths ask for an estimator over the same selected part. Reuse
within a query hands the second path the statistics the first one
collected, so `LoadedStatistics` is 1 instead of the 2 the test asserts
(measured: 1 by default, 2 with `statistics_cache_max_entries = 0`, 1
either way without parallel replicas).

Pin `statistics_cache_max_entries = 0` so the probe still checks that each
path collects only the selected part, as it does on `master`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@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 19, 2026
@rschu1ze

Copy link
Copy Markdown
Member

Addresses a corner case (same table joined > 1). Also, merging statistics (the only thing left after #120758) is a cheap operation. I think we don't need this PR.

@rschu1ze rschu1ze closed this Nov 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-statistics Column statistics: statistics kept per part on a column (tdigest, uniq, count-min sketch, minmax)... groeneai-origin-follow-up PR origin: groeneai's own out-of-scope finding during its PR work pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants