Skip to content

Do not allocate a whole-block flag buffer per group in -If aggregation over a Nullable argument - #122505

Merged
Algunenano merged 3 commits into
ClickHouse:masterfrom
groeneai:if-null-adapters-without-block-flag-buffers
Sep 29, 2026
Merged

Algunenano merged 3 commits into
ClickHouse:masterfrom
groeneai:if-null-adapters-without-block-flag-buffers

Conversation

@groeneai

@groeneai groeneai commented Sep 27, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #118490
Related: #118025

Changelog category (leave one):

  • Performance Improvement

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

-If aggregate functions with one Nullable argument, such as minIf(x, cond) or sumIf(y, cond) with a Nullable condition, no longer allocate a buffer the size of the whole block for every group with optimize_aggregation_in_order or for every window frame. With small groups or frames this makes them 1.7 to 3.1 times faster on x86_64.

Description

Queries #2 to #5 of aggregation_in_order_if_null_map.xml are noisy on amd runners only: over 10 days the two servers' times differ by over 15% in 62%, 60%, 49% and 22% of amd runs, never on arm. Example on master: Performance Comparison (amd_release, master_head, 2/6), where its two servers ran #2 in 96 and 64 ms. Found while investigating this job on #118490.

The -If null adapters merged the null map and the condition into a buffer sized by the call's absolute end row. Aggregation in order calls them once per group and window functions once per frame, so every 8-row group asked for up to 64 KiB. On x86_64 a request above 32 KiB bypasses the jemalloc thread cache and takes the arena large-extent path; with aarch64's 64 KiB pages these sizes are cached small classes.

With a single Nullable argument the adapters now pass the null map and the condition to the nested function separately. -If now applies such a condition passed down by -OrNull or -OrDefault (sumIfOrNullIf(x, c1, c2), Nullable x) instead of replacing it with its own; for a non-Nullable x it still does, as on master. The nested functions' own merges (min/max/argMin/argMax, groupBit*, varSamp and other moments, regr_*, timeSeriesLastTwoSamples) are sized to the rows, as sum and avg already are. Two or more Nullable arguments (#5), a Nullable condition of a one-argument -If, and the TimeSeries array merges are unchanged. Results are identical.

Release build, before / after: perf.py medians #2 37.1 / 22.0 ms, #3 39.9 / 20.0, #4 46.1 / 25.6; #0, #1 and #5 unchanged. 101-row window frames on 1M rows: minIf 342 / 185 ms, sumIf(y, cn) 313 / 103 ms.

🤖 Generated with Claude Code


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

Version info

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

groeneai and others added 2 commits September 27, 2026 01:50
…ion over a `Nullable` argument

The `-If` null adapters merged the null map with the condition into a buffer
sized by the absolute end row of the call and filled only `[row_begin, row_end)`.
Aggregation in order calls `addBatchSinglePlace` once per key interval, and
window frames once per frame update, so with 8-row groups every call asked for
up to 64 KiB to use 8 bytes. The merges the nested functions do for themselves
(`SingleValueData`, `groupBit*`, the simple moments, `regr_*`,
`timeSeriesLastTwoSamples`) were sized the same way.

On x86_64 every such request above 32 KiB exceeds jemalloc's thread cache
limit (`opt_tcache_max`) and takes the arena large-extent path, whose cost
depends on the state of the process. On aarch64 (64 KiB pages) these sizes are
small size classes served from the thread cache. That is why queries ClickHouse#2 to ClickHouse#5
of `tests/performance/aggregation_in_order_if_null_map.xml` are unstable on
the amd runners only: in the last 14 days CIDB has 2008 of the test's 2174 amd
`unstable` verdicts on ClickHouse#2 to ClickHouse#5, and 8 on arm in total.

With a single `Nullable` argument no merged map is needed:
`addBatchSinglePlaceNotNull` takes the null map and the condition column
separately, and every implementation handles `if_argument_pos`
(`AggregateFunctionIf` already calls them all that way). So
`AggregateFunctionIfNullUnary` with a non-`Nullable` condition passes the
value's null map and the condition at position 1, and
`AggregateFunctionIfNullVariadic` with exactly one `Nullable` argument passes
that argument's null map to the nested `-If` function, which applies the
condition. The merges those calls reach allocate `row_end - row_begin` bytes
and call their kernels with pointers rebased by `row_begin`, as `sum` and
`avg` already do. The same rows are added in the same order, so the results
do not change. Two or more `Nullable` arguments (query ClickHouse#5, `corr(x, w)`), a
`Nullable` condition of a one-argument `-If` function and the TimeSeries
array merges keep their merged buffer.

Measured on a release build (x86_64, `max_threads` 8), base / this change,
per run of each query of the test:
- jemalloc large allocations above 32 KiB: #0 703 / 703, ClickHouse#1 714 / 714,
  ClickHouse#2 302182 / 703, ClickHouse#3 302142 / 663, ClickHouse#4 229046 / 1718, ClickHouse#5 115413 / 115413;
- CPU profiler samples in the jemalloc large-extent path: ClickHouse#2 33% / 0.9%,
  ClickHouse#3 31% / 0.5%;
- perf.py median of 13 runs, two alternating rounds (ms): ClickHouse#2 38.2, 39.8 /
  24.6, 21.7; ClickHouse#3 39.0, 40.2 / 21.3, 19.8; ClickHouse#4 44.3, 45.4 / 28.3, 25.9;
  #0, ClickHouse#1 and ClickHouse#5 unchanged;
- `minIf(x, cond) OVER (ORDER BY k ROWS BETWEEN 100 PRECEDING AND CURRENT
  ROW)` over 1M rows: 340 / 166 ms, and `sumIf(y, cn)` over a `Nullable`
  condition: 301 / 89 ms;
- aggregation without keys over the same table: 12.2 / 12.3 ms.

Query #0, flagged on ClickHouse#118490,
never had such a buffer and is not changed here.
CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118490&sha=8ded98e22889e53dd536b141b564e136c76482a9&name_0=PR&name_1=Performance%20Comparison%20(amd_release%2C%20master_head%2C%203%2F6)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…tion over `Nullable` arguments

With one `Nullable` argument the `-If` null adapters now pass the null map
and the condition column separately (previous commit) and rely on the nested
function honouring `if_argument_pos`. `AggregateFunctionIf` did not: its
`addBatchSinglePlaceNotNull` (`AggregateFunctionIf.h`) took the position as
an unnamed parameter and passed its own condition, `num_arguments - 1`,
instead. `-OrNull` and `-OrDefault` forward the position into their nested
function, and the factory accepts `-If` under `-OrNull`/`-OrDefault` under
`-If`, so in `sumIfOrNullIf(x, c1, c2)` with a `Nullable` `x`, and in
`countIfOrNullIf(c, c2)` with a `Nullable(UInt8)` `c`, the inner `-If`
dropped `c2` without keys, with aggregation in order and in window frames.
Before the previous commit the adapters folded `!c2` into the merged null
map, so the replaced position did no harm there.

When a position is passed in, `AggregateFunctionIf::addBatchSinglePlaceNotNull`
now adds the rows that are not NULL and pass that condition one by one
through its own `add`, which checks its own condition. Without one it calls
the nested function as before.

`clickhouse local`, a `Memory` table (x Nullable(Float64), c Nullable(UInt8),
c1 UInt8, c2 UInt8) with the rows (1, 1, 1, 1), (10, 1, 1, 0) and
(100, 0, 0, 1): `SELECT sumIfOrNullIf(x, c1, c2)` and
`SELECT countIfOrNullIf(c, c2)` print 1 and 1 on master, 11 and 2 with the
previous commit, and 1 and 1 now. The test now covers both chains with an
outer condition that is independent of the inner one, and fails without
this change.

The adapters check for a row to add with the existing
`countBytesInFilterWithNull` instead of a new scalar loop.

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 Sep 27, 2026
@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 in round 1, none on the fix round) plus my own cold review (5 findings in round 1, 1 on the fix round).

# Sev Finding Verdict Evidence / action
1 ❌ -If under -OrNull/-OrDefault under -If with one Nullable argument (sumIfOrNullIf(x, c1, c2)) lost the outer condition: -If's addBatchSinglePlaceNotNull replaced the position passed down by -OrNull with its own (AggregateFunctionIf.h, AggregateFunctionOrFill.h) AGREE, fixed @ 57ce4fa -If applies an incoming condition row by row; without keys: master 1 and 1, first version 11 and 2, now 1 and 1
2 ⚠️ No test covered the chain of row 1 AGREE, fixed @ 57ce4fa both chains, with an outer condition independent of the inner one, in the in-order vs hash comparison and against a plain filter; the test fails without the fix
3 ⚠️ The description claimed every addBatchSinglePlaceNotNull already handled the separate condition AGREE, fixed @ 57ce4fa the description states the -If change, and that with a non-Nullable argument -If behaves as on master
4 ⚠️ The new stateless test does not detect a revert of the allocation change DISAGREE the performance test aggregation_in_order_if_null_map.xml (#2 to #4) is the oracle for speed; the stateless test guards results and fails when either new mechanism is broken (in-order vs hash EXCEPT 1250, ASan heap-buffer-overflow); SQL has no per-query allocation counter
5 💡 New scalar early-exit loop instead of the existing SIMD countBytesInFilterWithNull AGREE, fixed @ 57ce4fa helper removed; a never-true condition without keys stays at the master level (7.0 vs 7.2 ms)
6 💡 Test header wording (the window arm compares block sizes) AGREE, fixed @ 57ce4fa comment corrected

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding. Findings on hunks unchanged by the fix round are auto-dropped.

Session id: cron:clickhouse-review-slot-8:20260927-040700

@groeneai groeneai added the groeneai-origin-request PR origin: a maintainer pinged or directed groeneai label Sep 27, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [111f0e8]

Summary: ❌

job_name test_name status info comment
AST fuzzer (amd_release, oracle) ERROR IGNORED

AI Review

Summary

This PR changes the -If null-adapter batch paths so a single Nullable argument can reuse the original null map instead of materializing a whole-block merged flag buffer, fixes the forwarded-condition bug for nested combinators such as sumIfOrNullIf, and adds focused stateless coverage for the affected in-order, no-key, and windowed paths. I did not find any remaining correctness, safety, or evidence gaps in the current revision.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Measured on commit 111f0e8.

Metric Baseline Current Δ
Lines 87.90% 87.90% +0.00%
Functions 91.70% 91.70% +0.00%
Branches 79.30% 79.30% +0.00%

Changed lines: Changed C/C++ lines covered: 89/92 (96.74%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Sep 27, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-aggregate-functions Aggregate function implementations (sum, avg, count, quantile, combinators, etc.). label Sep 27, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

no significant changes detected. K_source=6 K_base=30 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: ff16c8e1-8acd-435b-8c0d-288493679a4e
  • MIRAI run: c9e6bfa1-b2ad-4c7f-ac82-1e74bbd1c4b1
  • PR check IDs:
    • clickbench_2283840_1790631896
    • clickbench_2283846_1790631896
    • clickbench_2283857_1790631896
    • tpch_adapted_1_official_2283863_1790631895
    • tpch_adapted_1_official_2283896_1790631896
    • tpch_adapted_1_official_2283911_1790631896

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 57ce4fa

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Performance Comparison (amd_release, master_head, 5/6) / json_key_formatting #2 dashboard confirmed_regression, client_time 0.908 -> 1.045 s (+15.0%), while the shard's own report does not flag the query (2 too long only). The dashboard had no recent master history for it, so it was judged against its 2% default floor. The query is count() over formatRow('JSONEachRow', ...) on a Memory table, with no -If combinator and no Nullable argument, so it never reaches the adapters and merges this diff changes. On arm the same query was +6% and green ClickHouse/performance-comparison#5 (external): the dashboard's confidence scoring, where @ fm4v handles these verdicts after #121847, which is already in this branch and did not prevent this verdict. That repository is not publicly readable, so its state cannot be measured from here
Performance Comparison (arm_release, master_head, 6/6) / cryptographic_hashes #18 same class: dashboard confirmed_regression, client_time 0.109 -> 0.177 s (+62.0%), while the shard's own report does not flag the query (5 too long only). It is SELECT ignore(halfMD5(materialize(''))) FROM numbers_mt(10000000), with no aggregate function at all. The dashboard flagged it on 64 pull request runs and 5 master runs in the last 14 days, in both directions, and on amd it got faster in this same run (0.300 -> 0.152 s) ClickHouse/performance-comparison#5 (external), the same owner as the row above
Mergeable Check, PR rollups, red only because of the two shards above (Mergeable Check reports Failed: 2) ClickHouse/performance-comparison#5 (external), the owner of both rows above

All 169 check runs completed (153 pass, 14 not selected, 2 red), Finish Workflow is green and
CH Inc sync passed. CIDB has no FAIL or ERROR test row on this head.

Session id: cron:our-pr-ci-monitor:20260927-130124

@Algunenano Algunenano self-assigned this Sep 27, 2026
FROM numbers(10000);

SET optimize_aggregation_in_order = 1;
SELECT count() > 0 FROM (EXPLAIN PIPELINE SELECT k, argMaxIf(y, x, cond) FROM t_agg_if_one_null_map GROUP BY k) WHERE explain ILIKE '%AggregatingInOrderTransform%';

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.

I don't understand the need of this test. Please remove this part and only include a query or queries that exercise this part of the code. No need for extra checks based on EXPLAIN and no need for TEMPORARY TABLES

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Thanks, done in 111f0e8: I removed the EXPLAIN checks, the temporary tables and the comparison queries. The test now only runs the queries that reach the changed code (aggregation in order, the no-key sumIfOrNullIf / countIfOrDefaultIf chain, window frames) and keeps their results in the reference. It still fails with the AggregateFunctionIf.h change reverted.

The test now runs aggregation in order, the no-key `-If` under `-OrNull` /
`-OrDefault` under `-If` chain, and 101-row window frames, and records their
values in the reference. The EXPLAIN checks, the temporary tables and the
comparisons against hash aggregation and plain filters are removed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai
groeneai requested a review from Algunenano September 28, 2026 17:05

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

The changes to src/AggregateFunctions/Combinators/AggregateFunctionIf.cpp aren't close to obvious.

The key part is that columns are indexed absolutely, same as null_map. We can only use spans when we call some inner function that accept it (like SingleValueData) and for that we need to reach the function with both columns, not combine them eagerly. Combining them eagerly makes sense mostly for vectorization, but for that you need to overload addBatchSinglePlaceNotNull and in that case you can merge the filters as you need (we already did). So in general it makes sense.

The alternative would be to change the API and make null_map an array where 0 is row_begin and ends in row_end, but I think that's even more confusing.

@clickhouse-gh

clickhouse-gh Bot commented Sep 28, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 111f0e877 with master dc88cd130 (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

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 111f0e8

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
AST fuzzer (amd_release, oracle) / NoREC oracle mismatch on hasToken(val, 'bar') trunk bug, not caused by this diff: the oracle compares SELECT count() FROM (SELECT (SELECT count()) FROM tab__fuzz_3 WHERE hasToken(val, 'bar')) (1) with SELECT countIf(hasToken(val, 'bar')) FROM tab__fuzz_3 (0). The table comes from 02346_text_index_preprocessor (rows foo, BAR, Baz, text index with preprocessor = lower(val)), and the preprocessor is applied to the WHERE predicate but not to the same call in the SELECT list, which is #117077. The fuzzed column is LowCardinality(String), so neither query reaches the Nullable -If adapters this diff changes. The same NoREC shape on a text index search function failed this check on at least 5 other PRs in the last 30 days #117774 (external, open)
Mergeable Check, PR rollups, red only because of the row above #117774 (external, open)

146 of 146 check runs completed (131 passed, 14 not selected, 1 red: the fuzzer job above), Finish Workflow is green and CH Inc sync passed. CIDB has no FAIL or ERROR test row on this head.

Session id: cron:our-pr-ci-monitor:20260928-230115

@Algunenano
Algunenano added this pull request to the merge queue Sep 29, 2026
Merged via the queue into ClickHouse:master with commit 5ece1cb Sep 29, 2026
147 of 149 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 29, 2026
subkanthi pushed a commit to subkanthi/ClickHouse that referenced this pull request Nov 23, 2026
…ce test

With groups of 8 rows about 75% of each query is per-group work (the
group-end search of in-order aggregation, the `-If`/`-Null` adapters,
state create and finalize). Its speed depends on how a build lays out
these small hot functions: 73 of 2667 amd builds since 2026-10-26 run
one of the six queries 16-35% slower than the rest of the same build,
with the same instruction count and one more branch miss per group. That
made the test fail on unrelated PRs (ClickHouse#120906: ClickHouse#3 +35%, #0 +27%) with a
different query each time.

Disable the six queries (their history keys stay) and append them on
three new tables: `sumIfOrDefault`, `avgIfOrDefault` and `sumIf` on
groups of 1024 rows, `corr` and `argMinIf` on groups of 128 rows and
`minIf` on groups of 256 rows. `corr` has the smallest per-group penalty
and needs the smaller groups to keep its ClickHouse#118025 guard (~1.10 at 1024
rows). `argMinIf` and `minIf` keep a guard of ClickHouse#122505: reverting its
change to the variadic and unary `-If` null adapters slows them 1.21x and
1.28x, while the other `-If` queries move +0.9% to +13.2%.

Measured locally with perf.py against the CI reference build: the
ClickHouse#120906 build runs the old #0/ClickHouse#3 at 1.31x/1.39x and the new copies at
1.016x/1.020x in the same processes (`sumIf` 1.067x in another run);
7 slow CI builds stay within 6.7% on the new queries (A/A 2.5%), below
the 15% minimum change threshold. Restoring the value-initialised
`row_end`-sized buffer at each ClickHouse#118025 site master still reaches
(`AggregateFunctionSum.h:669`, `AggregateFunctionAvg.h:539`,
`SingleValueData.cpp:39`, `AggregateFunctionNull.h:769`) slows its
queries 1.2x-1.8x, with identical results.

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

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