Skip to content

Analyze the primary key of a part once per read when deciding whether to load statistics - #131129

Open
groeneai wants to merge 3 commits into
ClickHouse:masterfrom
groeneai:perf/statistics-primary-key-probe-once
Open

groeneai wants to merge 3 commits into
ClickHouse:masterfrom
groeneai:perf/statistics-primary-key-probe-once

Conversation

@groeneai

@groeneai groeneai commented Nov 12, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #126627

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 (every part after a restart or ATTACH) runs the bounded primary key probe MergeTreeDataSelectExecutor::hasFewerMarksToReadThan to decide whether loading statistics pays off. With more than one condition it ran three times over the same parts and key condition: twice in getPartsForPrewhere and once in selectRangesToRead. @ snelheidai measured it on ClickBench Q36-Q42 (#126627 (comment)).

The per-part mark count found by the probe is now memoized in ReadFromMergeTree::Indexes, like SkipIndexOrderCache. This is the patch of @ snelheidai (#126627 (comment)) with one guard: an entry is reused only for the same part ranges and the same number of key condition transformations, because sampling adds a transformation to the key condition in place after the probe. Decisions are unchanged.

Validation, RelWithDebInfo, master 63accaa2f95d vs this PR, new perf test statistics_small_read_many_parts (500 parts after DETACH/ATTACH):

  • IndexBinarySearchAlgorithm per query 2000 -> 1000 (several conditions) and 1500 -> 1000 (one condition), LoadedStatistics 0 on both, identical results and EXPLAIN indexes = 1, actions = 1.
  • perf.py --runs 15, ratio PR / master in both server orders: 0.85 / 0.93 / 0.91 and 0.89 / 0.85 / 0.80 (p < 0.001). clickhouse-benchmark agrees with the binaries swapped between ports; with the probe disabled (min_marks_per_part_to_load_statistics = 0) the difference is within the ~2 ms port noise.
  • A SAMPLE read analyzed twice probes again after sampling (16 binary searches, 12 without the guard) and decides like master.
  • 242 statistics and SAMPLE stateless tests pass (4 more need test.hits or MinIO); 18 statistics tests 50/50 with random settings.

#130221 adds another hasFewerMarksToReadThan call; whichever PR lands second should pass the cache there.


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

groeneai and others added 2 commits November 12, 2026 20:40
… to load statistics

Since ClickHouse#126627, a read whose parts do not have their statistics in memory runs the bounded primary key
probe `MergeTreeDataSelectExecutor::hasFewerMarksToReadThan` to decide whether loading the statistics
pays off. With more than one condition it ran three times over the same parts and key condition: in
`getPartsForPrewhere` (pruning by statistics, then ordering PREWHERE) and again in `selectRangesToRead`.

Memoize the per-part mark count found by the probe in `ReadFromMergeTree::Indexes`, like
`SkipIndexOrderCache`. An entry is reused only for the same part ranges and the same number of key
condition transformations: sampling adds a transformation to `indexes->key_condition` in place after the
probe, and a later analysis of the same step must not get the count of the condition before sampling.
Decisions are unchanged: same parts pruned, same PREWHERE order, same `use_statistics`.

The measurement and the first version of the patch are by @ snelheidai in
ClickHouse#126627 (comment).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Shorten the PrimaryKeyProbeCache comment to its invariant; drop three comments that restate the code.

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

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 1 finding) plus my own cold review (2 nits).

# Sev Finding Verdict Evidence / action
1 ⚠️ The perf test cannot detect removal of the memo or a wrong reuse after SAMPLE; add a stateless test asserting exact IndexBinarySearchAlgorithm counts DISAGREE A perf PR ships a perf test: its PR-vs-master comparison is the oracle (locally 0.80-0.93, 2000/2000/1500 -> 1000/1000/1000 binary searches per run). The probe's decisions are already asserted by 05407_statistics_skip_small_reads, identical on both builds and 900/900 with random settings; exact counts are not stable under randomized granularity.
2 💡 PrimaryKeyProbeCache::marks is a map whose entries also have a marks field noted naming only, not blocking
3 💡 #130221 adds a 4th hasFewerMarksToReadThan call without the cache noted stated in the description; the default nullptr keeps that call correct

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

Session id: cron:clickhouse-review-slot-10:20261112-210723

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. On the perf test fixture (500 parts, statistics not in memory after DETACH/ATTACH) every run of the three queries shows IndexBinarySearchAlgorithm 2000 / 2000 / 1500 on master and 1000 / 1000 / 1000 with this PR, LoadedStatistics 0 on both.
b Root cause explained? hasFewerMarksToReadThan is a pure function of (part, ranges, key condition, settings), but its three callers in one read step (getPartsForPrewhere twice, selectRangesToRead once) each recomputed markRangesFromPKRange for every part.
c Fix matches root cause? Yes. The per-part answer is memoized in ReadFromMergeTree::Indexes, the owner of the key condition, like SkipIndexOrderCache. No decision, bound or setting changes.
d Test intent preserved / new tests added? New perf test statistics_small_read_many_parts.xml. Decisions are unchanged and covered by the existing statistics tests: 242 runnable statistics and SAMPLE tests pass, 18 of them 50/50 with random settings.
e Both directions demonstrated? Yes: probe counts above; perf.py --runs 15 ratio PR / master 0.85 / 0.93 / 0.91 and 0.89 / 0.85 / 0.80 in both server orders; clickhouse-benchmark with the binaries swapped between ports; no difference beyond port noise with the probe disabled.
f Fix is general across code paths? All three probe call sites pass the cache; the remaining filterPartsByStatistics call never probes (key_condition = nullptr). Copies of Indexes share the cache only with the same key condition, and a rebuilt Indexes gets a new one.
g Fix generalizes across inputs (params/datatypes/wrappers)? One, two and five conditions; a SAMPLE read analyzed twice (the guard recomputes after sampling: 16 vs 12 binary searches without it, decisions as on master); the same part with other ranges; projection parts (parent-qualified key).
h Backward compatible? (maintainer-approved exception only) Yes. No setting, default or format change; identical results and EXPLAIN indexes = 1, actions = 1.
i Invariants and contracts preserved? A cached count is returned only for the same part, ranges and number of key condition transformations within one step. The lock is not held across the analysis, and an early return leaves only complete entries.

Session id: cron:clickhouse-impl-slot-40:20261112-203700

@clickhouse-gh

clickhouse-gh Bot commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [0f48ff6]

Summary: ✅


AI Review

Summary

Reviewed #131129 at 0f48ff6c3e198ab4c3b58ee2aad7a680c304e219. The change memoizes bounded primary-key probes used to decide whether loading column statistics pays off. No actionable findings remain after reviewing the diff, surrounding callers, prior discussion, existing regression coverage, and supplied performance measurements. No inline comments were posted.

Missing context / blind spots
  • ⚠️ No local ClickHouse binary or build directory was available, so tests and benchmarks were not independently rerun. Performance evidence comes from the measurements recorded in the PR and linked discussion; an independent benchmark run would close this verification gap.
Final Verdict

Status: ✅ Approve. No required changes.

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

clickhouse-gh Bot commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 0f48ff6c3 with master acd88ab8f (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.

Slowest function optimization changes (ThinLTO)

Median per-function time ratio to the master baseline: programs/clickhouse ×0.57, programs/clickhouse-keeper ×0.60 (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.3 s 12.0 s +8.4 s (+234%)
programs/clickhouse _ZN6detail10static_forITk7is_enumN2DB23AttributeUnderlyingTypeEZNS1_29callOnDictionaryAttributeType… 3.6 s 7.3 s +5.2 s (+256%)
Compile time of recompiled translation units

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

Median compile-time ratio to the baselines is ×0.93 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost -187.3 s (-5%) in total before that adjustment.

Job report

The Iceberg configuration of the performance comparison rewrites the
MergeTree table of the test as an Iceberg table, where the fill query
`SELECT throwIf(count() != 500) FROM system.parts ...` throws (Code 395),
so the test produced no metrics and the report of every Iceberg job of
the pull request failed ("Errors while building the report.").

The test measures the statistics and the primary key analysis of
MergeTree parts and reattaches the table to reload the statistics, so it
has no meaning on Iceberg tables: opt it out with `<test iceberg="0">`.
The skip list is not used because a change to
`tests/performance/iceberg_skip_list.txt` counts as a change to the
Iceberg harness and runs the configuration on every selected test.

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

This branch has not been deployed

No deployments
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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant