Skip to content

Do not copy the aggregate function registry entry on every lookup - #128359

Merged
alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:faster-aggregate-function-factory-lookup
Nov 1, 2026
Merged

alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:faster-aggregate-function-factory-lookup

Conversation

@groeneai

@groeneai groeneai commented Oct 31, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #128352

Changelog category (leave one):

  • Performance Improvement

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

Resolving an aggregate function during query analysis no longer copies its registry entry, including its documentation, so queries with many aggregate functions are planned faster: EXPLAIN PLAN of ClickBench Q30 (90 SUM terms) executes 4.4% fewer instructions and about 2% fewer CPU cycles.

Description

AggregateFunctionFactory::getImpl and tryGetProperties copied the registered AggregateFunctionWithProperties (two std::function creators, the whole FunctionDocumentation and the properties) into a local on every lookup, and getAssociatedFunctionByNullsAction returned another copy by value. get calls both, so resolving one aggregate function copied its documentation at least twice. They now point to the entry. The maps are only written by registerFunction, before any lookup, and it rejects a null creator, so found != nullptr is the same test as the old found.creator.

Release build, x86, server pinned to 4 cores, 100M-row hits, master vs this PR, 3 server restarts each:

  • EXPLAIN PLAN of Q30: 4.4% fewer instructions in the query thread (79.55M -> 76.03M, spread under 0.02%) and 1.8% fewer cycles (27.10M -> 26.62M, measured on idle cores).
  • Q30 itself, with or without use_columns_cache = 1, changes by less than the benchmark noise. Memory usage is unchanged.
  • Results, EXPLAIN QUERY TREE and EXPLAIN actions of 22 queries (sum/count/avg rewrite and fusion, Nullable, Decimal, LowCardinality, aliases, RESPECT NULLS/IGNORE NULLS, combinators, window functions, remote) are identical to master on release and debug builds.

#128352 also proposed caching sum/count and plus/minus in RewriteSumFunctionWithSumAndCountPass and reusing equal replacements in FuseFunctionsPass. On top of this change the two caches save 1.1% of the instructions of EXPLAIN PLAN Q30 each, too little to see in time, so they are not included. Reusing the replacements saves another 5.7% of the instructions and 7.9% of the cycles of EXPLAIN PLAN Q30, but it changes different code, so it goes in a separate PR: #128371.

🤖 Generated with Claude Code


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

Version info

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

`AggregateFunctionFactory::getImpl` and `tryGetProperties` copied the
registered `AggregateFunctionWithProperties` (two `std::function` creators,
the whole `FunctionDocumentation` and the properties) into a local on every
lookup, and `getAssociatedFunctionByNullsAction` returned another copy by
value. `get` calls both, so every resolved aggregate function copied its
documentation strings at least twice.

Point to the entry instead. The maps are written only by `registerFunction`,
before any lookup, and it rejects a null creator, so `found != nullptr` is
the same test as the old `found.creator`.

Measured on a release build (x86, server pinned to 4 cores, 100M-row
ClickBench `hits`): `EXPLAIN PLAN` of ClickBench Q30 (90 `SUM` terms) uses
4.4% fewer instructions in the query thread and runs ~7% faster
(7.48 -> 6.96 ms); `EXPLAIN PLAN SELECT SUM(AdvEngineID), COUNT(*),
AVG(ResolutionWidth) FROM hits` runs ~14% faster (1.32 -> 1.13 ms).

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: my own cold review (4 findings) and an independent model (engine: codex; 0 findings).

# Sev Finding Verdict Evidence / action
1 ⚠️ The 3-function control EXPLAIN PLAN SELECT SUM(AdvEngineID), COUNT(*), AVG(ResolutionWidth) FROM hits gains more (-14%) than a per-lookup saving predicts, so it may be noise DISAGREE Measured, not noise: server CPU time 1.08 -> 0.90 ms in 3 of 3 runs. Its lookup count was not measured, so the PR body cites only the instruction-backed EXPLAIN PLAN Q30 numbers
2 💡 TableFunctionFactory::tryGetProperties/tryGetDocumentation copy their entry the same way DISAGREE (out of scope: separate PR) Different factory; it runs once per table function per query, not per aggregate term
3 💡 The perf CI runs Q30 on hits_100m_single, where reading dominates Noted The PR body says Q30 itself changes by less than the noise
4 💡 Open #125726 adds a caller in the old auto opt = ...; found = *opt; shape Noted It still compiles with the pointer return and its hunks do not overlap this diff

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

@groeneai

groeneai commented Oct 31, 2026 •

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, as a measurement: perf stat --per-thread -e instructions:u on the server during clickhouse benchmark -c 1 -i 1000 --query 'EXPLAIN PLAN <ClickBench Q30>'. The query thread executes 79.55M instructions per query on master and 76.03M with this PR, with a spread of at most 0.02% over 3 fresh server processes each.
b Root cause explained? getImpl and tryGetProperties assigned the registry entry (two std::functions, FunctionDocumentation, properties) to a local Value, and getAssociatedFunctionByNullsAction returned it by value, so every get copied the documentation at least twice.
c Fix matches root cause? Yes: the three sites point to the registered entry instead of copying it. No cache or new state.
d Test intent preserved / new tests added? No behaviour change, so no new test. 184 related stateless tests pass (the other 28 of the 212 fail identically on master in my environment: stateful tables, port-9000 clusters). 02476_fuse_sum_count and 02922_respect_nulls_extensive pass 50/50 with random settings. The ClickBench perf test already has Q30.
e Both directions demonstrated? Master vs this PR: 79.55M vs 76.03M instructions, 27.10M vs 26.62M cycles (idle cores) for EXPLAIN PLAN Q30. A 22-query differential corpus (results, EXPLAIN QUERY TREE, EXPLAIN actions) is identical to master, and a mutation that makes getAssociatedFunctionByNullsAction return nullptr changes its output (RESPECT NULLS queries), so the corpus does cover that path.
f Fix is general across code paths? All three copy sites are changed. getDocumentation still returns a copy, which system.functions needs. FunctionFactory already does not copy; TableFunctionFactory::tryGetProperties/tryGetDocumentation still do, but they run once per table function, not per aggregate term.
g Fix generalizes across inputs (params/datatypes/wrappers)? Every lookup goes through the same code: exact, case-insensitive and alias names, RESPECT NULLS/IGNORE NULLS, combinators (they recurse through get), window variants. The corpus covers each of them plus the UNKNOWN_AGGREGATE_FUNCTION and NOT_IMPLEMENTED errors.
h Backward compatible? (maintainer-approved exception only) Yes. Only a private method's return type changes; no setting, format or protocol change.
i Invariants and contracts preserved? The maps are written only by registerFunction, before any lookup, so the pointers stay valid and concurrent reads are as before. registerFunction rejects a null creator, so found != nullptr is equivalent to the old found.creator. Exceptions are thrown at the same places.

Session id: cron:clickhouse-impl-slot-5:20261031-082900

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @azat @KochetovNicolai, could you review this and add the can be tested label so CI runs? AggregateFunctionFactory::getImpl and tryGetProperties copied the whole registry entry (two std::function creators and the FunctionDocumentation) on every lookup; they now point to it, which removes 4.4% of the instructions of EXPLAIN PLAN for ClickBench Q30 (90 SUM terms).

@clickhouse-gh

clickhouse-gh Bot commented Oct 31, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [465e838]

Summary: ✅


AI Review

Summary

The PR avoids copying AggregateFunctionWithProperties during aggregate-function resolution by referencing the registered entries. No actionable findings in head 465e838cdd069a3fa922f4c3634d91fb23cd6a46; the reported before/after measurements support the planning-performance improvement, and existing tests plus the reported differential checks cover the preserved behavior.

Missing context / blind spots
  • ⚠️ No local build or test execution was performed. Full stateless and sanitizer CI jobs were still pending when inspected; their completed reports would close the remaining CI validation gap.
Final Verdict

Status: ✅ Approve — no changes requested.

@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements comp-aggregate-functions Aggregate function implementations (sum, avg, count, quantile, combinators, etc.). 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 465e838cd with master 3c82fa8cc (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

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

Job report

@alexey-milovidov alexey-milovidov left a comment

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.

Ok.

@alexey-milovidov alexey-milovidov self-assigned this Nov 1, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Nov 1, 2026
Merged via the queue into ClickHouse:master with commit ba0d3f0 Nov 1, 2026
529 of 531 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 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-aggregate-functions Aggregate function implementations (sum, avg, count, quantile, combinators, etc.). pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

3 participants