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/lib.rs b/vortex-scan/src/lib.rs index 943b675088a..ffe9af7b216 100644 --- a/vortex-scan/src/lib.rs +++ b/vortex-scan/src/lib.rs @@ -226,6 +226,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 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. pub trait DataSourceScan: 'static + Send { 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..aaefdce7c9a --- /dev/null +++ b/vortex-scan/src/source/plan.rs @@ -0,0 +1,417 @@ +// 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::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. +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. +/// +/// 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. +/// +/// [`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, + }; + // 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, + })) + } + + 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, + /// The parts of an unordered scan, cut when the scan was made. + planned: Option, +} + +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, self.planned) + } + + 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 one stream of the opened scan. +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()?.stream())) + } +} diff --git a/vortex-scan/src/source/plan_stream.rs b/vortex-scan/src/source/plan_stream.rs new file mode 100644 index 00000000000..549294bb694 --- /dev/null +++ b/vortex-scan/src/source/plan_stream.rs @@ -0,0 +1,327 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! 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, +//! 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 stream waits on +//! another for its work. Each part prunes again against the bound as it stands when a stream +//! takes it. +//! +//! 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 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 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; +use std::iter; +use std::ops::Range; +use std::sync::Arc; +use std::sync::atomic::AtomicUsize; +use std::sync::atomic::Ordering; + +use futures::StreamExt; +use futures::stream; +use futures::stream::BoxStream; +use parking_lot::Mutex; +use vortex_array::ArrayRef; +use vortex_error::VortexExpect; +use vortex_error::VortexResult; +use vortex_functions::dynamic::DynamicExprUpdates; +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::Claims; +use crate::stream::ExhaustedFlag; +use crate::stream::ScanExec; + +/// The parts of an unordered scan, cut when the scan is made. +pub(super) struct Planned { + work: Vec, +} + +/// 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(); + for unit in units { + let rows = state.unit_rows(unit)?; + if rows.is_empty() { + continue; + } + let (child, root) = prepare(state, unit, rows)?; + work.extend(run_root(child, root).await?); + } + Ok(Planned { work }) +} + +/// Opens 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); + let exhausted = ExhaustedFlag::new(); + if state.ordered { + let arrays = Arc::new(Mutex::new(Some(in_order(state, units)))); + 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() + .unwrap_or_else(|| stream::empty().boxed()); + limited(arrays, limit.clone()) + })); + } + + 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 progress = Arc::clone(&queue); + Ok(ScanExec::new(dtype, exhausted, 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.claims())) +} + +/// One child's prepared scan, shared by the parts of it that streams 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. +fn prepare( + state: &ScanState, + unit: &Unit, + rows: Range, +) -> 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()?); + 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)) +} + +/// 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. +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) +} + +/// A unit of work in the queue of an unordered scan. +enum Work { + Part(Part), + /// A batch a root returned itself. + Batch(ArrayRef), +} + +/// The queue of an unordered scan, which every stream of it takes from. +struct Queue { + /// The work no stream has taken yet, in unit and row order. + work: Mutex>, + /// The work the queue started with. + total: usize, + /// 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, and marks the scan exhausted + /// when it takes the last. + fn take(&self) -> Option { + 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(next) + } + + /// 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), + total: self.total, + } + } +} + +/// 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, + 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) { + self.queue.exhausted.set(); + return Ok(None); + } + match self.queue.take() { + None => return Ok(None), + 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); + } + } + } + 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?; + } + } + } + } +} + +/// 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..3319640e543 --- /dev/null +++ b/vortex-scan/src/source/tests.rs @@ -0,0 +1,210 @@ +// 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(()) +} + +/// 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 streams_share_the_scan() -> VortexResult<()> { + let exec = source_of(100_000) + .scan(ScanRequest::default()) + .await? + .open()?; + assert!(!exec.is_exhausted()); + let streams = [exec.stream(), exec.stream(), exec.stream()]; + let batches = try_join_all( + streams + .into_iter() + .map(|stream| stream.try_collect::>()), + ) + .await?; + assert!(exec.is_exhausted()); + assert!( + exec.progress() + .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() { + values.extend_from_slice(batch.execute::(&mut ctx)?.as_slice::()); + } + values.sort_unstable(); + assert_eq!(values, (0..100_000).collect::>()); + Ok(()) +}