Repository navigation
Answer min/max/count aggregations from per-part column statistics - #115738
Conversation
A query of the form SELECT min(column), max(column), count() FROM table without GROUP BY and filters is now answered from per-part column statistics (see `StatisticsMinMax`, collected automatically for suitable columns by the `auto_statistics_types` MergeTree setting) for the data parts that have them materialized, so no data is read for such parts. Parts without statistics (e.g. freshly inserted ones) are read normally and combined with the statistics of the other parts, like the exact count optimization does. The optimization is controlled by the new setting `use_statistics_for_min_max_aggregation` (enabled by default). It is disabled for anything that changes the visible rows or values at read time: FINAL, sampling, lightweight deletes, pending mutations, patch parts, masking policies, and the delete bitmap of unique-key tables. Nullable and LowCardinality columns are not supported yet. This speeds up ClickBench Q6 (SELECT MIN(EventDate), MAX(EventDate) FROM hits) from tens of milliseconds to about a millisecond: https://benchmark.clickhouse.com/ Co-Authored-By: Claude Fable 5 <[email protected]>
|
Workflow [PR], commit [3521fd8] Summary: ✅
AI ReviewSummaryThis PR adds a default-on rewrite that answers simple Findings
Tests
Final VerdictStatus:
LLVM Coverage ReportMeasured on commit 3521fd8.
Changed lines: Changed C/C++ lines covered: 237/250 (94.80%) · Uncovered code |
There was a problem hiding this comment.
Why is this code being placed into the projections usage?
There was a problem hiding this comment.
🕵 Because the machinery this optimization needs already exists there, and only there.
Answering min/max/count from per-part statistics is not "all or nothing": some parts have the statistics materialized and some do not (freshly inserted parts, since materialize_statistics_on_insert is disabled by default). So the plan has to be: produce one row of aggregate function states per covered part, read the remaining parts normally, and combine the two with AggregatingProjection. That is exactly the shape of the existing exact-count optimization (only_count_column / MinMaxProjectionCandidate in this file): a prepared source contributing partial states plus a narrowed ReadFromMergeTree for the leftovers, with the reading step disappearing entirely when all parts are covered.
Reimplementing it elsewhere would mean duplicating canUseProjectionForReadingStep and its guards (FINAL, sampling, patch parts, pending mutations, lightweight deletes, masking policies), the candidate and parts-splitting logic, and the AggregatingProjection wiring - and every future fix to those guards would have to be applied twice. Reusing them here keeps the guards in one place; the optimization is even presented as a pseudo projection (_statistics_min_max_projection) so EXPLAIN projections = 1 reports it uniformly.
If you would prefer it in a separate file, the natural refactoring is to first extract the shared "aggregate from a prepared per-part source" part of this file into a common helper, which I would rather do as a follow-up than inside this PR.
There was a problem hiding this comment.
Because it is implemented with "virtual projections".
The setting was recorded under `26.7`, but `master` is now `26.8`, so the `settings_changes_history` style check failed.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes8 object files changed (+27.90 KiB total), 0 added.
716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units317 translation units recompiled, 2801 s compile time in total, 317 of them have a recent master baseline. |
…nounce the fully short-circuited read Two fixes for the `_statistics_min_max_projection` optimization: - Accept only a zero-argument `count()`: `count(expr)` must still evaluate the argument (it can throw) when combined with `min`/`max` in one query, where no other shortcut applies. - When the statistics block covers all parts, mark the read as short-circuited with a prepared source, so the detached `ReadFromMergeTree` announces its empty read set to the parallel replicas coordinator. Without it, a follower that does not take the same short-circuit requests a stream the coordinator never registered, tripping the "Got read request from replica N for unknown stream" exception with `LOGICAL_ERROR` (reproduced locally with the failpoint, same class of bug as issue #110518). Co-Authored-By: Claude Fable 5 <[email protected]>
- Pin `optimize_aggregation_in_order` and the other settings the projection optimization's eligibility depends on: the test runner randomizes `optimize_aggregation_in_order`, and aggregation-in-order disables the optimization entirely, turning the EXPLAIN liveness checks into 0. This is what failed the flaky checks in https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=115738&sha=2be0c499fb23ea77e99d52effcec3b95abb06e04&name_0=PR - Add a case for `count` over an expression: the statistics shortcut must decline and the expression must be evaluated (and throw), covering the new zero-argument gate. The trivial count optimization is disabled where it would mask the check. Related: #115738 Co-Authored-By: Claude Fable 5 <[email protected]>
The `_statistics_min_max_projection` counterpart of test 04545: when the statistics block covers all parts, the fully short-circuited read must announce its empty read set to the coordinator. Verified live: without the announcement fix the test reproduces the "Got read request from replica 1 for unknown stream" exception with `LOGICAL_ERROR`. Co-Authored-By: Claude Fable 5 <[email protected]>
|
Hi @alexey-milovidov — this is a cleaner design than my earlier attempt in #105197, which I've closed in favor of this PR. If you consider follow-ups, two extensions may be worth it: GROUP BY partition key and partition-level filters. Both already work for the implicit |
|
🕵 Thank you, @zoomxi! Agreed on both follow-ups: |
…UMN mutations Pending `RENAME COLUMN` / `DROP COLUMN` mutations are metadata mutations applied at read time by `AlterConversions`, so the column data (and statistics) physically stored in a part may not belong to the column the query reads: `DROP COLUMN b, ADD COLUMN b` must read as the new default, and a name freed by a drop can be taken over by a rename. The guard only rejected `hasAlterMutations` (pending `MODIFY COLUMN`), so test 04872_read_renamed_then_dropped_and_readded_column got stale `min`/`max` answers from the statistics of the old column in the cases where the part-side and query-side column names coincide. Also reject `hasMetadataMutations`. Failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=115738&sha=687cbdfe1ff38aaf469100ed69617cec0a2eeb9c&name_0=PR&name_1=Fast%20test PR: #115738 Co-Authored-By: Claude Fable 5 <[email protected]>
…`SettingsChangesHistory.cpp` The 26.8 release went out while this PR was open, so the style check now requires the new setting to be recorded under the current version block. Co-Authored-By: Claude Fable 5 <[email protected]>
|
📊 Cloud Performance Report
1 query inconclusive (baseline era shift, segment too thin). K_source=6 K_base=30 flagged=0/65 clickbenchFlagged queries (3 of 43)
Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. tpch_adapted_1_official🟢 No significant changes Debug info
|
…not tracked `basic` is the default `auto_statistics_types` and, unlike the deprecated `minmax` type, it is declared for every column type: `basicStatisticsValidator` accepts everything, because the default-value count it collects is defined for any column. Its min/max sub-statistics, however, are populated only for numeric-like columns (`StatisticsBasic::hasNumericMinMax`). The eligibility check in `getStatisticsMinMaxAggregates` only looked at which statistics types are *declared* for the column, so `SELECT min(str), max(str) FROM table` on a table with the default settings built a statistics candidate, called `IMergeTreeDataPart::getEstimates` for every part (reading the statistics files on the first execution, and copying the estimates map under a mutex on every later one), found no min/max in them, and only then fell back to a normal read. That is an `O(parts)` metadata probe added to a query shape the optimization can never answer. Reject such columns up front. To keep the check from drifting away from the statistics implementations, the numeric-type test is extracted into `canStatisticsTrackMinMax` and used by `minMaxStatisticsValidator` and `StatisticsBasic` as well. Addresses #115738 (comment)
Test 04512 pins the shortcut against `auto_statistics_types = 'minmax'`, but the default is `basic, uniq_v2`, and `ColumnStatistics::getEstimate` reads min/max from a different sub-statistic there. Add a test that answers `min`/`max`/`count` from `basic` statistics - both with the default value of `auto_statistics_types` and with `basic` requested alone - compares the result with the same query run with `use_statistics_for_min_max_aggregation = 0`, and checks that a `String` column, for which `basic` is declared but tracks no min/max, is read normally. The default value is spelled out in the `CREATE TABLE` instead of being left out, because `clickhouse-test` randomizes every MergeTree setting a test does not set itself, and `auto_statistics_types` is one of them. Addresses #115738 (comment)
`min` and `max` skip `NaN` and return it only when every value is `NaN`, but a part whose values are all `NaN` reports `NaN` as both of its extremes via `getExtremes`. Folding the per-part extrema with the raw `Field` ordering therefore let a single all-`NaN` part poison the answer: with covered parts `[nan, nan]` and `[1, 2]` the shortcut answered `nan` for `max` while a normal read answers `2`. Fold float extrema with the same rule as `SingleValueDataFixed::setIfGreater` and `SingleValueDataFixed::setIfSmaller`: a `NaN` value never replaces a non-`NaN` accumulator, and any value replaces a `NaN` accumulator. Also decline parts with zero rows, for which `getExtremes` reports zeros rather than the absence of a value. New test `05053_min_max_aggregation_from_statistics_nan`.
|
🕵 @groeneai, investigate the failures, they look unrelated to this pull request, and provide a fix in a separate PR (if the fix is already in progress, link it here):
|
|
Both are unrelated to this pull request. Stress test (amd_msan), Verified for this occurrence rather than assumed. The aborting query is The seed replaces the relation statistics, so the plans pick different leftmost relations, a different table is asked to read in order in each, and the announcements for the one bare table name meet in the same coordinator ( One correction on the family: #106039 was closed on 2026-08-26 by #114916, which fixed a different carrier, a parameterized view planning its own read on a follower, and that fix is an ancestor of the tree that failed here. So this is a sibling carrier rather than a reopen. #112660 removes only this carrier: divergent per-replica real statistics and the process-global hash table statistics cache can also split join order without the setting. Integration tests, Plain master fails the same case in the same check, at
I cannot yet say what killed it. The counters this job retains do not discriminate: across the 7 runs of this check I measured, 3 red and 4 green, the |
…ectors `StatisticsBasic::build` and `StatisticsMinMax::build` are fed one output chunk at a time by `MergeTask` and `MutateTask`, and they folded the per-chunk extrema with the raw `Field` ordering. `IColumn::getExtremes` skips `NaN` and reports it only when every value of the chunk is `NaN`, and every comparison against `NaN` is false, so a part whose first chunk is all `NaN` kept `NaN` as its materialized extremum even when later chunks were finite. Fold with the same IEEE-754 rule as `SingleValueDataFixed::setIfSmaller` and `SingleValueDataFixed::setIfGreater` (shared as `StatisticsUtils::updateMin` and `StatisticsUtils::updateMax`), which is what the `min` and `max` aggregate functions themselves use. Record `use_statistics_for_min_max_aggregation` in `SettingsChangesHistory` as `false, true`, so `compatibility` below 26.9 keeps the pre-existing plan. Extend the test with a single part merged from an all-`NaN` prefix and a finite suffix, and renumber it to 05055.
| Estimates estimates; | ||
| try | ||
| { | ||
| estimates = part->getEstimates(); |
There was a problem hiding this comment.
IMergeTreeDataPart::getEstimates() is a part-wide cache fill, not a per-column lookup: on a cold part it calls loadStatistics() and deserializes every column's statistics blob before materializing estimates for the whole map (src/Storages/MergeTree/IMergeTreeDataPart.cpp:1439-1456). On current master the default auto_statistics_types is basic, uniq_v2, and uniq_v2 alone carries an HLL sketch of about 3 KiB per column (src/Storages/Statistics/StatisticsUniqV2.cpp:18).
That means this new fast path turns SELECT min(x), max(x), count() on a wide table into an all-columns statistics scan for every touched part just to read one column's extrema. For tables with many columns or many active parts, the first run can do substantially more metadata I/O and memory allocation than the baseline narrow-column read, which breaks the PR's performance contract even though the query reads 0 data rows.
Please load only the statistics for the columns actually used by stats_aggregates here, e.g. via loadStatistics(required_columns) or a dedicated getEstimates(required_columns) helper, instead of priming the whole estimates cache.
There was a problem hiding this comment.
We can fix it later.
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Answer
min,maxandcountaggregations withoutGROUP BYand filters directly from per-part column statistics (collected automatically for suitable columns by theauto_statistics_typesMergeTree setting), reading no data for the parts that have statistics materialized. This speeds up ClickBench Q6 (SELECT MIN(EventDate), MAX(EventDate) FROM hits) from tens of milliseconds to a few milliseconds. Controlled by the new settinguse_statistics_for_min_max_aggregation(enabled by default).A query of the form
SELECT min(column), max(column), count() FROM tablepreviously had to read the whole column when the column is neither the first primary key column nor a partition key column: for ClickBench Q6 that means scanning all 100MEventDatevalues on every run (>60 ms on the reference machine: https://benchmark.clickhouse.com/). Meanwhile the per-part statistics collected by default (auto_statistics_types = 'basic, uniq_v2') already store the exact minimum and maximum of every numeric-like column per part.The optimization is modeled on the exact count optimization in
optimizeUseAggregateProjection.cpp: parts with valid statistics contribute one row of aggregate function states through a prepared source (pseudo projection_statistics_min_max_projection), and the parts without statistics (parts written before the statistics were declared, and freshly inserted parts of a table larger thanmaterialize_statistics_on_insert_max_table_sizeor written withmaterialize_statistics_on_insert = 0) are read normally and combined viaAggregatingProjection. When all parts are covered, the reading step disappears entirely.The optimization is disabled for anything that changes the visible rows or values at read time:
FINAL, sampling, lightweight deletes, pending mutations, patch parts, masking policies, and the delete bitmap of unique-key tables (all reusing the same guards as the projection optimizations, plus per-part checks). Legacy statistics that stored min/max lossily asFloat64are rejected by aFieldtype check. Columns whose min/max the statistics do not track are declined up front (canStatisticsTrackMinMax): the defaultbasicstatistics type is declared for every column type but records min/max only for the numeric-like ones, so aStringcolumn must not pay a per-part statistics probe before falling back to a normal read. Nullable andLowCardinalitycolumns are not supported yet (statistics do not track the NULL-skipping semantics ofmin/max); they can be added as a follow-up.Measured on the 100M-row ClickBench
hitstable (fully merged state, 96-core machine,clickhouse benchmark): Q6 goes from 36 QPS reading 100M rows per query to 171 QPS reading 0 rows; on the 16-vCPU reference machines the baseline is ~60 ms, dominated entirely by the scan that this optimization removes. In the partially merged state right after data loading (79% of rows in merged parts), the query reads only the remaining 21%.EXPLAIN indexes = 1shows the covered parts as aStatisticsindex entry, andEXPLAIN projections = 1reports the pseudo projection with the number of parts and rows answered from statistics.Documentation entry for user-facing changes
Workflow [PR]
Sync PR [sync-upstream/pr/115738]
Version info
26.9.1.731(included in26.9and later)