diff --git a/vortex-scan/src/execution/driver.rs b/vortex-scan/src/execution/driver.rs index 7a904f80343..fd19cc9f485 100644 --- a/vortex-scan/src/execution/driver.rs +++ b/vortex-scan/src/execution/driver.rs @@ -12,6 +12,7 @@ //! produced the batch, beside the scan's other chunks. use std::future; +use std::num::NonZeroUsize; use std::sync::Arc; use std::task::Poll; @@ -42,6 +43,7 @@ use crate::prepare::ScanBuilder; pub struct ScanDriver { handle: Handle, concurrency: usize, + max_in_flight: Option, ordered: bool, } @@ -54,10 +56,18 @@ impl ScanDriver { Self { handle, concurrency, + max_in_flight: None, ordered, } } + /// Caps the chunks the scan decodes at once, in all, below the per-worker limit. `None` + /// keeps the per-worker limit only. + pub fn with_max_in_flight(mut self, max_in_flight: Option) -> Self { + self.max_in_flight = max_in_flight; + self + } + /// Prepares `builder` where compute runs, composes its planners, and streams their batches. /// Preparation errors are the stream's first item. pub fn run( @@ -101,6 +111,9 @@ impl ScanDriver { let scan = Arc::new(scan); let map_fn: MapFn = Arc::new(map_fn); let in_flight = self.concurrency * get_available_parallelism().unwrap_or(1); + let in_flight = self + .max_in_flight + .map_or(in_flight, |max| in_flight.min(max.get())); let inline = in_flight <= 1; let scope = WorkScope { file_ordinal: 0, diff --git a/vortex-scan/src/pool.rs b/vortex-scan/src/pool.rs index 26dbeedc8b2..f5a39f1ab2e 100644 --- a/vortex-scan/src/pool.rs +++ b/vortex-scan/src/pool.rs @@ -6,18 +6,24 @@ use std::any::Any; 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 async_lock::Mutex; use futures::StreamExt; +use futures::future; use futures::stream; +use futures::stream::BoxStream; +use vortex_array::ArrayRef; use vortex_array::dtype::DType; use vortex_array::expr::stats::Precision; use vortex_array::stream::ArrayStreamAdapter; use vortex_array::stream::ArrayStreamExt; use vortex_array::stream::SendableArrayStream; +use vortex_error::VortexExpect; use vortex_error::VortexResult; +use vortex_mask::Mask; use crate::DataSourceScanRef; use crate::Partition; @@ -58,6 +64,82 @@ pub trait ScanPool: 'static + Send + Sync { } } +/// A cloneable row budget shared by all work that can contribute rows to one scan. +/// +/// Filterless scans can reserve each unit's selected rows before decoding it, so rows past the +/// limit are never decoded. Filtered scans cannot know a unit's row count up front, so they take +/// rows from the budget as arrays are emitted and discard the excess. Either way, the order in +/// which rows are taken decides which rows are returned: an ordered scan takes them in row order, +/// an unordered one in completion order. +#[derive(Clone, Debug)] +pub struct RowLimit(Arc); + +impl RowLimit { + /// A budget of `limit` rows. + pub fn new(limit: u64) -> Self { + Self(Arc::new(AtomicU64::new(limit))) + } + + /// Reserves the rows selected by `mask` and keeps only the earliest granted rows of it. + pub fn limit(&self, mask: Mask) -> Mask { + let granted = self.take(mask.true_count()); + mask.limit(granted) + } + + /// Reserves up to `rows` rows, returning how many the remaining budget granted. + pub fn take(&self, rows: usize) -> usize { + let requested = u64::try_from(rows).unwrap_or(u64::MAX); + usize::try_from(self.reserve(requested)).unwrap_or(usize::MAX) + } + + /// Whether the budget is spent. + pub fn is_exhausted(&self) -> bool { + self.0.load(Ordering::Relaxed) == 0 + } + + fn reserve(&self, requested: u64) -> u64 { + let remaining = self + .0 + .try_update(Ordering::Relaxed, Ordering::Relaxed, |remaining| { + Some(remaining.saturating_sub(requested)) + }) + .ok() + .vortex_expect("row reservation always updates the budget"); + remaining.min(requested) + } +} + +/// Ends `arrays` once `limit` is spent, taking each array's rows from it as the array is yielded +/// and slicing the array that spends it. Also ends after the first error. +pub fn trim_to_limit( + arrays: BoxStream<'static, VortexResult>, + limit: RowLimit, +) -> BoxStream<'static, VortexResult> { + stream::unfold(Some(arrays), move |arrays| { + let limit = limit.clone(); + async move { + let mut arrays = arrays?; + if limit.is_exhausted() { + return None; + } + let array = match arrays.next().await? { + Ok(array) => array, + Err(err) => return Some((Err(err), None)), + }; + let granted = limit.take(array.len()); + if granted == array.len() { + return Some((Ok(array), Some(arrays))); + } + if granted == 0 { + return None; + } + Some((array.slice(0..granted), None)) + } + }) + .filter(|array| future::ready(array.as_ref().map_or(true, |array| !array.is_empty()))) + .boxed() +} + /// A pool whose workers take partitions one at a time from a scan's shared partition stream. /// /// A source without a pool of its own can open into this one, as long as it implements @@ -171,6 +253,10 @@ mod tests { use std::collections::VecDeque; use std::num::NonZeroUsize; use std::sync::Arc; + use std::sync::Barrier; + use std::sync::atomic::AtomicU64; + use std::sync::atomic::Ordering; + use std::thread; use futures::StreamExt; use futures::TryStreamExt; @@ -189,10 +275,13 @@ mod tests { use vortex_array::stream::SendableArrayStream; use vortex_buffer::Buffer; use vortex_error::VortexResult; + use vortex_mask::Mask; use super::PartitionPool; + use super::RowLimit; use super::ScanPool; use super::ScanPoolRef; + use super::trim_to_limit; use crate::DataSourceScan; use crate::DataSourceScanRef; use crate::Partition; @@ -384,4 +473,67 @@ mod tests { assert_eq!(rows.into_iter().sum::(), 14); Ok(()) } + + #[test] + fn reserve_grants_up_to_the_remaining_budget() { + let limit = RowLimit::new(5); + assert_eq!(limit.reserve(3), 3); + assert!(!limit.is_exhausted()); + assert_eq!(limit.reserve(10), 2); + assert!(limit.is_exhausted()); + assert_eq!(limit.reserve(1), 0); + } + + #[test] + fn limit_keeps_the_earliest_granted_rows() { + let limit = RowLimit::new(2); + let mask = Mask::from_iter([true, false, true, true, false, true]); + let limited = limit.limit(mask); + assert_eq!(limited.true_count(), 2); + assert!(limited.value(0)); + assert!(limited.value(2)); + assert!(!limited.value(3)); + assert!(!limited.value(5)); + assert!(limit.is_exhausted()); + } + + #[test] + fn concurrent_reservations_never_exceed_the_budget() { + const THREADS: usize = 8; + const PER_THREAD: u64 = 10_000; + const LIMIT: u64 = 25_000; + + let limit = RowLimit::new(LIMIT); + let granted_total = Arc::new(AtomicU64::new(0)); + let barrier = Arc::new(Barrier::new(THREADS)); + thread::scope(|scope| { + for _ in 0..THREADS { + let limit = limit.clone(); + let granted_total = Arc::clone(&granted_total); + let barrier = Arc::clone(&barrier); + scope.spawn(move || { + barrier.wait(); + let mut local = 0; + for _ in 0..PER_THREAD { + local += limit.reserve(1); + } + granted_total.fetch_add(local, Ordering::Relaxed); + }); + } + }); + assert_eq!(granted_total.load(Ordering::Relaxed), LIMIT); + assert!(limit.is_exhausted()); + } + + #[test] + fn trim_to_limit_slices_the_array_that_spends_it() -> VortexResult<()> { + let arrays = stream::iter((0..4).map(|_| Ok(Buffer::from_iter(0..3i32).into_array()))); + let trimmed: Vec<_> = + block_on(trim_to_limit(arrays.boxed(), RowLimit::new(7)).try_collect())?; + assert_eq!( + trimmed.iter().map(|a| a.len()).collect::>(), + vec![3, 3, 1] + ); + Ok(()) + } } diff --git a/vortex-scan/src/source.rs b/vortex-scan/src/source.rs index 08a3f38c296..fe5eaf10f6d 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; + +pub use plan::DeferredPlanChild; +pub use plan::FilePruner; +pub use plan::PlanChild; +pub use plan::PlanDataSource; +pub use plan::PlanSourceChild; + +#[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..3a177c212e5 --- /dev/null +++ b/vortex-scan/src/source/plan.rs @@ -0,0 +1,651 @@ +// 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; a deferred child is anything that expands into children, such as a file to +//! open, a table format's manifest, or a partition to list. + +use std::any::Any; +use std::collections::VecDeque; +use std::future; +use std::num::NonZeroUsize; +use std::ops::Range; +use std::sync::Arc; + +use async_trait::async_trait; +use futures::StreamExt; +use futures::TryStreamExt; +use futures::stream; +use futures::stream::BoxStream; +use vortex_array::ArrayRef; +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::ArrayStreamAdapter; +use vortex_array::stream::ArrayStreamExt; +use vortex_array::stream::SendableArrayStream; +use vortex_error::VortexResult; +use vortex_error::vortex_bail; +use vortex_io::session::RuntimeSessionExt; +use vortex_session::VortexSession; + +use super::ScanInput; +use crate::DataSource; +use crate::DataSourceScan; +use crate::DataSourceScanRef; +use crate::Partition; +use crate::PartitionRef; +use crate::PartitionStream; +use crate::ScanRequest; +use crate::execution::driver::ScanDriver; +use crate::pool::PartitionPool; +use crate::pool::RowLimit; +use crate::pool::ScanPoolRef; +use crate::pool::trim_to_limit; +use crate::prepare::ScanBuilder; +use crate::selection::Selection; + +/// 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>; + +/// A child of a [`PlanDataSource`] whose plan is ready to prepare: its [`ScanInput`] and what the +/// source knows of it without reading payloads. +#[derive(Clone)] +pub struct PlanChild { + input: ScanInput, + row_count: 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, + 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 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. + pub(super) 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() + } + + fn is_pruned(&self, filter: Option<&BoundExpression>) -> VortexResult { + match (&self.pruner, filter) { + (Some(pruner), Some(filter)) => pruner(filter), + _ => Ok(false), + } + } +} + +/// A child of a [`PlanDataSource`] that a scan expands when it reaches it: a file to open, a +/// manifest entry to read, a table partition to list. +/// +/// Expanding is work like any other unit of an opened scan: the worker that takes the child +/// expands it and queues the work of what it expanded into, for any worker to take. +#[async_trait] +pub trait DeferredPlanChild: 'static + Send + Sync { + /// The children this child stands for, in row order. They may be deferred in turn, as a + /// manifest's children are. An empty list skips the child. + async fn expand(&self) -> VortexResult>; +} + +/// A child of a [`PlanDataSource`]. +#[derive(Clone)] +pub enum PlanSourceChild { + /// A child whose plan is ready to prepare. + Ready(PlanChild), + /// A child that a scan expands when it reaches it, so a source over many children reads only + /// the metadata its scans need. + Deferred { + /// Expands the child. + child: Arc, + /// The child's size in bytes, if known. + byte_size: Option, + }, +} + +/// 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 ready 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. A scan reads its children in order, and a deferred child's children in its place. +/// +/// # Splitting and opening +/// +/// The work of a scan is plan work: chunks of a prepared plan, and the expansion of deferred +/// children. [`split`](DataSourceScan::split) does not cut a scan yet: it returns the scan whole. +/// [`open`](DataSourceScan::open) reads the scan's partitions through a [`PartitionPool`], each +/// worker taking one partition at a time. +/// +/// # Partitions +/// +/// A scan has one partition per child, whose [`index`](Partition::index) is the child's ordinal, +/// so a request's `partition_range` and `partition_selection` select children. A partition runs +/// its child, or each child a deferred one expands into, with a [`ScanDriver`] on the session's +/// runtime. +/// +/// [`ScanCache`]: crate::prepare::ScanCache +#[derive(Clone)] +pub struct PlanDataSource { + session: VortexSession, + dtype: DType, + children: Arc<[PlanSourceChild]>, + row_count: Precision, + byte_size: Precision, +} + +impl PlanDataSource { + /// A source scanning one ready `input` with `session`. + pub fn new(session: VortexSession, input: ScanInput) -> Self { + Self::from_child(session, PlanChild::new(input)) + } + + /// A source scanning one ready `child` with `session`. + pub fn from_child(session: VortexSession, child: PlanChild) -> Self { + let dtype = child.input.dtype.clone(); + let row_count = child.row_count.map_or(Precision::Absent, Precision::exact); + Self { + session, + dtype, + children: Arc::new([PlanSourceChild::Ready(child)]), + row_count, + byte_size: Precision::Absent, + } + } + + /// A source scanning `children` in order with `session`. Every child must have `dtype`; a + /// scan that expands a child of another dtype fails. + pub fn from_children( + session: VortexSession, + dtype: DType, + children: Vec, + ) -> Self { + let mut rows = Some(0u64); + let mut bytes = Some(0u64); + let mut known_rows = 0; + let mut known_files = 0; + for file in &children { + match file { + PlanSourceChild::Ready(file) => { + match file.row_count { + Some(count) => { + known_rows += count; + known_files += 1; + } + None => rows = None, + } + bytes = bytes.map(|bytes| bytes + file.byte_size()); + } + PlanSourceChild::Deferred { byte_size, .. } => { + rows = None; + bytes = bytes.zip(*byte_size).map(|(bytes, size)| bytes + size); + } + } + } + // Deferred children are estimated at the average row count of the ready ones. + let row_count = match rows { + Some(rows) => Precision::exact(rows + known_rows), + None if known_files > 0 => { + Precision::inexact(known_rows / known_files * children.len() as u64) + } + None => Precision::Absent, + }; + Self { + session, + dtype, + children: children.into(), + row_count, + byte_size: bytes.map_or(Precision::Absent, Precision::inexact), + } + } + + /// Sets the exact row count of a one-child source, which scans and partitions report. + pub fn with_row_count(mut self, row_count: u64) -> Self { + if let [PlanSourceChild::Ready(file)] = &*self.children { + self.children = Arc::new([PlanSourceChild::Ready( + file.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) -> &[PlanSourceChild] { + &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, file) 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 { + continue; + } + let rows = match file { + PlanSourceChild::Ready(file) => { + if file.is_pruned(filter.as_ref())? { + continue; + } + file.row_count + .map(|count| clamp_rows(request.row_range.clone(), count)) + } + PlanSourceChild::Deferred { .. } => None, + }; + if rows.as_ref().is_some_and(Range::is_empty) { + continue; + } + units.push(Unit { + child: ordinal, + rows, + }); + } + let state = ScanState { + session: self.session.clone(), + source_dtype: self.dtype.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, + split_concurrency: request.split_concurrency, + }; + 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, partition and pool of one scan of a [`PlanDataSource`] shares. +pub(super) struct ScanState { + pub(super) session: VortexSession, + source_dtype: DType, + children: Arc<[PlanSourceChild]>, + /// The dtype of the scan's output. + pub(super) dtype: DType, + pub(super) projection: BoundExpression, + pub(super) filter: Option, + row_range: Option>, + pub(super) selection: Selection, + pub(super) ordered: bool, + pub(super) limit: Option, + pub(super) split_concurrency: Option, +} + +impl ScanState { + /// The source's child at `ordinal`. + pub(super) fn child(&self, ordinal: usize) -> &PlanSourceChild { + &self.children[ordinal] + } + + /// The child at `ordinal` if it is ready. + pub(super) fn ready(&self, ordinal: usize) -> Option<&PlanChild> { + match &self.children[ordinal] { + PlanSourceChild::Ready(child) => Some(child), + PlanSourceChild::Deferred { .. } => None, + } + } + + /// Admits a child that expanding produced: `None` when its statistics rule out the filter, + /// and an error when its dtype is not the source's. + pub(super) fn admit(&self, child: PlanChild) -> VortexResult> { + if child.input.dtype != self.source_dtype { + vortex_bail!( + "a child of the source has dtype {}, but the source has dtype {}", + child.input.dtype, + self.source_dtype + ); + } + if child.is_pruned(self.filter.as_ref())? { + return Ok(None); + } + Ok(Some(child)) + } + + /// Expands `children` depth-first, in order, into the admitted ready children they stand for, + /// expanding each deferred child only once the children before it are taken. + /// + /// Each child comes with its share of the scan's work, which a deferred child divides evenly + /// among the children it expands into. The share of a child that is pruned, or that expands + /// into nothing, goes to `skipped`. + pub(super) fn expand_in_order( + self: &Arc, + children: Vec<(PlanSourceChild, f64)>, + skipped: Arc, + ) -> BoxStream<'static, VortexResult<(PlanChild, f64)>> { + let state = Arc::clone(self); + stream::try_unfold(VecDeque::from(children), move |mut queue| { + let state = Arc::clone(&state); + let skipped = Arc::clone(&skipped); + async move { + while let Some((child, share)) = queue.pop_front() { + match child { + PlanSourceChild::Ready(child) => match state.admit(child)? { + Some(child) => return Ok(Some(((child, share), queue))), + None => skipped(share), + }, + PlanSourceChild::Deferred { child, .. } => { + let children = child.expand().await?; + if children.is_empty() { + skipped(share); + } + let share = share / children.len().max(1) as f64; + for child in children.into_iter().rev() { + queue.push_front((child, share)); + } + } + } + } + Ok(None) + } + }) + .boxed() + } + + /// Runs `rows` of `child`, or the request's rows of it when `None`, with a [`ScanDriver`]. + fn drive( + &self, + child: &PlanChild, + rows: Option>, + ) -> BoxStream<'static, VortexResult> { + let rows = match rows.map_or_else(|| self.child_rows(child), Ok) { + Ok(rows) => rows, + Err(err) => return stream::once(future::ready(Err(err))).boxed(), + }; + if rows.is_empty() { + return stream::empty().boxed(); + } + ScanDriver::new(self.session.handle(), 1, self.ordered) + .with_max_in_flight(self.split_concurrency) + .run(self.builder(child, rows)) + } + + /// The rows of `child` this scan reads: the request's row range, clamped to the child. + pub(super) fn child_rows(&self, child: &PlanChild) -> VortexResult> { + Ok(clamp_rows(self.row_range.clone(), 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 it is open. + 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 PlanScan { + /// The rows of `unit` the scan selects before filtering, or `None` when not known yet. + fn unit_rows(&self, unit: &Unit) -> Option { + let rows = unit.rows.as_ref()?; + Some(self.state.selection.row_count_in_range(rows)) + } + + /// The bytes of `unit`, in proportion to its share of its child's rows. + fn unit_bytes(&self, unit: &Unit) -> Option { + match &self.state.children[unit.child] { + PlanSourceChild::Ready(file) => { + let bytes = file.byte_size(); + match (&unit.rows, file.row_count) { + (Some(rows), Some(count)) if count > 0 => Some( + u64::try_from( + u128::from(bytes) * u128::from(rows.end - rows.start) + / u128::from(count), + ) + .unwrap_or(u64::MAX), + ), + _ => Some(bytes), + } + } + PlanSourceChild::Deferred { byte_size, .. } => *byte_size, + } + } +} + +impl DataSourceScan for PlanScan { + fn dtype(&self) -> &DType { + &self.state.dtype + } + + fn partition_count(&self) -> Precision { + Precision::exact(self.units.len()) + } + + fn partitions(self: Box) -> PartitionStream { + // An unordered scan's partitions share one budget; an ordered scan's each apply the limit + // locally, and the caller trims the concatenated result. + let shared = (!self.state.ordered) + .then(|| self.state.limit.map(RowLimit::new)) + .flatten(); + let state = self.state; + stream::iter(self.units.into_iter().map(move |unit| { + let limit = shared.clone().or_else(|| state.limit.map(RowLimit::new)); + Ok(Box::new(PlanPartition { + state: Arc::clone(&state), + unit, + limit, + }) as PartitionRef) + })) + .boxed() + } + + fn row_count(&self) -> Precision { + let Some(rows) = self + .units + .iter() + .map(|unit| self.unit_rows(unit)) + .sum::>() + else { + return Precision::Absent; + }; + let rows = self.state.limit.map_or(rows, |limit| rows.min(limit)); + if self.state.filter.is_some() { + Precision::inexact(rows) + } else { + Precision::exact(rows) + } + } + + fn byte_size(&self) -> Precision { + self.units + .iter() + .map(|unit| self.unit_bytes(unit)) + .sum::>() + .map_or(Precision::Absent, Precision::inexact) + } + + fn split(self: Box, _n: NonZeroUsize) -> VortexResult> { + Ok(vec![self]) + } + + fn open(self: Box) -> VortexResult { + Ok(Arc::new(PartitionPool::new(self))) + } +} + +/// One child's rows of a scan of a [`PlanDataSource`]. +struct PlanPartition { + state: Arc, + unit: Unit, + limit: Option, +} + +impl Partition for PlanPartition { + fn as_any(&self) -> &dyn Any { + self + } + + fn index(&self) -> usize { + self.unit.child + } + + fn row_count(&self) -> Precision { + let rows = match (&self.unit.rows, self.state.ready(self.unit.child)) { + (Some(rows), _) => rows.clone(), + (None, Some(file)) if file.row_count.is_some() => match self.state.child_rows(file) { + Ok(rows) => rows, + Err(_) => return Precision::Absent, + }, + _ => return Precision::Absent, + }; + let rows = self.state.selection.row_count_in_range(&rows); + let rows = self.state.limit.map_or(rows, |limit| rows.min(limit)); + if self.state.filter.is_some() { + Precision::inexact(rows) + } else { + Precision::exact(rows) + } + } + + fn byte_size(&self) -> Precision { + Precision::Absent + } + + fn execute(self: Box) -> VortexResult { + let PlanPartition { state, unit, limit } = *self; + let dtype = state.dtype.clone(); + // A ready child runs as it is; a deferred one runs each child it expands into, in order. + let children = match state.ready(unit.child) { + Some(child) => stream::iter([Ok((child.clone(), unit.rows))]).boxed(), + None => state + .expand_in_order( + vec![(state.child(unit.child).clone(), 0.0)], + Arc::new(|_| {}), + ) + .map_ok(|(child, _)| (child, None)) + .boxed(), + }; + let driver = Arc::clone(&state); + let arrays = children + .map_ok(move |(child, rows)| driver.drive(&child, rows)) + .try_flatten() + .boxed(); + let arrays = match limit { + Some(limit) => trim_to_limit(arrays, limit), + None => arrays, + }; + Ok(ArrayStreamExt::boxed(ArrayStreamAdapter::new( + dtype, arrays, + ))) + } +} diff --git a/vortex-scan/src/source/tests.rs b/vortex-scan/src/source/tests.rs new file mode 100644 index 00000000000..f0a98a3c8d6 --- /dev/null +++ b/vortex-scan/src/source/tests.rs @@ -0,0 +1,189 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +use std::ops::Range; +use std::sync::Arc; + +use futures::TryStreamExt; +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_array::expr::stats::Precision; +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(()) +} + +#[tokio::test] +async fn partitions_report_their_rows() -> VortexResult<()> { + let partitions = partitions(ScanRequest { + row_range: Some(4..9), + ..Default::default() + }) + .await?; + assert_eq!(partitions[0].row_count(), Precision::exact(5_u64)); + Ok(()) +} + +#[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] +async fn requests_without_rows_have_no_partitions( + #[case] request: ScanRequest, +) -> VortexResult<()> { + assert!(partitions(request).await?.is_empty()); + 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(()) +}