Skip to content

Typed fast path for arraySort/arrayReverseSort over numeric arrays - #109832

Merged
murphy-4o merged 11 commits into
ClickHouse:masterfrom
raimannma:array-sort-typed-fast-path
Jul 14, 2026
Merged

murphy-4o merged 11 commits into
ClickHouse:masterfrom
raimannma:array-sort-typed-fast-path

Conversation

@raimannma

@raimannma raimannma commented Jul 8, 2026 •

Copy link
Copy Markdown
Contributor

Sort the values of numeric arrays directly in arraySort/arrayReverseSort when there is no lambda, instead of sorting a permutation through per-comparison IColumn::compareAt and permuting the nested column afterwards. Integers go through ::sort, long (U)Int8 ranges through a counting sort, and floats first move NaNs to the end so the sort comparator stays branchless while keeping the same NaN placement as the generic path. Decimal32/64/128/256 and DateTime64 arrays take the same fast path: their raw values order the same way as compareAt, because the scale is uniform within a column.

Measured single-threaded: 1.6-2.3x faster for typical array sizes and up to ~10x for long one-byte arrays; decimals measure 1.5-2.6x depending on the width. Adversarial shapes (presorted, all-equal, all-NaN, tiny and huge arrays) measured no slower than before. Nullable, String, lambda, and partial sort paths are unchanged.

Changelog category (leave one):

  • Performance Improvement

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

Functions arraySort and arrayReverseSort are several times faster over numeric arrays (including Decimal and DateTime64) when called without a lambda.

raimannma added 4 commits July 8, 2026 18:03
When there is no lambda (or the lambda is the identity), sort each
row's range of raw values of a numeric ColumnVector directly, instead
of sorting a permutation through per-comparison IColumn::compareAt and
permuting the nested column afterwards.

Strategy per type: sort from base/sort.h (ipnsort) for integers,
counting sort for (U)Int8 ranges of 256+ elements, and for floats a
partition moving NaNs last (matching the nan_direction_hint of the
generic path) followed by a branchless-comparator sort.

Measured single-threaded, net of data generation, min of 5 interleaved
runs: 1.6-1.8x for 32-element integer arrays, 2x for Float64 (2.3x
with NaNs present), 2.2x for UInt8 arrays of 300 elements, 9.8x for
UInt8 arrays of 2000 elements. Nullable, String, lambda, and partial
sort paths are unchanged. Output verified byte-identical against the
previous implementation across all numeric types, NaN/Inf mixtures,
Nullable elements, and empty/tiny/large arrays.
- Guard countingSort8 against UInt32 counter overflow: ranges longer than
  4294967295 elements fall back to `::sort`, matching the guard in
  `ColumnVector::updatePermutation`. Previously a single array row with
  2^32 equal one-byte values silently produced a corrupted result.
- Use the `is_floating_point` concept from `base/extended_types.h`
  instead of `std::is_floating_point_v`, so that a future `BFloat16`
  dispatch cannot silently take the integer branch with wrong NaN handling.
- Document in `FunctionArrayMapped.h` that `ArraySortImpl` detects the
  no-lambda case by pointer identity of the `getDataPtr` result.
- Cover the counting sort branch in tests: exact boundary checks at 256
  elements, randomized consistency checks straddling the threshold, and a
  long-array `UInt8` query in the performance test.
- Make the Float32 special-value tests actually run on `Array(Float32)`
  (the previous literals were promoted to `Float64`).
- Label the per-type consistency outputs to make failures attributable.
- Wrap identifiers in comments in inline code blocks.
The only caller enters the branch precisely when `mapped` is the same
column as the array data, so dispatching on `array.getData()` directly
makes the aliasing invariant unnecessary.
@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Jul 8, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 8, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [ec21641]

Summary: ✅


AI Review

Summary

This PR adds a typed fast path for arraySort/arrayReverseSort over numeric arrays and a byte-counting fast path in ::sort for contiguous 1-byte integral ranges. I did not find any remaining correctness, compatibility, or evidence gaps in the current diff; the earlier coverage gaps for BFloat16, wide integers, decimals, and DateTime64 are addressed in the current code and tests.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Jul 8, 2026
Comment thread src/Functions/array/arraySort.cpp Resolved
…rning

Dispatch over FOR_NUMERIC_TYPES instead of FOR_BASIC_NUMERIC_TYPES, so
Array(BFloat16) and Array((U)Int128/256) take the typed fast path too,
matching the "numeric arrays" wording of the changelog entry. Cover the
new types in the stateless test (boundary values and consistency with
the generic comparator path) and in the performance test.

Wrap the dispatch macro in NOLINT(bugprone-macro-parentheses), fixing
the clang-tidy error that failed the ARM tidy build:
https://s3.amazonaws.com/clickhouse-test-reports/PRs/109832/7a824e776076e9d740aa2fdf5722fb2977a0ad4e/build_arm_tidy/build_clickhouse/build_clickhouse.log

PR: ClickHouse#109832

Co-Authored-By: Claude Fable 5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 8, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

This PR adds an arraySort/arrayReverseSort numeric fast path plus a counting-sort route for 1-byte integers, both compile-time gated to those exact call shapes. None of the flagged queries (clickbench Q4, Q15, Q32, Q33 and tpch_adapted_1_official Q4) use arraySort or sort 1-byte data, so none can be affected by the change. The math already reached the right verdicts: the two -15.2% clickbench improvements are consistent co-location/run-to-run variance suppressed as within-envelope, and the +5-22% not_sure deltas are noise, not real PR effects.

clickbench

⚠️ 2 inconclusive

Flagged queries (2 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 32 not_sure 1321 1607 +21.6% 0.0126 The +21.7% is borderline and off-path — this query touches neither changed sort route — so it reads as variance. not_sure stands.
⚠️ 33 not_sure 1420 1500 +5.7% 0.0012 The +5.7% delta is small and unrelated to the arraySort/1-byte sort changes; not_sure is the right call.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

⚠️ 1 inconclusive

Flagged queries (1 of 22)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 4 not_sure 1018 1077 +5.8% <0.0001 History is noisy and this query exercises neither changed code path, so the +5.8% is intrinsic variance rather than a PR effect. not_sure stands.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

Debug info
  • StressHouse run: 42d78e11-c791-4048-8623-3b4490ea5abe
  • MIRAI run: c5d79aec-be1b-4a6a-8fbf-ccf28baa40e3
  • PR check IDs:
    • clickbench_475450_1783983873
    • clickbench_475456_1783983873
    • clickbench_475462_1783983873
    • tpch_adapted_1_official_475467_1783983872
    • tpch_adapted_1_official_475485_1783983873
    • tpch_adapted_1_official_475492_1783983873

Comment thread src/Functions/array/arraySort.cpp Resolved
Array(Decimal32/64/128/256) and Array(DateTime64) were still taking the
generic permutation path even though they are numeric. Sorting the raw
decimal values orders them the same way as compareAt, because the scale
is uniform within a column. Measured single-threaded with 32-element
arrays: 1.5-2.6x faster end-to-end depending on the decimal width.

Co-Authored-By: Claude Fable 5 <[email protected]>
@murphy-4o murphy-4o self-assigned this Jul 13, 2026
Comment thread src/Functions/array/arraySort.cpp Resolved
raimannma and others added 4 commits July 13, 2026 12:46
Move the counting sort for 1-byte integer types from the arraySort
fast path into ::sort in base/sort.h, where it applies to any
contiguous range ordered by plain std::less/std::greater. Compared to
the previous version:

- The threshold is lowered from 256 to 64 elements: measurements show
  the crossover against ipnsort on random data is at 64-128 elements.
- Sorted and reverse-sorted inputs are detected in advance (like
  ipnsort does internally): the histogram pass degenerates into a
  serial dependency chain on such patterns, and the pre-checks handle
  them at ~0.3-1.0 ns/element instead.

Benchmarks against ipnsort, pdqsort, pdqsort_branchless, driftsort and
std::sort on UInt8 data show the new ::sort is the fastest or tied at
every measured size and distribution from 64 elements up: up to 25x
faster than ipnsort on random data and ~12x on reverse-sorted data
with duplicates (where ipnsort's strictly-descending run detection
does not fire).

Co-Authored-By: Claude Fable 5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 14, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.80% 85.80% +0.00%
Functions 92.70% 92.70% +0.00%
Branches 78.00% 78.00% +0.00%

Changed lines: Changed C/C++ lines covered: 64/64 (100.00%) · Uncovered code

Full report · Diff report

@murphy-4o
murphy-4o enabled auto-merge July 14, 2026 03:59
@raimannma

Copy link
Copy Markdown
Contributor Author

@murphy-4o anything I need to do for the CH Inc sync check?

@murphy-4o
murphy-4o added this pull request to the merge queue Jul 14, 2026
@murphy-4o

Copy link
Copy Markdown
Member

@murphy-4o anything I need to do for the CH Inc sync check?

not really. i can handle it.

Merged via the queue into ClickHouse:master with commit 70ac4fd Jul 14, 2026
176 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 14, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…rning

Dispatch over FOR_NUMERIC_TYPES instead of FOR_BASIC_NUMERIC_TYPES, so
Array(BFloat16) and Array((U)Int128/256) take the typed fast path too,
matching the "numeric arrays" wording of the changelog entry. Cover the
new types in the stateless test (boundary values and consistency with
the generic comparator path) and in the performance test.

Wrap the dispatch macro in NOLINT(bugprone-macro-parentheses), fixing
the clang-tidy error that failed the ARM tidy build:
https://s3.amazonaws.com/clickhouse-test-reports/PRs/109832/7a824e776076e9d740aa2fdf5722fb2977a0ad4e/build_arm_tidy/build_clickhouse/build_clickhouse.log

PR: ClickHouse#109832

Co-Authored-By: Claude Fable 5 <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…fast-path

Typed fast path for arraySort/arrayReverseSort over numeric arrays
lazerg pushed a commit to lazerg/ClickHouse that referenced this pull request Nov 17, 2026
…arter of their rows

No existing query number or text changes: 2 queries (20 numbered entries) are disabled and 4 (20
entries) appended, as 26-45. The two `{type}` queries get `disabled="1"`, which stops all ten of
their expansions; the 16 sub-second ones (master's 0-4, 7-14, 17-19) are appended verbatim through
a new `{narrow_type}` substitution, the four over Int128 and UInt256 (master's 5, 6, 15, 16: 1.49-2.43 s
on MasterCI amd, 1.18-1.50 s on arm) through `{wide_type}` on numbers(500000) instead of 2000000.

Each of the four sorts 2M arrays of 32 16- or 32-byte elements on one thread through the typed fast
path of ClickHouse#109832; user time is linear in rows. The copies keep the same 65409-row blocks (8 instead of
31) and the same per-block work. Every run also pays a fixed fault-in of its block after perf.py's
jemalloc purge, as on MasterCI.

Measured with perf.py on the official MasterCI amd builds, 8 pinned cores, two repetitions on
different NUMA nodes (per-row gates with the L3 capped to 30 MiB, 20 runs per server):
- per-row user time copy / original 0.969-1.006; user-time sort share within 0.016;
- kept fraction of a per-row change 0.897-0.950 (fixed part 21-59 ms per run);
- ClickHouse#117346 (clang 23; MasterCI 0.878 amd / 0.913 arm on the UInt256 sort): original 0.911 / 0.916,
  copy 0.922 / 0.916; ClickHouse#120808 on the Int128 reverse sort: original 1.045 / 1.046, copy 1.051 / 1.044.

The Decimal128 query (entry 22) stays enabled: its copy kept under half of ClickHouse#120808's effect in one
of four pass measurements (0.42).

Projected copy medians 0.40-0.66 s amd, 0.31-0.41 s arm: about 21 s (amd) and 15 s (arm) less query
time per master perf job.

Related: ClickHouse#129258

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

5 participants