Repository navigation
Enable read_in_order_use_virtual_row by default - #106215
Conversation
Fixes #52624. When reading in order of the primary key over many parts (the `optimize_read_in_order` optimization), the merging pipeline opens one reader per part for the `MergingSortedTransform` and keeps a `CompressedReadBuffer` per column resident for each of them. With a large number of parts this makes even `ORDER BY pk LIMIT n` consume memory proportional to the number of parts, although only a few of them can contribute to the answer. `read_in_order_use_virtual_row` lets `MergingSortedTransform` reprioritize sources using primary key values taken from the sparse index, so the parts that cannot contribute are never read and their readers are never created. The optimization already existed but was disabled by default; this commit enables it. On a table with 300 parts and an 8 MB compress block size, the peak memory of `SELECT * FROM t ORDER BY k LIMIT 10` drops from ~700 MB to a few MB. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Workflow [PR], commit [8244319] Summary: ✅
AI ReviewSummaryThis PR flips Final Verdict✅ Approve LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 160/167 (95.81%) · Uncovered code |
…ests Enabling `read_in_order_use_virtual_row` by default adds `VirtualRowTransform` nodes to the `EXPLAIN PIPELINE` output of in-order reads over multiple parts. The tests `04105_limit_by_into_sort_explain` and `04052_explain_pipeline_distributed` inspect the pipeline shape of other optimizations (the `LIMIT BY` into sort optimization and distributed pipeline explain), where the virtual row transform is incidental noise. Pin `read_in_order_use_virtual_row = 0` in these tests so their references stay focused and deterministic, matching the existing precedent in `03257_reverse_sorting_key`. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…rder-virtual-row-default
…rder-virtual-row-default
|
Merged The only CI failure was the The merge produced no conflicts; the Verified locally on a freshly built binary:
|
…rder-virtual-row-default
The merge with master pulled in two `SettingsChangesHistory` entries for `query_plan_min_columns_for_join_lazy_indexing` and `query_plan_max_limit_for_join_lazy_indexing`. These came from the "Lazily apply selector and replication indexes in join" change that was later reverted on master, so the corresponding settings no longer exist. Applying `compatibility` walks the history and tries to restore old values for every listed setting; entries for non-existent settings make the `compatibility`-related stateless tests fail. Drop the orphans. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Merged Root cause of the 14 Fast test failures (all Verified locally against a freshly built binary: the formerly-failing No unresolved review threads. |
|
📊 Cloud Performance Report 🟢 AI verdict: This PR enables read_in_order_use_virtual_row by default and adds a bounded read-ahead window to MergingSortedTransform, which only affects ORDER BY primary-key reads with LIMIT over many parts. ClickBench Q23 (SELECT ... ORDER BY EventTime LIMIT 10) is ×2.2 faster — a clean on-path win from reading only the relevant parts. The uniform ~15% shifts across the GROUP BY aggregation queries (Q13, Q15-Q18, Q30, Q31) and the Q28 regression are off the changed code path and were downgraded to not-sure as variance. TPC-H Q7 (×8.6 faster) and Q8 (×2.2 faster) show large, consistent deltas the math locks in, but they are join/aggregation queries with no obvious read-in-order LIMIT path, so those wins are worth an independent sanity check. clickbench🟢 1 improved · Flagged queries (9 of 43)
Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. 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🟢 2 improved Flagged queries (2 of 22)
Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. 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
|
…rder-virtual-row-default
…rallel Enabling `read_in_order_use_virtual_row` by default caused consistent 1.3x-5x slowdowns in read-in-order perf tests (`distinct_in_order`, `optimize_sorting_for_input_stream`, `read_in_order_many_parts`, `monotonous_order_by`, `redundant_functions_in_order_by`) on both amd and arm. The cause: a source that starts with a virtual row is not read until `MergingSortedTransform` reaches its key, so the merge requests the sources strictly one by one and reading becomes single-threaded. Locally, `SELECT DISTINCT low, medium FROM distinct_cardinality_low ORDER BY low` ran at the same speed with `max_threads=1` and `max_threads=16` (0.25s), while with the optimization disabled it scaled to 0.06s. Fix: `MergingSortedAlgorithm` now reports deferred sources that are worth reading ahead (`Status::sources_to_prefetch`), and `IMergingTransform` asks those inputs for data without waiting for it: - without a limit, every source is read in full anyway, so the first `virtual_row_prefetch_window` deferred sources (in the order the merge will need them) read ahead immediately, and the window is topped up as their data arrives; - with a limit, only sources that are provably needed soon read ahead: those whose virtual row is not greater than the key at which the merge must stop within an already-read chunk (bounded by the remaining limit), so sources that cannot contribute are still never read and the memory savings are preserved exactly. The window is the number of pipeline threads, so peak reader memory is O(threads), not O(parts). On a 300-part table, `SELECT * FROM t ORDER BY k LIMIT 10` still reads only 8192 rows with 3 MB peak memory (vs 6.8M rows and 1.3 GB with the optimization disabled), while `DISTINCT ... ORDER BY` over 100M rows scales with threads again (0.26s -> 0.07s at 16 threads). Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=106215&sha=30b53cd589f189d928654bf816406e4afca9ce9d&name_0=PR&name_1=Performance%20Comparison%20%28amd_release%2C%20master_head%2C%203%2F6%29 Co-Authored-By: Claude Fable 5 <[email protected]>
|
Investigated the CI failures of the last run (sha Performance Comparison (slower queries) — real, caused by this PR, now fixed. Enabling Pushed Stress test (arm_ubsan), @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=106215&sha=30b53cd589f189d928654bf816406e4afca9ce9d&name_0=PR&name_1=Stress%20test%20%28arm_ubsan%29 and provide a fix in a separate PR. If the fix is already in progress, link it here. |
|
Investigated the Root cause confirmed (code + the arm_ubsan In stress this compounds exactly as you diagnosed: when the server is killed mid-test the trailing
Agreed this is unrelated to your PR. |
…rder-virtual-row-default
Review and the perf run found three flaws in the previous read-ahead: - With a `LIMIT`, the number of read-ahead sources was unbounded: every deferred source whose virtual row preceded the merge stop row was scheduled at once, so many overlapping parts could re-create the O(parts) resident-reader memory issue this PR fixes. - Read-ahead was issued only for sources provably needed by the merge, so shapes where the proof never arrives still degraded to a single thread. With a selective filter (`WHERE UserID = ...` or `WHERE URL LIKE '%google%'` with `ORDER BY pk LIMIT n`), filtered chunks rarely reach the merge, so nothing ever became provably needed: `order_by_read_in_order` showed 3.3x-4.7x and `lazyMaterialization` 1.9x-2.5x slowdowns on both architectures. - `sources_to_prefetch` was forwarded even on a finished status, and `IMergingTransformBase::prepare` processes prefetches before checking `state.is_finished`, so a query that already reached its `LIMIT` could still start reads that are never consumed. Now `MergingSortedAlgorithm` always keeps the next `virtual_row_prefetch_window` deferred sources (in the order the merge will need them) reading ahead, with or without a `LIMIT`. Under a `LIMIT` the read-ahead is speculative - the merge may finish before reaching a prefetched source - but the waste is bounded by O(threads) chunks (a source past its virtual row only buffers one chunk in its port until the merge consumes it), and peak reader memory stays bounded by the window instead of the number of parts. Pending read-ahead is dropped when the merge finishes, both in `merge` and in `IMergingTransformBase::prepare`. Test `04201_read_in_order_limit_with_filter` encoded the strict on-demand behavior (3 granules); with the window all 4 parts contribute one granule each, which is the documented O(threads) trade-off. Perf report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=106215&sha=45c2bf7746c88ff92a9c46a5f6dfb41dc46b8519&name_0=PR Co-Authored-By: Claude Fable 5 <[email protected]>
|
Pushed The two red checks on the previous run are unrelated to this PR:
|
|
@alexey-milovidov investigated STID 3440-2ddb. It is the same root cause as STID 3440-3393, which is already fixed by #105433 (merged into master 2026-06-11 19:20 UTC by @ azat). No separate PR is needed; this is covered. Root cause. Both STIDs crash at if (select.recursive_with)
for (const auto & child : select.with()->children) // with() is null
#105433 fixes this at the source in select_query->recursive_with = is_recursive_with && hasWith();Evidence it is the same bug and is fixed:
So the two red checks are indeed unrelated to this PR, and the segfault is resolved on current master by #105433. (session cron:clickhouse-worker-slot-2:20260612-034800) |
With the bounded read-ahead window for sources deferred behind virtual rows, a deferred source within the window may be speculatively prefetched and read one block ahead of the merge. For this test (two parts, `ORDER BY x LIMIT 10`), the second part is not needed to answer the query, but whether its one prefetched block is actually read before the merge finishes is timing dependent: the test passed locally (second part read `0` rows) but failed in CI (second part read `65536` rows). Assert the deterministic invariants instead of the exact per-part read count: both parts have their own `MergeTreeSelect` and `VirtualRowTransform` (so the virtual-row path is engaged) and neither reads more than one block. This mirrors the bounded-read assertion already used in `04201_read_in_order_limit_with_filter`. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=106215&sha=5d11e85846e1f09b165fa2ec58ce8eb582ca33b0&name_0=PR&name_1=Fast%20test Co-Authored-By: Claude Opus 4.8 <[email protected]>
A source deferred behind a virtual row reserves a read-ahead slot (`prefetches_in_flight`) when prefetched, and the slot is released in `MergingSortedAlgorithm::consume` once the source delivers its first real chunk. But when a prefetched source is completely filtered out upstream it finishes without ever delivering a real chunk: `IMergingTransformBase::prepare` sees the input finished and sets `state.no_data` without calling `consume`. The slot was then never released, so after `max_threads` such sources the window stopped refilling and the merge silently degraded to reading one part at a time, defeating the read-ahead and reproducing the very serialization the window is meant to avoid (e.g. a selective filter that empties leading parts). Add `IMergingAlgorithm::onSourceExhausted`, called from the transform when a required source finishes without data, and have `MergingSortedAlgorithm` release the deferred source there (the merge loop already drops it from the queue via `removeTop`, so only the read-ahead bookkeeping needs updating). The release logic is shared with `consume` through `releaseDeferredSource`. Add `05017_virtual_row_prefetch_filtered_out` exercising the path where the leading parts the merge walks through are all filtered out. Co-Authored-By: Claude Opus 4.8 <[email protected]>
The new regression test was created with prefix `05017`, far ahead of the current maximum test number on master (`04337`), which tripped the `test_numbers_check` style check (`Gap (4336, 5017) > 100`). The high number was picked by `add-test` because of unrelated untracked `050xx` files left in the shared working directory. Renumber to `04339` so the test numbers stay contiguous. No change to the test itself; the table name does not depend on the prefix. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=106215&sha=b2b7bdb327ee84f4e9485a56cb7845b11788a788&name_0=PR&name_1=Style%20check Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The stateless test `04339_virtual_row_prefetch_filtered_out` only checks result correctness, which holds with or without `MergingSortedAlgorithm::onSourceExhausted`: when the merge walks in-order through leading parts that are entirely filtered out, the same parts are read and the same rows are produced either way; the only difference is scheduling. With the read-ahead slot released the filtered-out parts are read concurrently; without it the window stalls after `max_threads` such sources and the merge degrades to reading one part at a time. That difference is timing-only, so it cannot be asserted deterministically in a stateless test, but it is exactly what the performance-comparison suite measures reliably. This test builds 64 parts with disjoint increasing key ranges where only the last part matches the filter, so `ORDER BY a LIMIT N` has to walk through 63 fully filtered-out leading parts, exercising the slot-release path at a scale where the serial-vs-parallel difference is measurable. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
🕵 @groeneai, please investigate the unrelated Stress test (arm_release) failure. It is the known |
|
This is not caused by this PR. STID The carrier here is an AST-fuzzer mutation of The err log shows the shard failing first ( I reproduced the mechanism locally on master ( So neither #102192 nor #107924 covers this occurrence: #102192 adds The owner is your #114983, which names this STID and this arm_release/arm_msan pattern, and rethrows the remembered destructive-build failure so the query reports the connection error instead of the logical error. #114849 addresses the same code path by preserving non-clonable sources for the deferred build. I will track both against CIDB and follow up here if |
|
🕵 @groeneai, investigate the failure: https://github.com/ClickHouse/ClickHouse/actions/runs/31941153595/job/95161801033 and provide a fix in a separate PR. The runner lost communication with GitHub while the |
|
Confirmed as infrastructure. Job 95161801033 is There is an open fixing PR and it is mine: #112984, which bounds the integration tests' nested containers by the job's memory limit. Its CI is now finished and clean on head One new detail. This is the first report of this wedge on a shard other than 5/6, and the breadth says the shard is incidental: of the master heads in the last three days that published only five of the six shards, the absent one was 4/6 on 18 of them, 2/6 on 11, 5/6 on 1 and 6/6 on 1. The wedge is runner-level and shard-agnostic, which fits the containment mechanism #112984 addresses rather than shard balance. This job also ran 112 minutes against 82 to 102 for the five that passed alongside it, so it is not a fixed-duration timeout. |
|
Thanks! So we will enable this, then enable |
The first CI run with `read_in_order_use_virtual_row` enabled by default failed `03711_read_in_order_through_join`: `ORDER BY pk LIMIT n` read about 155k rows where the reference expects a single granule (`Fail: 155656 rows read`), on every stateless shard. The read-ahead window that lets sources deferred behind virtual rows read in parallel was started eagerly — at `initialize` and on every consumed chunk — before the merge knew whether the front source's first chunk already satisfied the limit. When it did (e.g. `read_in_order_through_join` with the answer in the first part, the part split into `max_threads` streams), the window still speculatively read a block from each of the other streams, reading parts that the optimization exists to skip. Start the read-ahead only once the merge has finished with a source (its real data arrived, or it was exhausted without any) and still needs another one. The first source the merge asks for is the front source being resolved from its virtual row; the sources deferred behind it are not prefetched until the merge proves it must advance past the front. This preserves the parallelism win for selective filters — where the front chunks do not satisfy the limit, so the merge keeps requesting sources, and the window engages (including when the leading parts are entirely filtered out and exhausted without data) — while no longer reading parts that a limit answered by the front source never reaches. The `03581` and `04201` test comments are updated to describe the gated read-ahead; both assertions (bounded read counts) still hold. CI report: ClickHouse#106215 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The test created a query quota with `TO default`. A quota is a server-global entity, and in stress and parallel runs all stateless tests execute concurrently against the same server as the `default` user, so the quota on `default` was consumed by every concurrent query, exhausted its limit, and made the server reject subsequent queries with `QUOTA_EXCEEDED` — eventually taking the whole server down (`Server is not responding`). The interval is validated at CREATE time in `InterpreterCreateQuotaQuery`, independent of the `TO` assignment, so the quota does not need to be assigned to anyone for the test to exercise the `BAD_ARGUMENTS` rejection. Drop the `TO default` clause so the test no longer touches the shared `default` user; the reference output (`BAD_ARGUMENTS` / `BAD_ARGUMENTS` / `ok`) is unchanged. Surfaced on the `Stress test (amd_msan)` job of ClickHouse#106215 CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=106215&sha=0b2a2b671abe9df2dae40253fb8fafacaf699575&name_0=PR&name_1=Stress%20test%20%28amd_msan%29 Caused by: ClickHouse#110846 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The merge kept a window of sources deferred behind their virtual rows reading ahead (`virtual_row_prefetch_window`, `Status::sources_to_prefetch`, `onSourceExhausted`, `inputs_to_prefetch`). Reading ahead belongs to the reading side: with `read_in_order_use_sliced_pool` the pool knows the primary key of every unread granule and reads exactly what the merge is going to need next, while the merge can only guess by source. The merge now only asks for the input it needs. On the per-part path (the setting off, descending order, parallel replicas or a preliminary merge) the sources deferred behind virtual rows are read one after another when the merge reaches them, as before the window was added in #106215. The tests that asserted the window through `processors_profile_log` keep their assertions, which hold without read-ahead as well; only their comments change. The generated documentation of `read_in_order_use_virtual_row` and of `read_in_order_use_sliced_pool` is refreshed. Co-Authored-By: Claude Fable 5.1 <[email protected]>
Closes: #52624
When reading in order of the primary key over many parts (the
optimize_read_in_orderoptimization), the merging pipeline opens one reader per part to feed theMergingSortedTransform, and keeps aCompressedReadBufferper column resident for every one of them. With a large number of parts this makes evenORDER BY pk LIMIT nconsume memory proportional to the number of parts, even though only a few of them can contribute to the result. The original report describes a query needing ~42 GB for this reason (1803 parts × 3 columns × 8 MB compress blocks).The
read_in_order_use_virtual_rowoptimization letsMergingSortedTransformreprioritize sources using primary key values taken from the sparse index, so the parts that cannot contribute to the answer are never read and their readers are never created. The optimization already existed but was disabled by default; this change enables it.Measured on a table with 300 parts and an 8 MB compress block size, the peak memory of
SELECT * FROM t ORDER BY k LIMIT 10drops from ~700 MB to a few MB.Related issues: #53101, #53287, #7413 (closed), and #89638 (open) describe the same underlying behavior.
Note: the more aggressive
read_in_order_use_virtual_row_per_block(which also disablesread_in_order_use_bufferingand the preliminary merge) is intentionally left disabled by default, since it trades some parallelism for the extra memory savings.Update. The first CI run showed consistent 1.3x–5x slowdowns in read-in-order perf tests (
distinct_in_order,optimize_sorting_for_input_stream,read_in_order_many_parts,monotonous_order_by,redundant_functions_in_order_by) on both architectures. The cause: a source that starts with a virtual row is not read until the merge reaches its key, so the merge requests deferred sources strictly one by one and reading degrades to a single thread (locally,SELECT DISTINCTover 100M rows ran at the same speed withmax_threads=1andmax_threads=16). This was addressed by letting deferred sources read ahead: without aLIMITa window ofnumber of threadsdeferred sources, and with aLIMITonly sources provably needed soon (those whose virtual row is not greater than the key at which the merge must stop within an already-read chunk).Update 2. The second perf run and review showed that the "provably needed" rule for the
LIMITcase was wrong in both directions:SELECT * FROM hits WHERE UserID = ... ORDER BY pk LIMIT 100), filtered chunks rarely reach the merge, the proof never arrives, and reading degrades to a single stream again —order_by_read_in_ordershowed 3.3x–4.7x andlazyMaterialization1.9x–2.5x slowdowns on both architectures.Both are fixed by making the read-ahead window unconditional: the merge always keeps the next
number of threadsdeferred sources (in the order it will need them) reading ahead, with or without aLIMIT. Under aLIMITthe read-ahead is speculative — the merge may finish before reaching a prefetched source — but the number of speculative readers is bounded by O(threads). A released source can additionally retain chunks under the pre-existingBufferChunksTransformlimits; peak reader memory nevertheless stays bounded by the window instead of the number of parts: the 300-partLIMIT 10query above runs with ~7 MB peak memory and reads only the window's first chunks, vs ~1.3 GB and a full read without the optimization. Pending read-ahead is dropped as soon as the merge finishes, so a query that already produced itsLIMITdoes not start new reads.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Enable
read_in_order_use_virtual_rowby default. When reading in order of the primary key (e.g.ORDER BY primary_key LIMIT n) over a table with many parts, only the parts that can actually contribute to the result are read (plus a read-ahead window of at mostmax_threadsparts that keeps reading parallel), which significantly reduces peak memory consumption.Documentation entry for user-facing changes
Version info
26.8.1.1592(included in26.8and later)