Repository navigation
Stop read-in-order buffering from reading far past the LIMIT - #129198
Conversation
With a WHERE, ORDER BY <key> LIMIT n cannot push the limit into reading, so SortingStep::mergingSorted puts a BufferChunksTransform in front of every input of the read-in-order merge. Each buffer reads ahead until it alone has pulled n rows. When the WHERE fixes a key prefix (ClickHouse#66578: project = 'test' AND service = 'test', ORDER BY time) virtual rows are disabled, every input starts with real data, and the merge initializes only after the slowest input's first chunk, so every input reads to its own limit: inputs * n / selectivity rows. The buffers of one merge with a limit now share a ReadInOrderReadAheadTracker. Each publishes its first real row (a 1-row cut of the sort columns) and the number of rows it has pulled. An input the merge has taken at most one chunk from pauses read-ahead while its output port cannot take data, once the rows produced by the inputs whose first row sorts strictly before its own, plus its own rows, cover n. Read-in-order inputs normally do not overlap, so those rows all sort before its next row and the merge reaches the limit first. Inputs whose first row is not known yet are left out, which only underestimates. The rule only pauses: the demand path is unchanged, and after the merge's second pull the input is exempt, so results stay the same for overlapping inputs. The order comes from the inputs themselves because the merge initializes too late for the fixed-prefix case. No tracker without a limit, with always_read_till_end, or with a collation. Measured on the issue's 60M-row table (release, medians): LIMIT 100 reads 4.76M -> 1.07M rows at max_threads = 32 and 1.45M -> 0.72M at 8, and is slightly faster; LIMIT 10000 and no LIMIT keep their time (buffering's parallel read-ahead is what makes LIMIT 10000 3-7x faster than without it), also with the preliminary merge, virtual rows and overlapping parts. Closes ClickHouse#66578 Co-Authored-By: Claude Opus 5.5 <[email protected]>
The session `max_block_size = 128` that T1-T4 need also applied to the verification query, which scans `system.query_log` and `system.processors_profile_log` in full. Reset it to the default for that query and set it back to 128 for T3 and T4. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Drop the restatement of the pause condition above BufferChunksTransform::prepare's read-ahead pause; keep the liveness invariant. 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; 2 findings in round 1, 0 in round 2) plus my own review (4 findings over two rounds).
Severity: ❌ blocker / Session id: cron:clickhouse-review-slot-9:20261104-072100 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-6:20261104-045000 |
|
cc @CurtizJ @vdimir, could you review this and add the |
|
Workflow [PR], commit [a59f349] Summary: ❌
AI ReviewSummaryPR #129198, reviewed at Missing context / blind spots
Final VerdictStatus: ✅ Approve. |
Build profile diff (arm_release)Comparing commit See the job log for details. |
T1 and T2 expected exactly one input of the merge to read up to the LIMIT, which holds only when the dense part delivers its first rows before any sparse part reads 50 chunks. When the query got few CPU slots, or its threads were preempted, a sparse part sometimes reached its own LIMIT first, so the flaky check failed with (8,0,2) on T2. Run T1 and T2 on one thread. The single thread starts with the input of the last inserted part, so insert the dense part of `tab_asc` last, as `tab_desc` already does. With 8 parallel sessions on a server pinned to 2 CPUs the old test failed 34 of 80 runs and the new one passed 80 of 80. The base binary still fails both lines. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Each buffer kept one flag per input of the merge plus the list of inputs that sort before it, and rescanned all flags on every call, so the state and the work grew with the square of the number of inputs. A `Merge` table keeps every stream of every child for an ordered read: over 100 tables of 100 parts (10,000 inputs) peak memory went from 560 MB to 1215 MB and user CPU from 4.2 s to 6.6 s at `max_threads = 1`. Now the tracker keeps a shared log of the first 128 inputs that publish a first row, and each buffer compares itself only with them through a cursor into that log. The rule stays exact for merges with up to 128 inputs. With 10,000 inputs: 574 MB, 4.1 s user CPU at `LIMIT 10`; at `LIMIT 100000`, where nothing pauses, 216 MB vs 202 MB on master. At `LIMIT 1000` the paused inputs keep their readers open, as every input already does at `LIMIT 10`, so peak memory is 571 MB vs 284 MB on master. The new T5 in 05497 reads 200 one-granule parts through one merge; without the bound on the log, `setFirstRow` writes past the array there. Co-Authored-By: Claude Opus 5.5 <[email protected]>
A paused input keeps its reader open, while without the pause an input that exhausts its part in the first reads releases it. A `Merge` table keeps every stream of every child for an ordered read, so over 10,000 one-chunk parts at `LIMIT 1000` peak memory was 571 MB vs 284 MB on master (1,000 parts: 55 MB vs 29 MB). `SortingStep` now creates the tracker only for merges with at most 128 inputs, so larger merges read exactly as before: 285 MB at `LIMIT 1000`, 561 MB at `LIMIT 10` (master 560 MB), 1,000 parts 29 MB. A table read directly with 100 such parts uses 3.4 MB vs 3.3 MB on master. The query from ClickHouse#66578 has 13-35 inputs and keeps its reduction (4.76M -> 1.0-1.3M rows at `max_threads = 32`). T5 in 05497 now reads 200 parts through one merge and checks that each input reads to its own LIMIT; with the tracker 198 of them pause after their first chunk. The preliminary-merge arms of T3 run on two threads (two preliminary merges of four parts) and T3 checks that the pipeline has them. The first row an input publishes no longer references the `LowCardinality` dictionary of its chunk: the row is converted to a full column, so the tracker keeps one row per input and not a dictionary. Through preliminary merges the pause adds no memory: a table with 10,000 parts read by 8 merged streams peaks at 208 MB at `LIMIT 1000` with and without it, because each preliminary merge opens all its parts to start. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The flaky check runs 8 copies of the test at once with the thread fuzzer, and `Stateless tests (amd_debug|amd_binary, flaky check)` went over the 180 s limit (193-244 s per run) since the T5 case was added. Its own query_log shows where the time went: the 200-partition INSERT of tab_many wrote 200 parts at about 0.57 s each (122 s per run), and the T5 SELECTs another 43 s. T5 now gets its 136 inputs from 17 copies of the 8 parts of tab_desc in one UNION ALL, so it writes no parts, and it uses LIMIT 4: a sparse input needs 3 chunks to reach it, while the pre-cap build pauses it after 2. Each run also printed T3 and T4 results a second time with optimize_read_in_order = 0; the reference already pins those values, and under the fuzzer these full scans were the most expensive queries left, so they are removed. Measured with the CI thread-fuzzer settings, server and runner on 16 CPUs, 8 copies at -j 8: 139-156 s per run, against 170-357 s for the version of the test at 0e18237, which passed CI at a debug flaky-check p50 of 80 s. Debug build: 30/30 sequential, 50/50 at -j 8 with random settings, 80/80 on a server pinned to 2 CPUs. The build before the 128-input cap fails 12/12 on T5 only, (136,0,17); master fails 12/12 on T1 and T2 only. Co-Authored-By: Claude Opus 5.5 <[email protected]>
When `ORDER BY` has columns after the read-in-order prefix (e.g. `ORDER BY c1 DESC, toStartOfMinute(ts) DESC, ts DESC` with the key `(c1, toStartOfMinute(ts), xxHash32(c2), ...)`), `SortingStep` builds the read-in-order merge with no limit and applies the LIMIT in `FinishSortingTransform`. The read-ahead tracker was only created for a merge with a limit, so every `BufferChunksTransform` kept reading its whole part. The tracker now carries the limit of the sort, separately from the merge limit, which stays 0 there. Repro from ClickHouse#66578 (8 disjoint parts, LIMIT 21, release build): read_in_order_use_buffering = 1 reads 268-313K of 320K rows in ~100 ms before, 4.1-4.6K rows in 11-13 ms after (buffering = 0: 3-4K rows, 9 ms). Results identical. With overlapping parts that merge reads the whole table anyway (it fills a full block before emitting), so a paused input can lose its read-ahead: with 6 of 8 overlapping parts having no matching rows, LIMIT 21 goes from 110 to 190 ms, which is what read_in_order_use_buffering = 0 takes (200 ms). Minute-interleaved overlapping parts with matches everywhere are unchanged. Co-Authored-By: Claude Opus 5.5 <[email protected]>
CI finish ledger - d830242Every 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:20261113-043010 |
|
Yes, #117330 has the same issue. I built its head (042d6ed, RelWithDebInfo) and ran it next to master (official build 26.11.1.2168) and this PR's CI release build (d830242) with
The two PRs conflict: both change |
|
Fixing PR for the |
# Conflicts: # src/Processors/QueryPlan/BufferChunksTransform.h
|
🕵 Merged |
When the sort is finished after the read-in-order merge, the merge has no limit of its own and, if its inputs overlap, reads until it fills a block. Pausing an input there on its own rows, or on rows of an input that overlaps it, only delays reads the merge needs: while inputs without matching rows delay the merge, the paused inputs sit idle and read their parts afterwards. Eight overlapping parts, two with matches, `ORDER BY intDiv(x, 20) DESC, x DESC LIMIT 21`: 157-181 ms before, 90-97 ms after (buffering off: 163-184). In such a merge an input now pauses only when other inputs have produced the limit in rows that sort before its first row: the rows of another input count while its last produced row sorts before our first row. Merges with a limit keep the previous rule. The shape is added to read_in_order_virtual_row_filtered.xml. Co-Authored-By: Claude Opus 5.5 <[email protected]>
CI finish ledger - a59f349Every 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:20261115-020012 |
The new `Stateless tests (arm_asan_ubsan, azure, targeted)` job (ClickHouse#131576) runs the test 50 times on one server with fixed settings. `query_23` (`... WHERE URL LIKE '%google%' ORDER BY EventTime LIMIT 10`) is a TopK read: with the default `use_query_condition_cache = 1` every run stores the granules the TopK filter dropped, and the next run starts from them. The selection shrinks run over run (CI: 383, 26, 16, 9 marks), `ReadCompressedBytes` falls more slowly than the estimate, and the ratio crosses the test's 2x bound once it converges (2.005x / 2.022x on ClickHouse#109377 and ClickHouse#129198). Randomized jobs never converge because the cache and TopK settings are re-drawn per run. Pin `use_query_condition_cache=0` test-wide, as the sibling estimation tests 03801 and 04102 already do; the cache with autopr stays covered by 03783_autopr_dataflow_cache_reuse_qcc. Locally, unpatched at CI's thread count: red from run 4-5 (8-9 marks, 2.02-2.04x); patched: 10/10 with a constant 1084 marks, and 50/50 with random settings. Co-Authored-By: Claude Opus 5.5 <[email protected]>
bfbcd24
The test relied on a fixed key prefix (`WHERE k = 1`) to get a read-in-order merge without virtual rows. The virtual row is now kept for such a query, so the test counted 8 inputs with a virtual row instead of 0, and `Fast test` failed. Set `read_in_order_use_virtual_row = 0`: the test still checks that a buffered input without a virtual row stops reading ahead. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=132113&sha=854362d86090daa8626b9f8676cbcdcc7e9711a2&name_0=PR&name_1=Fast%20test #132113 Related: #129198 Co-Authored-By: Claude Fable 5.2 <[email protected]>
Closes: #66578
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Filtered
ORDER BY ... LIMITqueries that read a MergeTree table in order withread_in_order_use_buffering(the default) now read far fewer rows: an input stops reading ahead once the inputs that sort before it have already produced enough rows for theLIMIT, also when theORDER BYonly starts with a prefix of the sorting key. The two queries from #66578 read about 4 and 60 times fewer rows.Description
With a
WHERE,ORDER BY <key> LIMIT ncannot push the limit into reading, soSortingStepputs aBufferChunksTransform(#64607) in front of every input of the read-in-order merge, and each buffer reads ahead until it hasnrows. Without virtual rows (key prefix fixed by theWHERE) each input reads aboutn / selectivityrows first. When theORDER BYcontinues past the columns read in order, the merge has no limit (FinishSortingTransformapplies it) and each buffer reads its whole part.The buffers of one merge now share a tracker of each input's first row and pulled rows. An input the merge has taken at most one chunk from stops reading ahead once the inputs whose first row sorts strictly before its own, plus its own rows, cover
n, the limit of the sort; only merges with at most 128 inputs pause, as a paused input keeps its reader open. A merge without a limit can need all rows of overlapping inputs to fill a block, so there only rows of other inputs that sort before the input's first row count. Pausing never changes results: an input resumes once the merge needs it.Validation (release, medians):
LIMIT 100, 32 threads: 4.76M -> 1.07M rows, 0.032 -> 0.026 s (buffering off: 0.41M rows).LIMIT 21): 268-313K -> 4.9-5.9K rows, 100 -> 12 ms (buffering off: 9 ms).LIMIT 10000, noLIMIT, preliminary merges, virtual rows, overlap (also the second shape: 0.11 s, unbuffered 0.20 s): within noise at 4-384 threads.read_in_order_virtual_row_filtered.xml:LIMIT 1000.017 -> 0.010 s,LIMIT 3000unchanged, an overlap query added.🤖 Generated with Claude Code
Workflow [PR]
Sync PR [sync-upstream/pr/129198]
Version info
26.11.1.2452-master(included in26.11and later)