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]>
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
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]>
… 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]>
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]>
A preliminary merge of a two-level in-order merge forwarded a member's virtual row and, in the same step, demanded the member's next chunk (`required_source`). `IMergingTransformBase::prepare` then pulled and re-armed that input regardless of whether its output was needed, so every group's front part read 3-4 blocks even when the top-level merge deferred the group for good. The default mode thus read exactly what master reads (12 blocks for 4 groups, plus a timing-dependent block), and 05044_read_in_order_virtual_row_two_level_merge failed whenever the extra block appeared. Mark the status returned by `forwardVirtualRow` as `required_source_on_demand` and let the transform wait for `output.canPush()` before it reads that source. The deferred groups now read nothing: the default mode reads the front group's 3 in-flight blocks (24576 rows) deterministically for 2 to 16 groups, and the per-block mode reads one block. The test now merges 32 parts in 16 groups, so that the unfixed behaviour (48 or more blocks) stays far above the front group's slack even when a fuzzed scheduler lets its lane buffer up to `max_block_size` rows, and asserts bounds of 24 and 3 blocks. CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117330&sha=98053de9a486184da51897bb0defe93e5a79595f&name_0=PR&name_1=Fast%20test Co-Authored-By: Claude Fable 5.1 <[email protected]>
With `force_distinct_partitions_independently`, which CI randomizes, the read outputs each partition through its own port and the DISTINCT skips the cross-stream merge, so the two-level merge the test probes for is never built and its `MergingSortedTransform` count check returned 0. The four data comparisons were unaffected. Pin `allow_distinct_partitions_independently` and `force_distinct_partitions_independently` to 0 for the test. CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117330&sha=a414192401e67f6a62c3e2efc5f7d66ed365792b&name_0=PR&name_1=Stateless%20tests%20%28arm_binary%2C%20parallel%29 PR: #117330 Co-Authored-By: Claude Fable 5.1 <[email protected]>
Review follow-up: the current chunk of an input keeps its virtual-row info after `setVirtualRow`, so the merge loops ask `isVirtualRow` on it directly instead of tracking a parallel flag per input. `skip_last_row` would tell the same here (only the virtual-row branches set it); the header note about parallel FINAL setting it for real data was stale. Co-Authored-By: Claude Fable 5.1 <[email protected]>
Review follow-up: say at `forwardVirtualRow` why the member is read only on demand, and at the `emit_boundary_virtual_rows` decision why forwarding is not limited to the per-block mode. Co-Authored-By: Claude Fable 5.1 <[email protected]>
Default-initialize `Cut` and `QueuedLane` in `MergeTreeReadPoolInOrderSliced.h` (`cppcoreguidelines-pro-type-member-init`), remove the unused `hasFilter`, and rewrite the class comments of `MergeTreeInOrderSliceRouter` and `VirtualRowReadAheadTransform` to state the current rules only. Tidy reports: https://s3.amazonaws.com/clickhouse-test-reports/PRs/121816/57b8445d1bfe0d45dd66b7b96817ed0b02eb4784/pr/build_arm_tidy_3_4/job.log https://s3.amazonaws.com/clickhouse-test-reports/PRs/121816/57b8445d1bfe0d45dd66b7b96817ed0b02eb4784/pr/build_arm_tidy_4_4/job.log PR: #121816 Co-Authored-By: Claude Fable 5.1 <[email protected]>
…the pool off in three per-part tests The breadth gate of `schedule` must skip a lane with no slices in flight that lies after everything in flight, as it did before the router took over the slices: the lane the merge is on then gets its next slice only when the merge asks for it, and a LIMIT met by that slice reads nothing more. It was ported as "a lane never cut", which let the ask after an announcement read ahead one slice too far (28 rows instead of 12 in 02155, 63 instead of 40 in 02877). The router now passes the lanes with slices in flight in `Demand`, and `canShare` follows them too. `04516`, `03634` and `01045` fail with the pool on regardless of this change: they enumerate read pools by name, estimate the bytes of a per-part read, and count rows at block-size granularity, so they pin `read_in_order_use_sliced_pool` off like the other tests of the per-part path. Also rename `readAheadOnReadingSide` to `disableDefaultReadAheadWindow`. CI: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=121816&sha=f5733eac891c503341bcc2cdafbc2e330bb3d28a&name_0=PR PR: #121816 Co-Authored-By: Claude Fable 5.1 <[email protected]>
…hy unknown keys queue last The setting gets the `EXPERIMENTAL` tier. The comment on `compareKeys` states the reason an unknown key sorts after every known one: the lane queue is the read-ahead order, and the pool does not speculate on a lane it cannot place, while the merge's demand for such a lane is served regardless of the queue. Co-Authored-By: Claude Fable 5.1 <[email protected]>
… the error With `read_in_order_use_sliced_pool = 1` the first block read from the part holds the first granule only, so rows 1 and 2 reach the client before the cast throws on the NULL row in the second granule, and the harness prints them before the expected error. An aggregate outputs nothing until it completes, so the error is the only output under any read pool or block size. CI: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=121816&sha=c3de64160484401be4dfc15c13aaf16c040dfcc2&name_0=PR&name_1=Stateless%20tests%20%28arm_binary%2C%20parallel%29 PR: #121816 Co-Authored-By: Claude Fable 5.1 <[email protected]>
Conflicts resolved in favour of the branch: master changed the containers of the virtual-row `sources_to_prefetch` read-ahead to `VectorWithMemoryTracking`, which the branch had already removed; `updateQueryConditionCache` takes master's new `prewhere_filters_by_top_k_threshold` argument. Co-Authored-By: Claude Fable 5.1 <[email protected]>
Conflicts: src/Processors/Transforms/MergeSortingTransform.cpp src/Storages/MergeTree/MergeTreeSelectProcessor.cpp tests/queries/0_stateless/02149_read_in_order_fixed_prefix.sql Co-Authored-By: Claude Fable 5.1 <[email protected]>
Conflicts: `optimizeReadInOrder.cpp` (branch's `apply_virtual_row` update next to master's `join_requires_virtual_rows` check), `ReadFromMergeTree.cpp/.h` (master's `makeVirtualRowHeader` with the branch's block-interval argument of `setVirtualRowConversions`; `readInOrderSliced` now uses the helper too). `slicedPoolRequested` excludes `FINAL`: master now allows virtual rows with `FINAL`, and a `FINAL` read goes through its own merges, not the sliced pool. Co-Authored-By: Claude Fable 5.1 <[email protected]>
The settings `read_in_order_use_sliced_pool`, `read_in_order_virtual_row_block_interval` and `read_in_order_virtual_row_prefetch_window` were added while 26.10 was the current version; after the merge of master they land in 26.11, which the `settings_changes_history` style check requires the first record to name. CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=121816&sha=b7f9d55eba18397c76e1d00fda38866e22e96dd5&name_0=PR PR: #121816 Co-Authored-By: Claude Fable 5.1 <[email protected]>
Master now lets `FINAL` reads emit virtual rows, and with virtual rows the buffering of a read in order moves from `BufferChunksTransform` into `VirtualRowReadAheadTransform`. The test pins `BufferChunksTransform` as the producer of the rowless chunk, so it sets `read_in_order_use_virtual_row = 0`. CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=121816&sha=d1722671eeed050be2a6f9a5d28972134b85903b&name_0=PR&name_1=Fast%20test PR: #121816 Co-Authored-By: Claude Fable 5.1 <[email protected]>
…longer takes Master removed the trailing `ColumnsDescription` parameter of the constructor in adc84b8; the sources of the sliced pool still passed it, so the branch did not compile after the merge. Co-Authored-By: Claude Fable 5.1 <[email protected]>
The router pulled a chunk from a source and set the port not needed in two steps. A chunk pushed in between sat in a port that is not needed, and the next pull threw `Cannot pull block from port which is not needed`: a logical error that aborted the server in the flaky check of `05332_read_in_order_sliced_pool_refiner_queued_slices`, and reproduces locally about once in eighty runs of its query with 16 sources on 2 threads. The port is now pulled with `set_not_needed`, the way `ResizeProcessor` and `LimitTransform` pull, and set needed again unless the source is parked. CI: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=121816&sha=6590a208c85dc7673af868d2bb34af886a930e07&name_0=PR&name_1=Stateless%20tests%20%28amd_binary%2C%20flaky%20check%29 PR: #121816 Co-Authored-By: Claude Fable 5.1 <[email protected]>
… slices the index empties The first slice taken from a lane refines everything of the lane not yet handed to a reader: the slice itself, the slices of the lane still queued in the FIFO and the unread marks. A source that wants a slice of a lane being refined waits for the result, so that one refinement covers every mark once: `IndexReadRangesRefiner` subtracts the marks it drops from the part's remaining marks, and two refinements over the same marks left the part's index result cached until the end of the query. The queued slices are now intersected against a result that covers them. A slice the index leaves nothing of is dropped instead of being read as cut: the source takes the next slice, and the pool reports dropped and shrunk slices to the router, which takes them out of the marks in flight and never counts them as evidence for the read-ahead. Co-Authored-By: Claude Fable 5.1 <[email protected]>
The lane queue and the overlap check compared keys in ascending order and inverted them only for a read in reverse order. With a descending column in the sorting key the lanes were queued in the wrong order, so a `LIMIT` answered within the first part read ahead into parts the merge never reaches. The pool now takes the sorting key's reverse flags and applies them per column. Co-Authored-By: Claude Fable 5.1 <[email protected]>
A read through the sliced pool is not gated on the seal of a join: `markSealGatedReading` leaves such a reader alone, so it keeps the read-time index analysis of the join's runtime filter. Before, the reader was marked gated, `initializePipeline` dropped the filter from the read-time analysis, and the pool's sources were created without a seal, so neither pruning applied. Co-Authored-By: Claude Fable 5.1 <[email protected]>
…t reads through the pool One input reading through the pool disabled the buffering and the default read-ahead window of the whole union's merge, which the inputs read any other way still need. Co-Authored-By: Claude Fable 5.1 <[email protected]>
`read_in_order_virtual_row_prefetch_window` goes into the plan serialization settings, so that an explicit value and the window the optimizer sets for a merge over the sliced pool survive a serialized plan instead of falling back to the default on the receiving side. Co-Authored-By: Claude Fable 5.1 <[email protected]>
… slice A source of the pool hops between slices and parts, so a count per source let a part report after a couple of its own blocks, right after a short slice of another part. The count restarts at every slice, which announces its position when it starts. Co-Authored-By: Claude Fable 5.1 <[email protected]>
The style check requires them under `src/Processors/Transforms` since d619bd2. Co-Authored-By: Claude Fable 5.1 <[email protected]>
| lane_state.refining = true; | ||
| lane_to_refine = unionRanges(taken.ranges, lane_state.unread); |
There was a problem hiding this comment.
❌ Blocker: make the refinement claim exception-safe
lane_state.refining becomes true before unionRanges builds the refinement input. MarkRanges uses a throwing, memory-tracked allocator, so either union can throw MEMORY_LIMIT_EXCEEDED here. This happens before the try in getTask, so its cleanup never clears the claim or notifies refined_cv.
With another same-lane slice queued, a second source already entering takeSlice can acquire the mutex after the first source unwinds, see that abandoned claim, and wait indefinitely at line 314. Cancellation only sets the processor's cancellation flag and cancels index reads; it does not wake this wait or clear the claim. The executor then waits for the blocked worker, leaving the query unable to finish cancellation.
Build the complete lane_to_refine union before setting refining while still holding this mutex, or protect the entire claim lifetime with exception-safe cleanup. Please cover an allocation failure here with concurrent same-lane task acquisition.
Stacked on top of: #117330
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
New experimental setting
read_in_order_use_sliced_pool: readMergeTreein primary key order with a shared pool of threads that read slices of parts on demand, instead of one thread per part.🤖 Generated with Claude Code
Workflow [PR]
Sync PR [sync-upstream/pr/121816]