Repository navigation
Conversation
Controls the read-ahead window for sources deferred behind virtual rows in read-in-order merges: -1 means as many as the pipeline has threads (previous hardcoded behavior), 0 disables the read-ahead, N > 0 caps it. Co-Authored-By: Claude Fable 5 <[email protected]>
…nsform An N-lane coordinator transform between the in-order sources and the merge now owns both the per-lane buffering (absorbing BufferChunksTransform on the virtual-row path) and the read-ahead policy for sources deferred behind virtual rows. It handles the initial and the per-block virtual rows uniformly: a virtual row parks its lane and updates the lane's boundary; a lane is read on downstream demand, a demanded lane is kept reading ahead while under the buffer caps, and once demand has visited two distinct lanes (or there is no limit) the parked lanes closest to the merge in key order read ahead in parallel, bounded by read_in_order_virtual_row_prefetch_window. This fixes the serialization of read_in_order_use_virtual_row_per_block: every block was followed by a virtual row that left the port NotNeeded with no read-ahead anywhere (the merge window covered only the initial virtual rows and BufferChunksTransform was disabled in this mode), so scan-heavy ORDER BY pk LIMIT n queries with selective filters degraded 8-16x. With the coordinator the same queries run within ~1.3-2.7x of virtual rows disabled while keeping the zero-read guarantees for deferred sources and the boundary-precise read savings when the limit is answered by the front part. The merge-side deferral machinery (SourceDeferralState, topUpPrefetch, sources_to_prefetch plumbing, onSourceExhausted) is deleted; MergingSortedAlgorithm keeps only virtual-row-as-cursor handling. Co-Authored-By: Claude Fable 5 <[email protected]>
05042: a per-block scan that must visit every part (matches only at the end of the key range), forward and reverse, plus the fully-filtered-parts path that delivers 0-row chunks between virtual rows. 05043: mirror of 04617 with the per-block mode on - the limit answered by the front source across multiple blocks must leave the deferred source completely unread. Co-Authored-By: Claude Fable 5 <[email protected]>
…ed them apply_virtual_row was set whenever a virtual row conversion existed, even when ReadFromMergeTree::setVirtualRowConversions rejected it (the setting disabled or a query with FINAL). Previously that only made the merge look for virtual rows that never come; now it also selects the read-ahead coordinator instead of BufferChunksTransform, so tie the flag to the actual decision. Pin 03168_read_in_order_buffering_1 to the plain path, where BufferChunks presence still follows read_in_order_use_buffering. Co-Authored-By: Claude Fable 5 <[email protected]>
With the read-ahead window at zero and no buffering wanted, the transform adds nothing: the merge alone consumes the streams strictly on demand. Also document why the per-lane credit is bounded by one group and what the collation guard disables. Co-Authored-By: Claude Fable 5 <[email protected]>
The per-block gap is proportional to the virtual-row count (measured by varying the block size with the byte cap lifted), so shave the per-row costs: the read-ahead coordinator no longer deep-clones the chunk and rebuilds the full header layout to learn the boundary - it applies the conversions to a copy of the small pk block from the chunk info and takes the sort columns by name; the select processor shares one set of immutable empty header columns across all emitted virtual rows instead of allocating them per block. Co-Authored-By: Claude Fable 5 <[email protected]>
…partial Profiling the no-match scan (log_processors_profiles) showed the remaining per-block gap comes from the group-boundary round trips: the sources spent time blocked on push while their lanes were parked at every virtual row, and the coordinator put an O(lanes) full pass on the single-threaded critical path for every port event. Two changes: - After two consecutive groups with no real rows, a virtual row stops consuming the lane's credit: parking a fully-filtered lane at every boundary buys nothing and only stalls the scan. The lane free-runs like a single-shot one until real data appears. Only lanes already granted credit can trigger this, so the zero-read guarantees for deferred sources hold. - prepare(updated_inputs, updated_outputs) processes only the lanes whose ports changed, falling back to the full pass on the first call and when a port finished. Granting credit to a lane now also enqueues it into the running pass: its input may already hold a chunk pushed just before the lane parked, and setNeeded alone wakes only the upstream. The termination scan runs at the end of both prepare variants, because the terminal transition can be the processor's own doing (finishing the last live output), after which no port event will come back to conclude it. Co-Authored-By: Claude Fable 5 <[email protected]>
A lane scanning through filtered-out groups re-earns its credit at every virtual row (deliberately - crossing those groups is work the merge would demand anyway), which used to queue one virtual row per group: unbounded buffer growth in principle, and a merge cursor round trip per obsolete boundary. A newer virtual row strictly tightens the previous announcement, so keep at most one trailing virtual row in the buffer, and state the real speculation invariant on Lane::credit (buffer caps bound the real data; the window bounds the concurrency; boundary-only scan-through is allowed). Co-Authored-By: Claude Fable 5 <[email protected]>
The sorting step now skips the read-ahead transform for collated sort descriptions (the boundary ranking is collation-unaware, and virtual rows cannot occur there anyway since they follow the binary primary key order), so the transform loses its internal collation guard. Review feedback on the comments: define what a group is once in the class doc, cut the credit and free-run comments down, explain the free-run threshold and the full-pass fallbacks, and note why the plain BufferChunksTransform branch is still reachable (setting disabled or FINAL). Co-Authored-By: Claude Fable 5 <[email protected]>
Co-Authored-By: Claude Fable 5 <[email protected]>
- Count only speculative grants toward the read-ahead window: the lane feeding the merge and lanes that never announce boundaries hold their demand-driven credit outside it, so a window of N really permits N sources reading ahead (before, one slot was permanently occupied and window=1 behaved like 0; a boundary-less lane could hold a slot for the whole query). - Drop the data-less free-run: since the window refills in the same pass that consumes a boundary, a fully filtered lane is re-granted inline while it stays among the k nearest boundaries and stops once its boundary runs ahead - restoring the documented bound on reads wasted when a limit ends the merge early (a free-running lane could previously scan its whole part). - Compact replicated columns before measuring buffered bytes; measuring before compaction and subtracting after made the byte accounting drift upward until the cap silently stopped working. - Allow buffering for merges over pre-sorted remote streams with read_in_order_use_virtual_row_per_block enabled: those merges carry no virtual rows, and the setting no longer documents such a restriction. - Assert the reverse scan's read count in 05042 (the property its comment claims), repoint two comments from the deleted MergingSortedAlgorithm::onSourceExhausted to the new mechanism, and fix an overstatement in the 03168 comment. Co-Authored-By: Claude Fable 5 <[email protected]>
Measured in isolation on the most virtual-row-heavy cell (max_block_size = 8192, a no-match full scan, ~12k virtual rows): 0.092 s cached vs 0.094 s allocating per block - within noise. Not worth the extra member. Co-Authored-By: Claude Fable 5 <[email protected]>
Co-Authored-By: Claude Fable 5 <[email protected]>
A preliminary merge always knows the key of its own next output - the top of its sorting queue. When that top is a member's virtual row, forward it downstream before asking the member for data: the announcement is as valid for the merged group stream as it was for the member, so the top-level merge (and the read-ahead transform in front of it) can defer whole groups and, with read_in_order_use_virtual_row_per_block, keeps receiving the per-block boundaries. This removes the forced flat merge for the per-block mode (its main cost on tables with hundreds of parts) and restores the lazy win for the default mode above read_in_order_two_level_merge_threshold (a limit answered at the key range start no longer reads a block from every group). setVirtualRow now keeps the chunk info attached so a consumed virtual row remains one and can be re-emitted. Emission is skipped for a single group (nothing to defer it against, and the extra boundary hop lets the free-running read race one block further) and for the partition-wise output, which feeds aggregation rather than a merge. The read-ahead refill in VirtualRowReadAheadTransform no longer reads past a boundary still waiting in the lane buffer: crossing an announced boundary is the gated window's call, not the refill's. Co-Authored-By: Claude Fable 5 <[email protected]>
Co-Authored-By: Claude Fable 5 <[email protected]>
Mutate the chunk info in place in setVirtualRow instead of the extract-and-re-add dance, shorten two comments, and explain why the port-to-lane index exists (ports live in std::lists, the partial prepare receives pointers). Co-Authored-By: Claude Fable 5 <[email protected]>
|
Workflow [PR], commit [042d6ed] Summary: ✅
AI ReviewSummaryThis PR moves read-in-order buffering and speculative virtual-row wakeups out of Findings
Final VerdictStatus: Minimum required actions:
LLVM Coverage ReportMeasured on commit 042d6ed.
Changed lines: Changed C/C++ lines covered: 355/372 (95.43%) · Uncovered code |
The test disables read_in_order_use_virtual_row, so the reading step refuses virtual rows; since SortingStep respects that refusal, the no-op RemoveVirtualRowTransform is no longer inserted and EXPLAIN PIPELINE lost that line. No virtual rows were ever emitted in these pipelines. Co-Authored-By: Claude Fable 5 <[email protected]>
…ansform' into vdimir/virtual-row-read-ahead-transform
|
📊 Cloud Performance Report ✅ AI verdict: One query was flagged: tpch_adapted_1_official Q1 ran -17.2% faster (64 ms to 53 ms). This PR only changes the read-in-order path when sorting by the primary key: the virtual-row read-ahead, which now has its own transform, the per-block virtual row interval and buffering. Q1 is a full-scan aggregation that never uses that merge, so it was downgraded to not sure. Q1 also shifts often on master, its measurements were noisy, and its CPU time barely changed, so the speedup is run-to-run variance rather than an effect of this PR. Neither benchmark suite has a query that reads in primary key order with a LIMIT, so these results do not test the code this PR changes in either direction. clickbench🟢 No significant changes tpch_adapted_1_officialFlagged queries (1 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
|
The index-based loop is deliberate: grantCredit appends to touched_lanes while it runs, so a range-based for would be invalidated on reallocation. Co-Authored-By: Claude Fable 5 <[email protected]>
…pressing the lint The previous commit silenced modernize-loop-convert on the fixpoint loop of the partial prepare because `grantCredit` appends to `touched_lanes` while the loop runs, so the range-based form the check suggests would be invalidated on reallocation. Restructure the loop instead: each pass walks the prefix that existed when it started, and lanes touched during the pass trigger another pass. The fixpoint is unchanged, the growth of the container during iteration is explicit, and no suppression is needed. Co-Authored-By: Claude Fable 5.1 <[email protected]>
| max_block_bytes = settings[Setting::prefer_external_sort_block_bytes]; | ||
| read_in_order_use_virtual_row_per_block = settings[Setting::read_in_order_use_virtual_row] && settings[Setting::read_in_order_use_virtual_row_per_block]; | ||
| read_in_order_use_buffering = settings[Setting::read_in_order_use_buffering]; | ||
| virtual_row_prefetch_window = settings[Setting::read_in_order_virtual_row_prefetch_window]; |
There was a problem hiding this comment.
This wires the new setting only into the local DB::Settings constructor. SortingStep::serializeSettings still writes through updatePlanSettings, but Settings(const QueryPlanSerializationSettings &) never reconstructs virtual_row_prefetch_window, so any distributed/serialized FinishSorting step falls back to -1 on the worker. That silently ignores a user-set read_in_order_virtual_row_prefetch_window = 0 / N on the path where mergingSorted can still build a VirtualRowReadAheadTransform. Please either round-trip the setting through QueryPlanSerializationSettings or reject non-default values when the step is serialized.
… the iterated set The partial prepare iterated `touched_lanes` while `grantCredit`, two calls deep, appended to it. Record the woken lanes in `credited_lanes` instead and fold them into the touched set between fixpoint passes, so a pass never modifies the vector it iterates and the loop is a plain range-based for. `touchLane` reports whether the lane was new so a late credit counts as progress. The full prepare no longer needs to bump the touch epoch, and the partial prepare reuses `touchLane` for the port events instead of a duplicate lambda. Co-Authored-By: Claude Fable 5.1 <[email protected]>
A preliminary merge of a two-level in-order merge forwards its members' virtual rows downstream, but it forwarded the chunk `setVirtualRow` had materialized for its own cursor: one row holding the announced key. Everything between the preliminary and the final merge saw that row as data. A preliminary DISTINCT remembered the key and dropped the real rows that followed with the same key, so `SELECT DISTINCT ... ORDER BY` over several parts lost the first key of every part in read order (the table minimum ascending, the maximum descending), with both `DistinctTransform` and `DistinctSortedStreamTransform`. `04549_virtual_row_distinct_in_order_boundary` failed deterministically. `VirtualRowTransform` emits a virtual row as an empty chunk whose key lives only in the attached `MergeTreeReadInfo`, and every transform in between is transparent to that shape. Re-emit the forwarded announcement in the same shape: an empty chunk carrying the consumed chunk's infos. The read-ahead transform and the final merge take the key from the info, so nothing downstream changes. Adds 05055_virtual_row_two_level_merge_preliminary_distinct, which loses a distinct pair in both read directions without the fix. Co-Authored-By: Claude Fable 5.1 <[email protected]>
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes83 object files changed (+66.16 KiB total), 1 added.
719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units135 translation units recompiled, 1122 s compile time in total, 134 of them have a recent master baseline. |
Review follow-up: reuse the consumed chunk and reset its columns to empty instead of building a new chunk and moving the infos over, and state the general rule in the comment rather than the DISTINCT symptom. Co-Authored-By: Claude Fable 5.1 <[email protected]>
…er merge A preliminary merge consumes the virtual rows of its members, so the final merge saw a group only once it produced data: every group read at least one block from its front part even when the `LIMIT` was answered by the first group alone, and the per-block mode had to disable the preliminary merge altogether. With `forward_virtual_rows` set, `MergingSortedAlgorithm` re-emits a member's virtual row when it reaches the top of its queue, before asking the member for data, in the shape `VirtualRowTransform` uses (an empty chunk carrying the info), so the final merge and `VirtualRowReadAheadTransform` defer the group as they defer a single part. `IMergingTransformBase::prepare` returns `PortFull` right after pushing such an announcement, so no member is demanded until downstream asks past it. The group also hands out its first merged rows as soon as it has them instead of filling a whole merged block: with a selective filter the front group would otherwise scan all of its parts before the final merge could move on and open the read-ahead window for the other groups. The per-block mode no longer disables the preliminary merge. `LIMIT 3` over 16 groups reads 3 blocks instead of 16 (new test 05219). On the 128-part `t_vrow_bench` table (32 threads, 32 groups of 4 parts), default mode, against master: 0.1% `LIMIT 100000` 420-429 ms (100-109), sparse `LIMIT 10` 49-50 ms (18-20), no-match `LIMIT 10` 630 ms (36-37), dense `LIMIT 100` 70-72 ms reading 8.0M rows (30-34 ms, 24M rows). A group re-announces at every member switch and its lane parks until the final merge asks for it, and the read-ahead window only wakes lanes that have not started, so the 32 groups are served one part at a time. The same shapes with a flat merge (threshold 10000) take 123 and 42 ms. Re-emitting only the initial virtual row of a group measured 99-108 / 23-24 / 51-56 / 25 ms. Per-block mode (interval 8) against master's per-block mode: 963 (1975), 51 (35), 647 (597), 56 (14) ms. Co-Authored-By: Claude Fable 5.1 <[email protected]>
…wo-level in-order merge" This reverts commit 4a13890.
|
|
||
| /// Deferral needs only a one-chunk buffer per lane; deeper buffering is the | ||
| /// same optimization `BufferChunksTransform` provides and follows its setting. | ||
| bool deep_buffering = use_buffering && sort_settings.read_in_order_use_buffering; |
There was a problem hiding this comment.
This new deep_buffering path still depends on sort_settings.read_in_order_use_buffering, but serialized FinishSorting never reconstructs that field: SortingStep::Settings(const QueryPlanSerializationSettings &) hard-codes it to false, and PLAN_SERIALIZATION_SETTINGS has no carrier for it. A jointly-scoped SETTINGS make_distributed_plan = 1, serialize_query_plan = 1, read_in_order_use_buffering = 1 query will therefore lose buffering on the worker even though this PR now promises that per-block virtual rows work together with read_in_order_use_buffering. Please either round-trip the setting through QueryPlanSerializationSettings as well, or reject serialized FinishSorting when buffering would matter.
There was a problem hiding this comment.
Was it the case before the change when we use BufferChunksTransform?
There was a problem hiding this comment.
Yes. The same omission was already present on the plain BufferChunksTransform path: a deserialized FinishSorting rebuilt sort_settings.read_in_order_use_buffering as false, so that branch would also skip buffering on the executing node.
What changed in this PR is that read_in_order_use_virtual_row_per_block no longer disables buffering, and the new deep_buffering path in VirtualRowReadAheadTransform now depends on the same missing field. So the gap is now part of the newly-advertised behavior too, not only the older plain-buffering branch.
| /// - PREWHERE filters all rows (merge gets updated position without actual data) | ||
| /// - A downstream filter (WHERE, JOIN) removes all rows (virtual row passes through filters) | ||
| if (virtual_row_conversions && !result.is_finished) | ||
| if (virtual_row_conversions && !result.is_finished && ++blocks_since_virtual_row >= virtual_row_block_interval) |
There was a problem hiding this comment.
blocks_since_virtual_row lives on the processor, not on the current part/task, so this new interval is applied across part boundaries. A concrete trace with read_in_order_virtual_row_block_interval = 8: if one part ends after 7 blocks, the next part emits its first follow-up virtual row after 1 block; if it ends after 1 block, the next part waits 7. That violates the documented per-part contract ("a part reports its position ... after every N-th block") and makes the tuning depend on how many blocks the previous part happened to consume.
Please reset the counter when getNewTask switches to a new part (or keep it in the task/part state instead of on the processor).
c849d59 to
ea41437
Compare
…y exactly Under equal knobs the transform now reads the same as the policy it replaced inside `MergingSortedAlgorithm`: - The window is refilled only when the merge asks for a lane, never when a source runs dry, so the merge's own step does not queue behind the sources it wakes. An exhausted lane is closed on the merge's request and keeps its window slot until then. - `prepare` processes only the lanes whose ports were updated instead of all lanes on every call (2x CPU on 2048-part layouts). - A deferred lane the merge asks for stays deferred until it delivers data, so the window can still wake it; with per-block announcements every lane gets asked before any data arrives and no read-ahead happened at all. - The merge no longer re-requests an input right after pulling from it when the transform is upstream (`disableInputReadAhead`); the lane keeps the next chunk ready instead, so every request the transform sees is the merge's actual demand. Without buffering the caps are zero. Co-Authored-By: Claude Fable 5.1 <[email protected]>
| Chunk chunk = std::move(lane.chunks.front()); | ||
| lane.chunks.pop_front(); | ||
| if (isVirtualRow(chunk)) | ||
| lane.parked = true; |
There was a problem hiding this comment.
This keeps a speculative slot on a lane that has already parked itself again behind a later virtual row. A concrete trace with read_in_order_virtual_row_prefetch_window = 1: lane A is woken first, PREWHERE filters out its first block, and A then emits another virtual row whose key is already behind lane B. A still stays in Stage::Prefetched, so num_prefetching remains 1 and wakeDeferredLanes cannot start B or C; the startup falls back to serial A -> B -> C reads until some lane finally returns rows or EOF. That breaks the new "nearest deferred lanes keep reading" contract for selective filtered prefixes. I think a lane that re-parks on a later virtual row before delivering data needs to go back to Deferred and be reinserted by its new key instead of holding the old slot.
a49a5d8 to
90a7f18
Compare
…read-ahead-transform Resolve the conflict with the move of the settings changes history into the setting declarations (ee6b44f): the history records this PR added to `SettingsChangesHistory.cpp` now live as trailing arguments of the `DECLARE` of each setting. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Motivation
Followup #106215
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
read_in_order_virtual_row_block_interval(default 8) sets how many blocks a part reads before it reports its position to the merge, andread_in_order_virtual_row_prefetch_windowlimits how many parts are read ahead in parallel while the merge has not reached them yet (default: one fewer than the query threads). The default behavior of read-in-order queries is unchanged.Workflow [PR]
Sync PR [sync-upstream/pr/117330]