From 6520fcd61bb755a1ed8de022ce703b2d4e23cd98 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 17:12:25 -0500 Subject: [PATCH 1/7] Add a Scan API source over V2 plans whose open returns a ScanStream PlanDataSource exposes anything that lowers its data to plans over placed segments through the Scan API. Opening an unordered scan prepares each child once and cuts it into parts with part_root, queued for every clone of the returned ScanStream. Each clone drives a Run of its own on the task that polls it, one part at a time, and spawns nothing. An ordered scan runs in order on ScanDriver through the first clone polled. split returns the scan whole. Signed-off-by: Nicholas Gates Co-Authored-By: Claude Fable 5.2 --- Cargo.lock | 1 + vortex-scan/Cargo.toml | 1 + vortex-scan/src/execution/mod.rs | 1 - vortex-scan/src/source.rs | 14 +- vortex-scan/src/source/plan.rs | 404 ++++++++++++++++++++++++++ vortex-scan/src/source/plan_stream.rs | 359 +++++++++++++++++++++++ vortex-scan/src/source/tests.rs | 204 +++++++++++++ 7 files changed, 982 insertions(+), 2 deletions(-) create mode 100644 vortex-scan/src/source/plan.rs create mode 100644 vortex-scan/src/source/plan_stream.rs create mode 100644 vortex-scan/src/source/tests.rs diff --git a/Cargo.lock b/Cargo.lock index 1baac90bd38..f05a00d3e7d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -12358,6 +12358,7 @@ dependencies = [ name = "vortex-scan" version = "0.1.0" dependencies = [ + "async-channel", "async-lock", "async-trait", "bit-vec 0.10.2", diff --git a/vortex-scan/Cargo.toml b/vortex-scan/Cargo.toml index 9c1d41b1aa2..b2e0df7138b 100644 --- a/vortex-scan/Cargo.toml +++ b/vortex-scan/Cargo.toml @@ -15,6 +15,7 @@ version = { workspace = true } all-features = true [dependencies] +async-channel = { workspace = true } async-lock = { workspace = true } async-trait = { workspace = true } bit-vec = { workspace = true } diff --git a/vortex-scan/src/execution/mod.rs b/vortex-scan/src/execution/mod.rs index 577c1058e84..2bd2cd06a95 100644 --- a/vortex-scan/src/execution/mod.rs +++ b/vortex-scan/src/execution/mod.rs @@ -46,7 +46,6 @@ pub(crate) use self::chunk::ROW_BLOCK_SIZE; #[cfg(test)] pub(crate) use self::chunk::row_chunks; pub(crate) use self::chunk::rows_per_chunk; -#[cfg(test)] pub(crate) use self::chunk::scan_chunks; use self::filter::FilterPlanner; pub use self::filter::FilterPlans; diff --git a/vortex-scan/src/source.rs b/vortex-scan/src/source.rs index 08a3f38c296..34a6f819b1a 100644 --- a/vortex-scan/src/source.rs +++ b/vortex-scan/src/source.rs @@ -1,7 +1,8 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors -//! Source inputs and byte access for scans. +//! Source inputs and byte access for scans, and the [`DataSource`](crate::DataSource) that scans +//! them. use std::sync::Arc; @@ -32,3 +33,14 @@ pub struct ScanInput { /// State shared by repeated scans of this input. pub cache: Option, } + +mod plan; +mod plan_stream; + +pub use plan::FilePruner; +pub use plan::PlanChild; +pub use plan::PlanDataSource; +pub use plan::PlanSplitter; + +#[cfg(test)] +mod tests; diff --git a/vortex-scan/src/source/plan.rs b/vortex-scan/src/source/plan.rs new file mode 100644 index 00000000000..b4926a083b3 --- /dev/null +++ b/vortex-scan/src/source/plan.rs @@ -0,0 +1,404 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! [`PlanDataSource`]: a [`DataSource`] over plan children, scanned by the planner-driven +//! executor. +//! +//! Nothing here is about one format. A child is a [`ScanInput`], a plan over placed segments, +//! from a Vortex file, a Parquet file whose column chunks are segments, or any store that lowers +//! its data to plans. + +use std::any::Any; +use std::num::NonZeroUsize; +use std::ops::Range; +use std::sync::Arc; + +use async_trait::async_trait; +use futures::StreamExt; +use futures::stream; +use vortex_array::dtype::DType; +use vortex_array::dtype::FieldPath; +use vortex_array::expr::BoundExpression; +use vortex_array::expr::stats::Precision; +use vortex_array::stats::StatsSet; +use vortex_array::stream::SendableArrayStream; +use vortex_error::VortexResult; +use vortex_session::VortexSession; + +use super::ScanInput; +use super::plan_stream; +use crate::DataSource; +use crate::DataSourceScan; +use crate::DataSourceScanRef; +use crate::Partition; +use crate::PartitionRef; +use crate::PartitionStream; +use crate::ScanRequest; +use crate::prepare::ScanBuilder; +use crate::selection::Selection; +use crate::stream::ScanStream; + +/// Whether a child's own statistics, such as a file footer's, prove a filter, bound to the +/// child's dtype, false for every row of the child. +pub type FilePruner = Arc VortexResult + Send + Sync>; + +/// The row boundaries an opened scan cuts a child's work at, for the scan's projection and filter, +/// both bound to the child's dtype: ascending, covering the child's rows. A Vortex file gives its +/// layout splits over the fields the scan reads, as a V1 scan of the same fields cuts it. +pub type PlanSplitter = + Arc) -> VortexResult> + Send + Sync>; + +/// A child of a [`PlanDataSource`]: its [`ScanInput`] and what the source knows of it without +/// reading payloads. +#[derive(Clone)] +pub struct PlanChild { + input: ScanInput, + row_count: Option, + splitter: Option, + pruner: Option, +} + +impl PlanChild { + /// A child scanning `input`. Without a cache, the input gets a fresh one that every scan of + /// the child shares. + pub fn new(mut input: ScanInput) -> Self { + input.cache.get_or_insert_default(); + Self { + input, + row_count: None, + splitter: None, + pruner: None, + } + } + + /// Sets the child's exact row count. Without it, the source lowers the child's root plan to + /// learn the count when a scan needs it. + pub fn with_row_count(mut self, row_count: u64) -> Self { + self.row_count = Some(row_count); + self + } + + /// Sets fixed row boundaries that an opened scan cuts the child's work at, whatever it reads, + /// ascending and covering the child's rows. Without boundaries, the work is cut on the scan's + /// chunk grid. + pub fn with_splits(self, splits: Arc<[u64]>) -> Self { + self.with_splitter(Arc::new(move |_, _| Ok(splits.to_vec()))) + } + + /// Sets how an opened scan finds the row boundaries to cut the child's work at, from the + /// fields it reads. Without boundaries, the work is cut on the scan's chunk grid. + pub fn with_splitter(mut self, splitter: PlanSplitter) -> Self { + self.splitter = Some(splitter); + self + } + + /// Sets how the child's statistics rule out a scan's filter, so a scan they rule out reads + /// nothing of the child. + pub fn with_pruner(mut self, pruner: FilePruner) -> Self { + self.pruner = Some(pruner); + self + } + + /// The input this child scans. + pub fn input(&self) -> &ScanInput { + &self.input + } + + /// The child's rows, from the row count when set, else from its root plan. + fn rows(&self) -> VortexResult { + match self.row_count { + Some(rows) => Ok(rows), + None => Ok(self.input.root.get()?.row_count()), + } + } + + /// The bytes of all of the child's segments. + fn byte_size(&self) -> u64 { + self.input + .locations + .iter() + .map(|location| u64::from(location.length)) + .sum() + } + + /// The boundaries an opened scan of `projection` and `filter` cuts the child's work at, if the + /// child has them. + pub(super) fn splits( + &self, + projection: &BoundExpression, + filter: Option<&BoundExpression>, + ) -> VortexResult>> { + self.splitter + .as_ref() + .map(|splitter| splitter(projection, filter)) + .transpose() + } + + fn is_pruned(&self, filter: Option<&BoundExpression>) -> VortexResult { + match (&self.pruner, filter) { + (Some(pruner), Some(filter)) => pruner(filter), + _ => Ok(false), + } + } +} + +/// A [`DataSource`] over plan children, scanned by the planner-driven executor. +/// +/// This is the standard way to expose sources that can lower their data to plans over placed +/// segments, whatever their format. Every scan of a child shares the child's [`ScanCache`], so +/// scans that overlap in time plan it once. +/// +/// A scan's request applies to each child: its row range and row selection are in the child's +/// own rows, and its `partition_range` and `partition_selection` select children by ordinal. A +/// scan reads its children in order. +/// +/// [`split`](DataSourceScan::split) returns a scan whole. [`open`](DataSourceScan::open) runs it +/// on V2's planners and [`Run`](crate::planning::driver::Run) driver; see `plan_stream.rs`. A +/// scan's one partition reads its opened stream. +/// +/// [`ScanCache`]: crate::prepare::ScanCache +#[derive(Clone)] +pub struct PlanDataSource { + session: VortexSession, + dtype: DType, + children: Arc<[PlanChild]>, + row_count: Precision, + byte_size: Precision, +} + +impl PlanDataSource { + /// A source scanning one `input` with `session`. + pub fn new(session: VortexSession, input: ScanInput) -> Self { + Self::from_child(session, PlanChild::new(input)) + } + + /// A source scanning one `child` with `session`. + pub fn from_child(session: VortexSession, child: PlanChild) -> Self { + let dtype = child.input.dtype.clone(); + Self::from_children(session, dtype, vec![child]) + } + + /// A source scanning `children` in order with `session`. Every child must have `dtype`. + pub fn from_children(session: VortexSession, dtype: DType, children: Vec) -> Self { + let row_count = children + .iter() + .map(|child| child.row_count) + .sum::>() + .map_or(Precision::Absent, Precision::exact); + let byte_size = Precision::inexact(children.iter().map(PlanChild::byte_size).sum()); + Self { + session, + dtype, + children: children.into(), + row_count, + byte_size, + } + } + + /// Sets the exact row count of a one-child source, which scans report. + pub fn with_row_count(mut self, row_count: u64) -> Self { + if let [child] = &*self.children { + self.children = Arc::new([child.clone().with_row_count(row_count)]); + } + self.row_count = Precision::exact(row_count); + self + } + + /// Sets an estimate of the source's byte size. + pub fn with_byte_size(mut self, byte_size: Precision) -> Self { + self.byte_size = byte_size; + self + } + + /// The children this source scans, in order. + pub fn children(&self) -> &[PlanChild] { + &self.children + } + + /// The session scans of this source run with. + pub fn session(&self) -> &VortexSession { + &self.session + } +} + +#[async_trait] +impl DataSource for PlanDataSource { + fn dtype(&self) -> &DType { + &self.dtype + } + + fn row_count(&self) -> Precision { + self.row_count + } + + fn byte_size(&self) -> Precision { + self.byte_size + } + + async fn scan(&self, request: ScanRequest) -> VortexResult { + let projection = request.projection.bind(&self.dtype)?.optimize_recursive()?; + let filter = request + .filter + .map(|filter| filter.bind(&self.dtype)?.optimize_recursive()) + .transpose()?; + let mut units = Vec::new(); + let scans_rows = + request.limit != Some(0) && !request.row_range.as_ref().is_some_and(Range::is_empty); + for (ordinal, child) in self.children.iter().enumerate().filter(|_| scans_rows) { + let index = ordinal as u64; + let selected = request + .partition_range + .as_ref() + .is_none_or(|range| range.contains(&index)) + && request + .partition_selection + .row_count_in_range(&(index..index + 1)) + == 1; + if !selected || child.is_pruned(filter.as_ref())? { + continue; + } + let rows = child + .row_count + .map(|count| clamp_rows(request.row_range.clone(), count)); + if rows.as_ref().is_some_and(Range::is_empty) { + continue; + } + units.push(Unit { + child: ordinal, + rows, + }); + } + let state = ScanState { + session: self.session.clone(), + children: Arc::clone(&self.children), + dtype: projection.dtype().clone(), + projection, + filter, + row_range: request.row_range, + selection: request.selection, + ordered: request.ordered, + limit: request.limit, + }; + Ok(Box::new(PlanScan { + state: Arc::new(state), + units, + })) + } + + async fn field_statistics(&self, _field_path: &FieldPath) -> VortexResult { + Ok(StatsSet::default()) + } +} + +/// The request's `rows`, or all of them, clamped to a child of `count` rows. +fn clamp_rows(rows: Option>, count: u64) -> Range { + let rows = rows.unwrap_or(0..count); + let end = rows.end.min(count); + rows.start.min(end)..end +} + +/// What every piece and stream of one scan of a [`PlanDataSource`] shares. +pub(super) struct ScanState { + pub(super) session: VortexSession, + children: Arc<[PlanChild]>, + /// The dtype of the scan's output. + pub(super) dtype: DType, + pub(super) projection: BoundExpression, + pub(super) filter: Option, + row_range: Option>, + selection: Selection, + pub(super) ordered: bool, + pub(super) limit: Option, +} + +impl ScanState { + /// The source's child at `ordinal`. + pub(super) fn child(&self, ordinal: usize) -> &PlanChild { + &self.children[ordinal] + } + + /// The rows of `unit` this scan reads: its own, or else the request's row range clamped to + /// its child. + pub(super) fn unit_rows(&self, unit: &Unit) -> VortexResult> { + match &unit.rows { + Some(rows) => Ok(rows.clone()), + None => Ok(clamp_rows( + self.row_range.clone(), + self.child(unit.child).rows()?, + )), + } + } + + /// A builder of this scan's `rows` of `child`. + pub(super) fn builder(&self, child: &PlanChild, rows: Range) -> ScanBuilder { + ScanBuilder::new(self.session.clone(), child.input.clone()) + .with_projection(self.projection.clone()) + .with_some_filter(self.filter.clone()) + .with_selection(self.selection.clone()) + .with_row_range(rows) + } +} + +/// Rows of one child that a scan reads. +#[derive(Clone, Debug)] +pub(super) struct Unit { + /// The child's ordinal in the source. + pub(super) child: usize, + /// The child's rows, or `None` for the request's rows of a child whose row count is not known + /// until its plan is lowered. + pub(super) rows: Option>, +} + +/// A scan of a [`PlanDataSource`], or a piece split from one. +struct PlanScan { + state: Arc, + /// The scan's units, in child and row order. + units: Vec, +} + +impl DataSourceScan for PlanScan { + fn dtype(&self) -> &DType { + &self.state.dtype + } + + fn split(self: Box, _n: NonZeroUsize) -> VortexResult> { + Ok(vec![self]) + } + + fn open(self: Box) -> VortexResult { + plan_stream::open(self.state, self.units) + } + + fn partition_count(&self) -> Precision { + Precision::exact(1usize) + } + + fn partitions(self: Box) -> PartitionStream { + stream::iter([Ok(Box::new(PlanPartition(self)) as PartitionRef)]).boxed() + } +} + +/// A scan of a [`PlanDataSource`] as its one partition, which reads the scan's opened stream. +struct PlanPartition(Box); + +impl Partition for PlanPartition { + fn as_any(&self) -> &dyn Any { + self + } + + fn index(&self) -> usize { + 0 + } + + fn row_count(&self) -> Precision { + Precision::Absent + } + + fn byte_size(&self) -> Precision { + Precision::Absent + } + + fn execute(self: Box) -> VortexResult { + Ok(Box::pin(self.0.open()?)) + } +} diff --git a/vortex-scan/src/source/plan_stream.rs b/vortex-scan/src/source/plan_stream.rs new file mode 100644 index 00000000000..bd58a2da7cc --- /dev/null +++ b/vortex-scan/src/source/plan_stream.rs @@ -0,0 +1,359 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! The stream of an opened [`PlanDataSource`](super::PlanDataSource) scan: V2's planners and +//! [`Run`] driver behind [`ScanStream`]. +//! +//! An unordered scan prepares each child once and runs its [`part_root`], which cuts the child +//! into parts: the rows between the child's splits for the fields the scan reads, such as a +//! file's layout splits, or the scan's chunks for a child without splits. The parts go into one +//! queue that every clone of the stream takes from. Each clone owns a [`Run`], driven on the task +//! that polls the clone, and runs one part on it at a time: the part's chunks run side by side, +//! so one chunk's reads overlap another's compute, batches are returned as they are produced, and +//! reads are awaited with [`Run::poll_completion`]. Nothing is spawned, so a host that polls a +//! clone with `block_on` runs the scan's compute on its own thread. +//! +//! With a dynamic filter, such as the bound a top-N pushes down, a child's root prunes the child as +//! a whole before it cuts parts, which reads zone maps. Opening reads nothing, so such a root is +//! queued work too: the first clone to take it runs it and queues its parts. +//! +//! An ordered scan returns its rows in order through the first clone to be polled, running one +//! child after another on [`ScanDriver`], which keeps a scan's chunks in order. Later clones +//! return nothing. A host that reads an ordered scan in parallel +//! [splits](crate::DataSourceScan::split) it first. +//! +//! A limit is one [`RowLimit`] for the whole stream: clones stop taking parts once it is spent, +//! and each clone's output is trimmed to it. + +use std::future; +use std::iter; +use std::ops::Range; +use std::sync::Arc; +use std::sync::atomic::AtomicU64; +use std::sync::atomic::Ordering; + +use async_channel::Receiver; +use async_channel::Sender; +use futures::FutureExt; +use futures::StreamExt; +use futures::future::BoxFuture; +use futures::stream; +use futures::stream::BoxStream; +use parking_lot::Mutex; +use vortex_array::ArrayRef; +use vortex_array::scalar_fn::fns::dynamic::DynamicExprUpdates; +use vortex_error::VortexExpect; +use vortex_error::VortexResult; +use vortex_io::request::IoService; +use vortex_io::session::RuntimeSessionExt; + +use super::plan::ScanState; +use super::plan::Unit; +use crate::execution::driver::ScanDriver; +use crate::execution::scan_chunks; +use crate::limit::RowLimit; +use crate::limit::limit_rows; +use crate::planning::driver::Progress; +use crate::planning::driver::Run; +use crate::planning::planner::Planner; +use crate::planning::planner::WorkScope; +use crate::prepare::PreparedScan; +use crate::prepare::part_root; +use crate::stream::ScanStream; + +/// Opens the stream of the scan's `units`. +pub(super) fn open(state: Arc, units: Vec) -> VortexResult { + let dtype = state.dtype.clone(); + let limit = state.limit.map(RowLimit::new); + if state.ordered { + let arrays = Arc::new(Mutex::new(Some(in_order(state, units)))); + return Ok(ScanStream::new(dtype, move || { + let arrays = arrays + .lock() + .take() + .unwrap_or_else(|| stream::empty().boxed()); + limited(arrays, limit.clone()) + })); + } + + let (sender, receiver) = async_channel::unbounded(); + let mut total_rows = 0; + for unit in &units { + let rows = state.unit_rows(unit)?; + if rows.is_empty() { + continue; + } + total_rows += rows.end - rows.start; + let (child, root, dynamic) = prepare(&state, unit, rows)?; + let parts = run_root(child, root); + if dynamic { + send(&sender, Work::Root(parts, sender.clone())); + continue; + } + let work = parts + .now_or_never() + .vortex_expect("a root that only cuts parts reads nothing")?; + for work in work { + send(&sender, work); + } + } + // Only queued roots hold senders now, so the queue closes once it is empty and no root is + // left that could add to it. + drop(sender); + + let queue = Arc::new(Queue { + receiver, + total_rows, + rows_taken: AtomicU64::new(0), + }); + let progress = Arc::clone(&queue); + Ok(ScanStream::new(dtype, move || { + let worker = Worker { + queue: Arc::clone(&queue), + limit: limit.clone(), + run: Run::new(), + child: None, + }; + let arrays = stream::unfold(Some(worker), |worker| async move { + let mut worker = worker?; + match worker.next_array().await { + Ok(Some(array)) => Some((Ok(array), Some(worker))), + Ok(None) => None, + Err(err) => Some((Err(err), None)), + } + }) + .boxed(); + limited(arrays, limit.clone()) + }) + .with_progress(move || progress.progress())) +} + +/// One child's prepared scan, shared by the parts of it that clones run. +struct PreparedChild { + rows: Range, + io: Arc, +} + +/// A part of a child: the planner its root spawned for some of its rows. +struct Part { + child: Arc, + scope: WorkScope, + planner: Box, +} + +/// Prepares the scan of `rows` of the unit's child once and composes its root, returning whether +/// the root reads before it spawns parts. +fn prepare( + state: &ScanState, + unit: &Unit, + rows: Range, +) -> VortexResult<(Arc, Box, bool)> { + let child = state.child(unit.child); + let splits = child.splits(&state.projection, state.filter.as_ref())?; + let scan = Arc::new(state.builder(child, rows).prepare()?); + let splits = splits.unwrap_or_else(|| chunk_bounds(&scan)); + let dynamic = state + .filter + .as_ref() + .is_some_and(|filter| DynamicExprUpdates::new(filter).is_some()); + let root = part_root(&scan, &splits, dynamic); + let prepared = PreparedChild { + rows: scan.rows().clone(), + io: scan.io(), + }; + Ok((Arc::new(prepared), root, dynamic && scan.filter().is_some())) +} + +/// The boundaries of `scan`'s chunks, which cut the work of a child without splits of its own. +fn chunk_bounds(scan: &PreparedScan) -> Vec { + let rows = scan.rows().clone(); + let chunks = scan_chunks(rows.clone(), scan.chunk_rows); + iter::once(rows.start) + .chain(chunks.iter().map(|chunk| chunk.end)) + .collect() +} + +/// Runs a child's root on a run of its own, awaiting only its reads, and returns the work it +/// produces, in row order: the parts it spawns, and any batch it returns itself. +fn run_root( + child: Arc, + root: Box, +) -> BoxFuture<'static, VortexResult>> { + async move { + let mut run = Run::new(); + let scope = WorkScope { + file_ordinal: 0, + rows: child.rows.clone(), + }; + run.admit(root, scope, child.io.session()); + let mut work = Vec::new(); + loop { + match run.advance()? { + Progress::Spawn(scope, planner) => work.push(Work::Part(Part { + child: Arc::clone(&child), + scope, + planner, + })), + Progress::Batch(batch) => work.push(Work::Batch(batch.array)), + Progress::RootDone(_) if run.live_roots() > 0 => {} + Progress::RootDone(_) | Progress::Idle => break, + Progress::Waiting => future::poll_fn(|cx| run.poll_completion(cx)).await?, + } + } + Ok(work) + } + .boxed() +} + +/// A unit of work in the queue of an unordered scan. +enum Work { + Part(Part), + /// A batch a root returned itself. + Batch(ArrayRef), + /// A root that reads before it spawns parts, and the queue to send its parts to. The sender + /// keeps the queue open until they are in it. + Root(BoxFuture<'static, VortexResult>>, Sender), +} + +fn send(sender: &Sender, work: Work) { + // The queue is unbounded and closes only once every clone is dropped, when the work is moot. + drop(sender.try_send(work)); +} + +/// The queue of an unordered scan, which every clone of its stream takes from. +struct Queue { + receiver: Receiver, + /// The rows of the scan's units. + total_rows: u64, + /// The rows of the parts clones have taken. + rows_taken: AtomicU64, +} + +impl Queue { + /// The fraction of the scan's rows whose parts clones have taken. Pruning can leave rows that + /// no part covers, so a queue with nothing left to take has made all of its progress. + fn progress(&self) -> f64 { + if self.total_rows == 0 || self.is_drained() { + return 1.0; + } + (self.rows_taken.load(Ordering::Relaxed) as f64 / self.total_rows as f64).min(1.0) + } + + /// Whether the queue is empty and no root is left that could add to it. + fn is_drained(&self) -> bool { + self.receiver.is_empty() && self.receiver.sender_count() == 0 + } +} + +impl Drop for Queue { + fn drop(&mut self) { + // Queued roots hold senders of the queue itself; drain them so it can be freed. + self.receiver.close(); + while self.receiver.try_recv().is_ok() {} + } +} + +/// One clone's worker: a run of its own, fed one part at a time from the scan's queue, and driven +/// on the task that polls the clone. +struct Worker { + queue: Arc, + limit: Option, + run: Run, + /// The child of the part live on the run, whose I/O the planners that part spawns read through. + child: Option>, +} + +impl Worker { + /// The worker's next array, or `None` once the scan has no more work for it. + async fn next_array(&mut self) -> VortexResult> { + loop { + if self.run.live_roots() == 0 { + if self.limit.as_ref().is_some_and(RowLimit::is_exhausted) { + return Ok(None); + } + match self.take().await? { + None => return Ok(None), + Some(Taken::Batch(array)) => return Ok(Some(array)), + Some(Taken::Part(part)) => { + self.run + .admit(part.planner, part.scope, part.child.io.session()); + self.child = Some(part.child); + } + } + } + match self.run.advance()? { + Progress::Batch(batch) => return Ok(Some(batch.array)), + Progress::Spawn(scope, planner) => { + let child = self + .child + .as_ref() + .vortex_expect("a planner is spawned by a live part"); + self.run.admit(planner, scope, child.io.session()); + } + Progress::RootDone(_) | Progress::Idle => {} + Progress::Waiting => { + future::poll_fn(|cx| self.run.poll_completion(cx)).await?; + } + } + } + } + + /// Takes the next part or batch from the scan's queue, running the roots it finds there + /// first, or `None` once the queue is closed and empty. + async fn take(&mut self) -> VortexResult> { + loop { + let Ok(work) = self.queue.receiver.recv().await else { + return Ok(None); + }; + match work { + Work::Part(part) => { + self.queue.rows_taken.fetch_add( + part.scope.rows.end - part.scope.rows.start, + Ordering::Relaxed, + ); + return Ok(Some(Taken::Part(part))); + } + Work::Batch(array) => return Ok(Some(Taken::Batch(array))), + Work::Root(work, sender) => { + for work in work.await? { + send(&sender, work); + } + } + } + } + } +} + +/// What a worker takes from the queue. +enum Taken { + Part(Part), + Batch(ArrayRef), +} + +/// The arrays of an ordered scan: each unit's rows in order, one unit after another. +fn in_order(state: Arc, units: Vec) -> BoxStream<'static, VortexResult> { + stream::iter(units) + .flat_map(move |unit| { + let rows = match state.unit_rows(&unit) { + Ok(rows) => rows, + Err(err) => return stream::once(future::ready(Err(err))).boxed(), + }; + if rows.is_empty() { + return stream::empty().boxed(); + } + ScanDriver::new(state.session.handle(), 1, true) + .run(state.builder(state.child(unit.child), rows)) + }) + .boxed() +} + +/// `arrays`, trimmed to the scan's limit. +fn limited( + arrays: BoxStream<'static, VortexResult>, + limit: Option, +) -> BoxStream<'static, VortexResult> { + match limit { + Some(limit) => limit_rows(arrays, limit), + None => arrays, + } +} diff --git a/vortex-scan/src/source/tests.rs b/vortex-scan/src/source/tests.rs new file mode 100644 index 00000000000..daeb32082b5 --- /dev/null +++ b/vortex-scan/src/source/tests.rs @@ -0,0 +1,204 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +use std::ops::Range; +use std::sync::Arc; + +use futures::TryStreamExt; +use futures::future::try_join_all; +use roaring::RoaringTreemap; +use rstest::rstest; +use vortex_array::ArrayRef; +use vortex_array::IntoArray; +use vortex_array::VortexSessionExecute; +use vortex_array::arrays::ChunkedArray; +use vortex_array::arrays::PrimitiveArray; +use vortex_array::assert_arrays_eq; +use vortex_array::expr::checked_add; +use vortex_array::expr::gt; +use vortex_array::expr::lit; +use vortex_array::expr::root; +use vortex_buffer::Buffer; +use vortex_error::VortexResult; +use vortex_error::vortex_bail; +use vortex_io::session::RuntimeSessionExt; +use vortex_session::VortexSession; + +use super::PlanDataSource; +use super::ScanInput; +use super::SegmentFuture; +use super::SegmentId; +use super::SegmentSource; +use crate::DataSource; +use crate::PartitionRef; +use crate::ScanRequest; +use crate::execution::pipeline::synthetic::RowSource; +use crate::plan::LazyPlanRef; +use crate::selection::Selection; + +struct NoSegments; + +impl SegmentSource for NoSegments { + fn request(&self, _id: SegmentId) -> SegmentFuture { + Box::pin(async { vortex_bail!("an in-memory source must not request bytes") }) + } +} + +fn source() -> PlanDataSource { + source_of(20) +} + +fn source_of(row_count: u64) -> PlanDataSource { + let plan = RowSource::plan(row_count, vec![4, 7, 9], None, false); + let input = ScanInput { + dtype: plan.dtype().clone(), + root: LazyPlanRef::ready(plan), + locations: Arc::new([]), + segments: Arc::new(NoSegments), + cache: None, + }; + PlanDataSource::new(VortexSession::empty().with_tokio(), input).with_row_count(row_count) +} + +async fn partitions(request: ScanRequest) -> VortexResult> { + partitions_of(&source(), request).await +} + +async fn partitions_of( + source: &PlanDataSource, + request: ScanRequest, +) -> VortexResult> { + source.scan(request).await?.partitions().try_collect().await +} + +async fn collect(partitions: Vec) -> VortexResult { + let dtype = source().dtype().clone(); + let mut arrays = Vec::new(); + for partition in partitions { + let batches: Vec = partition.execute()?.try_collect().await?; + arrays.extend(batches); + } + Ok(ChunkedArray::try_new(arrays, dtype)?.into_array()) +} + +#[rstest] +#[case::unordered(false)] +#[case::ordered(true)] +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn execute_applies_the_request(#[case] ordered: bool) -> VortexResult<()> { + let partitions = partitions(ScanRequest { + projection: checked_add(root(), lit(100_u64)), + filter: Some(gt(root(), lit(5_u64))), + row_range: Some(2..18), + ordered, + ..Default::default() + }) + .await?; + assert_eq!(partitions.len(), 1); + let mut ctx = VortexSession::empty().create_execution_ctx(); + let actual = collect(partitions) + .await? + .execute::(&mut ctx)?; + let mut values = actual.as_slice::().to_vec(); + if !ordered { + values.sort_unstable(); + } + assert_eq!(values, (106_u64..118).collect::>()); + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn execute_applies_the_limit() -> VortexResult<()> { + let partitions = partitions(ScanRequest { + filter: Some(gt(root(), lit(5_u64))), + ordered: true, + limit: Some(5), + ..Default::default() + }) + .await?; + assert_arrays_eq!( + collect(partitions).await?, + Buffer::from_iter(6_u64..11).into_array(), + &mut VortexSession::empty().create_execution_ctx() + ); + Ok(()) +} + +/// A request that selects no rows of the source scans one partition, which reads nothing. +#[rstest] +#[case::zero_limit(ScanRequest { limit: Some(0), ..Default::default() })] +#[case::empty_rows(ScanRequest { row_range: Some(30..40), ..Default::default() })] +#[case::other_units(ScanRequest { partition_range: Some(1..4), ..Default::default() })] +#[case::unit_excluded(ScanRequest { + partition_selection: Selection::ExcludeRoaring(RoaringTreemap::from_iter([0_u64])), + ..Default::default() +})] +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn requests_without_rows_read_nothing(#[case] request: ScanRequest) -> VortexResult<()> { + let scan = source().scan(request).await?; + let partitions: Vec = scan.partitions().try_collect().await?; + assert_eq!(collect(partitions).await?.len(), 0); + Ok(()) +} + +/// The sorted values of every partition's output. +async fn sorted_values(partitions: Vec) -> VortexResult> { + let mut ctx = VortexSession::empty().create_execution_ctx(); + let mut values = collect(partitions) + .await? + .execute::(&mut ctx)? + .as_slice::() + .to_vec(); + values.sort_unstable(); + Ok(values) +} + +/// Selecting the source's unit, by range or by selection, returns its one partition. +#[rstest] +#[case::range(Some(0..1), Selection::All)] +#[case::wide_range(Some(0..5), Selection::All)] +#[case::selection(None, Selection::IncludeRoaring(RoaringTreemap::from_iter([0_u64, 3])))] +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn selecting_the_unit_returns_its_partition( + #[case] partition_range: Option>, + #[case] partition_selection: Selection, +) -> VortexResult<()> { + let partitions = partitions(ScanRequest { + partition_selection, + partition_range, + ..Default::default() + }) + .await?; + assert_eq!(partitions.len(), 1); + assert_eq!(partitions[0].index(), 0); + assert_eq!( + sorted_values(partitions).await?, + (0..20).collect::>() + ); + Ok(()) +} + +/// Clones of an opened scan share its parts: polled together, they return every row once. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn clones_share_the_scan() -> VortexResult<()> { + let stream = source_of(100_000) + .scan(ScanRequest::default()) + .await? + .open()?; + let clones = [stream.clone(), stream.clone(), stream.clone()]; + let batches = try_join_all( + clones + .into_iter() + .map(|clone| clone.try_collect::>()), + ) + .await?; + assert_eq!(stream.progress(), Some(1.0)); + let mut ctx = VortexSession::empty().create_execution_ctx(); + let mut values = Vec::new(); + for batch in batches.into_iter().flatten() { + values.extend_from_slice(batch.execute::(&mut ctx)?.as_slice::()); + } + values.sort_unstable(); + assert_eq!(values, (0..100_000).collect::>()); + Ok(()) +} From 5f32c1bf53517c0923ed107109b18e5e7b74104e Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 17:28:18 -0500 Subject: [PATCH 2/7] Name the sum type of a plan source's byte size Signed-off-by: Nicholas Gates Co-Authored-By: Claude Opus 5.5 --- vortex-scan/src/source/plan.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vortex-scan/src/source/plan.rs b/vortex-scan/src/source/plan.rs index b4926a083b3..c70e5f410fb 100644 --- a/vortex-scan/src/source/plan.rs +++ b/vortex-scan/src/source/plan.rs @@ -185,7 +185,7 @@ impl PlanDataSource { .map(|child| child.row_count) .sum::>() .map_or(Precision::Absent, Precision::exact); - let byte_size = Precision::inexact(children.iter().map(PlanChild::byte_size).sum()); + let byte_size = Precision::inexact(children.iter().map(PlanChild::byte_size).sum::()); Self { session, dtype, From 9411ff75ab532c1d5252cbe2cae63ed4e26ff702 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 20:55:34 -0500 Subject: [PATCH 3/7] Cut a V2 plan scan's parts in scan, so open reads nothing A dynamic filter's root reads zone maps before it cuts a child into parts. Running it in the async scan, which the host awaits, means opening only queues the parts, and no clone of the stream waits on another for its first work. The scan's work is known before it is opened, so the queue is a plain list. Signed-off-by: Nicholas Gates Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 1 - vortex-scan/Cargo.toml | 1 - vortex-scan/src/lib.rs | 5 + vortex-scan/src/source/plan.rs | 15 +- vortex-scan/src/source/plan_stream.rs | 228 +++++++++++--------------- 5 files changed, 116 insertions(+), 134 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index f05a00d3e7d..1baac90bd38 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -12358,7 +12358,6 @@ dependencies = [ name = "vortex-scan" version = "0.1.0" dependencies = [ - "async-channel", "async-lock", "async-trait", "bit-vec 0.10.2", diff --git a/vortex-scan/Cargo.toml b/vortex-scan/Cargo.toml index b2e0df7138b..9c1d41b1aa2 100644 --- a/vortex-scan/Cargo.toml +++ b/vortex-scan/Cargo.toml @@ -15,7 +15,6 @@ version = { workspace = true } all-features = true [dependencies] -async-channel = { workspace = true } async-lock = { workspace = true } async-trait = { workspace = true } bit-vec = { workspace = true } diff --git a/vortex-scan/src/lib.rs b/vortex-scan/src/lib.rs index d693b1d3bb8..aacdd3de337 100644 --- a/vortex-scan/src/lib.rs +++ b/vortex-scan/src/lib.rs @@ -222,6 +222,11 @@ pub type DataSourceScanRef = Box; /// order or a limit, on the [`ScanRequest`], and the source decides what the pieces are and how /// they run. /// +/// A source does the reads it needs to know a scan's units of work, such as pruning against zone +/// maps before cutting the scan into pieces, in the async [`DataSource::scan`], which the host +/// awaits. [`split`](Self::split) and [`open`](Self::open) are synchronous and read nothing, so +/// no clone of an opened stream waits on another for its first work. +/// /// A scan never starts threads. Its work may run as tasks on the session's runtime, which the /// host owns. pub trait DataSourceScan: 'static + Send { diff --git a/vortex-scan/src/source/plan.rs b/vortex-scan/src/source/plan.rs index c70e5f410fb..d65fcf16ba2 100644 --- a/vortex-scan/src/source/plan.rs +++ b/vortex-scan/src/source/plan.rs @@ -152,6 +152,9 @@ impl PlanChild { /// own rows, and its `partition_range` and `partition_selection` select children by ordinal. A /// scan reads its children in order. /// +/// Making an unordered scan does the reads it needs to know its units of work: it prepares each +/// child and cuts it into parts, which for a dynamic filter reads zone maps. +/// [`split`](DataSourceScan::split) and [`open`](DataSourceScan::open) read nothing. /// [`split`](DataSourceScan::split) returns a scan whole. [`open`](DataSourceScan::open) runs it /// on V2's planners and [`Run`](crate::planning::driver::Run) driver; see `plan_stream.rs`. A /// scan's one partition reads its opened stream. @@ -279,9 +282,17 @@ impl DataSource for PlanDataSource { ordered: request.ordered, limit: request.limit, }; + // An unordered scan's parts are its units of work, and cutting them can read zone maps, + // so it happens here, where the host awaits the scan, and opening reads nothing. + let planned = if state.ordered { + None + } else { + Some(plan_stream::plan(&state, &units).await?) + }; Ok(Box::new(PlanScan { state: Arc::new(state), units, + planned, })) } @@ -354,6 +365,8 @@ struct PlanScan { state: Arc, /// The scan's units, in child and row order. units: Vec, + /// The parts of an unordered scan, cut when the scan was made. + planned: Option, } impl DataSourceScan for PlanScan { @@ -366,7 +379,7 @@ impl DataSourceScan for PlanScan { } fn open(self: Box) -> VortexResult { - plan_stream::open(self.state, self.units) + plan_stream::open(self.state, self.units, self.planned) } fn partition_count(&self) -> Precision { diff --git a/vortex-scan/src/source/plan_stream.rs b/vortex-scan/src/source/plan_stream.rs index bd58a2da7cc..ef2b3e7f996 100644 --- a/vortex-scan/src/source/plan_stream.rs +++ b/vortex-scan/src/source/plan_stream.rs @@ -4,18 +4,21 @@ //! The stream of an opened [`PlanDataSource`](super::PlanDataSource) scan: V2's planners and //! [`Run`] driver behind [`ScanStream`]. //! -//! An unordered scan prepares each child once and runs its [`part_root`], which cuts the child -//! into parts: the rows between the child's splits for the fields the scan reads, such as a -//! file's layout splits, or the scan's chunks for a child without splits. The parts go into one -//! queue that every clone of the stream takes from. Each clone owns a [`Run`], driven on the task -//! that polls the clone, and runs one part on it at a time: the part's chunks run side by side, -//! so one chunk's reads overlap another's compute, batches are returned as they are produced, and -//! reads are awaited with [`Run::poll_completion`]. Nothing is spawned, so a host that polls a -//! clone with `block_on` runs the scan's compute on its own thread. +//! When an unordered scan is made, it prepares each child once and runs its [`part_root`], which +//! cuts the child into parts: the rows between the child's splits for the fields the scan reads, +//! such as a file's layout splits, or the scan's chunks for a child without splits. With a dynamic +//! filter, such as the bound a top-N pushes down, the root first prunes the child as a whole +//! against the bound as it stands, which reads zone maps. Those are the reads the scan needs to +//! know its units of work, so they run in the async [`scan`](crate::DataSource::scan), which the +//! host awaits. Opening the scan reads nothing: it only queues the parts, so no clone waits on +//! another for its work. Each part prunes again against the bound as it stands when a clone takes +//! it. //! -//! With a dynamic filter, such as the bound a top-N pushes down, a child's root prunes the child as -//! a whole before it cuts parts, which reads zone maps. Opening reads nothing, so such a root is -//! queued work too: the first clone to take it runs it and queues its parts. +//! Every clone of the stream takes parts from the one queue. Each clone owns a [`Run`], driven on +//! the task that polls the clone, and runs one part on it at a time: the part's chunks run side by +//! side, so one chunk's reads overlap another's compute, batches are returned as they are +//! produced, and reads are awaited with [`Run::poll_completion`]. Nothing is spawned, so a host +//! that polls a clone with `block_on` runs the scan's compute on its own thread. //! //! An ordered scan returns its rows in order through the first clone to be polled, running one //! child after another on [`ScanDriver`], which keeps a scan's chunks in order. Later clones @@ -25,18 +28,16 @@ //! A limit is one [`RowLimit`] for the whole stream: clones stop taking parts once it is spent, //! and each clone's output is trimmed to it. +use std::collections::VecDeque; use std::future; use std::iter; use std::ops::Range; use std::sync::Arc; +use std::sync::atomic::AtomicBool; use std::sync::atomic::AtomicU64; use std::sync::atomic::Ordering; -use async_channel::Receiver; -use async_channel::Sender; -use futures::FutureExt; use futures::StreamExt; -use futures::future::BoxFuture; use futures::stream; use futures::stream::BoxStream; use parking_lot::Mutex; @@ -61,8 +62,36 @@ use crate::prepare::PreparedScan; use crate::prepare::part_root; use crate::stream::ScanStream; -/// Opens the stream of the scan's `units`. -pub(super) fn open(state: Arc, units: Vec) -> VortexResult { +/// The parts of an unordered scan, cut when the scan is made. +pub(super) struct Planned { + work: Vec, + /// The rows of the scan's units. + total_rows: u64, +} + +/// Prepares each of the scan's `units` once and runs its root, awaiting the zone maps a dynamic +/// filter's root reads, and returns the work the roots produce, in unit and row order. +pub(super) async fn plan(state: &ScanState, units: &[Unit]) -> VortexResult { + let mut work = Vec::new(); + let mut total_rows = 0; + for unit in units { + let rows = state.unit_rows(unit)?; + if rows.is_empty() { + continue; + } + total_rows += rows.end - rows.start; + let (child, root) = prepare(state, unit, rows)?; + work.extend(run_root(child, root).await?); + } + Ok(Planned { work, total_rows }) +} + +/// Opens the stream of a scan of `units`. An unordered scan reads the parts it `planned`. +pub(super) fn open( + state: Arc, + units: Vec, + planned: Option, +) -> VortexResult { let dtype = state.dtype.clone(); let limit = state.limit.map(RowLimit::new); if state.ordered { @@ -76,34 +105,11 @@ pub(super) fn open(state: Arc, units: Vec) -> VortexResult, } -/// Prepares the scan of `rows` of the unit's child once and composes its root, returning whether -/// the root reads before it spawns parts. +/// Prepares the scan of `rows` of the unit's child once and composes its root. fn prepare( state: &ScanState, unit: &Unit, rows: Range, -) -> VortexResult<(Arc, Box, bool)> { +) -> VortexResult<(Arc, Box)> { let child = state.child(unit.child); let splits = child.splits(&state.projection, state.filter.as_ref())?; let scan = Arc::new(state.builder(child, rows).prepare()?); @@ -161,7 +166,7 @@ fn prepare( rows: scan.rows().clone(), io: scan.io(), }; - Ok((Arc::new(prepared), root, dynamic && scan.filter().is_some())) + Ok((Arc::new(prepared), root)) } /// The boundaries of `scan`'s chunks, which cut the work of a child without splits of its own. @@ -175,34 +180,28 @@ fn chunk_bounds(scan: &PreparedScan) -> Vec { /// Runs a child's root on a run of its own, awaiting only its reads, and returns the work it /// produces, in row order: the parts it spawns, and any batch it returns itself. -fn run_root( - child: Arc, - root: Box, -) -> BoxFuture<'static, VortexResult>> { - async move { - let mut run = Run::new(); - let scope = WorkScope { - file_ordinal: 0, - rows: child.rows.clone(), - }; - run.admit(root, scope, child.io.session()); - let mut work = Vec::new(); - loop { - match run.advance()? { - Progress::Spawn(scope, planner) => work.push(Work::Part(Part { - child: Arc::clone(&child), - scope, - planner, - })), - Progress::Batch(batch) => work.push(Work::Batch(batch.array)), - Progress::RootDone(_) if run.live_roots() > 0 => {} - Progress::RootDone(_) | Progress::Idle => break, - Progress::Waiting => future::poll_fn(|cx| run.poll_completion(cx)).await?, - } +async fn run_root(child: Arc, root: Box) -> VortexResult> { + let mut run = Run::new(); + let scope = WorkScope { + file_ordinal: 0, + rows: child.rows.clone(), + }; + run.admit(root, scope, child.io.session()); + let mut work = Vec::new(); + loop { + match run.advance()? { + Progress::Spawn(scope, planner) => work.push(Work::Part(Part { + child: Arc::clone(&child), + scope, + planner, + })), + Progress::Batch(batch) => work.push(Work::Batch(batch.array)), + Progress::RootDone(_) if run.live_roots() > 0 => {} + Progress::RootDone(_) | Progress::Idle => break, + Progress::Waiting => future::poll_fn(|cx| run.poll_completion(cx)).await?, } - Ok(work) } - .boxed() + Ok(work) } /// A unit of work in the queue of an unordered scan. @@ -210,19 +209,14 @@ enum Work { Part(Part), /// A batch a root returned itself. Batch(ArrayRef), - /// A root that reads before it spawns parts, and the queue to send its parts to. The sender - /// keeps the queue open until they are in it. - Root(BoxFuture<'static, VortexResult>>, Sender), -} - -fn send(sender: &Sender, work: Work) { - // The queue is unbounded and closes only once every clone is dropped, when the work is moot. - drop(sender.try_send(work)); } /// The queue of an unordered scan, which every clone of its stream takes from. struct Queue { - receiver: Receiver, + /// The work no clone has taken yet, in unit and row order. + work: Mutex>, + /// Set once a clone has taken the last of `work`. + exhausted: AtomicBool, /// The rows of the scan's units. total_rows: u64, /// The rows of the parts clones have taken. @@ -230,27 +224,30 @@ struct Queue { } impl Queue { + /// Takes the next work, or `None` once every one has been taken. + fn take(&self) -> Option { + let mut queue = self.work.lock(); + let work = queue.pop_front()?; + if queue.is_empty() { + self.exhausted.store(true, Ordering::Release); + } + if let Work::Part(part) = &work { + self.rows_taken.fetch_add( + part.scope.rows.end - part.scope.rows.start, + Ordering::Relaxed, + ); + } + Some(work) + } + /// The fraction of the scan's rows whose parts clones have taken. Pruning can leave rows that /// no part covers, so a queue with nothing left to take has made all of its progress. fn progress(&self) -> f64 { - if self.total_rows == 0 || self.is_drained() { + if self.total_rows == 0 || self.exhausted.load(Ordering::Relaxed) { return 1.0; } (self.rows_taken.load(Ordering::Relaxed) as f64 / self.total_rows as f64).min(1.0) } - - /// Whether the queue is empty and no root is left that could add to it. - fn is_drained(&self) -> bool { - self.receiver.is_empty() && self.receiver.sender_count() == 0 - } -} - -impl Drop for Queue { - fn drop(&mut self) { - // Queued roots hold senders of the queue itself; drain them so it can be freed. - self.receiver.close(); - while self.receiver.try_recv().is_ok() {} - } } /// One clone's worker: a run of its own, fed one part at a time from the scan's queue, and driven @@ -271,10 +268,10 @@ impl Worker { if self.limit.as_ref().is_some_and(RowLimit::is_exhausted) { return Ok(None); } - match self.take().await? { + match self.queue.take() { None => return Ok(None), - Some(Taken::Batch(array)) => return Ok(Some(array)), - Some(Taken::Part(part)) => { + Some(Work::Batch(array)) => return Ok(Some(array)), + Some(Work::Part(part)) => { self.run .admit(part.planner, part.scope, part.child.io.session()); self.child = Some(part.child); @@ -297,37 +294,6 @@ impl Worker { } } } - - /// Takes the next part or batch from the scan's queue, running the roots it finds there - /// first, or `None` once the queue is closed and empty. - async fn take(&mut self) -> VortexResult> { - loop { - let Ok(work) = self.queue.receiver.recv().await else { - return Ok(None); - }; - match work { - Work::Part(part) => { - self.queue.rows_taken.fetch_add( - part.scope.rows.end - part.scope.rows.start, - Ordering::Relaxed, - ); - return Ok(Some(Taken::Part(part))); - } - Work::Batch(array) => return Ok(Some(Taken::Batch(array))), - Work::Root(work, sender) => { - for work in work.await? { - send(&sender, work); - } - } - } - } - } -} - -/// What a worker takes from the queue. -enum Taken { - Part(Part), - Batch(ArrayRef), } /// The arrays of an ordered scan: each unit's rows in order, one unit after another. From c5d9897a6d6db6419a0964d47e84b1fdb16fd2f3 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Mon, 23 Nov 2026 19:15:22 -0500 Subject: [PATCH 4/7] Report a V2 plan scan's claimed parts on its stream Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-scan/src/source/plan_stream.rs | 53 +++++++++------------------ vortex-scan/src/source/tests.rs | 6 ++- 2 files changed, 23 insertions(+), 36 deletions(-) diff --git a/vortex-scan/src/source/plan_stream.rs b/vortex-scan/src/source/plan_stream.rs index ef2b3e7f996..ba2013921e1 100644 --- a/vortex-scan/src/source/plan_stream.rs +++ b/vortex-scan/src/source/plan_stream.rs @@ -33,8 +33,7 @@ use std::future; use std::iter; use std::ops::Range; use std::sync::Arc; -use std::sync::atomic::AtomicBool; -use std::sync::atomic::AtomicU64; +use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering; use futures::StreamExt; @@ -60,30 +59,27 @@ use crate::planning::planner::Planner; use crate::planning::planner::WorkScope; use crate::prepare::PreparedScan; use crate::prepare::part_root; +use crate::stream::Claims; use crate::stream::ScanStream; /// The parts of an unordered scan, cut when the scan is made. pub(super) struct Planned { work: Vec, - /// The rows of the scan's units. - total_rows: u64, } /// Prepares each of the scan's `units` once and runs its root, awaiting the zone maps a dynamic /// filter's root reads, and returns the work the roots produce, in unit and row order. pub(super) async fn plan(state: &ScanState, units: &[Unit]) -> VortexResult { let mut work = Vec::new(); - let mut total_rows = 0; for unit in units { let rows = state.unit_rows(unit)?; if rows.is_empty() { continue; } - total_rows += rows.end - rows.start; let (child, root) = prepare(state, unit, rows)?; work.extend(run_root(child, root).await?); } - Ok(Planned { work, total_rows }) + Ok(Planned { work }) } /// Opens the stream of a scan of `units`. An unordered scan reads the parts it `planned`. @@ -107,12 +103,11 @@ pub(super) fn open( let planned = planned.vortex_expect("an unordered scan cuts its parts when it is made"); let queue = Arc::new(Queue { - exhausted: AtomicBool::new(planned.work.is_empty()), + total: planned.work.len(), work: Mutex::new(planned.work.into()), - total_rows: planned.total_rows, - rows_taken: AtomicU64::new(0), + taken: AtomicUsize::new(0), }); - let progress = Arc::clone(&queue); + let claims = Arc::clone(&queue); Ok(ScanStream::new(dtype, move || { let worker = Worker { queue: Arc::clone(&queue), @@ -131,7 +126,7 @@ pub(super) fn open( .boxed(); limited(arrays, limit.clone()) }) - .with_progress(move || progress.progress())) + .with_claims(move || claims.claims())) } /// One child's prepared scan, shared by the parts of it that clones run. @@ -215,38 +210,26 @@ enum Work { struct Queue { /// The work no clone has taken yet, in unit and row order. work: Mutex>, - /// Set once a clone has taken the last of `work`. - exhausted: AtomicBool, - /// The rows of the scan's units. - total_rows: u64, - /// The rows of the parts clones have taken. - rows_taken: AtomicU64, + /// The work the queue started with. + total: usize, + /// The work clones have taken. + taken: AtomicUsize, } impl Queue { /// Takes the next work, or `None` once every one has been taken. fn take(&self) -> Option { - let mut queue = self.work.lock(); - let work = queue.pop_front()?; - if queue.is_empty() { - self.exhausted.store(true, Ordering::Release); - } - if let Work::Part(part) = &work { - self.rows_taken.fetch_add( - part.scope.rows.end - part.scope.rows.start, - Ordering::Relaxed, - ); - } + let work = self.work.lock().pop_front()?; + self.taken.fetch_add(1, Ordering::Relaxed); Some(work) } - /// The fraction of the scan's rows whose parts clones have taken. Pruning can leave rows that - /// no part covers, so a queue with nothing left to take has made all of its progress. - fn progress(&self) -> f64 { - if self.total_rows == 0 || self.exhausted.load(Ordering::Relaxed) { - return 1.0; + /// How much of the queue's work clones have taken, out of how much in all. + fn claims(&self) -> Claims { + Claims { + claimed: self.taken.load(Ordering::Relaxed).min(self.total), + total: self.total, } - (self.rows_taken.load(Ordering::Relaxed) as f64 / self.total_rows as f64).min(1.0) } } diff --git a/vortex-scan/src/source/tests.rs b/vortex-scan/src/source/tests.rs index daeb32082b5..3f5793abdaa 100644 --- a/vortex-scan/src/source/tests.rs +++ b/vortex-scan/src/source/tests.rs @@ -192,7 +192,11 @@ async fn clones_share_the_scan() -> VortexResult<()> { .map(|clone| clone.try_collect::>()), ) .await?; - assert_eq!(stream.progress(), Some(1.0)); + assert!( + stream + .claims() + .is_some_and(|claims| claims.total > 0 && claims.claimed == claims.total) + ); let mut ctx = VortexSession::empty().create_execution_ctx(); let mut values = Vec::new(); for batch in batches.into_iter().flatten() { From e946027690e0e91c230d0d1ce31b28c584e92ab5 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Mon, 23 Nov 2026 21:06:42 -0500 Subject: [PATCH 5/7] Import DynamicExprUpdates from vortex-functions, where develop moved it Signed-off-by: Nicholas Gates Co-Authored-By: Claude Opus 5.5 --- vortex-scan/src/source/plan_stream.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vortex-scan/src/source/plan_stream.rs b/vortex-scan/src/source/plan_stream.rs index ba2013921e1..d1d193e96b6 100644 --- a/vortex-scan/src/source/plan_stream.rs +++ b/vortex-scan/src/source/plan_stream.rs @@ -41,9 +41,9 @@ use futures::stream; use futures::stream::BoxStream; use parking_lot::Mutex; use vortex_array::ArrayRef; -use vortex_array::scalar_fn::fns::dynamic::DynamicExprUpdates; use vortex_error::VortexExpect; use vortex_error::VortexResult; +use vortex_functions::dynamic::DynamicExprUpdates; use vortex_io::request::IoService; use vortex_io::session::RuntimeSessionExt; From c722c017c3eea2bba39a4008a59d53e215f2d408 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Mon, 23 Nov 2026 22:15:59 -0500 Subject: [PATCH 6/7] Open a plan source scan into a ScanExec The queue marks the scan exhausted when its last part is taken or its limit is spent, and an ordered scan once its first stream exists. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-scan/src/source/plan.rs | 8 +-- vortex-scan/src/source/plan_stream.rs | 85 ++++++++++++++++----------- vortex-scan/src/source/tests.rs | 18 +++--- 3 files changed, 66 insertions(+), 45 deletions(-) diff --git a/vortex-scan/src/source/plan.rs b/vortex-scan/src/source/plan.rs index d65fcf16ba2..aaefdce7c9a 100644 --- a/vortex-scan/src/source/plan.rs +++ b/vortex-scan/src/source/plan.rs @@ -36,7 +36,7 @@ use crate::PartitionStream; use crate::ScanRequest; use crate::prepare::ScanBuilder; use crate::selection::Selection; -use crate::stream::ScanStream; +use crate::stream::ScanExec; /// Whether a child's own statistics, such as a file footer's, prove a filter, bound to the /// child's dtype, false for every row of the child. @@ -378,7 +378,7 @@ impl DataSourceScan for PlanScan { Ok(vec![self]) } - fn open(self: Box) -> VortexResult { + fn open(self: Box) -> VortexResult { plan_stream::open(self.state, self.units, self.planned) } @@ -391,7 +391,7 @@ impl DataSourceScan for PlanScan { } } -/// A scan of a [`PlanDataSource`] as its one partition, which reads the scan's opened stream. +/// A scan of a [`PlanDataSource`] as its one partition, which reads one stream of the opened scan. struct PlanPartition(Box); impl Partition for PlanPartition { @@ -412,6 +412,6 @@ impl Partition for PlanPartition { } fn execute(self: Box) -> VortexResult { - Ok(Box::pin(self.0.open()?)) + Ok(Box::pin(self.0.open()?.stream())) } } diff --git a/vortex-scan/src/source/plan_stream.rs b/vortex-scan/src/source/plan_stream.rs index d1d193e96b6..549294bb694 100644 --- a/vortex-scan/src/source/plan_stream.rs +++ b/vortex-scan/src/source/plan_stream.rs @@ -1,8 +1,8 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors -//! The stream of an opened [`PlanDataSource`](super::PlanDataSource) scan: V2's planners and -//! [`Run`] driver behind [`ScanStream`]. +//! An opened [`PlanDataSource`](super::PlanDataSource) scan: V2's planners and [`Run`] driver +//! behind [`ScanExec`] and its [`ScanStream`](crate::stream::ScanStream)s. //! //! When an unordered scan is made, it prepares each child once and runs its [`part_root`], which //! cuts the child into parts: the rows between the child's splits for the fields the scan reads, @@ -10,23 +10,24 @@ //! filter, such as the bound a top-N pushes down, the root first prunes the child as a whole //! against the bound as it stands, which reads zone maps. Those are the reads the scan needs to //! know its units of work, so they run in the async [`scan`](crate::DataSource::scan), which the -//! host awaits. Opening the scan reads nothing: it only queues the parts, so no clone waits on -//! another for its work. Each part prunes again against the bound as it stands when a clone takes -//! it. +//! host awaits. Opening the scan reads nothing: it only queues the parts, so no stream waits on +//! another for its work. Each part prunes again against the bound as it stands when a stream +//! takes it. //! -//! Every clone of the stream takes parts from the one queue. Each clone owns a [`Run`], driven on -//! the task that polls the clone, and runs one part on it at a time: the part's chunks run side by -//! side, so one chunk's reads overlap another's compute, batches are returned as they are -//! produced, and reads are awaited with [`Run::poll_completion`]. Nothing is spawned, so a host -//! that polls a clone with `block_on` runs the scan's compute on its own thread. +//! Every stream of the scan takes parts from the one queue, and the scan is exhausted once the +//! last part is taken. Each stream owns a [`Run`], driven on the task that polls the stream, and +//! runs one part on it at a time: the part's chunks run side by side, so one chunk's reads overlap +//! another's compute, batches are returned as they are produced, and reads are awaited with +//! [`Run::poll_completion`]. Nothing is spawned, so a host that polls a stream with `block_on` +//! runs the scan's compute on its own thread. //! -//! An ordered scan returns its rows in order through the first clone to be polled, running one -//! child after another on [`ScanDriver`], which keeps a scan's chunks in order. Later clones -//! return nothing. A host that reads an ordered scan in parallel -//! [splits](crate::DataSourceScan::split) it first. +//! An ordered scan returns its rows in order through its first stream, running one child after +//! another on [`ScanDriver`], which keeps a scan's chunks in order. The scan is exhausted once +//! that stream exists, and later streams return nothing. A host that reads an ordered scan in +//! parallel [splits](crate::DataSourceScan::split) it first. //! -//! A limit is one [`RowLimit`] for the whole stream: clones stop taking parts once it is spent, -//! and each clone's output is trimmed to it. +//! A limit is one [`RowLimit`] for the whole scan: streams stop taking parts once it is spent, +//! which also exhausts the scan, and each stream's output is trimmed to it. use std::collections::VecDeque; use std::future; @@ -60,7 +61,8 @@ use crate::planning::planner::WorkScope; use crate::prepare::PreparedScan; use crate::prepare::part_root; use crate::stream::Claims; -use crate::stream::ScanStream; +use crate::stream::ExhaustedFlag; +use crate::stream::ScanExec; /// The parts of an unordered scan, cut when the scan is made. pub(super) struct Planned { @@ -82,17 +84,21 @@ pub(super) async fn plan(state: &ScanState, units: &[Unit]) -> VortexResult, units: Vec, planned: Option, -) -> VortexResult { +) -> VortexResult { let dtype = state.dtype.clone(); let limit = state.limit.map(RowLimit::new); + let exhausted = ExhaustedFlag::new(); if state.ordered { let arrays = Arc::new(Mutex::new(Some(in_order(state, units)))); - return Ok(ScanStream::new(dtype, move || { + let flag = exhausted.clone(); + return Ok(ScanExec::new(dtype, exhausted, move || { + // The first stream returns every row, so later ones would find nothing. + flag.set(); let arrays = arrays .lock() .take() @@ -102,13 +108,17 @@ pub(super) fn open( } let planned = planned.vortex_expect("an unordered scan cuts its parts when it is made"); + if planned.work.is_empty() { + exhausted.set(); + } let queue = Arc::new(Queue { total: planned.work.len(), work: Mutex::new(planned.work.into()), taken: AtomicUsize::new(0), + exhausted: exhausted.clone(), }); - let claims = Arc::clone(&queue); - Ok(ScanStream::new(dtype, move || { + let progress = Arc::clone(&queue); + Ok(ScanExec::new(dtype, exhausted, move || { let worker = Worker { queue: Arc::clone(&queue), limit: limit.clone(), @@ -126,10 +136,10 @@ pub(super) fn open( .boxed(); limited(arrays, limit.clone()) }) - .with_claims(move || claims.claims())) + .with_progress(move || progress.claims())) } -/// One child's prepared scan, shared by the parts of it that clones run. +/// One child's prepared scan, shared by the parts of it that streams run. struct PreparedChild { rows: Range, io: Arc, @@ -206,25 +216,33 @@ enum Work { Batch(ArrayRef), } -/// The queue of an unordered scan, which every clone of its stream takes from. +/// The queue of an unordered scan, which every stream of it takes from. struct Queue { - /// The work no clone has taken yet, in unit and row order. + /// The work no stream has taken yet, in unit and row order. work: Mutex>, /// The work the queue started with. total: usize, - /// The work clones have taken. + /// The work streams have taken. taken: AtomicUsize, + /// Set once the last work is taken, or the scan's limit is spent. + exhausted: ExhaustedFlag, } impl Queue { - /// Takes the next work, or `None` once every one has been taken. + /// Takes the next work, or `None` once every one has been taken, and marks the scan exhausted + /// when it takes the last. fn take(&self) -> Option { - let work = self.work.lock().pop_front()?; + let mut work = self.work.lock(); + let next = work.pop_front()?; + if work.is_empty() { + self.exhausted.set(); + } + drop(work); self.taken.fetch_add(1, Ordering::Relaxed); - Some(work) + Some(next) } - /// How much of the queue's work clones have taken, out of how much in all. + /// How much of the queue's work streams have taken, out of how much in all. fn claims(&self) -> Claims { Claims { claimed: self.taken.load(Ordering::Relaxed).min(self.total), @@ -233,8 +251,8 @@ impl Queue { } } -/// One clone's worker: a run of its own, fed one part at a time from the scan's queue, and driven -/// on the task that polls the clone. +/// One stream's worker: a run of its own, fed one part at a time from the scan's queue, and driven +/// on the task that polls the stream. struct Worker { queue: Arc, limit: Option, @@ -249,6 +267,7 @@ impl Worker { loop { if self.run.live_roots() == 0 { if self.limit.as_ref().is_some_and(RowLimit::is_exhausted) { + self.queue.exhausted.set(); return Ok(None); } match self.queue.take() { diff --git a/vortex-scan/src/source/tests.rs b/vortex-scan/src/source/tests.rs index 3f5793abdaa..3319640e543 100644 --- a/vortex-scan/src/source/tests.rs +++ b/vortex-scan/src/source/tests.rs @@ -178,23 +178,25 @@ async fn selecting_the_unit_returns_its_partition( Ok(()) } -/// Clones of an opened scan share its parts: polled together, they return every row once. +/// The streams of an opened scan share its parts: polled together, they return every row once, +/// and the scan is exhausted once they have taken every part. #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn clones_share_the_scan() -> VortexResult<()> { - let stream = source_of(100_000) +async fn streams_share_the_scan() -> VortexResult<()> { + let exec = source_of(100_000) .scan(ScanRequest::default()) .await? .open()?; - let clones = [stream.clone(), stream.clone(), stream.clone()]; + assert!(!exec.is_exhausted()); + let streams = [exec.stream(), exec.stream(), exec.stream()]; let batches = try_join_all( - clones + streams .into_iter() - .map(|clone| clone.try_collect::>()), + .map(|stream| stream.try_collect::>()), ) .await?; + assert!(exec.is_exhausted()); assert!( - stream - .claims() + exec.progress() .is_some_and(|claims| claims.total > 0 && claims.claimed == claims.total) ); let mut ctx = VortexSession::empty().create_execution_ctx(); From 3e0c43178f7aa99dd6c79cda34f9c119f0e2dc58 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Mon, 23 Nov 2026 22:17:31 -0500 Subject: [PATCH 7/7] Describe opened scans as handing out streams Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-scan/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vortex-scan/src/lib.rs b/vortex-scan/src/lib.rs index 2180ad171c5..ffe9af7b216 100644 --- a/vortex-scan/src/lib.rs +++ b/vortex-scan/src/lib.rs @@ -229,7 +229,7 @@ pub type DataSourceScanRef = Box; /// A source does the reads it needs to know a scan's units of work, such as pruning against zone /// maps before cutting the scan into pieces, in the async [`DataSource::scan`], which the host /// awaits. [`split`](Self::split) and [`open`](Self::open) are synchronous and read nothing, so -/// no clone of an opened stream waits on another for its first work. +/// no stream of an opened scan waits on another for its first work. /// /// A scan never starts threads. Its work may run as tasks on the session's runtime, which the /// host owns.