Repository navigation
Use branchless quicksort (blqsort) for the general-purpose sort - #106618
alexey-milovidov wants to merge 13 commits into
Conversation
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]>
|
Workflow [PR], commit [ffe33c5] Summary: ✅
AI ReviewSummaryThis PR replaces the central Final VerdictStatus: ✅ Approve |
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]>
|
📊 Cloud Performance Report 🔴 AI verdict: 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)
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)
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
|
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]>
|
This included the library directly - not as a submodule. Direct source inclusion of small libraries is good. |
… 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]>
`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]>
|
Continued this PR: merged Performance regression fixed (
|
| 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 onmasterby809c2be747a("Fix flaky test test_multiple_disks::test_jbod_overflow"), now merged into this branch.- The bulk of the
arm_releaseshard 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%.
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]>
|
Pushed
Built |
|
Merged The two failures on the previous run (
@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 |
|
Confirmed, and both are already handled. Neither is caused by blqsort (it only touches Both are collateral from #106020 (multi-stage distributed queries, merged 06-09 16:06 UTC), which added CIDB, master only:
The old failing run |
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered by tests: 118/118 (100.00%) | Lost baseline coverage: none · Uncovered code |
|
Closing in favor of #106650 |
…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]>

Replace
pdqsortwith branchless quicksort (blqsort, https://github.com/chkas/blqsort) as the general-purpose comparison sort behind::sortinbase/base/sort.h.blqsortuses 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 atO(n log n). On unpatterned, high-cardinality data — the common case that reaches::sort— it is much faster thanpdqsortbecause it avoids branch mispredictions in the partitioning loop.pdqsortis 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_elementandpartial_sortcontinue to useminiselect. BecausetrySortruns before::sortand still usespdqsort, the patterned inputs on whichblqsortis weaker are filtered out before they reach it.blqsortoperates on raw pointers, so the (always contiguous) iterators are converted withstd::to_address.Measurements
Algorithm microbenchmark (aarch64, clang 21, 10M elements, best-of):
UInt64: 3.2x faster; randomFloat64: 3.9x faster; few-unique: ~2x faster.data[a] < data[b], the dominant pattern): 1.55x faster.Real
ORDER BYqueries (20M rows, single thread, best-of-5, end-to-end):Stringhigh-cardinalityORDER BY s: 6.99 s -> 5.92 s (~18% faster).Stringlow-cardinalityORDER BY s: 3.04 s -> 2.54 s (~20% faster).Float64 ORDER BY x(control, usesRadixSort, 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::sortelement-wise with zero failures. In the built server,ORDER BYoutput is provably sorted and byte-identical to thepdqsortoutput.Note on the vendored library
blqsort's branchless partitioning allocated its scratch buffers asT buf[N], which requiresTto 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 aClickHouse modificationcomment incontrib/blqsort/blqs.h. The header is vendored the same way ascontrib/pdqsort.Changelog category (leave one):
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 upORDER BYon non-numeric columns (e.g. strings) by roughly 20% and high-cardinality comparison sorts by several times.Documentation entry for user-facing changes
🤖 Generated with Claude Code