Skip to content

Use branchless quicksort (blqsort) for the general-purpose sort - #106618

Closed
alexey-milovidov wants to merge 13 commits into
masterfrom
try-blqsort
Closed

alexey-milovidov wants to merge 13 commits into
masterfrom
try-blqsort

Conversation

@alexey-milovidov

Copy link
Copy Markdown
Member

Replace pdqsort with branchless quicksort (blqsort, https://github.com/chkas/blqsort) as the general-purpose comparison sort behind ::sort in base/base/sort.h.

blqsort uses branchless partitioning and sorting networks for trivially-copyable types and BlockQuicksort (Edelkamp & Weiß) for complex types, with a heapsort fallback that keeps the worst case at O(n log n). On unpatterned, high-cardinality data — the common case that reaches ::sort — it is much faster than pdqsort because it avoids branch mispredictions in the partitioning loop.

pdqsort is kept where its pattern-defeating fast paths are the right tool: trySort (the pre-pass that detects already-sorted, reverse-sorted and nearly-sorted inputs) and the rare non-contiguous random-access iterators (e.g. reverse iterators over contiguous storage). nth_element and partial_sort continue to use miniselect. Because trySort runs before ::sort and still uses pdqsort, the patterned inputs on which blqsort is weaker are filtered out before they reach it.

blqsort operates on raw pointers, so the (always contiguous) iterators are converted with std::to_address.

Measurements

Algorithm microbenchmark (aarch64, clang 21, 10M elements, best-of):

  • random UInt64: 3.2x faster; random Float64: 3.9x faster; few-unique: ~2x faster.
  • random permutation with an indirect comparator (data[a] < data[b], the dominant pattern): 1.55x faster.

Real ORDER BY queries (20M rows, single thread, best-of-5, end-to-end):

  • String high-cardinality ORDER BY s: 6.99 s -> 5.92 s (~18% faster).
  • String low-cardinality ORDER BY s: 3.04 s -> 2.54 s (~20% faster).
  • Float64 ORDER BY x (control, uses RadixSort, not ::sort): unchanged, confirming the gains are attributable to the sort swap.

Correctness

An 880-case stress test (sizes 0..1M, boundary sizes around 11/512/1024, varying duplicate densities, sorted / reverse / organ-pipe inputs, and strings) matches std::sort element-wise with zero failures. In the built server, ORDER BY output is provably sorted and byte-identical to the pdqsort output.

Note on the vendored library

blqsort's branchless partitioning allocated its scratch buffers as T buf[N], which requires T to be default-constructible. Some ClickHouse types (e.g. DB::Interval) are trivially-copyable but not default-constructible. The buffers are switched to uninitialized aligned storage (valid for the trivially-copyable, implicit-lifetime types that take this path). The change is marked with a ClickHouse modification comment in contrib/blqsort/blqs.h. The header is vendored the same way as contrib/pdqsort.

Changelog category (leave one):

  • Performance Improvement

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

Use branchless quicksort (blqsort) for the general-purpose comparison sort, speeding up ORDER BY on non-numeric columns (e.g. strings) by roughly 20% and high-cardinality comparison sorts by several times.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

🤖 Generated with Claude Code

Replace `pdqsort` with branchless quicksort (`blqsort`) as the algorithm
behind `::sort` in `base/base/sort.h`. `blqsort` uses branchless
partitioning and sorting networks for trivially-copyable types and
BlockQuicksort for complex types, with a heapsort fallback bounding the
worst case at `O(n log n)`. On unpatterned, high-cardinality data it is
much faster than `pdqsort` by avoiding branch mispredictions in the
partitioning loop.

`pdqsort` is kept where its pattern-defeating fast paths help: `trySort`
(which already detects sorted, reverse-sorted and nearly-sorted inputs
before `::sort` runs) and the rare non-contiguous random-access
iterators. `blqsort` operates on raw pointers, so the always-contiguous
iterators are converted with `std::to_address`.

Microbenchmark (aarch64, clang 21, 10M elements, best-of): random
`UInt64` 3.2x faster, random `Float64` 3.9x faster, random permutation
with an indirect comparator 1.55x faster. Real `ORDER BY` on a `String`
column (20M rows, single thread) is ~18-20% faster end-to-end; arithmetic
`ORDER BY` is unchanged because it uses `RadixSort`.

`blqsort`'s branchless scratch buffers were allocated as `T buf[N]`,
requiring `T` to be default-constructible; some ClickHouse types (e.g.
`DB::Interval`) are trivially-copyable but not default-constructible.
The buffers are switched to uninitialized aligned storage, valid for the
trivially-copyable implicit-lifetime types that take this path. The
header is vendored the same way as `contrib/pdqsort`.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jun 6, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [ffe33c5]

Summary: ✅


AI Review

Summary

This PR replaces the central ::sort path for contiguous iterators with vendored blqsort, while preserving pdqsort for non-contiguous iterators and adding a pdqsort_try_sort pre-pass to keep patterned-input behavior. The earlier review issues around missing coverage and the right_offs uninitialized read are addressed in the current code, and I did not find new blockers or major issues in the final combined diff.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements submodule changed At least one submodule changed in this PR. labels Jun 6, 2026
Comment thread base/base/sort.h Resolved
Two distinct issues failed the `Build (arm_tidy)` job; 15 of the 16 failing
translation units were the same false positive.

1. The clang static analyzer reports `clang-analyzer-cplusplus.Move`
   ("moved-from object is moved") in `blqsort`'s heapsort. The moves are
   correct - each moved-from slot is overwritten before being read again -
   so the heapsort is wrapped in `NOLINTBEGIN/NOLINTEND` for that check.

2. `int last_version` and `CompressionMethod compression_method` in
   `Iceberg/Mutations.cpp` were declared uninitialized
   (`cppcoreguidelines-init-variables`). This is a pre-existing latent issue
   unrelated to sorting; it surfaced because changing the widely-included
   `base/base/sort.h` invalidated the clang-tidy cache and forced fresh
   re-analysis. Both variables are assigned in every branch before use, so
   initializing them at declaration is behavior-neutral.

Verified locally with clang-tidy: the heapsort warning is now suppressed
(exit 0).

CI report: https://s3.amazonaws.com/clickhouse-test-reports/PRs/106618/3e75bb2444cb646336f62f8a1efaae33cf08da7c/build_arm_tidy/build_clickhouse/build_clickhouse.log

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Comment thread contrib/blqsort/blqs.h Resolved
@clickhouse-gh

clickhouse-gh Bot commented Jun 6, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

🔴 AI verdict: degradation — 2 regressed, 4 improved out of 38 analysed

This PR replaces pdqsort with branchless quicksort (blqsort) in the core comparison-sort path behind ORDER BY and getPermutation, keeping a pdqsort pre-pass for already-patterned inputs. The flagged deltas are all sort-heavy queries and move exactly as that tradeoff predicts: high-cardinality unpatterned sorts get faster (Q22/Q23 on clickbench, Q7/Q20 on tpch_adapted_1_official), while near-sorted inputs regress (clickbench Q18 +11.76%, tpch Q8 +18.97%). Both regressions land on queries already trending down on master, so blqsort appears to compound an existing pattern-sensitive slowdown rather than introduce a fresh one. Q20's large improvement is real-looking but rests on noisy measurements, so treat it as borderline.

clickbench

🔴 1 regressed · 🟢 2 improved

Flagged queries (3 of 43)
Query Verdict Baseline med (ms) PR med (ms) Change q-value Hint
🔴 18 regression 1403 1568 +11.8% <0.0001 cpu: Swaps pdqsort->blqsort in ::sort; blqsort is slower on patterned inputs, plausible +11.76%; history trending.
🟢 22 improvement 334 262 -21.6% <0.0001 cpu: blqsort speeds high-cardinality sorts; -21.56% consistent, though base measurements were noisy.
🟢 23 improvement 297 199 -33.0% <0.0001 cpu: blqsort faster on unpatterned data; clean -33% with low variation, confirmed by both tests.

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 regressed · 🟢 2 improved

Flagged queries (3 of 22)
Query Verdict Baseline med (ms) PR med (ms) Change q-value Hint
🔴 8 regression 156 185 +19.0% <0.0001 cpu: blqsort regresses near-sorted/patterned inputs; +18.97% plausible; trending on master, may compound.
🟢 7 improvement 113 74 -34.5% <0.0001 cpu: Core sort path swapped to blqsort; -34.51% plausible for a sort-heavy query, both tests agree.
🟢 20 improvement 248 132 -46.8% <0.0001 cpu: On-path sort swap; large -46.77% but underlying measurements very noisy and history flaky -- borderline.

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: de584f07-8ce4-4575-bffb-3eec0448aaa4
  • MIRAI run: 9097a58e-6ada-48a9-830f-b2999c04e5d4
  • PR check IDs:
    • clickbench_25489_1781366080
    • clickbench_25491_1781366080
    • clickbench_25501_1781366080
    • tpch_adapted_1_official_25507_1781366080
    • tpch_adapted_1_official_25515_1781366080
    • tpch_adapted_1_official_25528_1781366080

Reviewer caught a real bug at blqs.h:389. `block_qsort` declared
`int left_offs, right_offs;` uninitialized. `right_offs` is assigned only
in the `else` (fill-right-block) branch of the partitioning loop; when the
median-of-medians pivot is the maximum of the range, no scanned element is
`>= pivot`, so `nleft` stays 0, the `else` branch never runs, and the
post-loop cleanup reads `right_offs` uninitialized. With a hostile value the
`right_offs - 1` loop bound overflows and the empty loop can instead perform
a wild out-of-bounds `iter_swap`.

A 21-element input reproduces it, proven under MemorySanitizer
(use-of-uninitialized-value at blqs.h:422, allocated at blqs.h:389).
Initializing both offsets to 0 fixes it. Verified: the MSan reproducer is
clean and the 880-case correctness stress test still passes.

Reported upstream: chkas/blqsort#2

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

This included the library directly - not as a submodule. Direct source inclusion of small libraries is good.

alexey-milovidov and others added 2 commits June 6, 2026 04:59
… read

SQL regression test for the uninitialized read of `right_offs` fixed in the
previous commit. `groupArraySorted` over a generic (`Field`) column sorts a
`std::vector<Field>` via `::sort`, which dispatches to `block_qsort` because
`Field` is larger than 16 bytes. The 21-element input is the reduced
reproducer (zero-padded so lexicographic order matches the integer order of
the C++ PoC); its median-of-medians pivot is the maximum of the range, so the
partitioning loop never assigns `right_offs` and the cleanup read it.

The argument is greater than 1000000 to select the sort strategy that keeps
values in insertion order, and `max_threads = 1` keeps the aggregation order
deterministic, so `block_qsort` sees exactly this sequence. Under
MemorySanitizer the unfixed code aborted with use-of-uninitialized-value; with
the fix the query returns the sorted array.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

A lot of slowdowns compared to pdqsort - looks like not worth it:

Screenshot 2026-06-06 at 19 57 11

alexey-milovidov and others added 3 commits June 8, 2026 13:47
`blqsort` has no pattern-defeating fast paths, unlike `pdqsort` which handled
already-sorted, reverse-sorted and nearly-sorted inputs internally on every
`::sort` call. The PR assumed such inputs are always filtered by a `trySort`
pre-pass at the call site, but that is not true for every caller: in particular
`ColumnDecimal<Decimal128>::getPermutation` skips the radix / `trySort` block
(because `Int128` is a big integer) and calls `::sort` directly. As a result
`ORDER BY toDecimal128(...) DESC` over ascending data (a reverse-sorted
permutation) regressed by an order of magnitude (`order_by_decimals` +389% in
the performance comparison).

Run `pdqsort_try_sort` (the same pre-pass behind `trySort`) inside `::sort`
before falling back to `blqsort`, restoring the behavior `pdqsort` provided. A
microbenchmark of the indirect reverse-sorted permutation (2M `Int128`) shows
`pdqsort` 4.2 ms, `blqsort` 74.8 ms, pre-pass + `blqsort` 4.1 ms; on random data
`blqsort` 101.9 ms vs pre-pass + `blqsort` 102.9 ms (~1% overhead), so the
several-fold speedup on unpatterned data is preserved.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…parators

Addresses review feedback: there was no in-tree test exercising the `::sort`
contract after switching the implementation to `blqsort`. The test compares
`::sort` with `std::sort` element-wise across boundary sizes (`0..13`, around
`512` and `1024`), patterned inputs (sorted, reverse, organ-pipe,
duplicate-heavy, all-equal), a 16-byte wide type matching `Decimal128`, and an
indirect comparator over a permutation (the hot `getPermutation` path, including
the reverse-sorted case that regressed). It also checks that `trySort` produces
a fully sorted result whenever it reports success.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Continued this PR: merged master (was 556 commits behind), fixed the real performance regression, and added the requested test.

Performance regression fixed (order_by_decimals +389%)

The perf comparison flagged order_by_decimals #4 — SELECT toDecimal128(number, 10) AS n FROM numbers(10000000) ORDER BY n DESC — as +389% (4.9x slower), consistently on both arm and amd. This is a genuine regression caused by the sort swap, not noise.

Root cause: the PR's premise is that patterned inputs are caught by a trySort pre-pass before reaching ::sort, so blqsort (which has no pattern-defeating fast paths) only ever sees unpatterned data. That invariant does not actually hold for every caller. ColumnDecimal<Decimal128>::getPermutation skips the radix/trySort block entirely (because Int128 is a big integer) and calls ::sort directly via getPermutationImpl / DefaultSort. For ORDER BY ... DESC over the ascending numbers(...) data, the permutation is reverse-sorted — exactly the pattern pdqsort used to defeat for free and blqsort does not.

Standalone benchmark of that exact path (indirect comparator over a 2M-element Int128 permutation, best-of-5):

case pdqsort (before) blqsort (this PR) pdqsort_try_sort + blqsort (fix)
reverse-sorted (DESC) 4.2 ms 74.8 ms 4.1 ms
random 185.5 ms 101.9 ms 102.9 ms

Fix (4b51db4): run pdqsort_try_sort (the same pre-pass behind trySort) inside ::sort's contiguous branch before falling back to blqsort. This restores exactly what pdqsort provided on every ::sort call — it makes the "trySort runs before ::sort" invariant true universally instead of relying on each caller — and costs only ~1% on unpatterned data, so the several-fold blqsort speedup is preserved. It also covers tiny-array callers like arraySort (the pre-pass insertion-sorts small ranges and returns). I left this as a single point inside ::sort rather than patching ColumnDecimal::getPermutation alone, because other non-radix callers reach ::sort directly too; happy to move it to the call site if you prefer.

Test (review thread)

Added src/Common/tests/gtest_sort.cpp (Sort.*) comparing ::sort/trySort against std::sort across the requested boundaries, patterns, a 16-byte wide type, and an indirect permutation comparator. All 4 tests pass locally.

CI

  • test_multiple_disks::test_jbod_overflow[mt|replicated] — known flaky, already fixed on master by 809c2be747a ("Fix flaky test test_multiple_disks::test_jbod_overflow"), now merged into this branch.
  • The bulk of the arm_release shard 1/6 "slower" entries (logical_functions_small, rand, order_by_single_column, array_sort) are a systematically slow shard run (2 faster / 12 slower clustered on one shard), not attributable changes. The genuine sort wins are confirmed: sort_string_full ~15% faster, sort_multi_column_mixed ~17%, sort_low_cardinality ~11%.

Comment thread src/Common/tests/gtest_sort.cpp Resolved
The new `gtest_sort.cpp` seeds `std::mt19937_64` with constant values for
reproducibility, which trips `cert-msc32-c,cert-msc51-cpp` in the `arm_tidy`
build. Suppress them with `NOLINT` as other deterministic test fixtures do.

Also add `Sort.MatchesStdSortStrings`, exercising `::sort` over `std::string`
across the same boundary sizes and patterns. `std::string` is not
trivially-copyable, so it takes the BlockQuicksort (`block_qsort`) path inside
`blqsort` — the path behind the user-visible claim of faster string `ORDER BY`,
which the previous tests (all trivially-copyable types) did not cover.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Pushed 9631585efdd:

  • Fixed the arm_tidy build failure — the only red. gtest_sort.cpp seeds std::mt19937_64 with constant values for reproducibility, which tripped cert-msc32-c,cert-msc51-cpp; suppressed with trailing // NOLINT as other deterministic test fixtures do.
  • Added Sort.MatchesStdSortStrings addressing the review thread — covers ::sort over std::string (the block_qsort complex-type path behind the string ORDER BY claim) across the same boundary sizes and patterns as the trivially-copyable cases.

Built unit_tests_dbms locally; all 5 Sort.* gtests pass. Did not re-merge master (merge-base 2026-06-08, <1 week; the sole red was this PR's own clang-tidy error, now fixed).

@alexey-milovidov

Copy link
Copy Markdown
Member Author

Merged master (up to 40f84e47315) to bring the branch current and refresh CI. The PR diff is unchanged — only the blqsort files.

The two failures on the previous run (9631585efdd) are both in the distributed-plan / stateless-worker subsystem and unrelated to the sort change:

  1. 03394_distributed_shuffle_join_early_close_sink (Stateless, distributed plan) — Distributed read: part all_1_1_0 selected by the coordinator is not available on this replica (diverged by merge or replication lag); retry the query (RECEIVED_ERROR_FROM_REMOTE_IO_SERVER). Recurring master-wide replica-divergence flake in DistributedQueryPlanExecutorRemote.
  2. Stress (arm_ubsan) — Logical error: Table A.B not found in catalog via QueryPlan::deserialize → DistributedPlanExecutor → StatelessTaskExecutor. Recurring master-wide stateless-worker flake.

@groeneai, could you investigate these two and provide a fix in a separate PR (or link an existing one)? They are not caused by this PR (it only changes ::sort in base/base/sort.h plus tests).

@groeneai

Copy link
Copy Markdown
Collaborator

Confirmed, and both are already handled. Neither is caused by blqsort (it only touches base/base/sort.h + tests, which cannot produce distributed catalog/replica errors).

Both are collateral from #106020 (multi-stage distributed queries, merged 06-09 16:06 UTC), which added DistributedPlanExecutor / StatelessTaskExecutor. That was reverted by #107122 (merged 06-11 01:37 UTC) and is already present in the 40f84e47315 master you just merged here. Re-land is in progress on davenger's #107146.

CIDB, master only:

  • 03394_distributed_shuffle_join_early_close_sink: 1 failure on 06-09, 1 on 06-10, 0 since the revert.
  • Logical error: '... not found in catalog' (QueryPlan::deserialize -> DistributedPlanExecutor -> StatelessTaskExecutor, all Stress variants incl. arm_ubsan): 8 on 06-09, 4 on 06-10, 0 on master or PR since the revert.

The old failing run 9631585efdd (06-10 01:32 UTC) sits inside that buggy window, before the revert. So no separate fix is needed from me; the fix is the revert already on your refreshed branch, and the refreshed CI should be clean of both.

@clickhouse-gh

clickhouse-gh Bot commented Jun 13, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.70% 84.70% +0.00%
Functions 92.30% 92.40% +0.10%
Branches 77.30% 77.30% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 118/118 (100.00%) | Lost baseline coverage: none · Uncovered code

Full report · Diff report

@alexey-milovidov

Copy link
Copy Markdown
Member Author

Closing in favor of #106650

@alexey-milovidov alexey-milovidov self-assigned this Jun 18, 2026
pull Bot pushed a commit to AnotherGenZ/ClickHouse that referenced this pull request Jun 18, 2026
…ting

Port the Rust standard library's current sort implementations to C++ and use
them in `base/base/sort.h`:

- ipnsort (by Lukas Bergdoll & Orson Peters) backs `::sort`, replacing
  `pdqsort`. It is pattern-defeating quicksort with a glidesort pivot, a
  sorting-network small-sort and a heapsort fallback, and detects already-sorted
  and reverse-sorted runs (handling them in O(n)). The port runs the full
  algorithm for trivially-copyable types and a move-based path otherwise. Its
  partition evaluates the comparator over a block in an ILP-friendly pre-pass
  before the serial rearrangement, which keeps throughput high for expensive
  (indirect / cache-missing) comparators - the dominant ClickHouse pattern.

- driftsort (by Orson Peters & Lukas Bergdoll) backs a new `::stableSort`,
  replacing `std::stable_sort` call sites. It is a powersort merge tree over
  detected runs with a stable scratch quicksort, several times faster than
  `std::stable_sort`. It allocates up to n/2 extra memory.

Both are vendored as header-only contribs (dual MIT / Apache-2.0), like
`contrib/pdqsort`. They need raw pointers, so contiguous iterators are converted
with `std::to_address`; non-contiguous iterators keep `pdqsort` /
`std::stable_sort`. `trySort`, `nth_element` and `partial_sort` are unchanged.

Validated against `std::sort` / `std::stable_sort` over thousands of randomized
cases under AddressSanitizer (sizes, duplicate densities, patterns, and
trivially-copyable, non-trivially-copyable and non-default-constructible element
types) with zero mismatches; driftsort verified stable.

Supersedes the blqsort approach in ClickHouse#106618: the CI performance comparison there
showed blqsort regressing `ORDER BY toDecimal128(...) DESC` ~4.9x (a
reverse-sorted worst case); ipnsort keeps the string-sort improvements without
that regression.

Related: ClickHouse#106618

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-performance Pull request with some performance improvements submodule changed At least one submodule changed in this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants