Repository navigation
Don't load statistics when the primary key leaves a small read - #126627
Conversation
Loading statistics costs a few small reads per data part. When the primary key narrows the read to a handful of granules, as in ClickBench Q36-Q42 (`WHERE CounterID = 62 AND ...`), loading the statistics of all parts on a cold start takes longer than the read itself, while pruning parts or ordering the conditions of `PREWHERE` by statistics can save almost nothing. Add the setting `min_marks_to_use_statistics` (default 1024): if fewer marks are left to read, statistics are not loaded for part pruning and for ordering the conditions of `PREWHERE`, which then fall back to the column sizes, as for tables without statistics. Answering `min`, `max` and `count` from statistics replaces the read and is not affected. Part pruning by statistics (`filterPartsByStatistics`) now runs after the primary key and skip index analysis in `selectRangesToRead` instead of before it, so it knows the number of marks to read and probes only the parts that are left. The `Statistics` entry of `EXPLAIN indexes = 1` is now printed after the `PrimaryKey` and `Skip` entries. The `PREWHERE` optimization runs before the range analysis, so it bounds the number of marks by the primary key with `hasFewerMarksToReadThan`, which stops as soon as the threshold is reached. Tests relying on statistics of small tables set `min_marks_to_use_statistics = 0`, and the setting is randomized in `clickhouse-test`. Related: ClickHouse/ClickBench#2047 Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Workflow [PR], commit [6586641] Summary: ✅
AI ReviewSummaryThe change avoids loading column statistics for small reads using The earlier Final VerdictStatus: ✅ Approve. No code changes requested. |
…of small tables `05259_statistics_cache_drop`, `05406_statistics_cache_weight_composite`, `03773_semi_join_equivalent_sets`, `05293_key_condition_monotonic_transform_strict_bounds` and `05222_key_condition_multi_atom_whole_tuple_wrapped_set` read a few marks only, so with the default threshold the statistics are no longer loaded for part pruning and `PREWHERE` ordering, and the asserted marks, plans and cache counters change. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=126627&sha=359fe902ca9f266057c8b00e768492d945ed0f78&name_0=PR&name_1=Fast%20test #126627 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Moving the pruning by statistics after the range analysis made every read pay the primary key analysis of the parts that statistics would have pruned. With statistics cached (warm runs), this is a large slowdown: the performance tests `prewhere`, `read_hits_with_aio`, `long_primary_key`, `set_index`, `join_filter_pushdown` and others were 50% to 50x slower. It also checked `max_rows_to_read` and `max_rows_to_read_leaf` against parts that statistics prune. Prune by statistics before the primary key analysis, as before, and decide whether the read is large enough with `hasFewerMarksToReadThan`, which now bounds the generic exclusion search of each part by a small number of steps (an inconclusive answer uses statistics). The probe runs only when pruning by statistics is enabled and can prune by the condition, or when statistics would order the conditions of `PREWHERE` (more than one condition). The candidate plans of automatic parallel replicas, which have no index analysis yet, skip statistics if the parts have fewer marks in total than `min_marks_to_use_statistics`. The references of the tests printing `EXPLAIN indexes = 1` are restored to the order of master. A test checks the row limits with pruning by statistics. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=126627&sha=0f929a952fe8ee4ea9ac6a04b98a0f2e034f281b&name_0=PR #126627 Co-Authored-By: Claude Opus 5.5 <[email protected]>
The function came from master and iterated over the result of `getPartsForPrewhere`, which now returns `PartsForPrewhere`. It does not order conditions, so it does not need the selectivity estimator. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes10 object files changed (+48.30 KiB total), 0 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 units290 translation units recompiled, 3100 s compile time in total, 290 of them have a recent master baseline. |
# Conflicts: # tests/queries/0_stateless/04811_prewhere_statistics_ordering_compact_parts.sql # tests/queries/0_stateless/04812_prewhere_statistics_tautology_last.sql # tests/queries/0_stateless/05182_prewhere_partition_statistics.sql # tests/queries/0_stateless/05183_prewhere_statistics_pruned_parts.sql # tests/queries/0_stateless/05320_statistics_cache_prewarm.sql
…primary key `min_marks_to_use_statistics` is meant to avoid loading statistics from disk for a small read. Statistics that are already in memory cost nothing: the estimates of a part are kept after an insert, a merge or the first query that needed them, and the statistics cache keeps the statistics for `PREWHERE`. Probing the primary key in that case only adds work (it can load a lazily loaded primary index of parts that the statistics prune right away), and skipping the statistics makes the read slower than on master, as in the performance tests `join_filter_pushdown` and `prewhere_subcolumns`. Now pruning parts by statistics uses them without the probe if the estimates of all parts are in memory (`IMergeTreeDataPart::areEstimatesInMemory`), and ordering the conditions of `PREWHERE` does the same if the statistics of all parts are cached (`IMergeTreeDataPart::areStatisticsCached`). The test reattaches the table so that statistics are read from disk, and checks that a small read uses statistics loaded by a previous query, and that parts pruned by statistics in memory do not load the primary index. #126627 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ey search algorithms The primary key probe of `min_marks_to_use_statistics` increments `IndexBinarySearchAlgorithm` and `IndexGenericExclusionSearchAlgorithm`, so a randomized `min_marks_to_use_statistics = 1` changed the counts asserted by `03518_key_condition_binary_search` and `03532_key_condition_continuous_range`. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=126627&sha=ad4f1b39b0ffc8aab7486a6264118cf6968cfcf6&name_0=PR&name_1=Stateless%20tests%20%28arm_binary%2C%20parallel%29 #126627 Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Status after merging
Open design question, needs a human decision: the
|
…ber of parts The threshold `min_marks_to_use_statistics` compared the number of marks left to read with a fixed number (1024), regardless of how many parts would load statistics. A read of a few hundred marks from a single part then never used statistics, although loading the statistics of one part is far cheaper than the read: the performance test `prewhere` (`SELECT Title FROM hits_10m_single PREWHERE WatchID % 2 = 1 WHERE UserID = 10000`) read 237 marks instead of pruning the only part by statistics, 2.6 ms -> 129.9 ms. The cost of loading statistics is proportional to the number of parts whose statistics are not in memory, so the setting is now per part and renamed to `min_marks_per_part_to_use_statistics` (default 64): statistics are skipped if fewer than this number multiplied by the number of parts that would load statistics are left to read. Parts with statistics in memory do not count, which replaces the separate in-memory checks. The test checks that a cold read of 200 marks of one part prunes it by statistics. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=126627&sha=ad4f1b39b0ffc8aab7486a6264118cf6968cfcf6&name_0=PR&name_1=Performance%20Comparison%20%28arm_release%2C%20master_head%2C%204%2F6%29 #126627 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…e primary key Parts whose estimates are in memory are now always pruned by statistics, and the primary key probe of `filterPartsByStatistics` only counts the parts whose estimates would be loaded. `getPartsForPrewhere` applies this pruning before its own probe for the selectivity estimator, so parts pruned by estimates retained after the statistics cache was evicted no longer force a lazy primary-index load with automatic `PREWHERE`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The flaky check ran the test with a randomized `index_granularity = 1`, and inserting 100000 rows into a compact part took 260 seconds (114 GB allocated), so the test exceeded 180 seconds. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=126627&sha=2ab1a02b55d32279c439ca97f5127904fca4fb48&name_0=PR&name_1=Stateless%20tests%20%28amd_binary%2C%20flaky%20check%29 #126627 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Resolve conflicts with #126625 (parallel loading of statistics): keep the pruning of parts whose estimates are in memory and the primary key probe for the parts whose statistics would be loaded, on top of `MergeTreeData::loadStatisticsOfPartsInParallel`. Replace `areEstimatesInMemory` by `tryGetEstimatesFromMemory` from master. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…arallel_load` The test from master counts the loads of statistics of small parts, which are now skipped because the primary key leaves a small read. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…al scan The initial scan in `filterPartsByStatistics` kept a copy of the in-memory `Estimates` of every part until `loadStatisticsOfPartsInParallel` consumed them, so the query memory grew with the number of parts times the number of columns with statistics. Now such parts are checked right away and only the decision is kept, restoring the bound of the loader's window. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…nit with an invalid `ESCAPE` The test relied on `KeyCondition` throwing for a string constant that does not parse as the `DateTime64` key type. This PR makes `KeyCondition` decline such a constant instead (commit 67e69e0), so the shared init no longer threw and the test failed in all unit test jobs. Use `s LIKE 'a|%' ESCAPE '||'` over a `String` key, which `KeyCondition` still rejects with `BAD_ARGUMENTS` at planning time, to keep exercising the cached `init_exception` path. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=126627&sha=latest&name_0=PR&name_1=Unit%20tests%20(tsan) Related: #126627 Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Merged
@groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=126627&sha=fd2e29f65064ab4a646d9761b25fcf74d80eca93&name_0=PR&name_1=La%20Casa%20Del%20Dolor%20%28amd_debug%29 and provide a fix in a separate PR. If the fix is already in progress, link it here. |
|
The In |
|
🕵 Thanks @groeneai, noted that the The only CI failure on ed895fd is @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=126627&sha=ed895fd1e5643a39655709eff7ff384f3d2c3654&name_0=PR&name_1=Stateless%20tests%20%28amd_debug%2C%20distributed%20plan%2C%20s3%20storage%2C%20parallel%29 and provide a fix in a separate PR. If the fix is already in progress, link it here. |
|
Acknowledged. I'm investigating the |
|
The fix is #129641. The cause is in the planner, not in this PR: |
|
🕵 Thanks @groeneai for #129641; it is still open, so |
|
For parts whose statistics are not in memory (e.g. all parts loaded at server startup, with the default Warm long-lived server, master 7b5f2bf (CI
The 95% intervals are within ±4 points. The patch below memoizes the number of marks that the probe finds in each part in
On the 20-part table without statistics, the same queries did not change (all intervals include 0). Full results (with ties broken) and Patchdiff --git a/src/Processors/QueryPlan/ReadFromMergeTree.cpp b/src/Processors/QueryPlan/ReadFromMergeTree.cpp
index d90b0998f45..098fb928335 100644
--- a/src/Processors/QueryPlan/ReadFromMergeTree.cpp
+++ b/src/Processors/QueryPlan/ReadFromMergeTree.cpp
@@ -3868,7 +3868,8 @@ ReadFromMergeTree::AnalysisResultPtr ReadFromMergeTree::selectRangesToRead(
/// statistics could save, so parts are pruned by statistics only if the primary key leaves enough marks.
res_parts = MergeTreeDataSelectExecutor::filterPartsByStatistics(
res_parts, metadata_snapshot, query_info_, mutations_snapshot, indexes->key_condition,
- settings[Setting::min_marks_per_part_to_load_statistics], context_, log, result.index_stats);
+ settings[Setting::min_marks_per_part_to_load_statistics], context_, log, result.index_stats,
+ /*deferred_parts=*/nullptr, indexes->primary_key_probe_cache.get());
result.sampling = MergeTreeDataSelectExecutor::getSampling(
query_info_,
@@ -6970,7 +6971,8 @@ ReadFromMergeTree::PartsForPrewhere ReadFromMergeTree::getPartsForPrewhere(const
RangesInDataParts parts_with_deferred_statistics;
res.parts = MergeTreeDataSelectExecutor::filterPartsByStatistics(
res.parts, getStorageMetadata(), query_info, mutations_snapshot, indexes->key_condition,
- min_marks_per_part_to_load_statistics, getContext(), log, unused_stats, &parts_with_deferred_statistics);
+ min_marks_per_part_to_load_statistics, getContext(), log, unused_stats, &parts_with_deferred_statistics,
+ indexes->primary_key_probe_cache.get());
if (!selectivity_estimator_columns || !settings[Setting::use_statistics] || !getStorageMetadata()->hasStatistics())
{
@@ -6981,7 +6983,8 @@ ReadFromMergeTree::PartsForPrewhere ReadFromMergeTree::getPartsForPrewhere(const
/// The range analysis has not run yet. Bound the number of marks to read by the primary key, to not
/// load statistics for a read that is cheaper than loading them.
res.use_statistics = !MergeTreeDataSelectExecutor::hasFewerMarksToReadThan(
- res.parts, getStorageMetadata(), indexes->key_condition, min_marks_to_load_statistics(res.parts), settings, log);
+ res.parts, getStorageMetadata(), indexes->key_condition, min_marks_to_load_statistics(res.parts), settings, log,
+ indexes->primary_key_probe_cache.get());
/// The statistics are loaded for ordering the conditions anyway, so prune the parts whose statistics
/// were not loaded above as well. The other parts were already checked and are not checked again.
diff --git a/src/Processors/QueryPlan/ReadFromMergeTree.h b/src/Processors/QueryPlan/ReadFromMergeTree.h
index 58ee33522ea..d09a28d9980 100644
--- a/src/Processors/QueryPlan/ReadFromMergeTree.h
+++ b/src/Processors/QueryPlan/ReadFromMergeTree.h
@@ -69,6 +69,24 @@ struct SkipIndexOrderCache
};
using SkipIndexOrderCachePtr = std::shared_ptr<SkipIndexOrderCache>;
+/// Memoizes, per part, the number of marks that the bounded primary key probe of
+/// `MergeTreeDataSelectExecutor::hasFewerMarksToReadThan` leaves to read, for one `ReadFromMergeTree::Indexes` object.
+/// The probe decides whether loading statistics pays off. With the same key condition and parts, it runs for pruning
+/// parts by statistics and for ordering the conditions of `PREWHERE` when `PREWHERE` is optimized, and for pruning
+/// parts by statistics again when the read is analyzed, so a selective read would analyze the primary key three times.
+struct PrimaryKeyProbeCache
+{
+ struct Entry
+ {
+ MarkRanges ranges;
+ size_t marks = 0;
+ };
+
+ std::mutex mutex;
+ std::unordered_map<String, Entry> marks TSA_GUARDED_BY(mutex);
+};
+using PrimaryKeyProbeCachePtr = std::shared_ptr<PrimaryKeyProbeCache>;
+
/// Contains parts each from different projection index
using ProjectionIndexReadRangesByIndex = std::unordered_map<size_t, RangesInDataParts>;
@@ -367,6 +385,8 @@ public:
UsefulSkipIndexes skip_indexes;
/// Shared by every index analysis of this step, see `SkipIndexOrderCache`.
SkipIndexOrderCachePtr skip_index_orders = std::make_shared<SkipIndexOrderCache>();
+ /// Shared by every probe of the primary key of this step, see `PrimaryKeyProbeCache`.
+ PrimaryKeyProbeCachePtr primary_key_probe_cache = std::make_shared<PrimaryKeyProbeCache>();
bool use_skip_indexes;
bool use_skip_indexes_for_disjunctions;
bool use_skip_indexes_if_final_exact_mode;
diff --git a/src/Storages/MergeTree/MergeTreeDataSelectExecutor.cpp b/src/Storages/MergeTree/MergeTreeDataSelectExecutor.cpp
index cc4fbe3f570..021d085178c 100644
--- a/src/Storages/MergeTree/MergeTreeDataSelectExecutor.cpp
+++ b/src/Storages/MergeTree/MergeTreeDataSelectExecutor.cpp
@@ -236,7 +236,8 @@ bool MergeTreeDataSelectExecutor::hasFewerMarksToReadThan(
const ConditionTemplate<KeyCondition>::Ptr & key_condition,
size_t limit,
const Settings & settings,
- LoggerPtr log)
+ LoggerPtr log,
+ PrimaryKeyProbeCache * probe_cache)
{
if (limit == 0)
return false;
@@ -265,10 +266,31 @@ bool MergeTreeDataSelectExecutor::hasFewerMarksToReadThan(
size_t marks = 0;
for (const auto & part : parts)
{
- marks += markRangesFromPKRange(
- part, metadata_snapshot, key_condition->generateForPart(part.data_part), nullptr, nullptr,
- /*exact_ranges=*/nullptr, pk_to_minmax_slot_ptr, probe_settings, log).getNumberOfMarks();
+ std::optional<size_t> part_marks;
+ String cache_key;
+ if (probe_cache)
+ {
+ cache_key = SkipIndexOrderCache::makeKey(*part.data_part);
+ std::lock_guard lock(probe_cache->mutex);
+ auto it = probe_cache->marks.find(cache_key);
+ if (it != probe_cache->marks.end() && std::ranges::equal(it->second.ranges, part.ranges))
+ part_marks = it->second.marks;
+ }
+
+ if (!part_marks)
+ {
+ part_marks = markRangesFromPKRange(
+ part, metadata_snapshot, key_condition->generateForPart(part.data_part), nullptr, nullptr,
+ /*exact_ranges=*/nullptr, pk_to_minmax_slot_ptr, probe_settings, log).getNumberOfMarks();
+
+ if (probe_cache)
+ {
+ std::lock_guard lock(probe_cache->mutex);
+ probe_cache->marks.insert_or_assign(cache_key, PrimaryKeyProbeCache::Entry{part.ranges, *part_marks});
+ }
+ }
+ marks += *part_marks;
if (marks >= limit)
return false;
}
@@ -961,7 +983,8 @@ RangesInDataParts MergeTreeDataSelectExecutor::filterPartsByStatistics(
const ContextPtr & context,
LoggerPtr log,
ReadFromMergeTree::IndexStats & index_stats,
- RangesInDataParts * deferred_parts)
+ RangesInDataParts * deferred_parts,
+ PrimaryKeyProbeCache * probe_cache)
{
const auto & settings = context->getSettingsRef();
@@ -1078,7 +1101,7 @@ RangesInDataParts MergeTreeDataSelectExecutor::filterPartsByStatistics(
min_marks_per_part_to_load_statistics, parts_to_load_statistics.size());
const bool load_statistics = !hasFewerMarksToReadThan(
- parts_to_load_statistics, metadata_snapshot, key_condition, min_marks_to_load_statistics, settings, log);
+ parts_to_load_statistics, metadata_snapshot, key_condition, min_marks_to_load_statistics, settings, log, probe_cache);
if (!load_statistics)
LOG_TRACE(log, "Not pruning {} parts without statistics in memory, because fewer than {} marks are left to read in them by the primary key",
diff --git a/src/Storages/MergeTree/MergeTreeDataSelectExecutor.h b/src/Storages/MergeTree/MergeTreeDataSelectExecutor.h
index 6406bb9e363..d2a8f160646 100644
--- a/src/Storages/MergeTree/MergeTreeDataSelectExecutor.h
+++ b/src/Storages/MergeTree/MergeTreeDataSelectExecutor.h
@@ -247,13 +247,15 @@ public:
/// Whether fewer than `limit` marks of the parts are left to read after the primary key analysis.
/// Stops the analysis as soon as `limit` marks are found, and bounds the analysis of each part,
/// so the answer is false when it cannot be established cheaply. Always false if `limit` is zero.
+ /// If `probe_cache` is not nullptr, the parts already probed with the same `key_condition` are not probed again.
static bool hasFewerMarksToReadThan(
const RangesInDataParts & parts,
const StorageMetadataPtr & metadata_snapshot,
const ConditionTemplate<KeyCondition>::Ptr & key_condition,
size_t limit,
const Settings & settings,
- LoggerPtr log);
+ LoggerPtr log,
+ PrimaryKeyProbeCache * probe_cache = nullptr);
/// Apply snapshot, virtual-column, min-max and partition filters before range analysis.
static RangesInDataParts filterParts(
@@ -286,6 +288,7 @@ public:
/// so the other parts are not pruned if `key_condition` leaves fewer than `min_marks_per_part_to_load_statistics`
/// marks to read in them per part (see `getMinMarksToLoadStatistics` and `hasFewerMarksToReadThan`).
/// If `deferred_parts` is not nullptr, the parts left unpruned for that reason are written to it.
+ /// `probe_cache` is passed to `hasFewerMarksToReadThan`.
static RangesInDataParts filterPartsByStatistics(
const RangesInDataParts & parts,
const StorageMetadataPtr & metadata_snapshot,
@@ -296,7 +299,8 @@ public:
const ContextPtr & context,
LoggerPtr log,
ReadFromMergeTree::IndexStats & index_stats,
- RangesInDataParts * deferred_parts = nullptr);
+ RangesInDataParts * deferred_parts = nullptr,
+ PrimaryKeyProbeCache * probe_cache = nullptr);
struct IndexAnalysisContext
{ |
…probe (ready-to-build) Cold PromQL range query on an s3 disk (S3 mock, 50 ms per GET, 64 fresh parts per inner table): shares per cause, the text index and first data reads after prewarm, cache-segment predownload as the read amplification, and the serial primary index loads of the statistics probe added by upstream ClickHouse#126627. Fix branch, PR text, A/B plan, outbox item and the lab (bench/tags-in-subquery-cold). Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
On current master, with #126627 and #123950 merged, the default statistics no longer slow down ClickBench cold runs. The main remaining query-time cost is on Q36–Q42: they do not load statistics, but still run the probe from my previous comment three times per read. Master 9e17b5d (26.11.1.1945), 4-vCPU x86 VM, ClickBench
The results in ClickBench#2047, which re-enables the statistics, are from 2026-10-09 and 10-18, before both PRs. @groeneai could you take a look? If the analysis and the memoization patch in the previous comment hold up, feel free to open a PR if it fits. Limitations: 3 rounds on 4 vCPUs; the patch was measured on ARM (previous comment), not again on this setup. |
|
Correction to my previous comment: the default statistics still slow down cold runs of the short ClickBench queries. The cold runs there included about 1.2 s of startup noise per restart, which hid a difference of about 10 ms per query. Measured after the table has loaded, with caches dropped, master's first run of Q37, Q40, Q41 and Q42 is 20%, 25%, 29% and 32% slower with the default statistics than without them. The cause is again The second patch below, on top of the memoization patch from the earlier comment, probes the parts in parallel, as Same data and VM as in the previous comment (4-vCPU x86,
With both patches, these cold runs are at the level of the table without statistics (0.97–1.04), and plan optimization takes 5.8–6.8 ms because it now loads the indexes, in parallel. The memoization patch alone does not change cold runs. Hot, with Limitations: 4 vCPUs, capped EBS, 12 parts, local Release builds. Tables with @groeneai could you take a look? If the analysis and both patches hold up, feel free to open a PR if it fits. Second patch: probe the parts in parallel (on top of the memoization patch)diff --git a/src/Storages/MergeTree/MergeTreeDataSelectExecutor.cpp b/src/Storages/MergeTree/MergeTreeDataSelectExecutor.cpp
index 8d6461143ba..003b33d4462 100644
--- a/src/Storages/MergeTree/MergeTreeDataSelectExecutor.cpp
+++ b/src/Storages/MergeTree/MergeTreeDataSelectExecutor.cpp
@@ -263,10 +263,9 @@ bool MergeTreeDataSelectExecutor::hasFewerMarksToReadThan(
= user_max_steps ? std::min(user_max_steps, max_steps_per_part) : max_steps_per_part;
/// Stop as soon as the limit is reached, so a large read costs the analysis of a few parts only.
- size_t marks = 0;
- for (const auto & part : parts)
+ /// The marks of each part are memoized in `probe_cache`, so the other probes of the same read reuse them.
+ auto probe_part = [&](const RangesInDataPart & part) -> size_t
{
- std::optional<size_t> part_marks;
String cache_key;
if (probe_cache)
{
@@ -274,23 +273,72 @@ bool MergeTreeDataSelectExecutor::hasFewerMarksToReadThan(
std::lock_guard lock(probe_cache->mutex);
auto it = probe_cache->marks.find(cache_key);
if (it != probe_cache->marks.end() && std::ranges::equal(it->second.ranges, part.ranges))
- part_marks = it->second.marks;
+ return it->second.marks;
}
- if (!part_marks)
+ const size_t part_marks = markRangesFromPKRange(
+ part, metadata_snapshot, key_condition->generateForPart(part.data_part), nullptr, nullptr,
+ /*exact_ranges=*/nullptr, pk_to_minmax_slot_ptr, probe_settings, log).getNumberOfMarks();
+
+ if (probe_cache)
{
- part_marks = markRangesFromPKRange(
- part, metadata_snapshot, key_condition->generateForPart(part.data_part), nullptr, nullptr,
- /*exact_ranges=*/nullptr, pk_to_minmax_slot_ptr, probe_settings, log).getNumberOfMarks();
+ std::lock_guard lock(probe_cache->mutex);
+ probe_cache->marks.insert_or_assign(cache_key, PrimaryKeyProbeCache::Entry{part.ranges, part_marks});
+ }
+ return part_marks;
+ };
- if (probe_cache)
- {
- std::lock_guard lock(probe_cache->mutex);
- probe_cache->marks.insert_or_assign(cache_key, PrimaryKeyProbeCache::Entry{part.ranges, *part_marks});
- }
+ /// The probe loads the primary index of every part it analyzes. When the index of more than one part is not in
+ /// memory yet (a cold start), analyze the parts in parallel, as the index analysis of the read does, instead of
+ /// loading their indexes one after another. The parts are taken in order and none is taken after the limit is
+ /// reached, so the decision is the same as with the serial probe, which can stop at most one part per thread earlier.
+ size_t num_threads = std::min<size_t>(parts.size(), settings[Setting::max_threads]);
+ if (settings[Setting::max_threads_for_indexes])
+ num_threads = std::min<size_t>(num_threads, settings[Setting::max_threads_for_indexes]);
+
+ if (num_threads > 1
+ && std::ranges::count_if(parts, [](const RangesInDataPart & part) { return part.data_part->tryGetIndex() == nullptr; }) > 1)
+ {
+ /// Outlive `pool`, whose destructor joins the jobs that still use them when scheduling throws.
+ std::atomic<size_t> total_marks = 0;
+ std::atomic<size_t> next_part_index = 0;
+ std::atomic<bool> limit_reached = false;
+
+ ThreadPool pool(
+ CurrentMetrics::MergeTreeDataSelectExecutorThreads,
+ CurrentMetrics::MergeTreeDataSelectExecutorThreadsActive,
+ CurrentMetrics::MergeTreeDataSelectExecutorThreadsScheduled,
+ num_threads);
+
+ for (size_t job = 0; job < num_threads; ++job)
+ {
+ pool.scheduleOrThrowOnError(
+ [&, thread_group = CurrentThread::getGroup(), component_name = Coordination::getCurrentComponent()]
+ {
+ ThreadGroupSwitcher switcher(thread_group, ThreadName::MERGETREE_INDEX);
+ auto local_component_guard = Coordination::setCurrentComponent(component_name);
+
+ while (!limit_reached.load(std::memory_order_relaxed) && !pool.isFinished())
+ {
+ const size_t part_index = next_part_index.fetch_add(1, std::memory_order_relaxed);
+ if (part_index >= parts.size())
+ break;
+
+ const size_t part_marks = probe_part(parts[part_index]);
+ if (total_marks.fetch_add(part_marks, std::memory_order_relaxed) + part_marks >= limit)
+ limit_reached.store(true, std::memory_order_relaxed);
+ }
+ });
}
- marks += *part_marks;
+ pool.wait();
+ return !limit_reached.load();
+ }
+
+ size_t marks = 0;
+ for (const auto & part : parts)
+ {
+ marks += probe_part(part);
if (marks >= limit)
return false;
} |
|
I opened #131129 with the memoization patch from #126627 (comment) and one guard: an entry is reused only for the same part ranges and the same number of key condition transformations, because sampling transforms the key condition in place after the probe. On 500 parts after It does not include the parallel probe from #126627 (comment); I will check the cold-run numbers and that patch separately. |
|
I opened #131667 with the parallel probe from #126627 (comment). The cold regression reproduced: on 12 parts on EBS, the plan optimization of Q37/Q40-Q42 takes ~300 ms on master against ~1.6 ms with Two changes from the patch: parts are probed in windows of |
`hasFewerMarksToReadThan` (added in ClickHouse#126627) analyzes the primary key of the parts one after another to decide whether loading statistics pays off. Analyzing a part loads its primary index when it is not in memory, so after a restart or `ATTACH` the first selective read loads the indexes of its parts serially during plan optimization, before the index analysis of the read, which would load them in parallel. Analyze the parts in windows of `num_threads` consecutive parts. A window in which more than one primary index is not in memory (neither loaded nor in the primary index cache, see the new `IMergeTreeDataPart::isIndexInMemory`) is analyzed in a thread pool, then consumed in part order with the same early return as before, and the next window starts only after that. The decision and the exception are those of the serial analysis; at most `num_threads - 1` parts after the stopping part are analyzed in addition. Hot reads, `max_threads = 1` and windows with at most one index to load are analyzed in the calling thread as before. Reported by @ snelheidai: ClickHouse#126627 (comment) Co-Authored-By: Claude Opus 5.5 <[email protected]>
Loading statistics costs a few small reads per data part. When the primary key narrows the read to a handful of granules, as in ClickBench Q36-Q42 (
WHERE CounterID = 62 AND ...on a table ordered by(CounterID, EventDate, ...)), loading the statistics of all parts on a cold start takes longer than the read itself (+0.5-0.75 s per query onc6a.metal), while pruning parts or ordering the conditions ofPREWHEREby statistics can save almost nothing there.This adds the query setting
min_marks_per_part_to_load_statistics(default 64 marks, about 500 thousand rows with the default granularity, per data part whose statistics are not in memory yet). If fewer marks than this number multiplied by the number of parts that would load statistics are left to read after the primary key analysis, statistics are not loaded for part pruning and for ordering the conditions ofPREWHERE; the conditions are then ordered by the sizes of their columns, as for tables without statistics. Answeringmin,maxandcountfrom statistics replaces the read, so it is not affected.Design:
filterPartsByStatistics) stays before the primary key analysis, as on master, so the statistics still save the primary key analysis of the parts they prune, and the row limits (max_rows_to_read,max_rows_to_read_leaf) apply to the parts that are left. Before loading statistics, it bounds the number of marks to read with a primary key probe (MergeTreeDataSelectExecutor::hasFewerMarksToReadThan). The probe stops as soon as the threshold is reached and limits the generic exclusion search of each part to 256 steps; the ranges it leaves unanalyzed count as a whole, so the bound is an upper bound, and an inconclusive probe uses statistics, as before. The probe runs only if pruning by statistics is enabled and can prune by the condition (not forFINAL, on-the-fly mutations, row or masking policies, or conditions that statistics cannot use).PREWHEREoptimization runs the same probe if statistics would order its conditions (use_statisticsand more than one condition). The candidate plans of automatic parallel replicas, which have no index analysis yet, skip statistics if the parts have fewer marks in total than the threshold. Running the full range analysis at this point and caching it inanalyzed_result_ptris not correct, because later optimizations (parallel replicas, read in order, top-K filters, projections) still change the read.PREWHERE. The threshold applies only when statistics would be read from disk.prewhere,read_hits_with_aio,long_primary_key,set_indexand others got 50% to 50x slower. The order of master is restored, and so are the references of the tests printingEXPLAIN indexes = 1.The threshold is per part because the cost of loading statistics is proportional to the number of parts that load them. An earlier version of this PR used a fixed threshold of 1024 marks for the whole read, so a read of 237 marks from a single part never used statistics, and the performance test
prewhere(where statistics prune the only part) got 50x slower.Tests that rely on statistics of small tables set
min_marks_per_part_to_load_statistics = 0; the setting is randomized inclickhouse-test. A new test checks that a read narrowed by the primary key does not load statistics (LoadedStatistics= 0, noStatisticsentry inEXPLAIN), that the same read does with the threshold disabled, that a cold read of 200 marks of one part prunes it by statistics, and that a large read does, with the same results. It also checks that the row limits apply after pruning by statistics.A local cold run (NVMe, server restart, dropped page cache, 30 parts x 55 columns, 30 marks to read; the machine was shared with other builds, so the timings are noisy):
LoadedStatisticsMicrosecondsgoes from 28-590 ms to 0, the median query time over 5 runs is 503 ms with the change, 781 ms with the threshold disabled, and 1779 ms with the master build.Related: ClickHouse/ClickBench#2047
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Column statistics are no longer loaded for pruning parts and ordering
PREWHEREconditions when the primary key leaves fewer thanmin_marks_per_part_to_load_statistics(64 by default) marks to read per part whose statistics would be loaded, which speeds up queries with a selective primary key condition on a cold start.🤖 Generated with Claude Code
Workflow [PR]
Sync PR [sync-upstream/pr/126627]
Version info
26.11.1.1600-master(included in26.11and later)