Repository navigation
Share the dynamic top-K threshold across the sorting streams of ORDER BY ... LIMIT - #124829
alexey-milovidov merged 8 commits into
Conversation
… BY ... LIMIT With N sorting streams, every PartialSortingTransform and MergeSortingTransform published the limit-th value of its own rows only, so the dynamic top-K threshold was about the (N * limit)-th value overall and got looser with more threads. Once __topKFilter filters rows, blocks rarely reach limit rows, and only the per-stream remerges tightened it. A TopKThresholdCollector, one per sort and shared by the PartialSortingTransforms of all streams, keeps the limit best first-sort-column values seen across the streams and publishes the limit-th one through the existing tracker. Candidates are appended and re-sorted with the column's own getPermutation once limit values are known, and then every limit / 2 more. Every row passes exactly one partial sort, so a published value is still backed by limit rows of the input. Float keys are excluded, because __topKFilter drops nan rows. So are sorts whose input carries LowCardinality, Dynamic or JSON columns: buffered chunks keep their source block's dictionaries, and with a tighter threshold the sort buffers many more small chunks before it remerges (2.8x peak memory with a high-cardinality LowCardinality(String) key at 16 threads). PartialSortingTransform also drops ChunkInfoRowNumbers, which no longer describes the rows after sorting. Without that, the extra buffered chunks kept their row numbers (1.12x peak memory at LIMIT 1000 with 4 threads). Analysis and the original patch: ClickHouse#124564 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Internal second-model review: adjudication log (click to expand)Pre-publication review by an independent model (engine: codex; 5 findings over 3 rounds) plus my own cold reviews (nits).
Severity: ❌ blocker / Session id: cron:clickhouse-review-slot-9:20261009-044200 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-6:20261009-030600 |
|
Workflow [PR], commit [f805574] Summary: ✅
AI ReviewSummaryThis PR shares a bounded Missing context / blind spots
Final VerdictStatus: ✅ Approve. No new inline findings. |
|
📊 Cloud Performance Report ✅ AI verdict: no significant changes detected. K_source=6 K_base=30 flagged=0/65 clickbench🟢 No significant changes tpch_adapted_1_official🟢 No significant changes Debug info
|
CI finish ledger - d01463dEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
All check runs completed. The other three Session id: cron:our-pr-ci-monitor:20261009-073003 |
| if (rows == 0) | ||
| return; | ||
|
|
||
| std::lock_guard lock(mutex); |
There was a problem hiding this comment.
I'm curious how the performance is affected by many threads contending for this lock, especially given the non-trivial amount of compute that's taken under it.
There was a problem hiding this comment.
Good question, it was worth measuring. I added temporary counters for the time threads spend waiting for and holding this mutex, summed over all threads (release build, 100M-row MergeTree tables with random and descending UInt64 keys, paired runs against master):
- With the default
query_plan_max_limit_for_top_k_optimization = 1000, wall time stayed within noise at 16 to 256 threads, but the re-sort under the mutex made the other threads wait 10-26 ms per query at 128-256 threads (about 1 ms held). - With the cap set to 0 the cost grows with
LIMIT, and the streams serialize on the mutex:LIMIT 10000on random keys was 1.59x slower than master at 64 threads,LIMIT 100000on descending keys 1.77x.
Fixed in 1e55279: one thread at a time sorts a copy taken out of the collector outside the mutex (and then merges what the others added meanwhile), and the collector is built only for LIMIT + OFFSET up to 1000. Now the summed wait is about 1 ms or less at 256 threads, every case I measured is 0.89-1.04x of master (cap-0 limits above 1000 run exactly as on master), and LIMIT 10 over the perf-test Parquet file stays at about 0.5x. I updated the PR description accordingly.
…ld it only up to LIMIT 1000 A review question on ClickHouse#124829 asked about lock contention. Measured with a temporary instrumented release build, 100M-row MergeTree tables, paired runs vs the merge base: - With the default `query_plan_max_limit_for_top_k_optimization = 1000`, the re-sort of 1.5 * limit values under the mutex made the other streams wait 10-26 ms in total per query at 128-256 threads. One thread now sorts a taken-out copy outside the mutex and also merges what the other threads added meanwhile; the wait is under 1 ms. - With the cap set to 0, the values copied per block grow with LIMIT and the streams serialize on the mutex: LIMIT 10000 on random keys was 1.59x slower at 64 threads, LIMIT 100000 on descending keys 1.77x. Above LIMIT 1000 the collector is not built, so these queries behave as on master. LIMIT 10 over the perf-test Parquet file keeps its gain (0.51x at 16 threads, 0.50x at 64). Co-Authored-By: Claude Opus 5.5 <[email protected]>
The stateless-test profile (tests/config/users.d/limits.yaml) sets max_rows_to_read = 20000000. With a throwing row limit, ReadFromMergeTree::supportsSkipIndexesOnDataRead() returns false, so the dynamic top-K threshold never skips marks and both engagement oracles of 05339 read every row (`read_rows < N` = 0) in every CI job, with and without randomized settings. Local runs without that profile passed. 04812 and 05046 pin the same settings for the same reason. Measured with a rig that has the CI profile (limits.yaml): the unpinned test fails on the CI merge commit build, the pinned one passes 1/1 deterministic and 64/64 randomized (-j 8) on that build and on the PR head build, and on master without the collector both engagement lines stay red. Co-Authored-By: Claude Opus 5.5 <[email protected]>
I didn't mean to imply that we needed significant engineering to work around the slowdown. This feature seems useful, maybe even especially for higher limits where no individual thread will accumulate that large a limit to get its own threshold for reads. |
|
Thanks, agreed that higher limits are where sharing could matter most, so I measured the current code with the cap lifted (release build, paired runs against master,
The single sorter is the limit: at So I kept the cap at 1000 here. It is also the default of |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units13 translation units recompiled, 78 s compile time in total, 13 of them have a recent master baseline. Median compile-time ratio to the baselines is ×1.09 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio. |
CI finish ledger - 05d1a20Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20261010-003008 |
Both read_rows probes now take the newest QueryFinish row of their log_comment, so rerunning the test in the same database (for example clickhouse-test --database <db>) still prints one line per probe. Before, the second run in one database printed an extra `1` for each probe. clickhouse-test's default runs were not affected because every run gets a fresh database. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Fixing PR for 03100_lwu_30_join_cache created: #125032 |
|
On ClickBench's partitioned Parquet files at 4 threads, this PR makes Q25 and Q27 about 11% faster, and 17-25% faster when the files are read best-first as in #124959 (base: current master plus the other open Parquet PRs, setup below). Merging the collector on the first better value, instead of after This PR (median time; geomean ratio [95% CI] over 10 paired runs):
Q25 is Suggestion: merge on the first better value. With --- a/src/Processors/Transforms/PartialSortingTransform.cpp
+++ b/src/Processors/Transforms/PartialSortingTransform.cpp
@@ -151,7 +151,7 @@ void TopKThresholdCollector::add(const IColumn & sorted, size_t rows)
values = sorted.cloneEmpty();
values->insertRangeFrom(sorted, 0, rows);
- if (merging || values->size() < limit + (boundary ? limit / 2 : 0))
+ if (merging || values->size() < limit + (boundary ? 1 : 0))
return;
to_merge = std::move(values);
@@ -182,7 +182,7 @@ void TopKThresholdCollector::add(const IColumn & sorted, size_t rows)
boundary = best->cut(limit - 1, 1);
/// Other threads did not merge what they added meanwhile because `merging` was set.
- if (added_meanwhile && values->size() >= limit + limit / 2)
+ if (added_meanwhile && values->size() >= limit + 1)
{
to_merge = std::move(values);
values = to_merge->cloneEmpty();
Q25 reads 41-43 row groups instead of 47-51. Q27 in the original order, Q24 and Q3 do not change significantly. Other top-K sorts, including dense ones, are unchanged or faster (8 runs): Limitation: 4 vCPUs cannot show contention at 64-256 threads, which is where merging more often could cost. If it does, merging eagerly only for small limits would keep this gain. Setup
The PR now conflicts with master only in |
…red-by-streams Resolve the conflict in PartialSortingTransform.h: keep master's public `min_limit_for_partial_sort_optimization` (ClickHouse#124827) and the `threshold_collector` member. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The collector re-sorted its values only after `limit / 2` values better than the published threshold had arrived. With `LIMIT 10` such values get rare as the threshold approaches its final value, so the tighter threshold reached the readers several row groups late. Merge as soon as one better value arrives; the sort stays outside the mutex and only one thread merges at a time. Suggested by @ snelheidai on ClickHouse#124829. Measured on ClickBench `hits` as 100 Parquet files, release build, eager / previous, 8-16 paired rounds: Q25 and Q27 at 4 threads 0.94-0.96; 16 to 256 threads (Parquet and MergeTree, integer and String keys, LIMIT 10 to 1000) 0.97 to 1.02, no contention cost; `ORDER BY WatchID LIMIT 100` at 4 threads 0.88. The worst case found is a descending input with a few surviving rows per granule at `LIMIT 1000`: about 1.02 at 1 and 4 threads, 1.00 at 16 and 64. Co-Authored-By: Claude Opus 5.5 <[email protected]>
CI finish ledger - 1720b8cEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
CIDB has no other Session id: cron:our-pr-ci-monitor:20261101-210002 |
alexey-milovidov
left a comment
There was a problem hiding this comment.
@groeneai, update the branch.
|
Updated: merged master ( |
…x-limit-threshold Resolve conflicts with ClickHouse#124829: the PartialSortingTransform constructor now takes threshold_collector_ before sorted_prefix_size_, and finishSorting passes both. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The test timed out in `Stateless tests (arm_binary, ParallelReplicas, s3 storage, sequential)` on PR ClickHouse#124829: the client waited 300 s for `OPTIMIZE ... FINAL`. The MergeTree randomizer drew `index_granularity = 20` with `min_bytes_for_wide_part = 1 GiB`, so the patch parts written by the UPDATE were Compact parts with 150,000 granules on S3. Applying them in the merge reads a compact patch part with two S3 GETs per granule: 300,038 GETs and a 558 s merge on CI, against 54 GETs and 1 s without randomization. Release builds get no granularity floor from the runner (it covers only slow builds and `long` tests), and this test is tagged off every slow build. Clamp both granularity settings with a per-test limits line. The row floor is 1000 rather than the usual 100 because at 100 the same draw still makes 60,000 GETs, about 110 s on CI. Granularity stays randomized above the bounds; the test checks patch application, which does not depend on it. Validated on the amd_binary build of ClickHouse#124829 against local MinIO: the CI draw replayed fails with return code 159 and 300,038 GETs; at the floor it makes 6,038 GETs and passes in 7-8 s (patch_parts_version v1 and v2); a runner patched to draw granularity 20..60 gets exactly 1000 / 100000 in every CREATE, and the raw draws come through when the line is corrupted; 50/50 randomized runs on S3 and on local disk. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Closes: #124564
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
ORDER BY ... LIMIT nwith the dynamic top-K filter on an integer, date/time, decimal or string column andnplusOFFSETup to 1000 now keeps one threshold for all sorting streams instead of one per stream, so the threshold no longer gets looser with more threads, and more Parquet row groups and MergeTree granules are skipped.SELECT WatchID, URL FROM hits ORDER BY WatchID LIMIT 10over ClickBenchhits.parquetwithmax_threads = 16skips 200 of its row groups instead of about 100 and runs about 2x faster.Description
Analysis and original patch by @ snelheidai in #124564.
Each sorting stream published the
limit-th value of its own rows toTopKThresholdTracker, so with N streams the threshold was about the (N * limit)-th value overall. Once__topKFilterfilters rows, blocks rarely reachlimitrows, and only the per-stream remerges tightened it.A
TopKThresholdCollector, one per sort and shared by thePartialSortingTransforms of all streams, keeps thelimitbest first-sort-column values across the streams and publishes thelimit-th one through the existing tracker. Every row passes exactly one partial sort, so a published value is still backed bylimitrows. One thread at a time re-sorts the collected values outside the collector's mutex.PartialSortingTransformalso dropsChunkInfoRowNumbers, which no longer match the sorted rows.The collector is used for
LIMIT+OFFSETup to 1000 (the defaultquery_plan_max_limit_for_top_k_optimization) and for integer, date/time, decimal, enum,IPv4andString/FixedStringfirst sort keys andNullableof them. Everything else keeps the per-stream threshold: larger limits (the streams contend for the mutex:LIMIT 10000with the cap set to 0 was 1.6x slower at 64 threads),Float*(__topKFilterdropsnanrows),UUID,IPv6,Tuple,Array,Map, and sorts that carryLowCardinality,DynamicorJSONcolumns.Measured with
clickhouse local, release build, geomean time fix/base [95% CI]:hits.parquet,ORDER BY WatchID LIMIT 10, 16 threads: 0.48 [0.45, 0.52]; the perf-test Parquet file,LIMIT 10, 64 threads: 0.50 [0.44, 0.56].LIMIT10 to 1000, 16 to 256 threads: 0.90 to 1.04; cap set to 0,LIMIT2000 to 100000: 0.95 to 1.02.The new test checks that the threshold collected across blocks and across 8 streams skips marks (both fail on master) and pins results for ties,
OFFSET,DESC,Nullable, collation andnan.🤖 Generated with Claude Code
Workflow [PR]
Sync PR [sync-upstream/pr/124829]
Version info
26.11.1.1091-master(included in26.11and later)