Skip to content

Share the dynamic top-K threshold across the sorting streams of ORDER BY ... LIMIT - #124829

Merged
alexey-milovidov merged 8 commits into
ClickHouse:masterfrom
groeneai:top-k-threshold-shared-by-streams
Nov 2, 2026
Merged

alexey-milovidov merged 8 commits into
ClickHouse:masterfrom
groeneai:top-k-threshold-shared-by-streams

Conversation

@groeneai

@groeneai groeneai commented Oct 9, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #124564

Changelog category (leave one):

  • Performance Improvement

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

ORDER BY ... LIMIT n with the dynamic top-K filter on an integer, date/time, decimal or string column and n plus OFFSET up 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 10 over ClickBench hits.parquet with max_threads = 16 skips 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 to TopKThresholdTracker, so with N streams the threshold was about the (N * limit)-th value overall. 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 across the streams and publishes the limit-th one through the existing tracker. Every row passes exactly one partial sort, so a published value is still backed by limit rows. One thread at a time re-sorts the collected values outside the collector's mutex. PartialSortingTransform also drops ChunkInfoRowNumbers, which no longer match the sorted rows.

The collector is used for LIMIT + OFFSET up to 1000 (the default query_plan_max_limit_for_top_k_optimization) and for integer, date/time, decimal, enum, IPv4 and String/FixedString first sort keys and Nullable of them. Everything else keeps the per-stream threshold: larger limits (the streams contend for the mutex: LIMIT 10000 with the cap set to 0 was 1.6x slower at 64 threads), Float* (__topKFilter drops nan rows), UUID, IPv6, Tuple, Array, Map, and sorts that carry LowCardinality, Dynamic or JSON columns.

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].
  • MergeTree, LIMIT 10 to 1000, 16 to 256 threads: 0.90 to 1.04; cap set to 0, LIMIT 2000 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 and nan.

🤖 Generated with Claude Code


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

Version info

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

… 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]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-issue PR origin: picked up an external GitHub issue labels Oct 9, 2026
@groeneai

groeneai commented Oct 9, 2026

Copy link
Copy Markdown
Collaborator Author
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).

# Sev Finding Verdict Evidence / action
1 ⚠️ The only read-rows check in 05339 ran one stream, so a collector built per stream kept the test green AGREE, fixed added an 8-part / 8-stream case where no stream holds LIMIT rows
2 ⚠️ The changelog claimed every ORDER BY ... LIMIT n, but the collector covers number and string keys only AGREE, fixed in the PR description the entry and the description name the key types that use it
3 ⚠️ A read task stolen from another stream lets a per-stream collector skip marks in the 8-stream case (MergeTreeReadPool.cpp:141-163) AGREE, fixed every large key is equal, so a per-stream threshold skips nothing unless one stream holds 4 of the 8 parts
4 ⚠️ No engagement check for Nullable and String keys DISAGREE falling back there changes no result; MergeTree has no row-skip observable for these keys (optimizeTopK.cpp:273-275), and the literal-result cases run with the collector engaged
5 ⚠️ A stream can still steal 4 parts and pass the 8-stream check with a per-stream collector DISAGREE (residual) if one stream reads every part, a per-stream collector sees the same rows as the shared one, so no read-rows check tells them apart on every schedule; that would need a test-only read-pool setting, which I can add if wanted. Measured: the per-stream mutation stayed red in 74/74 runs (64 under -j 8) and skipped marks only when forced to 4 parts per stream
6 💡 LIMIT 1000 with 4 threads on Parquet: wall 1.065 [1.010, 1.121], CPU 0.99 AGREE, noted disclosed in the description; 16 threads 0.96
7 💡 The new perf XML fills the same data as parquet_top_k_row_group_order.xml AGREE, noted kept separate for the 16-thread queries, where the gain is
8 💡 The LowCardinality/Dynamic/JSON check covers the whole sort header, not only the key AGREE, noted disclosed; with it, peak memory on those sorts stays at master's (0.88-0.99)

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

Session id: cron:clickhouse-review-slot-9:20261009-044200

@groeneai

groeneai commented Oct 9, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. On master, SELECT WatchID, URL FROM hits ORDER BY WatchID LIMIT 10 over hits.parquet skips 205 row groups at 1 thread, 157-173 at 4 and 83-112 at 16. The new test's two mark-skipping checks (one stream, and 8 streams of 60 rows each) return 0 on master on every run.
b Root cause explained? Only per-stream publishers feed TopKThresholdTracker (PartialSortingTransform per block, MergeSortingTransform per remerge), so with N streams the threshold is about the (N * limit)-th value.
c Fix matches root cause? Yes. One collector per sort combines the streams' values where they are sorted; consumers and bounds are unchanged.
d Test intent preserved / new tests added? New 05339_top_k_threshold_shared_by_streams.sql and parquet_top_k_threshold_streams.xml.
e Both directions demonstrated? Mark-skipping checks 0 on master, 1 with the fix (8 streams: 480 -> at most 240 rows read); row groups skipped at 16 threads 83-112 -> 200-202. Mutations (off-by-one publication, no collector, floats accepted, one collector per stream) each turn a test case red. 100/100 randomized and 64 parallel (-j 8) runs pass.
f Fix is general across code paths? Both sort paths that build a tracker (finishSorting, fullSortStreams) get the collector; per-stream publications and every consumer (__topKFilter, Parquet row groups, MergeTree marks) are unchanged.
g Fix generalizes across inputs (params/datatypes/wrappers)? Tested: Nullable with NULLS FIRST/LAST and a NULL threshold, collation, DESC, OFFSET, ties, two sort columns. Floats and sorts carrying LowCardinality/Dynamic/JSON columns keep master's behaviour (memory measured for top-level and Array LowCardinality).
h Backward compatible? (maintainer-approved exception only) Yes. No setting or format change; results identical to use_top_k_dynamic_filtering = 0 on 34 real-data queries.
i Invariants and contracts preserved? A published value is still backed by at least limit input rows, because every row passes exactly one partial sort. The collector state is guarded by one mutex.

Session id: cron:clickhouse-impl-slot-6:20261009-030600

@clickhouse-gh

clickhouse-gh Bot commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f805574]

Summary: ✅


AI Review

Summary

This PR shares a bounded TopKThresholdCollector across sorting streams so eligible ORDER BY ... LIMIT queries publish tighter thresholds and skip more input. No actionable findings remain. The earlier system.query_log retry finding is fixed. The regression test and reported before/after measurements support the correctness and performance claims.

Missing context / blind spots
  • ⚠️ The latest CI run for f8055746eb84b5f00bc900e86010135e9f214fdb is still running. The focused 05339_top_k_threshold_shared_by_streams test passed in the preceding 1720b8cf87025f9f91952e7037bf39081113cbcc run; completion of the current functional and sanitizer jobs will confirm coverage after the master merge. No local build or tests were run.
Final Verdict

Status: ✅ Approve. No new inline findings.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Oct 9, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. label Oct 9, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

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
  • StressHouse run: 415f91d2-c68a-4961-b939-11899b30d49d
  • MIRAI run: 6034b1c6-200a-4d63-bd5d-68232a9aada4
  • PR check IDs:
    • clickbench_668726_1791608093
    • clickbench_668732_1791608093
    • clickbench_668945_1791608111
    • tpch_adapted_1_official_669014_1791608114
    • tpch_adapted_1_official_669138_1791608122
    • tpch_adapted_1_official_669278_1791608219

@groeneai

groeneai commented Oct 9, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - d01463d

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Build (arm_tidy, 2/4) / Build ClickHouse master-side build break, not from this PR (which changes SortingStep and PartialSortingTransform): src/Common/Scheduler/Nodes/tests/gtest_throttler_constraint.cpp:25:11: error: use of undeclared identifier 'FifoQueue', the only error in the shard, in a file this PR does not touch. 21 true-master commits and 85 PRs fail this shard since 2026-10-09 00:30Z #124798 (external, open)
Mergeable Check, PR praktika rollups of the row above (Failed: Build (arm_tidy, 2/4), Dropped: 105), no independent failure #124798 (external, open)
CH Inc sync - CH Inc sync (private, not actionable by me)

All check runs completed. The other three arm_tidy shards passed. 105 jobs were dropped behind the shard 2/4 failure, so the functional test matrix has not run on this head yet.

Session id: cron:our-pr-ci-monitor:20261009-073003

if (rows == 0)
return;

std::lock_guard lock(mutex);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 10000 on random keys was 1.59x slower than master at 64 threads, LIMIT 100000 on 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.

groeneai and others added 2 commits October 9, 2026 14:22
…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]>
@EmeraldShift

Copy link
Copy Markdown
Contributor

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.

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.

@groeneai

groeneai commented Oct 9, 2026

Copy link
Copy Markdown
Collaborator Author

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, query_plan_max_limit_for_top_k_optimization = 0, 100M-row MergeTree tables):

  • It wins at 16 threads: LIMIT 100000 is 0.53x on ClickBench hits ordered by WatchID and 0.55x on random UInt64 keys.
  • It loses at 64-256 threads: LIMIT 100000 is 1.37x over the perf-test Parquet file and 2.2-2.5x on descending keys, and LIMIT 10000 is about 1.1x on random keys and on hits.

The single sorter is the limit: at LIMIT 100000 the streams push 4-12 million values per query into the collector, one thread at a time spends 45-69 ms in total re-sorting them, and at 64 threads the others wait 0.8-1.3 s summed on the mutex. Master finishes the same queries in 44-100 ms at 64 threads. At LIMIT 1000 (random keys, 64 threads) it is about 14 thousand values and 0.5 ms.

So I kept the cap at 1000 here. It is also the default of query_plan_max_limit_for_top_k_optimization, so unless that setting is raised, no query with LIMIT + OFFSET above 1000 gets a dynamic threshold at all. Higher limits need a collector that does not funnel every stream's values through one sorter, which I left out of this PR.

@clickhouse-gh

clickhouse-gh Bot commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing f8055746e with master ba0d3f020 (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

13 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.
The matched translation units cost +6.8 s (+10%) in total before that adjustment.

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 05d1a20

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests, 7 sequential jobs (amd_debug; amd_debug, distributed plan; arm_binary; arm_binary, AsyncInsert; arm_binary, ParallelReplicas; arm_binary, DBReplicated; arm_asan_ubsan, azure) / 05243_query_condition_cache_top_k_parquet not from this PR: a master regression from my #123903 (merged 17:15Z), after which a TopK read of a File(Parquet) table filtered only on _file stopped using the query condition cache (0 0 instead of 1 0 / 1 1); master was red until the revert #124977 (external, merged 19:25Z, reverts #123903; #124991 re-lands it with a fix). This run was dispatched at 17:50Z, before the revert, so I will merge master here to pick it up
Stateless tests (arm_binary, s3 storage, DBReplicated, parallel, 1/2) / 05316_secret_arguments_declared_by_engines not from this PR: the test came with #123364, and under DatabaseReplicated its last query_log check counts the CREATE DICTIONARY row twice (0 2 instead of 0 1; the password stays hidden) #124928 (external, merged 17:58Z). This run was dispatched at 17:50Z, before that merge, so the same master merge picks it up
Stateless tests (arm_binary, ParallelReplicas, s3 storage, sequential) / 03100_lwu_30_join_cache flaky, not from this PR (its top-K collector is built only for ORDER BY ... LIMIT reads, never for a merge): OPTIMIZE TABLE ... FINAL hit the 300 s client timeout under one randomized MergeTree-settings draw (index_granularity 20, min_merge_bytes_to_use_direct_io 1, ...). The rerun with the same settings timed out again; 28 of 28 runs without randomization passed a fix task is moved to pending (investigating at full effort, fixing-PR link to follow here)
Mergeable Check, PR praktika rollups of the rows above (Failed: 7; the azure job is allow_failure and does not gate) #124977, #124928 (external, merged), and the fix task above

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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for 03100_lwu_30_join_cache created: #125032

@snelheidai

Copy link
Copy Markdown

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 limit / 2 of them, makes Q25 another 9-12% faster.

This PR (median time; geomean ratio [95% CI] over 10 paired runs):

Query, file order Base PR PR / base
Q25, original 126.5 ms 112 ms 0.888 [0.852, 0.926]
Q27, original 127 ms 116 ms 0.889 [0.848, 0.933]
Q25, best-first 115 ms 89 ms 0.749 [0.687, 0.817]
Q27, best-first 114 ms 95 ms 0.829 [0.801, 0.857]

Q25 is SELECT SearchPhrase FROM hits WHERE SearchPhrase <> '' ORDER BY EventTime LIMIT 10; Q27 orders by EventTime, SearchPhrase. Together with #124959 they go from 126.5 to 89 ms and from 127 to 95 ms. Q25 reads 43-51 row groups instead of 53-55, and in best-first order 31-32 instead of 42-43, as many as the base reads with one thread. Q24 and Q26 do not change significantly in either order, and eight control queries (Q1, Q3, Q8, Q13, Q15, Q16, Q18, Q34) show no significant slowdown (6 runs).

Suggestion: merge on the first better value. With LIMIT 10 the collector publishes a tighter threshold only after 5 values better than the current one have arrived. In Q25 such values become rare as the threshold approaches its final value, so the tighter threshold comes several row groups late. This change on the PR head merges as soon as one arrives; the sort stays outside the mutex, with one merging thread at a time:

--- 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();
Query, file order PR PR + change Ratio
Q25, original 112 ms 97 ms 0.879 [0.845, 0.915]
Q25, best-first 89.5 ms 80 ms 0.909 [0.880, 0.938]
Q27, best-first 95 ms 89 ms 0.947 [0.914, 0.980]

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): ORDER BY WatchID LIMIT 1000 1.008, ORDER BY WatchID DESC LIMIT 10 0.982, ORDER BY Title LIMIT 1000 1.014 and Q25 with LIMIT 1000 1.004 are not significant; ORDER BY ClientIP LIMIT 1000 is 0.984 [0.975, 0.992], Q25 with max_threads = 16 0.948 [0.910, 0.989], and WHERE URL LIKE '%google%' ORDER BY EventTime DESC LIMIT 100 0.950 [0.920, 0.980].

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 PartialSortingTransform.h: #124827 moved min_limit_for_partial_sort_optimization to the public section. Keeping that and adding the threshold_collector member resolves it.

…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]>
@groeneai

groeneai commented Nov 1, 2026

Copy link
Copy Markdown
Collaborator Author

Adopted in 1720b8c, with the PartialSortingTransform.h conflict resolved in 7bbb71f; on a 384-core box it measured 0.94-0.96 for Q25/Q27 at 4 threads and 0.97-1.02 at 16 to 256 threads, so it applies to every limit up to 1000.

@groeneai

groeneai commented Nov 1, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 1720b8c

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (amd_debug, parallel) / 05474_parquet_corpus_writers broken on master, not from this PR: the polars 0.20 rows of the reference are stale, the same diff fails on master since 2026-11-01 and on 26 other PRs; the tree that ran (merge ref 0e54b39) predates the fix #128494 (ours, merged)
Stateless tests (arm_binary, parallel) / 05474_parquet_corpus_writers same as the row above #128494 (ours, merged)
Mergeable Check, PR praktika rollups of the rows above #128494 (ours, merged)

CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261101-210002

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

@groeneai, update the branch.

@alexey-milovidov alexey-milovidov self-assigned this Nov 1, 2026
@groeneai

groeneai commented Nov 1, 2026

Copy link
Copy Markdown
Collaborator Author

Updated: merged master (ba0d3f0) into the branch, new head f805574. The PR diff is unchanged, and the new head includes #128494, the fix for 05474_parquet_corpus_writers, the only failure in the previous run.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Nov 2, 2026
Merged via the queue into ClickHouse:master with commit 8a2805f Nov 2, 2026
179 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 2, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 3, 2026
…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]>
lilredbot pushed a commit to JTCunning/ClickHouse that referenced this pull request Nov 4, 2026
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]>
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-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. groeneai-origin-issue PR origin: picked up an external GitHub issue pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

5 participants