Skip to content

Build each sum/count/avg replacement once in FuseFunctionsPass - #128371

Merged
alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:fuse-functions-reuse-sum-count-replacement
Nov 1, 2026
Merged

alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:fuse-functions-reuse-sum-count-replacement

Conversation

@groeneai

@groeneai groeneai commented Oct 31, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #128352

Changelog category (leave one):

  • Performance Improvement

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

Faster planning of queries with many sum, count or avg over the same column, such as ClickBench Q30: optimize_syntax_fuse_functions now builds the replacement of each function once and copies it to the other equal aggregates. EXPLAIN PLAN of Q30 executes 3.9% fewer instructions and 4.3% fewer CPU cycles.

Description

optimize_arithmetic_operations_in_aggregate_functions turns the 90 SUM(ResolutionWidth + k) of ClickBench Q30 into sum(x) + k * count(x), so FuseFunctionsPass sees 90 sum(x) and 89 count(x) over one column. For each of them, replaceWithSumCount formatted the node's AST for its alias and resolved new tupleElement functions (plus toFloat64 and divide for avg) through FunctionFactory, with the same result every time.

Now the first node of each function name in a group is replaced as before. Every other equal node gets a copy that reuses its resolved functions and alias and shares the same sumCount node, as all replacements of a group already did. Only nodes over a column with no alias and no parentheses are copied: isEqual ignores parentheses, but the formatted alias keeps them, so sum(x) and (sum(x)) get different aliases. The query tree is unchanged, node sharing included.

Release build, x86, clickhouse local pinned to one idle core, perf stat over 200 x EXPLAIN PLAN Q30, 12 rounds, master vs this PR:

  • cycles -4.32% +- 0.75 (34.5M -> 33.1M), instructions -3.90% +- 0.03, lower in 12 of 12 rounds; master vs master: +0.01% +- 1.09;
  • a control query with one SUM, COUNT and AVG is unchanged.

The gain is in planning, about 0.4 ms per Q30. @ snelheidai measured -4.3% instructions and -9.6% cycles on Graviton3, on top of #128359: #128352 (comment)

Results, EXPLAIN QUERY TREE and EXPLAIN actions of 26 queries (aliases, parentheses, IGNORE NULLS, non-column arguments, HAVING/ORDER BY, remote, Q30) are identical to master on release and debug builds. The test gets the Q30 shape, equal avg nodes and a parenthesized one; its reference comes from master.

🤖 Generated with Claude Code


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

Version info

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

`tryFuseSumCountAvg` called `replaceWithSumCount` for every node of a
group. Each call formats the node's AST for its alias and resolves new
`tupleElement` functions (plus `toFloat64` and `divide` for `avg`)
through `FunctionFactory`. When `RewriteSumFunctionWithSumAndCountPass`
turns ClickBench Q30's 90 `sum(x + k)` into `sum(x) + k * count(x)`,
the pass sees 90 `sum(x)` and 89 `count(x)` over one column and repeats
that work 177 times with identical results.

Now the first node of each function name in a group goes through
`replaceWithSumCount`, and every later equal node gets a copy built by
`copySumCountReplacement`. The copy reuses the resolved functions and
the alias, and keeps sharing the one `sumCount` node, as the original
code already did across all replacements of a group.

The fast path is taken only for nodes over a COLUMN argument that have
no alias and are not parenthesized. Other nodes keep the old path:
- an alias is user-visible and per node;
- `isEqual` and the tree hash ignore the parenthesized flag, but
  `formatForErrorMessage` prints it, so `sum(x)` and `(sum(x))` land in
  one group with different aliases;
- non-column arguments can be equal but format differently
  (`x * 2` vs `multiply(x, 2)`).

The resulting query tree is identical to the one built before, including
node sharing, so `EXPLAIN QUERY TREE` output does not change. The test
gets a query with `sum`/`count` twins from the arithmetic rewrite, `avg`
twins and a parenthesized `avg` twin; its reference was generated with
the binary before this change.

Related: ClickHouse#128352

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 review (2 nits).

# Sev Finding Verdict Evidence / action
1 ⚠️ The test cannot tell whether replacements are built once or N times DISAGREE The query tree is identical by design and no existing counter counts function builds. The test reaches the new path: dropping only copySumCountReplacement's setAlias fails the existing count(b) * count(b) EXPLAIN. Cost measured: Q30 instructions 111.45M -> 107.10M.
2 💡 The repository guidelines prefer a new test over extending an existing one Noted The extension only adds lines and reuses this pass's existing fixture and EXPLAIN QUERY TREE reference.
3 💡 tryFuseQuantiles also formats each node Out of scope Separate code path, not measured.

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

Session id: cron:clickhouse-review-slot-9:20261031-122100

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? The repeated work is an instruction count: 111.45M -> 107.10M per EXPLAIN PLAN Q30, spread under 0.03% over 12 rounds.
b Root cause explained? For every alias-less, unparenthesized sum/count/avg over one column, replaceWithSumCount re-formatted the AST for the alias and re-resolved tupleElement (plus toFloat64/divide), always with the same result.
c Fix matches root cause? The first node of each function name is replaced as before; the others get a copy that reuses its resolved functions and alias and shares sumCount. The resulting query tree is the one master builds.
d Test intent preserved / new tests added? 02476_fuse_sum_count extended (additions only) with the Q30 shape, equal avg nodes and a parenthesized avg; reference generated on master. Dropping the alias copy, the parentheses check or the sumCount sharing each turns it red.
e Both directions demonstrated? Master vs this PR: cycles -4.32% +- 0.75, instructions -3.90% +- 0.03 (A/A +0.01% +- 1.09); results and EXPLAIN output of 26 queries identical on release and debug builds.
f Fix is general across code paths? Aliased, parenthesized and non-column nodes keep the old path. tryFuseQuantiles is a separate path and is not changed.
g Fix generalizes across inputs (params/datatypes/wrappers)? Nullable and LowCardinality(Nullable) arguments are skipped before the loop, as before; Int, UInt, Float, Decimal and LowCardinality columns, SUM/sum, IGNORE NULLS, HAVING/ORDER BY, joins and remote are covered.
h Backward compatible? (maintainer-approved exception only) Yes: no setting, format or stored state; query trees and results are unchanged.
i Invariants and contracts preserved? A copy is indistinguishable from what replaceWithSumCount builds for that node: same functions, same alias, the same shared sumCount, distinct objects elsewhere. Its type checks still run once per function name.

Session id: cron:clickhouse-impl-slot-6:20261031-113800

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @vdimir @yakov-olkhovskiy, could you review this and add the can be tested label so CI runs? In FuseFunctionsPass, equal alias-less sum/count/avg nodes over one column now get a copy of the first node's replacement instead of re-formatting the AST and re-resolving tupleElement for each node; the query tree is unchanged, and EXPLAIN PLAN of ClickBench Q30 runs about 4% fewer cycles.

@clickhouse-gh

clickhouse-gh Bot commented Oct 31, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [dc753dc]

Summary: ✅


AI Review

Summary

FuseFunctionsPass reuses resolved replacements for repeated sum, count, and avg over the same column while preserving aliases and shared sumCount nodes. No actionable findings at dc753dc5a825c379003ff4d252cbe95ab3ed074a. The supplied before/after measurements support the planning improvement, and the changed 02476_fuse_sum_count test passed in fast CI.

Final Verdict

✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). labels Oct 31, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Oct 31, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 31, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing dc753dc5a with master 94d1a63f2 (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.

Compile time of recompiled translation units

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

Job report

@alexey-milovidov alexey-milovidov self-assigned this Oct 31, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 31, 2026
Merged via the queue into ClickHouse:master with commit d2a4a8a Nov 1, 2026
529 of 531 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 1, 2026
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-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). 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