Skip to content

Don't load statistics when the primary key leaves a small read - #126627

Merged
alexey-milovidov merged 27 commits into
masterfrom
stats-skip-small-reads
Nov 7, 2026
Merged

alexey-milovidov merged 27 commits into
masterfrom
stats-skip-small-reads

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Oct 19, 2026 •

Copy link
Copy Markdown
Member

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 on c6a.metal), while pruning parts or ordering the conditions of PREWHERE by 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 of PREWHERE; the conditions are then ordered by the sizes of their columns, as for tables without statistics. Answering min, max and count from statistics replaces the read, so it is not affected.

Design:

  • Part pruning by statistics (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 for FINAL, on-the-fly mutations, row or masking policies, or conditions that statistics cannot use).
  • The PREWHERE optimization runs the same probe if statistics would order its conditions (use_statistics and 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 in analyzed_result_ptr is not correct, because later optimizations (parallel replicas, read in order, top-K filters, projections) still change the read.
  • Statistics that are already in memory cost nothing, so they are used without the probe: the estimates of the parts for pruning (kept after an insert, a merge or an earlier query), and the statistics cache for PREWHERE. The threshold applies only when statistics would be read from disk.
  • An earlier version of this PR moved the pruning by statistics after the range analysis. That made every read pay the primary key analysis of the parts that statistics would prune, and with cached statistics the performance tests prewhere, read_hits_with_aio, long_primary_key, set_index and others got 50% to 50x slower. The order of master is restored, and so are the references of the tests printing EXPLAIN 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 in clickhouse-test. A new test checks that a read narrowed by the primary key does not load statistics (LoadedStatistics = 0, no Statistics entry in EXPLAIN), 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): LoadedStatisticsMicroseconds goes 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):

  • Performance Improvement

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 PREWHERE conditions when the primary key leaves fewer than min_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

  • Merged into: 26.11.1.1600-master (included in 26.11 and later)

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

clickhouse-gh Bot commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [6586641]

Summary: ✅


AI Review

Summary

The change avoids loading column statistics for small reads using min_marks_per_part_to_load_statistics, while retaining pruning from in-memory estimates and statistics-based aggregation. Reviewed head 65866415986f: the earlier findings are addressed, and no new actionable findings remain. Four focused tests passed locally with exact reference matches, including both new regression tests and the parallel-loading and LowCardinality cast tests.

The earlier prewhere query 0 regression is superseded by subsequent measurements: the last completed comparison reports approximately 2.4 ms on both binaries for ARM and 1.9 ms for AMD. Across 8,607 query measurements, it reports no significant slowdowns. Completed performance comparison. Performance jobs for the latest head are still pending.

Final Verdict

Status: ✅ Approve. No code changes requested.

@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Oct 19, 2026
alexey-milovidov and others added 2 commits October 21, 2026 04:34
…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]>
alexey-milovidov and others added 3 commits October 23, 2026 03:55
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]>
@clickhouse-gh

clickhouse-gh Bot commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 658664159 with master 6edbb4dd8 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 233269369; 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

10 object files changed (+48.30 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/MergeTree/MergeTreeDataSelectExecutor.cpp.o 1.13 MiB 1.16 MiB +22.23 KiB (+1.92%)
src/CMakeFiles/dbms.dir/Processors/QueryPlan/ReadFromMergeTree.cpp.o 2.51 MiB 2.53 MiB +18.84 KiB (+0.73%)

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

290 translation units recompiled, 3100 s compile time in total, 290 of them have a recent master baseline.

Job report

alexey-milovidov and others added 3 commits October 24, 2026 19:37
# 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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Status after merging master and the new commits:

  • Resolved the merge conflicts in five tests: master removed SET enable_analyzer = 1 and this PR added SET min_marks_to_use_statistics = 0. Both changes are kept.
  • 03518_key_condition_binary_search and 03532_key_condition_continuous_range failed with a randomized min_marks_to_use_statistics = 1, because the primary key probe adds to the IndexBinarySearchAlgorithm / IndexGenericExclusionSearchAlgorithm counters they assert on. They now set the setting to 0.
  • Statistics already in memory are now used without the probe: the part estimates for pruning, the statistics cache for PREWHERE. This answers the review comment. It should also remove the confirmed regressions in join_filter_pushdown #0 (+106%) and prewhere_subcolumns Repair subtree2 #1 (+58%). Those tables are filled by the test itself, so every part keeps its estimates in memory from the insert and master pruned them for free.

Open design question, needs a human decision: the prewhere #0 regression (+4833%, arm 4/6) will most likely remain. hits_10m_single is loaded from disk, and on master the first query loads the estimates of its single part and keeps them for good. Every later query then prunes the part with no I/O (SelectedParts 0, LoadedStatistics 0 in the master run). With this PR, the probe finds 237 marks to read, below 1024, so the statistics are skipped. Because they are never loaded, every repetition reads the 237 marks (SelectedMarks 237, 128 ms instead of 2.6 ms). More generally, loading statistics is a one-time cost per part, while skipping them costs something on every query. A workload of only small reads never warms them up. Possible directions:

  1. Lower the default of min_marks_to_use_statistics (e.g. to 128). That probably fits the ClickBench Q36-Q42 reads, but it needs checking.
  2. Skip the statistics on the critical path of a small read, but load them into the statistics cache in the background so later queries can use them.
  3. Accept the regression in this perf test as the intended trade-off.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=126627&sha=ad4f1b39b0ffc8aab7486a6264118cf6968cfcf6&name_0=PR&name_1=Performance%20Comparison%20(arm_release%2C%20master_head%2C%204%2F6)

alexey-milovidov and others added 2 commits October 25, 2026 23:47
…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]>
alexey-milovidov and others added 4 commits October 27, 2026 03:00
…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]>
alexey-milovidov and others added 2 commits October 28, 2026 18:54
…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]>
alexey-milovidov and others added 2 commits November 3, 2026 07:51
…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (ed895fd); the affected translation units build. The two CI failures on fd2e29f are unrelated to this PR:

@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.

@groeneai

groeneai commented Nov 4, 2026

Copy link
Copy Markdown
Collaborator

The La Casa Del Dolor (amd_debug) failure is the ProcessList::killAllQueries deadlock with distributed query plans, already fixed by #128832 (open).

In gdb.log (10:48:16Z, after shutdown_wait_unfinished = 9), the main thread is in ProcessList::killAllQueries (ProcessList.cpp:974) -> ReadFromDistributedPlanSource::onCancel -> DistributedQueryPlanExecutorLocal::joinAllThreads. It is joining a DistQueryTask thread that waits in ProcessListEntry::~ProcessListEntry (ProcessList.cpp:501) for is_cancelling to be reset, and killAllQueries resets it only after all cancellations finish. Master (b306e87) still has this code, so I'm not opening a separate PR.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Thanks @groeneai, noted that the La Casa Del Dolor failure is covered by #128832.

The only CI failure on ed895fd is 02962_parallel_window_functions_different_partitioning in Stateless tests (amd_debug, distributed plan, s3 storage, parallel). It is unrelated to this PR: the test reads a Memory table, and this PR only changes the loading of statistics for MergeTree. The query returned a wrong result (one window partition summed to 14400 instead of 43800), and 488 reruns with the same randomized settings passed. The test has also failed in unrelated PRs (#128687 on 2026-11-02, #126386 on 2026-10-17, #122717 on 2026-09-30). I found no open issue for it.

@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.

@groeneai

groeneai commented Nov 5, 2026

Copy link
Copy Markdown
Collaborator

Acknowledged. I'm investigating the 02962_parallel_window_functions_different_partitioning wrong result; I'll follow up here with a fix PR (or my findings) shortly.

@groeneai

groeneai commented Nov 5, 2026 •

Copy link
Copy Markdown
Collaborator

The fix is #129641. The cause is in the planner, not in this PR: addWindowSteps skips the re-sort for the second window (a prefix sort with a different PARTITION BY) when getEffectiveMaxThreads returns 1, but the first window's sort scatters by the read's own sample. Since #125085 these are two samples of the fair share of CPU slots; in the failing run they were 2 and 1, so the (depname, empno) scatter split the sales partition. A subquery with max_threads = 2 under max_threads = 1 reproduces it deterministically, and the 26.3, 26.8, 26.9 and 26.10 releases return 14400 too.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Thanks @groeneai for #129641; it is still open, so 02962_parallel_window_functions_different_partitioning stays a known unrelated failure here. Merged master (6586641) to refresh CI; the merge was clean and the affected translation units build. No review threads are open. The open design question about the prewhere #0 regression still needs a human decision.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Nov 7, 2026
@alexey-milovidov alexey-milovidov self-assigned this Nov 7, 2026
Merged via the queue into master with commit 7fe649e Nov 7, 2026
188 checks passed
@alexey-milovidov
alexey-milovidov deleted the stats-skip-small-reads branch November 7, 2026 14:09
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 7, 2026
@snelheidai

Copy link
Copy Markdown

For parts whose statistics are not in memory (e.g. all parts loaded at server startup, with the default auto_statistics_types = 'basic, uniq_v2'), a read that the primary key narrows to a few marks now never loads them, so hasFewerMarksToReadThan runs again on every such query. With more than one condition it runs three times per read over the same parts and key condition: in getPartsForPrewhere (in filterPartsByStatistics and for ordering PREWHERE), and again in filterPartsByStatistics of selectRangesToReadImpl. It analyzes the parts one after another over their full ranges, so for Q42 one probe takes about 0.85 ms on 20 parts and 6 ms on 200 parts, more than the primary key analysis of the read itself (0.35 and 1.8 ms, FilteringMarksWithPrimaryKeyMicroseconds).

Warm long-lived server, master 7b5f2bf (CI arm_release, 4-vCPU Graviton), ClickBench hits split by cityHash64(WatchID) into 20 parts of 5M rows, or into 200 parts of 1M rows (a copy with the 13 columns these queries read). Median latency of 60 runs per block, paired rounds (n = 12 and 5). The baseline is the same table with use_statistics_for_part_pruning = 0, use_statistics = 0, which was within 2% of the table without statistics:

Query 20 parts 200 parts
Q40 26.0 → 28.1 ms (+8%) 89.0 → 106.8 ms (+20%)
Q41 22.7 → 25.4 ms (+12%) 85.3 → 102.1 ms (+20%)
Q42 17.2 → 19.8 ms (+15%) 64.6 → 82.4 ms (+27%)
SELECT sum(ResolutionWidth) FROM hits WHERE CounterID = 62 7.4 → 8.1 ms (+9%) 25.4 → 29.9 ms (+16%)
the same AND EventDate BETWEEN '2013-07-14' AND '2013-07-15' 10.8 → 13.2 ms (+23%) 44.8 → 61.7 ms (+38%)

The 95% intervals are within ±4 points. QueryPlanOptimizeMicroseconds of Q42 is 1.4 ms without the probes and 3.2 ms (20 parts) or 13.5 ms (200 parts) with them; the third probe runs later, when the pipeline is built.

The patch below memoizes the number of marks that the probe finds in each part in ReadFromMergeTree::Indexes, like SkipIndexOrderCache, so the three probes of a read analyze each part once. The decisions do not change. Paired A/B of local Release builds of 7b5f2bf with and without it, on the 13-column copies (8 rounds, a fresh server per round and build, alternating order):

Query 20 parts 200 parts
Q40 28.8 → 27.2 ms (−5.5% [−8.7, −2.1]) 110.3 → 98.9 ms (−10.4% [−11.0, −9.7])
Q41 25.9 → 24.1 ms (−5.1% [−9.0, −1.1]) 106.1 → 95.0 ms (−10.5% [−11.3, −9.6])
Q42 19.9 → 18.5 ms (−7.2% [−8.7, −5.8]) 85.4 → 74.7 ms (−12.8% [−13.2, −12.4])
CounterID = 62 7.74 → 7.47 ms (−3.3% [−6.6, +0.1]) 30.8 → 28.5 ms (−6.9% [−7.9, −5.8])
CounterID = 62 AND EventDate ... 13.1 → 11.6 ms (−11.9% [−13.7, −10.1]) 63.8 → 53.2 ms (−16.6% [−17.5, −15.7])

On the 20-part table without statistics, the same queries did not change (all intervals include 0). Full results (with ties broken) and EXPLAIN indexes = 1, actions = 1 were identical with and without the patch, and 124 of the 136 stateless tests about statistics pass with both builds (the other 12 need Keeper or configuration missing on this machine and fail with both). One probe per read remains: Q42 on 20 parts takes 18.5 ms with the patch and 17.5 ms without statistics. That is about what statistics already in memory cost: after loading them once with min_marks_per_part_to_load_statistics = 0, these queries were 2–8% (20 parts) and 4–11% (200 parts) slower than without statistics.

Patch
diff --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
     {

lilredbot added a commit to JTCunning/ClickHouse that referenced this pull request Nov 11, 2026
…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]>
@snelheidai

Copy link
Copy Markdown

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 hits in 12 parts with the default basic, uniq_v2 statistics, against the same data with auto_statistics_types = '' as ClickBench uses now. ClickBench protocol per query (restart, drop caches, I/O limited to 3000 IOPS and 120 MiB/s; cold = run 1, hot = best of runs 2 and 3), 43 queries × 3 rounds in alternating order, 95% intervals:

  • Hot Q37 is 7.1% [2.4, 12.0] slower (32.3 → 35.2 ms) and Q42 6.3% [1.1, 11.7] slower (11.2 → 12.4 ms); Q38, Q40 and Q41 are 2–6% slower, within noise. Per query, IndexBinarySearchAlgorithm goes from 2 to 38 (three probes over 12 parts), plan optimization takes 0.4–0.7 ms longer and the pipeline build 0.4 ms longer.
  • The statistics now answer Q2, Q3 and Q29 (sum, avg, with Answer sum, avg and sumCount from per-part statistics #123950) and Q6 (min, max): hot 90.4 → 1.8, 138.5 → 1.6, 91.9 → 10.0 and 15.8 → 1.9 ms.
  • Cold runs are not slower: the sum over the 43 queries is 576.4 → 573.0 s, with no significant per-query slowdown. Inserting a 10M-row sample of hits takes 5.6% longer (53.7 → 56.8 s, one insert thread, 2 rounds).

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.

@snelheidai

Copy link
Copy Markdown

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 hasFewerMarksToReadThan: when the primary indexes are not in memory yet, it loads them one part after another, before the index analysis of the read, which would load them in parallel. On master, plan optimization of these cold runs takes 12–15 ms, against 1.7–1.8 ms without statistics, and the index analysis then finds the indexes already loaded.

The second patch below, on top of the memoization patch from the earlier comment, probes the parts in parallel, as filterPartsByPrimaryKeyAndSkipIndexes does, when more than one part has no primary index in memory. The threads take the parts in order, add their marks to an atomic counter and take no more parts once the limit is reached, so the decision is the same as with the serial probe. Both patches apply to current master.

Same data and VM as in the previous comment (4-vCPU x86, hits in 12 parts, I/O limited to 3000 IOPS and 120 MiB/s; without statistics means auto_statistics_types = ''), with local Release builds of master 9e17b5d without and with both patches. Each cold run: restart, drop caches, SELECT count() so the table is loaded, then the query. Medians of 6 rounds, ms:

Query Without statistics Master Both patches Both patches / master [95% CI]
Q36 103.5 107.9 99.0 0.915 [0.889, 0.942]
Q37 54.7 65.4 53.7 0.821 [0.745, 0.906]
Q38 73.6 80.1 72.6 0.898 [0.842, 0.957]
Q39 216.8 221.0 221.1 0.986 [0.951, 1.024]
Q40 41.2 51.5 41.6 0.787 [0.730, 0.849]
Q41 35.1 45.2 34.9 0.809 [0.734, 0.891]
Q42 26.9 35.4 27.6 0.788 [0.697, 0.890]

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 clickhouse benchmark (2 × 300 queries), ms per query without statistics / master / both patches: Q37 34.73 / 36.15 / 35.30, Q41 13.08 / 13.65 / 13.03, Q42 10.04 / 11.00 / 10.41. Q2 and Q29 (answered from statistics), Q7 and Q19 do not change, cold or hot. Results are the same, apart from the order of tied rows in Q38–Q41, which varies between runs of every build. The 12 statistics tests I ran give the same output with and without the patches.

Limitations: 4 vCPUs, capped EBS, 12 parts, local Release builds. Tables with use_primary_key_cache keep the index of the part empty, so they always take the parallel path. #130221 (open) adds another hasFewerMarksToReadThan call, in filterPartsByLowCardinalityDictionaries; passing it the same cache would keep one probe per part.

@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;
     }

@groeneai

Copy link
Copy Markdown
Collaborator

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 DETACH/ATTACH, IndexBinarySearchAlgorithm per query drops from 2000 to 1000 (1500 to 1000 with one condition), with the same decisions, results and EXPLAIN indexes = 1, actions = 1; perf.py ratio PR / master 0.80 to 0.93.

It does not include the parallel probe from #126627 (comment); I will check the cold-run numbers and that patch separately.

@groeneai

Copy link
Copy Markdown
Collaborator

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 use_statistics = 0.

Two changes from the patch: parts are probed in windows of num_threads consecutive parts, each consumed in part order, so the decision and the exception are the serial probe's and at most num_threads - 1 extra parts are analyzed (a shared queue can analyze many parts the serial probe never reaches while an early part loads its index); and a new IMergeTreeDataPart::isIndexInMemory also checks the primary index cache, so tables with use_primary_key_cache stay serial when warm. Cold ratio PR / master with 4 threads: EBS Q37/Q40/Q41/Q42 0.69/0.65/0.67/0.64, NVMe Q40-Q42 0.78-0.84; hot reads within noise. It does not depend on #131129.

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

Labels

comp-statistics Column statistics: statistics kept per part on a column (tdigest, uniq, count-min sketch, minmax)... pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants