Repository navigation
Conversation
Internal second-model reviewReviewed cold against the code on disk, then re-reviewed by an independent model, over five
Also checked and found sound: the payload is handed out as |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-41:20260825-115100 |
|
cc @hanfei1991 @vdimir, could you review this? |
|
@groeneai We have had StatisticsCache per MergeTree, Why do we need another QueryStatisticsCache? |
|
Different scope, and I checked it rather than assuming: Measured on this branch's binary, one table, four reads in one query, four parts,
Control: 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. 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 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.
e16ee78 to
49d7c0c
Compare
|
Merged master (the branch was 964 commits behind) and collapsed the branch to one commit. Two test fixes while re-checking the tree:
|
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.
|
Workflow [PR], commit [4c57ead] Summary: ❌
AI ReviewSummaryThis PR reuses merged Missing context / blind spots
Findings
Final Verdict |
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'`.
CI fix for
|
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
|
📊 Cloud Performance Report ✅ AI verdict: 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
|
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)) |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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
There was a problem hiding this comment.
Done in 776b7b3: the statistics_cache_max_entries description now says the limit counts entries, not bytes.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes450 object files changed (+90.03 KiB total), 1 added.
719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units1367 translation units recompiled, 8837 s compile time in total, 1365 of them have a recent master baseline. Translation units without a recent master baseline:
|
…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]>
|
The latest push adapts this branch to the master merge: a one-line compile fix, and a Note that #120758 (for #120693) loads statistics through a per-part cache and makes |
Co-Authored-By: Claude Opus 5.5 <[email protected]>
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]>
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]>
…tatistics-within-query
|
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. |
Related: #116134
Related: #115998
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
A query reading the same
MergeTreetable many times, such as aUNION ALLof 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 settingstatistics_cache_max_entries.Description
Reported by @ Avogar on #116134 while measuring the #115998 reproducer: planning a 1500-branch
UNION ALLgot 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,
masterreplaced the table-wide statistics cache with aStatisticsCacheof 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::getConditionSelectivityEstimatorkeeps 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 (loadStatisticsreads 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_querycountsLoadedStatistics, the parts collected for an estimator, which onmastergrows 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 teststatistics_load_many_readsmeasures the planning time of the many-branch query.Workflow [PR]
Sync PR [sync-upstream/pr/116348]