Skip to content

Speed up -ForEach over arrays of Nullable values - #127846

Open
valerypetrov wants to merge 7 commits into
ClickHouse:masterfrom
valerypetrov:claude/null-unary-consecutive-places
Open

valerypetrov wants to merge 7 commits into
ClickHouse:masterfrom
valerypetrov:claude/null-unary-consecutive-places

Conversation

@valerypetrov

@valerypetrov valerypetrov commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

-ForEach hands the elements of an array to its nested function with addBatchConsecutivePlaces (#121137). For Nullable elements the nested function is AggregateFunctionNullUnary, which did not override it, so the default implementation made one virtual call to the nested add per element. This is the outer aggregation of every PromQL sum, avg, min and max, whose grids are Array(Nullable(Float64)). Now AggregateFunctionNullUnary makes one call per array to a new addBatchConsecutivePlacesNotNull of the nested function, the counterpart of addBatchSinglePlaceNotNull, whose loop skips the NULL rows and calls add directly. (A first version that passed runs of non-NULL rows was slower when NULLs are frequent, because every one-row run still cost a virtual call.)

Tests: a new functional test pins sumForEach, avgForEach, minForEach, maxForEach, countForEach, groupArrayForEach and uniqExactForEach with NULLs at the start, at the end, between values and at a position in every row, and compares many rows per key with the same aggregation over the elements. The aggregate_function_for_each performance test gets Array(Nullable(Float64)) queries.

Measured with the same compiler and flags, only this change toggled, best of 4 runs of 5:

Query (1.5M rows of 32 elements, max_threads = 1) NULLs Before, s After, s Change
SELECT sumForEach(a) FROM t none 0.135 0.081 -40%
SELECT maxForEach(a) FROM t none 0.146 0.121 -17%
SELECT k, avgForEach(a) FROM t GROUP BY k none 0.114 0.097 -15%
SELECT sumForEach(a) FROM t 1 in 8 0.132 0.079 -40%
SELECT maxForEach(a) FROM t 1 in 8 0.142 0.139 -2%
SELECT k, avgForEach(a) FROM t GROUP BY k 1 in 8 0.107 0.089 -17%
SELECT sumForEach(a) FROM t 1 in 2 0.144 0.077 -47%
SELECT maxForEach(a) FROM t 1 in 2 0.122 0.110 -10%
SELECT k, avgForEach(a) FROM t GROUP BY k 1 in 2 0.094 0.083 -12%
SELECT sumForEach(a) FROM t 7 in 8 0.096 0.074 -23%
SELECT maxForEach(a) FROM t 7 in 8 0.114 0.086 -25%
SELECT k, avgForEach(a) FROM t GROUP BY k 7 in 8 0.101 0.077 -24%

Related: #121137

🤖 Generated with Claude Code

Changelog category (leave one):

  • Performance Improvement

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

Speed up -ForEach aggregate functions over arrays of Nullable values, such as the outer sum, avg, min and max of PromQL queries.



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

@CLAassistant

CLAassistant commented Oct 26, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@clickhouse-gh clickhouse-gh Bot added the comp-aggregate-functions Aggregate function implementations (sum, avg, count, quantile, combinators, etc.). label Oct 26, 2026
valerypetrov and others added 2 commits October 26, 2026 16:09
…`Nullable`

`-ForEach` hands the elements of an array to its nested function with
`addBatchConsecutivePlaces`. For `Nullable` elements the nested function is
`AggregateFunctionNullUnary`, which did not override it, so the default
implementation made one virtual call to the nested `add` per element. This is
the outer aggregation of every PromQL `sum`, `avg`, `min` and `max`, whose
grids are `Array(Nullable(Float64))`. Pass each run of non-NULL rows to the
nested function in one call instead.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Splitting the rows into runs of non-NULL values made `-ForEach` slower when
NULLs are frequent: with alternating NULLs every run is one row, and each still
costs a virtual call. Add `addBatchConsecutivePlacesNotNull`, the counterpart
of `addBatchSinglePlaceNotNull`, so `AggregateFunctionNullUnary` makes one call
per array and the nested function skips the NULL rows in its own loop.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@valerypetrov
valerypetrov force-pushed the claude/null-unary-consecutive-places branch from dcb1241 to 43c90ef Compare October 26, 2026 16:13
@clickhouse-gh clickhouse-gh Bot added the external Author is not a member of the ClickHouse organization label Oct 27, 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

Workflow [PR], commit [28e0153]

Summary: ✅


AI Review

Summary

This PR speeds up -ForEach aggregation over Nullable array elements by passing each array to a nested batch loop that skips nulls. Reviewed head 28e0153d068d74a8089cf21bb925616e1ddcb70b; no actionable findings. The focused functional test passed in Fast test, and the PR supplies before/after performance measurements.

Missing context / blind spots
  • ⚠️ Sanitizer and performance CI results for this head were not available at review time. Their completed reports would close this validation gap; no local build or test run was performed. CI report.
Final Verdict

Status: ✅ Approve.

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

clickhouse-gh Bot commented Nov 1, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 28e0153d0 with master 7a987ba24 (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
Binary Master PR Δ
programs/clickhouse-stripped 813.37 MiB 812.77 MiB -608.63 KiB (-0.07%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

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

149 object files changed (+4.02 MiB total), 0 added.

Object file Master PR Δ
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionsArgMinArgMax… 16.09 MiB 16.43 MiB +346.55 KiB (+2.10%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionAvgWeighted.c… 13.68 MiB 13.93 MiB +260.36 KiB (+1.86%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionUniq.cpp.o 13.67 MiB 13.88 MiB +205.47 KiB (+1.47%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionRegr.cpp.o 5.95 MiB 6.09 MiB +145.86 KiB (+2.39%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionCorr.cpp.o 7.12 MiB 7.25 MiB +131.07 KiB (+1.80%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionQuantileExact… 7.03 MiB 7.16 MiB +125.34 KiB (+1.74%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionCovar.cpp.o 6.93 MiB 7.06 MiB +124.80 KiB (+1.76%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionSparkbar.cpp.o 5.35 MiB 5.47 MiB +120.66 KiB (+2.20%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionGroupArrayMov… 5.96 MiB 6.07 MiB +113.34 KiB (+1.86%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionGroupArray.cp… 4.55 MiB 4.65 MiB +103.33 KiB (+2.22%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionDeltaSumTimes… 3.53 MiB 3.63 MiB +102.34 KiB (+2.83%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionGroupNumericI… 5.82 MiB 5.89 MiB +76.38 KiB (+1.28%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionQuantile.cpp.o 3.69 MiB 3.77 MiB +75.03 KiB (+1.98%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionGroupUniqArra… 2.58 MiB 2.65 MiB +68.07 KiB (+2.58%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionQuantileDeter… 2.91 MiB 2.97 MiB +65.66 KiB (+2.21%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionSum.cpp.o 3.90 MiB 3.96 MiB +63.55 KiB (+1.59%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionQuantileInter… 3.69 MiB 3.74 MiB +60.27 KiB (+1.60%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionQuantileGK.cp… 3.41 MiB 3.46 MiB +59.84 KiB (+1.72%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionUniqCombined1… 3.23 MiB 3.28 MiB +54.24 KiB (+1.64%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionUniqCombined1… 3.23 MiB 3.28 MiB +54.24 KiB (+1.64%)

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

Slowest function optimization changes (ThinLTO)

Median per-function time ratio to the master baseline: programs/clickhouse ×0.63, programs/clickhouse-keeper ×0.69 (each binary is linked separately, on a different machine and with different build flags); deltas below are relative to it.

Binary Function Master PR Δ vs median
programs/clickhouse DB::registerFunctionConversion(DB::FunctionFactory&) 5.7 s 14.3 s +10.7 s (+297%)
programs/clickhouse _ZN6detail10static_forITk7is_enumN2DB23AttributeUnderlyingTypeEZNS1_29callOnDictionaryAttributeType… 3.4 s 7.5 s +5.3 s (+252%)
Compile time of recompiled translation units

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

Job report

@valerypetrov

Copy link
Copy Markdown
Contributor Author

@groeneai , check why the CI is failing here.

@groeneai

groeneai commented Nov 1, 2026

Copy link
Copy Markdown
Collaborator

Neither failure is caused by this PR.

  1. Stateless tests (arm_binary, s3 storage, DBReplicated, parallel, 1/2): the server aborted on Logical error: Trying to deserialize data into Variant column with not global variants order (STID 6636-4f2a); Server died and the UNKNOWN tests in that job follow from it. The stack is a read of SHARED paths of a JSON column through the columns cache (MergeTreeReaderWide::readRowsWithColumnsCache -> SerializationObjectTypedSharedData::decodeGranule -> SerializationVariant). It hit more than 20 other PRs and master in the last 14 days. Fix: Fix LOGICAL_ERROR reading SHARED paths of dynamic types of a JSON column with the columns cache #127867 (open).

  2. Performance Comparison (amd_release, master_head, 5/6), long_primary_key #1 +16.5%: the query is a count() with a long primary key and never reaches the new code (the only callers of addBatchConsecutivePlaces are in AggregateFunctionForEach.h). The job log says WARNING: no performance reference build, the reference is the official build, so this PR's build was compared with the official build, which is built with different flags. All three long_primary_key queries are +16% in this run, not only the flagged one. Master c189bd9 has no reference build: MasterCI skipped Build (amd_release_performance_reference) there as not affected by its changed files, while the source change under it (129258f) had no MasterCI run of its own. A fix task is created for this gap in the reference lookup; I'll post the fixing-PR link here.

Performance Comparison (arm_release, master_head, 6/6) is still running.

@groeneai

groeneai commented Nov 1, 2026

Copy link
Copy Markdown
Collaborator

The fixing PR for the skipped performance reference build is #128453.

alexey-milovidov pushed a commit to Onyx2406/ClickHouse that referenced this pull request Nov 1, 2026
The merge queue fast-forwards master over up to 5 merges in one push and
MasterCI runs once, for the push head. For a push, praktika read the changed
files of the head commit only (`gh api commits/{sha}`), so a job affected
only by an earlier commit of the same push was filtered as "Not affected by
the changed files and not required", and functional/integration shards
skipped themselves as "Only test files changed". At master c189bd9 (ClickHouse#128277
in `src/` + ClickHouse#128142 tests only) this skipped 95 jobs, including both
`Build (*_release_performance_reference)`, so PR performance runs based on it
fell back to the official build (`long_primary_key` +16% on amd, ClickHouse#127846).
At f760cbb all 32 builds were skipped.

Now a push event records its `before` (`_Environment.PUSH_BEFORE_SHA`), and
`GH.get_changed_file_statuses` walks first parents from the head down to it,
reading all pages of each commit's file list (`gh api --paginate`), and
unions them (the newest commit's status wins). If the files cannot all be
known - an all-zero or malformed `before` (created branch), a failed or
malformed read, a commit at GitHub's 3000-file listing limit, a walk that
does not reach `before` within 50 commits - the result is `None` with a
warning, never a partial list, and it is not cached. `store_data.py` keeps
`None` for push events, so no job is filtered by it (`Job.is_affected_by`);
before, a failed read stored `[]`, which filtered every non-required job.
Without `before` (local runs, the native orchestrator) the head-only read
is unchanged; PR, merge queue, schedule and dispatch are unchanged.

Validated locally against the real GitHub API by replaying the 404 batched
master pushes of October: the result equals the union of every pushed
commit's files (re-parsed independently, commit lists from git) on 402, and
is unknown on the 2 that contain a 3000-file commit (ClickHouse#126194, and the docs
translation ClickHouse#124860); the job filter keeps 14,871 more job-runs on 131
pushes, plus 952 test shards that self-skipped now run in full, ~+7.8% of
October's 203,420 master job-runs, including both reference builds on 106
pushes. 100 single-commit pushes give identical statuses, with one request
for heads of up to 100 files.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
valerypetrov and others added 4 commits November 6, 2026 15:24
…ojection_where

Master reverted the failing test in 6fd7777; this brings the branch up to date so CI runs against it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

This branch has not been deployed

No deployments
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.). external Author is not a member of the ClickHouse organization pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants