Skip to content

Load the primary indexes of parts in parallel when deciding whether to load statistics - #131667

Merged
alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:parallel-statistics-probe-index-load
Nov 15, 2026
Merged

alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:parallel-statistics-probe-index-load

Conversation

@groeneai

@groeneai groeneai commented Nov 14, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #126627
Related: #126627 (comment)
Related: #131129

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

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

Description

Since #126627, a read whose parts do not have their statistics in memory first runs hasFewerMarksToReadThan, a bounded primary key probe, to decide whether loading statistics pays off. The probe analyzes the parts one after another, and analyzing a part loads its primary index if 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, while the read's own index analysis loads them in parallel.

The probe now takes windows of num_threads consecutive parts. A window with more than one index not in memory (new IMergeTreeDataPart::isIndexInMemory, which also checks the primary index cache) is analyzed in a thread pool, then consumed in part order with the same early stop, so the decision and the exception are those of the serial probe, and at most num_threads - 1 extra parts are analyzed. Hot reads and max_threads = 1 keep the serial path.

RelWithDebInfo, ClickBench hits in 12 parts with default statistics, cold (restart, page cache evicted, SELECT count(), query), 8 rounds, ratio = PR / master. EBS, 4 threads: Q37/Q40/Q41/Q42 0.69/0.65/0.67/0.64 (plan optimization ~310 ms -> ~110 ms; 1.6 ms without statistics); 16 threads: 0.47-0.52. NVMe, 4 threads: Q40-Q42 0.78-0.84, Q36-Q39 within noise. Hot (hits; a 500-part table): within noise, except that with use_primary_key_cache on 500 parts the cache lookups of the in-memory check add ~0.5 ms of planning (ratios 1.00-1.06). Selected parts, marks and results are identical. Performance tests prewarm every query and cannot see this. The new test checks that the probe runs in parallel only while the indexes are not in memory (also with the primary index cache) and decides as the serial one.

Independent of #131129 (memoization of the same probe); whichever lands second resolves a small conflict.


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

Version info

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

groeneai and others added 3 commits November 14, 2026 12:10
`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]>
The test checked only the decision of the probe, which the parallel analysis
preserves by construction, so it stayed green if the parts were analyzed
serially, and the primary index cache path was never run.

Count, per read, the probes that analyzed the parts in parallel through the
existing trace line in `system.text_log`, and add a read with
`use_primary_key_cache = 1`, where an index in the cache counts as in memory.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Condense the window-probe comment to its ordering invariant and drop the pool's creation narration, keeping the destruction-order invariant.

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

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (2 rounds)

Pre-publication review by an independent model (engine: codex; round 1: 1 finding, round 2: 0) plus my own cold review of each round.

# Sev Finding Verdict Evidence / action
1 ⚠️ The test stayed green if the probe was not parallel, and never ran the primary index cache branch AGREE, fixed in 7078d55 per-read count of the probe's trace line in system.text_log, plus a read with use_primary_key_cache = 1; fails if the parallel branch or the cache check is removed
2 💡 With use_primary_key_cache = 1, the in-memory check adds one cache lookup per probed part noted, not changed ~0.5 ms of planning on 500 parts hot (in the description); without it every hot probe of such a table would start a thread pool
3 💡 The windowed loop resembles MergeTreeData::loadStatisticsOfPartsInParallel noted, not changed that helper has no early stop, uses windows of 4 * max_threads and the statistics loader's metrics

Severity: ❌ blocker / ⚠️ major / 💡 nit.

Session id: cron:clickhouse-review-slot-9:20261114-170501

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. ClickBench hits in 12 parts with default statistics, cold start on EBS (restart, page cache of the table evicted, SELECT count(), then the query): on master the plan optimization of Q37/Q40/Q41/Q42 takes ~300 ms against ~1.6 ms with use_statistics = 0, in 8 of 8 rounds each.
b Root cause explained? hasFewerMarksToReadThan analyzes the parts one after another in the calling thread; analyzing a part loads its primary index when it is not in memory, so a cold read loads N indexes serially during plan optimization, before the index analysis of the read (which loads them in parallel) runs.
c Fix matches root cause? Yes. The same parts are analyzed and the same indexes loaded, in windows of num_threads parts analyzed concurrently when more than one index of the window is not in memory. No bound or guard is relaxed.
d Test intent preserved / new tests added? New SQL test 05768_statistics_probe_parallel_index_load: per read it checks the decision (LoadedStatistics, SelectedParts) and counts the probes that ran in parallel (the existing trace line, via system.text_log): one per read while the indexes are not in memory, also with use_primary_key_cache = 1; max_threads = 1 gives the same decision with none. Four mutations make it fail: no early stop in the parallel loop, a stop right after the pool, isIndexInMemory always true (silently serial), isIndexInMemory ignoring the primary index cache. 05407_statistics_skip_small_reads is unchanged and passes. 50/50 randomized runs (25 with async logging, 25 without), 20/20 under ASan.
e Both directions demonstrated? Cold A/B, ratio = PR / master with 95 % CI over 8 rounds, EBS 4 threads: Q37 0.693 [0.648, 0.787], Q40 0.653 [0.587, 0.730], Q41 0.669 [0.569, 0.742], Q42 0.639 [0.594, 0.929]; 16 threads 0.47-0.52. The test fails under all four mutations and passes with the change.
f Fix is general across code paths? The probe has one implementation, used by all three call sites (getPartsForPrewhere twice, filterPartsByStatistics). Tables with use_primary_key_cache are covered by isIndexInMemory, which checks the cache with the key loadIndexToCache uses; projection parts use the same code.
g Fix generalizes across inputs (params/datatypes/wrappers)? max_threads = 1 and max_threads_for_indexes keep or cap the serial path; checked with the primary key cache on and off, cold and warm (the parallel path runs only cold), 1, 2, 4, 12 and 500 parts, 4 and 16 threads. Types are not involved.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, default or format change; the decision is unchanged (selected parts, marks, rows and query results identical between master and the PR in every cold and hot run).
i Invariants and contracts preserved? The decision and the exception are the serial probe's: every window is fully analyzed, then consumed in part order with the same early return, and a stored exception is rethrown only when its part is reached. The vectors and the lambda are declared before the pool, jobs capture the part index by value, each window is waited for before it is read, and jobs attach to the query's thread group.

Session id: cron:clickhouse-impl-slot-40:20261114-112900

@clickhouse-gh

clickhouse-gh Bot commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [471046d]

Summary: ✅


AI Review

Summary

The PR parallelizes cold primary-index loading in hasFewerMarksToReadThan using bounded windows, while preserving ordered early stopping and propagation of part-analysis exceptions. No actionable findings remain. The PR supplies cold/hot benchmark evidence, and 05768_statistics_probe_parallel_index_load passes in the current-head Fast test report.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-not-for-changelog This PR should not be mentioned in the changelog can be tested Allows running workflows for external contributors comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Nov 14, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 14, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 471046d7e with master 58726cc5c (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

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

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

Object file sizes

4 object files changed (+17.92 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/MergeTree/MergeTreeDataSelectExecutor.cpp.o 1.16 MiB 1.17 MiB +16.18 KiB (+1.36%)

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

Slowest function optimization changes (ThinLTO)

Median per-function time ratio to the master baseline: programs/clickhouse ×0.56, programs/clickhouse-keeper ×0.59 (each binary is linked separately, on a different machine and with different build flags); deltas below are relative to it.

Binary Function Master PR Δ vs median
programs/clickhouse DB::registerFunctionConversion(DB::FunctionFactory&) 6.4 s 11.5 s +7.9 s (+219%)
programs/clickhouse _ZN6detail10static_forITk7is_enumN2DB23AttributeUnderlyingTypeEZNS1_29callOnDictionaryAttributeType… 3.5 s 7.2 s +5.2 s (+263%)
Compile time of recompiled translation units

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

Job report

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Looks alright.

@alexey-milovidov alexey-milovidov self-assigned this Nov 15, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Nov 15, 2026
Merged via the queue into ClickHouse:master with commit d6fa719 Nov 15, 2026
570 of 572 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 15, 2026
lilredbot added a commit to JTCunning/ClickHouse that referenced this pull request Nov 16, 2026
 is the same fix)

Upstream ClickHouse#131667 (merged 2026-11-15) loads the statistics probe's primary
indexes in parallel the same way, so the branch is not to be submitted.
Run 1 of the A/B (-6.1%) had 2 of the 13 serial index loads in its window;
gen.sh now writes query.sql for the data it generates, and the lab README
says what a cold T1 run should select.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. pr-not-for-changelog This PR should not be mentioned in the changelog 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.

3 participants