From 28163bf322ca40e976f92c77e1aad29ace7a0393 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Thu, 19 Nov 2026 15:47:01 -0500 Subject: [PATCH 01/16] Add split and open to the Scan API A scan can now be split into independent pieces, or opened into a pool that host threads share by each polling a worker. Both have defaults on top of partitions, so every existing source supports them; sources and hosts move over in later changes. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-scan/src/lib.rs | 41 ++++++++- vortex-scan/src/pool.rs | 180 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 219 insertions(+), 2 deletions(-) create mode 100644 vortex-scan/src/pool.rs diff --git a/vortex-scan/src/lib.rs b/vortex-scan/src/lib.rs index 891c202fe11..299b2a835b7 100644 --- a/vortex-scan/src/lib.rs +++ b/vortex-scan/src/lib.rs @@ -26,6 +26,7 @@ pub mod arrays; pub mod execution; pub mod plan; pub mod planning; +pub mod pool; pub mod prepare; pub mod row_mask; pub mod selection; @@ -39,6 +40,8 @@ use std::sync::Arc; use async_trait::async_trait; use futures::stream::BoxStream; +use pool::PartitionPool; +use pool::ScanPoolRef; use selection::Selection; use vortex_array::aggregate_fn::AggregateFnRef; use vortex_array::dtype::DType; @@ -204,8 +207,13 @@ 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. -pub trait DataSourceScan: 'static + Send { +/// A data source scan reads data from the source. +/// +/// A host reads a scan in one of two ways. It [splits](Self::split) the scan into independent +/// pieces when each piece must be read on its own, such as by another process or with a declared +/// order. Otherwise it [opens](Self::open) the scan into a pool and has each of its threads poll a +/// worker of that pool. +pub trait DataSourceScan: 'static + Send + IntoDataSourceScanRef { /// The returned dtype of the scan. fn dtype(&self) -> &DType; @@ -214,6 +222,35 @@ pub trait DataSourceScan: 'static + Send { /// Returns a stream of partitions to be processed. fn partitions(self: Box) -> PartitionStream; + + /// Cuts the scan into at most `n` scans that together read the same rows, in order. + /// + /// Splitting reads metadata only. The result is never empty. A scan that cannot be cut + /// returns itself as the one piece, which is the default. + fn split(self: Box, n: NonZeroUsize) -> VortexResult> { + let _ = n; + Ok(vec![self.into_data_source_scan_ref()]) + } + + /// Opens the scan into a pool that host threads share by each polling a worker. + /// + /// The default pool hands out the scan's partitions, each to the next worker that asks. + fn open(self: Box) -> VortexResult { + let dtype = self.dtype().clone(); + Ok(Arc::new(PartitionPool::new(dtype, self.partitions()))) + } +} + +/// Converts a boxed scan into a [`DataSourceScanRef`]. Implemented for every scan. +pub trait IntoDataSourceScanRef { + /// Returns this scan as a [`DataSourceScanRef`]. + fn into_data_source_scan_ref(self: Box) -> DataSourceScanRef; +} + +impl IntoDataSourceScanRef for T { + fn into_data_source_scan_ref(self: Box) -> DataSourceScanRef { + self + } } /// A reference-counted partition. diff --git a/vortex-scan/src/pool.rs b/vortex-scan/src/pool.rs new file mode 100644 index 00000000000..ec103cb6506 --- /dev/null +++ b/vortex-scan/src/pool.rs @@ -0,0 +1,180 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Pools of work that host threads share by each polling a worker. + +use std::sync::Arc; + +use async_lock::Mutex; +use futures::StreamExt; +use futures::stream; +use vortex_array::dtype::DType; +use vortex_array::stream::ArrayStreamAdapter; +use vortex_array::stream::ArrayStreamExt; +use vortex_array::stream::SendableArrayStream; + +use crate::PartitionStream; + +/// A shared reference to a [`ScanPool`]. +pub type ScanPoolRef = Arc; + +/// The shared work of an opened scan, which host threads read by each polling a worker. +pub trait ScanPool: 'static + Send + Sync { + /// The dtype of the arrays every worker returns. + fn dtype(&self) -> &DType; + + /// Returns a new worker: a stream its caller polls inline, on its own thread. + /// + /// Workers take work from the pool until none is left, so together they return every row of + /// the scan exactly once. A host may start any number of workers, at any time. A worker never + /// spawns tasks of its own. Dropping a worker before it ends gives up the work it had taken, + /// so a host drops a worker early only when it abandons the scan. + fn worker(self: Arc) -> SendableArrayStream; +} + +/// A pool whose workers take partitions one at a time from a shared partition stream. +pub(crate) struct PartitionPool { + dtype: DType, + partitions: Mutex, +} + +impl PartitionPool { + pub(crate) fn new(dtype: DType, partitions: PartitionStream) -> Self { + Self { + dtype, + partitions: Mutex::new(partitions), + } + } +} + +impl ScanPool for PartitionPool { + fn dtype(&self) -> &DType { + &self.dtype + } + + fn worker(self: Arc) -> SendableArrayStream { + let dtype = self.dtype.clone(); + let partitions = stream::unfold(self, |pool| async move { + let next = pool.partitions.lock().await.next().await?; + Some((next, pool)) + }); + let arrays = 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(), + } + }); + ArrayStreamExt::boxed(ArrayStreamAdapter::new(dtype, arrays)) + } +} + +#[cfg(test)] +mod tests { + use std::any::Any; + use std::num::NonZeroUsize; + use std::sync::Arc; + + use futures::StreamExt; + use futures::TryStreamExt; + use futures::executor::block_on; + use futures::future::try_join_all; + use futures::stream; + 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 crate::DataSourceScan; + 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 = Buffer::from_iter(0..self.rows as i32).into_array(); + Ok(ArrayStreamExt::boxed(ArrayStreamAdapter::new( + DTYPE.clone(), + stream::iter([Ok(array)]), + ))) + } + } + + /// A scan that implements only the partition methods. + struct PartitionOnlyScan { + rows: Vec, + } + + impl DataSourceScan for PartitionOnlyScan { + fn dtype(&self) -> &DType { + &DTYPE + } + + 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() + } + } + + #[test] + fn default_open_shares_partitions_across_workers() -> VortexResult<()> { + let scan = Box::new(PartitionOnlyScan { + rows: vec![2, 3, 4, 5], + }); + let pool = scan.open()?; + let workers = (0..3).map(|_| { + Arc::clone(&pool) + .worker() + .try_fold(0, |rows, array| async move { Ok(rows + array.len()) }) + }); + let rows: usize = block_on(try_join_all(workers))?.into_iter().sum(); + assert_eq!(rows, 14); + Ok(()) + } + + #[test] + fn default_split_returns_the_scan() -> VortexResult<()> { + let scan = Box::new(PartitionOnlyScan { rows: vec![2, 3] }); + let pieces = scan.split(NonZeroUsize::new(4).unwrap_or(NonZeroUsize::MIN))?; + assert_eq!(pieces.len(), 1); + assert_eq!(pieces[0].partition_count(), Precision::exact(2usize)); + Ok(()) + } +} From 525b5650c178015789d75866e84c2bf02cf0013d Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Thu, 19 Nov 2026 18:30:07 -0500 Subject: [PATCH 02/16] Let pool workers spawn onto the session runtime Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-scan/src/pool.rs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/vortex-scan/src/pool.rs b/vortex-scan/src/pool.rs index ec103cb6506..c607bfbee75 100644 --- a/vortex-scan/src/pool.rs +++ b/vortex-scan/src/pool.rs @@ -26,9 +26,10 @@ pub trait ScanPool: 'static + Send + Sync { /// Returns a new worker: a stream its caller polls inline, on its own thread. /// /// Workers take work from the pool until none is left, so together they return every row of - /// the scan exactly once. A host may start any number of workers, at any time. A worker never - /// spawns tasks of its own. Dropping a worker before it ends gives up the work it had taken, - /// so a host drops a worker early only when it abandons the scan. + /// the scan exactly once. A host may start any number of workers, at any time. A worker may + /// spawn its work onto the session's runtime, so its splits decode concurrently and their I/O + /// starts early, but it starts no threads of its own. Dropping a worker before it ends gives + /// up the work it had taken, so a host drops a worker early only when it abandons the scan. fn worker(self: Arc) -> SendableArrayStream; } From 17033023590f367e00b9a9032058ea9a5eb10fef Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Thu, 19 Nov 2026 18:55:54 -0500 Subject: [PATCH 03/16] Report pool progress and exhaustion, and plan-time scan size Settle the ScanPool trait before hosts build on it: progress() and is_exhausted() let a host draw a progress bar and stop starting workers on a drained pool. Both have safe defaults. DataSourceScan gains plan-time row_count/byte_size estimates, and PartitionPool becomes public so a scan that cannot split can still open over its partitions. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-scan/src/lib.rs | 15 +++++- vortex-scan/src/pool.rs | 100 ++++++++++++++++++++++++++++++++++++---- 2 files changed, 103 insertions(+), 12 deletions(-) diff --git a/vortex-scan/src/lib.rs b/vortex-scan/src/lib.rs index 299b2a835b7..ac3ceca127f 100644 --- a/vortex-scan/src/lib.rs +++ b/vortex-scan/src/lib.rs @@ -223,6 +223,16 @@ pub trait DataSourceScan: 'static + Send + IntoDataSourceScanRef { /// Returns a stream of partitions to be processed. fn partitions(self: Box) -> PartitionStream; + /// Estimates the rows this scan returns, from plan-time state only. + fn row_count(&self) -> Precision { + Precision::Absent + } + + /// Estimates the bytes this scan reads, before any filter, from plan-time state only. + fn byte_size(&self) -> Precision { + Precision::Absent + } + /// Cuts the scan into at most `n` scans that together read the same rows, in order. /// /// Splitting reads metadata only. The result is never empty. A scan that cannot be cut @@ -236,8 +246,9 @@ pub trait DataSourceScan: 'static + Send + IntoDataSourceScanRef { /// /// The default pool hands out the scan's partitions, each to the next worker that asks. fn open(self: Box) -> VortexResult { - let dtype = self.dtype().clone(); - Ok(Arc::new(PartitionPool::new(dtype, self.partitions()))) + Ok(Arc::new(PartitionPool::new( + self.into_data_source_scan_ref(), + ))) } } diff --git a/vortex-scan/src/pool.rs b/vortex-scan/src/pool.rs index c607bfbee75..e61d38238a5 100644 --- a/vortex-scan/src/pool.rs +++ b/vortex-scan/src/pool.rs @@ -4,15 +4,20 @@ //! Pools of work that host threads share by each polling a worker. use std::sync::Arc; +use std::sync::atomic::AtomicBool; +use std::sync::atomic::AtomicUsize; +use std::sync::atomic::Ordering; use async_lock::Mutex; use futures::StreamExt; use futures::stream; 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 crate::DataSourceScanRef; use crate::PartitionStream; /// A shared reference to a [`ScanPool`]. @@ -23,27 +28,56 @@ pub trait ScanPool: 'static + Send + Sync { /// The dtype of the arrays every worker returns. fn dtype(&self) -> &DType; - /// Returns a new worker: a stream its caller polls inline, on its own thread. + /// Returns a new worker: a stream that one host thread polls. /// /// Workers take work from the pool until none is left, so together they return every row of /// the scan exactly once. A host may start any number of workers, at any time. A worker may /// spawn its work onto the session's runtime, so its splits decode concurrently and their I/O - /// starts early, but it starts no threads of its own. Dropping a worker before it ends gives - /// up the work it had taken, so a host drops a worker early only when it abandons the scan. + /// starts early, but it never starts threads of its own. Dropping a worker before it ends + /// gives up the work it had taken, so a host drops a worker early only when it abandons the + /// scan. fn worker(self: Arc) -> SendableArrayStream; + + /// The fraction of the pool's work that workers have taken, from 0.0 to 1.0, for a host's + /// progress bar. Never blocks. + fn progress(&self) -> f64 { + 0.0 + } + + /// Whether workers have taken every unit of the pool, so a new worker would return nothing. + /// + /// A host that moves threads between pools uses it to stop starting workers on a drained + /// pool. `false` is always a safe answer. Never blocks. + fn is_exhausted(&self) -> bool { + false + } } -/// A pool whose workers take partitions one at a time from a shared partition stream. -pub(crate) struct PartitionPool { +/// A pool whose workers take partitions one at a time from a scan's shared partition stream. +/// +/// This is the default [`open`](crate::DataSourceScan::open) of every scan. +pub struct PartitionPool { dtype: DType, partitions: Mutex, + /// The scan's partition count, if it is known or estimated. + partition_count: Option, + taken: AtomicUsize, + exhausted: AtomicBool, } impl PartitionPool { - pub(crate) fn new(dtype: DType, partitions: PartitionStream) -> Self { + /// Opens a pool over the partitions of `scan`. + pub fn new(scan: DataSourceScanRef) -> Self { + let partition_count = match scan.partition_count() { + Precision::Exact(count) | Precision::Inexact(count) => Some(count), + Precision::Absent => None, + }; Self { - dtype, - partitions: Mutex::new(partitions), + dtype: scan.dtype().clone(), + partitions: Mutex::new(scan.partitions()), + partition_count, + taken: AtomicUsize::new(0), + exhausted: AtomicBool::new(false), } } } @@ -56,7 +90,11 @@ impl ScanPool for PartitionPool { fn worker(self: Arc) -> SendableArrayStream { let dtype = self.dtype.clone(); let partitions = stream::unfold(self, |pool| async move { - let next = pool.partitions.lock().await.next().await?; + let Some(next) = pool.partitions.lock().await.next().await else { + pool.exhausted.store(true, Ordering::Release); + return None; + }; + pool.taken.fetch_add(1, Ordering::Relaxed); Some((next, pool)) }); let arrays = partitions.flat_map(|partition| { @@ -67,6 +105,22 @@ impl ScanPool for PartitionPool { }); ArrayStreamExt::boxed(ArrayStreamAdapter::new(dtype, arrays)) } + + fn progress(&self) -> f64 { + if self.exhausted.load(Ordering::Acquire) { + return 1.0; + } + match self.partition_count { + Some(count) if count > 0 => { + (self.taken.load(Ordering::Relaxed) as f64 / count as f64).clamp(0.0, 1.0) + } + _ => 0.0, + } + } + + fn is_exhausted(&self) -> bool { + self.exhausted.load(Ordering::Acquire) + } } #[cfg(test)] @@ -122,7 +176,7 @@ mod tests { } fn execute(self: Box) -> VortexResult { - let array = Buffer::from_iter(0..self.rows as i32).into_array(); + let array = Buffer::from_iter(0..i32::try_from(self.rows)?).into_array(); Ok(ArrayStreamExt::boxed(ArrayStreamAdapter::new( DTYPE.clone(), stream::iter([Ok(array)]), @@ -170,6 +224,32 @@ mod tests { Ok(()) } + /// Progress counts partitions as workers take them, and the pool is exhausted once a worker + /// finds none left. + #[test] + fn default_pool_reports_progress_and_exhaustion() -> VortexResult<()> { + let scan = Box::new(PartitionOnlyScan { + rows: vec![2, 3, 4, 5], + }); + let pool = scan.open()?; + assert_eq!(pool.progress(), 0.0); + assert!(!pool.is_exhausted()); + + let mut worker = Arc::clone(&pool).worker(); + let first = block_on(worker.next()).transpose()?; + assert_eq!(first.map(|array| array.len()), Some(2)); + assert_eq!(pool.progress(), 0.25); + assert!(!pool.is_exhausted()); + + let rest = + block_on(worker.try_fold(0, |rows, array| async move { Ok(rows + array.len()) }))?; + assert_eq!(rest, 12); + assert_eq!(pool.progress(), 1.0); + assert!(pool.is_exhausted()); + assert!(block_on(Arc::clone(&pool).worker().next()).is_none()); + Ok(()) + } + #[test] fn default_split_returns_the_scan() -> VortexResult<()> { let scan = Box::new(PartitionOnlyScan { rows: vec![2, 3] }); From 5703e0e6e070f0b50361fe3bc1cfb380db4b2627 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Thu, 19 Nov 2026 19:15:57 -0500 Subject: [PATCH 04/16] Document split_concurrency for pool workers Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-scan/src/lib.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/vortex-scan/src/lib.rs b/vortex-scan/src/lib.rs index ac3ceca127f..3a5899f31a6 100644 --- a/vortex-scan/src/lib.rs +++ b/vortex-scan/src/lib.rs @@ -179,7 +179,8 @@ 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 of each partition, or of each worker of an opened scan's pool, to decode + /// at once. /// /// `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 From 3148faa155f31358c1b6cb1a45661dcd28d3bf41 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Thu, 19 Nov 2026 20:08:23 -0500 Subject: [PATCH 05/16] Say that hosts drive the runtime their pool workers spawn onto A worker is one host thread's share of a pool's output, while the pool's work runs as tasks on the session's runtime. A host whose runtime has no threads of its own must drive it while waiting on a worker. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-scan/src/lib.rs | 3 +-- vortex-scan/src/pool.rs | 12 +++++++----- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/vortex-scan/src/lib.rs b/vortex-scan/src/lib.rs index 3a5899f31a6..e6d409034ba 100644 --- a/vortex-scan/src/lib.rs +++ b/vortex-scan/src/lib.rs @@ -179,8 +179,7 @@ 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, or of each worker of an opened scan's pool, to decode - /// at once. + /// The most splits of each partition, or of an opened scan's pool, to decode at once. /// /// `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 diff --git a/vortex-scan/src/pool.rs b/vortex-scan/src/pool.rs index e61d38238a5..e4002d0ae3e 100644 --- a/vortex-scan/src/pool.rs +++ b/vortex-scan/src/pool.rs @@ -31,11 +31,13 @@ pub trait ScanPool: 'static + Send + Sync { /// Returns a new worker: a stream that one host thread polls. /// /// Workers take work from the pool until none is left, so together they return every row of - /// the scan exactly once. A host may start any number of workers, at any time. A worker may - /// spawn its work onto the session's runtime, so its splits decode concurrently and their I/O - /// starts early, but it never starts threads of its own. Dropping a worker before it ends - /// gives up the work it had taken, so a host drops a worker early only when it abandons the - /// scan. + /// the scan exactly once. A host may start any number of workers, at any time, and the number + /// it runs is its parallelism. A pool may run its work as tasks on the session's runtime, + /// which the host owns, and hand each result to whichever worker asks next; it never 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 worker, for + /// example with `block_on`. Dropping a worker before it ends gives up any work it had taken, + /// so a host drops a worker early only when it abandons the scan. fn worker(self: Arc) -> SendableArrayStream; /// The fraction of the pool's work that workers have taken, from 0.0 to 1.0, for a host's From 794ac0c4cd896121afdba08c4c6215468276837f Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 13:12:31 -0500 Subject: [PATCH 06/16] Make split and open the methods every scan implements A source now puts its own tuned execution behind split and open instead of tuning one shared pool to fit every engine. partitions() gets a default derived from them: one partition per split piece, each draining one worker of the piece's opened pool. PartitionPool stays as the stopgap open for a source that still implements partitions(), which is what every in-repo scan does for now. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-datafusion/src/v2/source.rs | 11 +++ vortex-layout/src/scan/layout.rs | 18 ++++ vortex-layout/src/scan/multi.rs | 10 ++ vortex-scan/src/lib.rs | 76 ++++++++------- vortex-scan/src/pool.rs | 144 +++++++++++++++++++++++++++-- 5 files changed, 215 insertions(+), 44 deletions(-) diff --git a/vortex-datafusion/src/v2/source.rs b/vortex-datafusion/src/v2/source.rs index cefefb0f696..40b0523a112 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,8 @@ mod tests { use vortex::scan::Partition; use vortex::scan::PartitionRef; use vortex::scan::PartitionStream; + use vortex::scan::pool::PartitionPool; + use vortex::scan::pool::ScanPoolRef; use vortex::session::VortexSession; use vortex_arrow::ArrowSessionExt; @@ -1221,6 +1224,14 @@ mod tests { &self.dtype } + fn split(self: Box, _n: NonZeroUsize) -> VortexResult> { + Ok(vec![self]) + } + + fn open(self: Box) -> VortexResult { + Ok(Arc::new(PartitionPool::new(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 a0ab69310f8..6d25f042a60 100644 --- a/vortex-layout/src/scan/layout.rs +++ b/vortex-layout/src/scan/layout.rs @@ -37,6 +37,8 @@ use vortex_scan::Partition; use vortex_scan::PartitionRef; use vortex_scan::PartitionStream; use vortex_scan::ScanRequest; +use vortex_scan::pool::PartitionPool; +use vortex_scan::pool::ScanPoolRef; use vortex_scan::selection::Selection; use vortex_session::VortexSession; @@ -244,6 +246,14 @@ impl DataSourceScan for LayoutReaderScan { &self.dtype } + fn split(self: Box, _n: NonZeroUsize) -> VortexResult> { + Ok(vec![self]) + } + + fn open(self: Box) -> VortexResult { + Ok(Arc::new(PartitionPool::new(self))) + } + fn partition_count(&self) -> Precision { let (lower, upper) = self.size_hint(); match upper { @@ -403,6 +413,14 @@ impl DataSourceScan for Empty { &self.dtype } + fn split(self: Box, _n: NonZeroUsize) -> VortexResult> { + Ok(vec![self]) + } + + fn open(self: Box) -> VortexResult { + Ok(Arc::new(PartitionPool::new(self))) + } + fn partition_count(&self) -> Precision { Precision::exact(1usize) } diff --git a/vortex-layout/src/scan/multi.rs b/vortex-layout/src/scan/multi.rs index 1f1ee275688..630ea7da9c8 100644 --- a/vortex-layout/src/scan/multi.rs +++ b/vortex-layout/src/scan/multi.rs @@ -57,6 +57,8 @@ use vortex_scan::Partition; use vortex_scan::PartitionRef; use vortex_scan::PartitionStream; use vortex_scan::ScanRequest; +use vortex_scan::pool::PartitionPool; +use vortex_scan::pool::ScanPoolRef; use vortex_scan::selection::Selection; use vortex_session::VortexSession; use vortex_utils::parallelism::get_available_parallelism; @@ -393,6 +395,14 @@ impl DataSourceScan for MultiLayoutScan { &self.dtype } + fn split(self: Box, _n: NonZeroUsize) -> VortexResult> { + Ok(vec![self]) + } + + fn open(self: Box) -> VortexResult { + Ok(Arc::new(PartitionPool::new(self))) + } + fn partition_count(&self) -> Precision { let count = self.ready.len() + self.deferred.len(); if self.deferred.is_empty() { diff --git a/vortex-scan/src/lib.rs b/vortex-scan/src/lib.rs index e6d409034ba..5a86a27aaa8 100644 --- a/vortex-scan/src/lib.rs +++ b/vortex-scan/src/lib.rs @@ -39,8 +39,10 @@ use std::ops::Range; use std::sync::Arc; use async_trait::async_trait; +use futures::StreamExt; +use futures::stream; use futures::stream::BoxStream; -use pool::PartitionPool; +use pool::ScanPartition; use pool::ScanPoolRef; use selection::Selection; use vortex_array::aggregate_fn::AggregateFnRef; @@ -55,6 +57,7 @@ use vortex_array::stream::SendableArrayStream; use vortex_error::VortexResult; use vortex_error::vortex_bail; use vortex_session::VortexSession; +use vortex_utils::parallelism::get_available_parallelism; /// A sendable stream of partitions. pub type PartitionStream = BoxStream<'static, VortexResult>; @@ -213,15 +216,50 @@ pub type DataSourceScanRef = Box; /// pieces when each piece must be read on its own, such as by another process or with a declared /// order. Otherwise it [opens](Self::open) the scan into a pool and has each of its threads poll a /// worker of that pool. -pub trait DataSourceScan: 'static + Send + IntoDataSourceScanRef { +/// +/// A source implements [`split`](Self::split) and [`open`](Self::open) by putting its own tuned +/// execution behind them. [`partitions`](Self::partitions) is derived from them for hosts that +/// still read partitions. +pub trait DataSourceScan: 'static + Send { /// The returned dtype of the scan. fn dtype(&self) -> &DType; + /// Cuts the scan into at most `n` scans that together read the same rows, in order. + /// + /// Splitting reads metadata only. The result is never empty. A scan that cannot be cut + /// returns itself as the one piece. + fn split(self: Box, n: NonZeroUsize) -> VortexResult>; + + /// Opens the scan into a pool that host threads share by each polling a worker. + /// + /// A source that has no pool of its own yet may return a + /// [`PartitionPool`](pool::PartitionPool) over itself, as long as it implements + /// [`partitions`](Self::partitions): the default `partitions` opens the scan, so the two + /// together would never end. + fn open(self: Box) -> VortexResult; + /// Returns an estimate of the total number of partitions the scan will produce. - fn partition_count(&self) -> Precision; + fn partition_count(&self) -> Precision { + Precision::Absent + } /// Returns a stream of partitions to be processed. - fn partitions(self: Box) -> PartitionStream; + /// + /// The default [splits](Self::split) the scan into one piece per available core and makes + /// each piece a partition, which [opens](Self::open) the piece and drains one worker of its + /// pool. + fn partitions(self: Box) -> PartitionStream { + let n = get_available_parallelism() + .and_then(NonZeroUsize::new) + .unwrap_or(NonZeroUsize::MIN); + match self.split(n) { + Ok(pieces) => stream::iter(pieces.into_iter().enumerate().map(|(index, scan)| { + Ok(Box::new(ScanPartition::new(index, scan)) as PartitionRef) + })) + .boxed(), + Err(err) => stream::once(async move { Err(err) }).boxed(), + } + } /// Estimates the rows this scan returns, from plan-time state only. fn row_count(&self) -> Precision { @@ -232,36 +270,6 @@ pub trait DataSourceScan: 'static + Send + IntoDataSourceScanRef { fn byte_size(&self) -> Precision { Precision::Absent } - - /// Cuts the scan into at most `n` scans that together read the same rows, in order. - /// - /// Splitting reads metadata only. The result is never empty. A scan that cannot be cut - /// returns itself as the one piece, which is the default. - fn split(self: Box, n: NonZeroUsize) -> VortexResult> { - let _ = n; - Ok(vec![self.into_data_source_scan_ref()]) - } - - /// Opens the scan into a pool that host threads share by each polling a worker. - /// - /// The default pool hands out the scan's partitions, each to the next worker that asks. - fn open(self: Box) -> VortexResult { - Ok(Arc::new(PartitionPool::new( - self.into_data_source_scan_ref(), - ))) - } -} - -/// Converts a boxed scan into a [`DataSourceScanRef`]. Implemented for every scan. -pub trait IntoDataSourceScanRef { - /// Returns this scan as a [`DataSourceScanRef`]. - fn into_data_source_scan_ref(self: Box) -> DataSourceScanRef; -} - -impl IntoDataSourceScanRef for T { - fn into_data_source_scan_ref(self: Box) -> DataSourceScanRef { - self - } } /// A reference-counted partition. diff --git a/vortex-scan/src/pool.rs b/vortex-scan/src/pool.rs index e4002d0ae3e..26dbeedc8b2 100644 --- a/vortex-scan/src/pool.rs +++ b/vortex-scan/src/pool.rs @@ -3,6 +3,7 @@ //! Pools of work that host threads share by each polling a worker. +use std::any::Any; use std::sync::Arc; use std::sync::atomic::AtomicBool; use std::sync::atomic::AtomicUsize; @@ -16,8 +17,10 @@ use vortex_array::expr::stats::Precision; use vortex_array::stream::ArrayStreamAdapter; use vortex_array::stream::ArrayStreamExt; use vortex_array::stream::SendableArrayStream; +use vortex_error::VortexResult; use crate::DataSourceScanRef; +use crate::Partition; use crate::PartitionStream; /// A shared reference to a [`ScanPool`]. @@ -57,7 +60,8 @@ pub trait ScanPool: 'static + Send + Sync { /// A pool whose workers take partitions one at a time from a scan's shared partition stream. /// -/// This is the default [`open`](crate::DataSourceScan::open) of every scan. +/// A source without a pool of its own can open into this one, as long as it implements +/// [`partitions`](crate::DataSourceScan::partitions) itself. pub struct PartitionPool { dtype: DType, partitions: Mutex, @@ -125,9 +129,46 @@ impl ScanPool for PartitionPool { } } +/// A piece of a split scan as a partition, which opens the piece and drains one worker of it. +/// +/// This is how the default [`partitions`](crate::DataSourceScan::partitions) reads a scan. +pub(crate) struct ScanPartition { + index: usize, + scan: DataSourceScanRef, +} + +impl ScanPartition { + pub(crate) fn new(index: usize, scan: DataSourceScanRef) -> Self { + Self { index, scan } + } +} + +impl Partition for ScanPartition { + fn as_any(&self) -> &dyn Any { + self + } + + fn index(&self) -> usize { + self.index + } + + fn row_count(&self) -> Precision { + self.scan.row_count() + } + + fn byte_size(&self) -> Precision { + self.scan.byte_size() + } + + fn execute(self: Box) -> VortexResult { + Ok(self.scan.open()?.worker()) + } +} + #[cfg(test)] mod tests { use std::any::Any; + use std::collections::VecDeque; use std::num::NonZeroUsize; use std::sync::Arc; @@ -136,6 +177,8 @@ mod tests { use futures::executor::block_on; use futures::future::try_join_all; use futures::stream; + use parking_lot::Mutex; + use vortex_array::ArrayRef; use vortex_array::IntoArray; use vortex_array::dtype::DType; use vortex_array::dtype::Nullability; @@ -147,7 +190,11 @@ mod tests { use vortex_buffer::Buffer; use vortex_error::VortexResult; + use super::PartitionPool; + use super::ScanPool; + use super::ScanPoolRef; use crate::DataSourceScan; + use crate::DataSourceScanRef; use crate::Partition; use crate::PartitionRef; use crate::PartitionStream; @@ -178,7 +225,7 @@ mod tests { } fn execute(self: Box) -> VortexResult { - let array = Buffer::from_iter(0..i32::try_from(self.rows)?).into_array(); + let array = rows_array(self.rows)?; Ok(ArrayStreamExt::boxed(ArrayStreamAdapter::new( DTYPE.clone(), stream::iter([Ok(array)]), @@ -186,7 +233,12 @@ mod tests { } } - /// A scan that implements only the partition methods. + /// The array of `rows` rows that a test partition or pool returns. + fn rows_array(rows: usize) -> VortexResult { + Ok(Buffer::from_iter(0..i32::try_from(rows)?).into_array()) + } + + /// A scan that has no pool of its own, so it opens into a [`PartitionPool`]. struct PartitionOnlyScan { rows: Vec, } @@ -196,6 +248,14 @@ mod tests { &DTYPE } + fn split(self: Box, _n: NonZeroUsize) -> VortexResult> { + Ok(vec![self]) + } + + fn open(self: Box) -> VortexResult { + Ok(Arc::new(PartitionPool::new(self))) + } + fn partition_count(&self) -> Precision { Precision::exact(self.rows.len()) } @@ -211,7 +271,7 @@ mod tests { } #[test] - fn default_open_shares_partitions_across_workers() -> VortexResult<()> { + fn partition_pool_shares_partitions_across_workers() -> VortexResult<()> { let scan = Box::new(PartitionOnlyScan { rows: vec![2, 3, 4, 5], }); @@ -229,7 +289,7 @@ mod tests { /// Progress counts partitions as workers take them, and the pool is exhausted once a worker /// finds none left. #[test] - fn default_pool_reports_progress_and_exhaustion() -> VortexResult<()> { + fn partition_pool_reports_progress_and_exhaustion() -> VortexResult<()> { let scan = Box::new(PartitionOnlyScan { rows: vec![2, 3, 4, 5], }); @@ -252,12 +312,76 @@ mod tests { Ok(()) } + /// A scan that implements only `split` and `open`, with a pool of its own. + struct SplitOnlyScan { + rows: Vec, + } + + impl DataSourceScan for SplitOnlyScan { + fn dtype(&self) -> &DType { + &DTYPE + } + + fn split(self: Box, n: NonZeroUsize) -> VortexResult> { + let size = self.rows.len().div_ceil(n.get()).max(1); + Ok(self + .rows + .chunks(size) + .map(|rows| { + Box::new(SplitOnlyScan { + rows: rows.to_vec(), + }) as DataSourceScanRef + }) + .collect()) + } + + fn open(self: Box) -> VortexResult { + Ok(Arc::new(RowsPool { + rows: Mutex::new(self.rows.into()), + })) + } + } + + /// A pool whose workers each take the next count of rows. + struct RowsPool { + rows: Mutex>, + } + + impl ScanPool for RowsPool { + fn dtype(&self) -> &DType { + &DTYPE + } + + fn worker(self: Arc) -> SendableArrayStream { + let arrays = stream::unfold(self, |pool| async move { + let rows = pool.rows.lock().pop_front()?; + Some((rows_array(rows), pool)) + }); + ArrayStreamExt::boxed(ArrayStreamAdapter::new(DTYPE.clone(), arrays)) + } + } + + /// The default `partitions` reads a scan that implements only `split` and `open`, one + /// partition per piece. #[test] - fn default_split_returns_the_scan() -> VortexResult<()> { - let scan = Box::new(PartitionOnlyScan { rows: vec![2, 3] }); - let pieces = scan.split(NonZeroUsize::new(4).unwrap_or(NonZeroUsize::MIN))?; - assert_eq!(pieces.len(), 1); - assert_eq!(pieces[0].partition_count(), Precision::exact(2usize)); + fn default_partitions_open_each_piece() -> VortexResult<()> { + let scan = Box::new(SplitOnlyScan { + rows: vec![2, 3, 4, 5], + }); + let partitions: Vec = block_on(scan.partitions().try_collect())?; + assert!(!partitions.is_empty()); + for (index, partition) in partitions.iter().enumerate() { + assert_eq!(partition.index(), index); + } + let rows = block_on(try_join_all(partitions.into_iter().map( + |partition| async move { + partition + .execute()? + .try_fold(0, |rows, array| async move { Ok(rows + array.len()) }) + .await + }, + )))?; + assert_eq!(rows.into_iter().sum::(), 14); Ok(()) } } From 93e06a51da97bf048ce95b673e57552bcfd4acc7 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 13:47:24 -0500 Subject: [PATCH 07/16] Require every scan pool to report when all its work is taken A host reading several pools, one per file of a table, moves threads to the next pool once the current one is exhausted, so is_exhausted must turn true once every unit is taken, not once the work finishes. PartitionPool reports it as soon as it has taken an exact partition count. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-scan/src/pool.rs | 50 +++++++++++++++++++++++++++++++++-------- 1 file changed, 41 insertions(+), 9 deletions(-) diff --git a/vortex-scan/src/pool.rs b/vortex-scan/src/pool.rs index 26dbeedc8b2..cb099c91ce1 100644 --- a/vortex-scan/src/pool.rs +++ b/vortex-scan/src/pool.rs @@ -49,13 +49,18 @@ pub trait ScanPool: 'static + Send + Sync { 0.0 } - /// Whether workers have taken every unit of the pool, so a new worker would return nothing. + /// Whether workers have taken every unit of the pool's work, so a new worker would return + /// nothing. Units taken may still be running in the workers that took them. /// - /// A host that moves threads between pools uses it to stop starting workers on a drained - /// pool. `false` is always a safe answer. Never blocks. - fn is_exhausted(&self) -> bool { - false - } + /// A host that reads several pools, such as one per file of a table, moves a thread to the + /// next pool once the current one is exhausted, while the workers that took its last units + /// finish them. A pool that reports exhaustion only once its work has finished makes every + /// thread wait for the slowest unit before any moves on. + /// + /// It must never be true while a unit is left to take. It must be true once every unit is + /// taken, or at the latest once a worker has asked for another unit and found none, for a + /// pool that cannot know its last unit in advance. Never blocks. + fn is_exhausted(&self) -> bool; } /// A pool whose workers take partitions one at a time from a scan's shared partition stream. @@ -67,6 +72,8 @@ pub struct PartitionPool { partitions: Mutex, /// The scan's partition count, if it is known or estimated. partition_count: Option, + /// Whether `partition_count` is exact, so the pool is exhausted once that many are taken. + count_is_exact: bool, taken: AtomicUsize, exhausted: AtomicBool, } @@ -74,7 +81,9 @@ pub struct PartitionPool { impl PartitionPool { /// Opens a pool over the partitions of `scan`. pub fn new(scan: DataSourceScanRef) -> Self { - let partition_count = match scan.partition_count() { + let precision = scan.partition_count(); + let count_is_exact = matches!(precision, Precision::Exact(_)); + let partition_count = match precision { Precision::Exact(count) | Precision::Inexact(count) => Some(count), Precision::Absent => None, }; @@ -82,6 +91,7 @@ impl PartitionPool { dtype: scan.dtype().clone(), partitions: Mutex::new(scan.partitions()), partition_count, + count_is_exact, taken: AtomicUsize::new(0), exhausted: AtomicBool::new(false), } @@ -100,7 +110,7 @@ impl ScanPool for PartitionPool { pool.exhausted.store(true, Ordering::Release); return None; }; - pool.taken.fetch_add(1, Ordering::Relaxed); + pool.taken.fetch_add(1, Ordering::Release); Some((next, pool)) }); let arrays = partitions.flat_map(|partition| { @@ -118,7 +128,7 @@ impl ScanPool for PartitionPool { } match self.partition_count { Some(count) if count > 0 => { - (self.taken.load(Ordering::Relaxed) as f64 / count as f64).clamp(0.0, 1.0) + (self.taken.load(Ordering::Acquire) as f64 / count as f64).clamp(0.0, 1.0) } _ => 0.0, } @@ -126,6 +136,10 @@ impl ScanPool for PartitionPool { fn is_exhausted(&self) -> bool { self.exhausted.load(Ordering::Acquire) + || (self.count_is_exact + && self + .partition_count + .is_some_and(|count| self.taken.load(Ordering::Acquire) >= count)) } } @@ -312,6 +326,20 @@ mod tests { Ok(()) } + /// With an exact partition count, the pool is exhausted as soon as its last partition is + /// taken, before the worker that took it asks for more. + #[test] + fn partition_pool_is_exhausted_when_its_last_partition_is_taken() -> VortexResult<()> { + let pool = Box::new(PartitionOnlyScan { rows: vec![2, 3] }).open()?; + let mut worker = Arc::clone(&pool).worker(); + assert!(block_on(worker.next()).is_some()); + assert!(!pool.is_exhausted()); + assert!(block_on(worker.next()).is_some()); + assert!(pool.is_exhausted()); + assert!(block_on(worker.next()).is_none()); + Ok(()) + } + /// A scan that implements only `split` and `open`, with a pool of its own. struct SplitOnlyScan { rows: Vec, @@ -359,6 +387,10 @@ mod tests { }); ArrayStreamExt::boxed(ArrayStreamAdapter::new(DTYPE.clone(), arrays)) } + + fn is_exhausted(&self) -> bool { + self.rows.lock().is_empty() + } } /// The default `partitions` reads a scan that implements only `split` and `open`, one From 1d002df04bdbc1741bdadf8af021f7588868851f Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 13:53:39 -0500 Subject: [PATCH 08/16] Keep only the scan and pool methods the stack's hosts call DataSourceScan::row_count and byte_size and ScanPool::progress and is_exhausted have no caller yet. Each comes back with the host that calls it. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-scan/src/lib.rs | 10 ---- vortex-scan/src/pool.rs | 112 ++-------------------------------------- 2 files changed, 3 insertions(+), 119 deletions(-) diff --git a/vortex-scan/src/lib.rs b/vortex-scan/src/lib.rs index 5a86a27aaa8..5a282ac2a53 100644 --- a/vortex-scan/src/lib.rs +++ b/vortex-scan/src/lib.rs @@ -260,16 +260,6 @@ pub trait DataSourceScan: 'static + Send { Err(err) => stream::once(async move { Err(err) }).boxed(), } } - - /// Estimates the rows this scan returns, from plan-time state only. - fn row_count(&self) -> Precision { - Precision::Absent - } - - /// Estimates the bytes this scan reads, before any filter, from plan-time state only. - fn byte_size(&self) -> Precision { - Precision::Absent - } } /// A reference-counted partition. diff --git a/vortex-scan/src/pool.rs b/vortex-scan/src/pool.rs index cb099c91ce1..b04ec0a0a4d 100644 --- a/vortex-scan/src/pool.rs +++ b/vortex-scan/src/pool.rs @@ -5,9 +5,6 @@ use std::any::Any; use std::sync::Arc; -use std::sync::atomic::AtomicBool; -use std::sync::atomic::AtomicUsize; -use std::sync::atomic::Ordering; use async_lock::Mutex; use futures::StreamExt; @@ -42,25 +39,6 @@ pub trait ScanPool: 'static + Send + Sync { /// example with `block_on`. Dropping a worker before it ends gives up any work it had taken, /// so a host drops a worker early only when it abandons the scan. fn worker(self: Arc) -> SendableArrayStream; - - /// The fraction of the pool's work that workers have taken, from 0.0 to 1.0, for a host's - /// progress bar. Never blocks. - fn progress(&self) -> f64 { - 0.0 - } - - /// Whether workers have taken every unit of the pool's work, so a new worker would return - /// nothing. Units taken may still be running in the workers that took them. - /// - /// A host that reads several pools, such as one per file of a table, moves a thread to the - /// next pool once the current one is exhausted, while the workers that took its last units - /// finish them. A pool that reports exhaustion only once its work has finished makes every - /// thread wait for the slowest unit before any moves on. - /// - /// It must never be true while a unit is left to take. It must be true once every unit is - /// taken, or at the latest once a worker has asked for another unit and found none, for a - /// pool that cannot know its last unit in advance. Never blocks. - fn is_exhausted(&self) -> bool; } /// A pool whose workers take partitions one at a time from a scan's shared partition stream. @@ -70,30 +48,14 @@ pub trait ScanPool: 'static + Send + Sync { pub struct PartitionPool { dtype: DType, partitions: Mutex, - /// The scan's partition count, if it is known or estimated. - partition_count: Option, - /// Whether `partition_count` is exact, so the pool is exhausted once that many are taken. - count_is_exact: bool, - taken: AtomicUsize, - exhausted: AtomicBool, } impl PartitionPool { /// Opens a pool over the partitions of `scan`. pub fn new(scan: DataSourceScanRef) -> Self { - let precision = scan.partition_count(); - let count_is_exact = matches!(precision, Precision::Exact(_)); - let partition_count = match precision { - Precision::Exact(count) | Precision::Inexact(count) => Some(count), - Precision::Absent => None, - }; Self { dtype: scan.dtype().clone(), partitions: Mutex::new(scan.partitions()), - partition_count, - count_is_exact, - taken: AtomicUsize::new(0), - exhausted: AtomicBool::new(false), } } } @@ -106,11 +68,7 @@ impl ScanPool for PartitionPool { fn worker(self: Arc) -> SendableArrayStream { let dtype = self.dtype.clone(); let partitions = stream::unfold(self, |pool| async move { - let Some(next) = pool.partitions.lock().await.next().await else { - pool.exhausted.store(true, Ordering::Release); - return None; - }; - pool.taken.fetch_add(1, Ordering::Release); + let next = pool.partitions.lock().await.next().await?; Some((next, pool)) }); let arrays = partitions.flat_map(|partition| { @@ -121,26 +79,6 @@ impl ScanPool for PartitionPool { }); ArrayStreamExt::boxed(ArrayStreamAdapter::new(dtype, arrays)) } - - fn progress(&self) -> f64 { - if self.exhausted.load(Ordering::Acquire) { - return 1.0; - } - match self.partition_count { - Some(count) if count > 0 => { - (self.taken.load(Ordering::Acquire) as f64 / count as f64).clamp(0.0, 1.0) - } - _ => 0.0, - } - } - - fn is_exhausted(&self) -> bool { - self.exhausted.load(Ordering::Acquire) - || (self.count_is_exact - && self - .partition_count - .is_some_and(|count| self.taken.load(Ordering::Acquire) >= count)) - } } /// A piece of a split scan as a partition, which opens the piece and drains one worker of it. @@ -167,11 +105,11 @@ impl Partition for ScanPartition { } fn row_count(&self) -> Precision { - self.scan.row_count() + Precision::Absent } fn byte_size(&self) -> Precision { - self.scan.byte_size() + Precision::Absent } fn execute(self: Box) -> VortexResult { @@ -300,46 +238,6 @@ mod tests { Ok(()) } - /// Progress counts partitions as workers take them, and the pool is exhausted once a worker - /// finds none left. - #[test] - fn partition_pool_reports_progress_and_exhaustion() -> VortexResult<()> { - let scan = Box::new(PartitionOnlyScan { - rows: vec![2, 3, 4, 5], - }); - let pool = scan.open()?; - assert_eq!(pool.progress(), 0.0); - assert!(!pool.is_exhausted()); - - let mut worker = Arc::clone(&pool).worker(); - let first = block_on(worker.next()).transpose()?; - assert_eq!(first.map(|array| array.len()), Some(2)); - assert_eq!(pool.progress(), 0.25); - assert!(!pool.is_exhausted()); - - let rest = - block_on(worker.try_fold(0, |rows, array| async move { Ok(rows + array.len()) }))?; - assert_eq!(rest, 12); - assert_eq!(pool.progress(), 1.0); - assert!(pool.is_exhausted()); - assert!(block_on(Arc::clone(&pool).worker().next()).is_none()); - Ok(()) - } - - /// With an exact partition count, the pool is exhausted as soon as its last partition is - /// taken, before the worker that took it asks for more. - #[test] - fn partition_pool_is_exhausted_when_its_last_partition_is_taken() -> VortexResult<()> { - let pool = Box::new(PartitionOnlyScan { rows: vec![2, 3] }).open()?; - let mut worker = Arc::clone(&pool).worker(); - assert!(block_on(worker.next()).is_some()); - assert!(!pool.is_exhausted()); - assert!(block_on(worker.next()).is_some()); - assert!(pool.is_exhausted()); - assert!(block_on(worker.next()).is_none()); - Ok(()) - } - /// A scan that implements only `split` and `open`, with a pool of its own. struct SplitOnlyScan { rows: Vec, @@ -387,10 +285,6 @@ mod tests { }); ArrayStreamExt::boxed(ArrayStreamAdapter::new(DTYPE.clone(), arrays)) } - - fn is_exhausted(&self) -> bool { - self.rows.lock().is_empty() - } } /// The default `partitions` reads a scan that implements only `split` and `open`, one From 39b4ebec4d1cb5b58d2a807f5f0d18fa8d9240fa Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 14:05:17 -0500 Subject: [PATCH 09/16] Require partitions again and drop ScanPool::dtype Every source in the stack implements partitions, and no host reads the derived default, so partitions and partition_count are required as on develop. A worker's stream already carries its dtype, so the pool does not repeat it. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-scan/src/lib.rs | 42 +++----------- vortex-scan/src/pool.rs | 126 +--------------------------------------- 2 files changed, 10 insertions(+), 158 deletions(-) diff --git a/vortex-scan/src/lib.rs b/vortex-scan/src/lib.rs index 5a282ac2a53..62c1f3ede68 100644 --- a/vortex-scan/src/lib.rs +++ b/vortex-scan/src/lib.rs @@ -39,10 +39,7 @@ use std::ops::Range; use std::sync::Arc; use async_trait::async_trait; -use futures::StreamExt; -use futures::stream; use futures::stream::BoxStream; -use pool::ScanPartition; use pool::ScanPoolRef; use selection::Selection; use vortex_array::aggregate_fn::AggregateFnRef; @@ -57,7 +54,6 @@ use vortex_array::stream::SendableArrayStream; use vortex_error::VortexResult; use vortex_error::vortex_bail; use vortex_session::VortexSession; -use vortex_utils::parallelism::get_available_parallelism; /// A sendable stream of partitions. pub type PartitionStream = BoxStream<'static, VortexResult>; @@ -218,12 +214,17 @@ pub type DataSourceScanRef = Box; /// worker of that pool. /// /// A source implements [`split`](Self::split) and [`open`](Self::open) by putting its own tuned -/// execution behind them. [`partitions`](Self::partitions) is derived from them for hosts that -/// still read partitions. +/// execution behind them. pub trait DataSourceScan: 'static + Send { /// The returned dtype of the scan. fn dtype(&self) -> &DType; + /// Returns an estimate of the total number of partitions the scan will produce. + fn partition_count(&self) -> Precision; + + /// Returns a stream of partitions to be processed. + fn partitions(self: Box) -> PartitionStream; + /// Cuts the scan into at most `n` scans that together read the same rows, in order. /// /// Splitting reads metadata only. The result is never empty. A scan that cannot be cut @@ -232,34 +233,9 @@ pub trait DataSourceScan: 'static + Send { /// Opens the scan into a pool that host threads share by each polling a worker. /// - /// A source that has no pool of its own yet may return a - /// [`PartitionPool`](pool::PartitionPool) over itself, as long as it implements - /// [`partitions`](Self::partitions): the default `partitions` opens the scan, so the two - /// together would never end. + /// A source that has no pool of its own may return a [`PartitionPool`](pool::PartitionPool) + /// over itself. fn open(self: Box) -> VortexResult; - - /// Returns an estimate of the total number of partitions the scan will produce. - fn partition_count(&self) -> Precision { - Precision::Absent - } - - /// Returns a stream of partitions to be processed. - /// - /// The default [splits](Self::split) the scan into one piece per available core and makes - /// each piece a partition, which [opens](Self::open) the piece and drains one worker of its - /// pool. - fn partitions(self: Box) -> PartitionStream { - let n = get_available_parallelism() - .and_then(NonZeroUsize::new) - .unwrap_or(NonZeroUsize::MIN); - match self.split(n) { - Ok(pieces) => stream::iter(pieces.into_iter().enumerate().map(|(index, scan)| { - Ok(Box::new(ScanPartition::new(index, scan)) as PartitionRef) - })) - .boxed(), - Err(err) => stream::once(async move { Err(err) }).boxed(), - } - } } /// A reference-counted partition. diff --git a/vortex-scan/src/pool.rs b/vortex-scan/src/pool.rs index b04ec0a0a4d..bc3290e04dc 100644 --- a/vortex-scan/src/pool.rs +++ b/vortex-scan/src/pool.rs @@ -3,21 +3,17 @@ //! Pools of work that host threads share by each polling a worker. -use std::any::Any; use std::sync::Arc; use async_lock::Mutex; use futures::StreamExt; use futures::stream; 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::VortexResult; use crate::DataSourceScanRef; -use crate::Partition; use crate::PartitionStream; /// A shared reference to a [`ScanPool`]. @@ -25,9 +21,6 @@ pub type ScanPoolRef = Arc; /// The shared work of an opened scan, which host threads read by each polling a worker. pub trait ScanPool: 'static + Send + Sync { - /// The dtype of the arrays every worker returns. - fn dtype(&self) -> &DType; - /// Returns a new worker: a stream that one host thread polls. /// /// Workers take work from the pool until none is left, so together they return every row of @@ -43,8 +36,7 @@ pub trait ScanPool: 'static + Send + Sync { /// 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 -/// [`partitions`](crate::DataSourceScan::partitions) itself. +/// A source without a pool of its own can open into this one. pub struct PartitionPool { dtype: DType, partitions: Mutex, @@ -61,10 +53,6 @@ impl PartitionPool { } impl ScanPool for PartitionPool { - fn dtype(&self) -> &DType { - &self.dtype - } - fn worker(self: Arc) -> SendableArrayStream { let dtype = self.dtype.clone(); let partitions = stream::unfold(self, |pool| async move { @@ -81,46 +69,9 @@ impl ScanPool for PartitionPool { } } -/// A piece of a split scan as a partition, which opens the piece and drains one worker of it. -/// -/// This is how the default [`partitions`](crate::DataSourceScan::partitions) reads a scan. -pub(crate) struct ScanPartition { - index: usize, - scan: DataSourceScanRef, -} - -impl ScanPartition { - pub(crate) fn new(index: usize, scan: DataSourceScanRef) -> Self { - Self { index, scan } - } -} - -impl Partition for ScanPartition { - fn as_any(&self) -> &dyn Any { - self - } - - fn index(&self) -> usize { - self.index - } - - fn row_count(&self) -> Precision { - Precision::Absent - } - - fn byte_size(&self) -> Precision { - Precision::Absent - } - - fn execute(self: Box) -> VortexResult { - Ok(self.scan.open()?.worker()) - } -} - #[cfg(test)] mod tests { use std::any::Any; - use std::collections::VecDeque; use std::num::NonZeroUsize; use std::sync::Arc; @@ -129,7 +80,6 @@ mod tests { use futures::executor::block_on; use futures::future::try_join_all; use futures::stream; - use parking_lot::Mutex; use vortex_array::ArrayRef; use vortex_array::IntoArray; use vortex_array::dtype::DType; @@ -143,7 +93,6 @@ mod tests { use vortex_error::VortexResult; use super::PartitionPool; - use super::ScanPool; use super::ScanPoolRef; use crate::DataSourceScan; use crate::DataSourceScanRef; @@ -237,77 +186,4 @@ mod tests { assert_eq!(rows, 14); Ok(()) } - - /// A scan that implements only `split` and `open`, with a pool of its own. - struct SplitOnlyScan { - rows: Vec, - } - - impl DataSourceScan for SplitOnlyScan { - fn dtype(&self) -> &DType { - &DTYPE - } - - fn split(self: Box, n: NonZeroUsize) -> VortexResult> { - let size = self.rows.len().div_ceil(n.get()).max(1); - Ok(self - .rows - .chunks(size) - .map(|rows| { - Box::new(SplitOnlyScan { - rows: rows.to_vec(), - }) as DataSourceScanRef - }) - .collect()) - } - - fn open(self: Box) -> VortexResult { - Ok(Arc::new(RowsPool { - rows: Mutex::new(self.rows.into()), - })) - } - } - - /// A pool whose workers each take the next count of rows. - struct RowsPool { - rows: Mutex>, - } - - impl ScanPool for RowsPool { - fn dtype(&self) -> &DType { - &DTYPE - } - - fn worker(self: Arc) -> SendableArrayStream { - let arrays = stream::unfold(self, |pool| async move { - let rows = pool.rows.lock().pop_front()?; - Some((rows_array(rows), pool)) - }); - ArrayStreamExt::boxed(ArrayStreamAdapter::new(DTYPE.clone(), arrays)) - } - } - - /// The default `partitions` reads a scan that implements only `split` and `open`, one - /// partition per piece. - #[test] - fn default_partitions_open_each_piece() -> VortexResult<()> { - let scan = Box::new(SplitOnlyScan { - rows: vec![2, 3, 4, 5], - }); - let partitions: Vec = block_on(scan.partitions().try_collect())?; - assert!(!partitions.is_empty()); - for (index, partition) in partitions.iter().enumerate() { - assert_eq!(partition.index(), index); - } - let rows = block_on(try_join_all(partitions.into_iter().map( - |partition| async move { - partition - .execute()? - .try_fold(0, |rows, array| async move { Ok(rows + array.len()) }) - .await - }, - )))?; - assert_eq!(rows.into_iter().sum::(), 14); - Ok(()) - } } From 6697509ac89f25894d77de1be3a7532abf7ace5a Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 14:09:31 -0500 Subject: [PATCH 10/16] Say that split_concurrency bounds each partition or worker Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-scan/src/lib.rs | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/vortex-scan/src/lib.rs b/vortex-scan/src/lib.rs index 62c1f3ede68..6a5a07161d1 100644 --- a/vortex-scan/src/lib.rs +++ b/vortex-scan/src/lib.rs @@ -178,12 +178,14 @@ 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, or of an opened scan's pool, to decode at once. + /// The most splits that each partition, or each worker of an opened scan, decodes at once. /// - /// `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 partition or worker on its own, not the whole scan: a scan read by several + /// of them 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, } From e36740da35f02051c311eeceed1eec201ff3d74b Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 14:20:22 -0500 Subject: [PATCH 11/16] Open scans into a cloneable ScanStream and define split by request order Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-datafusion/src/v2/source.rs | 7 +- vortex-layout/src/scan/layout.rs | 11 +- vortex-layout/src/scan/multi.rs | 7 +- vortex-scan/src/lib.rs | 40 +++-- vortex-scan/src/pool.rs | 268 ++++++++++++++++++++++------- 5 files changed, 242 insertions(+), 91 deletions(-) diff --git a/vortex-datafusion/src/v2/source.rs b/vortex-datafusion/src/v2/source.rs index 40b0523a112..5de7976b856 100644 --- a/vortex-datafusion/src/v2/source.rs +++ b/vortex-datafusion/src/v2/source.rs @@ -1076,8 +1076,7 @@ mod tests { use vortex::scan::Partition; use vortex::scan::PartitionRef; use vortex::scan::PartitionStream; - use vortex::scan::pool::PartitionPool; - use vortex::scan::pool::ScanPoolRef; + use vortex::scan::pool::ScanStream; use vortex::session::VortexSession; use vortex_arrow::ArrowSessionExt; @@ -1228,8 +1227,8 @@ mod tests { Ok(vec![self]) } - fn open(self: Box) -> VortexResult { - Ok(Arc::new(PartitionPool::new(self))) + fn open(self: Box) -> VortexResult { + Ok(ScanStream::from_partitions(self)) } fn partition_count(&self) -> Precision { diff --git a/vortex-layout/src/scan/layout.rs b/vortex-layout/src/scan/layout.rs index 6d25f042a60..b1e83172e93 100644 --- a/vortex-layout/src/scan/layout.rs +++ b/vortex-layout/src/scan/layout.rs @@ -37,8 +37,7 @@ use vortex_scan::Partition; use vortex_scan::PartitionRef; use vortex_scan::PartitionStream; use vortex_scan::ScanRequest; -use vortex_scan::pool::PartitionPool; -use vortex_scan::pool::ScanPoolRef; +use vortex_scan::pool::ScanStream; use vortex_scan::selection::Selection; use vortex_session::VortexSession; @@ -250,8 +249,8 @@ impl DataSourceScan for LayoutReaderScan { Ok(vec![self]) } - fn open(self: Box) -> VortexResult { - Ok(Arc::new(PartitionPool::new(self))) + fn open(self: Box) -> VortexResult { + Ok(ScanStream::from_partitions(self)) } fn partition_count(&self) -> Precision { @@ -417,8 +416,8 @@ impl DataSourceScan for Empty { Ok(vec![self]) } - fn open(self: Box) -> VortexResult { - Ok(Arc::new(PartitionPool::new(self))) + fn open(self: Box) -> VortexResult { + Ok(ScanStream::from_partitions(self)) } fn partition_count(&self) -> Precision { diff --git a/vortex-layout/src/scan/multi.rs b/vortex-layout/src/scan/multi.rs index 630ea7da9c8..6eaf7e3d74c 100644 --- a/vortex-layout/src/scan/multi.rs +++ b/vortex-layout/src/scan/multi.rs @@ -57,8 +57,7 @@ use vortex_scan::Partition; use vortex_scan::PartitionRef; use vortex_scan::PartitionStream; use vortex_scan::ScanRequest; -use vortex_scan::pool::PartitionPool; -use vortex_scan::pool::ScanPoolRef; +use vortex_scan::pool::ScanStream; use vortex_scan::selection::Selection; use vortex_session::VortexSession; use vortex_utils::parallelism::get_available_parallelism; @@ -399,8 +398,8 @@ impl DataSourceScan for MultiLayoutScan { Ok(vec![self]) } - fn open(self: Box) -> VortexResult { - Ok(Arc::new(PartitionPool::new(self))) + fn open(self: Box) -> VortexResult { + Ok(ScanStream::from_partitions(self)) } fn partition_count(&self) -> Precision { diff --git a/vortex-scan/src/lib.rs b/vortex-scan/src/lib.rs index 6a5a07161d1..e5233fd66c9 100644 --- a/vortex-scan/src/lib.rs +++ b/vortex-scan/src/lib.rs @@ -40,7 +40,7 @@ use std::sync::Arc; use async_trait::async_trait; use futures::stream::BoxStream; -use pool::ScanPoolRef; +use pool::ScanStream; use selection::Selection; use vortex_array::aggregate_fn::AggregateFnRef; use vortex_array::dtype::DType; @@ -178,10 +178,11 @@ 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 that each partition, or each worker of an opened scan, decodes at once. + /// The most splits that each worker decodes at once, where a worker is a partition or a + /// clone of an opened scan's stream. /// - /// It bounds each partition or worker on its own, not the whole scan: a scan read by several - /// of them decodes up to this many splits in each. `None` keeps the source's default. Each + /// 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 @@ -210,13 +211,12 @@ pub type DataSourceScanRef = Box; /// A data source scan reads data from the source. /// -/// A host reads a scan in one of two ways. It [splits](Self::split) the scan into independent -/// pieces when each piece must be read on its own, such as by another process or with a declared -/// order. Otherwise it [opens](Self::open) the scan into a pool and has each of its threads poll a -/// worker of that pool. -/// -/// A source implements [`split`](Self::split) and [`open`](Self::open) by putting its own tuned -/// execution behind them. +/// A host reads a scan the same way whatever the source. A partition-based host, such as +/// DataFusion, [splits](Self::split) the scan into one piece per partition and reads each piece +/// on its own. A morsel-based host, such as DuckDB, [opens](Self::open) the scan once and has +/// each of its threads poll a clone of the returned [`ScanStream`]. The host states what it +/// needs, such as order or a limit, on the [`ScanRequest`], and the source decides what the +/// pieces are and how they run. pub trait DataSourceScan: 'static + Send { /// The returned dtype of the scan. fn dtype(&self) -> &DType; @@ -227,17 +227,23 @@ pub trait DataSourceScan: 'static + Send { /// Returns a stream of partitions to be processed. fn partitions(self: Box) -> PartitionStream; - /// Cuts the scan into at most `n` scans that together read the same rows, in order. + /// Cuts the scan into at most `n` pieces that together read its rows. + /// + /// For an unordered request the pieces may share work: which piece returns which rows is + /// unspecified, the pieces of one call together return every row once, and they must be + /// read in the same process. [`split_shared`](pool::split_shared) splits a scan this way. + /// For an ordered request the pieces are fixed and contiguous, and their concatenation reads + /// the rows in scan order. /// - /// Splitting reads metadata only. The result is never empty. A scan that cannot be cut + /// Splitting reads metadata only. The result is never empty, and a scan that cannot be cut /// returns itself as the one piece. fn split(self: Box, n: NonZeroUsize) -> VortexResult>; - /// Opens the scan into a pool that host threads share by each polling a worker. + /// Opens the scan into a stream whose clones host threads share; see [`ScanStream`]. /// - /// A source that has no pool of its own may return a [`PartitionPool`](pool::PartitionPool) - /// over itself. - fn open(self: Box) -> VortexResult; + /// A source that has no worker queue of its own may return + /// [`ScanStream::from_partitions`] over itself. + fn open(self: Box) -> VortexResult; } /// A reference-counted partition. diff --git a/vortex-scan/src/pool.rs b/vortex-scan/src/pool.rs index bc3290e04dc..36977a945d7 100644 --- a/vortex-scan/src/pool.rs +++ b/vortex-scan/src/pool.rs @@ -1,71 +1,202 @@ -// SPDX-License-Identifier: Apache-2.0 -// SPDX-FileCopyrightText: Copyright the Vortex contributors - -//! Pools of work that host threads share by each polling a worker. +//! The stream that an opened scan returns, which host threads share by each polling a clone. +use std::any::Any; +use std::fmt; +use std::num::NonZeroUsize; +use std::pin::Pin; use std::sync::Arc; +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::ArrayStreamAdapter; +use vortex_array::expr::stats::Precision; +use vortex_array::stream::ArrayStream; use vortex_array::stream::ArrayStreamExt; use vortex_array::stream::SendableArrayStream; +use vortex_error::VortexResult; +use crate::DataSourceScan; use crate::DataSourceScanRef; +use crate::Partition; +use crate::PartitionRef; use crate::PartitionStream; -/// A shared reference to a [`ScanPool`]. -pub type ScanPoolRef = Arc; - -/// The shared work of an opened scan, which host threads read by each polling a worker. -pub trait ScanPool: 'static + Send + Sync { - /// Returns a new worker: a stream that one host thread polls. - /// - /// Workers take work from the pool until none is left, so together they return every row of - /// the scan exactly once. A host may start any number of workers, at any time, and the number - /// it runs is its parallelism. A pool may run its work as tasks on the session's runtime, - /// which the host owns, and hand each result to whichever worker asks next; it never 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 worker, for - /// example with `block_on`. Dropping a worker before it ends gives up any work it had taken, - /// so a host drops a worker early only when it abandons the scan. - fn worker(self: Arc) -> SendableArrayStream; -} +/// Starts a new worker over the shared work of an opened scan. +type NewWorker = dyn Fn() -> BoxStream<'static, VortexResult> + Send + Sync; -/// A pool whose workers take partitions one at a time from a scan's shared partition stream. +/// The arrays of an opened scan, which host threads read by each polling a clone. /// -/// A source without a pool of its own can open into this one. -pub struct PartitionPool { +/// A clone is another worker over the same remaining work, like a clone of a channel's receiver: +/// the clones take work until none is left, so together they return every row of the scan +/// exactly once, and the number a host polls is its parallelism. The work may run as tasks on +/// the session's runtime, which the host owns, and its results go to whichever clone asks next; +/// a scan never 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 clone, for +/// example with `block_on`. Dropping a clone before it ends gives up any work it had taken, so a +/// host drops a clone early only when it abandons the scan. +pub struct ScanStream { dtype: DType, - partitions: Mutex, + new_worker: Arc, + worker: Option>>, } -impl PartitionPool { - /// Opens a pool over the partitions of `scan`. - pub fn new(scan: DataSourceScanRef) -> Self { +impl ScanStream { + /// A stream whose clones each poll 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. A clone starts its worker when it is first polled. + pub fn new( + dtype: DType, + new_worker: impl Fn() -> BoxStream<'static, VortexResult> + Send + Sync + 'static, + ) -> Self { Self { - dtype: scan.dtype().clone(), - partitions: Mutex::new(scan.partitions()), + dtype, + new_worker: Arc::new(new_worker), + worker: None, } } + + /// A stream whose clones take the partitions of `scan` one at a time. + /// + /// A source that has no worker queue of its own can open into this one. + pub fn from_partitions(scan: DataSourceScanRef) -> Self { + let dtype = scan.dtype().clone(); + let partitions = Arc::new(Mutex::new(scan.partitions())); + Self::new(dtype, move || { + let partitions = stream::unfold(Arc::clone(&partitions), |shared| async move { + let next = shared.lock().await.next().await?; + 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() + }) + } } -impl ScanPool for PartitionPool { - fn worker(self: Arc) -> SendableArrayStream { - let dtype = self.dtype.clone(); - let partitions = stream::unfold(self, |pool| async move { - let next = pool.partitions.lock().await.next().await?; - Some((next, pool)) - }); - let arrays = 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(), - } - }); - ArrayStreamExt::boxed(ArrayStreamAdapter::new(dtype, arrays)) +impl Clone for ScanStream { + fn clone(&self) -> Self { + Self { + dtype: self.dtype.clone(), + new_worker: Arc::clone(&self.new_worker), + worker: None, + } + } +} + +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(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + let this = self.get_mut(); + let new_worker = &*this.new_worker; + this.worker + .get_or_insert_with(new_worker) + .poll_next_unpin(cx) + } +} + +impl ArrayStream for ScanStream { + fn dtype(&self) -> &DType { + &self.dtype + } +} + +/// Splits an unordered scan by opening it once and handing each of `n` pieces a clone of its +/// stream. +/// +/// The pieces share the scan's work, so which piece returns which rows is unspecified. Together +/// they return every row once, and they must be read in the same process. A piece opens into its +/// clone, does not split further, and has one partition that reads its clone. +pub fn split_shared( + scan: DataSourceScanRef, + n: NonZeroUsize, +) -> VortexResult> { + let stream = scan.open()?; + let mut pieces: Vec = (1..n.get()) + .map(|_| { + Box::new(SharedScan { + stream: stream.clone(), + }) as DataSourceScanRef + }) + .collect(); + pieces.push(Box::new(SharedScan { stream })); + Ok(pieces) +} + +/// A piece of a [`split_shared`] scan: one clone of the opened scan's stream. +struct SharedScan { + stream: ScanStream, +} + +impl DataSourceScan for SharedScan { + fn dtype(&self) -> &DType { + &self.stream.dtype + } + + fn partition_count(&self) -> Precision { + Precision::exact(1usize) + } + + fn partitions(self: Box) -> PartitionStream { + let partition = Box::new(SharedPartition { + stream: self.stream, + }) as PartitionRef; + stream::once(async move { Ok(partition) }).boxed() + } + + fn split(self: Box, _n: NonZeroUsize) -> VortexResult> { + Ok(vec![self]) + } + + fn open(self: Box) -> VortexResult { + Ok(self.stream) + } +} + +/// The one partition of a [`SharedScan`]. +struct SharedPartition { + stream: ScanStream, +} + +impl Partition for SharedPartition { + 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(ArrayStreamExt::boxed(self.stream)) } } @@ -73,7 +204,6 @@ impl ScanPool for PartitionPool { mod tests { use std::any::Any; use std::num::NonZeroUsize; - use std::sync::Arc; use futures::StreamExt; use futures::TryStreamExt; @@ -91,9 +221,10 @@ mod tests { use vortex_array::stream::SendableArrayStream; use vortex_buffer::Buffer; use vortex_error::VortexResult; + use vortex_error::vortex_err; - use super::PartitionPool; - use super::ScanPoolRef; + use super::ScanStream; + use super::split_shared; use crate::DataSourceScan; use crate::DataSourceScanRef; use crate::Partition; @@ -139,7 +270,7 @@ mod tests { Ok(Buffer::from_iter(0..i32::try_from(rows)?).into_array()) } - /// A scan that has no pool of its own, so it opens into a [`PartitionPool`]. + /// A scan that has no pool of its own, so it opens into [`ScanStream::from_partitions`]. struct PartitionOnlyScan { rows: Vec, } @@ -153,8 +284,8 @@ mod tests { Ok(vec![self]) } - fn open(self: Box) -> VortexResult { - Ok(Arc::new(PartitionPool::new(self))) + fn open(self: Box) -> VortexResult { + Ok(ScanStream::from_partitions(self)) } fn partition_count(&self) -> Precision { @@ -171,19 +302,36 @@ mod tests { } } + /// 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 partition_pool_shares_partitions_across_workers() -> VortexResult<()> { + fn clones_share_partitions() -> VortexResult<()> { + let stream = Box::new(PartitionOnlyScan { + rows: vec![2, 3, 4, 5], + }) + .open()?; + assert_eq!(total_rows([stream.clone(), stream.clone(), stream])?, 14); + Ok(()) + } + + #[test] + fn shared_pieces_read_every_row_once() -> VortexResult<()> { let scan = Box::new(PartitionOnlyScan { rows: vec![2, 3, 4, 5], }); - let pool = scan.open()?; - let workers = (0..3).map(|_| { - Arc::clone(&pool) - .worker() - .try_fold(0, |rows, array| async move { Ok(rows + array.len()) }) - }); - let rows: usize = block_on(try_join_all(workers))?.into_iter().sum(); - assert_eq!(rows, 14); + let pieces = split_shared(scan, NonZeroUsize::new(3).ok_or_else(|| vortex_err!("3"))?)?; + assert_eq!(pieces.len(), 3); + let streams = pieces + .into_iter() + .map(|piece| piece.open()) + .collect::>>()?; + assert_eq!(total_rows(streams)?, 14); Ok(()) } } From 17e58eb1aea2c45501a96e1f04cb971be06b7f05 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 14:37:36 -0500 Subject: [PATCH 12/16] Rename vortex_scan::pool to stream and state the scan contract exactly Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-datafusion/src/v2/source.rs | 2 +- vortex-layout/src/scan/layout.rs | 2 +- vortex-layout/src/scan/multi.rs | 2 +- vortex-scan/src/lib.rs | 36 +++++++++++++++----------- vortex-scan/src/{pool.rs => stream.rs} | 12 ++++----- 5 files changed, 30 insertions(+), 24 deletions(-) rename vortex-scan/src/{pool.rs => stream.rs} (94%) diff --git a/vortex-datafusion/src/v2/source.rs b/vortex-datafusion/src/v2/source.rs index 5de7976b856..8a29b7a7bf2 100644 --- a/vortex-datafusion/src/v2/source.rs +++ b/vortex-datafusion/src/v2/source.rs @@ -1076,7 +1076,7 @@ mod tests { use vortex::scan::Partition; use vortex::scan::PartitionRef; use vortex::scan::PartitionStream; - use vortex::scan::pool::ScanStream; + use vortex::scan::stream::ScanStream; use vortex::session::VortexSession; use vortex_arrow::ArrowSessionExt; diff --git a/vortex-layout/src/scan/layout.rs b/vortex-layout/src/scan/layout.rs index b1e83172e93..daed084d8e6 100644 --- a/vortex-layout/src/scan/layout.rs +++ b/vortex-layout/src/scan/layout.rs @@ -37,8 +37,8 @@ use vortex_scan::Partition; use vortex_scan::PartitionRef; use vortex_scan::PartitionStream; use vortex_scan::ScanRequest; -use vortex_scan::pool::ScanStream; use vortex_scan::selection::Selection; +use vortex_scan::stream::ScanStream; use vortex_session::VortexSession; use crate::LayoutReaderRef; diff --git a/vortex-layout/src/scan/multi.rs b/vortex-layout/src/scan/multi.rs index 6eaf7e3d74c..17576c82a3b 100644 --- a/vortex-layout/src/scan/multi.rs +++ b/vortex-layout/src/scan/multi.rs @@ -57,8 +57,8 @@ use vortex_scan::Partition; use vortex_scan::PartitionRef; use vortex_scan::PartitionStream; use vortex_scan::ScanRequest; -use vortex_scan::pool::ScanStream; use vortex_scan::selection::Selection; +use vortex_scan::stream::ScanStream; use vortex_session::VortexSession; use vortex_utils::parallelism::get_available_parallelism; diff --git a/vortex-scan/src/lib.rs b/vortex-scan/src/lib.rs index e5233fd66c9..001f90e5e6a 100644 --- a/vortex-scan/src/lib.rs +++ b/vortex-scan/src/lib.rs @@ -26,11 +26,11 @@ pub mod arrays; pub mod execution; pub mod plan; pub mod planning; -pub mod pool; 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; @@ -40,8 +40,8 @@ use std::sync::Arc; use async_trait::async_trait; use futures::stream::BoxStream; -use pool::ScanStream; use selection::Selection; +use stream::ScanStream; use vortex_array::aggregate_fn::AggregateFnRef; use vortex_array::dtype::DType; use vortex_array::dtype::FieldPath; @@ -211,12 +211,16 @@ pub type DataSourceScanRef = Box; /// A data source scan reads data from the source. /// -/// A host reads a scan the same way whatever the source. A partition-based host, such as -/// DataFusion, [splits](Self::split) the scan into one piece per partition and reads each piece -/// on its own. A morsel-based host, such as DuckDB, [opens](Self::open) the scan once and has -/// each of its threads poll a clone of the returned [`ScanStream`]. The host states what it -/// needs, such as order or a limit, on the [`ScanRequest`], and the source decides what the -/// pieces are and how they run. +/// Each host reads every scan the same way, whatever the source: its execution model is fixed. +/// A partition-based host, such as DataFusion, always [splits](Self::split) the scan into one +/// piece per partition and reads each piece as a stream. A morsel-based host, such as DuckDB, +/// never splits: it [opens](Self::open) the scan once and has each of its threads poll a clone +/// of the returned [`ScanStream`]. 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; @@ -229,19 +233,21 @@ pub trait DataSourceScan: 'static + Send { /// Cuts the scan into at most `n` pieces that together read its rows. /// - /// For an unordered request the pieces may share work: which piece returns which rows is - /// unspecified, the pieces of one call together return every row once, and they must be - /// read in the same process. [`split_shared`](pool::split_shared) splits a scan this way. - /// For an ordered request the pieces are fixed and contiguous, and their concatenation reads - /// the rows in scan order. + /// - For an unordered request, the pieces may share work. Which piece returns which rows is + /// unspecified, and the pieces of one call together return every row exactly once. They + /// must be read in the process that split them. [`split_shared`](stream::split_shared) + /// splits a scan this way. + /// - For an ordered request, the pieces are fixed and 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 that cannot be cut /// returns itself as the one piece. fn split(self: Box, n: NonZeroUsize) -> VortexResult>; - /// Opens the scan into a stream whose clones host threads share; see [`ScanStream`]. + /// Opens the scan into a [`ScanStream`] of its rows, which host threads share by each + /// polling a clone. /// - /// A source that has no worker queue of its own may return + /// A source that has no queue of work of its own may return /// [`ScanStream::from_partitions`] over itself. fn open(self: Box) -> VortexResult; } diff --git a/vortex-scan/src/pool.rs b/vortex-scan/src/stream.rs similarity index 94% rename from vortex-scan/src/pool.rs rename to vortex-scan/src/stream.rs index 36977a945d7..957b01407df 100644 --- a/vortex-scan/src/pool.rs +++ b/vortex-scan/src/stream.rs @@ -34,9 +34,9 @@ type NewWorker = dyn Fn() -> BoxStream<'static, VortexResult> + Send + /// /// A clone is another worker over the same remaining work, like a clone of a channel's receiver: /// the clones take work until none is left, so together they return every row of the scan -/// exactly once, and the number a host polls is its parallelism. The work may run as tasks on -/// the session's runtime, which the host owns, and its results go to whichever clone asks next; -/// a scan never starts threads of its own. A host whose runtime has no threads of its own, such +/// exactly once, in no particular order across clones. The number of clones a host polls is its +/// parallelism. 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 clone, for /// example with `block_on`. Dropping a clone before it ends gives up any work it had taken, so a /// host drops a clone early only when it abandons the scan. @@ -64,7 +64,7 @@ impl ScanStream { /// A stream whose clones take the partitions of `scan` one at a time. /// - /// A source that has no worker queue of its own can open into this one. + /// A source that has no queue of work of its own can open into this one. pub fn from_partitions(scan: DataSourceScanRef) -> Self { let dtype = scan.dtype().clone(); let partitions = Arc::new(Mutex::new(scan.partitions())); @@ -265,12 +265,12 @@ mod tests { } } - /// The array of `rows` rows that a test partition or pool returns. + /// 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 pool of its own, so it opens into [`ScanStream::from_partitions`]. + /// A scan that has no queue of work of its own, so it opens into [`ScanStream::from_partitions`]. struct PartitionOnlyScan { rows: Vec, } From cef16c63b49f9f423a8f60307ea269b2bcb99420 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 14:44:33 -0500 Subject: [PATCH 13/16] Describe split's callers as hosts that read a fixed number of streams Signed-off-by: Nicholas Gates Co-Authored-By: Claude Opus 5.5 --- vortex-scan/src/lib.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/vortex-scan/src/lib.rs b/vortex-scan/src/lib.rs index 001f90e5e6a..1838ff10157 100644 --- a/vortex-scan/src/lib.rs +++ b/vortex-scan/src/lib.rs @@ -212,8 +212,9 @@ pub type DataSourceScanRef = Box; /// 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 partition-based host, such as DataFusion, always [splits](Self::split) the scan into one -/// piece per partition and reads each piece as a stream. A morsel-based host, such as DuckDB, +/// A host that reads a fixed number of streams always [splits](Self::split) the scan into that +/// many pieces and reads each piece as a stream; DataFusion's count is its output partition +/// count. A morsel-based host, such as DuckDB, /// never splits: it [opens](Self::open) the scan once and has each of its threads poll a clone /// of the returned [`ScanStream`]. 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 From f93a16d78954c8f1bf1b5cdd4cdc69206cc9e4ef Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 16:26:21 -0500 Subject: [PATCH 14/16] Make split strictly partitioning and leave sharing to open Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-scan/src/lib.rs | 30 +++++------ vortex-scan/src/stream.rs | 105 -------------------------------------- 2 files changed, 14 insertions(+), 121 deletions(-) diff --git a/vortex-scan/src/lib.rs b/vortex-scan/src/lib.rs index 1838ff10157..93f5bf03bcb 100644 --- a/vortex-scan/src/lib.rs +++ b/vortex-scan/src/lib.rs @@ -212,13 +212,13 @@ pub type DataSourceScanRef = Box; /// 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 reads a fixed number of streams always [splits](Self::split) the scan into that -/// many pieces and reads each piece as a stream; DataFusion's count is its output partition -/// count. A morsel-based host, such as DuckDB, -/// never splits: it [opens](Self::open) the scan once and has each of its threads poll a clone -/// of the returned [`ScanStream`]. 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 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 poll a +/// clone of the returned [`ScanStream`]. 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. @@ -232,17 +232,15 @@ pub trait DataSourceScan: 'static + Send { /// Returns a stream of partitions to be processed. fn partitions(self: Box) -> PartitionStream; - /// Cuts the scan into at most `n` pieces that together read its rows. + /// Partitions the scan into at most `n` fixed pieces. /// - /// - For an unordered request, the pieces may share work. Which piece returns which rows is - /// unspecified, and the pieces of one call together return every row exactly once. They - /// must be read in the process that split them. [`split_shared`](stream::split_shared) - /// splits a scan this way. - /// - For an ordered request, the pieces are fixed and contiguous, and reading them one after - /// another returns the rows in scan order. + /// 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 that cannot be cut - /// returns itself as the one piece. + /// 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 polls clones of its stream. fn split(self: Box, n: NonZeroUsize) -> VortexResult>; /// Opens the scan into a [`ScanStream`] of its rows, which host threads share by each diff --git a/vortex-scan/src/stream.rs b/vortex-scan/src/stream.rs index 957b01407df..960918a91aa 100644 --- a/vortex-scan/src/stream.rs +++ b/vortex-scan/src/stream.rs @@ -1,8 +1,6 @@ //! The stream that an opened scan returns, which host threads share by each polling a clone. -use std::any::Any; use std::fmt; -use std::num::NonZeroUsize; use std::pin::Pin; use std::sync::Arc; use std::task::Context; @@ -15,17 +13,10 @@ 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::ArrayStream; -use vortex_array::stream::ArrayStreamExt; -use vortex_array::stream::SendableArrayStream; use vortex_error::VortexResult; -use crate::DataSourceScan; use crate::DataSourceScanRef; -use crate::Partition; -use crate::PartitionRef; -use crate::PartitionStream; /// Starts a new worker over the shared work of an opened scan. type NewWorker = dyn Fn() -> BoxStream<'static, VortexResult> + Send + Sync; @@ -121,85 +112,6 @@ impl ArrayStream for ScanStream { } } -/// Splits an unordered scan by opening it once and handing each of `n` pieces a clone of its -/// stream. -/// -/// The pieces share the scan's work, so which piece returns which rows is unspecified. Together -/// they return every row once, and they must be read in the same process. A piece opens into its -/// clone, does not split further, and has one partition that reads its clone. -pub fn split_shared( - scan: DataSourceScanRef, - n: NonZeroUsize, -) -> VortexResult> { - let stream = scan.open()?; - let mut pieces: Vec = (1..n.get()) - .map(|_| { - Box::new(SharedScan { - stream: stream.clone(), - }) as DataSourceScanRef - }) - .collect(); - pieces.push(Box::new(SharedScan { stream })); - Ok(pieces) -} - -/// A piece of a [`split_shared`] scan: one clone of the opened scan's stream. -struct SharedScan { - stream: ScanStream, -} - -impl DataSourceScan for SharedScan { - fn dtype(&self) -> &DType { - &self.stream.dtype - } - - fn partition_count(&self) -> Precision { - Precision::exact(1usize) - } - - fn partitions(self: Box) -> PartitionStream { - let partition = Box::new(SharedPartition { - stream: self.stream, - }) as PartitionRef; - stream::once(async move { Ok(partition) }).boxed() - } - - fn split(self: Box, _n: NonZeroUsize) -> VortexResult> { - Ok(vec![self]) - } - - fn open(self: Box) -> VortexResult { - Ok(self.stream) - } -} - -/// The one partition of a [`SharedScan`]. -struct SharedPartition { - stream: ScanStream, -} - -impl Partition for SharedPartition { - 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(ArrayStreamExt::boxed(self.stream)) - } -} - #[cfg(test)] mod tests { use std::any::Any; @@ -221,10 +133,8 @@ mod tests { use vortex_array::stream::SendableArrayStream; use vortex_buffer::Buffer; use vortex_error::VortexResult; - use vortex_error::vortex_err; use super::ScanStream; - use super::split_shared; use crate::DataSourceScan; use crate::DataSourceScanRef; use crate::Partition; @@ -319,19 +229,4 @@ mod tests { assert_eq!(total_rows([stream.clone(), stream.clone(), stream])?, 14); Ok(()) } - - #[test] - fn shared_pieces_read_every_row_once() -> VortexResult<()> { - let scan = Box::new(PartitionOnlyScan { - rows: vec![2, 3, 4, 5], - }); - let pieces = split_shared(scan, NonZeroUsize::new(3).ok_or_else(|| vortex_err!("3"))?)?; - assert_eq!(pieces.len(), 3); - let streams = pieces - .into_iter() - .map(|piece| piece.open()) - .collect::>>()?; - assert_eq!(total_rows(streams)?, 14); - Ok(()) - } } From 211d1b149c290cb0c190bf6d0bba830aaca469a3 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Mon, 23 Nov 2026 21:06:49 -0500 Subject: [PATCH 15/16] Split and open the test array scan, which develop added Signed-off-by: Nicholas Gates Co-Authored-By: Claude Opus 5.5 --- vortex-scan/src/test.rs | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/vortex-scan/src/test.rs b/vortex-scan/src/test.rs index f57b5559b31..48b8e31c7e8 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::ScanStream; 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(ScanStream::from_partitions(self)) + } + fn partition_count(&self) -> Precision { Precision::Exact(self.arrays.len()) } From db074535f821efa8b15bb540b02292e0cd4ea9de Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Mon, 23 Nov 2026 22:10:48 -0500 Subject: [PATCH 16/16] Open a scan into a shared ScanExec that hands out streams A host joins a scan on ScanExec::is_exhausted, a flag set once and never cleared, and creates each thread's stream with ScanExec::stream. The handle is Sync, so hosts share it without a lock. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-datafusion/src/v2/source.rs | 6 +- vortex-layout/src/scan/layout.rs | 10 +- vortex-layout/src/scan/multi.rs | 6 +- vortex-scan/src/lib.rs | 18 ++-- vortex-scan/src/stream.rs | 165 ++++++++++++++++++++++------- vortex-scan/src/test.rs | 6 +- 6 files changed, 147 insertions(+), 64 deletions(-) diff --git a/vortex-datafusion/src/v2/source.rs b/vortex-datafusion/src/v2/source.rs index e20e3f9af69..4390b01aa9a 100644 --- a/vortex-datafusion/src/v2/source.rs +++ b/vortex-datafusion/src/v2/source.rs @@ -1076,7 +1076,7 @@ mod tests { use vortex::scan::Partition; use vortex::scan::PartitionRef; use vortex::scan::PartitionStream; - use vortex::scan::stream::ScanStream; + use vortex::scan::stream::ScanExec; use vortex::session::VortexSession; use vortex_arrow::ArrowSessionExt; @@ -1227,8 +1227,8 @@ mod tests { Ok(vec![self]) } - fn open(self: Box) -> VortexResult { - Ok(ScanStream::from_partitions(self)) + fn open(self: Box) -> VortexResult { + Ok(ScanExec::from_partitions(self)) } fn partition_count(&self) -> Precision { diff --git a/vortex-layout/src/scan/layout.rs b/vortex-layout/src/scan/layout.rs index 54c37220a57..c240daddb36 100644 --- a/vortex-layout/src/scan/layout.rs +++ b/vortex-layout/src/scan/layout.rs @@ -40,7 +40,7 @@ use vortex_scan::PartitionRef; use vortex_scan::PartitionStream; use vortex_scan::ScanRequest; use vortex_scan::selection::Selection; -use vortex_scan::stream::ScanStream; +use vortex_scan::stream::ScanExec; use vortex_session::VortexSession; use crate::LayoutReaderRef; @@ -347,8 +347,8 @@ impl DataSourceScan for LayoutReaderScan { Ok(vec![self]) } - fn open(self: Box) -> VortexResult { - Ok(ScanStream::from_partitions(self)) + fn open(self: Box) -> VortexResult { + Ok(ScanExec::from_partitions(self)) } fn partition_count(&self) -> Precision { @@ -531,8 +531,8 @@ impl DataSourceScan for EmptyScan { Ok(vec![self]) } - fn open(self: Box) -> VortexResult { - Ok(ScanStream::from_partitions(self)) + fn open(self: Box) -> VortexResult { + Ok(ScanExec::from_partitions(self)) } fn partition_count(&self) -> Precision { diff --git a/vortex-layout/src/scan/multi.rs b/vortex-layout/src/scan/multi.rs index 1f38c08f555..b085753f08b 100644 --- a/vortex-layout/src/scan/multi.rs +++ b/vortex-layout/src/scan/multi.rs @@ -58,7 +58,7 @@ use vortex_scan::PartitionRef; use vortex_scan::PartitionStream; use vortex_scan::ScanRequest; use vortex_scan::selection::Selection; -use vortex_scan::stream::ScanStream; +use vortex_scan::stream::ScanExec; use vortex_session::VortexSession; use vortex_utils::parallelism::get_available_parallelism; @@ -414,8 +414,8 @@ impl DataSourceScan for MultiLayoutScan { Ok(vec![self]) } - fn open(self: Box) -> VortexResult { - Ok(ScanStream::from_partitions(self)) + fn open(self: Box) -> VortexResult { + Ok(ScanExec::from_partitions(self)) } fn partition_count(&self) -> Precision { diff --git a/vortex-scan/src/lib.rs b/vortex-scan/src/lib.rs index 7847032f33b..4a625b9c421 100644 --- a/vortex-scan/src/lib.rs +++ b/vortex-scan/src/lib.rs @@ -43,7 +43,7 @@ use futures::StreamExt; use futures::TryStreamExt; use futures::stream::BoxStream; use selection::Selection; -use stream::ScanStream; +use stream::ScanExec; use vortex_array::aggregate_fn::AggregateFnRef; use vortex_array::dtype::DType; use vortex_array::dtype::FieldPath; @@ -183,7 +183,7 @@ pub struct ScanRequest { /// trim the concatenated result. pub limit: Option, /// The most splits that each worker decodes at once, where a worker is a partition or a - /// clone of an opened scan's stream. + /// stream of an opened scan. /// /// 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 @@ -219,8 +219,8 @@ pub type DataSourceScanRef = Box; /// 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 poll a -/// clone of the returned [`ScanStream`]. The host states the properties it needs, such as row +/// 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. /// @@ -244,15 +244,15 @@ pub trait DataSourceScan: 'static + Send { /// /// 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 polls clones of its stream. + /// 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 [`ScanStream`] of its rows, which host threads share by each - /// polling a clone. + /// 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 - /// [`ScanStream::from_partitions`] over itself. - fn open(self: Box) -> VortexResult; + /// [`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 index 960918a91aa..cd7a9154c04 100644 --- a/vortex-scan/src/stream.rs +++ b/vortex-scan/src/stream.rs @@ -1,8 +1,13 @@ -//! The stream that an opened scan returns, which host threads share by each polling a clone. +// 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; @@ -21,48 +26,91 @@ use crate::DataSourceScanRef; /// Starts a new worker over the shared work of an opened scan. type NewWorker = dyn Fn() -> BoxStream<'static, VortexResult> + Send + Sync; -/// The arrays of an opened scan, which host threads read by each polling a clone. +/// A flag that an opened scan sets once no stream created afterwards would find work. /// -/// A clone is another worker over the same remaining work, like a clone of a channel's receiver: -/// the clones take work until none is left, so together they return every row of the scan -/// exactly once, in no particular order across clones. The number of clones a host polls is its -/// parallelism. 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 clone, for -/// example with `block_on`. Dropping a clone before it ends gives up any work it had taken, so a -/// host drops a clone early only when it abandons the scan. -pub struct ScanStream { +/// 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, - worker: Option>>, } -impl ScanStream { - /// A stream whose clones each poll a worker from `new_worker`. +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. A clone starts its worker when it is first polled. + /// 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), - worker: None, } } - /// A stream whose clones take the partitions of `scan` one at a time. + /// 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. + /// 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())); - Self::new(dtype, move || { - let partitions = stream::unfold(Arc::clone(&partitions), |shared| async move { - let next = shared.lock().await.next().await?; - Some((next, shared)) + 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( @@ -74,18 +122,50 @@ impl ScanStream { .boxed() }) } -} -impl Clone for ScanStream { - fn clone(&self) -> Self { - Self { + /// 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(), - new_worker: Arc::clone(&self.new_worker), - worker: None, + 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") @@ -97,12 +177,8 @@ impl fmt::Debug for ScanStream { impl Stream for ScanStream { type Item = VortexResult; - fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { - let this = self.get_mut(); - let new_worker = &*this.new_worker; - this.worker - .get_or_insert_with(new_worker) - .poll_next_unpin(cx) + fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + self.worker.poll_next_unpin(cx) } } @@ -134,6 +210,7 @@ mod tests { use vortex_buffer::Buffer; use vortex_error::VortexResult; + use super::ScanExec; use super::ScanStream; use crate::DataSourceScan; use crate::DataSourceScanRef; @@ -180,7 +257,7 @@ mod tests { 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 [`ScanStream::from_partitions`]. + /// A scan that has no queue of work of its own, so it opens into [`ScanExec::from_partitions`]. struct PartitionOnlyScan { rows: Vec, } @@ -194,8 +271,8 @@ mod tests { Ok(vec![self]) } - fn open(self: Box) -> VortexResult { - Ok(ScanStream::from_partitions(self)) + fn open(self: Box) -> VortexResult { + Ok(ScanExec::from_partitions(self)) } fn partition_count(&self) -> Precision { @@ -221,12 +298,18 @@ mod tests { } #[test] - fn clones_share_partitions() -> VortexResult<()> { - let stream = Box::new(PartitionOnlyScan { + fn streams_share_partitions() -> VortexResult<()> { + let exec = Box::new(PartitionOnlyScan { rows: vec![2, 3, 4, 5], }) .open()?; - assert_eq!(total_rows([stream.clone(), stream.clone(), stream])?, 14); + 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 48b8e31c7e8..a00404caf54 100644 --- a/vortex-scan/src/test.rs +++ b/vortex-scan/src/test.rs @@ -70,7 +70,7 @@ use crate::source::ScanInput; use crate::source::SegmentFuture; use crate::source::SegmentId; use crate::source::SegmentSource; -use crate::stream::ScanStream; +use crate::stream::ScanExec; pub static SESSION: LazyLock = LazyLock::new(VortexSession::empty); @@ -105,8 +105,8 @@ impl DataSourceScan for TestArrayScan { Ok(vec![self]) } - fn open(self: Box) -> VortexResult { - Ok(ScanStream::from_partitions(self)) + fn open(self: Box) -> VortexResult { + Ok(ScanExec::from_partitions(self)) } fn partition_count(&self) -> Precision {