Skip to content

Build arrays of arrays in function array without virtual calls per element - #128389

Open
groeneai wants to merge 5 commits into
ClickHouse:masterfrom
groeneai:function-array-nested-arrays-fast-path
Open

groeneai wants to merge 5 commits into
ClickHouse:masterfrom
groeneai:function-array-nested-arrays-fast-path

Conversation

@groeneai

@groeneai groeneai commented Oct 31, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #128330

Changelog category (leave one):

  • Performance Improvement

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

Function array (the [...] operator) builds arrays of arrays from non-constant arguments faster: about 2x when the inner arrays hold numbers, decimals or FixedString values.

Description

FunctionArray built Array(Array(T)) through executeGeneric: one virtual ColumnArray::insertFrom per (row, argument), which makes a second virtual insertRangeFrom on the nested column, an out-of-line memcpy and an offsets.push_back. In complex_array_creation ([[zero], [zero]], [[], [zero]], 20M elements per query) this chain is 83-89% of the query in the CPU profiles of this arm run, where it was also the code that ran 41% slower in one PR build (a binary whose diff never reaches it).

The new executeArray writes all element offsets in one pass, then copies the nested data. For fixed-width nested types (numbers, decimals, FixedString, UUID, IPv6, ...) it reserves the whole result once and copies raw bytes (memcpySmallAllowReadWriteOverflow15 up to 64 bytes, memcpy above, as in ColumnArray::replicateNumber). Other nested types keep the same insertRangeFrom call that ColumnArray::insertFrom made. Results are unchanged. Other element types (Map, LowCardinality, Variant, top-level UUID/IPv6) stay on executeGeneric.

x86 release, max_threads = 1, median of 75 runs, before -> after:

  • [[zero], [zero]]: 0.091 -> 0.045 s (2.02x); [[], [zero]]: 0.093 -> 0.045 s (2.07x)
  • [[toString(zero)], ...]: 1.12x, [[toNullable(zero)], ...]: 1.05x (generic path)
  • [a, a] with 8 KB / 4 MB elements: 1.77x / 4.46x; 8-byte + 1-byte elements: 1.63x

tests/performance/complex_array_creation.xml gets queries for Decimal64, FixedString, String and Nullable inner elements and for 8 KB inner arrays; 05838_array_of_arrays_from_columns checks that [a, b] equals arrayConcat([a], [b]) on both paths.

🤖 Generated with Claude Code


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

groeneai and others added 2 commits October 31, 2026 16:15
…element

`FunctionArray` built `Array(Array(T))` through `executeGeneric`, i.e. one
virtual `ColumnArray::insertFrom` per (row, argument). That call makes a second
virtual `insertRangeFrom` on the nested column (resize + out-of-line `memcpy`)
and an `offsets.push_back`. In `complex_array_creation` (20M elements per query)
this chain is 83-89% of the query in the arm CI CPU profiles, and it is the code
that ran ~41% slower in a per-binary slow build on PR ClickHouse#128330.

New `executeArray`, tried right before `executeGeneric`:
- writes all element offsets in one pass;
- fixed-width nested types (`isFixedAndContiguous`: ColumnVector of any T,
  ColumnDecimal, ColumnFixedString): one `insertRawUninitialized` for the whole
  result, then a raw copy per element. Copies of up to 64 bytes use
  `memcpySmallAllowReadWriteOverflow15`, longer ones `memcpy`: the 16-byte-step
  helper is slower than `memcpy` for long values (measured ~5% with 4 MB arrays
  in `ColumnArray::replicateNumber`, which uses the same split). The small copy's
  over-write lands on bytes the next copy rewrites or in the right padding;
- other nested types: the same `insertRangeFrom` call `ColumnArray::insertFrom`
  made, after one `reserve`, so their results are identical by construction.

x86 release, `max_threads = 1`, median of 75 runs (5 interleaved rounds):
`[[zero], [zero]]` 0.090 -> 0.044 s, `[[], [zero]]` 0.092 -> 0.043 s,
`[[toString(zero)], ...]` 1.12x, `[[toNullable(zero)], ...]` 1.08x,
`[a, a]` with 8 KB / 4 MB elements 2.11x / 4.38x, 8-byte + 1-byte elements 1.64x.
Results of the old and new binaries are byte-identical over 25 element types.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Drop the summary comment above executeArray; the code states the same thing.

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; 0 findings) plus a separate cold review (0 findings).
Checked: dispatch order in FunctionArray::execute, the Tuple recursion, offsets [-1] on PaddedPODArray,
the fixed-width predicate (ColumnVector, ColumnDecimal, ColumnFixedString only), padding for the small-copy
over-read and over-write, and that other nested types make the same insertRangeFrom calls as before.

Session id: cron:clickhouse-review-slot-8:20261031-161800

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Not a failure: the arm slowdown is per binary. The measured cost is the construction path itself: [[zero], [zero]] / [[], [zero]] 2.05x / 2.14x faster on x86 release, stable over 5 interleaved rounds.
b Root cause explained? executeGeneric made a virtual ColumnArray::insertFrom per element, which makes a virtual insertRangeFrom, a memcpy call and a push_back; 83-89% of the query in the CI profiles.
c Fix matches root cause? Yes: executeArray writes offsets in one pass and copies nested data directly; no threshold or test change.
d Test intent preserved / new tests added? complex_array_creation.xml unchanged. New 05473_array_of_arrays_from_columns; a mutation of each copy loop turns every check red.
e Both directions demonstrated? Before/after timings; byte-identical results of the old and new binaries over 25 element types.
f Fix is general across code paths? Covers executeImpl and the Tuple path (executeTuple); Nullable(Array) does not exist. Other element types keep executeGeneric.
g Fix generalizes across inputs (params/datatypes/wrappers)? Fixed-width (numbers, decimals, FixedString, UUID, IPv6) and other nested types (String, Nullable, Array, Tuple, Map, LowCardinality, Variant), empty arrays, constants, elements of 0..300 values.
h Backward compatible? (maintainer-approved exception only) Yes: no setting or format change, results byte-identical.
i Invariants and contracts preserved? offsets.size() == N * rows and offsets.back() == data.size(); small-copy over-write lands on bytes copied next or in the right padding.

Session id: cron:clickhouse-impl-slot-4:20261031-151400

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @Ergus @rschu1ze, could you review this and add the can be tested label so CI runs? Function array built Array(Array(T)) with one virtual ColumnArray::insertFrom per element; the new executeArray writes all offsets in one pass and copies fixed-width nested data as raw bytes, about 2x faster on complex_array_creation.

@clickhouse-gh

clickhouse-gh Bot commented Oct 31, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [0a0bc46]

Summary: ✅


AI Review

Summary

The PR optimizes array construction with Array arguments by filling offsets directly and copying fixed-width nested values in bulk. The earlier excessive reservation is removed, and the current revision includes result comparisons alongside performance tests and before/after measurements. Review of the current diff and all prior discussion found no unresolved actionable findings. 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 comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... labels Oct 31, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Nov 1, 2026
Comment thread src/Functions/array/array.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Nov 1, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 0a0bc4627 with master c11848bfc (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

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

Job report

`ColumnArray::reserve(n)` reserves `n` elements of its own nested column
too, so `out_nested.reserve(total)` in the generic branch of
`executeArray` allocated room for one innermost element per inner array.
With 200000 empty `Array(FixedString(256))` values that is a 51 MiB
allocation for nothing, and `[a, a]` failed under a 20 MB memory limit
that the previous `executeGeneric` loop stayed within. The same happens
through `Tuple` and `Map` holding arrays.

The previous loop did not reserve the nested column either, so drop the
call. Measured on x86 release against the base, median of 75 runs:
`[[toString(zero)], ...]` 1.12x, `[[toNullable(zero)], ...]` 1.05x
(1.13x / 1.08x with the reserve); the fixed-width branch is unchanged.

The test covers empty inner arrays of `Array`, `Tuple` and `Map`
elements under a 20 MB limit; all three fail with the reserve.

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

groeneai commented Nov 1, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 02a811f

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
Stateless tests (amd_debug, parallel) / 05474_parquet_corpus_writers not from this PR (it changes only FunctionArray): master since the merge of #128336 reads the nine polars 0.20.31 u64 > 9223372036854775807 rows as ok, while the reference still expects INCORRECT_DATA; true master fails the same way #128494 (ours, open)
Stateless tests (arm_binary, parallel) / 05474_parquet_corpus_writers same as the row above #128494 (ours, open)
Mergeable Check, PR praktika rollups of the rows above #128494 (ours, open)

CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261101-163005

@rschu1ze

rschu1ze commented Nov 9, 2026

Copy link
Copy Markdown
Member

cc @Ergus @rschu1ze, could you review this and add the can be tested label so CI runs?

Sorry, I won't find the time to check in detail.

@Ergus If you have some time :) ... thanks.

… test

Review asked for a performance test instead of the stateless test, so
`05473_array_of_arrays_from_columns` is removed and the existing
`complex_array_creation.xml` gets the shapes this change touches, after
its two unchanged queries:

- `Decimal64` and `FixedString(1)` inner elements (raw byte copy),
- `String` and `Nullable(UInt8)` inner elements (`insertRangeFrom` path),
- `[a, a]` with 8 KB inner arrays (the `memcpy` branch above 64 bytes).

Official amd_release builds of master b1e2520 and of this PR, local
`tests/performance/scripts/perf.py` run against two servers, median of
15 runs, master -> PR: 0.096 -> 0.052, 0.099 -> 0.050, 0.105 -> 0.056,
0.124 -> 0.072, 0.163 -> 0.147, 0.165 -> 0.157, 0.300 -> 0.170 s.

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

groeneai commented Nov 9, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 9e02bd1

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
Stress test (amd_tsan) / Hung check failed, possible deadlock found hang, not from this PR (it changes only array construction and a performance test): a theilsU(n, n) OVER (ORDER BY n ROWS BETWEEN ...) query of 04506_distributed_plan_window_function was cancelled (max_execution_time = 10) and still ran 3185 s inside AggregateWindowFunctionRecalculate::evaluate, which #129257 (merged 2026-11-06) added. A minimal theilsU window query stops on max_execution_time at that merge's first parent and keeps running at the merge commit a fix task is created (investigating at full effort, fixing-PR link to follow here)
Mergeable Check, PR praktika rollups of the row above a fix task is created (the row above)

The Performance Comparison jobs on this head have no red.

Session id: cron:our-pr-ci-monitor:20261109-130005

@groeneai

groeneai commented Nov 9, 2026 •

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the Stress test (amd_tsan) hung check row: #130328 (my revert #130331 was closed in favor of it).

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

I don't see any tests to check the results of the new copy paths because performance test only measures time. It does not compare results against a reference.

Could you add back a small stateless .sql test that compares results. For example, compare [a, b] against arrayConcat([a], [b]) for range(number % 20)

Because 05473 seems to be removed.

Review asked for a stateless test that compares results, because the
performance test only measures time. Each row counts the rows where
`[a, b]` differs from `arrayConcat([a], [b])`; `[a]` with one argument
copies its column with `insertRangeFrom` and does not reach the new code.

Rows cover the raw byte copy (`UInt8`, `UInt64`, `Decimal128`,
`FixedString(2)`, an always-empty argument, a constant argument, `Array`
inside `Tuple`) and the `insertRangeFrom` path (`String`, `Nullable`,
`Array(Array(UInt8))`). `complex_array_creation.xml` stays.

Checked on a debug build: all rows 0, same output from the master
snapshot binary, 50/50 randomized runs OK. Replacing every copy with
zeros or defaults makes every row non-zero; zeroing only the `memcpy`
branch above 64 bytes makes the `UInt64`, `Decimal128`, `Tuple` and
`Const` rows non-zero.

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

Copy link
Copy Markdown
Collaborator Author

Thanks, added back in 0a0bc46 as 05838_array_of_arrays_from_columns (05473 is taken on master now). Each row counts the rows where [a, b] differs from arrayConcat([a], [b]) over range(number % 20), for the raw-copy types (UInt8, UInt64, Decimal128, FixedString, an empty and a constant argument, Array inside Tuple) and the insertRangeFrom types (String, Nullable, Array(Array(UInt8))). [a] with one argument does not reach the new code, so the comparison does not depend on it.

Checked locally: zeroing every copy makes every row non-zero, and zeroing only the memcpy branch above 64 bytes makes the four rows with longer inner arrays non-zero. The performance test stays.

@Ergus Ergus 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 now

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-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants