Skip to content

Move virtual row read-ahead and buffering into a new VirtualRowReadAheadTransform - #117330

Open
vdimir wants to merge 76 commits into
masterfrom
vdimir/virtual-row-read-ahead-transform
Open

vdimir wants to merge 76 commits into
masterfrom
vdimir/virtual-row-read-ahead-transform

Conversation

@vdimir

@vdimir vdimir commented Aug 31, 2026 •

Copy link
Copy Markdown
Member

Motivation

Followup #106215

Changelog category (leave one):

  • Improvement

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

  • Two new settings tune the read-in-order merge: read_in_order_virtual_row_block_interval (default 8) sets how many blocks a part reads before it reports its position to the merge, and read_in_order_virtual_row_prefetch_window limits 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]

vdimir and others added 17 commits August 25, 2026 13:19
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]>
- 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]>
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]>
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]>
@clickhouse-gh

clickhouse-gh Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [042d6ed]

Summary: ✅


AI Review

Summary

This PR moves read-in-order buffering and speculative virtual-row wakeups out of MergingSortedTransform into the new VirtualRowReadAheadTransform, and adds read_in_order_virtual_row_block_interval to thin out per-block announcements. I still request changes: four major issues remain in the current code, and one previously dismissed distributed-plan serialization gap still appears real in the current tree.

Findings

⚠️ Majors

  • [src/Processors/QueryPlan/SortingStep.cpp:178] Serialized FinishSorting still drops read_in_order_virtual_row_prefetch_window: Settings(const QueryPlanSerializationSettings &) never reconstructs it, and updatePlanSettings never writes it. A distributed / serialized FinishSorting therefore falls back to the worker default -1, silently ignoring a user-set read_in_order_virtual_row_prefetch_window = 0 / N on the path that now builds VirtualRowReadAheadTransform. Suggested fix: round-trip the setting through QueryPlanSerializationSettings, or reject serialization when the value is non-default.
  • [src/Processors/QueryPlan/SortingStep.cpp:191] The new deep-buffering path still loses read_in_order_use_buffering after query-plan serialization because deserialization hard-codes it to false. That was already a gap for BufferChunksTransform, but this PR makes it part of the newly advertised per-block virtual-row behavior too, so a serialized FinishSorting can silently stop buffering on the worker. Suggested fix: serialize read_in_order_use_buffering as part of the plan settings, or fail closed when buffering would matter.
  • [src/Storages/MergeTree/MergeTreeSelectProcessor.cpp:521] blocks_since_virtual_row still lives on the processor instead of the current part/task, so read_in_order_virtual_row_block_interval is applied across part boundaries. If one part ends after 7 blocks and the interval is 8, the next part emits its first follow-up virtual row after 1 block; if the previous part ends after 1 block, the next part waits 7. That violates the documented per-part contract and makes the tuning depend on how many blocks the previous part happened to consume. Suggested fix: reset the counter when getNewTask switches parts, or keep it in part/task state instead of on the processor.
  • [src/Processors/Transforms/VirtualRowReadAheadTransform.cpp:245] A lane that was woken by the window keeps its speculative slot even after it parks itself again behind a later virtual row. With read_in_order_virtual_row_prefetch_window = 1, a filtered prefix can therefore pin the only slot on lane A while lanes B/C stay blocked, degrading startup back to serial A → B → C reads until some lane finally returns data or EOF. Suggested fix: when a prefetched lane re-announces itself before delivering data, move it back to Deferred, update its ordering key, and free the prefetch slot so wakeDeferredLanes can wake the next nearest lane.
  • [src/Processors/QueryPlan/ReadFromMergeTree.cpp:1029] [dismissed by author -- https://github.com/Move virtual row read-ahead and buffering into a new VirtualRowReadAheadTransform #117330#discussion_r4007232611] The read step still pulls per-block virtual-row behavior from ambient settings, while ReadFromMergeTree::serialize / deserialize do not carry either read_in_order_use_virtual_row_per_block or read_in_order_virtual_row_block_interval (src/Processors/QueryPlan/ReadFromMergeTree.cpp:6869, src/Processors/QueryPlan/ReadFromMergeTree.cpp:7003). So a nested SETTINGS make_distributed_plan = 1, serialize_query_plan = 1, ... read can still execute on the worker with a different virtual-row schedule than the coordinator planned. I still consider this real because the current wire format never serializes those settings, despite the on-thread claim that changed settings are carried with the plan. Suggested fix: round-trip the effective per-block mode + interval with the read-in-order contract, or reject serialized reads that need non-default values.
Final Verdict

Status: ⚠️ Request changes

Minimum required actions:

  • Preserve read_in_order_virtual_row_prefetch_window and read_in_order_use_buffering across serialized FinishSorting steps, or reject such serialized plans when non-default behavior is required.
  • Reset the per-block virtual-row interval at part boundaries.
  • Release and re-order a prefetched lane when it re-parks on a later virtual row before delivering data.
  • Fix or fail closed the ReadFromMergeTree serialized-read settings gap for per-block virtual rows.

LLVM Coverage Report

Measured on commit 042d6ed.

Metric Baseline Current Δ
Lines 88.10% 88.10% +0.00%
Functions 91.70% 91.70% +0.00%
Branches 79.50% 79.50% +0.00%

Changed lines: Changed C/C++ lines covered: 355/372 (95.43%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Aug 31, 2026
vdimir and others added 2 commits September 1, 2026 07:56
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
@clickhouse-gh

clickhouse-gh Bot commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

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_official

⚠️ 1 inconclusive

Flagged queries (1 of 22)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 1 not_sure 64 53 -17.2% <0.0001 aggregation: Q1 scans lineitem, aggregates by return flag and line status, then sorts the small result, so it never runs the read-in-order merge this PR rewrites. The query is also noisy on master.

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
  • StressHouse run: c3375ed8-13d0-4cdc-b710-8cc90caaa05a
  • MIRAI run: 326d4839-3c9c-409c-9782-ad4975e29c81
  • PR check IDs:
    • clickbench_2963143_1790972233
    • clickbench_2963149_1790972234
    • clickbench_2963166_1790972233
    • tpch_adapted_1_official_2963185_1790972234
    • tpch_adapted_1_official_2963199_1790972234
    • tpch_adapted_1_official_2963213_1790972234

vdimir and others added 3 commits September 1, 2026 15:44
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];

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.

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.

vdimir and others added 2 commits September 2, 2026 15:14
… 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]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 042d6ede4 with master 782be4dce (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.

Object file sizes

83 object files changed (+66.16 KiB total), 1 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/Transforms/VirtualRowReadAheadTransform.cpp.o new 140.42 KiB +140.42 KiB
src/CMakeFiles/dbms.dir/Processors/Merges/Algorithms/MergingSortedAlgorithm.cpp.o 3.74 MiB 3.70 MiB -38.96 KiB (-1.02%)

719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

135 translation units recompiled, 1122 s compile time in total, 134 of them have a recent master baseline.

Job report

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]>
vdimir and others added 3 commits September 17, 2026 13:49
…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]>

/// 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;

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.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Was it the case before the change when we use BufferChunksTransform?

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.

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)

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.

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

@vdimir
vdimir force-pushed the vdimir/virtual-row-read-ahead-transform branch from c849d59 to ea41437 Compare September 21, 2026 10:51
vdimir and others added 2 commits September 21, 2026 15:05
…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]>
@alexey-milovidov alexey-milovidov mentioned this pull request Sep 21, 2026
1 task done
Chunk chunk = std::move(lane.chunks.front());
lane.chunks.pop_front();
if (isVirtualRow(chunk))
lane.parked = true;

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.

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.

@vdimir
vdimir force-pushed the vdimir/virtual-row-read-ahead-transform branch from a49a5d8 to 90a7f18 Compare September 23, 2026 17:39
vdimir and others added 6 commits September 23, 2026 17:41

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. pr-improvement Pull request with some product improvements pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants