Skip to content

Answer sum, avg and sumCount from per-part statistics - #123950

Merged
alexey-milovidov merged 29 commits into
masterfrom
small-perf-wins-from-lowlevel-pattern-audit-2026-09-19
Nov 10, 2026
Merged

alexey-milovidov merged 29 commits into
masterfrom
small-perf-wins-from-lowlevel-pattern-audit-2026-09-19

Conversation

@NIKTONIKTO717

@NIKTONIKTO717 NIKTONIKTO717 commented Oct 5, 2026 •

Copy link
Copy Markdown
Member

basic statistics now keep exact sums of integer/Decimal columns, so sum, avg, sumCount without GROUP BY/filters read only parts lacking them. ClickBench create.sql minus auto_statistics_types = '', loaded with this PR: Q2, Q3 are instant (1 ms vs 16-22 ms), Q29 2x faster.

Setting use_statistics_for_sum_avg_aggregation (off with compatibility < 26.11); needs basic statistics.

Design: sum is a trailing basic field (old readers skip it) in sum's accumulator type and wraparound; states via deserialize; merges backfill old parts.

Downsides: not stored for Nullable/LowCardinality; pseudo-projection renamed _statistics_projection; mixed-version replicas fetch merged parts.

Changelog category (leave one):

  • Performance Improvement

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

sum, avg and sumCount of integer and Decimal columns without GROUP BY and filters are now answered from basic column statistics without reading the data, and so is count(column) in such queries. Controlled by the new setting use_statistics_for_sum_avg_aggregation (enabled by default). Parts written by older versions get the sum on their next merge.


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

Version info

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

@NIKTONIKTO717 NIKTONIKTO717 added the pr-performance Pull request with some performance improvements label Oct 5, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [7e2be7b]

Summary: ❌

job_name test_name status info comment
Storage memory check FAIL
07_many_parts.sql FAIL cidb IGNORED

AI Review

Summary

The PR answers unfiltered sum, avg, sumCount, and eligible count(column) aggregations from per-part statistics, with reads for parts lacking usable summaries. Reviewed head 7e2be7bcb3d9ae7ce0621a96d18b3e14317ba932 and all prior discussion; earlier findings are addressed and no new findings remain. Both new stateless regressions (05320 and 05567) passed using the PR-head fast-test binary, including the expected ILLEGAL_DIVISION exceptions with the optimization enabled and disabled.

Final Verdict

Status: ✅ Approve. No unresolved findings.

@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Oct 5, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 7e2be7bcb with master b351954fd (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

162 object files changed (+1.09 MiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/QueryPlan/Optimizations/optimizeUseAggregateProjection.cpp.o 790.34 KiB 884.07 KiB +93.74 KiB (+11.86%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionUniq.cpp.o 13.56 MiB 13.63 MiB +63.83 KiB (+0.46%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionSum.cpp.o 3.81 MiB 3.86 MiB +50.38 KiB (+1.29%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionCovar.cpp.o 6.88 MiB 6.93 MiB +48.01 KiB (+0.68%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionCorr.cpp.o 7.07 MiB 7.11 MiB +47.73 KiB (+0.66%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionGroupArrayMov… 5.89 MiB 5.93 MiB +42.53 KiB (+0.70%)
src/CMakeFiles/dbms.dir/Storages/Statistics/StatisticsBasic.cpp.o 108.12 KiB 144.52 KiB +36.40 KiB (+33.67%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionGroupNumericI… 5.79 MiB 5.82 MiB +31.68 KiB (+0.53%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionUniqCombined1… 3.12 MiB 3.14 MiB +24.21 KiB (+0.76%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionUniqCombined1… 3.11 MiB 3.14 MiB +24.20 KiB (+0.76%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionUniqCombined2… 3.11 MiB 3.14 MiB +24.20 KiB (+0.76%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionUniqCombined1… 3.11 MiB 3.14 MiB +24.20 KiB (+0.76%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionUniqCombined1… 3.11 MiB 3.14 MiB +24.20 KiB (+0.76%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionUniqCombined1… 3.11 MiB 3.14 MiB +24.20 KiB (+0.76%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionUniqCombined1… 3.11 MiB 3.14 MiB +24.20 KiB (+0.76%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionUniqCombined1… 3.11 MiB 3.14 MiB +24.20 KiB (+0.76%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionUniqCombined1… 3.11 MiB 3.14 MiB +24.20 KiB (+0.76%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionAvgWeighted.c… 13.64 MiB 13.66 MiB +21.64 KiB (+0.15%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionSumCount.cpp.o 2.01 MiB 2.03 MiB +20.43 KiB (+0.99%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionQuantileExact… 2.98 MiB 3.00 MiB +20.27 KiB (+0.66%)

719 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

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

Job report

@NIKTONIKTO717
NIKTONIKTO717 marked this pull request as ready for review October 6, 2026 08:22
@NIKTONIKTO717 NIKTONIKTO717 added the memory When memory usage is higher than expected label Oct 6, 2026
@clickhouse-gh clickhouse-gh Bot added comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... and removed comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Oct 6, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 6, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 32 queries analysed

No query changes in a way this PR can explain. The one flagged query, clickbench Q16, measured +12.8% (598 ms vs 530 ms), but that is inside master's own recent range of 519-669 ms, so it stays a non-directional not_sure. The suppression is consistent with the diff: the new path that answers sum/avg/sumCount and count(column) from per-part statistics only runs for aggregations with no GROUP BY and no filter, and Q16 has a GROUP BY, so it still goes through normal aggregation. Two of the PR's clickbench runs shared the same machine, which adds run-to-run variance and fits this small shift, and nothing here looks like a real effect of the change.

clickbench

⚠️ 1 inconclusive

Flagged queries (1 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 16 not_sure 530 598 +12.8% <0.0001 aggregation: Q16 is a GROUP BY aggregation, and the new statistics shortcut only fires when there is no GROUP BY and no filter, so this PR's changed path never runs for it. The +12.8% is inside master's normal range of 519-669 ms.

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: 58b01e6b-165e-487a-a357-a7cbeddbd736
  • MIRAI run: b381b00a-09aa-41da-8447-46bc9745ca86
  • PR check IDs:
    • clickbench_5166_1791291153
    • clickbench_5274_1791291194
    • clickbench_5372_1791291215
    • tpch_adapted_1_official_5659_1791291514
    • tpch_adapted_1_official_5720_1791291516
    • tpch_adapted_1_official_5853_1791291545

# Conflicts:
#	tests/queries/0_stateless/05029_columns_cache_comment_keeps_cache.sql
#	tests/queries/0_stateless/05136_columns_cache_part_removal_invalidation.sh
…m-lowlevel-pattern-audit-2026-09-19

# Conflicts:
#	src/Processors/QueryPlan/Optimizations/optimizeUseAggregateProjection.cpp
#	src/Storages/MergeTree/IMergeTreeDataPart.cpp
#	src/Storages/MergeTree/IMergeTreeDataPart.h
#	src/Storages/Statistics/tests/gtest_stats.cpp
#	tests/queries/0_stateless/05029_columns_cache_comment_keeps_cache.sql
#	tests/queries/0_stateless/05136_columns_cache_part_removal_invalidation.sh
… of github.com:ClickHouse/ClickHouse into small-perf-wins-from-lowlevel-pattern-audit-2026-09-19

# Conflicts:
#	tests/queries/0_stateless/05136_columns_cache_part_removal_invalidation.sh
@clickhouse-gh clickhouse-gh Bot added comp-skip-index Skipping indexes (minmax, set, bloom) and their evaluation. and removed comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... labels Oct 22, 2026
@clickhouse-gh clickhouse-gh Bot added comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. and removed comp-skip-index Skipping indexes (minmax, set, bloom) and their evaluation. labels Oct 22, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

Yes, it should be ignored.

…emory check`

`IMergeTreeDataPart` keeps an `Estimates` map with an `Estimate` per column per part. An inline
`std::optional<Field>` grew `Estimate` from 208 to 272 bytes and moved every hash node from the
256-byte to the 320-byte jemalloc size class, even for columns without a sum: +640,000 bytes in
`07_many_parts.sql` (1000 parts x 10 columns). `OptionalFieldPtr` takes 8 bytes inline (the node
is 256 bytes again) and allocates the `Field` only for the columns that have a sum.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=123950&sha=ff22f2472b232cb00b502e76eab576a73fe4a429&name_0=PR&name_1=Storage%20memory%20check
#123950

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. and removed comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... labels Nov 9, 2026
Comment thread src/Storages/Statistics/Statistics.h Resolved
…torage memory check`"

This reverts commit 9e032bc per review: accept the `Storage memory check` difference instead.

#123950 (comment)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... and removed comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Nov 9, 2026
The previous run skipped the full CI suite because of an unresolved review thread.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
ch-samuel-reviewer-1 added a commit to ch-samuel-reviewer-1/ClickHouse that referenced this pull request Nov 9, 2026
`Storage memory check` fails a pull request whose memory increase is
intended, which blocks `Mergeable Check`: ClickHouse#123950 keeps a new statistic per
part, so `07_many_parts.sql` grows by 640,056 bytes (5.5%).

With the `ci-storage-memory-increase-ok` label, a scenario over the
threshold is reported OK and the job passes; without it, the failing
scenario says how to allow it. As for `ci-relocation-headroom-ok`, a success
that only the label allowed is not cached, and a private sync pull request
reads the label from `upstream_pr_labels`. The HTML report still shows the
increase.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Nov 9, 2026
Merged via the queue into master with commit 95d1955 Nov 10, 2026
185 of 187 checks passed
@alexey-milovidov
alexey-milovidov deleted the small-perf-wins-from-lowlevel-pattern-audit-2026-09-19 branch November 10, 2026 02:13
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 10, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 10, 2026
Since ClickHouse#123950 (merged with master in 21e71b8), `SELECT sum(id)` over the
web disk table is answered from the per-part `basic` statistics. The statistics
are loaded by the first query and kept in memory, so the query after
`http_forbid_headers` forbids `Authorization` sent no HTTP request and
`test_userinfo_with_forbidden_authorization` failed with "Client expected to be
failed but succeeded".

A filter disables that optimization, so every query reads `id` from the web
server again. The query needs no new setting, so the test stays the same on
release branches that do not have `use_statistics_for_sum_avg_aggregation`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov added a commit that referenced this pull request Nov 11, 2026
…_small_read_streams_columns_cache`

After merging `master`, `sum(k)` is answered from per-part statistics
(#123950), so `EXPLAIN PIPELINE`
no longer contains `MergeTreeSelect` and the test failed in the Fast test:
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=123890&sha=9ac96b189b524ed4582f6520a99a25a157b973f0&name_0=PR&name_1=Fast%20test

Related: #123890

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov added a commit that referenced this pull request Nov 11, 2026
Since #123950 `SELECT sum(x)` is answered from the `basic` statistics of the part with
`use_statistics_for_sum_avg_aggregation`, so the query did not read the column through the
userspace page cache any more: `05569_ubsan_unsigned_overflow_review_cases_7` returned `4950` instead
of `INVALID_SETTING_VALUE`, and `05508_ubsan_unsigned_overflow_review_cases_6` passed without
exercising the huge `page_cache_lookahead_blocks`. Disable the setting in both, as #123950 did for
the other page cache tests.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=120906&sha=13dbf235e9be8f7884d7b189970551437ff17fb1&name_0=PR&name_1=Stateless%20tests%20(amd_debug%2C%20flaky%20check)
#120906
Related: #123950

Co-Authored-By: Claude Opus 5.5 <[email protected]>
CheSema added a commit that referenced this pull request Nov 11, 2026
Since #123950, `sum(k)` can come from `basic` statistics, so the queries read nothing.
alexey-milovidov pushed a commit to pugachevdmitry/ClickHouse that referenced this pull request Nov 12, 2026
…part files after the upgrade

After the restart, the upgraded server executes a MERGE_PARTS or MUTATE_PART
entry whose result the other replica already committed under the previous
release. checkPartChecksumsAndCommit compares the new part with the ZooKeeper
part header written by the old release. Releases change the byte format of
uncompressed part files: statistics.packed is registered with file_hash only,
so it lands in the "hash of uncompressed files" bucket, and its content changed
in 26.7 (auto_statistics_types default) and in 26.11 (ClickHouse#123950 adds the sum to
basic statistics). The task then logs CHECKSUM_DOESNT_MATCH at error level,
removes the local part and fetches the replica's part. The upgrade guide
(docs/guides/oss/update.mdx) documents this message as expected while replica
versions differ, and the statistics author confirmed it on ClickHouse#130674, but the
post-upgrade log scan treated it as a failure.

Filter the line only when "hash of uncompressed files doesn't match" is the
sole clause. Divergent column data ("uncompressed hash of compressed files"),
both clauses together, a different number of files and the KILL MUTATION
"different columns hash" case still fail the job. The Upgrade check is the only
CI job that reports these lines (the stress tests scan only
"<Error>.*Application"), so a broader filter on "is not byte-identical to data
on another replicas" would remove the only CI detector of divergent column data
after replicated merges and mutations.

Validated by running the extracted scan on the Upgrade check log of ClickHouse#130547
(1 line -> 0) and on 7 control lines (7 -> 5, every other shape kept), with
GNU grep 3.11 locally and inside clickhouse/stress-test. Changing "Code: 40" to
"Code: 41" in the new pattern restores both results.

Related: ClickHouse#103395
Related: ClickHouse#130674

Co-Authored-By: Claude Opus 5.5 <[email protected]>
subkanthi pushed a commit to subkanthi/ClickHouse that referenced this pull request Nov 17, 2026
…ections with parallel replicas

The aggregate and normal projection optimizers decided whether a coordinated read is the
initiator's own share (and so must return what a projection or a prepared source answers)
from `QueryPlanOptimizationSettings::is_parallel_replicas_initiator_with_projection_support`,
computed once from the context the whole plan is optimized with. The initiator's local plan
is optimized with a copy of the OUTER settings, so when parallel replicas are enabled only in
a subquery's SETTINGS the flag is false there: the initiator emitted a NullSource for the
`_minmax_count_projection`, `_statistics_projection` and `_exact_count_projection` blocks and
skipped the projection read beside parts without the projection, while the followers do the
same by design. `min`/`max`/`count` came back as 0 (since ClickHouse#82807), `sum`/`avg` as 0/nan (since
ClickHouse#123950), and projection-answered rows were dropped.

Use `ReadFromMergeTree::isParallelReplicasLocalPlanForInitiator()`, which reads the read's own
context and is already used by the same code for the empty-ranges announcement (and its
follower twin for the follower failpoints), and remove the plan-wide field. For a query whose
outer and subquery contexts agree the answer is unchanged.

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-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... memory When memory usage is higher than expected 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.

3 participants