Skip to content

Return the argument of emptyArrayToSingle when no array is empty - #130581

Merged
alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:empty-array-to-single-no-copy
Nov 11, 2026
Merged

alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:empty-array-to-single-no-copy

Conversation

@groeneai

@groeneai groeneai commented Nov 10, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #128472

Changelog category (leave one):

  • Performance Improvement

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

LEFT ARRAY JOIN is faster when no joined array is empty: emptyArrayToSingle now returns its argument as is instead of copying it row by row, which makes the LEFT ARRAY JOIN query of the array_join performance test about 1.6x faster.

Description

Performance Comparison (amd_release, master_head, 6/6) on #128472, which only changes Iceberg manifest writing, flagged array_join #1 (LEFT ARRAY JOIN of two one-element arrays over 10M rows) at +15%, confirmed after restart: report.

An aligned LEFT ARRAY JOIN runs emptyArrayToSingle over every joined array. The function always rebuilt the column one row at a time, a PODArray::resize and an out-of-line memcpy call per row, even when no array is empty and the result equals the input. That copy is the whole gap between #1 (0.112 s on master) and the inner ARRAY JOIN #0 over the same data (0.058 s). In the job's CPU profile all extra time of the PR binary is in this loop (self +30%, its memcpy calls +76%), while executeImpl is byte-identical in both binaries, only at another address: a per-row call loop that is sensitive to code placement.

Now emptyArrayToSingle checks the offsets once (std::adjacent_find, stopping at the first empty array) and returns its argument when no array is empty. Columns are copy-on-write, and executeConst already returns its argument for the same case.

Validation: local RelWithDebInfo A/B, 10 interleaved rounds of 11 runs, 8 threads: #1 0.1015 -> 0.0620 s (1.65x); #0 and a column with one empty array per block stay within noise (0.98x, 1.00x). 00206_empty_array_to_single gains queries for every element type path, Nullable, LowCardinality, nested arrays, an empty array only in the last row, a LEFT ARRAY JOIN mixing both cases, and a Map; its new reference comes from the unchanged binary, and fast paths with either condition removed fail it.


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

Version info

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

An aligned `LEFT ARRAY JOIN` runs `emptyArrayToSingle` over every joined
array column of a block. The function always rebuilt the column one row at
a time, with a `PODArray::resize` and an out-of-line `memcpy` call per row,
even when no array was empty and the result equals the input. That copy was
the whole difference between `LEFT ARRAY JOIN` and `ARRAY JOIN` over the
same data (`array_join` ClickHouse#1 0.112 s vs #0 0.058 s on master).

A per-row loop around a call to a tiny out-of-line callee is sensitive to
code placement. On ClickHouse#128472, whose diff only touches Iceberg manifest
writing, `Performance Comparison (amd_release, master_head, 6/6)` flagged
`array_join` ClickHouse#1 at +15% (confirmed after restart at three stack
placements). In the job's CPU profile the extra time is all in this loop
(self +30%, its `memcpy` calls +76%), while `executeImpl` is byte-identical
in the reference and the PR binary, only at another address.

Now the function checks the offsets once (`std::adjacent_find`, stopping at
the first empty array) and returns its argument as is when no array is
empty, which takes the loop off the path of such queries. Columns are
copy-on-write, so sharing the argument is safe, as in `executeConst` here.

Local RelWithDebInfo A/B, 10 interleaved rounds of 11 runs, 8 threads:
`array_join` ClickHouse#1 0.1015 -> 0.0620 s (1.65x), #0 and a column with one empty
array per block unchanged (0.98x, 1.00x).

`00206_empty_array_to_single` gains queries for every element type path,
`Nullable`, `LowCardinality`, nested arrays, an empty array only in the last
row, a `LEFT ARRAY JOIN` mixing a column with and without empty arrays, and
a `Map`; the reference was produced by the unchanged binary.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=128472&sha=7d3c4efb51731de1f1f13b27344be6f8e4645e81&name_0=PR&name_1=Performance%20Comparison%20%28amd_release%2C%20master_head%2C%206%2F6%29
Related: ClickHouse#128472

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 added SQL queries check values only, so they still pass if the fast path is removed (00206_empty_array_to_single.sql) DISAGREE The change is a speed-up; the CI check that fails on removal is the existing tests/performance/array_join.xml query #1 (local A/B 1.65x, every one of 10 rounds at least 1.42x). Wrong wiring fails 00206: the fast path without either condition fails it. No pointer-identity gtest added.
2 💡 Per-type row in the first new query exercises a type-independent path DISAGREE One cheap query that also pins the returned type; kept.
3 💡 .claude/CLAUDE.md prefers a new test file over extending one DISAGREE The new queries test the function 00206 covers and the test diff is additions only; kept.

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

Session id: cron:clickhouse-review-slot-8:20261110-182627

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Release A/B of array_join #1 (base vs fix, 10 interleaved rounds of 11 runs, 8 threads): faster in every round (1.42x to 2.26x, median 1.65x).
b Root cause explained? An aligned LEFT ARRAY JOIN runs emptyArrayToSingle on every joined array, and the function copied the column row by row (a resize plus an out-of-line 8-byte memcpy per row) even when no array was empty. That per-row call loop is code-placement sensitive: on #128472 the identical executeImpl at another address ran ~15% slower.
c Fix matches root cause? Yes. The copy is skipped exactly when it is the identity (no empty array), in the function that does it; every caller benefits. No perf test query changed.
d Test intent preserved / new tests added? 00206_empty_array_to_single extended (additions only); reference produced by the unchanged binary. The existing array_join #1 perf query measures the gain in CI.
e Both directions demonstrated? Base slow, fix fast (A/B above). 00206 passes on base (20 randomized runs) and fix (50/50 randomized), and fails on two mutated fast paths (each with one condition removed).
f Fix is general across code paths? The check precedes all four type dispatch paths (numbers, String, FixedString, generic) and reads only the outer offsets; all callers (ArrayJoinAction, ArrayJoinStep, the arrayJoin(emptyArrayToSingle(x)) lowering, direct calls) go through it.
g Fix generalizes across inputs (params/datatypes/wrappers)? Tested: integers, String, FixedString, Nullable, LowCardinality, nested Array, Map via ARRAY JOIN, an empty array only in the last row, an empty first row, mixed columns in one LEFT ARRAY JOIN. Const input keeps its existing path.
h Backward compatible? (maintainer-approved exception only) Yes: identical results and types, no setting, no format change.
i Invariants and contracts preserved? When no array is empty the copy would equal the argument (same type, offsets, data, null map), so returning it is exact; columns are copy-on-write and no ARRAY JOIN consumer mutates the result in place. The ILLEGAL_COLUMN check stays first.

Session id: cron:clickhouse-impl-slot-4:20261110-172600

@clickhouse-gh

clickhouse-gh Bot commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c47f9d4]

Summary: ✅


AI Review

Summary

PR #130581, reviewed at c47f9d45e77c9fa1c01f35efccd91277854d37d4, makes emptyArrayToSingle return its input when every array is nonempty. No actionable findings. The PR provides interleaved before/after measurements showing a 1.65× improvement, and CI passed 00206_empty_array_to_single and 05345_lower_array_join_empty_array_to_single. No local build or tests were run.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements can be tested Allows running workflows for external contributors comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... labels Nov 10, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 10, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing c47f9d45e with master 09696fc14 (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.

Slowest function optimization changes (ThinLTO)

Median per-function time ratio to the master baseline: programs/clickhouse-keeper ×1.10 (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&) 7.3 s 16.1 s +9.1 s (+129%)
Compile time of recompiled translation units

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

Job report

@yariks5s yariks5s self-assigned this Nov 10, 2026

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

Quite obscure, but good.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Nov 10, 2026
@alexey-milovidov alexey-milovidov self-assigned this Nov 10, 2026
Merged via the queue into ClickHouse:master with commit b192835 Nov 11, 2026
369 of 370 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 11, 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-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... 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.

4 participants