Skip to content

Compare integer keys inline in sumMap, minMap and maxMap - #124340

Merged
alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:summap-inline-integer-key-compare
Oct 7, 2026
Merged

alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:summap-inline-integer-key-compare

Conversation

@groeneai

@groeneai groeneai commented Oct 7, 2026 •

Copy link
Copy Markdown
Collaborator

Performance Comparison (arm_release, master_head, 1/6) on #109369 reported sum_map query 2 (sumMap(key, val) over arrays) as slower: https://s3.amazonaws.com/clickhouse-test-reports/PRs/109369/057d1a84efd5862b92d7cf35211c466cd4a3aa99/pr/performance_comparison_arm_release_master_head_1_6/report.html. That PR does not touch this code. In the job's profile, 55% of the samples are in Field::operator<, called for every array element by the ordered Field map in AggregateFunctionMapBase::add. The call is out-of-line, so its cost moves with code placement, and this test reports "slower" on many unrelated PRs.

This change gives the map, and the key set of sumMapFiltered, a comparator that compares UInt64 and Int64 fields inline and calls Field::operator< otherwise. It returns the same value as Field::operator< for every pair, so the order, the results and the serialized state do not change. The comparator is chosen once from the key type: native integer, Enum, Date, Date32 and DateTime keys use it, and every other key type keeps std::less<Field>, which runs the same code as before.

Release build, x86, max_threads = 1, median of 15 runs, time relative to master:

query ratio
sum_map.xml queries 0..7 0.43x..0.53x (geometric mean 0.47x)
Int64 keys 0.47x
Date keys 0.52x
sumMapFiltered 0.70x
String keys 0.99x, same instruction count
Float64 keys 1.03x, same instruction count

.text grows by 335,872 bytes (+0.07%). #107554 is the larger typed-aggregation rewrite of these functions, and this change does not replace it.

Related: #109369
Related: #107554

Changelog category (leave one):

  • Performance Improvement

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

sumMap, minMap, maxMap, sumMapWithOverflow and sumMapFiltered over arrays are up to 2.3 times faster for integer, Enum, Date, Date32 and DateTime keys.


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

Version info

  • Merged into: 26.10.1.1719-master (included in 26.10 and later)

groeneai and others added 2 commits October 6, 2026 22:51
The ordered map behind sumMap, sumMapWithOverflow, sumMapFiltered, minMap
and maxMap is keyed by Field, so every array element costs a few calls to
the out-of-line Field::operator< (41.8% of query 2 samples in
tests/performance/sum_map.xml on x86, 55% on the arm CI profile).

Use a comparator that compares UInt64 and Int64 keys inline and delegates
every other pair to Field::operator<. It returns the same value as
Field::operator< for every pair, so the iteration order, the results and
the serialized state are unchanged.

Measured (release, x86, max_threads=1, median of 15, 4 interleaved
rounds): sum_map.xml queries 0..7 at 0.42x..0.53x of master time, Int64
keys 0.47x, sumMapFiltered 0.71x; String keys 1.06x (+4.4% instructions).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The per-comparison type check of the previous commit cost every other key
type a few instructions per tree step (String keys: +4.4% instructions).
Choose the comparator once, from the key type, when the function is
created: native integer, Enum, Date, Date32 and DateTime keys use
FieldLess, every other key type keeps std::less<Field>, so it runs the
same code as before.

Measured against master (release, x86, max_threads=1, median of 15, 4
interleaved rounds): sum_map.xml queries 0..7 at 0.43x..0.53x (gmean
0.47), Int64 keys 0.47x, Date keys 0.52x, sumMapFiltered 0.70x. String and
Float64 keys: 0.99x and 1.03x wall, the same instruction count (1.000x).
.text grows by 335,872 bytes (+0.07%).

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=109369&sha=057d1a84efd5862b92d7cf35211c466cd4a3aa99&name_0=PR&name_1=Performance%20Comparison%20%28arm_release%2C%20master_head%2C%201%2F6%29
PR: ClickHouse#109369

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Oct 7, 2026
@groeneai

groeneai commented Oct 7, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 0 findings) plus my own cold review (1 nit).

# Sev Finding Verdict Evidence / action
1 💡 tests/performance/sum_map.xml has only UInt8 keys, so CI does not time the non-integer key path or sumMapFiltered DISAGREE Non-integer keys keep std::less<Field>, the default comparator of MapWithMemoryTracking, i.e. the code that runs today; locally String and Float64 keys run the same instruction count as master (1.000x). A String key query would mostly time the out-of-line Field::operator<, the placement-sensitive shape this change removes. No change.

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

Session id: cron:clickhouse-review-slot-8:20261007-000100

@groeneai

groeneai commented Oct 7, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, per binary. Local A/B (release, x86, max_threads = 1, median of 15, 4 interleaved rounds): query 2 takes 0.132 s on master and 0.070 s with the change; perf stat gives 2.137 G vs 1.092 G instructions per query, with 0.001% spread between repetitions.
b Root cause explained? AggregateFunctionMapBase::add inserts every array element into a std::map<Field, Array>, so each tree step calls Field::operator<, which is out-of-line in Field.cpp. For integer keys that is a cross-TU call around a single integer comparison, and its cost depends on code placement, so sum_map reports "slower" on unrelated PRs.
c Fix matches root cause? Yes. The comparator of the map compares UInt64 and Int64 fields inline, which removes the call for integer-like keys. Field::operator< is gone from the query 2 profile (41.8% of samples on master). The test and its thresholds are unchanged.
d Test intent preserved / new tests added? No test changed. Inverting the UInt64 branch of the comparator turns 15 existing stateless tests red (e.g. 00502_sum_map), inverting the Int64 branch turns 7 red (e.g. 02480_max_map_null_totals), so the existing tests cover both branches. tests/performance/sum_map.xml measures all 8 integer-key queries.
e Both directions demonstrated? Yes: master vs change on the same box, 13 queries, plus identical results and identical -State bytes on 26 expressions and a MergeTree state round-trip.
f Fix is general across code paths? All 6 registered functions (sumMap, sumMapWithOverflow, sumMapFiltered, sumMapFilteredWithOverflow, minMap, maxMap), both argument forms, and the key set of sumMapFiltered.
g Fix generalizes across inputs (params/datatypes/wrappers)? Native integers (incl. Bool), Enum8/16, Date, Date32 and DateTime keys use the inline comparison. Nullable, LowCardinality, String, Float, Decimal, DateTime64, UUID and other keys keep std::less<Field> (String and Float64 keys: same instruction count as master). Mixed UInt64/Int64 filter keys fall through to Field::operator<. Results and state verified identical for each of these key types, incl. NaN, NULL and negative Enum values.
h Backward compatible? (maintainer-approved exception only) Yes. The order is the same as Field::operator<, so the serialized state is byte-identical; no setting, no state version change.
i Invariants and contracts preserved? The comparator equals Field::operator< on every pair, so key uniqueness and sorted iteration are unchanged. The comparator type depends only on the key type of the aggregate function, so every state merged into a place uses the same map type.

Session id: cron:clickhouse-impl-slot-5:20261006-232500

@clickhouse-gh

clickhouse-gh Bot commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [d59da2e]

Summary: ✅


AI Review

Summary

This PR specializes the ordered Field comparator used by the array-based *Map aggregates for integer-like key types, so AggregateFunctionMapBase::add no longer pays an out-of-line Field::operator< call on every tree step for the common integer/Enum/Date/DateTime cases. I did not find an unresolved correctness, compatibility, or state-serialization issue in the current code: the fast path only short-circuits same-type UInt64/Int64 comparisons and otherwise falls back to the existing Field ordering, and the same comparator selection is applied consistently to the filtered variants' whitelist set as well.

Final Verdict
  • Status: ✅ Approve
  • The current implementation matches the stated contract and the PR includes enough before/after evidence for the claimed performance improvement on this shared hot path.

LLVM Coverage Report

Measured on commit d59da2e.

Metric Baseline Current Δ
Lines 88.20% 88.20% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 79.70% 79.70% +0.00%

Changed lines: Changed C/C++ lines covered: 57/65 (87.69%) · Uncovered code

Full report · Diff report

@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 7, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 7, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing d59da2e22 with master 33d5cfbbc (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

⚠️ Significant changes: object file sizes.

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 ⚠️

4 object files changed (+1.38 MiB total), 0 added.

Object file Master PR Δ
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionSumMap.cpp.o 1.57 MiB 2.95 MiB +1.38 MiB (+87.88%)

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

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

Job report

@clickhouse-gh

clickhouse-gh Bot commented Oct 7, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

This PR only changes the sumMap, minMap and maxMap family of aggregate functions (and their MappedArrays, WithOverflow and Filtered variants). For integer-like keys they now use a dedicated comparator instead of the generic one. No ClickBench or TPC-H query in this run calls these functions. The two flagged rows, ClickBench Q16 (+10.0%) and Q18 (+13.3%), are plain GROUP BY/count() aggregations whose PR medians fall inside master's current range, so marking them not_sure is correct, and there is no code-path reason to contest that. This run shows no performance impact from the PR; a benchmark that calls sumMap with integer keys would be needed to measure the intended speedup.

clickbench

⚠️ 2 inconclusive

Flagged queries (2 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 16 not_sure 529 582 +10.0% <0.0001 aggregation: This is a GROUP BY over UserID and SearchPhrase with count() and never calls the sumMap/minMap/maxMap functions this PR changes. The 582 ms median falls inside master's current range of 519-648.5 ms.
⚠️ 18 not_sure 864 979 +13.3% 0.0019 aggregation: This is a GROUP BY over UserID, a minute value and SearchPhrase with count(), and none of the changed map aggregate functions run. The 979 ms median falls inside master's current range of 842-1125 ms, and both runs were noisy.

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: d3e157f3-cbf3-4c78-b1da-ef6eb20aca5f
  • MIRAI run: 4a307902-ee52-4119-b8ea-2aab5923dc0f
  • PR check IDs:
    • clickbench_105467_1791338685
    • clickbench_105473_1791338685
    • clickbench_105479_1791338685
    • tpch_adapted_1_official_105490_1791338685
    • tpch_adapted_1_official_105501_1791338685
    • tpch_adapted_1_official_105539_1791338685

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

LGTM. However, I didn't understand why the new comparator is faster than the generic one. Can the generic one be improved the similar way?

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 7, 2026
@alexey-milovidov alexey-milovidov self-assigned this Oct 7, 2026
@groeneai

groeneai commented Oct 7, 2026

Copy link
Copy Markdown
Collaborator Author

The generic comparator is slow here because of the call, not the comparison. merged_maps is a std::map<Field, Array> and add does one emplace per array element (5M per query in sum_map.xml, 23 distinct keys), so every tree step calls Field::operator<. That function is out of line in Field.cpp (since c206f31), so each step is a call that compares which twice and then switches on the type, all around one integer compare. FieldLess is in the same translation unit, so it is inlined into the tree walk: a couple of type checks and the integer compare. On query 2 (local release build, x86): 2.14G -> 1.09G instructions per query. Field::operator< was 42% of the samples on master; with FieldLess it is gone, and the self time of add, which now includes the comparison, barely changed (3757 -> 3840 samples). So almost all of that cost was the call and the dispatch.

The generic one can get the same fast path: an inline same-type UInt64/Int64 check in Field.h, with the rest of the switch staying out of line (no new includes). The price is that every non-integer comparison pays the extra checks. The first commit of this PR was exactly that shape (one comparator with the fast path for all key types), and String keys got +4.4% instructions (1.06x wall). That is why the final version picks the comparator by key type when the function is created, so non-integer keys keep std::less<Field> (instructions unchanged). Also, the only other Field-keyed ordered container in src/ is in LogicalExpressionOptimizerPass (query analysis, not per row), so a generic change would mostly speed up this same map. I would keep it local, but I can send the Field.h variant as a separate PR with the same A/B if you prefer.

Merged via the queue into ClickHouse:master with commit 1df1840 Oct 7, 2026
149 checks passed
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 7, 2026
huldarchen pushed a commit to huldarchen/ClickHouse that referenced this pull request Oct 10, 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.). groeneai-origin-request PR origin: a maintainer pinged or directed groeneai 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