Skip to content

Answer min/max/count aggregations from per-part column statistics - #115738

Merged
alexey-milovidov merged 18 commits into
masterfrom
min-max-from-statistics
Sep 4, 2026
Merged

alexey-milovidov merged 18 commits into
masterfrom
min-max-from-statistics

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 21, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Performance Improvement

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

Answer min, max and count aggregations without GROUP BY and filters directly from per-part column statistics (collected automatically for suitable columns by the auto_statistics_types MergeTree 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 setting use_statistics_for_min_max_aggregation (enabled by default).

A query of the form SELECT min(column), max(column), count() FROM table previously 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 100M EventDate values 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 than materialize_statistics_on_insert_max_table_size or written with materialize_statistics_on_insert = 0) are read normally and combined via AggregatingProjection. 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 as Float64 are rejected by a Field type check. Columns whose min/max the statistics do not track are declined up front (canStatisticsTrackMinMax): the default basic statistics type is declared for every column type but records min/max only for the numeric-like ones, so a String column must not pay a per-part statistics probe before falling back to a normal read. Nullable and LowCardinality columns are not supported yet (statistics do not track the NULL-skipping semantics of min/max); they can be added as a follow-up.

Measured on the 100M-row ClickBench hits table (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 = 1 shows the covered parts as a Statistics index entry, and EXPLAIN projections = 1 reports the pseudo projection with the number of parts and rows answered from statistics.

Documentation entry for user-facing changes

  • Documentation is written (the setting is documented in its definition, from which the documentation is generated)

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

Version info

  • Merged into: 26.9.1.731 (included in 26.9 and later)

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

clickhouse-gh Bot commented Aug 21, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [3521fd8]

Summary: ✅


AI Review

Summary

This PR adds a default-on rewrite that answers simple min/max/count() aggregations from per-part MergeTree column statistics instead of reading data. The earlier correctness issues around count(expr), metadata mutations, NaN, compatibility, and the fully short-circuited parallel-replicas path look addressed on the current tip, but one material performance hole remains: the new path still loads and copies every column's statistics for each candidate part, so I would not approve it yet.

Findings

⚠️ Majors

  • [src/Processors/QueryPlan/Optimizations/optimizeUseAggregateProjection.cpp:998] The new shortcut calls part->getEstimates() for every candidate part, and IMergeTreeDataPart::getEstimates() still does a full loadStatistics() / full-map estimate build for all columns on a cold part and returns a copy of the entire cached map on every later query (src/Storages/MergeTree/IMergeTreeDataPart.cpp:1439-1458). With the default auto_statistics_types = 'basic, uniq_v2', that means SELECT min(x), max(x), count() on a wide table can deserialize and copy unrelated per-column statistics blobs just to read one column's extrema. This breaks the PR's Performance Improvement contract and can make the new default-on path slower than the baseline narrow-column scan. Suggested fix: add a required-column estimate path (loadStatistics(required_columns) or getEstimates(required_columns)) and request only the columns referenced by stats_aggregates.
Tests
  • ⚠️ After narrowing the lookup, add a focused benchmark or profile on a wide table with default auto_statistics_types = 'basic, uniq_v2' to show the shortcut no longer deserializes unrelated columns and still wins over the baseline scan.
Final Verdict

Status: ⚠️ Request changes

  • Narrow the statistics load/estimate path to the aggregate's referenced columns, and provide one focused wide-table measurement showing the default-on optimization still improves or at least does not regress this query shape.

LLVM Coverage Report

Measured on commit 3521fd8.

Metric Baseline Current Δ
Lines 88.70% 88.70% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 81.00% 81.00% +0.00%

Changed lines: Changed C/C++ lines covered: 237/250 (94.80%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Aug 21, 2026

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.

Why is this code being placed into the projections usage?

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.

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

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.

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

clickhouse-gh Bot commented Aug 22, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 3521fd8b4 with master 6113efbf0 (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

8 object files changed (+27.90 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/QueryPlan/Optimizations/optimizeUseAggregateProjection.cpp.o 588.52 KiB 648.18 KiB +59.65 KiB (+10.14%)
src/CMakeFiles/dbms.dir/Storages/Statistics/StatisticsMinMax.cpp.o 83.16 KiB 64.79 KiB -18.37 KiB (-22.09%)
src/CMakeFiles/dbms.dir/Storages/Statistics/StatisticsBasic.cpp.o 106.08 KiB 88.43 KiB -17.65 KiB (-16.64%)

716 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

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

Job report

alexey-milovidov and others added 4 commits August 25, 2026 13:02
…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]>
@zoomxi

zoomxi commented Aug 26, 2026

Copy link
Copy Markdown
Contributor

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 _minmax_count_projection in the same pass, and statistics would extend them to min/max over non-key columns.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Thank you, @zoomxi! Agreed on both follow-ups: GROUP BY over (a prefix of) the partition key and partition-pruning filters already have the required machinery in the same pass (the implicit _minmax_count_projection builds its block per partition and filters parts before aggregating), so extending the statistics path to those cases is a natural next step, together with Nullable columns and materializing cheap minmax statistics on insert.

alexey-milovidov and others added 2 commits August 27, 2026 16:11
…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]>
@clickhouse-gh

clickhouse-gh Bot commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

⚠️ AI verdict: not_sure — no significant changes across 41 queries analysed

1 query inconclusive (baseline era shift, segment too thin). K_source=6 K_base=30 flagged=0/65

clickbench

⚠️ 3 inconclusive

Flagged queries (3 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 18 not_sure 1080 1155 +7.0% 0.0007
⚠️ 32 not_sure 1333 1420 +6.5% 0.0132
⚠️ 33 not_sure 1224 1312 +7.2% 0.0003

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
  • StressHouse run: 82afd3eb-34d7-4816-b1ae-3328ea716148
  • MIRAI run: e99fdb9e-4cdc-4e87-b5f8-e48c7d8d66fc
  • PR check IDs:
    • clickbench_1122310_1788491351
    • clickbench_1122413_1788491357
    • clickbench_1122545_1788491372
    • tpch_adapted_1_official_1122674_1788491419
    • tpch_adapted_1_official_1122776_1788491438
    • tpch_adapted_1_official_1122933_1788491565

…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`.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @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):

Comment thread src/Core/SettingsChangesHistory.cpp Resolved
@groeneai

Copy link
Copy Markdown
Collaborator

Both are unrelated to this pull request.

Stress test (amd_msan), Coordination mode mismatch: fixing PR in progress, #112660 (mine, open since 2026-07-30, no review yet).

Verified for this occurrence rather than assumed. The aborting query is 03279_pr_3_way_joins_right_first_left, and every query_log row under its initial_query_id (the initiator plus two replica-side queries) carries query_plan_optimize_join_order_randomize = 1, a value tests/clickhouse-test:1712 picks with probability 0.05 per run. 1 means "derive a seed", and QueryPlanOptimizationSettings.cpp:212-214 substitutes randomSeed() inside a constructor that runs once per plan construction, so the server logged three different seeds for the three plans of that one query:

{2137f44c-c5cc-459a-b2f3-e2ce4df738ef} Using random seed 4497400673924170155    (initiator)
{e63e2bcf-a40f-4e12-8baf-0a4877fa9be0} Using random seed 14563062883386667323   (replica)
{6541da21-6cf7-423b-b276-2c28a8bd0d3f} Using random seed 15491262922248287731   (replica)

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 (ParallelReplicasReadingCoordinator.cpp:1461, which is the stack in fatal.log). #112660 derives the seed from initial_query_id, identical for all three rows above.

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, test_s3_plain_rewritable: no fixing PR exists. A fix task owns it and I will post the fixing-PR link here when it opens.

Plain master fails the same case in the same check, at 691db87c896b (16:27:14Z), which is the master tip this run built your tree against, and at 257b90c684dd (15:13:22Z).

172.16.1.10:9000 is a cluster node's native port, not the object storage (minio1 is 172.16.1.5:9001 in that run's docker.log). One of the five server processes was killed: node4 stops logging at 17:19:41.194 in the middle of a BlobKillerThread round, with no <Fatal>, no Received signal, no sanitizer report and no shutdown line, while the other four log on to 17:20:05 and shut down normally, and the teardown ps aux dump shows node4 with no clickhouse server process. #85092 is a different mode, a row content assertion mismatch.

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 /docker leaf peak is 40.78 of 40.78 GiB in every one. The record that would name the breaching cgroup is the kernel's, and the job drops dmesg unless a cgroup counter fired, which a container level memcg kill does not move on cgroup v1. #117104 keeps that record, so it is a prerequisite for naming the mechanism, not the fix.

…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();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

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.

We can fix it later.

@clickhouse-gh clickhouse-gh Bot added the comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... label Sep 4, 2026

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

LGTM

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... 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.

5 participants