Skip to content

Presize the result and copy short values inline in ColumnArray::replicateNumber - #127665

Merged
alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:array-replicate-number-inline-copy
Oct 24, 2026
Merged

alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:array-replicate-number-inline-copy

Conversation

@groeneai

@groeneai groeneai commented Oct 23, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #117136 (comment)

Changelog category (leave one):

  • Performance Improvement

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

Repeating arrays of numbers, as materialize of a constant array and arrayWithConstant do, is faster: the result is allocated once, and arrays of up to 64 bytes are copied inline instead of through a separate memcpy call. For example, SELECT has(materialize(range(10)), 5) FROM numbers(10000000) is about 35% faster.

Description

Performance Comparison (amd_release, master_head, 3/6) on #117136 reported rewrite_array_exists +17% (job). The same two queries were also slower on three master runs. In CI's CPU profiles of this test (amd, 30 days), 597 of 1056 run pairs differ by at least 40 samples, and on average 81% of that gap is in ColumnArray::replicate + memcpy, while has itself does not change.

materialize(range(10)) goes through ColumnArray::replicateNumber, which for every output row grew both result arrays and called memcpy for 10 bytes, about 10M calls per query. It now computes the exact result size first, as ColumnString::replicate does, and copies values of up to 64 bytes with memcpySmallAllowReadWriteOverflow15; longer values keep memcpy, which is faster for them.

Validation, local release A/B (10 interleaved rounds, 90 samples per query, fix/base median):

  • rewrite_array_exists queries 0 and 1: 0.047 s -> 0.030 s (0.64)
  • column_array_replicate: Decimal32 0.62, Decimal64 0.66, (U)Int128 0.87/0.89, Decimal128 0.91; 256-bit types 0.97 to 1.07 (UInt256 read 0.89 in a re-run; all three run the same code)
  • other sizes: 64-byte arrays 0.94; 128 B, 1 KB, 8000 B 0.97, 0.60, 0.98; 4 MB 0.99 (constant length) and 0.63 (varying length, the result is no longer regrown); sparse repeat counts 1.00, 1.01, 0.93

These are local numbers; this PR's own performance comparison is the real check. The change removes the per-row call, it does not prove that a slow run cannot happen again.

New test 05446_array_replicate_numeric covers 8 element types (widths 1 to 32 bytes, Nullable, Tuple), lengths 0 to 36 and repeat counts 0 to 3. Four mutations of the new loop each make it fail.

🤖 Generated with Claude Code


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

Version info

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

groeneai and others added 2 commits October 23, 2026 21:01
…l per row

ColumnArray::replicateNumber grew both result arrays and called memcpy for
every output row. For `materialize(range(10))` over 10M rows that is about
10M calls of 10 bytes, and in CI's CPU profiles of `rewrite_array_exists`
this is where the slow runs spend their extra time (on average 81% of the
gap between the slow and fast binary of a run, while `has` is flat).

Compute the exact result size once, write the offsets by index, and copy
each row with memcpySmallAllowReadWriteOverflow15, as ColumnString::replicate
and ColumnArray::replicateString already do. Both containers are
PaddedPODArray, and the copies go in increasing order, so the overflow of
each copy lands in the next one or in the right padding.

Locally (release, 4 pinned cores) `rewrite_array_exists` goes from 0.048 s
to 0.030 s per query, `column_array_replicate` is 5-40% faster for the
narrower element types and unchanged for 256-bit types, and 8000-byte
arrays are unchanged.

The new test covers 8 element types (widths 1 to 32 bytes, Nullable,
Tuple), array lengths 0 to 36 and repeat counts 0 to 3.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
memcpySmallAllowReadWriteOverflow15 copies in 16-byte steps and is slower
than memcpy for long values: with constant 4 MB arrays the previous commit
was about 5% slower than master (per-round medians 0.189-0.193 s on master,
0.199-0.204 s with the change). Copy values of up to 64 bytes inline and
keep memcpy for longer ones, the same threshold as copyStagedKeyBytes in
AdaptiveAggregationKernels.cpp.

Release builds, 4 pinned cores, 10 interleaved rounds, median vs master:
constant 4 MB arrays 0.990, `materialize(range(1000000))` over 128 rows
1.000, `rewrite_array_exists` queries 0.638, 1 KB arrays of varying length
0.60 (the exact result size means the result is no longer regrown).

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; 3 findings on the first head, 0 on the delta recheck).

# Sev Finding Verdict Evidence / action
1 ⚠️ memcpySmallAllowReadWriteOverflow15 is slower than memcpy for long values AGREE, fixed @ 19c711b values over 64 bytes keep memcpy; constant 4 MB rows 0.99 of master
2 ⚠️ the exact-size pass costs time when most rows repeat 0 times DISAGREE the reported numbers came from debug builds; release: 1.00, 1.01 and 0.93 of master on three sparse queries, incl. the reviewer's own
3 ⚠️ the new test passes on master DISAGREE a SQL test cannot observe speed; four mutations of the new loop make it fail; rewrite_array_exists and column_array_replicate are the performance checks

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

Session id: cron:clickhouse-review-slot-8:20261023-231200

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Performance change, so the repro is a local release A/B: rewrite_array_exists queries 0 and 1 run 0.047 s on base and 0.030 s with the change, on every one of 10 interleaved rounds (90 samples each). The CI slow mode itself needs CI hardware; this PR's own performance comparison is the oracle.
b Root cause explained? ColumnArray::replicateNumber grew both result arrays and called memcpy for every output row (about 10M calls of 10 bytes for materialize(range(10)) over 10M rows). CI's CPU profiles of this test put on average 81% of the slow-vs-fast gap in ColumnArray::replicate + memcpy.
c Fix matches root cause? Yes. The result is sized exactly once and values of up to 64 bytes are copied inline with memcpySmallAllowReadWriteOverflow15, in the one function every caller goes through; longer values keep memcpy, which is faster for them. No test or threshold changed.
d Test intent preserved / new tests added? New test 05446_array_replicate_numeric: 8 element types, lengths 0 to 36, repeat counts 0 to 3, toString oracle computed before the replication.
e Both directions demonstrated? Speed: base vs fix A/B above. Correctness: the test passes on base and on the fix, and four mutations of the new loop each make it fail (source shifted by one element, offset stored before the increment, and the byte count without sizeof(T) in either the inline or the memcpy branch).
f Fix is general across code paths? One template for all 20 dispatched number types; replicateNullable, replicateTuple and ColumnMap::replicate reach it. replicateString, ColumnString, ColumnFixedString already copy inline; replicateGeneric is a different path.
g Fix generalizes across inputs (params/datatypes/wrappers)? Element widths 1, 2, 4, 8, 16, 32 bytes, Nullable, Tuple, empty arrays, repeat count 0, rows on both sides of the 64-byte threshold. Speed checked from 10 bytes to 4 MB per value, constant and varying lengths, and sparse repeat counts.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, format, serialization or default change.
i Invariants and contracts preserved? Each source row appears replicate_offsets[i] - replicate_offsets[i - 1] times; offsets and data sizes are exact by construction; the 15-byte overflow of the inline copy stays inside the next copy or the PaddedPODArray right padding; the size-mismatch throw and empty-column return are unchanged.

Session id: cron:clickhouse-impl-slot-5:20261023-220900

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @CurtizJ @azat, could you review this and add the can be tested label so CI runs? ColumnArray::replicateNumber (used by materialize of a constant array) grew both result arrays and called memcpy for every output row; it now sizes the result once and copies values of up to 64 bytes inline.

@clickhouse-gh

clickhouse-gh Bot commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [19c711b]

Summary: ✅


AI Review

Summary

The PR preallocates the result of ColumnArray::replicateNumber and copies arrays of up to 64 bytes inline, retaining memcpy for longer arrays. No actionable findings at 19c711b45d0704f8755e99e48d1613f306ec58eb. The reported release A/B measurements support the performance claim; the new stateless test and 74 additional boundary and wrapper queries passed locally using the PR's Fast test binary.

Missing context / blind spots
  • ⚠️ CI performance comparisons on both architectures and sanitizer jobs were still pending. Completed reports are needed to independently confirm the reported performance and sanitizer behavior.
Final Verdict

✅ Approve — no unresolved findings.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Oct 23, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Oct 23, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-data-types Type system & core datatypes used across query planning/execution. label Oct 24, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 24, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 19c711b45 with master 4ad5968c3 (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, 9 s compile time in total, 7 of them have a recent master baseline.

Job report

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

All good.

@alexey-milovidov alexey-milovidov self-assigned this Oct 24, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 24, 2026
Merged via the queue into ClickHouse:master with commit 9dbfeed Oct 24, 2026
526 of 528 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 24, 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-data-types Type system & core datatypes used across query planning/execution. 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