Skip to content

Load statistics of data parts in parallel - #126625

Merged
alexey-milovidov merged 10 commits into
masterfrom
stats-parallel-load
Oct 26, 2026
Merged

alexey-milovidov merged 10 commits into
masterfrom
stats-parallel-load

Conversation

@alexey-milovidov

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

Copy link
Copy Markdown
Member

Related: ClickHouse/ClickBench#2047

The consumers of statistics loaded them part by part, and each part does several small blocking reads (the index of statistics.packed, then one read per column), so on a cold disk the latencies of tens of parts add up (hundreds of milliseconds on EBS). This made ClickBench cold runs slower after auto statistics (basic, uniq_v2) were enabled by default.

This PR adds MergeTreeData::loadStatisticsOfPartsInParallel, which loads the statistics of the parts on up to max_threads threads of a local pool, the same way as the analysis of indexes in filterPartsByPrimaryKeyAndSkipIndexes, and uses it in all three consumers:

  • MergeTreeData::getConditionSelectivityEstimator (ordering of PREWHERE conditions, join ordering);
  • MergeTreeDataSelectExecutor::filterPartsByStatistics (part pruning by statistics);
  • makeBlockWithMinMaxFromStatistics (min/max/count answered from statistics).

The per-part results are combined sequentially in the order of parts, so the result does not depend on the scheduling. If several parts throw, the exception of the first of them (in the order of parts) is rethrown, so the error is deterministic as well. The existing per-part fallback in makeBlockWithMinMaxFromStatistics (a part whose statistics cannot be loaded is read instead) is kept as is.

Local cold-run measurement (stop server, drop page cache, start server, run a warm-up query on another table, run the query), a table with 100 UInt64 columns, auto statistics basic, uniq_v2 and 30 parts, local NVMe on a heavily loaded machine, query_duration_ms of 3 runs:

Query master this PR this PR, max_threads = 1
PREWHERE with 3 conditions 246, 397, 407 96, 112, 207 1454, 965, 329
min/max of 2 columns from statistics 837, 513, 1670 44, 37, 118 581, 2014, 211
all parts pruned by statistics 405, 394, 228 87, 39, 33 346, 266, 193

Changelog category (leave one):

  • Performance Improvement

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

The statistics of data parts are loaded in parallel (up to max_threads threads) for part pruning by statistics, the ordering of PREWHERE conditions and min/max/count from statistics. This speeds up the first queries over tables with many parts on a cold disk.

🤖 Generated with Claude Code


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

Version info

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

The consumers of statistics loaded them part by part, and each part does several
small reads (the index of `statistics.packed`, then one read per column), so on a
cold disk the latencies of tens of parts added up. This made ClickBench cold runs
slower after auto statistics were enabled by default:
ClickHouse/ClickBench#2047

Add `MergeTreeData::loadStatisticsOfPartsInParallel`, which runs the loading of
the parts on up to `max_threads` threads of a local pool (like the analysis of
indexes in `filterPartsByPrimaryKeyAndSkipIndexes`), and use it in all three
consumers: `MergeTreeData::getConditionSelectivityEstimator` (the ordering of
`PREWHERE` conditions and join ordering), `filterPartsByStatistics` (part pruning)
and `makeBlockWithMinMaxFromStatistics` (`min`/`max`/`count` from statistics).
The results are combined in the order of parts, and if several parts throw, the
exception of the first of them is rethrown, so nothing depends on the scheduling.

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

clickhouse-gh Bot commented Oct 18, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [d4e8e7f]

Summary: ✅


AI Review

Summary

Loads cold part statistics in parallel for pruning, selectivity estimation, and min/max/count aggregation, preserving ordered consumption and a synchronous warm path. No remaining actionable findings at d4e8e7f4bee4e44b3a801d09de59680f8878f00a; the prior findings are addressed. The new stateless test matches its reference, and the 1,000-part, 100-column warm-memory reproduction passes under a 10 MiB query limit with max_threads = 1 and 8.

Final Verdict

✅ Approve.

@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 18, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit d4e8e7f4bee4e44b3a801d09de59680f8878f00a was not compared: the CI logs cluster did not answer (exception 241, code 500: { "meta": [ { "name": "file", "type": "String" }, { "name…).

See the job log for details.

alexey-milovidov and others added 2 commits October 21, 2026 07:12
`loadStatisticsOfPartsInParallel` now takes a `consume_part` callback, which is called in the order of parts in the calling thread. The parts are loaded in batches of `2 * num_threads`, and a batch is consumed (and its loaded statistics released) before the next one is loaded, so the statistics of the entire selection are no longer held at once. This matters because the loaded statistics are not freed by the eviction from the statistics cache while held, and they are loaded under `MemoryTrackerBlockerInThread`.

The jobs also stop taking new parts once the pool is finished (its destructor has started because a later `scheduleOrThrowOnError` has thrown), like in `filterPartsByPrimaryKeyAndSkipIndexes`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov and others added 2 commits October 23, 2026 07:45
…g thread

Only the parts whose statistics (or estimates) are not in memory are loaded
by the thread pool; the others are copied synchronously right before they are
consumed, so a warm query does not schedule any jobs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov and others added 5 commits October 24, 2026 21:59
The parallel loading checked whether the statistics of every part were in the
cache, and then loaded them, so a warm query looked up the statistics of every
column twice. This made planning slower for tables with many parts: the
`join_planning_pruned_statistics` performance test reported +22.6% on query 1.
Now the statistics in memory are loaded from the cache directly, and only the
parts with a miss are loaded in the pool.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=126625&sha=892dde08716ddd5c1a4c544371d768f4cf0d7422&name_0=PR&name_1=Performance%20Comparison%20%28arm_release%2C%20master_head%2C%205%2F6%29
#126625

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…allel_load`

The inserted parts have their estimates already and the statistics were in
memory, so every query of the test took the synchronous path. Now the table is
reattached before each cold query, with `prewarm_statistics_cache = 0`, the
parallel results are compared with the sequential ones, and planning-only
queries check that the cold loads use the pool and the warm ones do not.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…well

`loadStatisticsOfPartsInParallel` loaded the statistics of all parts that are in memory
in a single pass before consuming any part, so the estimates of every warm part of the
selection were held at once. Now the parts are processed in windows of `4 * max_threads`
consecutive parts: the parts of a window that are in memory are loaded in the calling
thread (and consumed at once if no part before them is left to load), the others are
loaded in the pool (or in the calling thread if there is only one), and the window is
consumed in the order of parts before the next one is processed. The pool is created on
the first window that needs it, so a warm query still does not use it.

`05407_statistics_parallel_load` gets a case with a few warm parts in the middle of cold
ones. It is also tagged `no-parallel`: it counts the misses of the process-wide statistics
cache, but concurrent queries to `system.parts_columns` load the statistics of all tables,
and the late-destroyed parts of a detached table evict the entries of the reattached parts,
which share the key. That made the counts differ in the targeted ASan/UBSan run:
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=126625&sha=404ec21155b6defa31aeb66b6c90fdd160fe3f4b&name_0=PR&name_1=Stateless%20tests%20%28arm_asan_ubsan%2C%20targeted%29
#126625

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

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=126625&sha=404ec21155b6defa31aeb66b6c90fdd160fe3f4b&name_0=PR&name_1=Stateless%20tests%20%28arm_binary%2C%20AsyncInsert%2C%20s3%20storage%2C%20parallel%29 (02530_dictionaries_update_field_hashed and 02530_dictionaries_update_field_complex_key_hashed hit the 600 s deadline in a while clickhouse_test_time_left loop, in several jobs on 2026-10-25), and provide a fix in a separate PR. If the fix is already in progress, link it here.

The other unrelated failures of 404ec21 are covered: the fixes for 05315_plain_rewritable_part_removal_without_copies (#127763), 05045_create_token (#127762) and test_s3_disk_apply_new_settings (#127679) are merged and now in this branch. 00563_insert_into_remote_and_zookeeper_long and 01532_execute_merges_on_single_replica_long are addressed by #127766. 05407_statistics_parallel_load (targeted run) was caused by this PR and is fixed in d05d94d.

@groeneai

Copy link
Copy Markdown
Collaborator

This is the repeated DST hour of 2026-10-25 (the CI server runs in Europe/Amsterdam): ClickHouseDictionarySource sent the update_field bound as local wall-clock text, which resolves to the earlier occurrence, so every update re-read Second together with SecondUpdated, and hashed / complex_key_hashed keep the first fetched row of a key (flat keeps the last one and did not fail). All failures of the family are in jobs started on 2026-10-25 between 00:00 and 01:40 UTC, none after. The fix is in progress: #127765

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

All good.

@alexey-milovidov alexey-milovidov self-assigned this Oct 26, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 26, 2026
Merged via the queue into master with commit 448c85f Oct 26, 2026
179 checks passed
@alexey-milovidov
alexey-milovidov deleted the stats-parallel-load branch October 26, 2026 22:11
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 26, 2026
alexey-milovidov added a commit that referenced this pull request Oct 26, 2026
Resolve the conflicts with #126625,
which loads the statistics of parts in parallel and added
`tryLoadStatisticsFromCache` and `tryGetEstimatesFromMemory` on top of the
per-column statistics cache. Adapt them to the cache with one entry per part
of this PR: `tryGetStatisticsFromCache` probes the entry of the part, and
`filterStatistics` (shared with `loadStatistics`) picks the requested columns.
`getEstimates` and `tryGetEstimatesFromMemory` take no columns, as the
estimates of all columns are memoized at once.

Update the reference of `05407_statistics_parallel_load`: a cold part now
counts one `StatisticsCacheMisses` instead of one per column.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov added a commit that referenced this pull request Oct 27, 2026
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]>
syoshida20 pushed a commit to syoshida20/ClickHouse that referenced this pull request Nov 1, 2026
Add three rules to the agent instructions:

- `.claude/skills/review/SKILL.md`, triggered expansion "Jobs on other
  threads": list everything a scheduled job uses, including a lambda or
  `std::function` it calls, and check that each outlives the join on
  every exit after the first schedule (a later schedule throws, the
  scheduling thread throws while doing its own share, an early return).
  The joiner is declared after everything the jobs use, and a closure
  that refers to the pool is captured by value.
- Same file, "A fix is new code": a re-review covers the code changed
  since the previous review, including the fixes for earlier findings,
  with the same gates as the first review.
- `.claude/CLAUDE.md`: the same lifetime rule for authors.

The last round of ClickHouse#126625 moved the job body of
`loadStatisticsOfPartsInParallel` into a closure declared after the
pool, called by the jobs through `[&]`. A later schedule that threw
destroyed the closure before the pool joined the jobs (fixed by
ClickHouse#127911). The AI review approved that round with "the prior findings
are addressed", and Stress tests, the only ones that inject thread
creation failures broadly, were green on the final head.

Asked for in
ClickHouse#127911 (comment)

The reply there listed "`wait` rethrows" as an exit; it is not in the
rule because `ThreadPool::wait` and
`waitForAllToFinishAndRethrowFirstError` join all jobs before
rethrowing.

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
subkanthi pushed a commit to subkanthi/ClickHouse that referenced this pull request Nov 22, 2026
…llel

For a filter on a `JSON` path or on a key of a `Map` with
`map_serialization_version = 'with_buckets'`, the PREWHERE optimizer computes the
exact size of the subcolumn in every costed part, and for these types that reads
the serialization prefixes of the part (3 files per part for a JSON path, 1 for a
bucketed Map). `ReadFromMergeTree::getColumnSizesForPrewhere` (pruned parts) and
`MergeTreeData::getColumnSizes(columns, true)` (every active part) did it part
after part, subcolumn after subcolumn, in the planning thread, with one reader per
subcolumn: `getSubcolumnSize` sizes one name. When the prefixes are not in memory,
the planning latency is the number of parts times the sequential round trips: on
26.10 with a MinIO on loopback, 30 / 150 / 300 GETs and 25 / 113 / 238 ms of
planning for 10 / 50 / 100 parts, all on one thread (ClickHouse#129228). Two paths of one
JSON column built two readers per part and read the column's shared prefix twice.

Both loops now go through `MergeTreeData::addColumnSizesOfParts`, which runs
`loadStatisticsOfPartsInParallel` (ClickHouse#126625) over the parts: the parts whose sizes
are memoized are summed in the calling thread, the others are sized on up to
`max_threads` threads of a local pool (no pool on a warm query), and the sizes are
handed over through `consume_part` in part order rather than through the
1024-entry LRU memo of the part, which a query sizing more subcolumns would evict.

Per part, `IMergeTreeDataPart::getColumnAndSubcolumnSizes` resolves every name
first, as the loops did (a physical column may have the name of a subcolumn of
another one), and sizes the subcolumns that are not memoized with one
`getSubcolumnSizes` call per storage column, so the subcolumns of one column share
one reader and read a prefix they share once. Not one reader per part:
`MergeTreeReaderWide::getAllColumnsSubstreams` reads the prefixes of every column
of the reader as soon as one of them needs them, which would read, e.g., the
dictionary of a `Map(LowCardinality(String), ...)` key that is otherwise not read.

The sizes and the PREWHERE decisions are unchanged. The `max_threads` of
`MergeTreeData::getColumnSizes` is the query's, taken from `CurrentThread` (the
storage method has no context); without a query context the sizing runs in the
calling thread.

Related: ClickHouse#129228

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

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