diff --git a/vortex-datafusion/src/v2/source.rs b/vortex-datafusion/src/v2/source.rs index 098e1218228..4390b01aa9a 100644 --- a/vortex-datafusion/src/v2/source.rs +++ b/vortex-datafusion/src/v2/source.rs @@ -1029,6 +1029,7 @@ fn estimate_to_df_precision(est: &Precision) -> DFPrecision { #[cfg(test)] mod tests { use std::any::Any; + use std::num::NonZeroUsize; use std::sync::Arc; use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering; @@ -1075,6 +1076,7 @@ mod tests { use vortex::scan::Partition; use vortex::scan::PartitionRef; use vortex::scan::PartitionStream; + use vortex::scan::stream::ScanExec; use vortex::session::VortexSession; use vortex_arrow::ArrowSessionExt; @@ -1221,6 +1223,14 @@ mod tests { &self.dtype } + fn split(self: Box, _n: NonZeroUsize) -> VortexResult> { + Ok(vec![self]) + } + + fn open(self: Box) -> VortexResult { + Ok(ScanExec::from_partitions(self)) + } + fn partition_count(&self) -> Precision { Precision::Exact(2) } diff --git a/vortex-layout/src/scan/layout.rs b/vortex-layout/src/scan/layout.rs index bada8995e0c..c240daddb36 100644 --- a/vortex-layout/src/scan/layout.rs +++ b/vortex-layout/src/scan/layout.rs @@ -40,6 +40,7 @@ use vortex_scan::PartitionRef; use vortex_scan::PartitionStream; use vortex_scan::ScanRequest; use vortex_scan::selection::Selection; +use vortex_scan::stream::ScanExec; use vortex_session::VortexSession; use crate::LayoutReaderRef; @@ -342,6 +343,14 @@ impl DataSourceScan for LayoutReaderScan { &self.dtype } + fn split(self: Box, _n: NonZeroUsize) -> VortexResult> { + Ok(vec![self]) + } + + fn open(self: Box) -> VortexResult { + Ok(ScanExec::from_partitions(self)) + } + fn partition_count(&self) -> Precision { let (lower, upper) = self.size_hint(); match upper { @@ -518,6 +527,14 @@ impl DataSourceScan for EmptyScan { &self.dtype } + fn split(self: Box, _n: NonZeroUsize) -> VortexResult> { + Ok(vec![self]) + } + + fn open(self: Box) -> VortexResult { + Ok(ScanExec::from_partitions(self)) + } + fn partition_count(&self) -> Precision { let (lower, upper) = self.size_hint(); match upper { diff --git a/vortex-layout/src/scan/multi.rs b/vortex-layout/src/scan/multi.rs index ba3141628be..b085753f08b 100644 --- a/vortex-layout/src/scan/multi.rs +++ b/vortex-layout/src/scan/multi.rs @@ -58,6 +58,7 @@ use vortex_scan::PartitionRef; use vortex_scan::PartitionStream; use vortex_scan::ScanRequest; use vortex_scan::selection::Selection; +use vortex_scan::stream::ScanExec; use vortex_session::VortexSession; use vortex_utils::parallelism::get_available_parallelism; @@ -409,6 +410,14 @@ impl DataSourceScan for MultiLayoutScan { &self.dtype } + fn split(self: Box, _n: NonZeroUsize) -> VortexResult> { + Ok(vec![self]) + } + + fn open(self: Box) -> VortexResult { + Ok(ScanExec::from_partitions(self)) + } + fn partition_count(&self) -> Precision { let count = self.ready.len() + self.deferred.len(); if !self.deferred.is_empty() || matches!(self.request.filter, Ok(Some(_))) { diff --git a/vortex-scan/src/lib.rs b/vortex-scan/src/lib.rs index ee17f591a64..4a625b9c421 100644 --- a/vortex-scan/src/lib.rs +++ b/vortex-scan/src/lib.rs @@ -30,6 +30,7 @@ pub mod prepare; pub mod row_mask; pub mod selection; pub mod source; +pub mod stream; pub mod strict_sorted_buffer; use std::any::Any; @@ -42,6 +43,7 @@ use futures::StreamExt; use futures::TryStreamExt; use futures::stream::BoxStream; use selection::Selection; +use stream::ScanExec; use vortex_array::aggregate_fn::AggregateFnRef; use vortex_array::dtype::DType; use vortex_array::dtype::FieldPath; @@ -180,12 +182,15 @@ pub struct ScanRequest { /// order is completion order, so each partition applies the limit locally and the caller must /// trim the concatenated result. pub limit: Option, - /// The most splits of each partition to decode at once, in all. + /// The most splits that each worker decodes at once, where a worker is a partition or a + /// stream of an opened scan. /// - /// `None` keeps the reader's default, which scales with the machine's cores. Each split being - /// decoded holds the decoded chunks of every column it overlaps, so a scan that runs alongside - /// others, such as one task of several on a machine, can set this to bound its memory. It does - /// not bound I/O: segment reads for later splits may still be coalesced ahead of them. + /// It bounds each worker on its own, not the whole scan: a scan read by several workers + /// decodes up to this many splits in each. `None` keeps the source's default. Each + /// split being decoded holds the decoded chunks of every column it overlaps, so a scan that + /// runs alongside others, such as one task of several on a machine, can set this to bound its + /// memory. It does not bound I/O: segment reads for later splits may still be coalesced ahead + /// of them. pub split_concurrency: Option, } @@ -208,7 +213,19 @@ impl Default for ScanRequest { /// A boxed data source scan. pub type DataSourceScanRef = Box; -/// A data source scan produces partitions that can be executed to read data from the source. +/// A data source scan reads data from the source. +/// +/// Each host reads every scan the same way, whatever the source: its execution model is fixed. +/// A host that needs a fixed number of partitions, such as DataFusion with its output partition +/// count, [splits](Self::split) the scan into fixed pieces that each own their rows. A host that +/// runs its own threads, such as DuckDB, or that wants its partitions to share work, never +/// splits: it [opens](Self::open) the scan once and has each of its threads or partitions read a +/// [stream](ScanExec::stream) of the returned [`ScanExec`]. The host states the properties it needs, such as row +/// order or a limit, on the [`ScanRequest`], and the source decides what the pieces are and how +/// they run. +/// +/// 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 { /// The returned dtype of the scan. fn dtype(&self) -> &DType; @@ -218,6 +235,24 @@ pub trait DataSourceScan: 'static + Send { /// Returns a stream of partitions to be processed. fn partitions(self: Box) -> PartitionStream; + + /// Partitions the scan into at most `n` fixed pieces. + /// + /// Each piece owns its rows: the pieces together return every row of the scan exactly once, + /// and no two return the same row. When the request is ordered, the pieces are contiguous, + /// and reading them one after another returns the rows in scan order. + /// + /// Splitting reads metadata only. The result is never empty, and a scan with no cut points + /// returns itself as the one piece. A host that wants its threads to share the scan's work + /// instead [opens](Self::open) the scan and reads a stream of it on each thread. + fn split(self: Box, n: NonZeroUsize) -> VortexResult>; + + /// Opens the scan into a [`ScanExec`], whose work host threads share by each reading a + /// [stream](ScanExec::stream) of it. + /// + /// A source that has no queue of work of its own may return + /// [`ScanExec::from_partitions`] over itself. + fn open(self: Box) -> VortexResult; } impl dyn DataSourceScan { diff --git a/vortex-scan/src/stream.rs b/vortex-scan/src/stream.rs new file mode 100644 index 00000000000..cd7a9154c04 --- /dev/null +++ b/vortex-scan/src/stream.rs @@ -0,0 +1,315 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! An opened scan: the work its host threads share, and the streams that read it. + +use std::fmt; +use std::pin::Pin; +use std::sync::Arc; +use std::sync::atomic::AtomicBool; +use std::sync::atomic::Ordering; +use std::task::Context; +use std::task::Poll; + +use async_lock::Mutex; +use futures::Stream; +use futures::StreamExt; +use futures::stream; +use futures::stream::BoxStream; +use vortex_array::ArrayRef; +use vortex_array::dtype::DType; +use vortex_array::stream::ArrayStream; +use vortex_error::VortexResult; + +use crate::DataSourceScanRef; + +/// Starts a new worker over the shared work of an opened scan. +type NewWorker = dyn Fn() -> BoxStream<'static, VortexResult> + Send + Sync; + +/// A flag that an opened scan sets once no stream created afterwards would find work. +/// +/// It is set at most once and never cleared, so hosts read it from a cache line that is almost +/// never written. Clones share the flag: a source keeps one clone where it hands out work and +/// gives another to its [`ScanExec`]. +#[derive(Clone, Debug, Default)] +pub struct ExhaustedFlag(Arc); + +impl ExhaustedFlag { + /// A flag that is not yet set. + pub fn new() -> Self { + Self::default() + } + + /// Marks the scan exhausted. Later calls do nothing. + pub fn set(&self) { + if !self.0.load(Ordering::Relaxed) { + self.0.store(true, Ordering::Release); + } + } + + /// Whether the flag is set. + pub fn is_set(&self) -> bool { + self.0.load(Ordering::Acquire) + } +} + +/// An opened scan: the work that its host threads share. +/// +/// A host that runs its own threads, or whose partitions share the scan's work, opens the scan +/// once and has each thread or partition read a [`stream`](Self::stream) of it. The streams take +/// work until none is left, so together they return every row of the scan exactly once, in no +/// particular order across streams. The number of streams a host reads is its parallelism. +/// Clones of a `ScanExec` share the same work, so a host keeps one per scan wherever its threads +/// can reach it. +/// +/// A host decides whether another thread should join the scan with +/// [`is_exhausted`](Self::is_exhausted), which never blocks and writes nothing, so it is cheap +/// under a host's own lock. It creates the joining thread's stream after releasing that lock. +#[derive(Clone)] +pub struct ScanExec { + dtype: DType, + exhausted: ExhaustedFlag, + new_worker: Arc, +} + +impl ScanExec { + /// An opened scan whose streams each read a worker from `new_worker`. + /// + /// The workers that `new_worker` returns must share one queue of work, so that together they + /// return every row exactly once. Creating a worker must be cheap and read nothing: a worker + /// takes its first work when it is first polled. The source sets `exhausted` once a worker + /// created afterwards would find no work. + pub fn new( + dtype: DType, + exhausted: ExhaustedFlag, + new_worker: impl Fn() -> BoxStream<'static, VortexResult> + Send + Sync + 'static, + ) -> Self { + Self { + dtype, + exhausted, + new_worker: Arc::new(new_worker), + } + } + + /// An opened scan whose streams take the partitions of `scan` one at a time. + /// + /// A source that has no queue of work of its own can open into this one. It does not know its + /// work up front, so it is exhausted only once a stream finds the partitions have run out. + pub fn from_partitions(scan: DataSourceScanRef) -> Self { + let dtype = scan.dtype().clone(); + let exhausted = ExhaustedFlag::new(); + let partitions = Arc::new(Mutex::new(scan.partitions())); + let flag = exhausted.clone(); + Self::new(dtype, exhausted, move || { + let flag = flag.clone(); + let partitions = stream::unfold(Arc::clone(&partitions), move |shared| { + let flag = flag.clone(); + async move { + let Some(next) = shared.lock().await.next().await else { + flag.set(); + return None; + }; + Some((next, shared)) + } + }); + partitions + .flat_map( + |partition| match partition.and_then(|partition| partition.execute()) { + Ok(arrays) => arrays.left_stream(), + Err(err) => stream::once(async move { Err(err) }).right_stream(), + }, + ) + .boxed() + }) + } + + /// The dtype of the scan's arrays. + pub fn dtype(&self) -> &DType { + &self.dtype + } + + /// Whether a stream created now would find no work. Never blocks, and writes nothing. + /// + /// Once true it stays true. While it is false a new stream may still find nothing, because + /// streams take their work only when first polled. + pub fn is_exhausted(&self) -> bool { + self.exhausted.is_set() + } + + /// A new stream over the scan's remaining work, which one host thread or partition reads. + pub fn stream(&self) -> ScanStream { + ScanStream { + dtype: self.dtype.clone(), + worker: (self.new_worker)(), + } + } +} + +impl fmt::Debug for ScanExec { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("ScanExec") + .field("dtype", &self.dtype) + .field("exhausted", &self.is_exhausted()) + .finish_non_exhaustive() + } +} + +/// One worker over the work of a [`ScanExec`], which one host thread or partition reads. +/// +/// The work may run as tasks on the session's runtime, which the host owns, and nothing starts +/// threads of its own. A host whose runtime has no threads of its own, such as a +/// `CurrentThreadRuntime`, must therefore drive that runtime while it waits on a stream, for +/// example with `block_on`. Dropping a stream before it ends gives up any work it had taken, so a +/// host drops a stream early only when it abandons the scan. +pub struct ScanStream { + dtype: DType, + worker: BoxStream<'static, VortexResult>, +} + +impl fmt::Debug for ScanStream { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("ScanStream") + .field("dtype", &self.dtype) + .finish_non_exhaustive() + } +} + +impl Stream for ScanStream { + type Item = VortexResult; + + fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + self.worker.poll_next_unpin(cx) + } +} + +impl ArrayStream for ScanStream { + fn dtype(&self) -> &DType { + &self.dtype + } +} + +#[cfg(test)] +mod tests { + use std::any::Any; + use std::num::NonZeroUsize; + + use futures::StreamExt; + use futures::TryStreamExt; + use futures::executor::block_on; + use futures::future::try_join_all; + use futures::stream; + use vortex_array::ArrayRef; + use vortex_array::IntoArray; + use vortex_array::dtype::DType; + use vortex_array::dtype::Nullability; + use vortex_array::dtype::PType; + use vortex_array::expr::stats::Precision; + use vortex_array::stream::ArrayStreamAdapter; + use vortex_array::stream::ArrayStreamExt; + use vortex_array::stream::SendableArrayStream; + use vortex_buffer::Buffer; + use vortex_error::VortexResult; + + use super::ScanExec; + use super::ScanStream; + use crate::DataSourceScan; + use crate::DataSourceScanRef; + use crate::Partition; + use crate::PartitionRef; + use crate::PartitionStream; + + static DTYPE: DType = DType::Primitive(PType::I32, Nullability::NonNullable); + + /// A partition of `rows` rows, returned as one array. + struct RowsPartition { + index: usize, + rows: usize, + } + + impl Partition for RowsPartition { + fn as_any(&self) -> &dyn Any { + self + } + + fn index(&self) -> usize { + self.index + } + + fn row_count(&self) -> Precision { + Precision::exact(self.rows as u64) + } + + fn byte_size(&self) -> Precision { + Precision::Absent + } + + fn execute(self: Box) -> VortexResult { + let array = rows_array(self.rows)?; + Ok(ArrayStreamExt::boxed(ArrayStreamAdapter::new( + DTYPE.clone(), + stream::iter([Ok(array)]), + ))) + } + } + + /// The array of `rows` rows that a test partition returns. + fn rows_array(rows: usize) -> VortexResult { + Ok(Buffer::from_iter(0..i32::try_from(rows)?).into_array()) + } + + /// A scan that has no queue of work of its own, so it opens into [`ScanExec::from_partitions`]. + struct PartitionOnlyScan { + rows: Vec, + } + + impl DataSourceScan for PartitionOnlyScan { + fn dtype(&self) -> &DType { + &DTYPE + } + + fn split(self: Box, _n: NonZeroUsize) -> VortexResult> { + Ok(vec![self]) + } + + fn open(self: Box) -> VortexResult { + Ok(ScanExec::from_partitions(self)) + } + + fn partition_count(&self) -> Precision { + Precision::exact(self.rows.len()) + } + + fn partitions(self: Box) -> PartitionStream { + stream::iter( + self.rows.into_iter().enumerate().map(|(index, rows)| { + Ok(Box::new(RowsPartition { index, rows }) as PartitionRef) + }), + ) + .boxed() + } + } + + /// The rows that `streams` return together, each polled concurrently. + fn total_rows(streams: impl IntoIterator) -> VortexResult { + let workers = streams + .into_iter() + .map(|stream| stream.try_fold(0, |rows, array| async move { Ok(rows + array.len()) })); + Ok(block_on(try_join_all(workers))?.into_iter().sum()) + } + + #[test] + fn streams_share_partitions() -> VortexResult<()> { + let exec = Box::new(PartitionOnlyScan { + rows: vec![2, 3, 4, 5], + }) + .open()?; + assert!(!exec.is_exhausted()); + assert_eq!( + total_rows([exec.stream(), exec.stream(), exec.stream()])?, + 14 + ); + assert!(exec.is_exhausted()); + assert_eq!(total_rows([exec.stream()])?, 0); + Ok(()) + } +} diff --git a/vortex-scan/src/test.rs b/vortex-scan/src/test.rs index f57b5559b31..a00404caf54 100644 --- a/vortex-scan/src/test.rs +++ b/vortex-scan/src/test.rs @@ -4,6 +4,7 @@ //! Source-independent fixtures shared by plan and engine tests. use std::any::Any; +use std::num::NonZeroUsize; use std::ops::Range; use std::sync::Arc; use std::sync::LazyLock; @@ -69,6 +70,7 @@ use crate::source::ScanInput; use crate::source::SegmentFuture; use crate::source::SegmentId; use crate::source::SegmentSource; +use crate::stream::ScanExec; pub static SESSION: LazyLock = LazyLock::new(VortexSession::empty); @@ -99,6 +101,14 @@ impl DataSourceScan for TestArrayScan { &self.dtype } + fn split(self: Box, _n: NonZeroUsize) -> VortexResult> { + Ok(vec![self]) + } + + fn open(self: Box) -> VortexResult { + Ok(ScanExec::from_partitions(self)) + } + fn partition_count(&self) -> Precision { Precision::Exact(self.arrays.len()) }