From 28163bf322ca40e976f92c77e1aad29ace7a0393 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Thu, 19 Nov 2026 15:47:01 -0500 Subject: [PATCH 01/80] 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/80] 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 e468b71e2cb5bbc44725d4801ed5afd1572c7fb8 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Thu, 19 Nov 2026 15:54:11 -0500 Subject: [PATCH 03/80] Give layout scans a native split and open Layout scans now split on their layout splits and open into a pool whose workers share those splits through a channel. Multi-file scans queue an open for each deferred file; the worker that opens one sends the file's splits back into the channel for any worker to take. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-layout/src/scan/layout.rs | 553 ++++++++++++++++++- vortex-layout/src/scan/mod.rs | 1 + vortex-layout/src/scan/multi.rs | 681 +++++++++++++++++++++++- vortex-layout/src/scan/pool.rs | 480 +++++++++++++++++ vortex-layout/src/scan/repeated_scan.rs | 37 +- vortex-layout/src/scan/test.rs | 36 ++ vortex-scan/src/lib.rs | 15 +- vortex-scan/src/pool.rs | 14 +- 8 files changed, 1803 insertions(+), 14 deletions(-) create mode 100644 vortex-layout/src/scan/pool.rs diff --git a/vortex-layout/src/scan/layout.rs b/vortex-layout/src/scan/layout.rs index a0ab69310f8..926ea7cc8e8 100644 --- a/vortex-layout/src/scan/layout.rs +++ b/vortex-layout/src/scan/layout.rs @@ -37,6 +37,7 @@ use vortex_scan::Partition; use vortex_scan::PartitionRef; use vortex_scan::PartitionStream; use vortex_scan::ScanRequest; +use vortex_scan::pool::ScanPoolRef; use vortex_scan::selection::Selection; use vortex_session::VortexSession; @@ -44,9 +45,19 @@ use crate::LayoutReaderRef; use crate::scan::limit::RowLimit; use crate::scan::metrics::ScanMetrics; use crate::scan::metrics::ScanRecorder; +use crate::scan::pool::FileWork; +use crate::scan::pool::PiecePartition; +use crate::scan::pool::PoolFile; +use crate::scan::pool::PoolOptions; +use crate::scan::pool::PreparedScan; +use crate::scan::pool::open_pool; use crate::scan::scan_builder::ScanBuilder; /// An implementation of a [`DataSource`] that reads data from a [`LayoutReaderRef`]. +/// +/// When a scan is [split](DataSourceScan::split) or [opened](DataSourceScan::open), its units are +/// the layout's splits. Workers of an opened scan share them, each keeping several in flight on +/// its own thread. pub struct LayoutReaderDataSource { reader: LayoutReaderRef, session: VortexSession, @@ -201,6 +212,7 @@ impl DataSource for LayoutReaderDataSource { dtype, projection, filter, + limit: scan_request.limit, remaining_limit: scan_request.limit, row_limit, selection: scan_request.selection, @@ -224,6 +236,8 @@ struct LayoutReaderScan { dtype: DType, projection: BoundExpression, filter: Option, + /// The request's limit. + limit: Option, /// Limit rows not yet covered by the splits produced so far; production stops at zero. /// Decremented only for filterless scans, where each split's output is exactly its /// selected row count. @@ -239,6 +253,36 @@ struct LayoutReaderScan { split_size: u64, } +impl LayoutReaderScan { + /// Prepares the scan once, for splitting or opening. + fn into_split_scan(self) -> VortexResult { + let row_count = DataSourceScan::row_count(&self); + let options = LayoutScanOptions { + dtype: self.dtype, + ordered: self.ordered, + limit: self.limit, + has_filter: self.filter.is_some(), + splits_in_flight: self.split_concurrency, + }; + let row_range = clamp_row_range(self.next_row..self.end_row, self.reader.row_count()); + let scan = ScanBuilder::new(self.session, self.reader) + .with_row_range(row_range) + .with_selection(self.selection) + .with_projection(self.projection) + .with_some_filter(self.filter) + .with_some_scan_metrics(self.metrics) + .with_ordered(self.ordered) + .prepare()?; + let ranges = scan.split_ranges(None); + Ok(LayoutSplitScan { + options, + row_count, + scan: Arc::new(scan), + ranges, + }) + } +} + impl DataSourceScan for LayoutReaderScan { fn dtype(&self) -> &DType { &self.dtype @@ -256,6 +300,165 @@ impl DataSourceScan for LayoutReaderScan { fn partitions(self: Box) -> PartitionStream { (*self).boxed() } + + fn row_count(&self) -> Precision { + let selected = self + .selection + .row_count_in_range(&(self.next_row..self.end_row)); + let rows = self.limit.map_or(selected, |limit| selected.min(limit)); + if self.filter.is_some() { + Precision::inexact(rows) + } else { + Precision::exact(rows) + } + } + + fn split(self: Box, n: NonZeroUsize) -> VortexResult> { + Box::new(self.into_split_scan()?).split(n) + } + + fn open(self: Box) -> VortexResult { + Box::new(self.into_split_scan()?).open() + } +} + +/// Clamps a requested row range to the rows of the source. +fn clamp_row_range(row_range: Range, total_rows: u64) -> Range { + let end = row_range.end.min(total_rows); + row_range.start.min(end)..end +} + +/// What a [`LayoutSplitScan`] and every piece cut from it share. +#[derive(Clone)] +struct LayoutScanOptions { + dtype: DType, + ordered: bool, + limit: Option, + has_filter: bool, + splits_in_flight: Option, +} + +/// A prepared scan of one layout reader over some of its splits: a [`LayoutReaderScan`] that was +/// split or opened, or a piece cut from one. +struct LayoutSplitScan { + options: LayoutScanOptions, + row_count: Precision, + scan: Arc, + /// The scan's units: its layout splits, in row order. + ranges: Vec>, +} + +impl LayoutSplitScan { + /// A piece over some of the prepared scan's split `ranges`. + fn piece( + options: &LayoutScanOptions, + scan: Arc, + ranges: Vec>, + ) -> Self { + let selected = ranges + .iter() + .map(|range| scan.selected_row_count(range)) + .sum::(); + Self { + options: options.clone(), + row_count: if options.has_filter { + Precision::inexact(selected) + } else { + Precision::exact(selected) + }, + scan, + ranges, + } + } +} + +impl DataSourceScan for LayoutSplitScan { + fn dtype(&self) -> &DType { + &self.options.dtype + } + + fn partition_count(&self) -> Precision { + Precision::exact(1usize) + } + + fn partitions(self: Box) -> PartitionStream { + let index = self.ranges.first().map_or(0, |range| { + usize::try_from(range.start).unwrap_or(usize::MAX) + }); + PiecePartition::stream(self, index) + } + + fn row_count(&self) -> Precision { + self.row_count + } + + fn split(self: Box, n: NonZeroUsize) -> VortexResult> { + if self.options.limit.is_some() || self.ranges.len() <= 1 || n.get() == 1 { + return Ok(vec![self]); + } + let LayoutSplitScan { + options, + scan, + ranges, + .. + } = *self; + Ok(group_contiguous(ranges, n) + .into_iter() + .map(|ranges| { + Box::new(LayoutSplitScan::piece(&options, Arc::clone(&scan), ranges)) + as DataSourceScanRef + }) + .collect()) + } + + fn open(self: Box) -> VortexResult { + let LayoutScanOptions { + dtype, + ordered, + limit, + has_filter, + splits_in_flight, + } = self.options; + if limit == Some(0) { + return Box::new(Empty::new(dtype, 0)).open(); + } + let work = FileWork::start(self.scan, self.ranges)?; + let options = PoolOptions { + dtype, + ordered, + limit, + has_filter, + splits_in_flight, + }; + Ok(open_pool(options, vec![PoolFile::Opened(work)], None)) + } +} + +/// Groups consecutive `ranges` into at most `n` contiguous groups of about equal row counts. +/// +/// Never cuts a range: each range lands whole in one group. +pub(crate) fn group_contiguous(ranges: Vec>, n: NonZeroUsize) -> Vec>> { + let total = ranges + .iter() + .map(|range| u128::from(range.end - range.start)) + .sum::() + .max(1); + let n_groups = n.get() as u128; + let mut groups: Vec>> = Vec::new(); + let mut current_group = None; + let mut before = 0u128; + for range in ranges { + let group = (before * n_groups / total).min(n_groups - 1); + before += u128::from(range.end - range.start); + if current_group != Some(group) { + current_group = Some(group); + groups.push(Vec::new()); + } + if let Some(last) = groups.last_mut() { + last.push(range); + } + } + groups } impl Stream for LayoutReaderScan { @@ -393,11 +596,17 @@ impl Partition for LayoutReaderSplit { } /// A scan that produces no data, only empty arrays with the correct row count. -struct Empty { +pub(crate) struct Empty { dtype: DType, row_count: u64, } +impl Empty { + pub(crate) fn new(dtype: DType, row_count: u64) -> Self { + Self { dtype, row_count } + } +} + impl DataSourceScan for Empty { fn dtype(&self) -> &DType { &self.dtype @@ -410,6 +619,10 @@ impl DataSourceScan for Empty { fn partitions(self: Box) -> PartitionStream { stream::iter([Ok(self as _)]).boxed() } + + fn row_count(&self) -> Precision { + Precision::exact(self.row_count) + } } impl Partition for Empty { @@ -620,3 +833,341 @@ mod tests { Ok(()) } } + +#[cfg(test)] +mod pool_tests { + use std::num::NonZeroUsize; + use std::sync::Arc; + + use rstest::rstest; + use vortex_array::dtype::DType; + use vortex_array::dtype::Nullability; + use vortex_array::dtype::StructFields; + use vortex_array::expr::Expression; + use vortex_array::expr::root; + use vortex_buffer::Buffer; + use vortex_error::VortexResult; + use vortex_metrics::DefaultMetricsRegistry; + use vortex_metrics::MetricValue; + use vortex_metrics::MetricsRegistry; + use vortex_scan::DataSource; + use vortex_scan::DataSourceScanRef; + use vortex_scan::ScanRequest; + use vortex_scan::selection::Selection; + use vortex_scan::strict_sorted_buffer::StrictSortedBuffer; + + use super::LayoutReaderDataSource; + use super::group_contiguous; + use crate::scan::test::TestLayoutReader; + use crate::scan::test::collect_scan_values; + use crate::scan::test::keep_odd; + use crate::scan::test::new_session; + use crate::scan::test::read_with_one_worker; + use crate::scan::test::read_with_workers; + + fn counter_values(registry: &DefaultMetricsRegistry) -> Vec { + registry + .snapshot() + .iter() + .map(|metric| match metric.value() { + MetricValue::Counter(counter) => counter.value(), + _ => panic!("expected a scan counter"), + }) + .collect() + } + + fn plan( + source: &LayoutReaderDataSource, + request: ScanRequest, + ) -> VortexResult { + futures::executor::block_on(source.scan(request)) + } + + /// Earlier splits finish last, so completion order is the reverse of row order. + fn slow_start(row: u64) -> usize { + usize::try_from(32u64.saturating_sub(row)).unwrap_or(0) + } + + fn source(reader: TestLayoutReader) -> LayoutReaderDataSource { + LayoutReaderDataSource::new(Arc::new(reader), new_session()) + } + + /// Each opened scan is one execution: it counts one file scan, and one attempt per split. + #[test] + fn opened_executions_share_aggregate_handles() -> VortexResult<()> { + let registry = Arc::new(DefaultMetricsRegistry::default()); + let source = source(TestLayoutReader::new(8).with_split_size(2)) + .with_metrics_registry(Arc::::clone(®istry)); + for execution in 1..=2 { + let pool = plan(&source, ScanRequest::default())?.open()?; + let values = read_with_workers(&pool, 2)?.concat(); + assert_eq!(values.len(), 8); + assert_eq!( + counter_values(®istry), + [4 * execution, 0, 0, execution, 0] + ); + } + Ok(()) + } + + /// N workers on one pool read every split exactly once. + #[rstest] + #[case::ordered(true)] + #[case::unordered(false)] + fn workers_read_every_split_once(#[case] ordered: bool) -> VortexResult<()> { + let source = source(TestLayoutReader::new(64).with_split_size(1)); + let pool = plan( + &source, + ScanRequest { + ordered, + ..Default::default() + }, + )? + .open()?; + let per_worker = read_with_workers(&pool, 4)?; + + let mut values = per_worker.concat(); + values.sort_unstable(); + assert_eq!(values, (0..64).collect::>()); + Ok(()) + } + + /// A worker of an ordered pool yields rows in row order, even when later splits finish + /// first, and later workers of the pool get nothing. + #[test] + fn ordered_worker_yields_row_order() -> VortexResult<()> { + let read = |ordered| { + let source = source( + TestLayoutReader::new(32) + .with_split_size(1) + .with_yields(slow_start), + ); + let pool = plan( + &source, + ScanRequest { + ordered, + ..Default::default() + }, + )? + .open()?; + let first = read_with_one_worker(Arc::clone(&pool))?; + let second = read_with_one_worker(pool)?; + assert!(second.is_empty()); + Ok::<_, vortex_error::VortexError>(first) + }; + + assert_eq!(read(true)?, (0..32).collect::>()); + // The same splits complete out of order, so an unordered worker does not keep row order. + assert_ne!(read(false)?, (0..32).collect::>()); + Ok(()) + } + + /// A limit holds across several workers of an unordered pool, whether splits reserve their + /// rows up front (no filter) or trim their output (filter). + #[rstest] + #[case::reserved(None)] + #[case::trimmed(Some(root()))] + fn unordered_limit_holds_across_workers( + #[case] filter: Option, + ) -> VortexResult<()> { + let source = source(TestLayoutReader::new(64).with_split_size(2)); + let pool = plan( + &source, + ScanRequest { + filter, + limit: Some(7), + ..Default::default() + }, + )? + .open()?; + let mut values = read_with_workers(&pool, 4)?.concat(); + values.sort_unstable(); + values.dedup(); + assert_eq!(values.len(), 7); + Ok(()) + } + + /// An ordered pool with a limit returns exactly the first `limit` rows. + #[rstest] + #[case::reserved(false, &[0, 1, 2, 3, 4])] + #[case::trimmed(true, &[1, 3, 5, 7, 9])] + fn ordered_limit_returns_the_first_rows( + #[case] filtered: bool, + #[case] expected: &[i32], + ) -> VortexResult<()> { + let source = source( + TestLayoutReader::new(32) + .with_split_size(2) + .with_keep_row(keep_odd) + .with_yields(slow_start), + ); + let pool = plan( + &source, + ScanRequest { + filter: filtered.then(root), + ordered: true, + limit: Some(5), + ..Default::default() + }, + )? + .open()?; + assert_eq!(read_with_one_worker(pool)?, expected); + Ok(()) + } + + /// With a sparse selection and no filter, each split contributes only its selected rows, so + /// the workers keep taking splits until the limit is actually filled. + #[rstest] + #[case::ordered(true)] + #[case::unordered(false)] + fn opened_sparse_selection_with_limit_fills_the_limit( + #[case] ordered: bool, + ) -> VortexResult<()> { + let source = source(TestLayoutReader::new(12).with_split_size(2)); + + // Every two-row split contains exactly one selected row (the even ones). + let selection = + Selection::IncludeByIndex(StrictSortedBuffer::try_new(Buffer::from_iter([ + 0u64, 2, 4, 6, 8, 10, + ]))?); + let pool = plan( + &source, + ScanRequest { + selection, + limit: Some(3), + ordered, + ..Default::default() + }, + )? + .open()?; + let mut values = read_with_one_worker(pool)?; + if !ordered { + values.sort_unstable(); + } + assert_eq!(values, [0, 2, 4]); + Ok(()) + } + + /// `split(n)` pieces cover the scan exactly, are in row order, and never cut a layout split. + #[rstest] + #[case::fewer_pieces_than_splits(3, 3)] + #[case::more_pieces_than_splits(16, 7)] + fn split_pieces_cover_the_scan_on_split_boundaries( + #[case] n: usize, + #[case] expected_pieces: usize, + ) -> VortexResult<()> { + // Splits of three rows: [0, 3), [3, 6), ..., [18, 20). + let source = source(TestLayoutReader::new(20).with_split_size(3)); + let scan = plan(&source, ScanRequest::default())?; + let pieces = scan.split(NonZeroUsize::new(n).expect("non-zero"))?; + assert_eq!(pieces.len(), expected_pieces); + assert_eq!( + pieces + .iter() + .map(|piece| piece.row_count().as_exact()) + .sum::>(), + Some(20) + ); + + let mut values = Vec::new(); + for piece in pieces { + let piece_values = read_with_one_worker(piece.open()?)?; + let first = *piece_values.first().expect("pieces are not empty"); + let last = *piece_values.last().expect("pieces are not empty"); + assert_eq!(first % 3, 0, "piece starts on a split boundary"); + assert!( + (last + 1) % 3 == 0 || last == 19, + "piece ends on a split boundary" + ); + values.extend(piece_values); + } + assert_eq!(values, (0..20).collect::>()); + Ok(()) + } + + /// A piece read through the partitions API returns the same rows as its pool. + #[test] + fn split_pieces_read_through_partitions() -> VortexResult<()> { + let source = source(TestLayoutReader::new(20).with_split_size(3)); + let scan = plan( + &source, + ScanRequest { + ordered: true, + ..Default::default() + }, + )?; + let mut values = Vec::new(); + for piece in scan.split(NonZeroUsize::new(3).expect("non-zero"))? { + let partitions = + futures::executor::block_on_stream(piece.partitions()).collect::>(); + assert_eq!(partitions.len(), 1); + for partition in partitions { + values.extend(collect_scan_values(futures::executor::block_on_stream( + partition?.execute()?, + ))?); + } + } + assert_eq!(values, (0..20).collect::>()); + Ok(()) + } + + #[test] + fn split_keeps_a_limited_scan_whole() -> VortexResult<()> { + let source = source(TestLayoutReader::new(20).with_split_size(3)); + let scan = plan( + &source, + ScanRequest { + limit: Some(4), + ..Default::default() + }, + )?; + let pieces = scan.split(NonZeroUsize::new(4).expect("non-zero"))?; + assert_eq!(pieces.len(), 1); + Ok(()) + } + + #[test] + fn grouping_never_returns_more_groups_than_requested() { + let ranges = (0..10u64) + .map(|start| start * 10..start * 10 + 10) + .collect(); + let groups = group_contiguous(ranges, NonZeroUsize::new(3).expect("non-zero")); + assert_eq!(groups.len(), 3); + assert_eq!(groups.concat().len(), 10); + } + + /// A length-only scan opens into one pool whose workers together return its rows once. + #[test] + fn length_only_scan_returns_its_rows_once_across_workers() -> VortexResult<()> { + let source = source(TestLayoutReader::new(10).with_dtype(DType::Struct( + StructFields::empty(), + Nullability::NonNullable, + ))); + let pool = plan( + &source, + ScanRequest { + limit: Some(7), + ..Default::default() + }, + )? + .open()?; + let rows: usize = std::thread::scope(|scope| { + let handles = (0..3) + .map(|_| { + let worker = Arc::clone(&pool).worker(); + scope.spawn(move || { + futures::executor::block_on_stream(worker) + .map(|array| array.map(|array| array.len())) + .sum::>() + }) + }) + .collect::>(); + handles + .into_iter() + .map(|handle| handle.join().expect("worker thread panicked")) + .sum::>() + })?; + assert_eq!(rows, 7); + Ok(()) + } +} diff --git a/vortex-layout/src/scan/mod.rs b/vortex-layout/src/scan/mod.rs index ea8e8843773..ea8ea2d8e0f 100644 --- a/vortex-layout/src/scan/mod.rs +++ b/vortex-layout/src/scan/mod.rs @@ -7,6 +7,7 @@ pub mod layout; mod limit; pub mod metrics; pub mod multi; +mod pool; pub mod repeated_scan; pub mod scan_builder; pub mod split_by; diff --git a/vortex-layout/src/scan/multi.rs b/vortex-layout/src/scan/multi.rs index 1f1ee275688..be41497e0ad 100644 --- a/vortex-layout/src/scan/multi.rs +++ b/vortex-layout/src/scan/multi.rs @@ -57,12 +57,24 @@ 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; use crate::LayoutReaderRef; +use crate::scan::layout::Empty; +use crate::scan::layout::group_contiguous; use crate::scan::limit::RowLimit; +use crate::scan::pool::FileWork; +use crate::scan::pool::PiecePartition; +use crate::scan::pool::PlannedSplits; +use crate::scan::pool::PoolFile; +use crate::scan::pool::PoolOptions; +use crate::scan::pool::PrepareFile; +use crate::scan::pool::PreparedScan; +use crate::scan::pool::open_pool; use crate::scan::scan_builder::ScanBuilder; /// Default concurrency for opening deferred readers. @@ -322,7 +334,6 @@ impl DataSource for MultiLayoutDataSource { row_limit, ready, deferred, - handle: self.session.handle(), concurrency: self.concurrency, })) } @@ -374,6 +385,17 @@ impl BoundScanRequest { split_concurrency, }) } + + /// Whether the scan filters rows, so its output row count is unknown up front. A filter + /// that failed to bind counts as one. + fn has_filter(&self) -> bool { + !matches!(self.filter, Ok(None)) + } + + /// Whether the request selects partitions, which only the partitions path applies. + fn selects_partitions(&self) -> bool { + self.partition_range.is_some() || !matches!(self.partition_selection, Selection::All) + } } struct MultiLayoutScan { @@ -384,10 +406,31 @@ struct MultiLayoutScan { row_limit: Option, ready: VecDeque, deferred: VecDeque>, - handle: vortex_io::runtime::Handle, concurrency: usize, } +impl MultiLayoutScan { + /// The scan as files to split or open. Files keep their partition order. + fn into_split_scan(self) -> MultiLayoutSplitScan { + let children = self + .ready + .into_iter() + .map(ScanChild::Opened) + .chain(self.deferred.into_iter().map(ScanChild::Deferred)) + .collect(); + MultiLayoutSplitScan { + context: Arc::new(ScanContext { + session: self.session, + source_dtype: self.source_dtype, + dtype: self.dtype, + request: self.request, + }), + children, + index: 0, + } + } +} + impl DataSourceScan for MultiLayoutScan { fn dtype(&self) -> &DType { &self.dtype @@ -402,6 +445,35 @@ impl DataSourceScan for MultiLayoutScan { } } + fn row_count(&self) -> Precision { + let estimate = estimate_row_count( + &self.request, + self.ready + .iter() + .map(|reader| file_row_count(&self.request, reader)), + self.ready.len() + self.deferred.len(), + ); + if self.request.selects_partitions() { + estimate.into_inexact() + } else { + estimate + } + } + + fn split(self: Box, n: NonZeroUsize) -> VortexResult> { + if self.request.selects_partitions() { + return Ok(vec![self]); + } + Box::new(self.into_split_scan()).split(n) + } + + fn open(self: Box) -> VortexResult { + if self.request.selects_partitions() { + return Ok(Arc::new(PartitionPool::new(self))); + } + Box::new(self.into_split_scan()).open() + } + fn partitions(self: Box) -> PartitionStream { let Self { session, @@ -411,9 +483,9 @@ impl DataSourceScan for MultiLayoutScan { row_limit, ready, deferred, - handle, concurrency, } = *self; + let handle = session.handle(); let ordered = request.ordered; @@ -623,6 +695,279 @@ impl Partition for MultiLayoutPartition { } } +/// The rows `request` selects from an opened file, before any filter or limit. +fn file_row_count(request: &BoundScanRequest, reader: &LayoutReaderRef) -> u64 { + let row_range = request + .row_range + .clone() + .unwrap_or_else(|| 0..reader.row_count()); + request.selection.row_count_in_range(&row_range) +} + +/// Estimates the rows a scan of `files` files returns from the rows of the files whose rows are +/// known, extrapolating to the rest. +fn estimate_row_count( + request: &BoundScanRequest, + known: impl Iterator, + files: usize, +) -> Precision { + let (rows, known_files) = known.fold((0u64, 0u64), |(rows, count), file_rows| { + (rows.saturating_add(file_rows), count + 1) + }); + let files = files as u64; + let (rows, is_exact) = if known_files == files { + (rows, !request.has_filter()) + } else if let Some(average) = rows.checked_div(known_files) { + (average.saturating_mul(files), false) + } else { + return Precision::Absent; + }; + let rows = request.limit.map_or(rows, |limit| rows.min(limit)); + if is_exact { + Precision::exact(rows) + } else { + Precision::inexact(rows) + } +} + +/// What every piece of a split or opened multi-layout scan shares. +struct ScanContext { + session: VortexSession, + source_dtype: DType, + dtype: DType, + request: BoundScanRequest, +} + +impl ScanContext { + /// Plans the scan of one opened file: checks its dtype, prunes it on statistics, and + /// prepares its splits. Returns `None` when statistics reject the file. Reads metadata only. + fn plan_file(&self, reader: LayoutReaderRef) -> VortexResult> { + if reader.dtype() != &self.source_dtype { + return Err(vortex_err!( + "Multi-layout reader dtype mismatch: expected {}, got {}", + self.source_dtype, + reader.dtype() + )); + } + let filter = self.request.filter.clone()?; + let row_range = self + .request + .row_range + .clone() + .unwrap_or_else(|| 0..reader.row_count()); + + if let Some(filter) = &filter { + let mask_len = usize::try_from(row_range.end - row_range.start).unwrap_or(usize::MAX); + if let Ok(pruning) = + reader.pruning_evaluation(&row_range, filter, Mask::new_true(mask_len)) + && let Some(Ok(mask)) = pruning.now_or_never() + && mask.all_false() + { + return Ok(None); + } + } + + let scan = ScanBuilder::new(self.session.clone(), reader) + .with_row_range(row_range) + .with_selection(self.request.selection.clone()) + .with_projection(self.request.projection.clone()) + .with_some_filter(filter) + .with_ordered(self.request.ordered) + .prepare()?; + let ranges = scan.split_ranges(None); + Ok(Some((Arc::new(scan), ranges))) + } + + /// Starts reading an opened file for one execution. + fn start_file(&self, reader: LayoutReaderRef) -> VortexResult { + match self.plan_file(reader)? { + Some((scan, ranges)) => FileWork::start(scan, ranges), + None => Ok(FileWork::empty()), + } + } +} + +/// One file of a split or opened multi-layout scan. +enum ScanChild { + Opened(LayoutReaderRef), + /// An opened file whose splits are known: all of them, or the share of one piece. + Planned { + scan: Arc, + ranges: Vec>, + }, + Deferred(Arc), +} + +/// A multi-layout scan that was split or opened, or a piece cut from one. Its units are files, +/// then each file's splits. +struct MultiLayoutSplitScan { + context: Arc, + children: Vec, + /// The index of the piece's single partition. + index: usize, +} + +impl MultiLayoutSplitScan { + /// Splits a planned file's ranges into `pieces` contiguous groups. + fn split_child(child: ScanChild, pieces: usize) -> Vec { + match child { + ScanChild::Planned { scan, ranges } if pieces > 1 => group_contiguous( + ranges, + NonZeroUsize::new(pieces).unwrap_or(NonZeroUsize::MIN), + ) + .into_iter() + .map(|ranges| ScanChild::Planned { + scan: Arc::clone(&scan), + ranges, + }) + .collect(), + child => vec![child], + } + } +} + +impl DataSourceScan for MultiLayoutSplitScan { + fn dtype(&self) -> &DType { + &self.context.dtype + } + + fn partition_count(&self) -> Precision { + Precision::exact(1usize) + } + + fn partitions(self: Box) -> PartitionStream { + let index = self.index; + PiecePartition::stream(self, index) + } + + fn row_count(&self) -> Precision { + let request = &self.context.request; + let known = self.children.iter().filter_map(|child| match child { + ScanChild::Opened(reader) => Some(file_row_count(request, reader)), + ScanChild::Planned { scan, ranges } => Some( + ranges + .iter() + .map(|range| scan.selected_row_count(range)) + .sum(), + ), + ScanChild::Deferred(_) => None, + }); + estimate_row_count(request, known, self.children.len()) + } + + fn split(self: Box, n: NonZeroUsize) -> VortexResult> { + if self.context.request.limit.is_some() || n.get() == 1 || self.children.is_empty() { + return Ok(vec![self]); + } + let MultiLayoutSplitScan { + context, children, .. + } = *self; + + // Plan the opened files so they can be cut on their splits. Deferred files stay whole: + // splitting never opens a file. + let mut planned = Vec::with_capacity(children.len()); + for child in children { + match child { + ScanChild::Opened(reader) => { + if let Some((scan, ranges)) = context.plan_file(reader)? { + planned.push(ScanChild::Planned { scan, ranges }); + } + } + child => planned.push(child), + } + } + if planned.is_empty() { + return Ok(vec![Box::new(MultiLayoutSplitScan { + context, + children: planned, + index: 0, + })]); + } + + let n = n.get(); + let pieces: Vec> = if n <= planned.len() { + // Group whole files into contiguous pieces. + let files = planned.len(); + let mut pieces: Vec> = Vec::new(); + let mut current = None; + for (index, child) in planned.into_iter().enumerate() { + let piece = index * n / files; + if current != Some(piece) { + current = Some(piece); + pieces.push(Vec::new()); + } + if let Some(last) = pieces.last_mut() { + last.push(child); + } + } + pieces + } else { + // One piece per file, and the pieces left over cut planned files on their splits, in + // proportion to their rows. + let extra = (n - planned.len()) as u128; + let rows = |child: &ScanChild| match child { + ScanChild::Planned { ranges, .. } => ranges + .iter() + .map(|range| u128::from(range.end - range.start)) + .sum::(), + _ => 0, + }; + let total = planned.iter().map(rows).sum::().max(1); + planned + .into_iter() + .flat_map(|child| { + let pieces = 1 + usize::try_from(extra * rows(&child) / total).unwrap_or(0); + Self::split_child(child, pieces) + }) + .map(|child| vec![child]) + .collect() + }; + + Ok(pieces + .into_iter() + .enumerate() + .map(|(index, children)| { + Box::new(MultiLayoutSplitScan { + context: Arc::clone(&context), + children, + index, + }) as DataSourceScanRef + }) + .collect()) + } + + fn open(self: Box) -> VortexResult { + let MultiLayoutSplitScan { + context, children, .. + } = *self; + let request = &context.request; + if request.limit == Some(0) { + return Box::new(Empty::new(context.dtype.clone(), 0)).open(); + } + + let mut files = Vec::with_capacity(children.len()); + for child in children { + files.push(match child { + ScanChild::Opened(reader) => PoolFile::Opened(context.start_file(reader)?), + ScanChild::Planned { scan, ranges } => { + PoolFile::Opened(FileWork::start(scan, ranges)?) + } + ScanChild::Deferred(factory) => PoolFile::Deferred(factory), + }); + } + + let options = PoolOptions { + dtype: context.dtype.clone(), + ordered: request.ordered, + limit: request.limit, + has_filter: request.has_filter(), + splits_in_flight: request.split_concurrency, + }; + let prepare: PrepareFile = Arc::new(move |reader| context.start_file(reader)); + Ok(open_pool(options, files, Some(prepare))) + } +} + #[cfg(test)] mod tests { use std::sync::Arc; @@ -799,3 +1144,333 @@ mod tests { Ok(()) } } + +#[cfg(test)] +mod pool_tests { + use std::sync::Arc; + use std::sync::atomic::AtomicBool; + use std::sync::atomic::AtomicUsize; + use std::sync::atomic::Ordering; + use std::task::Context; + use std::task::Poll; + + use async_trait::async_trait; + use futures::StreamExt; + use futures::future::poll_fn; + use futures::task::ArcWake; + use futures::task::AtomicWaker; + use futures::task::noop_waker_ref; + use futures::task::waker; + use rstest::rstest; + use vortex_array::ArrayRef; + use vortex_array::dtype::Nullability; + use vortex_array::dtype::PType; + use vortex_array::expr::root; + use vortex_array::stream::SendableArrayStream; + use vortex_buffer::Buffer; + use vortex_error::VortexResult; + use vortex_io::runtime::BlockingRuntime; + use vortex_io::runtime::single::SingleThreadRuntime; + use vortex_scan::DataSource; + use vortex_scan::ScanRequest; + use vortex_scan::strict_sorted_buffer::StrictSortedBuffer; + + use super::*; + use crate::scan::test::InFlight; + use crate::scan::test::TestLayoutReader; + use crate::scan::test::collect_scan_values; + use crate::scan::test::new_session; + use crate::scan::test::read_with_one_worker; + use crate::scan::test::read_with_workers; + use crate::scan::test::session_with_handle; + + fn plan( + source: &MultiLayoutDataSource, + request: ScanRequest, + ) -> VortexResult { + futures::executor::block_on(source.scan(request)) + } + + fn i32_dtype() -> DType { + DType::Primitive(PType::I32, Nullability::NonNullable) + } + + /// A factory whose open completes only once its gate is released. + #[derive(Default)] + struct Gate { + is_open: AtomicBool, + waker: AtomicWaker, + } + + impl Gate { + fn release(&self) { + self.is_open.store(true, Ordering::SeqCst); + self.waker.wake(); + } + } + + struct GatedFactory { + reader: LayoutReaderRef, + gate: Arc, + opens: Arc, + } + + #[async_trait] + impl LayoutReaderFactory for GatedFactory { + async fn open(&self) -> VortexResult> { + self.opens.fetch_add(1, Ordering::SeqCst); + poll_fn(|cx| { + self.gate.waker.register(cx.waker()); + if self.gate.is_open.load(Ordering::SeqCst) { + Poll::Ready(()) + } else { + Poll::Pending + } + }) + .await; + Ok(Some(Arc::clone(&self.reader))) + } + } + + fn gated_factory(reader: TestLayoutReader, gate: &Arc) -> Arc { + Arc::new(GatedFactory { + reader: Arc::new(reader), + gate: Arc::clone(gate), + opens: Arc::default(), + }) + } + + /// Deferred files of `rows` one-row splits, the `i`th producing `100 * i + row`. + fn gated_source(files: usize, rows: u64) -> (MultiLayoutDataSource, Vec>) { + let gates: Vec<_> = (0..files).map(|_| Arc::new(Gate::default())).collect(); + let factories = gates + .iter() + .enumerate() + .map(|(index, gate)| { + let base = 100 * i32::try_from(index).expect("few files"); + gated_factory( + TestLayoutReader::new(rows) + .with_split_size(1) + .with_base(base), + gate, + ) + }) + .collect(); + let source = + MultiLayoutDataSource::new_deferred(i32_dtype(), factories, vec![], &new_session()); + (source, gates) + } + + #[derive(Default)] + struct WakeFlag(AtomicBool); + + impl ArcWake for WakeFlag { + fn wake_by_ref(arc_self: &Arc) { + arc_self.0.store(true, Ordering::SeqCst); + } + } + + fn poll_worker( + worker: &mut SendableArrayStream, + cx: &mut Context<'_>, + ) -> Poll>> { + worker.poll_next_unpin(cx) + } + + /// A deferred file is opened by a worker, and its splits are shared with other workers. A + /// worker that finds only an open in progress waits, and is woken when the open adds splits. + #[test] + fn deferred_file_splits_are_shared_with_waiting_workers() -> VortexResult<()> { + let (source, gates) = gated_source(1, 16); + let pool = plan(&source, ScanRequest::default())?.open()?; + let mut opener = Arc::clone(&pool).worker(); + let mut waiter = Arc::clone(&pool).worker(); + let mut noop = Context::from_waker(noop_waker_ref()); + let flag = Arc::new(WakeFlag::default()); + let flag_waker = waker(Arc::clone(&flag)); + let mut flagged = Context::from_waker(&flag_waker); + + // The opener takes the only file and blocks on its open; the waiter finds nothing to take + // but an open in progress, so it waits. + assert!(poll_worker(&mut opener, &mut noop).is_pending()); + assert!(poll_worker(&mut waiter, &mut flagged).is_pending()); + + gates[0].release(); + let Poll::Ready(Some(first)) = poll_worker(&mut opener, &mut noop) else { + panic!("the opener reads a split of the file it opened"); + }; + assert!(flag.0.load(Ordering::SeqCst), "the waiter is woken"); + + let waiter_values = collect_scan_values(futures::executor::block_on_stream(waiter))?; + let opener_values = collect_scan_values( + std::iter::once(first).chain(futures::executor::block_on_stream(opener)), + )?; + assert!( + !waiter_values.is_empty(), + "the waiter reads the opened file's splits" + ); + let mut values = [opener_values, waiter_values].concat(); + values.sort_unstable(); + assert_eq!(values, (0..16).collect::>()); + Ok(()) + } + + /// An ordered worker emits files in file order, even when a later file opens first. + #[test] + fn ordered_worker_emits_files_in_order() -> VortexResult<()> { + let (source, gates) = gated_source(3, 3); + let pool = plan( + &source, + ScanRequest { + ordered: true, + ..Default::default() + }, + )? + .open()?; + let mut worker = pool.worker(); + let mut noop = Context::from_waker(noop_waker_ref()); + assert!(poll_worker(&mut worker, &mut noop).is_pending()); + for gate in gates.iter().rev() { + gate.release(); + if !Arc::ptr_eq(gate, &gates[0]) { + assert!(poll_worker(&mut worker, &mut noop).is_pending()); + } + } + let values = collect_scan_values(futures::executor::block_on_stream(worker))?; + assert_eq!(values, [0, 1, 2, 100, 101, 102, 200, 201, 202]); + Ok(()) + } + + /// A limit is shared by every worker and file of an unordered pool. + #[test] + fn pool_limit_is_shared_across_readers() -> VortexResult<()> { + let first: LayoutReaderRef = Arc::new(TestLayoutReader::new(4).with_split_size(1)); + let gate = Arc::new(Gate::default()); + gate.release(); + let source = MultiLayoutDataSource::new_with_first( + first, + vec![gated_factory( + TestLayoutReader::new(4).with_split_size(1).with_base(10), + &gate, + )], + vec![], + &new_session(), + ); + + let pool = plan( + &source, + ScanRequest { + filter: Some(root()), + limit: Some(3), + ..Default::default() + }, + )? + .open()?; + let values = read_with_workers(&pool, 3)?.concat(); + + assert_eq!(values.len(), 3); + Ok(()) + } + + /// Splitting cuts opened files on their splits and keeps deferred files whole, in order. + #[test] + fn split_cuts_opened_files_and_keeps_deferred_files_whole() -> VortexResult<()> { + let first: LayoutReaderRef = Arc::new(TestLayoutReader::new(6).with_split_size(2)); + let opens = Arc::new(AtomicUsize::new(0)); + let gate = Arc::new(Gate::default()); + gate.release(); + let source = MultiLayoutDataSource::new_with_first( + first, + vec![Arc::new(GatedFactory { + reader: Arc::new(TestLayoutReader::new(4).with_split_size(2).with_base(100)), + gate, + opens: Arc::clone(&opens), + })], + vec![], + &new_session(), + ); + let scan = plan( + &source, + ScanRequest { + ordered: true, + ..Default::default() + }, + )?; + let pieces = scan.split(NonZeroUsize::new(4).expect("non-zero"))?; + assert_eq!(opens.load(Ordering::SeqCst), 0, "splitting opens no file"); + // The opened file's three splits take three pieces; the deferred file stays whole. + assert_eq!(pieces.len(), 4); + + let mut values = Vec::new(); + for piece in pieces { + values.extend(read_with_one_worker(piece.open()?)?); + } + assert_eq!(values, [0, 1, 2, 3, 4, 5, 100, 101, 102, 103]); + Ok(()) + } + + /// A request that selects partitions is split and opened by its partitions, so both paths + /// read the same files. + #[rstest] + #[case::range(Some(1..2), None)] + #[case::selection(None, Some(1))] + fn selected_partitions_open_by_partition( + #[case] partition_range: Option>, + #[case] selected_partition: Option, + ) -> VortexResult<()> { + let partition_selection = match selected_partition { + Some(index) => { + Selection::IncludeByIndex(StrictSortedBuffer::try_new(Buffer::from_iter([index]))?) + } + None => Selection::All, + }; + // The partitions path spawns file opens onto the session's runtime. + let runtime = SingleThreadRuntime::default(); + let gate = Arc::new(Gate::default()); + gate.release(); + let source = MultiLayoutDataSource::new_with_first( + Arc::new(TestLayoutReader::new(3)), + vec![gated_factory(TestLayoutReader::new(3).with_base(10), &gate)], + vec![], + &session_with_handle(runtime.handle()), + ); + let request = ScanRequest { + partition_range, + partition_selection, + ordered: true, + ..Default::default() + }; + let pieces = plan(&source, request.clone())?.split(NonZeroUsize::new(4).expect("4"))?; + assert_eq!(pieces.len(), 1); + let pool = plan(&source, request)?.open()?; + let values = collect_scan_values(runtime.block_on_stream(pool.worker()))?; + assert_eq!(values, [10, 11, 12]); + Ok(()) + } + + /// A worker reads at most `split_concurrency` splits at once. + #[rstest] + #[case(1)] + #[case(2)] + fn split_concurrency_bounds_each_worker(#[case] max: usize) -> VortexResult<()> { + let in_flight = Arc::new(InFlight::default()); + let reader: LayoutReaderRef = Arc::new( + TestLayoutReader::new(64) + .with_split_size(1) + .with_in_flight(Arc::clone(&in_flight)), + ); + let source = MultiLayoutDataSource::new_with_first(reader, vec![], vec![], &new_session()); + let pool = plan( + &source, + ScanRequest { + ordered: true, + split_concurrency: NonZeroUsize::new(max), + ..Default::default() + }, + )? + .open()?; + assert_eq!(read_with_one_worker(pool)?, (0..64).collect::>()); + assert!(in_flight.peak() <= max, "peak {}", in_flight.peak()); + Ok(()) + } +} diff --git a/vortex-layout/src/scan/pool.rs b/vortex-layout/src/scan/pool.rs new file mode 100644 index 00000000000..fcfea905b7a --- /dev/null +++ b/vortex-layout/src/scan/pool.rs @@ -0,0 +1,480 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! The work that the workers of an opened layout scan share. +//! +//! A pool's units are the splits of one or more files, and the files not yet opened. A worker +//! takes units and keeps up to `splits_in_flight` of them running on its own thread: it +//! builds a split's task only when it takes the split, and never spawns. Opening a deferred file +//! is a unit like any other. +//! +//! - An unordered pool hands units out through a channel. The worker that opens a deferred file +//! sends the file's splits back into the channel, where any worker can take them. The channel +//! closes once every open has finished, which ends the workers. +//! - An ordered pool gives all of its units, in row order, to its first worker; later workers +//! get nothing. Parallel ordered reads cut the scan with `split` first. + +use std::any::Any; +use std::num::NonZeroUsize; +use std::ops::Range; +use std::sync::Arc; + +use async_channel::Receiver; +use async_channel::Sender; +use futures::FutureExt; +use futures::StreamExt; +use futures::future; +use futures::future::BoxFuture; +use futures::stream; +use futures::stream::BoxStream; +use parking_lot::Mutex; +use tracing::Instrument; +use vortex_array::ArrayRef; +use vortex_array::dtype::DType; +use vortex_array::expr::stats::Precision; +use vortex_array::stream::ArrayStreamAdapter; +use vortex_array::stream::ArrayStreamExt; +use vortex_array::stream::SendableArrayStream; +use vortex_error::VortexResult; +use vortex_scan::DataSourceScanRef; +use vortex_scan::Partition; +use vortex_scan::PartitionRef; +use vortex_scan::PartitionStream; +use vortex_scan::pool::ScanPool; +use vortex_scan::pool::ScanPoolRef; +use vortex_scan::row_mask::RowMask; + +use crate::LayoutReaderRef; +use crate::scan::limit::RowLimit; +use crate::scan::multi::LayoutReaderFactory; +use crate::scan::repeated_scan::RepeatedScan; +use crate::scan::repeated_scan::can_prune_file; +use crate::scan::tasks::TaskContext; + +/// A scan prepared once and shared by every piece and execution of it. +pub(crate) type PreparedScan = RepeatedScan; + +/// A prepared scan and the row ranges of its splits, in row order. +pub(crate) type PlannedSplits = (Arc, Vec>); + +/// The most splits each worker keeps in flight when the request does not say; stands in for the +/// scan engine's memory budget. +const SPLITS_IN_FLIGHT_PER_WORKER: usize = 4; + +/// One execution of one file's prepared scan. +pub(crate) struct FileScan { + scan: Arc, + /// Records this execution's events, so file events count once for each execution. + ctx: Arc, +} + +/// One file's splits for one execution, ready to be handed to workers. +pub(crate) struct FileWork { + scan: Option>, + ranges: Vec>, +} + +impl FileWork { + /// A file with nothing to read, for example one that statistics pruned. + pub(crate) fn empty() -> Self { + Self { + scan: None, + ranges: Vec::new(), + } + } + + /// Starts an execution of `scan` over its split `ranges`. + /// + /// Counts a file scan attempt when the ranges select any row, and returns no work when + /// whole-file statistics reject the filter. + pub(crate) fn start(scan: Arc, ranges: Vec>) -> VortexResult { + if !ranges.iter().any(|range| scan.selects_rows(range)) { + return Ok(Self::empty()); + } + let ctx = scan.task_context(); + if can_prune_file(&ctx)? { + return Ok(Self::empty()); + } + Ok(Self { + scan: Some(Arc::new(FileScan { scan, ctx })), + ranges, + }) + } +} + +/// Opens a deferred file's reader into its work for this execution. +pub(crate) type PrepareFile = Arc VortexResult + Send + Sync>; + +/// A file of a pool, in file order. +pub(crate) enum PoolFile { + Opened(FileWork), + Deferred(Arc), +} + +/// How a pool reads its splits. +pub(crate) struct PoolOptions { + pub(crate) dtype: DType, + pub(crate) ordered: bool, + pub(crate) limit: Option, + /// Whether the scan filters rows, so a split's output row count is unknown up front. + pub(crate) has_filter: bool, + /// The most splits each worker keeps in flight, or the default when `None`. + pub(crate) splits_in_flight: Option, +} + +/// Opens a pool over `files`, in file order. `prepare` turns an opened deferred file into work. +pub(crate) fn open_pool( + options: PoolOptions, + files: Vec, + prepare: Option, +) -> ScanPoolRef { + let limit = match options.limit { + None => PoolLimit::Unlimited, + Some(limit) if options.has_filter => PoolLimit::Trim(RowLimit::new(limit)), + Some(limit) => PoolLimit::Reserve(RowLimit::new(limit)), + }; + let splits_in_flight = options + .splits_in_flight + .map_or(SPLITS_IN_FLIGHT_PER_WORKER, NonZeroUsize::get); + let shared = Arc::new(Shared { + limit, + prepare, + file_share: 1.0 / files.len().max(1) as f64, + progress: Mutex::new(0.0), + }); + if options.ordered { + return Arc::new(OrderedPool { + dtype: options.dtype, + shared, + files: Mutex::new(Some(files)), + splits_in_flight, + }); + } + + let (sender, receiver) = async_channel::unbounded(); + for file in files { + match file { + PoolFile::Opened(work) => { + for (file, range, progress) in shared.file_splits(work) { + send(&sender, Work::Split(file, range, progress)); + } + } + PoolFile::Deferred(factory) => send(&sender, Work::Open(factory, sender.clone())), + } + } + Arc::new(UnorderedPool { + dtype: options.dtype, + shared, + receiver, + splits_in_flight, + }) +} + +/// How a pool's row limit is applied. +enum PoolLimit { + Unlimited, + /// A split's selected rows are its output rows, so each split reserves them from the budget + /// when a worker takes it, and rows past the limit are never decoded. Admission order is + /// row order for an ordered pool, so it returns exactly the first rows. + Reserve(RowLimit), + /// A split's output rows are unknown until its filter has run, so workers take rows from the + /// budget as they yield them and discard the excess. + Trim(RowLimit), +} + +impl PoolLimit { + fn is_exhausted(&self) -> bool { + match self { + PoolLimit::Unlimited => false, + PoolLimit::Reserve(limit) | PoolLimit::Trim(limit) => limit.is_exhausted(), + } + } +} + +/// A split's output: `None` when it has no rows to return. +type SplitFuture = BoxFuture<'static, VortexResult>>; + +/// A split of a file, with the progress that taking it adds. +type FileSplit = (Arc, Range, f64); + +/// What every worker of a pool shares. +struct Shared { + limit: PoolLimit, + prepare: Option, + /// The progress that one file adds. + file_share: f64, + progress: Mutex, +} + +impl Shared { + /// The splits of an opened file, in row order. + fn file_splits(&self, work: FileWork) -> Vec { + let rows: u64 = work + .ranges + .iter() + .map(|range| range.end - range.start) + .sum(); + match work.scan { + Some(scan) if rows > 0 => { + let per_row = self.file_share / rows as f64; + work.ranges + .into_iter() + .map(|range| { + let progress = per_row * (range.end - range.start) as f64; + (Arc::clone(&scan), range, progress) + }) + .collect() + } + _ => { + *self.progress.lock() += self.file_share; + Vec::new() + } + } + } + + /// Opens a deferred file into its work. + fn open_file( + self: &Arc, + factory: Arc, + ) -> BoxFuture<'static, VortexResult> { + let shared = Arc::clone(self); + async move { + let reader = factory + .open() + .instrument(tracing::info_span!("LayoutReaderFactory::open")) + .await?; + match (reader, &shared.prepare) { + (Some(reader), Some(prepare)) => prepare(reader), + _ => Ok(FileWork::empty()), + } + } + .boxed() + } + + /// Takes a split: reserves its rows from a reserved limit and builds its task. + fn admit(&self, (file, range, progress): FileSplit) -> SplitFuture { + *self.progress.lock() += progress; + let Some(mask) = file.scan.split_mask(&range) else { + return future::ready(Ok(None)).boxed(); + }; + let mask = match &self.limit { + PoolLimit::Reserve(limit) => { + let reserved = limit.limit(mask.mask().clone()); + if reserved.all_false() { + return future::ready(Ok(None)).boxed(); + } + RowMask::new(range.start, reserved) + } + PoolLimit::Unlimited | PoolLimit::Trim(_) => mask, + }; + match file.scan.split_task(&file.ctx, mask) { + Ok(task) => task, + Err(err) => future::ready(Err(err)).boxed(), + } + } + + #[expect( + dead_code, + reason = "read by ScanPool::progress, which arrives with its first host" + )] + fn progress(&self) -> f64 { + if self.limit.is_exhausted() { + return 1.0; + } + self.progress.lock().clamp(0.0, 1.0) + } +} + +/// A worker's output: skips splits with no rows, trims to a trimmed limit, and ends after the +/// first error or once a trimmed limit is spent. +fn limit_output( + outputs: BoxStream<'static, VortexResult>>, + shared: Arc, +) -> BoxStream<'static, VortexResult> { + stream::unfold(Some(outputs), move |outputs| { + let shared = Arc::clone(&shared); + async move { + let mut outputs = outputs?; + loop { + if let PoolLimit::Trim(limit) = &shared.limit + && limit.is_exhausted() + { + return None; + } + let array = match outputs.next().await? { + Ok(Some(array)) => array, + Ok(None) => continue, + Err(err) => return Some((Err(err), None)), + }; + let PoolLimit::Trim(limit) = &shared.limit else { + return Some((Ok(array), Some(outputs))); + }; + let granted = limit.take(array.len()); + if granted == 0 { + return None; + } + if granted == array.len() { + return Some((Ok(array), Some(outputs))); + } + return Some((array.slice(0..granted), None)); + } + } + }) + .boxed() +} + +/// A unit of an unordered pool. +enum Work { + Split(Arc, Range, f64), + /// A deferred file, and where to send its splits once it is open. The sender keeps the + /// channel open until the file's splits are in it. + Open(Arc, Sender), +} + +fn send(sender: &Sender, work: Work) { + // The channel is unbounded and closes only once the pool is dropped, when the work is moot. + drop(sender.try_send(work)); +} + +/// A pool whose workers share its units through a channel. +struct UnorderedPool { + dtype: DType, + shared: Arc, + receiver: Receiver, + splits_in_flight: usize, +} + +impl UnorderedPool { + fn run(shared: &Arc, work: Work) -> SplitFuture { + match work { + Work::Split(file, range, progress) => shared.admit((file, range, progress)), + Work::Open(factory, sender) => { + let shared = Arc::clone(shared); + async move { + let work = shared.open_file(factory).await?; + for (file, range, progress) in shared.file_splits(work) { + send(&sender, Work::Split(file, range, progress)); + } + Ok(None) + } + .boxed() + } + } + } +} + +impl ScanPool for UnorderedPool { + fn dtype(&self) -> &DType { + &self.dtype + } + + fn worker(self: Arc) -> SendableArrayStream { + let dtype = self.dtype.clone(); + let shared = Arc::clone(&self.shared); + let runner = Arc::clone(&shared); + let receiver = self.receiver.clone(); + let splits_in_flight = self.splits_in_flight; + // The worker holds the pool, so the pool is dropped only after its last worker. + let outputs = receiver + .take_while(move |_| future::ready(!self.shared.limit.is_exhausted())) + .map(move |work| UnorderedPool::run(&runner, work)) + .buffer_unordered(splits_in_flight) + .boxed(); + ArrayStreamExt::boxed(ArrayStreamAdapter::new( + dtype, + limit_output(outputs, shared), + )) + } +} + +impl Drop for UnorderedPool { + fn drop(&mut self) { + // Pending opens hold senders of the channel itself; drain them so it can be freed. + self.receiver.close(); + while self.receiver.try_recv().is_ok() {} + } +} + +/// A pool that gives all of its units, in row order, to its first worker. +struct OrderedPool { + dtype: DType, + shared: Arc, + /// The files, until the first worker takes them. + files: Mutex>>, + splits_in_flight: usize, +} + +impl ScanPool for OrderedPool { + fn dtype(&self) -> &DType { + &self.dtype + } + + fn worker(self: Arc) -> SendableArrayStream { + let dtype = self.dtype.clone(); + let Some(files) = self.files.lock().take() else { + return ArrayStreamExt::boxed(ArrayStreamAdapter::new(dtype, stream::empty())); + }; + let shared = Arc::clone(&self.shared); + let opener = Arc::clone(&shared); + let splitter = Arc::clone(&shared); + let admitter = Arc::clone(&shared); + let outputs = stream::iter(files) + .then(move |file| match file { + PoolFile::Opened(work) => future::ready(Ok(work)).boxed(), + PoolFile::Deferred(factory) => opener.open_file(factory), + }) + .flat_map(move |work| match work { + Ok(work) => { + stream::iter(splitter.file_splits(work).into_iter().map(Ok)).left_stream() + } + Err(err) => stream::once(future::ready(Err(err))).right_stream(), + }) + .take_while(move |_| future::ready(!shared.limit.is_exhausted())) + .map(move |split| match split { + Ok(split) => admitter.admit(split), + Err(err) => future::ready(Err(err)).boxed(), + }) + .buffered(self.splits_in_flight) + .boxed(); + ArrayStreamExt::boxed(ArrayStreamAdapter::new( + dtype, + limit_output(outputs, Arc::clone(&self.shared)), + )) + } +} + +/// The single partition of a scan piece that is read through the partitions API: it opens the +/// piece and reads it with one worker. +pub(crate) struct PiecePartition { + piece: DataSourceScanRef, + index: usize, +} + +impl PiecePartition { + /// The partitions of `piece`: one, whose index is `index`. + pub(crate) fn stream(piece: DataSourceScanRef, index: usize) -> PartitionStream { + stream::iter([Ok(Box::new(PiecePartition { piece, index }) as PartitionRef)]).boxed() + } +} + +impl Partition for PiecePartition { + fn as_any(&self) -> &dyn Any { + self + } + + fn index(&self) -> usize { + self.index + } + + fn row_count(&self) -> Precision { + self.piece.row_count() + } + + fn byte_size(&self) -> Precision { + self.piece.byte_size() + } + + fn execute(self: Box) -> VortexResult { + Ok(self.piece.open()?.worker()) + } +} diff --git a/vortex-layout/src/scan/repeated_scan.rs b/vortex-layout/src/scan/repeated_scan.rs index 2a1c7026923..dcd4cba58c8 100644 --- a/vortex-layout/src/scan/repeated_scan.rs +++ b/vortex-layout/src/scan/repeated_scan.rs @@ -175,7 +175,7 @@ impl RepeatedScan { } /// Each execution gets its own recorder, so file events count once for each execution. - fn task_context(&self) -> Arc { + pub(crate) fn task_context(&self) -> Arc { Arc::new(TaskContext { filter: self .filter @@ -188,7 +188,10 @@ impl RepeatedScan { }) } - fn split_ranges(&self, row_range: Option>) -> Vec> { + /// The row ranges of the scan's splits within `row_range`, in row order. + /// + /// Ranges whose rows the selection excludes are included; [`Self::split_mask`] skips them. + pub(crate) fn split_ranges(&self, row_range: Option>) -> Vec> { let selection_range: Option> = match &self.selection { Selection::IncludeByIndex(buf) if !buf.is_empty() => { Some(buf[0]..buf[buf.len() - 1] + 1) @@ -244,6 +247,33 @@ impl RepeatedScan { } } + /// Whether the selection includes any row of `range`. + pub(crate) fn selects_rows(&self, range: &Range) -> bool { + self.selection.row_count_in_range(range) != 0 + } + + /// The number of rows of `range` that the selection includes. + pub(crate) fn selected_row_count(&self, range: &Range) -> u64 { + self.selection.row_count_in_range(range) + } + + /// The selected rows of the split over `range`, or `None` if the selection excludes them all. + pub(crate) fn split_mask(&self, range: &Range) -> Option { + selected_mask(&self.selection, range) + } + + /// Builds the task of one split. The task does no work until it is polled, but building it + /// may register the split's reads with the reader, so build it only when it is about to run. + /// + /// `mask` must select at least one row. + pub(crate) fn split_task( + &self, + ctx: &Arc, + mask: RowMask, + ) -> VortexResult>>> { + Ok(map_split(split_exec(ctx, mask)?, &self.map_fn)) + } + /// The non-empty row masks of the splits within `row_range`, in split order. fn split_masks(&self, row_range: Option>) -> impl Iterator + '_ { self.split_ranges(row_range) @@ -362,7 +392,8 @@ fn selected_mask(selection: &Selection, range: &Range) -> Option { (!mask.mask().all_false()).then_some(mask) } -fn can_prune_file(ctx: &TaskContext) -> VortexResult { +/// Counts a file scan attempt and returns whether whole-file statistics reject the filter. +pub(crate) fn can_prune_file(ctx: &TaskContext) -> VortexResult { ctx.count::(ScanRecorder::attempt_file_scan); if let Some(filter) = &ctx.filter && can_prune_conjuncts(filter, ctx.reader.as_ref())? diff --git a/vortex-layout/src/scan/test.rs b/vortex-layout/src/scan/test.rs index 85c4b25d8b1..41c9ce19e1e 100644 --- a/vortex-layout/src/scan/test.rs +++ b/vortex-layout/src/scan/test.rs @@ -27,6 +27,7 @@ use vortex_io::runtime::single::SingleThreadRuntime; use vortex_io::session::RuntimeSession; use vortex_io::session::RuntimeSessionExt; use vortex_mask::Mask; +use vortex_scan::pool::ScanPoolRef; use vortex_session::VortexSession; use crate::ArrayFuture; @@ -70,6 +71,7 @@ pub struct TestLayoutReader { projection_masks: Option>>>, filter_exprs: Option>>>, in_flight: Option>, + yields: fn(u64) -> usize, } /// Counts projections running at once, and the most that ever were. @@ -101,6 +103,7 @@ impl TestLayoutReader { projection_masks: None, filter_exprs: None, in_flight: None, + yields: |_| 0, } } @@ -137,6 +140,13 @@ impl TestLayoutReader { self } + /// Makes the projection of the split starting at row `start` yield `yields(start)` times + /// before it finishes, so tests can make splits complete out of row order. + pub fn with_yields(mut self, yields: fn(u64) -> usize) -> Self { + self.yields = yields; + self + } + pub fn with_filter_exprs(mut self, filter_exprs: Arc>>) -> Self { self.filter_exprs = Some(filter_exprs); self @@ -261,8 +271,12 @@ impl LayoutReader for TestLayoutReader { let projection_masks = self.projection_masks.clone(); let fail = self.fail_projection || (self.fail_first_projection && row_range.start == 0); let in_flight = self.in_flight.clone(); + let yields = (self.yields)(row_range.start); Ok(Box::pin(async move { + for _ in 0..yields { + tokio::task::yield_now().await; + } if let Some(in_flight) = &in_flight { let now = in_flight.now.fetch_add(1, Ordering::SeqCst) + 1; in_flight.peak.fetch_max(now, Ordering::SeqCst); @@ -313,6 +327,28 @@ where Ok(values) } +/// Reads `pool` with `workers` workers, each polled on its own thread, returning each worker's +/// values in the order it yielded them. +pub fn read_with_workers(pool: &ScanPoolRef, workers: usize) -> VortexResult>> { + std::thread::scope(|scope| { + let handles = (0..workers) + .map(|_| { + let worker = Arc::clone(pool).worker(); + scope.spawn(move || collect_scan_values(futures::executor::block_on_stream(worker))) + }) + .collect::>(); + handles + .into_iter() + .map(|handle| handle.join().expect("worker thread panicked")) + .collect() + }) +} + +/// Reads `pool` with a single worker polled on the calling thread. +pub fn read_with_one_worker(pool: ScanPoolRef) -> VortexResult> { + collect_scan_values(futures::executor::block_on_stream(pool.worker())) +} + /// Let already-spawned scan tasks run to completion after the stream has been dropped. pub fn drain_runtime(runtime: &SingleThreadRuntime) { for _ in 0..4 { 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..2de077014a5 100644 --- a/vortex-scan/src/pool.rs +++ b/vortex-scan/src/pool.rs @@ -13,6 +13,7 @@ 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`]. @@ -33,17 +34,20 @@ pub trait ScanPool: 'static + Send + Sync { fn worker(self: Arc) -> SendableArrayStream; } -/// 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, } 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 { Self { - dtype, - partitions: Mutex::new(partitions), + dtype: scan.dtype().clone(), + partitions: Mutex::new(scan.partitions()), } } } From 540b8cc413063c68113656719b1c24c29cb8bcf7 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Thu, 19 Nov 2026 18:30:06 -0500 Subject: [PATCH 04/80] Spawn pool splits onto the session runtime Decoding a split inline kept each worker's splits on its own thread. Spawning them onto the session's runtime, as V1 scans do, lets idle runtime threads decode them and starts their I/O at once. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-layout/src/scan/pool.rs | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/vortex-layout/src/scan/pool.rs b/vortex-layout/src/scan/pool.rs index fcfea905b7a..c5f09310d45 100644 --- a/vortex-layout/src/scan/pool.rs +++ b/vortex-layout/src/scan/pool.rs @@ -4,9 +4,8 @@ //! The work that the workers of an opened layout scan share. //! //! A pool's units are the splits of one or more files, and the files not yet opened. A worker -//! takes units and keeps up to `splits_in_flight` of them running on its own thread: it -//! builds a split's task only when it takes the split, and never spawns. Opening a deferred file -//! is a unit like any other. +//! takes units and keeps up to `splits_in_flight` of them in flight, each spawned onto the +//! session's runtime when the worker takes it. Opening a deferred file is a unit like any other. //! //! - An unordered pool hands units out through a channel. The worker that opens a deferred file //! sends the file's splits back into the channel, where any worker can take them. The channel @@ -36,6 +35,7 @@ use vortex_array::stream::ArrayStreamAdapter; use vortex_array::stream::ArrayStreamExt; use vortex_array::stream::SendableArrayStream; use vortex_error::VortexResult; +use vortex_io::session::RuntimeSessionExt; use vortex_scan::DataSourceScanRef; use vortex_scan::Partition; use vortex_scan::PartitionRef; @@ -251,7 +251,7 @@ impl Shared { .boxed() } - /// Takes a split: reserves its rows from a reserved limit and builds its task. + /// Takes a split: reserves its rows from a reserved limit and spawns its task. fn admit(&self, (file, range, progress): FileSplit) -> SplitFuture { *self.progress.lock() += progress; let Some(mask) = file.scan.split_mask(&range) else { @@ -267,10 +267,12 @@ impl Shared { } PoolLimit::Unlimited | PoolLimit::Trim(_) => mask, }; - match file.scan.split_task(&file.ctx, mask) { - Ok(task) => task, - Err(err) => future::ready(Err(err)).boxed(), - } + // Spawned onto the session's runtime, as V1 scans do: another runtime thread may decode + // it while this worker drives its other splits, and its I/O starts right away. + let handle = file.ctx.session.handle(); + handle + .spawn(async move { file.scan.split_task(&file.ctx, mask)?.await }) + .boxed() } #[expect( From f9241d72c51e9deee597bcd36a988855274e4543 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Thu, 19 Nov 2026 16:03:47 -0500 Subject: [PATCH 05/80] Read DataFusion v2 scans through split and open Each DataSourceExec execution now opens its Vortex scan into a pool whose workers back the output partitions, or splits it into one piece per partition when order matters or work stealing is disabled, replacing the partition stream shared under a mutex. A fetch now bounds each of several output partitions rather than forcing one. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- Cargo.lock | 1 + vortex-datafusion/Cargo.toml | 1 + vortex-datafusion/src/v2/source.rs | 539 ++++++++++++++++------------- 3 files changed, 295 insertions(+), 246 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index ab273f5e43d..ee47754210f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -11733,6 +11733,7 @@ dependencies = [ "insta", "itertools 0.14.0", "object_store 0.13.2", + "parking_lot", "rstest", "tempfile", "tokio", diff --git a/vortex-datafusion/Cargo.toml b/vortex-datafusion/Cargo.toml index fa73a69b0e9..e4d046a523d 100644 --- a/vortex-datafusion/Cargo.toml +++ b/vortex-datafusion/Cargo.toml @@ -32,6 +32,7 @@ datafusion-pruning = { workspace = true } futures = { workspace = true } itertools = { workspace = true } object_store = { workspace = true } +parking_lot = { workspace = true } tokio = { workspace = true, features = ["rt-multi-thread", "fs"] } tokio-stream = { workspace = true } tracing = { workspace = true, features = ["std", "attributes"] } diff --git a/vortex-datafusion/src/v2/source.rs b/vortex-datafusion/src/v2/source.rs index cefefb0f696..a0fa069cea2 100644 --- a/vortex-datafusion/src/v2/source.rs +++ b/vortex-datafusion/src/v2/source.rs @@ -70,6 +70,7 @@ use std::any::Any; use std::fmt; use std::fmt::Formatter; +use std::num::NonZeroUsize; use std::pin::Pin; use std::sync::Arc; use std::sync::atomic::AtomicBool; @@ -113,10 +114,11 @@ use futures::Stream; use futures::StreamExt; use futures::TryStreamExt; use futures::future::try_join_all; -use futures::lock::Mutex; use futures::stream; -use futures::task::AtomicWaker; +use futures::stream::BoxStream; +use parking_lot::Mutex; use tokio::sync::OnceCell; +use vortex::array::ArrayRef; use vortex::dtype::DType; use vortex::dtype::FieldPath; use vortex::dtype::Nullability; @@ -132,8 +134,9 @@ use vortex::expr::stats::Precision; use vortex::expr::transform::replace; use vortex::io::session::RuntimeSessionExt; use vortex::scan::DataSourceRef; -use vortex::scan::PartitionStream; +use vortex::scan::DataSourceScanRef; use vortex::scan::ScanRequest; +use vortex::scan::pool::ScanPoolRef; use vortex::session::VortexSession; use vortex_arrow::ArrowSessionExt; use vortex_utils::parallelism::get_available_parallelism; @@ -146,9 +149,6 @@ use crate::convert::schema::calculate_physical_schema; use crate::convert::stats::stats_set_to_df; use crate::convert::to_record_batch; -// Bound active Scan API partition streams independently of the DataFusion output count. -const SCAN_PARTITION_READ_AHEAD: usize = 2; - /// Builder for [`VortexDataSource`]. /// /// Use the builder to declare how an existing Vortex @@ -350,6 +350,7 @@ impl VortexDataSourceBuilder { dynamic_filters: Vec::new(), limit: None, ordered: self.output_ordering.is_some(), + preserve_order: false, target_parallelism: get_available_parallelism().unwrap_or(1), }) } @@ -379,16 +380,24 @@ impl VortexDataSource { /// During execution, it builds the final Vortex [`ScanRequest`] from the /// current projection, pushed filters, ordering hints, and row limit. /// -/// Unordered scans expose the requested DataFusion output partitions, sharing one lazy scan -/// per execution through [`DataSource::create_sibling_state`]. Ordered and fetch-limited scans -/// use one output partition to preserve partition sequence and a global fetch limit. Direct -/// [`DataSource::open`] calls support only a single output partition; multiple output partitions -/// must be opened through [`DataSourceExec`] or shared [`OpenArgs`]. Dropping an output partition -/// before completion cancels its execution; other output partitions report an error. -/// Scan initialization attempts are serialized; cancellation may drop a pending attempt, -/// allowing another output partition to retry it. +/// Unordered scans expose the requested DataFusion output partitions, which share one lazy scan +/// per execution through [`DataSource::create_sibling_state`]. A scan with a declared global +/// ordering uses one output partition. /// -/// [`DataSourceExec`]: datafusion_datasource::source::DataSourceExec +/// The output partitions read the scan in one of two ways, chosen as DataFusion's own file scans +/// choose whether to steal work. By default the scan is [opened] into a pool and every output +/// partition polls its own worker, so partitions that finish early take work from the others. +/// When each partition must keep its rows in order, or when +/// `datafusion.execution.enable_file_stream_work_stealing` is off, the scan is instead [split] +/// into one piece per output partition, and partitions beyond the piece count return no rows. +/// A direct [`DataSource::open`] without shared [`OpenArgs`] always splits, since its partition +/// cannot share a pool with the others. +/// +/// As with DataFusion's work-stealing file scans, dropping an output partition before it ends +/// abandons the work it had taken, so a host drops one early only when it abandons the scan. +/// +/// [opened]: vortex::scan::DataSourceScan::open +/// [split]: vortex::scan::DataSourceScan::split /// /// Use [`crate::VortexSource`] instead when DataFusion should discover and plan /// `.vortex` files on its own. @@ -439,11 +448,13 @@ pub struct VortexDataSource { dynamic_filters: Vec>, /// An optional row limit populated by [`DataSource::with_fetch`]. limit: Option, - /// Whether to preserve the order of the output rows. + /// Whether to preserve a declared global order, which keeps one output partition. ordered: bool, + /// Whether each output partition must return its rows in order, as DataFusion requests + /// through [`DataSource::with_preserve_order`]. + preserve_order: bool, /// Target Arrow conversion concurrency when only one output partition is exposed. - /// Each unordered output partition opens at most two Scan API partitions concurrently. target_parallelism: usize, } @@ -460,27 +471,42 @@ impl fmt::Debug for VortexDataSource { impl VortexDataSource { fn output_partition_count(&self) -> usize { - if self.ordered || self.limit.is_some() { + if self.ordered { 1 } else { self.output_partitions } } + /// Whether output partition `i` reads its own piece of a split scan rather than taking work + /// from a pool shared by every output partition. + /// + /// This mirrors when DataFusion's `FileScanConfig` turns off work stealing: an order-sensitive + /// scan must keep each partition's rows in sequence, and a host that runs partitions in + /// isolation disables stealing through `enable_file_stream_work_stealing`. + fn splits(&self, config: &ConfigOptions) -> bool { + self.ordered || self.preserve_order || !config.execution.enable_file_stream_work_stealing + } + + fn scan_request(&self) -> ScanRequest { + ScanRequest { + projection: self.projected_projection.clone(), + filter: self.filter.clone(), + limit: self.limit.map(|l| u64::try_from(l).unwrap_or(u64::MAX)), + ordered: self.ordered || self.preserve_order, + ..Default::default() + } + } + fn open_partition( &self, partition: usize, execution: Arc, ) -> DFResult { - if execution.cancelled.load(Ordering::Acquire) { - return Err(DataFusionError::Execution( - "scan execution cancelled".into(), - )); - } - let output = execution.output_partitions.get(partition).ok_or_else(|| { + let claimed = execution.claimed.get(partition).ok_or_else(|| { DataFusionError::Execution(format!("invalid scan output partition {partition}")) })?; - if output.claimed.swap(true, Ordering::AcqRel) { + if claimed.swap(true, Ordering::AcqRel) { return Err(DataFusionError::Execution( "scan output partition already opened; reset the execution plan before replay" .into(), @@ -493,59 +519,45 @@ impl VortexDataSource { stream::empty(), )) as SendableRecordBatchStream } else { - let scan_request = ScanRequest { - projection: self.projected_projection.clone(), - filter: self.filter.clone(), - limit: self.limit.map(|l| u64::try_from(l).unwrap_or(u64::MAX)), - ordered: self.ordered, - ..Default::default() - }; let data_source = Arc::clone(&self.data_source); - let partitions = stream::try_unfold(Arc::clone(&execution), move |execution| { - let data_source = Arc::clone(&data_source); - let request = scan_request.clone(); - async move { - // Cancellation may retry initialization, but never runs attempts concurrently. - let partitions = execution - .scan_partitions - .get_or_init(|| async { - data_source - .scan(request) - .await - .map(|scan| Mutex::new(Some(scan.partitions()))) - }) - .await - .as_ref() - .map_err(Clone::clone)?; - let partition = { - let mut partitions = partitions.lock().await; - let next = match partitions.as_mut() { - Some(partitions) => partitions.try_next().await?, - None => None, - }; - if next.is_none() { - drop(partitions.take()); - } - next - }; - Ok(partition.map(|partition| (partition, execution))) - } + let request = self.scan_request(); + let arrays = stream::once(async move { + let work = execution + .work + .get_or_init(|| execution.start(data_source, request)) + .await + .as_ref() + .map_err(Clone::clone)?; + let worker = match work { + ScanWork::Pool(pool) => Some(Arc::clone(pool).worker()), + ScanWork::Pieces(pieces) => { + let piece = pieces.get(partition).and_then(|piece| piece.lock().take()); + piece + .map(|piece| piece.open()) + .transpose()? + .map(|pool| pool.worker()) + } + }; + // Output partitions beyond the scan's pieces have nothing to read. + VortexResult::Ok(match worker { + Some(worker) => worker.left_stream(), + None => stream::empty().right_stream(), + }) }) + .try_flatten() .boxed(); - self.batch_stream(partitions, partition, metrics.clone())? + self.batch_stream(arrays, partition, metrics.clone())? }; Ok(Box::pin(OutputPartitionStream { - partition, schema: Arc::clone(&self.leftover_schema), - stream: Some(stream), - execution, + stream, metrics, })) } fn batch_stream( &self, - scan_partitions: PartitionStream, + arrays: BoxStream<'static, VortexResult>, partition: usize, metrics: BaselineMetrics, ) -> DFResult { @@ -561,7 +573,6 @@ impl VortexDataSource { } else { 1 }; - let ordered = self.ordered; let limit = self.limit; // Pre-build the leftover projector (if any) so we can apply it after batch conversion. @@ -571,64 +582,45 @@ impl VortexDataSource { .map(|proj| proj.make_projector(&self.projected_schema)) .transpose()?; - // Defer the async DataSource::scan() call to the first poll of the stream. - let stream = stream::once(async move { - let scan_streams = scan_partitions.map(|split| split?.execute()); - - // When ordering is requested we must emit partition output in partition order, so we - // flatten the split streams sequentially. Otherwise we use try_flatten_unordered to - // poll multiple split streams concurrently so that the next split is already warm when - // the current one finishes. - let flattened = if ordered { - scan_streams.try_flatten().left_stream() - } else { - scan_streams - .try_flatten_unordered(Some(SCAN_PARTITION_READ_AHEAD)) - .right_stream() - }; - - let handle = session.handle(); - let stream = flattened - .map(move |result| { - let session = session.clone(); - let target_field = Arc::clone(&projected_target_field); - let metrics = metrics.intermediate(); - handle.spawn_cpu(move || { - let _timer = metrics.elapsed_compute().timer(); - to_record_batch(result?, &target_field, &session) - }) + let handle = session.handle(); + let stream = arrays + .map(move |result| { + let session = session.clone(); + let target_field = Arc::clone(&projected_target_field); + let metrics = metrics.intermediate(); + handle.spawn_cpu(move || { + let _timer = metrics.elapsed_compute().timer(); + to_record_batch(result?, &target_field, &session) }) - .buffered(conversion_concurrency) - .map(|result| result.map_err(|e| DataFusionError::External(Box::new(e)))); - - // DataFusion drops its own limit operator once `with_fetch` accepts the limit, so the - // fetch must be exact here. Unordered scans share the limit across partitions, but - // ordered partitions each apply it locally and rely on this trim. - let stream = match limit { - Some(limit) => LimitStream::new( - Box::pin(RecordBatchStreamAdapter::new(projected_schema, stream)), - 0, - Some(limit), - BaselineMetrics::new(&ExecutionPlanMetricsSet::new(), partition), - ) - .boxed(), - None => stream.boxed(), - }; - - // Apply leftover projection (expressions that couldn't be pushed into Vortex). - let stream = if let Some(projector) = leftover_projector { - stream - .map(move |batch_result| { - batch_result.and_then(|batch| projector.project_batch(&batch)) - }) - .boxed() - } else { - stream.boxed() - }; + }) + .buffered(conversion_concurrency) + .map(|result| result.map_err(|e| DataFusionError::External(Box::new(e)))); + + // With one output partition DataFusion drops its own limit operator once `with_fetch` + // accepts the limit, so the fetch must be exact here. With several, the fetch bounds each + // partition and DataFusion keeps a global limit above. An unordered scan shares its limit + // across partitions, but ordered pieces each apply it locally and rely on this trim. + let stream = match limit { + Some(limit) => LimitStream::new( + Box::pin(RecordBatchStreamAdapter::new(projected_schema, stream)), + 0, + Some(limit), + BaselineMetrics::new(&ExecutionPlanMetricsSet::new(), partition), + ) + .boxed(), + None => stream.boxed(), + }; - Ok::<_, DataFusionError>(stream) - }) - .try_flatten(); + // Apply leftover projection (expressions that couldn't be pushed into Vortex). + let stream = if let Some(projector) = leftover_projector { + stream + .map(move |batch_result| { + batch_result.and_then(|batch| projector.project_batch(&batch)) + }) + .boxed() + } else { + stream + }; Ok(Box::pin(RecordBatchStreamAdapter::new( Arc::clone(&self.leftover_schema), @@ -637,43 +629,57 @@ impl VortexDataSource { } } -#[derive(Default)] -struct OutputPartitionState { - claimed: AtomicBool, - waker: AtomicWaker, +/// The scan shared by every output partition of one execution of the exec. +/// +/// The first output partition polled starts the scan; every other partition reads the same one. +struct ScanExecution { + /// Whether to split the scan into one piece per output partition rather than open it into a + /// pool that every output partition takes work from. + split: bool, + claimed: Vec, + work: OnceCell>, } -struct ScanExecution { - output_partitions: Vec, - cancelled: AtomicBool, - scan_partitions: OnceCell>>>, +enum ScanWork { + /// Every output partition polls its own worker of this pool. + Pool(ScanPoolRef), + /// Output partition `i` takes piece `i`, if there is one. + Pieces(Vec>>), } impl ScanExecution { - fn new(output_partitions: usize) -> Self { + fn new(output_partitions: usize, split: bool) -> Self { Self { - output_partitions: (0..output_partitions) - .map(|_| OutputPartitionState::default()) + split, + claimed: (0..output_partitions) + .map(|_| AtomicBool::new(false)) .collect(), - cancelled: AtomicBool::new(false), - scan_partitions: OnceCell::new(), + work: OnceCell::new(), } } - fn cancel(&self) { - if !self.cancelled.swap(true, Ordering::AcqRel) { - for output in &self.output_partitions { - output.waker.wake(); - } + async fn start( + &self, + data_source: DataSourceRef, + request: ScanRequest, + ) -> VortexResult { + let scan = data_source.scan(request).await?; + if !self.split { + return Ok(ScanWork::Pool(scan.open()?)); } + let pieces = NonZeroUsize::new(self.claimed.len()).unwrap_or(NonZeroUsize::MIN); + Ok(ScanWork::Pieces( + scan.split(pieces)? + .into_iter() + .map(|piece| Mutex::new(Some(piece))) + .collect(), + )) } } struct OutputPartitionStream { - partition: usize, schema: SchemaRef, - stream: Option, - execution: Arc, + stream: SendableRecordBatchStream, metrics: BaselineMetrics, } @@ -683,34 +689,8 @@ impl Stream for OutputPartitionStream { fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { let metrics = self.metrics.clone(); let _timer = metrics.elapsed_compute().timer(); - self.execution.output_partitions[self.partition] - .waker - .register(cx.waker()); - let mut result = if self.execution.cancelled.load(Ordering::Acquire) { - Poll::Ready(None) - } else { - match self.stream.as_mut() { - Some(stream) => stream.as_mut().poll_next(cx), - None => Poll::Ready(None), - } - }; - if self.stream.is_some() && self.execution.cancelled.load(Ordering::Acquire) { - result = Poll::Ready(Some(Err(DataFusionError::Execution( - "scan execution cancelled".into(), - )))); - } - if matches!(result, Poll::Ready(Some(Err(_)))) { - self.execution.cancel(); - } - if matches!(result, Poll::Ready(None | Some(Err(_)))) { - self.stream = None; - drop( - self.execution.output_partitions[self.partition] - .waker - .take(), - ); - } - metrics.record_poll(result) + let poll = self.stream.as_mut().poll_next(cx); + metrics.record_poll(poll) } } @@ -722,21 +702,6 @@ impl RecordBatchStream for OutputPartitionStream { impl Drop for OutputPartitionStream { fn drop(&mut self) { - if self.stream.is_some() { - self.execution.cancel(); - } - drop(self.stream.take()); - drop( - self.execution.output_partitions[self.partition] - .waker - .take(), - ); - if self.execution.cancelled.load(Ordering::Acquire) - && let Some(Ok(partitions)) = self.execution.scan_partitions.get() - && let Some(mut partitions) = partitions.try_lock() - { - drop(partitions.take()); - } self.metrics.done(); } } @@ -747,16 +712,19 @@ impl DataSource for VortexDataSource { partition: usize, _context: Arc, ) -> DFResult { - if self.output_partition_count() != 1 { - return Err(DataFusionError::Execution( - "multiple scan output partitions require sibling execution state".into(), - )); - } - self.open_partition(partition, Arc::new(ScanExecution::new(1))) + // Without sibling state this partition cannot share a pool with the others, so it scans + // on its own and reads only its piece. + self.open_partition( + partition, + Arc::new(ScanExecution::new(self.output_partition_count(), true)), + ) } - fn create_sibling_state(&self, _config: &ConfigOptions) -> Option> { - Some(Arc::new(ScanExecution::new(self.output_partition_count()))) + fn create_sibling_state(&self, config: &ConfigOptions) -> Option> { + Some(Arc::new(ScanExecution::new( + self.output_partition_count(), + self.splits(config), + ))) } fn open_with_args(&self, args: OpenArgs) -> DFResult { @@ -838,15 +806,18 @@ impl DataSource for VortexDataSource { } else { statistics }; - // Fetch is accepted only for one output partition, so it applies globally. - Ok(Arc::new(statistics.with_fetch(self.limit, 0, 1)?)) + // The fetch bounds each output partition. + Ok(Arc::new(statistics.with_fetch( + self.limit, + 0, + self.output_partition_count(), + )?)) } fn with_fetch(&self, limit: Option) -> Option> { - // DataSourceExec retains its partition properties when accepting fetch. - if limit.is_some() - && (self.output_partition_count() > 1 || !self.dynamic_filters.is_empty()) - { + // DataSourceExec retains its partition properties when accepting fetch, so the fetch + // bounds each output partition and DataFusion keeps a global limit above several. + if limit.is_some() && !self.dynamic_filters.is_empty() { return None; } let mut this = self.clone(); @@ -859,6 +830,12 @@ impl DataSource for VortexDataSource { self.limit } + fn with_preserve_order(&self, preserve_order: bool) -> Option> { + let mut this = self.clone(); + this.preserve_order = preserve_order; + Some(Arc::new(this)) + } + // Note that we're explicitly "swapping" the projection. That means everything we do must // be computed over the original input schema, rather than the projected output schema. fn try_swapping_with_projection( @@ -1047,8 +1024,6 @@ mod tests { use datafusion_physical_plan::expressions::BinaryExpr; use datafusion_physical_plan::expressions::lit; use futures::TryStreamExt; - use futures::task::ArcWake; - use futures::task::waker_ref; use rstest::rstest; use vortex::VortexSessionDefault; use vortex::array::IntoArray; @@ -1081,15 +1056,6 @@ mod tests { use super::*; use crate::v2::VortexTable; - #[derive(Default)] - struct WakeCounter(AtomicUsize); - - impl ArcWake for WakeCounter { - fn wake_by_ref(arc_self: &Arc) { - arc_self.0.fetch_add(1, Ordering::Relaxed); - } - } - /// The source enforces a pushed-down `LIMIT` itself: DataFusion removes its limit operator /// once the fetch is accepted, so a filtered scan over several partitions must still return /// exactly `LIMIT` rows. @@ -1356,8 +1322,10 @@ mod tests { source.partition_statistics(Some(0))?.num_rows, DFPrecision::Absent ); - assert!(source.with_fetch(Some(1)).is_none()); - assert!(source.open(0, Arc::new(TaskContext::default())).is_err()); + let fetched = source + .with_fetch(Some(1)) + .expect("fetch bounds each partition"); + assert_eq!(fetched.output_partitioning().partition_count(), 4); let plan = Arc::new(DataSourceExec::new(Arc::clone(&source))) as Arc; assert_eq!(scans.load(Ordering::Relaxed), 0); let context = Arc::new(TaskContext::default()); @@ -1384,7 +1352,8 @@ mod tests { assert_eq!(plan.metrics().expect("scan metrics").output_rows(), Some(4)); assert!(plan.execute(0, Arc::clone(&context)).is_err()); let reset = Arc::clone(&plan).reset_state()?; - let independent = Arc::new(DataSourceExec::new(source)) as Arc; + let independent = + Arc::new(DataSourceExec::new(Arc::clone(&source))) as Arc; let (reset, independent) = futures::try_join!( collect(reset, Arc::clone(&context)), collect(independent, context) @@ -1392,39 +1361,117 @@ mod tests { assert_eq!(values(reset), [0, 1, 100, 101]); assert_eq!(values(independent), [0, 1, 100, 101]); assert_eq!(scans.load(Ordering::Relaxed), 3); - let cancelled = Arc::clone(&plan).reset_state()?; - let mut output = cancelled.execute(0, Arc::new(TaskContext::default()))?; - assert!(output.try_next().await?.is_some()); - drop(output); - assert!( - cancelled - .execute(1, Arc::new(TaskContext::default())) - .is_err() + + // Without sibling state a partition scans on its own and reads only its piece. + let direct = |partition| source.open(partition, Arc::new(TaskContext::default())); + assert_eq!(values(direct(0)?.try_collect().await?), [0, 1, 100, 101]); + assert!(values(direct(1)?.try_collect().await?).is_empty()); + Ok(()) + } + + /// A file of 12 rows in splits of 3, scanned through the v2 table. + async fn split_file_source() -> VortexResult<(DataSourceRef, VortexSession, SchemaRef)> { + let session = VortexSession::default(); + let array = StructArray::from_fields(&[( + "a", + buffer![0i32, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11].into_array(), + )])? + .into_array(); + let mut buf = ByteBufferMut::empty(); + session + .write_options() + .write(&mut buf, array.to_array_stream()) + .await?; + let file = session.open_options().open_buffer(buf)?; + let data_source: DataSourceRef = Arc::new( + LayoutReaderDataSource::new(file.layout_reader()?, session.clone()) + .with_split_max_row_count(3), ); + let schema = Arc::new(session.arrow().to_arrow_schema(file.dtype())?); + Ok((data_source, session, schema)) + } - let execution = Arc::new(ScanExecution::new(2)); - let output = |partition| OutputPartitionStream { - partition, - schema: plan.schema(), - stream: Some(Box::pin(RecordBatchStreamAdapter::new( - plan.schema(), - stream::pending(), - ))), - execution: Arc::clone(&execution), - metrics: BaselineMetrics::new(&ExecutionPlanMetricsSet::new(), partition), - }; - let cancelled = output(0); - let mut pending = Box::pin(output(1)); - let wakes = Arc::new(WakeCounter::default()); - let waker = waker_ref(&wakes); - let mut cx = Context::from_waker(&waker); - assert!(pending.as_mut().poll_next(&mut cx).is_pending()); - drop(cancelled); - assert_eq!(wakes.0.load(Ordering::Relaxed), 1); - assert!(matches!( - pending.as_mut().poll_next(&mut cx), - Poll::Ready(Some(Err(_))) - )); + fn partition_values(batches: &[RecordBatch]) -> Vec { + batches + .iter() + .flat_map(|batch| { + batch + .column(0) + .as_primitive::() + .values() + .iter() + .copied() + }) + .collect() + } + + /// With work stealing off, each output partition reads one contiguous piece in order, and + /// partitions beyond the piece count return no rows. + #[tokio::test] + async fn without_work_stealing_partitions_read_split_pieces() -> anyhow::Result<()> { + let (data_source, session, schema) = split_file_source().await?; + let source = VortexDataSource::builder(data_source, session) + .with_arrow_schema(schema) + .build() + .await? + .repartitioned(8, 0, None)? + .expect("repartitioning supported"); + let plan = Arc::new(DataSourceExec::new(source)) as Arc; + let mut config = datafusion::prelude::SessionConfig::new(); + config + .options_mut() + .execution + .enable_file_stream_work_stealing = false; + let context = Arc::new(TaskContext::default().with_session_config(config)); + + let mut partitions = Vec::new(); + for partition in 0..8 { + let batches: Vec = plan + .execute(partition, Arc::clone(&context))? + .try_collect() + .await?; + partitions.push(partition_values(&batches)); + } + let pieces: Vec<_> = partitions.iter().filter(|p| !p.is_empty()).collect(); + assert!(pieces.len() > 1, "expected several pieces: {partitions:?}"); + assert!(partitions[pieces.len()..].iter().all(Vec::is_empty)); + assert_eq!( + pieces.into_iter().flatten().copied().collect::>(), + (0..12).collect::>() + ); + Ok(()) + } + + /// A fetch bounds each of several output partitions, and the pooled scan shares its limit. + #[tokio::test] + async fn fetch_bounds_each_of_several_partitions() -> anyhow::Result<()> { + let (data_source, session, schema) = split_file_source().await?; + let source = VortexDataSource::builder(data_source, session) + .with_arrow_schema(schema) + .build() + .await? + .repartitioned(4, 0, None)? + .expect("repartitioning supported") + .with_fetch(Some(5)) + .expect("fetch supported"); + let plan = Arc::new(DataSourceExec::new(source)) as Arc; + assert_eq!(plan.properties().partitioning.partition_count(), 4); + let context = Arc::new(TaskContext::default()); + + let partitions = try_join_all((0..4).map(|partition| { + let stream = plan.execute(partition, Arc::clone(&context)); + async move { + let batches: Vec = stream?.try_collect().await?; + Ok::<_, DataFusionError>(partition_values(&batches)) + } + })) + .await?; + assert!(partitions.iter().all(|values| values.len() <= 5)); + let mut values = partitions.concat(); + assert!(values.len() >= 5, "{partitions:?}"); + values.sort_unstable(); + values.dedup(); + assert_eq!(values.len(), partitions.iter().map(Vec::len).sum::()); Ok(()) } From d1359915a3c8bd82bdd1d9fbda5b99b2037a1e01 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Thu, 19 Nov 2026 16:05:54 -0500 Subject: [PATCH 06/80] Split the v2 test scan into one piece per partition The layout file in the split-mode test had a single layout split, so splitting it returned one piece. The test scan now splits natively. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-datafusion/src/v2/source.rs | 63 ++++++++++++++++++++---------- 1 file changed, 43 insertions(+), 20 deletions(-) diff --git a/vortex-datafusion/src/v2/source.rs b/vortex-datafusion/src/v2/source.rs index a0fa069cea2..c320bee1209 100644 --- a/vortex-datafusion/src/v2/source.rs +++ b/vortex-datafusion/src/v2/source.rs @@ -1176,10 +1176,15 @@ mod tests { } } + /// The values of each test partition. + const TEST_PARTITIONS: [&[i32]; 2] = [&[0, 1], &[100, 101]]; + + /// A scan of some of [`TEST_PARTITIONS`], which splits into one piece per partition. struct TestScan { dtype: DType, limit: Option, polls: Arc, + partitions: Vec, } impl DataSourceScan for TestScan { @@ -1188,17 +1193,36 @@ mod tests { } fn partition_count(&self) -> Precision { - Precision::Exact(2) + Precision::Exact(self.partitions.len()) + } + + fn split(self: Box, n: NonZeroUsize) -> VortexResult> { + if n.get() < self.partitions.len() { + return Ok(vec![self]); + } + Ok(self + .partitions + .iter() + .map(|&partition| { + Box::new(TestScan { + dtype: self.dtype.clone(), + limit: self.limit, + polls: Arc::clone(&self.polls), + partitions: vec![partition], + }) as DataSourceScanRef + }) + .collect()) } fn partitions(self: Box) -> PartitionStream { let limit = self .limit .map(|limit| usize::try_from(limit).unwrap_or(usize::MAX)); - let partitions: Vec> = [&[0, 1][..], &[100, 101][..]] - .into_iter() - .enumerate() - .map(|(index, values)| { + let partitions: Vec> = self + .partitions + .iter() + .map(|&index| { + let values = TEST_PARTITIONS[index]; // Ordered partitions enforce their own limit; the adapter must enforce the // global limit when it concatenates their outputs. let values = &values[..limit.unwrap_or(values.len()).min(values.len())]; @@ -1231,6 +1255,7 @@ mod tests { dtype: self.dtype.clone(), limit: request.limit, polls: Arc::clone(&self.polls), + partitions: vec![0, 1], })) } @@ -1364,8 +1389,9 @@ mod tests { // Without sibling state a partition scans on its own and reads only its piece. let direct = |partition| source.open(partition, Arc::new(TaskContext::default())); - assert_eq!(values(direct(0)?.try_collect().await?), [0, 1, 100, 101]); - assert!(values(direct(1)?.try_collect().await?).is_empty()); + assert_eq!(values(direct(0)?.try_collect().await?), [0, 1]); + assert_eq!(values(direct(1)?.try_collect().await?), [100, 101]); + assert!(values(direct(2)?.try_collect().await?).is_empty()); Ok(()) } @@ -1405,16 +1431,19 @@ mod tests { .collect() } - /// With work stealing off, each output partition reads one contiguous piece in order, and + /// With work stealing off, each output partition reads its own piece in order, and /// partitions beyond the piece count return no rows. #[tokio::test] async fn without_work_stealing_partitions_read_split_pieces() -> anyhow::Result<()> { - let (data_source, session, schema) = split_file_source().await?; - let source = VortexDataSource::builder(data_source, session) - .with_arrow_schema(schema) + let data_source: DataSourceRef = Arc::new(TestDataSource { + dtype: test_dtype(), + polls: Arc::default(), + scans: Arc::default(), + }); + let source = VortexDataSource::builder(data_source, VortexSession::default()) .build() .await? - .repartitioned(8, 0, None)? + .repartitioned(4, 0, None)? .expect("repartitioning supported"); let plan = Arc::new(DataSourceExec::new(source)) as Arc; let mut config = datafusion::prelude::SessionConfig::new(); @@ -1425,20 +1454,14 @@ mod tests { let context = Arc::new(TaskContext::default().with_session_config(config)); let mut partitions = Vec::new(); - for partition in 0..8 { + for partition in 0..4 { let batches: Vec = plan .execute(partition, Arc::clone(&context))? .try_collect() .await?; partitions.push(partition_values(&batches)); } - let pieces: Vec<_> = partitions.iter().filter(|p| !p.is_empty()).collect(); - assert!(pieces.len() > 1, "expected several pieces: {partitions:?}"); - assert!(partitions[pieces.len()..].iter().all(Vec::is_empty)); - assert_eq!( - pieces.into_iter().flatten().copied().collect::>(), - (0..12).collect::>() - ); + assert_eq!(partitions, [vec![0, 1], vec![100, 101], vec![], vec![]]); Ok(()) } From be5ce7aec91ebad13cb3841002785ebd819a89c0 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Thu, 19 Nov 2026 18:37:19 -0500 Subject: [PATCH 07/80] Convert scan workers to Arrow through vortex-arrow Adds ArrowArrayStreamExt::to_arrow, which converts each array of a stream to a RecordBatch as a CPU task on the session's runtime with bounded, order-preserving concurrency. The v2 DataFusion source now calls it on each worker instead of spawning conversions itself. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- Cargo.lock | 1 + vortex-arrow/Cargo.toml | 1 + vortex-arrow/src/lib.rs | 2 + vortex-arrow/src/stream.rs | 116 +++++++++++++++++++++++++++++ vortex-datafusion/src/v2/source.rs | 57 ++++++-------- 5 files changed, 143 insertions(+), 34 deletions(-) create mode 100644 vortex-arrow/src/stream.rs diff --git a/Cargo.lock b/Cargo.lock index ee47754210f..09694b71a38 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -11381,6 +11381,7 @@ dependencies = [ "vortex-decimal-byte-parts", "vortex-error", "vortex-fsst", + "vortex-io", "vortex-mask", "vortex-onpair", "vortex-scan", diff --git a/vortex-arrow/Cargo.toml b/vortex-arrow/Cargo.toml index c5abfd50fce..e14053ceba4 100644 --- a/vortex-arrow/Cargo.toml +++ b/vortex-arrow/Cargo.toml @@ -40,6 +40,7 @@ tracing = { workspace = true } vortex-array = { workspace = true } vortex-buffer = { workspace = true, features = ["arrow"] } vortex-error = { workspace = true } +vortex-io = { workspace = true } vortex-mask = { workspace = true } vortex-scan = { workspace = true } vortex-session = { workspace = true } diff --git a/vortex-arrow/src/lib.rs b/vortex-arrow/src/lib.rs index dea929599ff..8970cc6c1fa 100644 --- a/vortex-arrow/src/lib.rs +++ b/vortex-arrow/src/lib.rs @@ -39,6 +39,7 @@ mod run_end_import; mod scalar; mod scan; mod session; +mod stream; #[cfg(feature = "_test-harness")] pub mod test_harness; #[cfg(test)] @@ -55,3 +56,4 @@ pub use options::*; pub use scalar::ToArrowDatum; pub use scan::ArrowScanExt; pub use session::*; +pub use stream::ArrowArrayStreamExt; diff --git a/vortex-arrow/src/stream.rs b/vortex-arrow/src/stream.rs new file mode 100644 index 00000000000..cfdca8fd618 --- /dev/null +++ b/vortex-arrow/src/stream.rs @@ -0,0 +1,116 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Arrow output for array streams. + +use std::future; +use std::num::NonZeroUsize; +use std::sync::Arc; + +use arrow_array::RecordBatch; +use arrow_array::cast::AsArray; +use arrow_schema::Field; +use arrow_schema::SchemaRef; +use futures::StreamExt; +use futures::stream; +use futures::stream::BoxStream; +use vortex_array::VortexSessionExecute; +use vortex_array::stream::ArrayStream; +use vortex_error::VortexResult; +use vortex_io::session::RuntimeSessionExt; +use vortex_session::VortexSession; + +use crate::ArrowSessionExt; +use crate::ExecuteArrowExt; + +/// Arrow record-batch output for an [`ArrayStream`], such as a scan worker. +pub trait ArrowArrayStreamExt: ArrayStream + Send + Sized + 'static { + /// Converts each array of the stream to an Arrow [`RecordBatch`] with `schema`. + /// + /// Each conversion runs as a CPU task on the session's runtime, with at most `concurrency` + /// in flight, and the batches keep the stream's order. When `schema` is `None`, the session + /// derives it from the stream's dtype. + fn to_arrow( + self, + session: &VortexSession, + schema: Option, + concurrency: NonZeroUsize, + ) -> BoxStream<'static, VortexResult> { + let schema = match schema { + Some(schema) => schema, + None => match session.arrow().to_arrow_schema(self.dtype()) { + Ok(schema) => Arc::new(schema), + Err(error) => return stream::once(future::ready(Err(error))).boxed(), + }, + }; + let field = Arc::new(Field::new_struct("", schema.fields().clone(), false)); + let session = session.clone(); + let handle = session.handle(); + self.map(move |array| { + let session = session.clone(); + let field = Arc::clone(&field); + handle.spawn_cpu(move || { + let arrow = + array?.execute_arrow(Some(&field), &mut session.create_execution_ctx())?; + Ok(RecordBatch::from(arrow.as_struct().clone())) + }) + }) + .buffered(concurrency.get()) + .boxed() + } +} + +impl ArrowArrayStreamExt for S {} + +#[cfg(test)] +mod tests { + use std::num::NonZeroUsize; + + use arrow_array::cast::AsArray; + use arrow_array::types::Int32Type; + use futures::TryStreamExt; + use futures::stream; + use vortex_array::IntoArray; + use vortex_array::arrays::StructArray; + use vortex_array::stream::ArrayStreamAdapter; + use vortex_buffer::buffer; + use vortex_error::VortexResult; + use vortex_io::runtime::single::block_on; + use vortex_io::session::RuntimeSessionExt; + use vortex_session::VortexSession; + + use super::ArrowArrayStreamExt; + + #[test] + fn converts_each_array_in_order() -> VortexResult<()> { + let arrays = [buffer![0i32, 1], buffer![2i32], buffer![3i32, 4, 5]] + .into_iter() + .map(|values| { + StructArray::from_fields(&[("a", values.into_array())]).map(IntoArray::into_array) + }) + .collect::>>()?; + let dtype = arrays[0].dtype().clone(); + let batches: Vec<_> = block_on(|handle| { + let session = VortexSession::empty().with_handle(handle); + ArrayStreamAdapter::new(dtype, stream::iter(arrays.into_iter().map(Ok))) + .to_arrow( + &session, + None, + NonZeroUsize::new(2).unwrap_or(NonZeroUsize::MIN), + ) + .try_collect() + })?; + let values: Vec = batches + .iter() + .flat_map(|batch| { + batch + .column(0) + .as_primitive::() + .values() + .to_vec() + }) + .collect(); + assert_eq!(values, [0, 1, 2, 3, 4, 5]); + Ok(()) + } +} diff --git a/vortex-datafusion/src/v2/source.rs b/vortex-datafusion/src/v2/source.rs index c320bee1209..342c958ead0 100644 --- a/vortex-datafusion/src/v2/source.rs +++ b/vortex-datafusion/src/v2/source.rs @@ -78,7 +78,6 @@ use std::sync::atomic::Ordering; use std::task::Context; use std::task::Poll; -use arrow_schema::Field; use arrow_schema::Schema; use arrow_schema::SchemaRef; use datafusion_common::ColumnStatistics; @@ -118,7 +117,6 @@ use futures::stream; use futures::stream::BoxStream; use parking_lot::Mutex; use tokio::sync::OnceCell; -use vortex::array::ArrayRef; use vortex::dtype::DType; use vortex::dtype::FieldPath; use vortex::dtype::Nullability; @@ -132,12 +130,12 @@ use vortex::expr::pack; use vortex::expr::root; use vortex::expr::stats::Precision; use vortex::expr::transform::replace; -use vortex::io::session::RuntimeSessionExt; use vortex::scan::DataSourceRef; use vortex::scan::DataSourceScanRef; use vortex::scan::ScanRequest; use vortex::scan::pool::ScanPoolRef; use vortex::session::VortexSession; +use vortex_arrow::ArrowArrayStreamExt; use vortex_arrow::ArrowSessionExt; use vortex_utils::parallelism::get_available_parallelism; @@ -147,7 +145,6 @@ use crate::convert::exprs::ExpressionConverter; use crate::convert::exprs::ProcessedProjection; use crate::convert::schema::calculate_physical_schema; use crate::convert::stats::stats_set_to_df; -use crate::convert::to_record_batch; /// Builder for [`VortexDataSource`]. /// @@ -521,7 +518,10 @@ impl VortexDataSource { } else { let data_source = Arc::clone(&self.data_source); let request = self.scan_request(); - let arrays = stream::once(async move { + let session = self.session.clone(); + let schema = Arc::clone(&self.projected_schema); + let concurrency = self.conversion_concurrency(); + let batches = stream::once(async move { let work = execution .work .get_or_init(|| execution.start(data_source, request)) @@ -540,13 +540,13 @@ impl VortexDataSource { }; // Output partitions beyond the scan's pieces have nothing to read. VortexResult::Ok(match worker { - Some(worker) => worker.left_stream(), - None => stream::empty().right_stream(), + Some(worker) => worker.to_arrow(&session, Some(schema), concurrency), + None => stream::empty().boxed(), }) }) .try_flatten() .boxed(); - self.batch_stream(arrays, partition, metrics.clone())? + self.batch_stream(batches, partition)? }; Ok(Box::pin(OutputPartitionStream { schema: Arc::clone(&self.leftover_schema), @@ -555,24 +555,23 @@ impl VortexDataSource { })) } + /// How many arrays each output partition converts to Arrow at once: one when several + /// partitions already convert in parallel, or the target parallelism for a single one. + fn conversion_concurrency(&self) -> NonZeroUsize { + let concurrency = if self.output_partition_count() == 1 { + self.target_parallelism + } else { + 1 + }; + NonZeroUsize::new(concurrency).unwrap_or(NonZeroUsize::MIN) + } + fn batch_stream( &self, - arrays: BoxStream<'static, VortexResult>, + batches: BoxStream<'static, VortexResult>, partition: usize, - metrics: BaselineMetrics, ) -> DFResult { let projected_schema = Arc::clone(&self.projected_schema); - let projected_target_field = Arc::new(Field::new_struct( - "", - projected_schema.fields().clone(), - false, - )); - let session = self.session.clone(); - let conversion_concurrency = if self.output_partition_count() == 1 { - self.target_parallelism - } else { - 1 - }; let limit = self.limit; // Pre-build the leftover projector (if any) so we can apply it after batch conversion. @@ -582,19 +581,8 @@ impl VortexDataSource { .map(|proj| proj.make_projector(&self.projected_schema)) .transpose()?; - let handle = session.handle(); - let stream = arrays - .map(move |result| { - let session = session.clone(); - let target_field = Arc::clone(&projected_target_field); - let metrics = metrics.intermediate(); - handle.spawn_cpu(move || { - let _timer = metrics.elapsed_compute().timer(); - to_record_batch(result?, &target_field, &session) - }) - }) - .buffered(conversion_concurrency) - .map(|result| result.map_err(|e| DataFusionError::External(Box::new(e)))); + let stream = + batches.map(|result| result.map_err(|e| DataFusionError::External(Box::new(e)))); // With one output partition DataFusion drops its own limit operator once `with_fetch` // accepts the limit, so the fetch must be exact here. With several, the fetch bounds each @@ -1014,6 +1002,7 @@ mod tests { use arrow_array::cast::AsArray; use arrow_array::types::Int32Type; use arrow_schema::DataType; + use arrow_schema::Field; use async_trait::async_trait; use datafusion::prelude::SessionContext; use datafusion_datasource::source::DataSourceExec; From d2b06172bf1e3076caf4ab3b4d82a9f65eb0e9b1 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Thu, 19 Nov 2026 12:30:11 -0500 Subject: [PATCH 08/80] Add a datafusion-bench flag for the Scan API table path Benchmarking VortexTable needed both --scan-v1 true and VORTEX_USE_SCAN_API=1, so it could not be compared with the listing table's V2 scan in one run. --scan-api true registers Vortex tables through the Scan API whatever --scan-v1 says; the environment variable keeps working. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- benchmarks/datafusion-bench/src/main.rs | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/benchmarks/datafusion-bench/src/main.rs b/benchmarks/datafusion-bench/src/main.rs index e2acd536fdc..e7d4ae6af55 100644 --- a/benchmarks/datafusion-bench/src/main.rs +++ b/benchmarks/datafusion-bench/src/main.rs @@ -124,6 +124,12 @@ struct Args { #[arg(long, default_value_t = true, action = clap::ArgAction::Set)] scan_v1: bool, + /// Register Vortex tables through the Scan API (`VortexTable` over a `MultiFileDataSource`) + /// instead of a listing table, whatever `--scan-v1` says. `VORTEX_USE_SCAN_API=1` does the same + /// when `--scan-v1` is true. + #[arg(long, default_value_t = false, action = clap::ArgAction::Set)] + scan_api: bool, + #[arg(long = "opt", value_delimiter = ',', value_parser = value_parser!(Opt))] options: Vec, } @@ -137,6 +143,7 @@ async fn main() -> anyhow::Result<()> { let args = Args::parse(); let opts = Opts::from(args.options); let scan_v2 = !args.scan_v1; + let scan_api = args.scan_api || (args.scan_v1 && use_scan_api()); set_join_set_tracer(get_static_tracer())?; setup_logging_and_tracing(args.verbose, args.tracing)?; @@ -196,7 +203,8 @@ async fn main() -> anyhow::Result<()> { session.sql(&sql).await?.collect().await?; } datafusion_bench::make_object_store(&session, benchmark.data_url())?; - register_benchmark_tables(&session, benchmark, format, scan_v2).await?; + register_benchmark_tables(&session, benchmark, format, scan_v2, scan_api) + .await?; Ok((session, format)) } }, @@ -261,9 +269,9 @@ async fn register_benchmark_tables( benchmark: &B, format: Format, scan_v2: bool, + scan_api: bool, ) -> anyhow::Result<()> { - if !scan_v2 && use_scan_api() && matches!(format, Format::OnDiskVortex | Format::VortexCompact) - { + if scan_api && matches!(format, Format::OnDiskVortex | Format::VortexCompact) { register_v2_tables(session, benchmark, format).await } else { let benchmark_base = benchmark.data_url().join(&format!("{}/", format.name()))?; @@ -300,7 +308,7 @@ async fn register_benchmark_tables( } } -/// Register tables using the V2 `VortexTable` + `MultiFileDataSource` path. +/// Register tables using the Scan API path: a `VortexTable` over a `MultiFileDataSource`. async fn register_v2_tables( session: &SessionContext, benchmark: &B, From 17033023590f367e00b9a9032058ea9a5eb10fef Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Thu, 19 Nov 2026 18:55:54 -0500 Subject: [PATCH 09/80] 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 2d3e3e7f46e4e7869ad01e49785a3b5b968d56a9 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Thu, 19 Nov 2026 19:07:56 -0500 Subject: [PATCH 10/80] Keep the shared partition stream behind VORTEX_SCAN_POOL=0 The v2 DataFusion source keeps develop's execution, output partitions sharing the scan's partition stream with its single-partition fetch, selectable at runtime so one binary can compare it with split and open. VORTEX_SCAN_POOL defaults to split and open; the partition stream goes away with the partition API. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-datafusion/src/v2/mod.rs | 1 + vortex-datafusion/src/v2/source.rs | 172 ++++++++++++++++++++++++++--- 2 files changed, 159 insertions(+), 14 deletions(-) diff --git a/vortex-datafusion/src/v2/mod.rs b/vortex-datafusion/src/v2/mod.rs index 7f16da3ed84..3d1822f7d0d 100644 --- a/vortex-datafusion/src/v2/mod.rs +++ b/vortex-datafusion/src/v2/mod.rs @@ -40,5 +40,6 @@ mod table; #[cfg(test)] mod tests; +pub use source::SCAN_POOL_ENV; pub use source::VortexDataSource; pub use table::VortexTable; diff --git a/vortex-datafusion/src/v2/source.rs b/vortex-datafusion/src/v2/source.rs index 342c958ead0..91783177691 100644 --- a/vortex-datafusion/src/v2/source.rs +++ b/vortex-datafusion/src/v2/source.rs @@ -113,10 +113,14 @@ use futures::Stream; use futures::StreamExt; use futures::TryStreamExt; use futures::future::try_join_all; +use futures::lock::Mutex as AsyncMutex; use futures::stream; use futures::stream::BoxStream; use parking_lot::Mutex; use tokio::sync::OnceCell; +use vortex::array::stream::ArrayStreamAdapter; +use vortex::array::stream::ArrayStreamExt; +use vortex::array::stream::SendableArrayStream; use vortex::dtype::DType; use vortex::dtype::FieldPath; use vortex::dtype::Nullability; @@ -132,6 +136,8 @@ use vortex::expr::stats::Precision; use vortex::expr::transform::replace; use vortex::scan::DataSourceRef; use vortex::scan::DataSourceScanRef; +use vortex::scan::PartitionRef; +use vortex::scan::PartitionStream; use vortex::scan::ScanRequest; use vortex::scan::pool::ScanPoolRef; use vortex::session::VortexSession; @@ -193,6 +199,17 @@ pub struct VortexDataSourceBuilder { projection: Option>, expression_converter: Arc, output_ordering: Option, + scan_pool: bool, +} + +/// The environment variable that selects how [`VortexDataSource`] reads its scan: `0` keeps the +/// shared partition stream, anything else (the default) splits or opens the scan. +/// +/// It exists to compare the two in one binary, and goes away with the partition stream. +pub const SCAN_POOL_ENV: &str = "VORTEX_SCAN_POOL"; + +fn scan_pool_from_env() -> bool { + std::env::var(SCAN_POOL_ENV).map_or(true, |value| value != "0") } impl VortexDataSourceBuilder { @@ -250,6 +267,13 @@ impl VortexDataSourceBuilder { self } + /// Selects whether the scan is split or opened (`true`) or read through its shared partition + /// stream (`false`). Defaults to [`SCAN_POOL_ENV`], read when the builder is created. + pub fn with_scan_pool(mut self, scan_pool: bool) -> Self { + self.scan_pool = scan_pool; + self + } + /// Builds the [`VortexDataSource`]. /// /// The builder eagerly resolves statistics for the initial projection @@ -349,6 +373,7 @@ impl VortexDataSourceBuilder { ordered: self.output_ordering.is_some(), preserve_order: false, target_parallelism: get_available_parallelism().unwrap_or(1), + scan_pool: self.scan_pool, }) } } @@ -363,6 +388,7 @@ impl VortexDataSource { arrow_schema: None, projection: None, output_ordering: None, + scan_pool: scan_pool_from_env(), } } } @@ -453,6 +479,9 @@ pub struct VortexDataSource { /// Target Arrow conversion concurrency when only one output partition is exposed. target_parallelism: usize, + /// Whether to split or open the scan rather than read its shared partition stream, which + /// keeps one output partition for a limited scan. + scan_pool: bool, } impl fmt::Debug for VortexDataSource { @@ -468,7 +497,7 @@ impl fmt::Debug for VortexDataSource { impl VortexDataSource { fn output_partition_count(&self) -> usize { - if self.ordered { + if self.ordered || (!self.scan_pool && self.limit.is_some()) { 1 } else { self.output_partitions @@ -481,8 +510,17 @@ impl VortexDataSource { /// This mirrors when DataFusion's `FileScanConfig` turns off work stealing: an order-sensitive /// scan must keep each partition's rows in sequence, and a host that runs partitions in /// isolation disables stealing through `enable_file_stream_work_stealing`. - fn splits(&self, config: &ConfigOptions) -> bool { - self.ordered || self.preserve_order || !config.execution.enable_file_stream_work_stealing + fn scan_mode(&self, config: &ConfigOptions) -> ScanMode { + if !self.scan_pool { + ScanMode::Partitions + } else if self.ordered + || self.preserve_order + || !config.execution.enable_file_stream_work_stealing + { + ScanMode::Split + } else { + ScanMode::Open + } } fn scan_request(&self) -> ScanRequest { @@ -521,6 +559,7 @@ impl VortexDataSource { let session = self.session.clone(); let schema = Arc::clone(&self.projected_schema); let concurrency = self.conversion_concurrency(); + let ordered = self.ordered; let batches = stream::once(async move { let work = execution .work @@ -529,6 +568,9 @@ impl VortexDataSource { .as_ref() .map_err(Clone::clone)?; let worker = match work { + ScanWork::Partitions(partitions) => { + Some(Arc::clone(partitions).arrays(ordered)) + } ScanWork::Pool(pool) => Some(Arc::clone(pool).worker()), ScanWork::Pieces(pieces) => { let piece = pieces.get(partition).and_then(|piece| piece.lock().take()); @@ -621,14 +663,25 @@ impl VortexDataSource { /// /// The first output partition polled starts the scan; every other partition reads the same one. struct ScanExecution { - /// Whether to split the scan into one piece per output partition rather than open it into a - /// pool that every output partition takes work from. - split: bool, + mode: ScanMode, claimed: Vec, work: OnceCell>, } +/// How the output partitions of one execution read the scan. +#[derive(Clone, Copy, PartialEq, Eq)] +enum ScanMode { + /// Every output partition takes partitions from the scan's one shared partition stream. + Partitions, + /// Every output partition polls its own worker of the opened scan. + Open, + /// Output partition `i` reads piece `i` of the split scan. + Split, +} + enum ScanWork { + /// Every output partition takes partitions from this shared stream. + Partitions(Arc), /// Every output partition polls its own worker of this pool. Pool(ScanPoolRef), /// Output partition `i` takes piece `i`, if there is one. @@ -636,9 +689,9 @@ enum ScanWork { } impl ScanExecution { - fn new(output_partitions: usize, split: bool) -> Self { + fn new(output_partitions: usize, mode: ScanMode) -> Self { Self { - split, + mode, claimed: (0..output_partitions) .map(|_| AtomicBool::new(false)) .collect(), @@ -652,8 +705,15 @@ impl ScanExecution { request: ScanRequest, ) -> VortexResult { let scan = data_source.scan(request).await?; - if !self.split { - return Ok(ScanWork::Pool(scan.open()?)); + match self.mode { + ScanMode::Partitions => { + return Ok(ScanWork::Partitions(Arc::new(SharedPartitions { + dtype: scan.dtype().clone(), + partitions: AsyncMutex::new(Some(scan.partitions())), + }))); + } + ScanMode::Open => return Ok(ScanWork::Pool(scan.open()?)), + ScanMode::Split => {} } let pieces = NonZeroUsize::new(self.claimed.len()).unwrap_or(NonZeroUsize::MIN); Ok(ScanWork::Pieces( @@ -665,6 +725,46 @@ impl ScanExecution { } } +/// Scan API partitions shared by every output partition, each taking the next one it needs. +struct SharedPartitions { + dtype: DType, + partitions: AsyncMutex>, +} + +/// The most partitions each output partition reads at once from [`SharedPartitions`]. +const SCAN_PARTITION_READ_AHEAD: usize = 2; + +impl SharedPartitions { + /// Takes the next partition, dropping the stream once it ends. + async fn next(&self) -> Option> { + let mut partitions = self.partitions.lock().await; + let next = partitions.as_mut()?.next().await; + if next.is_none() { + drop(partitions.take()); + } + next + } + + /// The arrays of the partitions this output partition takes, in partition order when + /// `ordered`, or reading a few partitions at once otherwise. + fn arrays(self: Arc, ordered: bool) -> SendableArrayStream { + let dtype = self.dtype.clone(); + let partitions = stream::unfold(self, |shared| async move { + let next = shared.next().await?; + Some((next, shared)) + }) + .map(|partition| partition.and_then(|partition| partition.execute())); + let arrays = if ordered { + partitions.try_flatten().boxed() + } else { + partitions + .try_flatten_unordered(Some(SCAN_PARTITION_READ_AHEAD)) + .boxed() + }; + ArrayStreamExt::boxed(ArrayStreamAdapter::new(dtype, arrays)) + } +} + struct OutputPartitionStream { schema: SchemaRef, stream: SendableRecordBatchStream, @@ -700,18 +800,27 @@ impl DataSource for VortexDataSource { partition: usize, _context: Arc, ) -> DFResult { - // Without sibling state this partition cannot share a pool with the others, so it scans + // Without sibling state this partition cannot share work with the others, so it scans // on its own and reads only its piece. + let mode = if self.scan_pool { + ScanMode::Split + } else if self.output_partition_count() == 1 { + ScanMode::Partitions + } else { + return Err(DataFusionError::Execution( + "multiple scan output partitions require sibling execution state".into(), + )); + }; self.open_partition( partition, - Arc::new(ScanExecution::new(self.output_partition_count(), true)), + Arc::new(ScanExecution::new(self.output_partition_count(), mode)), ) } fn create_sibling_state(&self, config: &ConfigOptions) -> Option> { Some(Arc::new(ScanExecution::new( self.output_partition_count(), - self.splits(config), + self.scan_mode(config), ))) } @@ -805,7 +914,10 @@ impl DataSource for VortexDataSource { fn with_fetch(&self, limit: Option) -> Option> { // DataSourceExec retains its partition properties when accepting fetch, so the fetch // bounds each output partition and DataFusion keeps a global limit above several. - if limit.is_some() && !self.dynamic_filters.is_empty() { + if limit.is_some() + && (!self.dynamic_filters.is_empty() + || (!self.scan_pool && self.output_partition_count() > 1)) + { return None; } let mut this = self.clone(); @@ -819,6 +931,9 @@ impl DataSource for VortexDataSource { } fn with_preserve_order(&self, preserve_order: bool) -> Option> { + if !self.scan_pool { + return None; + } let mut this = self.clone(); this.preserve_order = preserve_order; Some(Arc::new(this)) @@ -1319,6 +1434,7 @@ mod tests { scans: Arc::clone(&scans), }); let source = VortexDataSource::builder(data_source, VortexSession::default()) + .with_scan_pool(true) .build() .await?; for requested in [0, 1, 257] { @@ -1420,6 +1536,32 @@ mod tests { .collect() } + /// With the pool off, output partitions share the scan's partition stream as on develop: a + /// fetch keeps one partition, and direct opens need a single partition. + #[tokio::test] + async fn without_scan_pool_partitions_share_the_partition_stream() -> anyhow::Result<()> { + let data_source: DataSourceRef = Arc::new(TestDataSource { + dtype: test_dtype(), + polls: Arc::default(), + scans: Arc::default(), + }); + let source = VortexDataSource::builder(data_source, VortexSession::default()) + .with_scan_pool(false) + .build() + .await? + .repartitioned(4, 0, None)? + .expect("repartitioning supported"); + assert!(source.with_fetch(Some(1)).is_none()); + assert!(source.with_preserve_order(true).is_none()); + assert!(source.open(0, Arc::new(TaskContext::default())).is_err()); + + let plan = Arc::new(DataSourceExec::new(Arc::clone(&source))) as Arc; + let mut values = partition_values(&collect(plan, Arc::new(TaskContext::default())).await?); + values.sort_unstable(); + assert_eq!(values, [0, 1, 100, 101]); + Ok(()) + } + /// With work stealing off, each output partition reads its own piece in order, and /// partitions beyond the piece count return no rows. #[tokio::test] @@ -1430,6 +1572,7 @@ mod tests { scans: Arc::default(), }); let source = VortexDataSource::builder(data_source, VortexSession::default()) + .with_scan_pool(true) .build() .await? .repartitioned(4, 0, None)? @@ -1460,6 +1603,7 @@ mod tests { let (data_source, session, schema) = split_file_source().await?; let source = VortexDataSource::builder(data_source, session) .with_arrow_schema(schema) + .with_scan_pool(true) .build() .await? .repartitioned(4, 0, None)? From 8626a3ffde7562efbfb84886ef73894c71b28d8d Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Thu, 19 Nov 2026 15:54:11 -0500 Subject: [PATCH 11/80] Give layout scans a native split and open Layout scans now split on their layout splits and open into a pool whose workers share those splits through a channel. Multi-file scans queue an open for each deferred file; the worker that opens one sends the file's splits back into the channel for any worker to take. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-layout/src/scan/layout.rs | 553 ++++++++++++++++++- vortex-layout/src/scan/mod.rs | 1 + vortex-layout/src/scan/multi.rs | 681 +++++++++++++++++++++++- vortex-layout/src/scan/pool.rs | 480 +++++++++++++++++ vortex-layout/src/scan/repeated_scan.rs | 37 +- vortex-layout/src/scan/test.rs | 36 ++ 6 files changed, 1781 insertions(+), 7 deletions(-) create mode 100644 vortex-layout/src/scan/pool.rs diff --git a/vortex-layout/src/scan/layout.rs b/vortex-layout/src/scan/layout.rs index a0ab69310f8..926ea7cc8e8 100644 --- a/vortex-layout/src/scan/layout.rs +++ b/vortex-layout/src/scan/layout.rs @@ -37,6 +37,7 @@ use vortex_scan::Partition; use vortex_scan::PartitionRef; use vortex_scan::PartitionStream; use vortex_scan::ScanRequest; +use vortex_scan::pool::ScanPoolRef; use vortex_scan::selection::Selection; use vortex_session::VortexSession; @@ -44,9 +45,19 @@ use crate::LayoutReaderRef; use crate::scan::limit::RowLimit; use crate::scan::metrics::ScanMetrics; use crate::scan::metrics::ScanRecorder; +use crate::scan::pool::FileWork; +use crate::scan::pool::PiecePartition; +use crate::scan::pool::PoolFile; +use crate::scan::pool::PoolOptions; +use crate::scan::pool::PreparedScan; +use crate::scan::pool::open_pool; use crate::scan::scan_builder::ScanBuilder; /// An implementation of a [`DataSource`] that reads data from a [`LayoutReaderRef`]. +/// +/// When a scan is [split](DataSourceScan::split) or [opened](DataSourceScan::open), its units are +/// the layout's splits. Workers of an opened scan share them, each keeping several in flight on +/// its own thread. pub struct LayoutReaderDataSource { reader: LayoutReaderRef, session: VortexSession, @@ -201,6 +212,7 @@ impl DataSource for LayoutReaderDataSource { dtype, projection, filter, + limit: scan_request.limit, remaining_limit: scan_request.limit, row_limit, selection: scan_request.selection, @@ -224,6 +236,8 @@ struct LayoutReaderScan { dtype: DType, projection: BoundExpression, filter: Option, + /// The request's limit. + limit: Option, /// Limit rows not yet covered by the splits produced so far; production stops at zero. /// Decremented only for filterless scans, where each split's output is exactly its /// selected row count. @@ -239,6 +253,36 @@ struct LayoutReaderScan { split_size: u64, } +impl LayoutReaderScan { + /// Prepares the scan once, for splitting or opening. + fn into_split_scan(self) -> VortexResult { + let row_count = DataSourceScan::row_count(&self); + let options = LayoutScanOptions { + dtype: self.dtype, + ordered: self.ordered, + limit: self.limit, + has_filter: self.filter.is_some(), + splits_in_flight: self.split_concurrency, + }; + let row_range = clamp_row_range(self.next_row..self.end_row, self.reader.row_count()); + let scan = ScanBuilder::new(self.session, self.reader) + .with_row_range(row_range) + .with_selection(self.selection) + .with_projection(self.projection) + .with_some_filter(self.filter) + .with_some_scan_metrics(self.metrics) + .with_ordered(self.ordered) + .prepare()?; + let ranges = scan.split_ranges(None); + Ok(LayoutSplitScan { + options, + row_count, + scan: Arc::new(scan), + ranges, + }) + } +} + impl DataSourceScan for LayoutReaderScan { fn dtype(&self) -> &DType { &self.dtype @@ -256,6 +300,165 @@ impl DataSourceScan for LayoutReaderScan { fn partitions(self: Box) -> PartitionStream { (*self).boxed() } + + fn row_count(&self) -> Precision { + let selected = self + .selection + .row_count_in_range(&(self.next_row..self.end_row)); + let rows = self.limit.map_or(selected, |limit| selected.min(limit)); + if self.filter.is_some() { + Precision::inexact(rows) + } else { + Precision::exact(rows) + } + } + + fn split(self: Box, n: NonZeroUsize) -> VortexResult> { + Box::new(self.into_split_scan()?).split(n) + } + + fn open(self: Box) -> VortexResult { + Box::new(self.into_split_scan()?).open() + } +} + +/// Clamps a requested row range to the rows of the source. +fn clamp_row_range(row_range: Range, total_rows: u64) -> Range { + let end = row_range.end.min(total_rows); + row_range.start.min(end)..end +} + +/// What a [`LayoutSplitScan`] and every piece cut from it share. +#[derive(Clone)] +struct LayoutScanOptions { + dtype: DType, + ordered: bool, + limit: Option, + has_filter: bool, + splits_in_flight: Option, +} + +/// A prepared scan of one layout reader over some of its splits: a [`LayoutReaderScan`] that was +/// split or opened, or a piece cut from one. +struct LayoutSplitScan { + options: LayoutScanOptions, + row_count: Precision, + scan: Arc, + /// The scan's units: its layout splits, in row order. + ranges: Vec>, +} + +impl LayoutSplitScan { + /// A piece over some of the prepared scan's split `ranges`. + fn piece( + options: &LayoutScanOptions, + scan: Arc, + ranges: Vec>, + ) -> Self { + let selected = ranges + .iter() + .map(|range| scan.selected_row_count(range)) + .sum::(); + Self { + options: options.clone(), + row_count: if options.has_filter { + Precision::inexact(selected) + } else { + Precision::exact(selected) + }, + scan, + ranges, + } + } +} + +impl DataSourceScan for LayoutSplitScan { + fn dtype(&self) -> &DType { + &self.options.dtype + } + + fn partition_count(&self) -> Precision { + Precision::exact(1usize) + } + + fn partitions(self: Box) -> PartitionStream { + let index = self.ranges.first().map_or(0, |range| { + usize::try_from(range.start).unwrap_or(usize::MAX) + }); + PiecePartition::stream(self, index) + } + + fn row_count(&self) -> Precision { + self.row_count + } + + fn split(self: Box, n: NonZeroUsize) -> VortexResult> { + if self.options.limit.is_some() || self.ranges.len() <= 1 || n.get() == 1 { + return Ok(vec![self]); + } + let LayoutSplitScan { + options, + scan, + ranges, + .. + } = *self; + Ok(group_contiguous(ranges, n) + .into_iter() + .map(|ranges| { + Box::new(LayoutSplitScan::piece(&options, Arc::clone(&scan), ranges)) + as DataSourceScanRef + }) + .collect()) + } + + fn open(self: Box) -> VortexResult { + let LayoutScanOptions { + dtype, + ordered, + limit, + has_filter, + splits_in_flight, + } = self.options; + if limit == Some(0) { + return Box::new(Empty::new(dtype, 0)).open(); + } + let work = FileWork::start(self.scan, self.ranges)?; + let options = PoolOptions { + dtype, + ordered, + limit, + has_filter, + splits_in_flight, + }; + Ok(open_pool(options, vec![PoolFile::Opened(work)], None)) + } +} + +/// Groups consecutive `ranges` into at most `n` contiguous groups of about equal row counts. +/// +/// Never cuts a range: each range lands whole in one group. +pub(crate) fn group_contiguous(ranges: Vec>, n: NonZeroUsize) -> Vec>> { + let total = ranges + .iter() + .map(|range| u128::from(range.end - range.start)) + .sum::() + .max(1); + let n_groups = n.get() as u128; + let mut groups: Vec>> = Vec::new(); + let mut current_group = None; + let mut before = 0u128; + for range in ranges { + let group = (before * n_groups / total).min(n_groups - 1); + before += u128::from(range.end - range.start); + if current_group != Some(group) { + current_group = Some(group); + groups.push(Vec::new()); + } + if let Some(last) = groups.last_mut() { + last.push(range); + } + } + groups } impl Stream for LayoutReaderScan { @@ -393,11 +596,17 @@ impl Partition for LayoutReaderSplit { } /// A scan that produces no data, only empty arrays with the correct row count. -struct Empty { +pub(crate) struct Empty { dtype: DType, row_count: u64, } +impl Empty { + pub(crate) fn new(dtype: DType, row_count: u64) -> Self { + Self { dtype, row_count } + } +} + impl DataSourceScan for Empty { fn dtype(&self) -> &DType { &self.dtype @@ -410,6 +619,10 @@ impl DataSourceScan for Empty { fn partitions(self: Box) -> PartitionStream { stream::iter([Ok(self as _)]).boxed() } + + fn row_count(&self) -> Precision { + Precision::exact(self.row_count) + } } impl Partition for Empty { @@ -620,3 +833,341 @@ mod tests { Ok(()) } } + +#[cfg(test)] +mod pool_tests { + use std::num::NonZeroUsize; + use std::sync::Arc; + + use rstest::rstest; + use vortex_array::dtype::DType; + use vortex_array::dtype::Nullability; + use vortex_array::dtype::StructFields; + use vortex_array::expr::Expression; + use vortex_array::expr::root; + use vortex_buffer::Buffer; + use vortex_error::VortexResult; + use vortex_metrics::DefaultMetricsRegistry; + use vortex_metrics::MetricValue; + use vortex_metrics::MetricsRegistry; + use vortex_scan::DataSource; + use vortex_scan::DataSourceScanRef; + use vortex_scan::ScanRequest; + use vortex_scan::selection::Selection; + use vortex_scan::strict_sorted_buffer::StrictSortedBuffer; + + use super::LayoutReaderDataSource; + use super::group_contiguous; + use crate::scan::test::TestLayoutReader; + use crate::scan::test::collect_scan_values; + use crate::scan::test::keep_odd; + use crate::scan::test::new_session; + use crate::scan::test::read_with_one_worker; + use crate::scan::test::read_with_workers; + + fn counter_values(registry: &DefaultMetricsRegistry) -> Vec { + registry + .snapshot() + .iter() + .map(|metric| match metric.value() { + MetricValue::Counter(counter) => counter.value(), + _ => panic!("expected a scan counter"), + }) + .collect() + } + + fn plan( + source: &LayoutReaderDataSource, + request: ScanRequest, + ) -> VortexResult { + futures::executor::block_on(source.scan(request)) + } + + /// Earlier splits finish last, so completion order is the reverse of row order. + fn slow_start(row: u64) -> usize { + usize::try_from(32u64.saturating_sub(row)).unwrap_or(0) + } + + fn source(reader: TestLayoutReader) -> LayoutReaderDataSource { + LayoutReaderDataSource::new(Arc::new(reader), new_session()) + } + + /// Each opened scan is one execution: it counts one file scan, and one attempt per split. + #[test] + fn opened_executions_share_aggregate_handles() -> VortexResult<()> { + let registry = Arc::new(DefaultMetricsRegistry::default()); + let source = source(TestLayoutReader::new(8).with_split_size(2)) + .with_metrics_registry(Arc::::clone(®istry)); + for execution in 1..=2 { + let pool = plan(&source, ScanRequest::default())?.open()?; + let values = read_with_workers(&pool, 2)?.concat(); + assert_eq!(values.len(), 8); + assert_eq!( + counter_values(®istry), + [4 * execution, 0, 0, execution, 0] + ); + } + Ok(()) + } + + /// N workers on one pool read every split exactly once. + #[rstest] + #[case::ordered(true)] + #[case::unordered(false)] + fn workers_read_every_split_once(#[case] ordered: bool) -> VortexResult<()> { + let source = source(TestLayoutReader::new(64).with_split_size(1)); + let pool = plan( + &source, + ScanRequest { + ordered, + ..Default::default() + }, + )? + .open()?; + let per_worker = read_with_workers(&pool, 4)?; + + let mut values = per_worker.concat(); + values.sort_unstable(); + assert_eq!(values, (0..64).collect::>()); + Ok(()) + } + + /// A worker of an ordered pool yields rows in row order, even when later splits finish + /// first, and later workers of the pool get nothing. + #[test] + fn ordered_worker_yields_row_order() -> VortexResult<()> { + let read = |ordered| { + let source = source( + TestLayoutReader::new(32) + .with_split_size(1) + .with_yields(slow_start), + ); + let pool = plan( + &source, + ScanRequest { + ordered, + ..Default::default() + }, + )? + .open()?; + let first = read_with_one_worker(Arc::clone(&pool))?; + let second = read_with_one_worker(pool)?; + assert!(second.is_empty()); + Ok::<_, vortex_error::VortexError>(first) + }; + + assert_eq!(read(true)?, (0..32).collect::>()); + // The same splits complete out of order, so an unordered worker does not keep row order. + assert_ne!(read(false)?, (0..32).collect::>()); + Ok(()) + } + + /// A limit holds across several workers of an unordered pool, whether splits reserve their + /// rows up front (no filter) or trim their output (filter). + #[rstest] + #[case::reserved(None)] + #[case::trimmed(Some(root()))] + fn unordered_limit_holds_across_workers( + #[case] filter: Option, + ) -> VortexResult<()> { + let source = source(TestLayoutReader::new(64).with_split_size(2)); + let pool = plan( + &source, + ScanRequest { + filter, + limit: Some(7), + ..Default::default() + }, + )? + .open()?; + let mut values = read_with_workers(&pool, 4)?.concat(); + values.sort_unstable(); + values.dedup(); + assert_eq!(values.len(), 7); + Ok(()) + } + + /// An ordered pool with a limit returns exactly the first `limit` rows. + #[rstest] + #[case::reserved(false, &[0, 1, 2, 3, 4])] + #[case::trimmed(true, &[1, 3, 5, 7, 9])] + fn ordered_limit_returns_the_first_rows( + #[case] filtered: bool, + #[case] expected: &[i32], + ) -> VortexResult<()> { + let source = source( + TestLayoutReader::new(32) + .with_split_size(2) + .with_keep_row(keep_odd) + .with_yields(slow_start), + ); + let pool = plan( + &source, + ScanRequest { + filter: filtered.then(root), + ordered: true, + limit: Some(5), + ..Default::default() + }, + )? + .open()?; + assert_eq!(read_with_one_worker(pool)?, expected); + Ok(()) + } + + /// With a sparse selection and no filter, each split contributes only its selected rows, so + /// the workers keep taking splits until the limit is actually filled. + #[rstest] + #[case::ordered(true)] + #[case::unordered(false)] + fn opened_sparse_selection_with_limit_fills_the_limit( + #[case] ordered: bool, + ) -> VortexResult<()> { + let source = source(TestLayoutReader::new(12).with_split_size(2)); + + // Every two-row split contains exactly one selected row (the even ones). + let selection = + Selection::IncludeByIndex(StrictSortedBuffer::try_new(Buffer::from_iter([ + 0u64, 2, 4, 6, 8, 10, + ]))?); + let pool = plan( + &source, + ScanRequest { + selection, + limit: Some(3), + ordered, + ..Default::default() + }, + )? + .open()?; + let mut values = read_with_one_worker(pool)?; + if !ordered { + values.sort_unstable(); + } + assert_eq!(values, [0, 2, 4]); + Ok(()) + } + + /// `split(n)` pieces cover the scan exactly, are in row order, and never cut a layout split. + #[rstest] + #[case::fewer_pieces_than_splits(3, 3)] + #[case::more_pieces_than_splits(16, 7)] + fn split_pieces_cover_the_scan_on_split_boundaries( + #[case] n: usize, + #[case] expected_pieces: usize, + ) -> VortexResult<()> { + // Splits of three rows: [0, 3), [3, 6), ..., [18, 20). + let source = source(TestLayoutReader::new(20).with_split_size(3)); + let scan = plan(&source, ScanRequest::default())?; + let pieces = scan.split(NonZeroUsize::new(n).expect("non-zero"))?; + assert_eq!(pieces.len(), expected_pieces); + assert_eq!( + pieces + .iter() + .map(|piece| piece.row_count().as_exact()) + .sum::>(), + Some(20) + ); + + let mut values = Vec::new(); + for piece in pieces { + let piece_values = read_with_one_worker(piece.open()?)?; + let first = *piece_values.first().expect("pieces are not empty"); + let last = *piece_values.last().expect("pieces are not empty"); + assert_eq!(first % 3, 0, "piece starts on a split boundary"); + assert!( + (last + 1) % 3 == 0 || last == 19, + "piece ends on a split boundary" + ); + values.extend(piece_values); + } + assert_eq!(values, (0..20).collect::>()); + Ok(()) + } + + /// A piece read through the partitions API returns the same rows as its pool. + #[test] + fn split_pieces_read_through_partitions() -> VortexResult<()> { + let source = source(TestLayoutReader::new(20).with_split_size(3)); + let scan = plan( + &source, + ScanRequest { + ordered: true, + ..Default::default() + }, + )?; + let mut values = Vec::new(); + for piece in scan.split(NonZeroUsize::new(3).expect("non-zero"))? { + let partitions = + futures::executor::block_on_stream(piece.partitions()).collect::>(); + assert_eq!(partitions.len(), 1); + for partition in partitions { + values.extend(collect_scan_values(futures::executor::block_on_stream( + partition?.execute()?, + ))?); + } + } + assert_eq!(values, (0..20).collect::>()); + Ok(()) + } + + #[test] + fn split_keeps_a_limited_scan_whole() -> VortexResult<()> { + let source = source(TestLayoutReader::new(20).with_split_size(3)); + let scan = plan( + &source, + ScanRequest { + limit: Some(4), + ..Default::default() + }, + )?; + let pieces = scan.split(NonZeroUsize::new(4).expect("non-zero"))?; + assert_eq!(pieces.len(), 1); + Ok(()) + } + + #[test] + fn grouping_never_returns_more_groups_than_requested() { + let ranges = (0..10u64) + .map(|start| start * 10..start * 10 + 10) + .collect(); + let groups = group_contiguous(ranges, NonZeroUsize::new(3).expect("non-zero")); + assert_eq!(groups.len(), 3); + assert_eq!(groups.concat().len(), 10); + } + + /// A length-only scan opens into one pool whose workers together return its rows once. + #[test] + fn length_only_scan_returns_its_rows_once_across_workers() -> VortexResult<()> { + let source = source(TestLayoutReader::new(10).with_dtype(DType::Struct( + StructFields::empty(), + Nullability::NonNullable, + ))); + let pool = plan( + &source, + ScanRequest { + limit: Some(7), + ..Default::default() + }, + )? + .open()?; + let rows: usize = std::thread::scope(|scope| { + let handles = (0..3) + .map(|_| { + let worker = Arc::clone(&pool).worker(); + scope.spawn(move || { + futures::executor::block_on_stream(worker) + .map(|array| array.map(|array| array.len())) + .sum::>() + }) + }) + .collect::>(); + handles + .into_iter() + .map(|handle| handle.join().expect("worker thread panicked")) + .sum::>() + })?; + assert_eq!(rows, 7); + Ok(()) + } +} diff --git a/vortex-layout/src/scan/mod.rs b/vortex-layout/src/scan/mod.rs index ea8e8843773..ea8ea2d8e0f 100644 --- a/vortex-layout/src/scan/mod.rs +++ b/vortex-layout/src/scan/mod.rs @@ -7,6 +7,7 @@ pub mod layout; mod limit; pub mod metrics; pub mod multi; +mod pool; pub mod repeated_scan; pub mod scan_builder; pub mod split_by; diff --git a/vortex-layout/src/scan/multi.rs b/vortex-layout/src/scan/multi.rs index 1f1ee275688..be41497e0ad 100644 --- a/vortex-layout/src/scan/multi.rs +++ b/vortex-layout/src/scan/multi.rs @@ -57,12 +57,24 @@ 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; use crate::LayoutReaderRef; +use crate::scan::layout::Empty; +use crate::scan::layout::group_contiguous; use crate::scan::limit::RowLimit; +use crate::scan::pool::FileWork; +use crate::scan::pool::PiecePartition; +use crate::scan::pool::PlannedSplits; +use crate::scan::pool::PoolFile; +use crate::scan::pool::PoolOptions; +use crate::scan::pool::PrepareFile; +use crate::scan::pool::PreparedScan; +use crate::scan::pool::open_pool; use crate::scan::scan_builder::ScanBuilder; /// Default concurrency for opening deferred readers. @@ -322,7 +334,6 @@ impl DataSource for MultiLayoutDataSource { row_limit, ready, deferred, - handle: self.session.handle(), concurrency: self.concurrency, })) } @@ -374,6 +385,17 @@ impl BoundScanRequest { split_concurrency, }) } + + /// Whether the scan filters rows, so its output row count is unknown up front. A filter + /// that failed to bind counts as one. + fn has_filter(&self) -> bool { + !matches!(self.filter, Ok(None)) + } + + /// Whether the request selects partitions, which only the partitions path applies. + fn selects_partitions(&self) -> bool { + self.partition_range.is_some() || !matches!(self.partition_selection, Selection::All) + } } struct MultiLayoutScan { @@ -384,10 +406,31 @@ struct MultiLayoutScan { row_limit: Option, ready: VecDeque, deferred: VecDeque>, - handle: vortex_io::runtime::Handle, concurrency: usize, } +impl MultiLayoutScan { + /// The scan as files to split or open. Files keep their partition order. + fn into_split_scan(self) -> MultiLayoutSplitScan { + let children = self + .ready + .into_iter() + .map(ScanChild::Opened) + .chain(self.deferred.into_iter().map(ScanChild::Deferred)) + .collect(); + MultiLayoutSplitScan { + context: Arc::new(ScanContext { + session: self.session, + source_dtype: self.source_dtype, + dtype: self.dtype, + request: self.request, + }), + children, + index: 0, + } + } +} + impl DataSourceScan for MultiLayoutScan { fn dtype(&self) -> &DType { &self.dtype @@ -402,6 +445,35 @@ impl DataSourceScan for MultiLayoutScan { } } + fn row_count(&self) -> Precision { + let estimate = estimate_row_count( + &self.request, + self.ready + .iter() + .map(|reader| file_row_count(&self.request, reader)), + self.ready.len() + self.deferred.len(), + ); + if self.request.selects_partitions() { + estimate.into_inexact() + } else { + estimate + } + } + + fn split(self: Box, n: NonZeroUsize) -> VortexResult> { + if self.request.selects_partitions() { + return Ok(vec![self]); + } + Box::new(self.into_split_scan()).split(n) + } + + fn open(self: Box) -> VortexResult { + if self.request.selects_partitions() { + return Ok(Arc::new(PartitionPool::new(self))); + } + Box::new(self.into_split_scan()).open() + } + fn partitions(self: Box) -> PartitionStream { let Self { session, @@ -411,9 +483,9 @@ impl DataSourceScan for MultiLayoutScan { row_limit, ready, deferred, - handle, concurrency, } = *self; + let handle = session.handle(); let ordered = request.ordered; @@ -623,6 +695,279 @@ impl Partition for MultiLayoutPartition { } } +/// The rows `request` selects from an opened file, before any filter or limit. +fn file_row_count(request: &BoundScanRequest, reader: &LayoutReaderRef) -> u64 { + let row_range = request + .row_range + .clone() + .unwrap_or_else(|| 0..reader.row_count()); + request.selection.row_count_in_range(&row_range) +} + +/// Estimates the rows a scan of `files` files returns from the rows of the files whose rows are +/// known, extrapolating to the rest. +fn estimate_row_count( + request: &BoundScanRequest, + known: impl Iterator, + files: usize, +) -> Precision { + let (rows, known_files) = known.fold((0u64, 0u64), |(rows, count), file_rows| { + (rows.saturating_add(file_rows), count + 1) + }); + let files = files as u64; + let (rows, is_exact) = if known_files == files { + (rows, !request.has_filter()) + } else if let Some(average) = rows.checked_div(known_files) { + (average.saturating_mul(files), false) + } else { + return Precision::Absent; + }; + let rows = request.limit.map_or(rows, |limit| rows.min(limit)); + if is_exact { + Precision::exact(rows) + } else { + Precision::inexact(rows) + } +} + +/// What every piece of a split or opened multi-layout scan shares. +struct ScanContext { + session: VortexSession, + source_dtype: DType, + dtype: DType, + request: BoundScanRequest, +} + +impl ScanContext { + /// Plans the scan of one opened file: checks its dtype, prunes it on statistics, and + /// prepares its splits. Returns `None` when statistics reject the file. Reads metadata only. + fn plan_file(&self, reader: LayoutReaderRef) -> VortexResult> { + if reader.dtype() != &self.source_dtype { + return Err(vortex_err!( + "Multi-layout reader dtype mismatch: expected {}, got {}", + self.source_dtype, + reader.dtype() + )); + } + let filter = self.request.filter.clone()?; + let row_range = self + .request + .row_range + .clone() + .unwrap_or_else(|| 0..reader.row_count()); + + if let Some(filter) = &filter { + let mask_len = usize::try_from(row_range.end - row_range.start).unwrap_or(usize::MAX); + if let Ok(pruning) = + reader.pruning_evaluation(&row_range, filter, Mask::new_true(mask_len)) + && let Some(Ok(mask)) = pruning.now_or_never() + && mask.all_false() + { + return Ok(None); + } + } + + let scan = ScanBuilder::new(self.session.clone(), reader) + .with_row_range(row_range) + .with_selection(self.request.selection.clone()) + .with_projection(self.request.projection.clone()) + .with_some_filter(filter) + .with_ordered(self.request.ordered) + .prepare()?; + let ranges = scan.split_ranges(None); + Ok(Some((Arc::new(scan), ranges))) + } + + /// Starts reading an opened file for one execution. + fn start_file(&self, reader: LayoutReaderRef) -> VortexResult { + match self.plan_file(reader)? { + Some((scan, ranges)) => FileWork::start(scan, ranges), + None => Ok(FileWork::empty()), + } + } +} + +/// One file of a split or opened multi-layout scan. +enum ScanChild { + Opened(LayoutReaderRef), + /// An opened file whose splits are known: all of them, or the share of one piece. + Planned { + scan: Arc, + ranges: Vec>, + }, + Deferred(Arc), +} + +/// A multi-layout scan that was split or opened, or a piece cut from one. Its units are files, +/// then each file's splits. +struct MultiLayoutSplitScan { + context: Arc, + children: Vec, + /// The index of the piece's single partition. + index: usize, +} + +impl MultiLayoutSplitScan { + /// Splits a planned file's ranges into `pieces` contiguous groups. + fn split_child(child: ScanChild, pieces: usize) -> Vec { + match child { + ScanChild::Planned { scan, ranges } if pieces > 1 => group_contiguous( + ranges, + NonZeroUsize::new(pieces).unwrap_or(NonZeroUsize::MIN), + ) + .into_iter() + .map(|ranges| ScanChild::Planned { + scan: Arc::clone(&scan), + ranges, + }) + .collect(), + child => vec![child], + } + } +} + +impl DataSourceScan for MultiLayoutSplitScan { + fn dtype(&self) -> &DType { + &self.context.dtype + } + + fn partition_count(&self) -> Precision { + Precision::exact(1usize) + } + + fn partitions(self: Box) -> PartitionStream { + let index = self.index; + PiecePartition::stream(self, index) + } + + fn row_count(&self) -> Precision { + let request = &self.context.request; + let known = self.children.iter().filter_map(|child| match child { + ScanChild::Opened(reader) => Some(file_row_count(request, reader)), + ScanChild::Planned { scan, ranges } => Some( + ranges + .iter() + .map(|range| scan.selected_row_count(range)) + .sum(), + ), + ScanChild::Deferred(_) => None, + }); + estimate_row_count(request, known, self.children.len()) + } + + fn split(self: Box, n: NonZeroUsize) -> VortexResult> { + if self.context.request.limit.is_some() || n.get() == 1 || self.children.is_empty() { + return Ok(vec![self]); + } + let MultiLayoutSplitScan { + context, children, .. + } = *self; + + // Plan the opened files so they can be cut on their splits. Deferred files stay whole: + // splitting never opens a file. + let mut planned = Vec::with_capacity(children.len()); + for child in children { + match child { + ScanChild::Opened(reader) => { + if let Some((scan, ranges)) = context.plan_file(reader)? { + planned.push(ScanChild::Planned { scan, ranges }); + } + } + child => planned.push(child), + } + } + if planned.is_empty() { + return Ok(vec![Box::new(MultiLayoutSplitScan { + context, + children: planned, + index: 0, + })]); + } + + let n = n.get(); + let pieces: Vec> = if n <= planned.len() { + // Group whole files into contiguous pieces. + let files = planned.len(); + let mut pieces: Vec> = Vec::new(); + let mut current = None; + for (index, child) in planned.into_iter().enumerate() { + let piece = index * n / files; + if current != Some(piece) { + current = Some(piece); + pieces.push(Vec::new()); + } + if let Some(last) = pieces.last_mut() { + last.push(child); + } + } + pieces + } else { + // One piece per file, and the pieces left over cut planned files on their splits, in + // proportion to their rows. + let extra = (n - planned.len()) as u128; + let rows = |child: &ScanChild| match child { + ScanChild::Planned { ranges, .. } => ranges + .iter() + .map(|range| u128::from(range.end - range.start)) + .sum::(), + _ => 0, + }; + let total = planned.iter().map(rows).sum::().max(1); + planned + .into_iter() + .flat_map(|child| { + let pieces = 1 + usize::try_from(extra * rows(&child) / total).unwrap_or(0); + Self::split_child(child, pieces) + }) + .map(|child| vec![child]) + .collect() + }; + + Ok(pieces + .into_iter() + .enumerate() + .map(|(index, children)| { + Box::new(MultiLayoutSplitScan { + context: Arc::clone(&context), + children, + index, + }) as DataSourceScanRef + }) + .collect()) + } + + fn open(self: Box) -> VortexResult { + let MultiLayoutSplitScan { + context, children, .. + } = *self; + let request = &context.request; + if request.limit == Some(0) { + return Box::new(Empty::new(context.dtype.clone(), 0)).open(); + } + + let mut files = Vec::with_capacity(children.len()); + for child in children { + files.push(match child { + ScanChild::Opened(reader) => PoolFile::Opened(context.start_file(reader)?), + ScanChild::Planned { scan, ranges } => { + PoolFile::Opened(FileWork::start(scan, ranges)?) + } + ScanChild::Deferred(factory) => PoolFile::Deferred(factory), + }); + } + + let options = PoolOptions { + dtype: context.dtype.clone(), + ordered: request.ordered, + limit: request.limit, + has_filter: request.has_filter(), + splits_in_flight: request.split_concurrency, + }; + let prepare: PrepareFile = Arc::new(move |reader| context.start_file(reader)); + Ok(open_pool(options, files, Some(prepare))) + } +} + #[cfg(test)] mod tests { use std::sync::Arc; @@ -799,3 +1144,333 @@ mod tests { Ok(()) } } + +#[cfg(test)] +mod pool_tests { + use std::sync::Arc; + use std::sync::atomic::AtomicBool; + use std::sync::atomic::AtomicUsize; + use std::sync::atomic::Ordering; + use std::task::Context; + use std::task::Poll; + + use async_trait::async_trait; + use futures::StreamExt; + use futures::future::poll_fn; + use futures::task::ArcWake; + use futures::task::AtomicWaker; + use futures::task::noop_waker_ref; + use futures::task::waker; + use rstest::rstest; + use vortex_array::ArrayRef; + use vortex_array::dtype::Nullability; + use vortex_array::dtype::PType; + use vortex_array::expr::root; + use vortex_array::stream::SendableArrayStream; + use vortex_buffer::Buffer; + use vortex_error::VortexResult; + use vortex_io::runtime::BlockingRuntime; + use vortex_io::runtime::single::SingleThreadRuntime; + use vortex_scan::DataSource; + use vortex_scan::ScanRequest; + use vortex_scan::strict_sorted_buffer::StrictSortedBuffer; + + use super::*; + use crate::scan::test::InFlight; + use crate::scan::test::TestLayoutReader; + use crate::scan::test::collect_scan_values; + use crate::scan::test::new_session; + use crate::scan::test::read_with_one_worker; + use crate::scan::test::read_with_workers; + use crate::scan::test::session_with_handle; + + fn plan( + source: &MultiLayoutDataSource, + request: ScanRequest, + ) -> VortexResult { + futures::executor::block_on(source.scan(request)) + } + + fn i32_dtype() -> DType { + DType::Primitive(PType::I32, Nullability::NonNullable) + } + + /// A factory whose open completes only once its gate is released. + #[derive(Default)] + struct Gate { + is_open: AtomicBool, + waker: AtomicWaker, + } + + impl Gate { + fn release(&self) { + self.is_open.store(true, Ordering::SeqCst); + self.waker.wake(); + } + } + + struct GatedFactory { + reader: LayoutReaderRef, + gate: Arc, + opens: Arc, + } + + #[async_trait] + impl LayoutReaderFactory for GatedFactory { + async fn open(&self) -> VortexResult> { + self.opens.fetch_add(1, Ordering::SeqCst); + poll_fn(|cx| { + self.gate.waker.register(cx.waker()); + if self.gate.is_open.load(Ordering::SeqCst) { + Poll::Ready(()) + } else { + Poll::Pending + } + }) + .await; + Ok(Some(Arc::clone(&self.reader))) + } + } + + fn gated_factory(reader: TestLayoutReader, gate: &Arc) -> Arc { + Arc::new(GatedFactory { + reader: Arc::new(reader), + gate: Arc::clone(gate), + opens: Arc::default(), + }) + } + + /// Deferred files of `rows` one-row splits, the `i`th producing `100 * i + row`. + fn gated_source(files: usize, rows: u64) -> (MultiLayoutDataSource, Vec>) { + let gates: Vec<_> = (0..files).map(|_| Arc::new(Gate::default())).collect(); + let factories = gates + .iter() + .enumerate() + .map(|(index, gate)| { + let base = 100 * i32::try_from(index).expect("few files"); + gated_factory( + TestLayoutReader::new(rows) + .with_split_size(1) + .with_base(base), + gate, + ) + }) + .collect(); + let source = + MultiLayoutDataSource::new_deferred(i32_dtype(), factories, vec![], &new_session()); + (source, gates) + } + + #[derive(Default)] + struct WakeFlag(AtomicBool); + + impl ArcWake for WakeFlag { + fn wake_by_ref(arc_self: &Arc) { + arc_self.0.store(true, Ordering::SeqCst); + } + } + + fn poll_worker( + worker: &mut SendableArrayStream, + cx: &mut Context<'_>, + ) -> Poll>> { + worker.poll_next_unpin(cx) + } + + /// A deferred file is opened by a worker, and its splits are shared with other workers. A + /// worker that finds only an open in progress waits, and is woken when the open adds splits. + #[test] + fn deferred_file_splits_are_shared_with_waiting_workers() -> VortexResult<()> { + let (source, gates) = gated_source(1, 16); + let pool = plan(&source, ScanRequest::default())?.open()?; + let mut opener = Arc::clone(&pool).worker(); + let mut waiter = Arc::clone(&pool).worker(); + let mut noop = Context::from_waker(noop_waker_ref()); + let flag = Arc::new(WakeFlag::default()); + let flag_waker = waker(Arc::clone(&flag)); + let mut flagged = Context::from_waker(&flag_waker); + + // The opener takes the only file and blocks on its open; the waiter finds nothing to take + // but an open in progress, so it waits. + assert!(poll_worker(&mut opener, &mut noop).is_pending()); + assert!(poll_worker(&mut waiter, &mut flagged).is_pending()); + + gates[0].release(); + let Poll::Ready(Some(first)) = poll_worker(&mut opener, &mut noop) else { + panic!("the opener reads a split of the file it opened"); + }; + assert!(flag.0.load(Ordering::SeqCst), "the waiter is woken"); + + let waiter_values = collect_scan_values(futures::executor::block_on_stream(waiter))?; + let opener_values = collect_scan_values( + std::iter::once(first).chain(futures::executor::block_on_stream(opener)), + )?; + assert!( + !waiter_values.is_empty(), + "the waiter reads the opened file's splits" + ); + let mut values = [opener_values, waiter_values].concat(); + values.sort_unstable(); + assert_eq!(values, (0..16).collect::>()); + Ok(()) + } + + /// An ordered worker emits files in file order, even when a later file opens first. + #[test] + fn ordered_worker_emits_files_in_order() -> VortexResult<()> { + let (source, gates) = gated_source(3, 3); + let pool = plan( + &source, + ScanRequest { + ordered: true, + ..Default::default() + }, + )? + .open()?; + let mut worker = pool.worker(); + let mut noop = Context::from_waker(noop_waker_ref()); + assert!(poll_worker(&mut worker, &mut noop).is_pending()); + for gate in gates.iter().rev() { + gate.release(); + if !Arc::ptr_eq(gate, &gates[0]) { + assert!(poll_worker(&mut worker, &mut noop).is_pending()); + } + } + let values = collect_scan_values(futures::executor::block_on_stream(worker))?; + assert_eq!(values, [0, 1, 2, 100, 101, 102, 200, 201, 202]); + Ok(()) + } + + /// A limit is shared by every worker and file of an unordered pool. + #[test] + fn pool_limit_is_shared_across_readers() -> VortexResult<()> { + let first: LayoutReaderRef = Arc::new(TestLayoutReader::new(4).with_split_size(1)); + let gate = Arc::new(Gate::default()); + gate.release(); + let source = MultiLayoutDataSource::new_with_first( + first, + vec![gated_factory( + TestLayoutReader::new(4).with_split_size(1).with_base(10), + &gate, + )], + vec![], + &new_session(), + ); + + let pool = plan( + &source, + ScanRequest { + filter: Some(root()), + limit: Some(3), + ..Default::default() + }, + )? + .open()?; + let values = read_with_workers(&pool, 3)?.concat(); + + assert_eq!(values.len(), 3); + Ok(()) + } + + /// Splitting cuts opened files on their splits and keeps deferred files whole, in order. + #[test] + fn split_cuts_opened_files_and_keeps_deferred_files_whole() -> VortexResult<()> { + let first: LayoutReaderRef = Arc::new(TestLayoutReader::new(6).with_split_size(2)); + let opens = Arc::new(AtomicUsize::new(0)); + let gate = Arc::new(Gate::default()); + gate.release(); + let source = MultiLayoutDataSource::new_with_first( + first, + vec![Arc::new(GatedFactory { + reader: Arc::new(TestLayoutReader::new(4).with_split_size(2).with_base(100)), + gate, + opens: Arc::clone(&opens), + })], + vec![], + &new_session(), + ); + let scan = plan( + &source, + ScanRequest { + ordered: true, + ..Default::default() + }, + )?; + let pieces = scan.split(NonZeroUsize::new(4).expect("non-zero"))?; + assert_eq!(opens.load(Ordering::SeqCst), 0, "splitting opens no file"); + // The opened file's three splits take three pieces; the deferred file stays whole. + assert_eq!(pieces.len(), 4); + + let mut values = Vec::new(); + for piece in pieces { + values.extend(read_with_one_worker(piece.open()?)?); + } + assert_eq!(values, [0, 1, 2, 3, 4, 5, 100, 101, 102, 103]); + Ok(()) + } + + /// A request that selects partitions is split and opened by its partitions, so both paths + /// read the same files. + #[rstest] + #[case::range(Some(1..2), None)] + #[case::selection(None, Some(1))] + fn selected_partitions_open_by_partition( + #[case] partition_range: Option>, + #[case] selected_partition: Option, + ) -> VortexResult<()> { + let partition_selection = match selected_partition { + Some(index) => { + Selection::IncludeByIndex(StrictSortedBuffer::try_new(Buffer::from_iter([index]))?) + } + None => Selection::All, + }; + // The partitions path spawns file opens onto the session's runtime. + let runtime = SingleThreadRuntime::default(); + let gate = Arc::new(Gate::default()); + gate.release(); + let source = MultiLayoutDataSource::new_with_first( + Arc::new(TestLayoutReader::new(3)), + vec![gated_factory(TestLayoutReader::new(3).with_base(10), &gate)], + vec![], + &session_with_handle(runtime.handle()), + ); + let request = ScanRequest { + partition_range, + partition_selection, + ordered: true, + ..Default::default() + }; + let pieces = plan(&source, request.clone())?.split(NonZeroUsize::new(4).expect("4"))?; + assert_eq!(pieces.len(), 1); + let pool = plan(&source, request)?.open()?; + let values = collect_scan_values(runtime.block_on_stream(pool.worker()))?; + assert_eq!(values, [10, 11, 12]); + Ok(()) + } + + /// A worker reads at most `split_concurrency` splits at once. + #[rstest] + #[case(1)] + #[case(2)] + fn split_concurrency_bounds_each_worker(#[case] max: usize) -> VortexResult<()> { + let in_flight = Arc::new(InFlight::default()); + let reader: LayoutReaderRef = Arc::new( + TestLayoutReader::new(64) + .with_split_size(1) + .with_in_flight(Arc::clone(&in_flight)), + ); + let source = MultiLayoutDataSource::new_with_first(reader, vec![], vec![], &new_session()); + let pool = plan( + &source, + ScanRequest { + ordered: true, + split_concurrency: NonZeroUsize::new(max), + ..Default::default() + }, + )? + .open()?; + assert_eq!(read_with_one_worker(pool)?, (0..64).collect::>()); + assert!(in_flight.peak() <= max, "peak {}", in_flight.peak()); + Ok(()) + } +} diff --git a/vortex-layout/src/scan/pool.rs b/vortex-layout/src/scan/pool.rs new file mode 100644 index 00000000000..fcfea905b7a --- /dev/null +++ b/vortex-layout/src/scan/pool.rs @@ -0,0 +1,480 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! The work that the workers of an opened layout scan share. +//! +//! A pool's units are the splits of one or more files, and the files not yet opened. A worker +//! takes units and keeps up to `splits_in_flight` of them running on its own thread: it +//! builds a split's task only when it takes the split, and never spawns. Opening a deferred file +//! is a unit like any other. +//! +//! - An unordered pool hands units out through a channel. The worker that opens a deferred file +//! sends the file's splits back into the channel, where any worker can take them. The channel +//! closes once every open has finished, which ends the workers. +//! - An ordered pool gives all of its units, in row order, to its first worker; later workers +//! get nothing. Parallel ordered reads cut the scan with `split` first. + +use std::any::Any; +use std::num::NonZeroUsize; +use std::ops::Range; +use std::sync::Arc; + +use async_channel::Receiver; +use async_channel::Sender; +use futures::FutureExt; +use futures::StreamExt; +use futures::future; +use futures::future::BoxFuture; +use futures::stream; +use futures::stream::BoxStream; +use parking_lot::Mutex; +use tracing::Instrument; +use vortex_array::ArrayRef; +use vortex_array::dtype::DType; +use vortex_array::expr::stats::Precision; +use vortex_array::stream::ArrayStreamAdapter; +use vortex_array::stream::ArrayStreamExt; +use vortex_array::stream::SendableArrayStream; +use vortex_error::VortexResult; +use vortex_scan::DataSourceScanRef; +use vortex_scan::Partition; +use vortex_scan::PartitionRef; +use vortex_scan::PartitionStream; +use vortex_scan::pool::ScanPool; +use vortex_scan::pool::ScanPoolRef; +use vortex_scan::row_mask::RowMask; + +use crate::LayoutReaderRef; +use crate::scan::limit::RowLimit; +use crate::scan::multi::LayoutReaderFactory; +use crate::scan::repeated_scan::RepeatedScan; +use crate::scan::repeated_scan::can_prune_file; +use crate::scan::tasks::TaskContext; + +/// A scan prepared once and shared by every piece and execution of it. +pub(crate) type PreparedScan = RepeatedScan; + +/// A prepared scan and the row ranges of its splits, in row order. +pub(crate) type PlannedSplits = (Arc, Vec>); + +/// The most splits each worker keeps in flight when the request does not say; stands in for the +/// scan engine's memory budget. +const SPLITS_IN_FLIGHT_PER_WORKER: usize = 4; + +/// One execution of one file's prepared scan. +pub(crate) struct FileScan { + scan: Arc, + /// Records this execution's events, so file events count once for each execution. + ctx: Arc, +} + +/// One file's splits for one execution, ready to be handed to workers. +pub(crate) struct FileWork { + scan: Option>, + ranges: Vec>, +} + +impl FileWork { + /// A file with nothing to read, for example one that statistics pruned. + pub(crate) fn empty() -> Self { + Self { + scan: None, + ranges: Vec::new(), + } + } + + /// Starts an execution of `scan` over its split `ranges`. + /// + /// Counts a file scan attempt when the ranges select any row, and returns no work when + /// whole-file statistics reject the filter. + pub(crate) fn start(scan: Arc, ranges: Vec>) -> VortexResult { + if !ranges.iter().any(|range| scan.selects_rows(range)) { + return Ok(Self::empty()); + } + let ctx = scan.task_context(); + if can_prune_file(&ctx)? { + return Ok(Self::empty()); + } + Ok(Self { + scan: Some(Arc::new(FileScan { scan, ctx })), + ranges, + }) + } +} + +/// Opens a deferred file's reader into its work for this execution. +pub(crate) type PrepareFile = Arc VortexResult + Send + Sync>; + +/// A file of a pool, in file order. +pub(crate) enum PoolFile { + Opened(FileWork), + Deferred(Arc), +} + +/// How a pool reads its splits. +pub(crate) struct PoolOptions { + pub(crate) dtype: DType, + pub(crate) ordered: bool, + pub(crate) limit: Option, + /// Whether the scan filters rows, so a split's output row count is unknown up front. + pub(crate) has_filter: bool, + /// The most splits each worker keeps in flight, or the default when `None`. + pub(crate) splits_in_flight: Option, +} + +/// Opens a pool over `files`, in file order. `prepare` turns an opened deferred file into work. +pub(crate) fn open_pool( + options: PoolOptions, + files: Vec, + prepare: Option, +) -> ScanPoolRef { + let limit = match options.limit { + None => PoolLimit::Unlimited, + Some(limit) if options.has_filter => PoolLimit::Trim(RowLimit::new(limit)), + Some(limit) => PoolLimit::Reserve(RowLimit::new(limit)), + }; + let splits_in_flight = options + .splits_in_flight + .map_or(SPLITS_IN_FLIGHT_PER_WORKER, NonZeroUsize::get); + let shared = Arc::new(Shared { + limit, + prepare, + file_share: 1.0 / files.len().max(1) as f64, + progress: Mutex::new(0.0), + }); + if options.ordered { + return Arc::new(OrderedPool { + dtype: options.dtype, + shared, + files: Mutex::new(Some(files)), + splits_in_flight, + }); + } + + let (sender, receiver) = async_channel::unbounded(); + for file in files { + match file { + PoolFile::Opened(work) => { + for (file, range, progress) in shared.file_splits(work) { + send(&sender, Work::Split(file, range, progress)); + } + } + PoolFile::Deferred(factory) => send(&sender, Work::Open(factory, sender.clone())), + } + } + Arc::new(UnorderedPool { + dtype: options.dtype, + shared, + receiver, + splits_in_flight, + }) +} + +/// How a pool's row limit is applied. +enum PoolLimit { + Unlimited, + /// A split's selected rows are its output rows, so each split reserves them from the budget + /// when a worker takes it, and rows past the limit are never decoded. Admission order is + /// row order for an ordered pool, so it returns exactly the first rows. + Reserve(RowLimit), + /// A split's output rows are unknown until its filter has run, so workers take rows from the + /// budget as they yield them and discard the excess. + Trim(RowLimit), +} + +impl PoolLimit { + fn is_exhausted(&self) -> bool { + match self { + PoolLimit::Unlimited => false, + PoolLimit::Reserve(limit) | PoolLimit::Trim(limit) => limit.is_exhausted(), + } + } +} + +/// A split's output: `None` when it has no rows to return. +type SplitFuture = BoxFuture<'static, VortexResult>>; + +/// A split of a file, with the progress that taking it adds. +type FileSplit = (Arc, Range, f64); + +/// What every worker of a pool shares. +struct Shared { + limit: PoolLimit, + prepare: Option, + /// The progress that one file adds. + file_share: f64, + progress: Mutex, +} + +impl Shared { + /// The splits of an opened file, in row order. + fn file_splits(&self, work: FileWork) -> Vec { + let rows: u64 = work + .ranges + .iter() + .map(|range| range.end - range.start) + .sum(); + match work.scan { + Some(scan) if rows > 0 => { + let per_row = self.file_share / rows as f64; + work.ranges + .into_iter() + .map(|range| { + let progress = per_row * (range.end - range.start) as f64; + (Arc::clone(&scan), range, progress) + }) + .collect() + } + _ => { + *self.progress.lock() += self.file_share; + Vec::new() + } + } + } + + /// Opens a deferred file into its work. + fn open_file( + self: &Arc, + factory: Arc, + ) -> BoxFuture<'static, VortexResult> { + let shared = Arc::clone(self); + async move { + let reader = factory + .open() + .instrument(tracing::info_span!("LayoutReaderFactory::open")) + .await?; + match (reader, &shared.prepare) { + (Some(reader), Some(prepare)) => prepare(reader), + _ => Ok(FileWork::empty()), + } + } + .boxed() + } + + /// Takes a split: reserves its rows from a reserved limit and builds its task. + fn admit(&self, (file, range, progress): FileSplit) -> SplitFuture { + *self.progress.lock() += progress; + let Some(mask) = file.scan.split_mask(&range) else { + return future::ready(Ok(None)).boxed(); + }; + let mask = match &self.limit { + PoolLimit::Reserve(limit) => { + let reserved = limit.limit(mask.mask().clone()); + if reserved.all_false() { + return future::ready(Ok(None)).boxed(); + } + RowMask::new(range.start, reserved) + } + PoolLimit::Unlimited | PoolLimit::Trim(_) => mask, + }; + match file.scan.split_task(&file.ctx, mask) { + Ok(task) => task, + Err(err) => future::ready(Err(err)).boxed(), + } + } + + #[expect( + dead_code, + reason = "read by ScanPool::progress, which arrives with its first host" + )] + fn progress(&self) -> f64 { + if self.limit.is_exhausted() { + return 1.0; + } + self.progress.lock().clamp(0.0, 1.0) + } +} + +/// A worker's output: skips splits with no rows, trims to a trimmed limit, and ends after the +/// first error or once a trimmed limit is spent. +fn limit_output( + outputs: BoxStream<'static, VortexResult>>, + shared: Arc, +) -> BoxStream<'static, VortexResult> { + stream::unfold(Some(outputs), move |outputs| { + let shared = Arc::clone(&shared); + async move { + let mut outputs = outputs?; + loop { + if let PoolLimit::Trim(limit) = &shared.limit + && limit.is_exhausted() + { + return None; + } + let array = match outputs.next().await? { + Ok(Some(array)) => array, + Ok(None) => continue, + Err(err) => return Some((Err(err), None)), + }; + let PoolLimit::Trim(limit) = &shared.limit else { + return Some((Ok(array), Some(outputs))); + }; + let granted = limit.take(array.len()); + if granted == 0 { + return None; + } + if granted == array.len() { + return Some((Ok(array), Some(outputs))); + } + return Some((array.slice(0..granted), None)); + } + } + }) + .boxed() +} + +/// A unit of an unordered pool. +enum Work { + Split(Arc, Range, f64), + /// A deferred file, and where to send its splits once it is open. The sender keeps the + /// channel open until the file's splits are in it. + Open(Arc, Sender), +} + +fn send(sender: &Sender, work: Work) { + // The channel is unbounded and closes only once the pool is dropped, when the work is moot. + drop(sender.try_send(work)); +} + +/// A pool whose workers share its units through a channel. +struct UnorderedPool { + dtype: DType, + shared: Arc, + receiver: Receiver, + splits_in_flight: usize, +} + +impl UnorderedPool { + fn run(shared: &Arc, work: Work) -> SplitFuture { + match work { + Work::Split(file, range, progress) => shared.admit((file, range, progress)), + Work::Open(factory, sender) => { + let shared = Arc::clone(shared); + async move { + let work = shared.open_file(factory).await?; + for (file, range, progress) in shared.file_splits(work) { + send(&sender, Work::Split(file, range, progress)); + } + Ok(None) + } + .boxed() + } + } + } +} + +impl ScanPool for UnorderedPool { + fn dtype(&self) -> &DType { + &self.dtype + } + + fn worker(self: Arc) -> SendableArrayStream { + let dtype = self.dtype.clone(); + let shared = Arc::clone(&self.shared); + let runner = Arc::clone(&shared); + let receiver = self.receiver.clone(); + let splits_in_flight = self.splits_in_flight; + // The worker holds the pool, so the pool is dropped only after its last worker. + let outputs = receiver + .take_while(move |_| future::ready(!self.shared.limit.is_exhausted())) + .map(move |work| UnorderedPool::run(&runner, work)) + .buffer_unordered(splits_in_flight) + .boxed(); + ArrayStreamExt::boxed(ArrayStreamAdapter::new( + dtype, + limit_output(outputs, shared), + )) + } +} + +impl Drop for UnorderedPool { + fn drop(&mut self) { + // Pending opens hold senders of the channel itself; drain them so it can be freed. + self.receiver.close(); + while self.receiver.try_recv().is_ok() {} + } +} + +/// A pool that gives all of its units, in row order, to its first worker. +struct OrderedPool { + dtype: DType, + shared: Arc, + /// The files, until the first worker takes them. + files: Mutex>>, + splits_in_flight: usize, +} + +impl ScanPool for OrderedPool { + fn dtype(&self) -> &DType { + &self.dtype + } + + fn worker(self: Arc) -> SendableArrayStream { + let dtype = self.dtype.clone(); + let Some(files) = self.files.lock().take() else { + return ArrayStreamExt::boxed(ArrayStreamAdapter::new(dtype, stream::empty())); + }; + let shared = Arc::clone(&self.shared); + let opener = Arc::clone(&shared); + let splitter = Arc::clone(&shared); + let admitter = Arc::clone(&shared); + let outputs = stream::iter(files) + .then(move |file| match file { + PoolFile::Opened(work) => future::ready(Ok(work)).boxed(), + PoolFile::Deferred(factory) => opener.open_file(factory), + }) + .flat_map(move |work| match work { + Ok(work) => { + stream::iter(splitter.file_splits(work).into_iter().map(Ok)).left_stream() + } + Err(err) => stream::once(future::ready(Err(err))).right_stream(), + }) + .take_while(move |_| future::ready(!shared.limit.is_exhausted())) + .map(move |split| match split { + Ok(split) => admitter.admit(split), + Err(err) => future::ready(Err(err)).boxed(), + }) + .buffered(self.splits_in_flight) + .boxed(); + ArrayStreamExt::boxed(ArrayStreamAdapter::new( + dtype, + limit_output(outputs, Arc::clone(&self.shared)), + )) + } +} + +/// The single partition of a scan piece that is read through the partitions API: it opens the +/// piece and reads it with one worker. +pub(crate) struct PiecePartition { + piece: DataSourceScanRef, + index: usize, +} + +impl PiecePartition { + /// The partitions of `piece`: one, whose index is `index`. + pub(crate) fn stream(piece: DataSourceScanRef, index: usize) -> PartitionStream { + stream::iter([Ok(Box::new(PiecePartition { piece, index }) as PartitionRef)]).boxed() + } +} + +impl Partition for PiecePartition { + fn as_any(&self) -> &dyn Any { + self + } + + fn index(&self) -> usize { + self.index + } + + fn row_count(&self) -> Precision { + self.piece.row_count() + } + + fn byte_size(&self) -> Precision { + self.piece.byte_size() + } + + fn execute(self: Box) -> VortexResult { + Ok(self.piece.open()?.worker()) + } +} diff --git a/vortex-layout/src/scan/repeated_scan.rs b/vortex-layout/src/scan/repeated_scan.rs index 2a1c7026923..dcd4cba58c8 100644 --- a/vortex-layout/src/scan/repeated_scan.rs +++ b/vortex-layout/src/scan/repeated_scan.rs @@ -175,7 +175,7 @@ impl RepeatedScan { } /// Each execution gets its own recorder, so file events count once for each execution. - fn task_context(&self) -> Arc { + pub(crate) fn task_context(&self) -> Arc { Arc::new(TaskContext { filter: self .filter @@ -188,7 +188,10 @@ impl RepeatedScan { }) } - fn split_ranges(&self, row_range: Option>) -> Vec> { + /// The row ranges of the scan's splits within `row_range`, in row order. + /// + /// Ranges whose rows the selection excludes are included; [`Self::split_mask`] skips them. + pub(crate) fn split_ranges(&self, row_range: Option>) -> Vec> { let selection_range: Option> = match &self.selection { Selection::IncludeByIndex(buf) if !buf.is_empty() => { Some(buf[0]..buf[buf.len() - 1] + 1) @@ -244,6 +247,33 @@ impl RepeatedScan { } } + /// Whether the selection includes any row of `range`. + pub(crate) fn selects_rows(&self, range: &Range) -> bool { + self.selection.row_count_in_range(range) != 0 + } + + /// The number of rows of `range` that the selection includes. + pub(crate) fn selected_row_count(&self, range: &Range) -> u64 { + self.selection.row_count_in_range(range) + } + + /// The selected rows of the split over `range`, or `None` if the selection excludes them all. + pub(crate) fn split_mask(&self, range: &Range) -> Option { + selected_mask(&self.selection, range) + } + + /// Builds the task of one split. The task does no work until it is polled, but building it + /// may register the split's reads with the reader, so build it only when it is about to run. + /// + /// `mask` must select at least one row. + pub(crate) fn split_task( + &self, + ctx: &Arc, + mask: RowMask, + ) -> VortexResult>>> { + Ok(map_split(split_exec(ctx, mask)?, &self.map_fn)) + } + /// The non-empty row masks of the splits within `row_range`, in split order. fn split_masks(&self, row_range: Option>) -> impl Iterator + '_ { self.split_ranges(row_range) @@ -362,7 +392,8 @@ fn selected_mask(selection: &Selection, range: &Range) -> Option { (!mask.mask().all_false()).then_some(mask) } -fn can_prune_file(ctx: &TaskContext) -> VortexResult { +/// Counts a file scan attempt and returns whether whole-file statistics reject the filter. +pub(crate) fn can_prune_file(ctx: &TaskContext) -> VortexResult { ctx.count::(ScanRecorder::attempt_file_scan); if let Some(filter) = &ctx.filter && can_prune_conjuncts(filter, ctx.reader.as_ref())? diff --git a/vortex-layout/src/scan/test.rs b/vortex-layout/src/scan/test.rs index 85c4b25d8b1..41c9ce19e1e 100644 --- a/vortex-layout/src/scan/test.rs +++ b/vortex-layout/src/scan/test.rs @@ -27,6 +27,7 @@ use vortex_io::runtime::single::SingleThreadRuntime; use vortex_io::session::RuntimeSession; use vortex_io::session::RuntimeSessionExt; use vortex_mask::Mask; +use vortex_scan::pool::ScanPoolRef; use vortex_session::VortexSession; use crate::ArrayFuture; @@ -70,6 +71,7 @@ pub struct TestLayoutReader { projection_masks: Option>>>, filter_exprs: Option>>>, in_flight: Option>, + yields: fn(u64) -> usize, } /// Counts projections running at once, and the most that ever were. @@ -101,6 +103,7 @@ impl TestLayoutReader { projection_masks: None, filter_exprs: None, in_flight: None, + yields: |_| 0, } } @@ -137,6 +140,13 @@ impl TestLayoutReader { self } + /// Makes the projection of the split starting at row `start` yield `yields(start)` times + /// before it finishes, so tests can make splits complete out of row order. + pub fn with_yields(mut self, yields: fn(u64) -> usize) -> Self { + self.yields = yields; + self + } + pub fn with_filter_exprs(mut self, filter_exprs: Arc>>) -> Self { self.filter_exprs = Some(filter_exprs); self @@ -261,8 +271,12 @@ impl LayoutReader for TestLayoutReader { let projection_masks = self.projection_masks.clone(); let fail = self.fail_projection || (self.fail_first_projection && row_range.start == 0); let in_flight = self.in_flight.clone(); + let yields = (self.yields)(row_range.start); Ok(Box::pin(async move { + for _ in 0..yields { + tokio::task::yield_now().await; + } if let Some(in_flight) = &in_flight { let now = in_flight.now.fetch_add(1, Ordering::SeqCst) + 1; in_flight.peak.fetch_max(now, Ordering::SeqCst); @@ -313,6 +327,28 @@ where Ok(values) } +/// Reads `pool` with `workers` workers, each polled on its own thread, returning each worker's +/// values in the order it yielded them. +pub fn read_with_workers(pool: &ScanPoolRef, workers: usize) -> VortexResult>> { + std::thread::scope(|scope| { + let handles = (0..workers) + .map(|_| { + let worker = Arc::clone(pool).worker(); + scope.spawn(move || collect_scan_values(futures::executor::block_on_stream(worker))) + }) + .collect::>(); + handles + .into_iter() + .map(|handle| handle.join().expect("worker thread panicked")) + .collect() + }) +} + +/// Reads `pool` with a single worker polled on the calling thread. +pub fn read_with_one_worker(pool: ScanPoolRef) -> VortexResult> { + collect_scan_values(futures::executor::block_on_stream(pool.worker())) +} + /// Let already-spawned scan tasks run to completion after the stream has been dropped. pub fn drain_runtime(runtime: &SingleThreadRuntime) { for _ in 0..4 { From d300a84cd3ad7416f0cb111c5a16e5586046a7a2 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Thu, 19 Nov 2026 18:30:06 -0500 Subject: [PATCH 12/80] Spawn pool splits onto the session runtime Decoding a split inline kept each worker's splits on its own thread. Spawning them onto the session's runtime, as V1 scans do, lets idle runtime threads decode them and starts their I/O at once. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-layout/src/scan/pool.rs | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/vortex-layout/src/scan/pool.rs b/vortex-layout/src/scan/pool.rs index fcfea905b7a..c5f09310d45 100644 --- a/vortex-layout/src/scan/pool.rs +++ b/vortex-layout/src/scan/pool.rs @@ -4,9 +4,8 @@ //! The work that the workers of an opened layout scan share. //! //! A pool's units are the splits of one or more files, and the files not yet opened. A worker -//! takes units and keeps up to `splits_in_flight` of them running on its own thread: it -//! builds a split's task only when it takes the split, and never spawns. Opening a deferred file -//! is a unit like any other. +//! takes units and keeps up to `splits_in_flight` of them in flight, each spawned onto the +//! session's runtime when the worker takes it. Opening a deferred file is a unit like any other. //! //! - An unordered pool hands units out through a channel. The worker that opens a deferred file //! sends the file's splits back into the channel, where any worker can take them. The channel @@ -36,6 +35,7 @@ use vortex_array::stream::ArrayStreamAdapter; use vortex_array::stream::ArrayStreamExt; use vortex_array::stream::SendableArrayStream; use vortex_error::VortexResult; +use vortex_io::session::RuntimeSessionExt; use vortex_scan::DataSourceScanRef; use vortex_scan::Partition; use vortex_scan::PartitionRef; @@ -251,7 +251,7 @@ impl Shared { .boxed() } - /// Takes a split: reserves its rows from a reserved limit and builds its task. + /// Takes a split: reserves its rows from a reserved limit and spawns its task. fn admit(&self, (file, range, progress): FileSplit) -> SplitFuture { *self.progress.lock() += progress; let Some(mask) = file.scan.split_mask(&range) else { @@ -267,10 +267,12 @@ impl Shared { } PoolLimit::Unlimited | PoolLimit::Trim(_) => mask, }; - match file.scan.split_task(&file.ctx, mask) { - Ok(task) => task, - Err(err) => future::ready(Err(err)).boxed(), - } + // Spawned onto the session's runtime, as V1 scans do: another runtime thread may decode + // it while this worker drives its other splits, and its I/O starts right away. + let handle = file.ctx.session.handle(); + handle + .spawn(async move { file.scan.split_task(&file.ctx, mask)?.await }) + .boxed() } #[expect( From f1bf5cfd552566d0a0d63c0d9b619e7b3d48cffb Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Thu, 19 Nov 2026 18:58:00 -0500 Subject: [PATCH 13/80] Drive layout pool tests with a background runtime Pool splits are spawned onto the session runtime, so the test session needs a runtime that runs them while test workers block on their streams. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-layout/src/scan/layout.rs | 4 +++- vortex-layout/src/scan/multi.rs | 3 ++- vortex-layout/src/scan/test.rs | 12 ++++++++++++ 3 files changed, 17 insertions(+), 2 deletions(-) diff --git a/vortex-layout/src/scan/layout.rs b/vortex-layout/src/scan/layout.rs index 926ea7cc8e8..0413edff9c6 100644 --- a/vortex-layout/src/scan/layout.rs +++ b/vortex-layout/src/scan/layout.rs @@ -1071,7 +1071,9 @@ mod pool_tests { let mut values = Vec::new(); for piece in pieces { - let piece_values = read_with_one_worker(piece.open()?)?; + // The scan is unordered, so a piece's splits may finish in any order. + let mut piece_values = read_with_one_worker(piece.open()?)?; + piece_values.sort_unstable(); let first = *piece_values.first().expect("pieces are not empty"); let last = *piece_values.last().expect("pieces are not empty"); assert_eq!(first % 3, 0, "piece starts on a split boundary"); diff --git a/vortex-layout/src/scan/multi.rs b/vortex-layout/src/scan/multi.rs index be41497e0ad..5acaa3a9063 100644 --- a/vortex-layout/src/scan/multi.rs +++ b/vortex-layout/src/scan/multi.rs @@ -1296,7 +1296,8 @@ mod pool_tests { assert!(poll_worker(&mut waiter, &mut flagged).is_pending()); gates[0].release(); - let Poll::Ready(Some(first)) = poll_worker(&mut opener, &mut noop) else { + // The opener's split runs on the session runtime, so wait for it rather than polling once. + let Some(first) = futures::executor::block_on(opener.next()) else { panic!("the opener reads a split of the file it opened"); }; assert!(flag.0.load(Ordering::SeqCst), "the waiter is woken"); diff --git a/vortex-layout/src/scan/test.rs b/vortex-layout/src/scan/test.rs index 41c9ce19e1e..3e0b70465e6 100644 --- a/vortex-layout/src/scan/test.rs +++ b/vortex-layout/src/scan/test.rs @@ -23,6 +23,8 @@ use vortex_error::VortexResult; use vortex_error::vortex_err; use vortex_io::runtime::BlockingRuntime; use vortex_io::runtime::Handle; +use vortex_io::runtime::current::CurrentThreadRuntime; +use vortex_io::runtime::current::CurrentThreadWorkerPool; use vortex_io::runtime::single::SingleThreadRuntime; use vortex_io::session::RuntimeSession; use vortex_io::session::RuntimeSessionExt; @@ -38,10 +40,20 @@ use crate::session::LayoutSession; static SESSION: LazyLock = LazyLock::new(VortexSession::empty); +/// A runtime driven by background threads, so splits the pools spawn make progress while test +/// workers block on their streams with `futures::executor`. +static RUNTIME: LazyLock<(CurrentThreadRuntime, CurrentThreadWorkerPool)> = LazyLock::new(|| { + let runtime = CurrentThreadRuntime::new(); + let pool = runtime.new_pool(); + pool.set_workers(4); + (runtime, pool) +}); + pub fn new_session() -> VortexSession { VortexSession::empty() .with::() .with::() + .with_handle(RUNTIME.0.handle()) } pub fn session_with_handle(handle: Handle) -> VortexSession { From d10623da315dd2f044c978c357bc53b115fb8143 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Thu, 19 Nov 2026 19:09:33 -0500 Subject: [PATCH 14/80] Run pool splits the way execute_stream runs them A benchmark of the pool should measure the pool, not a different way of running splits. Pools now build a file's split tasks all at once when a worker first takes one, so the file's reads register together and coalesce, as execute_stream builds a partition's tasks up front. Scans with a filter and a limit build each split lazily on a CPU task and optimize the trimmed output on a second one, through the same helpers execute_stream now uses. A worker keeps as many splits in flight as one partition stream does by default (four per core, capped by split_concurrency), so a host with a worker per core matches the partitions path's in-flight total. Deferred files open on the session runtime, at most the source's open concurrency at once, in both pool kinds. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-layout/src/scan/layout.rs | 92 +++++- vortex-layout/src/scan/multi.rs | 82 +++++- vortex-layout/src/scan/pool.rs | 358 +++++++++++++++++------- vortex-layout/src/scan/repeated_scan.rs | 68 +++-- vortex-layout/src/scan/scan_builder.rs | 5 +- vortex-layout/src/scan/test.rs | 11 + 6 files changed, 481 insertions(+), 135 deletions(-) diff --git a/vortex-layout/src/scan/layout.rs b/vortex-layout/src/scan/layout.rs index 0413edff9c6..38f801fd9a9 100644 --- a/vortex-layout/src/scan/layout.rs +++ b/vortex-layout/src/scan/layout.rs @@ -57,7 +57,7 @@ use crate::scan::scan_builder::ScanBuilder; /// /// When a scan is [split](DataSourceScan::split) or [opened](DataSourceScan::open), its units are /// the layout's splits. Workers of an opened scan share them, each keeping several in flight on -/// its own thread. +/// the session's runtime. pub struct LayoutReaderDataSource { reader: LayoutReaderRef, session: VortexSession, @@ -258,11 +258,12 @@ impl LayoutReaderScan { fn into_split_scan(self) -> VortexResult { let row_count = DataSourceScan::row_count(&self); let options = LayoutScanOptions { + session: self.session.clone(), dtype: self.dtype, ordered: self.ordered, limit: self.limit, has_filter: self.filter.is_some(), - splits_in_flight: self.split_concurrency, + split_concurrency: self.split_concurrency, }; let row_range = clamp_row_range(self.next_row..self.end_row, self.reader.row_count()); let scan = ScanBuilder::new(self.session, self.reader) @@ -331,11 +332,12 @@ fn clamp_row_range(row_range: Range, total_rows: u64) -> Range { /// What a [`LayoutSplitScan`] and every piece cut from it share. #[derive(Clone)] struct LayoutScanOptions { + session: VortexSession, dtype: DType, ordered: bool, limit: Option, has_filter: bool, - splits_in_flight: Option, + split_concurrency: Option, } /// A prepared scan of one layout reader over some of its splits: a [`LayoutReaderScan`] that was @@ -413,22 +415,26 @@ impl DataSourceScan for LayoutSplitScan { fn open(self: Box) -> VortexResult { let LayoutScanOptions { + session, dtype, ordered, limit, has_filter, - splits_in_flight, + split_concurrency, } = self.options; if limit == Some(0) { return Box::new(Empty::new(dtype, 0)).open(); } let work = FileWork::start(self.scan, self.ranges)?; let options = PoolOptions { + session, dtype, ordered, limit, has_filter, - splits_in_flight, + split_concurrency, + // A single opened file has nothing to open. + open_concurrency: 1, }; Ok(open_pool(options, vec![PoolFile::Opened(work)], None)) } @@ -838,7 +844,10 @@ mod tests { mod pool_tests { use std::num::NonZeroUsize; use std::sync::Arc; + use std::sync::atomic::AtomicUsize; + use std::sync::atomic::Ordering; + use futures::StreamExt; use rstest::rstest; use vortex_array::dtype::DType; use vortex_array::dtype::Nullability; @@ -987,6 +996,79 @@ mod pool_tests { Ok(()) } + /// Split tasks are built as `execute_stream` builds them: all of a file's at once, so their + /// reads are registered together, when a worker takes its first split; but one at a time, as + /// workers take them, when the scan has both a filter and a limit. + #[rstest] + #[case::unfiltered(None, None, true)] + #[case::filtered(Some(root()), None, true)] + #[case::limited(None, Some(1000), true)] + #[case::filtered_and_limited(Some(root()), Some(1000), false)] + fn split_tasks_build_like_execute_stream( + #[case] filter: Option, + #[case] limit: Option, + #[case] up_front: bool, + ) -> VortexResult<()> { + let built = Arc::new(AtomicUsize::new(0)); + let source = source( + TestLayoutReader::new(16) + .with_split_size(1) + .with_built_projections(Arc::clone(&built)), + ); + let pool = plan( + &source, + ScanRequest { + filter, + limit, + split_concurrency: NonZeroUsize::new(1), + ..Default::default() + }, + )? + .open()?; + let mut worker = Arc::clone(&pool).worker(); + assert!(futures::executor::block_on(worker.next()).is_some()); + let built_after_first = built.load(Ordering::SeqCst); + if up_front { + assert_eq!(built_after_first, 16); + } else { + assert!( + built_after_first < 16, + "built {built_after_first} splits up front" + ); + } + + let rest = collect_scan_values(futures::executor::block_on_stream(worker))?; + assert_eq!(rest.len(), 15); + assert_eq!(built.load(Ordering::SeqCst), 16); + Ok(()) + } + + /// A pool reports the share of its splits that workers have taken, and is exhausted once + /// none are left to take. + #[rstest] + #[case::ordered(true)] + #[case::unordered(false)] + fn pools_report_progress_and_exhaustion(#[case] ordered: bool) -> VortexResult<()> { + let source = source(TestLayoutReader::new(8).with_split_size(2)); + let pool = plan( + &source, + ScanRequest { + ordered, + ..Default::default() + }, + )? + .open()?; + assert_eq!(pool.progress(), 0.0); + assert!(!pool.is_exhausted()); + + let values = read_with_one_worker(Arc::clone(&pool))?; + assert_eq!(values.len(), 8); + assert_eq!(pool.progress(), 1.0); + assert!(pool.is_exhausted()); + assert!(read_with_one_worker(pool)?.is_empty()); + Ok(()) + } + /// An ordered pool with a limit returns exactly the first `limit` rows. #[rstest] #[case::reserved(false, &[0, 1, 2, 3, 4])] diff --git a/vortex-layout/src/scan/multi.rs b/vortex-layout/src/scan/multi.rs index 5acaa3a9063..0ae1db43e65 100644 --- a/vortex-layout/src/scan/multi.rs +++ b/vortex-layout/src/scan/multi.rs @@ -221,8 +221,8 @@ impl MultiLayoutDataSource { /// Sets the concurrency for opening deferred readers. /// - /// Controls how many file opens run in parallel via `buffer_unordered`. - /// Defaults to the number of available CPU cores. + /// Controls how many file opens run in parallel, on the partitions path and in an opened + /// scan's pool alike. Defaults to the number of available CPU cores. pub fn with_concurrency(mut self, concurrency: usize) -> Self { self.concurrency = concurrency; self @@ -424,6 +424,7 @@ impl MultiLayoutScan { source_dtype: self.source_dtype, dtype: self.dtype, request: self.request, + open_concurrency: self.concurrency, }), children, index: 0, @@ -736,6 +737,8 @@ struct ScanContext { source_dtype: DType, dtype: DType, request: BoundScanRequest, + /// The most deferred files that are opened at once. + open_concurrency: usize, } impl ScanContext { @@ -957,11 +960,13 @@ impl DataSourceScan for MultiLayoutSplitScan { } let options = PoolOptions { + session: context.session.clone(), dtype: context.dtype.clone(), ordered: request.ordered, limit: request.limit, has_filter: request.has_filter(), - splits_in_flight: request.split_concurrency, + split_concurrency: request.split_concurrency, + open_concurrency: context.open_concurrency, }; let prepare: PrepareFile = Arc::new(move |reader| context.start_file(reader)); Ok(open_pool(options, files, Some(prepare))) @@ -1277,12 +1282,81 @@ mod pool_tests { worker.poll_next_unpin(cx) } + /// An unordered pool opens at most the source's open concurrency of deferred files at once, + /// however many workers are waiting for splits. + #[test] + fn deferred_opens_are_bounded() -> VortexResult<()> { + let opens = Arc::new(AtomicUsize::new(0)); + let gates: Vec<_> = (0..6).map(|_| Arc::new(Gate::default())).collect(); + let factories = gates + .iter() + .enumerate() + .map(|(index, gate)| { + let base = 100 * i32::try_from(index).expect("few files"); + Arc::new(GatedFactory { + reader: Arc::new(TestLayoutReader::new(4).with_split_size(1).with_base(base)), + gate: Arc::clone(gate), + opens: Arc::clone(&opens), + }) as Arc + }) + .collect(); + let source = + MultiLayoutDataSource::new_deferred(i32_dtype(), factories, vec![], &new_session()) + .with_concurrency(2); + let pool = plan(&source, ScanRequest::default())?.open()?; + let mut workers: Vec<_> = (0..4).map(|_| Arc::clone(&pool).worker()).collect(); + let mut noop = Context::from_waker(noop_waker_ref()); + for worker in &mut workers { + assert!(poll_worker(worker, &mut noop).is_pending()); + } + // Opens run on the session's runtime; give them time to start. + for _ in 0..200 { + if opens.load(Ordering::SeqCst) >= 2 { + break; + } + std::thread::sleep(std::time::Duration::from_millis(1)); + } + std::thread::sleep(std::time::Duration::from_millis(20)); + assert_eq!(opens.load(Ordering::SeqCst), 2); + + for gate in &gates { + gate.release(); + } + let mut values = std::thread::scope(|scope| { + let handles: Vec<_> = workers + .into_iter() + .map(|worker| { + scope.spawn(move || { + collect_scan_values(futures::executor::block_on_stream(worker)) + }) + }) + .collect(); + handles + .into_iter() + .map(|handle| handle.join().expect("worker thread panicked")) + .collect::>>() + })? + .concat(); + values.sort_unstable(); + let expected: Vec = (0..6) + .flat_map(|file| (0..4).map(move |row| 100 * file + row)) + .collect(); + assert_eq!(values, expected); + assert_eq!(opens.load(Ordering::SeqCst), 6); + Ok(()) + } + /// A deferred file is opened by a worker, and its splits are shared with other workers. A /// worker that finds only an open in progress waits, and is woken when the open adds splits. #[test] fn deferred_file_splits_are_shared_with_waiting_workers() -> VortexResult<()> { let (source, gates) = gated_source(1, 16); - let pool = plan(&source, ScanRequest::default())?.open()?; + // Each worker holds at most two splits, so the opener leaves splits for the waiter. + let request = ScanRequest { + split_concurrency: NonZeroUsize::new(2), + ..Default::default() + }; + let pool = plan(&source, request)?.open()?; let mut opener = Arc::clone(&pool).worker(); let mut waiter = Arc::clone(&pool).worker(); let mut noop = Context::from_waker(noop_waker_ref()); diff --git a/vortex-layout/src/scan/pool.rs b/vortex-layout/src/scan/pool.rs index c5f09310d45..f0094a6e16a 100644 --- a/vortex-layout/src/scan/pool.rs +++ b/vortex-layout/src/scan/pool.rs @@ -4,22 +4,37 @@ //! The work that the workers of an opened layout scan share. //! //! A pool's units are the splits of one or more files, and the files not yet opened. A worker -//! takes units and keeps up to `splits_in_flight` of them in flight, each spawned onto the -//! session's runtime when the worker takes it. Opening a deferred file is a unit like any other. +//! takes units and keeps several splits in flight, each spawned onto the session's runtime; it +//! never starts threads of its own. Opening a deferred file is a unit like any other, and at most +//! `open_concurrency` opens are queued or running at once. +//! +//! Splits run as [`RepeatedScan::execute_stream`] runs them: +//! +//! - A scan with a filter and a limit builds each split on a CPU thread only once a worker takes +//! it ([`spawn_lazy_split`]), so no new split starts once the limit is spent, and optimizes the +//! rows the limit keeps on a second CPU task ([`spawn_map_trimmed`]). +//! - Every other scan builds all of a file's split tasks together, when a worker first takes one +//! of them, so the file's reads are registered at once and can coalesce. A limit is reserved +//! then, in split order. +//! +//! The pools differ in how workers share units: //! //! - An unordered pool hands units out through a channel. The worker that opens a deferred file -//! sends the file's splits back into the channel, where any worker can take them. The channel -//! closes once every open has finished, which ends the workers. +//! sends the file's splits back into the channel, where any worker can take them, followed by +//! the next deferred file. The channel closes once every open has finished, which ends the +//! workers. //! - An ordered pool gives all of its units, in row order, to its first worker; later workers //! get nothing. Parallel ordered reads cut the scan with `split` first. use std::any::Any; +use std::collections::VecDeque; use std::num::NonZeroUsize; use std::ops::Range; use std::sync::Arc; use async_channel::Receiver; use async_channel::Sender; +use async_lock::OnceCell; use futures::FutureExt; use futures::StreamExt; use futures::future; @@ -43,13 +58,22 @@ use vortex_scan::PartitionStream; use vortex_scan::pool::ScanPool; use vortex_scan::pool::ScanPoolRef; use vortex_scan::row_mask::RowMask; +use vortex_session::VortexSession; use crate::LayoutReaderRef; use crate::scan::limit::RowLimit; use crate::scan::multi::LayoutReaderFactory; +use crate::scan::repeated_scan::DEFAULT_SPLITS_PER_THREAD; +use crate::scan::repeated_scan::MapFn; use crate::scan::repeated_scan::RepeatedScan; +use crate::scan::repeated_scan::SplitConcurrency; use crate::scan::repeated_scan::can_prune_file; +use crate::scan::repeated_scan::spawn_lazy_split; +use crate::scan::repeated_scan::spawn_map_trimmed; +use crate::scan::repeated_scan::stop_on_error; +use crate::scan::tasks::SplitFuture; use crate::scan::tasks::TaskContext; +use crate::scan::tasks::split_exec; /// A scan prepared once and shared by every piece and execution of it. pub(crate) type PreparedScan = RepeatedScan; @@ -57,30 +81,60 @@ pub(crate) type PreparedScan = RepeatedScan; /// A prepared scan and the row ranges of its splits, in row order. pub(crate) type PlannedSplits = (Arc, Vec>); -/// The most splits each worker keeps in flight when the request does not say; stands in for the -/// scan engine's memory budget. -const SPLITS_IN_FLIGHT_PER_WORKER: usize = 4; - -/// One execution of one file's prepared scan. +/// One execution of one file's prepared scan over some of its splits. pub(crate) struct FileScan { scan: Arc, /// Records this execution's events, so file events count once for each execution. ctx: Arc, + /// The row ranges of the splits, in row order. + ranges: Vec>, + /// The task of each split, built together when a worker first takes one of them. `None` + /// where the split has no rows to read, or a worker has taken it. + tasks: OnceCell>>>, +} + +impl FileScan { + /// The tasks of the file's splits, built on first use. A file whose tasks are built once a + /// reserved limit is spent builds none. + async fn tasks(&self, limit: &PoolLimit) -> VortexResult<&[Mutex>]> { + let tasks = self + .tasks + .get_or_try_init(|| future::ready(self.build_tasks(limit))) + .await?; + Ok(tasks) + } + + /// Builds every split's task, which registers its reads, reserving a reserved limit in split + /// order. + fn build_tasks(&self, limit: &PoolLimit) -> VortexResult>>> { + self.ranges + .iter() + .map(|range| { + let mask = self.scan.split_mask(range).and_then(|mask| match limit { + PoolLimit::Reserve(limit) => { + let reserved = limit.limit(mask.mask().clone()); + (!reserved.all_false()).then(|| RowMask::new(range.start, reserved)) + } + PoolLimit::Unlimited | PoolLimit::Trim(_) => Some(mask), + }); + let task = mask + .map(|mask| self.scan.split_task(&self.ctx, mask)) + .transpose()?; + Ok(Mutex::new(task)) + }) + .collect() + } } /// One file's splits for one execution, ready to be handed to workers. pub(crate) struct FileWork { - scan: Option>, - ranges: Vec>, + file: Option>, } impl FileWork { /// A file with nothing to read, for example one that statistics pruned. pub(crate) fn empty() -> Self { - Self { - scan: None, - ranges: Vec::new(), - } + Self { file: None } } /// Starts an execution of `scan` over its split `ranges`. @@ -96,8 +150,12 @@ impl FileWork { return Ok(Self::empty()); } Ok(Self { - scan: Some(Arc::new(FileScan { scan, ctx })), - ranges, + file: Some(Arc::new(FileScan { + scan, + ctx, + ranges, + tasks: OnceCell::new(), + })), }) } } @@ -113,13 +171,16 @@ pub(crate) enum PoolFile { /// How a pool reads its splits. pub(crate) struct PoolOptions { + pub(crate) session: VortexSession, pub(crate) dtype: DType, pub(crate) ordered: bool, pub(crate) limit: Option, /// Whether the scan filters rows, so a split's output row count is unknown up front. pub(crate) has_filter: bool, - /// The most splits each worker keeps in flight, or the default when `None`. - pub(crate) splits_in_flight: Option, + /// The request's bound on the splits each worker keeps in flight. + pub(crate) split_concurrency: Option, + /// The most deferred files that are queued or being opened at once. + pub(crate) open_concurrency: usize, } /// Opens a pool over `files`, in file order. `prepare` turns an opened deferred file into work. @@ -133,14 +194,26 @@ pub(crate) fn open_pool( Some(limit) if options.has_filter => PoolLimit::Trim(RowLimit::new(limit)), Some(limit) => PoolLimit::Reserve(RowLimit::new(limit)), }; - let splits_in_flight = options - .splits_in_flight - .map_or(SPLITS_IN_FLIGHT_PER_WORKER, NonZeroUsize::get); + // A worker takes the place of a partition that one host thread drains, so it keeps as many + // splits in flight as a partition's stream does by default: four per core, at most the + // request's `split_concurrency`. A host with a worker per core therefore has the in-flight + // total of the partitions path, where each of DuckDB's threads drained one file's partition + // and each of DataFusion's `target_partitions` streams drained one partition, each with up to + // `4 × cores` splits in flight. + let splits_in_flight = SplitConcurrency { + per_worker: DEFAULT_SPLITS_PER_THREAD, + max: options.split_concurrency, + } + .splits_in_flight() + .max(1); + let open_concurrency = options.open_concurrency.max(1); let shared = Arc::new(Shared { limit, prepare, + session: options.session, file_share: 1.0 / files.len().max(1) as f64, progress: Mutex::new(0.0), + deferred: Mutex::new(VecDeque::new()), }); if options.ordered { return Arc::new(OrderedPool { @@ -148,18 +221,24 @@ pub(crate) fn open_pool( shared, files: Mutex::new(Some(files)), splits_in_flight, + open_concurrency, }); } let (sender, receiver) = async_channel::unbounded(); + let mut opens = 0; for file in files { match file { PoolFile::Opened(work) => { - for (file, range, progress) in shared.file_splits(work) { - send(&sender, Work::Split(file, range, progress)); + for split in shared.file_splits(work) { + send(&sender, Work::Split(split)); } } - PoolFile::Deferred(factory) => send(&sender, Work::Open(factory, sender.clone())), + PoolFile::Deferred(factory) if opens < open_concurrency => { + opens += 1; + send(&sender, Work::Open(factory, sender.clone())); + } + PoolFile::Deferred(factory) => shared.deferred.lock().push_back(factory), } } Arc::new(UnorderedPool { @@ -173,9 +252,9 @@ pub(crate) fn open_pool( /// How a pool's row limit is applied. enum PoolLimit { Unlimited, - /// A split's selected rows are its output rows, so each split reserves them from the budget - /// when a worker takes it, and rows past the limit are never decoded. Admission order is - /// row order for an ordered pool, so it returns exactly the first rows. + /// A split's selected rows are its output rows, so a file reserves its splits' rows from the + /// budget in split order when it builds their tasks, and rows past the limit are never + /// decoded. Files build in row order in an ordered pool, so it returns exactly the first rows. Reserve(RowLimit), /// A split's output rows are unknown until its filter has run, so workers take rows from the /// budget as they yield them and discard the excess. @@ -183,112 +262,160 @@ enum PoolLimit { } impl PoolLimit { - fn is_exhausted(&self) -> bool { + /// Whether the budget is spent, so no file that has not started has rows to return. + fn is_spent(&self) -> bool { match self { PoolLimit::Unlimited => false, PoolLimit::Reserve(limit) | PoolLimit::Trim(limit) => limit.is_exhausted(), } } + + /// Whether a trimmed budget is spent, so workers end without returning any more rows. + fn is_trimmed_out(&self) -> bool { + matches!(self, PoolLimit::Trim(limit) if limit.is_exhausted()) + } } /// A split's output: `None` when it has no rows to return. -type SplitFuture = BoxFuture<'static, VortexResult>>; +type SplitOutput = BoxFuture<'static, VortexResult>>; -/// A split of a file, with the progress that taking it adds. -type FileSplit = (Arc, Range, f64); +/// A split of a file by its index, with the progress that taking it adds. +type FileSplit = (Arc, usize, f64); /// What every worker of a pool shares. struct Shared { limit: PoolLimit, prepare: Option, + /// The session whose runtime runs the pool's splits and opens. + session: VortexSession, /// The progress that one file adds. file_share: f64, progress: Mutex, + /// An unordered pool's deferred files that are not yet queued for opening, in file order. + deferred: Mutex>>, } impl Shared { /// The splits of an opened file, in row order. fn file_splits(&self, work: FileWork) -> Vec { - let rows: u64 = work + let Some(file) = work.file else { + *self.progress.lock() += self.file_share; + return Vec::new(); + }; + let rows: u64 = file .ranges .iter() .map(|range| range.end - range.start) .sum(); - match work.scan { - Some(scan) if rows > 0 => { - let per_row = self.file_share / rows as f64; - work.ranges - .into_iter() - .map(|range| { - let progress = per_row * (range.end - range.start) as f64; - (Arc::clone(&scan), range, progress) - }) - .collect() - } - _ => { - *self.progress.lock() += self.file_share; - Vec::new() - } + if rows == 0 { + *self.progress.lock() += self.file_share; + return Vec::new(); } + let per_row = self.file_share / rows as f64; + (0..file.ranges.len()) + .map(|index| { + let range = &file.ranges[index]; + let progress = per_row * (range.end - range.start) as f64; + (Arc::clone(&file), index, progress) + }) + .collect() } - /// Opens a deferred file into its work. + /// Opens a deferred file into its work on the session's runtime. A file that starts after + /// the limit is spent is not opened. fn open_file( self: &Arc, factory: Arc, ) -> BoxFuture<'static, VortexResult> { + if self.limit.is_spent() { + return future::ready(Ok(FileWork::empty())).boxed(); + } let shared = Arc::clone(self); - async move { - let reader = factory - .open() - .instrument(tracing::info_span!("LayoutReaderFactory::open")) - .await?; - match (reader, &shared.prepare) { - (Some(reader), Some(prepare)) => prepare(reader), - _ => Ok(FileWork::empty()), - } + self.session + .handle() + .spawn(async move { + let reader = factory + .open() + .instrument(tracing::info_span!("LayoutReaderFactory::open")) + .await?; + match (reader, &shared.prepare) { + (Some(reader), Some(prepare)) => prepare(reader), + _ => Ok(FileWork::empty()), + } + }) + .boxed() + } + + /// The next deferred file of an unordered pool to open, if any is left and the limit is not + /// spent. + fn next_deferred(&self) -> Option> { + let mut deferred = self.deferred.lock(); + if self.limit.is_spent() { + deferred.clear(); } - .boxed() + deferred.pop_front() } - /// Takes a split: reserves its rows from a reserved limit and spawns its task. - fn admit(&self, (file, range, progress): FileSplit) -> SplitFuture { + /// Takes a split and runs it on the session's runtime. + fn admit(self: &Arc, (file, index, progress): FileSplit) -> SplitOutput { *self.progress.lock() += progress; - let Some(mask) = file.scan.split_mask(&range) else { - return future::ready(Ok(None)).boxed(); - }; - let mask = match &self.limit { - PoolLimit::Reserve(limit) => { - let reserved = limit.limit(mask.mask().clone()); - if reserved.all_false() { - return future::ready(Ok(None)).boxed(); - } - RowMask::new(range.start, reserved) + let handle = self.session.handle(); + if let PoolLimit::Trim(_) = &self.limit { + let Some(mask) = file.scan.split_mask(&file.ranges[index]) else { + return future::ready(Ok(None)).boxed(); + }; + return spawn_lazy_split(&handle, move || split_exec(&file.ctx, mask).map(Some)) + .boxed(); + } + let shared = Arc::clone(self); + async move { + let task = file.tasks(&shared.limit).await?[index].lock().take(); + match task { + Some(task) => handle.spawn(task).await, + None => Ok(None), } - PoolLimit::Unlimited | PoolLimit::Trim(_) => mask, - }; - // Spawned onto the session's runtime, as V1 scans do: another runtime thread may decode - // it while this worker drives its other splits, and its I/O starts right away. - let handle = file.ctx.session.handle(); - handle - .spawn(async move { file.scan.split_task(&file.ctx, mask)?.await }) - .boxed() + } + .boxed() } - #[expect( - dead_code, - reason = "read by ScanPool::progress, which arrives with its first host" - )] fn progress(&self) -> f64 { - if self.limit.is_exhausted() { + if self.limit.is_trimmed_out() { return 1.0; } self.progress.lock().clamp(0.0, 1.0) } + + /// A worker's output: skips splits with no rows, trims to a trimmed limit, and ends after the + /// first error or once a trimmed limit is spent. A trimmed array is optimized again, on a CPU + /// task, `splits_in_flight` at a time. + fn output( + self: Arc, + outputs: BoxStream<'static, VortexResult>>, + ordered: bool, + splits_in_flight: usize, + ) -> BoxStream<'static, VortexResult> { + let trimmed = matches!(self.limit, PoolLimit::Trim(_)); + let handle = self.session.handle(); + let session = self.session.clone(); + let arrays = limit_output(outputs, self); + if !trimmed { + return arrays; + } + let identity: MapFn = Arc::new(Ok); + let mapped = arrays.map(move |array| { + spawn_map_trimmed(&handle, session.clone(), Arc::clone(&identity), array) + }); + let mapped = if ordered { + mapped.buffered(splits_in_flight).boxed() + } else { + mapped.buffer_unordered(splits_in_flight).boxed() + }; + stop_on_error(mapped) + } } -/// A worker's output: skips splits with no rows, trims to a trimmed limit, and ends after the -/// first error or once a trimmed limit is spent. +/// Skips splits with no rows, trims to a trimmed limit, and ends after the first error or once +/// a trimmed limit is spent. fn limit_output( outputs: BoxStream<'static, VortexResult>>, shared: Arc, @@ -298,9 +425,7 @@ fn limit_output( async move { let mut outputs = outputs?; loop { - if let PoolLimit::Trim(limit) = &shared.limit - && limit.is_exhausted() - { + if shared.limit.is_trimmed_out() { return None; } let array = match outputs.next().await? { @@ -327,9 +452,9 @@ fn limit_output( /// A unit of an unordered pool. enum Work { - Split(Arc, Range, f64), + Split(FileSplit), /// A deferred file, and where to send its splits once it is open. The sender keeps the - /// channel open until the file's splits are in it. + /// channel open until the file's splits, and the next deferred file, are in it. Open(Arc, Sender), } @@ -347,17 +472,24 @@ struct UnorderedPool { } impl UnorderedPool { - fn run(shared: &Arc, work: Work) -> SplitFuture { + fn run(shared: &Arc, work: Work) -> SplitOutput { match work { - Work::Split(file, range, progress) => shared.admit((file, range, progress)), + Work::Split(split) => shared.admit(split), Work::Open(factory, sender) => { let shared = Arc::clone(shared); async move { - let work = shared.open_file(factory).await?; - for (file, range, progress) in shared.file_splits(work) { - send(&sender, Work::Split(file, range, progress)); + let opened = shared.open_file(factory).await.map(|work| { + for split in shared.file_splits(work) { + send(&sender, Work::Split(split)); + } + None + }); + // Queue the next file behind this one's splits, so opens keep pace with the + // workers and at most `open_concurrency` are queued or running at once. + if let Some(next) = shared.next_deferred() { + send(&sender, Work::Open(next, sender.clone())); } - Ok(None) + opened } .boxed() } @@ -378,15 +510,25 @@ impl ScanPool for UnorderedPool { let splits_in_flight = self.splits_in_flight; // The worker holds the pool, so the pool is dropped only after its last worker. let outputs = receiver - .take_while(move |_| future::ready(!self.shared.limit.is_exhausted())) + .take_while(move |_| future::ready(!self.shared.limit.is_trimmed_out())) .map(move |work| UnorderedPool::run(&runner, work)) .buffer_unordered(splits_in_flight) .boxed(); ArrayStreamExt::boxed(ArrayStreamAdapter::new( dtype, - limit_output(outputs, shared), + shared.output(outputs, false, splits_in_flight), )) } + + fn progress(&self) -> f64 { + self.shared.progress() + } + + fn is_exhausted(&self) -> bool { + // Pending opens hold senders, so the channel closes only once every unit is in it. + self.shared.limit.is_trimmed_out() + || (self.receiver.is_closed() && self.receiver.is_empty()) + } } impl Drop for UnorderedPool { @@ -404,6 +546,7 @@ struct OrderedPool { /// The files, until the first worker takes them. files: Mutex>>, splits_in_flight: usize, + open_concurrency: usize, } impl ScanPool for OrderedPool { @@ -420,18 +563,21 @@ impl ScanPool for OrderedPool { let opener = Arc::clone(&shared); let splitter = Arc::clone(&shared); let admitter = Arc::clone(&shared); + let gate = Arc::clone(&shared); + // Deferred files open `open_concurrency` at a time, ahead of the splits being read. let outputs = stream::iter(files) - .then(move |file| match file { + .map(move |file| match file { PoolFile::Opened(work) => future::ready(Ok(work)).boxed(), PoolFile::Deferred(factory) => opener.open_file(factory), }) + .buffered(self.open_concurrency) .flat_map(move |work| match work { Ok(work) => { stream::iter(splitter.file_splits(work).into_iter().map(Ok)).left_stream() } Err(err) => stream::once(future::ready(Err(err))).right_stream(), }) - .take_while(move |_| future::ready(!shared.limit.is_exhausted())) + .take_while(move |_| future::ready(!gate.limit.is_trimmed_out())) .map(move |split| match split { Ok(split) => admitter.admit(split), Err(err) => future::ready(Err(err)).boxed(), @@ -440,9 +586,17 @@ impl ScanPool for OrderedPool { .boxed(); ArrayStreamExt::boxed(ArrayStreamAdapter::new( dtype, - limit_output(outputs, Arc::clone(&self.shared)), + shared.output(outputs, true, self.splits_in_flight), )) } + + fn progress(&self) -> f64 { + self.shared.progress() + } + + fn is_exhausted(&self) -> bool { + self.shared.limit.is_trimmed_out() || self.files.lock().is_none() + } } /// The single partition of a scan piece that is read through the partitions API: it opens the diff --git a/vortex-layout/src/scan/repeated_scan.rs b/vortex-layout/src/scan/repeated_scan.rs index dcd4cba58c8..4431e452ce9 100644 --- a/vortex-layout/src/scan/repeated_scan.rs +++ b/vortex-layout/src/scan/repeated_scan.rs @@ -31,6 +31,8 @@ use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_error::vortex_bail; use vortex_io::runtime::BlockingRuntime; +use vortex_io::runtime::Handle; +use vortex_io::runtime::Task; use vortex_io::session::RuntimeSessionExt; use vortex_scan::row_mask::RowMask; use vortex_scan::selection::Selection; @@ -84,7 +86,7 @@ pub struct RepeatedScan { pub type ScanTasks = Vec>>>; /// A function applied to each projected split array. -type MapFn = Arc VortexResult + Send + Sync>; +pub(crate) type MapFn = Arc VortexResult + Send + Sync>; impl RepeatedScan { pub fn execute_array_iter( @@ -326,21 +328,13 @@ impl RepeatedScan { .map(move |split| { let ctx = Arc::clone(&ctx); let selection = selection.clone(); - split_handle.spawn_nested(move |handle| async move { - let task = handle - .spawn_cpu(move || { - let Some(row_mask) = - split.either(Some, |range| selected_mask(&selection, &range)) - else { - return Ok(None); - }; - split_exec(&ctx, row_mask).map(Some) - }) - .await?; - match task { - Some(task) => task.await, - None => Ok(None), - } + spawn_lazy_split(&split_handle, move || { + let Some(row_mask) = + split.either(Some, |range| selected_mask(&selection, &range)) + else { + return Ok(None); + }; + split_exec(&ctx, row_mask).map(Some) }) }); let map_fn = Arc::clone(map_fn); @@ -349,9 +343,7 @@ impl RepeatedScan { .boxed(); let session = self.session.clone(); let mapped = limit_rows(arrays, limit).map(move |array| { - let map_fn = Arc::clone(&map_fn); - let session = session.clone(); - handle.spawn_cpu(move || map_fn(array?.optimize_ctx(&session)?)) + spawn_map_trimmed(&handle, session.clone(), Arc::clone(&map_fn), array) }); buffer(mapped, ordered, concurrency) } @@ -386,6 +378,36 @@ impl RepeatedScan { } } +/// Builds a split's task on a CPU thread and runs it, both on the session's runtime. +/// +/// This is how scans with a filter and a limit run their splits: a split's output row count is +/// unknown until its filter has run, so each split is built only once it is about to run, and none +/// start once the limit is spent. `build` returns `None` when the split has nothing to read. Every +/// other scan builds all of its split tasks up front with [`RepeatedScan::split_task`], so that +/// their reads are registered together and can coalesce, and runs each with [`Handle::spawn`]. +pub(crate) fn spawn_lazy_split( + handle: &Handle, + build: impl FnOnce() -> VortexResult> + Send + 'static, +) -> Task>> { + handle.spawn_nested(move |handle| async move { + match handle.spawn_cpu(build).await? { + Some(task) => task.await, + None => Ok(None), + } + }) +} + +/// Optimizes an array that a limit may have trimmed and maps it, on a CPU thread: the second +/// stage of a scan with a filter and a limit, after [`spawn_lazy_split`]. +pub(crate) fn spawn_map_trimmed( + handle: &Handle, + session: VortexSession, + map_fn: MapFn, + array: VortexResult, +) -> Task> { + handle.spawn_cpu(move || map_fn(array?.optimize_ctx(&session)?)) +} + /// This function returns `None` if the selection excludes every row in `range`. fn selected_mask(selection: &Selection, range: &Range) -> Option { let mask = selection.row_mask(range); @@ -452,7 +474,7 @@ fn limit_rows( } /// Yield the first error and drop upstream without polling it again. -fn stop_on_error( +pub(crate) fn stop_on_error( stream: BoxStream<'static, VortexResult>, ) -> BoxStream<'static, VortexResult> { let mut stream = Some(stream); @@ -469,6 +491,10 @@ fn stop_on_error( .boxed() } +/// The splits a scan keeps in flight for each worker thread by default, which allows for some I/O +/// lookahead without too much impact on work-stealing. +pub(crate) const DEFAULT_SPLITS_PER_THREAD: usize = 4; + /// How many splits a scan makes progress on at once: `per_worker` for each worker thread, as /// [`get_available_parallelism`] counts them, and at most `max` in all when that is set. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -478,7 +504,7 @@ pub(crate) struct SplitConcurrency { } impl SplitConcurrency { - fn splits_in_flight(self) -> usize { + pub(crate) fn splits_in_flight(self) -> usize { let scaled = self .per_worker .saturating_mul(get_available_parallelism().unwrap_or(1)); diff --git a/vortex-layout/src/scan/scan_builder.rs b/vortex-layout/src/scan/scan_builder.rs index 3785489d710..96373ae3e72 100644 --- a/vortex-layout/src/scan/scan_builder.rs +++ b/vortex-layout/src/scan/scan_builder.rs @@ -40,6 +40,7 @@ use crate::scan::limit::RowLimit; use crate::scan::limit::ScanLimit; use crate::scan::metrics::ScanMetrics; use crate::scan::metrics::ScanUsage; +use crate::scan::repeated_scan::DEFAULT_SPLITS_PER_THREAD; use crate::scan::repeated_scan::RepeatedScan; use crate::scan::repeated_scan::ScanTasks; use crate::scan::repeated_scan::SplitConcurrency; @@ -103,10 +104,8 @@ impl ScanBuilder { selection: Default::default(), split_by: SplitBy::default(), natural_splits: None, - // We default to four tasks per worker thread, which allows for some I/O lookahead - // without too much impact on work-stealing. concurrency: SplitConcurrency { - per_worker: 4, + per_worker: DEFAULT_SPLITS_PER_THREAD, max: None, }, map_fn: Arc::new(Ok), diff --git a/vortex-layout/src/scan/test.rs b/vortex-layout/src/scan/test.rs index 3e0b70465e6..0e15bcced80 100644 --- a/vortex-layout/src/scan/test.rs +++ b/vortex-layout/src/scan/test.rs @@ -84,6 +84,7 @@ pub struct TestLayoutReader { filter_exprs: Option>>>, in_flight: Option>, yields: fn(u64) -> usize, + built_projections: Option>, } /// Counts projections running at once, and the most that ever were. @@ -116,6 +117,7 @@ impl TestLayoutReader { filter_exprs: None, in_flight: None, yields: |_| 0, + built_projections: None, } } @@ -159,6 +161,12 @@ impl TestLayoutReader { self } + /// Counts the projections built, which is when a split registers its reads. + pub fn with_built_projections(mut self, built: Arc) -> Self { + self.built_projections = Some(built); + self + } + pub fn with_filter_exprs(mut self, filter_exprs: Arc>>) -> Self { self.filter_exprs = Some(filter_exprs); self @@ -284,6 +292,9 @@ impl LayoutReader for TestLayoutReader { let fail = self.fail_projection || (self.fail_first_projection && row_range.start == 0); let in_flight = self.in_flight.clone(); let yields = (self.yields)(row_range.start); + if let Some(built) = &self.built_projections { + built.fetch_add(1, Ordering::SeqCst); + } Ok(Box::pin(async move { for _ in 0..yields { From c638db423a70e230720a626aed1cc37b96e33be8 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Thu, 19 Nov 2026 19:15:57 -0500 Subject: [PATCH 15/80] Pass a pool's open slot on when its worker drops An open slot now passes to the next deferred file whether the open finished or its worker gave it up, so a dropped worker strands only the file it was opening. A spent limit counts the unopened files as read, so progress ends at 1.0. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-layout/src/scan/multi.rs | 114 +++++++++++++++++++++++++++----- vortex-layout/src/scan/pool.rs | 72 +++++++++++++------- 2 files changed, 147 insertions(+), 39 deletions(-) diff --git a/vortex-layout/src/scan/multi.rs b/vortex-layout/src/scan/multi.rs index 0ae1db43e65..b71bc2eace7 100644 --- a/vortex-layout/src/scan/multi.rs +++ b/vortex-layout/src/scan/multi.rs @@ -1287,22 +1287,8 @@ mod pool_tests { #[test] fn deferred_opens_are_bounded() -> VortexResult<()> { let opens = Arc::new(AtomicUsize::new(0)); - let gates: Vec<_> = (0..6).map(|_| Arc::new(Gate::default())).collect(); - let factories = gates - .iter() - .enumerate() - .map(|(index, gate)| { - let base = 100 * i32::try_from(index).expect("few files"); - Arc::new(GatedFactory { - reader: Arc::new(TestLayoutReader::new(4).with_split_size(1).with_base(base)), - gate: Arc::clone(gate), - opens: Arc::clone(&opens), - }) as Arc - }) - .collect(); - let source = - MultiLayoutDataSource::new_deferred(i32_dtype(), factories, vec![], &new_session()) - .with_concurrency(2); + let (source, gates) = counted_source(6, 4, &opens); + let source = source.with_concurrency(2); let pool = plan(&source, ScanRequest::default())?.open()?; let mut workers: Vec<_> = (0..4).map(|_| Arc::clone(&pool).worker()).collect(); let mut noop = Context::from_waker(noop_waker_ref()); @@ -1416,6 +1402,102 @@ mod pool_tests { Ok(()) } + /// Deferred files of `rows` one-row splits whose opens are released, counted by `opens`; the + /// `i`th produces `100 * i + row`. + fn counted_source( + files: usize, + rows: u64, + opens: &Arc, + ) -> (MultiLayoutDataSource, Vec>) { + let gates: Vec<_> = (0..files).map(|_| Arc::new(Gate::default())).collect(); + let factories = gates + .iter() + .enumerate() + .map(|(index, gate)| { + let base = 100 * i32::try_from(index).expect("few files"); + Arc::new(GatedFactory { + reader: Arc::new( + TestLayoutReader::new(rows) + .with_split_size(1) + .with_base(base), + ), + gate: Arc::clone(gate), + opens: Arc::clone(opens), + }) as Arc + }) + .collect(); + let source = + MultiLayoutDataSource::new_deferred(i32_dtype(), factories, vec![], &new_session()); + (source, gates) + } + + /// An ordered pool reserves an unfiltered limit in row order across files, so it returns + /// exactly the first rows even when the limit ends inside a later file. + #[test] + fn ordered_reserved_limit_crosses_files() -> VortexResult<()> { + let (source, gates) = counted_source(3, 4, &Arc::default()); + for gate in &gates { + gate.release(); + } + let pool = plan( + &source, + ScanRequest { + ordered: true, + limit: Some(6), + ..Default::default() + }, + )? + .open()?; + assert_eq!(read_with_one_worker(pool)?, [0, 1, 2, 3, 100, 101]); + Ok(()) + } + + /// Once an unordered pool's reserved limit is spent, it opens no more files, and reports + /// that it is done. + #[test] + fn spent_limit_stops_opening_files() -> VortexResult<()> { + let opens = Arc::new(AtomicUsize::new(0)); + let (source, gates) = counted_source(6, 4, &opens); + for gate in &gates { + gate.release(); + } + let source = source.with_concurrency(1); + let pool = plan( + &source, + ScanRequest { + limit: Some(2), + ..Default::default() + }, + )? + .open()?; + let values = read_with_one_worker(Arc::clone(&pool))?; + assert_eq!(values.len(), 2); + assert!(opens.load(Ordering::SeqCst) < 6, "opened every file"); + assert!(pool.is_exhausted()); + assert_eq!(pool.progress(), 1.0); + Ok(()) + } + + /// A worker dropped while it opens a file gives up only that file: the next deferred file + /// still opens, and other workers read it. + #[test] + fn dropped_opener_strands_only_its_file() -> VortexResult<()> { + let (source, gates) = counted_source(3, 2, &Arc::default()); + let source = source.with_concurrency(1); + let pool = plan(&source, ScanRequest::default())?.open()?; + let mut dropped = Arc::clone(&pool).worker(); + let mut noop = Context::from_waker(noop_waker_ref()); + assert!(poll_worker(&mut dropped, &mut noop).is_pending()); + drop(dropped); + + gates[1].release(); + gates[2].release(); + let mut values = read_with_one_worker(pool)?; + values.sort_unstable(); + assert_eq!(values, [100, 101, 200, 201]); + Ok(()) + } + /// A limit is shared by every worker and file of an unordered pool. #[test] fn pool_limit_is_shared_across_readers() -> VortexResult<()> { diff --git a/vortex-layout/src/scan/pool.rs b/vortex-layout/src/scan/pool.rs index f0094a6e16a..973623e8eba 100644 --- a/vortex-layout/src/scan/pool.rs +++ b/vortex-layout/src/scan/pool.rs @@ -236,7 +236,11 @@ pub(crate) fn open_pool( } PoolFile::Deferred(factory) if opens < open_concurrency => { opens += 1; - send(&sender, Work::Open(factory, sender.clone())); + let slot = OpenSlot { + shared: Arc::clone(&shared), + sender: sender.clone(), + }; + send(&sender, Work::Open(factory, slot)); } PoolFile::Deferred(factory) => shared.deferred.lock().push_back(factory), } @@ -347,10 +351,11 @@ impl Shared { } /// The next deferred file of an unordered pool to open, if any is left and the limit is not - /// spent. + /// spent. Once it is spent, the files left count as read. fn next_deferred(&self) -> Option> { let mut deferred = self.deferred.lock(); - if self.limit.is_spent() { + if self.limit.is_spent() && !deferred.is_empty() { + *self.progress.lock() += self.file_share * deferred.len() as f64; deferred.clear(); } deferred.pop_front() @@ -453,9 +458,33 @@ fn limit_output( /// A unit of an unordered pool. enum Work { Split(FileSplit), - /// A deferred file, and where to send its splits once it is open. The sender keeps the - /// channel open until the file's splits, and the next deferred file, are in it. - Open(Arc, Sender), + /// A deferred file, and the open slot it holds until its splits are in the channel. + Open(Arc, OpenSlot), +} + +/// One of an unordered pool's `open_concurrency` open slots. Its sender keeps the channel open +/// while the file that holds it is queued or opening. +struct OpenSlot { + shared: Arc, + sender: Sender, +} + +impl Drop for OpenSlot { + /// Passes the slot to the next deferred file, queued behind the splits of the file that held + /// it, so opens keep pace with the workers. The slot passes on whether the open finished or a + /// dropped worker gave it up, so that worker strands only the file it was opening. + fn drop(&mut self) { + if self.sender.is_closed() { + return; + } + if let Some(next) = self.shared.next_deferred() { + let slot = OpenSlot { + shared: Arc::clone(&self.shared), + sender: self.sender.clone(), + }; + send(&self.sender, Work::Open(next, slot)); + } + } } fn send(sender: &Sender, work: Work) { @@ -475,24 +504,17 @@ impl UnorderedPool { fn run(shared: &Arc, work: Work) -> SplitOutput { match work { Work::Split(split) => shared.admit(split), - Work::Open(factory, sender) => { - let shared = Arc::clone(shared); - async move { - let opened = shared.open_file(factory).await.map(|work| { - for split in shared.file_splits(work) { - send(&sender, Work::Split(split)); - } - None - }); - // Queue the next file behind this one's splits, so opens keep pace with the - // workers and at most `open_concurrency` are queued or running at once. - if let Some(next) = shared.next_deferred() { - send(&sender, Work::Open(next, sender.clone())); + Work::Open(factory, slot) => async move { + let opened = slot.shared.open_file(factory).await.map(|work| { + for split in slot.shared.file_splits(work) { + send(&slot.sender, Work::Split(split)); } - opened - } - .boxed() + None + }); + drop(slot); + opened } + .boxed(), } } } @@ -521,11 +543,14 @@ impl ScanPool for UnorderedPool { } fn progress(&self) -> f64 { + if self.is_exhausted() { + return 1.0; + } self.shared.progress() } fn is_exhausted(&self) -> bool { - // Pending opens hold senders, so the channel closes only once every unit is in it. + // Open slots hold senders, so the channel closes only once every unit is in it. self.shared.limit.is_trimmed_out() || (self.receiver.is_closed() && self.receiver.is_empty()) } @@ -595,6 +620,7 @@ impl ScanPool for OrderedPool { } fn is_exhausted(&self) -> bool { + // The first worker takes every file. self.shared.limit.is_trimmed_out() || self.files.lock().is_none() } } From 5703e0e6e070f0b50361fe3bc1cfb380db4b2627 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Thu, 19 Nov 2026 19:15:57 -0500 Subject: [PATCH 16/80] 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 0cd40e45df61e85ca78440a3469f70ea3af12dcb Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Thu, 19 Nov 2026 19:25:53 -0500 Subject: [PATCH 17/80] Request shared segments without an exclusive lock When pool workers share one file's splits, many threads request segments from one SharedSegmentSource. Each request took an exclusive shard lock and held it across the inner request. Requests now look up an in-flight request under a read lock, make the inner request outside any lock, and lock exclusively only to record it, with the shard count scaled to the cores. A requester that loses a race for the same segment drops its own request, which reads the same bytes, so coalescing is unchanged. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-io/src/segments/shared.rs | 128 ++++++++++++++++++++++++++----- 1 file changed, 109 insertions(+), 19 deletions(-) diff --git a/vortex-io/src/segments/shared.rs b/vortex-io/src/segments/shared.rs index dbaf553264a..bed9394a9d2 100644 --- a/vortex-io/src/segments/shared.rs +++ b/vortex-io/src/segments/shared.rs @@ -6,6 +6,7 @@ use std::sync::Arc; use futures::FutureExt; use futures::TryFutureExt; use futures::future::BoxFuture; +use futures::future::Shared; use futures::future::WeakShared; use vortex_array::buffer::BufferHandle; use vortex_error::SharedVortexResult; @@ -20,6 +21,11 @@ use super::SegmentSource; /// A [`SegmentSource`] that allows multiple requesters to await the same underlying segment /// request. +/// +/// Many threads may request segments of one source at once, for example the workers of a scan +/// pool sharing one file's splits. Requests therefore look for a request in flight under a shared +/// lock, call the inner source outside any lock, and take an exclusive lock only to record a new +/// request. pub struct SharedSegmentSource { inner: S, in_flight: DashMap>, @@ -32,33 +38,117 @@ impl SharedSegmentSource { pub fn new(inner: S) -> Self { Self { inner, - in_flight: DashMap::with_hasher_and_shard_amount(Default::default(), 64), + // The default shard count scales with the machine's cores, as the requesters do. + in_flight: DashMap::default(), } } + + /// The request in flight for `id`, if any. + fn in_flight(&self, id: SegmentId) -> Option> { + self.in_flight.get(&id)?.upgrade() + } } impl SegmentSource for SharedSegmentSource { fn request(&self, id: SegmentId) -> SegmentFuture { - loop { - match self.in_flight.entry(id) { - Entry::Occupied(e) => { - if let Some(shared_future) = e.get().upgrade() { - return shared_future.map_err(VortexError::from).boxed(); - } else { - // The future has been dropped, remove the entry and try again. - e.remove(); - } - } - Entry::Vacant(e) => { - let future = self.inner.request(id).map_err(Arc::new).boxed().shared(); - e.insert( - future - .downgrade() - .vortex_expect("just created, cannot be polled to completion"), - ); - return future.map_err(VortexError::from).boxed(); + if let Some(future) = self.in_flight(id) { + return future.map_err(VortexError::from).boxed(); + } + + let future = self.inner.request(id).map_err(Arc::new).boxed().shared(); + let weak = future + .downgrade() + .vortex_expect("just created, cannot be polled to completion"); + match self.in_flight.entry(id) { + Entry::Occupied(mut entry) => { + if let Some(existing) = entry.get().upgrade() { + // Another requester recorded the same segment first. Its request reads the + // same bytes, so dropping this one changes nothing that is read or coalesced. + return existing.map_err(VortexError::from).boxed(); } + entry.insert(weak); } + Entry::Vacant(entry) => { + entry.insert(weak); + } + } + future.map_err(VortexError::from).boxed() + } +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + use std::sync::atomic::AtomicUsize; + use std::sync::atomic::Ordering; + + use futures::FutureExt; + use futures::executor::block_on; + use vortex_array::buffer::BufferHandle; + use vortex_buffer::ByteBuffer; + use vortex_error::VortexResult; + + use super::*; + + /// Counts its requests, and answers each with the segment's id as one byte. + #[derive(Default)] + struct Counting(AtomicUsize); + + impl SegmentSource for Counting { + fn request(&self, id: SegmentId) -> SegmentFuture { + self.0.fetch_add(1, Ordering::SeqCst); + let byte = u8::try_from(*id).unwrap_or(u8::MAX); + async move { Ok(BufferHandle::new_host(ByteBuffer::from(vec![byte]))) }.boxed() + } + } + + #[test] + fn concurrent_requests_share_one_inner_request() -> VortexResult<()> { + let source = SharedSegmentSource::new(Counting::default()); + let first = source.request(SegmentId::from(7)); + let second = source.request(SegmentId::from(7)); + assert_eq!(source.inner.0.load(Ordering::SeqCst), 1); + assert_eq!(block_on(first)?.to_host_sync().as_slice(), [7]); + assert_eq!(block_on(second)?.to_host_sync().as_slice(), [7]); + Ok(()) + } + + #[test] + fn a_finished_request_is_made_again() -> VortexResult<()> { + let source = SharedSegmentSource::new(Counting::default()); + drop(block_on(source.request(SegmentId::from(3)))?); + drop(block_on(source.request(SegmentId::from(3)))?); + assert_eq!(source.inner.0.load(Ordering::SeqCst), 2); + Ok(()) + } + + /// Threads requesting the same segments at once each get their segment. + #[test] + fn racing_requesters_get_their_segments() -> VortexResult<()> { + let source = Arc::new(SharedSegmentSource::new(Counting::default())); + let futures = std::thread::scope(|scope| { + let handles: Vec<_> = (0..8) + .map(|_| { + let source = Arc::clone(&source); + scope.spawn(move || { + (0..64u32) + .map(|id| source.request(SegmentId::from(id))) + .collect::>() + }) + }) + .collect(); + handles + .into_iter() + .flat_map(|handle| handle.join().expect("requester panicked")) + .collect::>() + }); + // A requester that loses a race drops its own inner request, so there may be more than + // one per segment, but never fewer. + assert!(source.inner.0.load(Ordering::SeqCst) >= 64); + for (index, future) in futures.into_iter().enumerate() { + let id = u8::try_from(index % 64).unwrap_or(u8::MAX); + assert_eq!(block_on(future)?.to_host_sync().as_slice(), [id]); } + Ok(()) } } From 3148faa155f31358c1b6cb1a45661dcd28d3bf41 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Thu, 19 Nov 2026 20:08:23 -0500 Subject: [PATCH 18/80] 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 7843fbcc1197b64ec09aeef6b54c07852ab4d69d Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Thu, 19 Nov 2026 20:14:00 -0500 Subject: [PATCH 19/80] Share an unordered pool's output instead of its work MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Workers of an unordered pool each kept their own window of splits, so with fewer splits than workers × window the first workers took most of a scan and the rest idled. The pool now runs its splits in lanes on the session runtime, splits_in_flight of them across the whole pool, and every worker takes rows from one bounded output channel. A worker is just one host thread's share of the output, so the number of workers is only the host's parallelism. Trimming to a filtered limit happens once, in the lanes, and dropping a worker gives up nothing. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-layout/src/scan/multi.rs | 91 ++++++--------- vortex-layout/src/scan/pool.rs | 190 +++++++++++++++++++++++--------- 2 files changed, 169 insertions(+), 112 deletions(-) diff --git a/vortex-layout/src/scan/multi.rs b/vortex-layout/src/scan/multi.rs index b71bc2eace7..9ccbe87712d 100644 --- a/vortex-layout/src/scan/multi.rs +++ b/vortex-layout/src/scan/multi.rs @@ -1162,10 +1162,8 @@ mod pool_tests { use async_trait::async_trait; use futures::StreamExt; use futures::future::poll_fn; - use futures::task::ArcWake; use futures::task::AtomicWaker; use futures::task::noop_waker_ref; - use futures::task::waker; use rstest::rstest; use vortex_array::ArrayRef; use vortex_array::dtype::Nullability; @@ -1266,15 +1264,6 @@ mod pool_tests { (source, gates) } - #[derive(Default)] - struct WakeFlag(AtomicBool); - - impl ArcWake for WakeFlag { - fn wake_by_ref(arc_self: &Arc) { - arc_self.0.store(true, Ordering::SeqCst); - } - } - fn poll_worker( worker: &mut SendableArrayStream, cx: &mut Context<'_>, @@ -1332,47 +1321,27 @@ mod pool_tests { Ok(()) } - /// A deferred file is opened by a worker, and its splits are shared with other workers. A - /// worker that finds only an open in progress waits, and is woken when the open adds splits. + /// Rows go to whichever worker asks for them: a worker that stops asking holds none back, + /// so another worker that waited while the file opened reads all of it. #[test] - fn deferred_file_splits_are_shared_with_waiting_workers() -> VortexResult<()> { + fn rows_go_to_whichever_worker_asks() -> VortexResult<()> { let (source, gates) = gated_source(1, 16); - // Each worker holds at most two splits, so the opener leaves splits for the waiter. - let request = ScanRequest { - split_concurrency: NonZeroUsize::new(2), - ..Default::default() - }; - let pool = plan(&source, request)?.open()?; - let mut opener = Arc::clone(&pool).worker(); + let pool = plan(&source, ScanRequest::default())?.open()?; + let mut idle = Arc::clone(&pool).worker(); let mut waiter = Arc::clone(&pool).worker(); let mut noop = Context::from_waker(noop_waker_ref()); - let flag = Arc::new(WakeFlag::default()); - let flag_waker = waker(Arc::clone(&flag)); - let mut flagged = Context::from_waker(&flag_waker); - // The opener takes the only file and blocks on its open; the waiter finds nothing to take - // but an open in progress, so it waits. - assert!(poll_worker(&mut opener, &mut noop).is_pending()); - assert!(poll_worker(&mut waiter, &mut flagged).is_pending()); + // Both workers find only an open in progress, so both wait. + assert!(poll_worker(&mut idle, &mut noop).is_pending()); + assert!(poll_worker(&mut waiter, &mut noop).is_pending()); gates[0].release(); - // The opener's split runs on the session runtime, so wait for it rather than polling once. - let Some(first) = futures::executor::block_on(opener.next()) else { - panic!("the opener reads a split of the file it opened"); - }; - assert!(flag.0.load(Ordering::SeqCst), "the waiter is woken"); - - let waiter_values = collect_scan_values(futures::executor::block_on_stream(waiter))?; - let opener_values = collect_scan_values( - std::iter::once(first).chain(futures::executor::block_on_stream(opener)), - )?; - assert!( - !waiter_values.is_empty(), - "the waiter reads the opened file's splits" - ); - let mut values = [opener_values, waiter_values].concat(); - values.sort_unstable(); - assert_eq!(values, (0..16).collect::>()); + let values = collect_scan_values(futures::executor::block_on_stream(waiter))?; + assert_eq!(values.len(), 16); + let mut sorted = values; + sorted.sort_unstable(); + assert_eq!(sorted, (0..16).collect::>()); + assert!(futures::executor::block_on(idle.next()).is_none()); Ok(()) } @@ -1478,10 +1447,10 @@ mod pool_tests { Ok(()) } - /// A worker dropped while it opens a file gives up only that file: the next deferred file - /// still opens, and other workers read it. + /// Opens run in the pool's lanes, not in its workers, so dropping a worker that is waiting + /// on an open gives up nothing: the other workers still read every file. #[test] - fn dropped_opener_strands_only_its_file() -> VortexResult<()> { + fn dropped_worker_gives_up_nothing() -> VortexResult<()> { let (source, gates) = counted_source(3, 2, &Arc::default()); let source = source.with_concurrency(1); let pool = plan(&source, ScanRequest::default())?.open()?; @@ -1490,11 +1459,12 @@ mod pool_tests { assert!(poll_worker(&mut dropped, &mut noop).is_pending()); drop(dropped); - gates[1].release(); - gates[2].release(); + for gate in &gates { + gate.release(); + } let mut values = read_with_one_worker(pool)?; values.sort_unstable(); - assert_eq!(values, [100, 101, 200, 201]); + assert_eq!(values, [0, 1, 100, 101, 200, 201]); Ok(()) } @@ -1605,11 +1575,16 @@ mod pool_tests { Ok(()) } - /// A worker reads at most `split_concurrency` splits at once. + /// A pool reads at most `split_concurrency` splits at once, however many workers read it. #[rstest] - #[case(1)] - #[case(2)] - fn split_concurrency_bounds_each_worker(#[case] max: usize) -> VortexResult<()> { + #[case::ordered(true, 1)] + #[case::ordered(true, 2)] + #[case::unordered(false, 1)] + #[case::unordered(false, 2)] + fn split_concurrency_bounds_the_pool( + #[case] ordered: bool, + #[case] max: usize, + ) -> VortexResult<()> { let in_flight = Arc::new(InFlight::default()); let reader: LayoutReaderRef = Arc::new( TestLayoutReader::new(64) @@ -1620,13 +1595,15 @@ mod pool_tests { let pool = plan( &source, ScanRequest { - ordered: true, + ordered, split_concurrency: NonZeroUsize::new(max), ..Default::default() }, )? .open()?; - assert_eq!(read_with_one_worker(pool)?, (0..64).collect::>()); + let mut values = read_with_workers(&pool, 4)?.concat(); + values.sort_unstable(); + assert_eq!(values, (0..64).collect::>()); assert!(in_flight.peak() <= max, "peak {}", in_flight.peak()); Ok(()) } diff --git a/vortex-layout/src/scan/pool.rs b/vortex-layout/src/scan/pool.rs index 973623e8eba..fa58016a7dd 100644 --- a/vortex-layout/src/scan/pool.rs +++ b/vortex-layout/src/scan/pool.rs @@ -3,34 +3,40 @@ //! The work that the workers of an opened layout scan share. //! -//! A pool's units are the splits of one or more files, and the files not yet opened. A worker -//! takes units and keeps several splits in flight, each spawned onto the session's runtime; it -//! never starts threads of its own. Opening a deferred file is a unit like any other, and at most -//! `open_concurrency` opens are queued or running at once. +//! A pool's units are the splits of one or more files, and the files not yet opened. Its splits +//! run as tasks on the session's runtime, at most `splits_in_flight` at once across the whole +//! pool; it never starts threads of its own. Opening a deferred file is a unit like any other, and +//! at most `open_concurrency` opens are queued or running at once. //! //! Splits run as [`RepeatedScan::execute_stream`] runs them: //! -//! - A scan with a filter and a limit builds each split on a CPU thread only once a worker takes -//! it ([`spawn_lazy_split`]), so no new split starts once the limit is spent, and optimizes the +//! - A scan with a filter and a limit builds each split on a CPU thread only once it is taken +//! to run ([`spawn_lazy_split`]), so no new split starts once the limit is spent, and optimizes the //! rows the limit keeps on a second CPU task ([`spawn_map_trimmed`]). -//! - Every other scan builds all of a file's split tasks together, when a worker first takes one -//! of them, so the file's reads are registered at once and can coalesce. A limit is reserved +//! - Every other scan builds all of a file's split tasks together, when the first of them is +//! taken, so the file's reads are registered at once and can coalesce. A limit is reserved //! then, in split order. //! -//! The pools differ in how workers share units: +//! The pools differ in how workers share the work: //! -//! - An unordered pool hands units out through a channel. The worker that opens a deferred file -//! sends the file's splits back into the channel, where any worker can take them, followed by -//! the next deferred file. The channel closes once every open has finished, which ends the -//! workers. -//! - An ordered pool gives all of its units, in row order, to its first worker; later workers -//! get nothing. Parallel ordered reads cut the scan with `split` first. +//! - An unordered pool runs `splits_in_flight` lanes on the runtime once its first worker starts. +//! Each lane takes the next unit from a channel of units, runs it, and sends its rows into one +//! bounded output channel; a lane that opens a deferred file sends the file's splits back into +//! the channel of units, followed by the next deferred file. Workers only take rows from the +//! output channel, so whichever worker asks next gets the next rows, however many workers there +//! are, and the number of workers is only the host's parallelism. The output channel closes +//! once every lane has finished, which ends the workers. +//! - An ordered pool gives all of its units, in row order, to its first worker, which keeps +//! `splits_in_flight` of them running at once; later workers get nothing. Parallel ordered reads +//! cut the scan with `split` first. use std::any::Any; use std::collections::VecDeque; use std::num::NonZeroUsize; use std::ops::Range; use std::sync::Arc; +use std::sync::atomic::AtomicBool; +use std::sync::atomic::Ordering; use async_channel::Receiver; use async_channel::Sender; @@ -50,6 +56,7 @@ use vortex_array::stream::ArrayStreamAdapter; use vortex_array::stream::ArrayStreamExt; use vortex_array::stream::SendableArrayStream; use vortex_error::VortexResult; +use vortex_io::runtime::Task; use vortex_io::session::RuntimeSessionExt; use vortex_scan::DataSourceScanRef; use vortex_scan::Partition; @@ -194,12 +201,10 @@ pub(crate) fn open_pool( Some(limit) if options.has_filter => PoolLimit::Trim(RowLimit::new(limit)), Some(limit) => PoolLimit::Reserve(RowLimit::new(limit)), }; - // A worker takes the place of a partition that one host thread drains, so it keeps as many - // splits in flight as a partition's stream does by default: four per core, at most the - // request's `split_concurrency`. A host with a worker per core therefore has the in-flight - // total of the partitions path, where each of DuckDB's threads drained one file's partition - // and each of DataFusion's `target_partitions` streams drained one partition, each with up to - // `4 × cores` splits in flight. + // The pool keeps as many splits in flight as one scan stream does by default: four per core, + // at most the request's `split_concurrency`, however many workers read it. The runtime's + // threads decode them, so more in flight would only read further ahead, and the file's + // registered reads already let I/O coalesce ahead of the splits being decoded. let splits_in_flight = SplitConcurrency { per_worker: DEFAULT_SPLITS_PER_THREAD, max: options.split_concurrency, @@ -214,6 +219,7 @@ pub(crate) fn open_pool( file_share: 1.0 / files.len().max(1) as f64, progress: Mutex::new(0.0), deferred: Mutex::new(VecDeque::new()), + failed: AtomicBool::new(false), }); if options.ordered { return Arc::new(OrderedPool { @@ -245,10 +251,13 @@ pub(crate) fn open_pool( PoolFile::Deferred(factory) => shared.deferred.lock().push_back(factory), } } + let (output, outputs) = async_channel::bounded(splits_in_flight); Arc::new(UnorderedPool { dtype: options.dtype, shared, - receiver, + units: receiver, + outputs, + lanes: Mutex::new(Lanes::Idle(output)), splits_in_flight, }) } @@ -297,6 +306,8 @@ struct Shared { progress: Mutex, /// An unordered pool's deferred files that are not yet queued for opening, in file order. deferred: Mutex>>, + /// Whether a unit of an unordered pool failed, which stops its lanes. + failed: AtomicBool, } impl Shared { @@ -390,13 +401,12 @@ impl Shared { self.progress.lock().clamp(0.0, 1.0) } - /// A worker's output: skips splits with no rows, trims to a trimmed limit, and ends after the - /// first error or once a trimmed limit is spent. A trimmed array is optimized again, on a CPU - /// task, `splits_in_flight` at a time. + /// An ordered worker's output: skips splits with no rows, trims to a trimmed limit, and ends + /// after the first error or once a trimmed limit is spent. A trimmed array is optimized again, + /// on a CPU task, `splits_in_flight` at a time. fn output( self: Arc, outputs: BoxStream<'static, VortexResult>>, - ordered: bool, splits_in_flight: usize, ) -> BoxStream<'static, VortexResult> { let trimmed = matches!(self.limit, PoolLimit::Trim(_)); @@ -410,12 +420,7 @@ impl Shared { let mapped = arrays.map(move |array| { spawn_map_trimmed(&handle, session.clone(), Arc::clone(&identity), array) }); - let mapped = if ordered { - mapped.buffered(splits_in_flight).boxed() - } else { - mapped.buffer_unordered(splits_in_flight).boxed() - }; - stop_on_error(mapped) + stop_on_error(mapped.buffered(splits_in_flight).boxed()) } } @@ -492,11 +497,24 @@ fn send(sender: &Sender, work: Work) { drop(sender.try_send(work)); } -/// A pool whose workers share its units through a channel. +/// The lanes of an unordered pool. +enum Lanes { + /// Not started: the sender of the output channel, for the lanes to hold once they start. + Idle(Sender>), + /// Running, until the pool is dropped, which aborts them. + Running( + #[expect(dead_code, reason = "held so that dropping the pool aborts the lanes")] + Vec>, + ), +} + +/// A pool whose lanes run its units on the runtime, and whose workers share their output. struct UnorderedPool { dtype: DType, shared: Arc, - receiver: Receiver, + units: Receiver, + outputs: Receiver>, + lanes: Mutex, splits_in_flight: usize, } @@ -517,6 +535,73 @@ impl UnorderedPool { .boxed(), } } + + /// Starts the lanes, once. + fn start_lanes(&self) { + let mut lanes = self.lanes.lock(); + let Lanes::Idle(output) = &*lanes else { + return; + }; + let output = output.clone(); + let handle = self.shared.session.handle(); + let running = (0..self.splits_in_flight) + .map(|_| { + handle.spawn(lane( + Arc::clone(&self.shared), + self.units.clone(), + output.clone(), + )) + }) + .collect(); + // Dropping the pool's own sender leaves the lanes holding the output channel open. + *lanes = Lanes::Running(running); + } +} + +/// A lane: runs units one at a time and sends their rows to the workers, trimming them to a +/// trimmed limit. Ends once the units run out, a limit is spent, a unit fails, or every worker +/// is gone. +async fn lane(shared: Arc, units: Receiver, output: Sender>) { + let handle = shared.session.handle(); + let identity: MapFn = Arc::new(Ok); + while !shared.limit.is_trimmed_out() && !shared.failed.load(Ordering::Acquire) { + let Ok(work) = units.recv().await else { + return; + }; + let array = match UnorderedPool::run(&shared, work).await { + Ok(Some(array)) => Ok(array), + Ok(None) => continue, + Err(err) => Err(err), + }; + let array = match (&shared.limit, array) { + (PoolLimit::Trim(limit), Ok(array)) => { + let granted = limit.take(array.len()); + if granted == 0 { + return; + } + let array = if granted < array.len() { + array.slice(0..granted) + } else { + Ok(array) + }; + spawn_map_trimmed( + &handle, + shared.session.clone(), + Arc::clone(&identity), + array, + ) + .await + } + (_, array) => array, + }; + let failed = array.is_err(); + if failed { + shared.failed.store(true, Ordering::Release); + } + if output.send(array).await.is_err() || failed { + return; + } + } } impl ScanPool for UnorderedPool { @@ -525,21 +610,15 @@ impl ScanPool for UnorderedPool { } fn worker(self: Arc) -> SendableArrayStream { + self.start_lanes(); let dtype = self.dtype.clone(); - let shared = Arc::clone(&self.shared); - let runner = Arc::clone(&shared); - let receiver = self.receiver.clone(); - let splits_in_flight = self.splits_in_flight; - // The worker holds the pool, so the pool is dropped only after its last worker. - let outputs = receiver - .take_while(move |_| future::ready(!self.shared.limit.is_trimmed_out())) - .map(move |work| UnorderedPool::run(&runner, work)) - .buffer_unordered(splits_in_flight) - .boxed(); - ArrayStreamExt::boxed(ArrayStreamAdapter::new( - dtype, - shared.output(outputs, false, splits_in_flight), - )) + // The worker holds the pool, so the lanes run until the pool's last worker is dropped. + let arrays = stream::unfold(self, |pool| async move { + let array = pool.outputs.recv().await.ok()?; + Some((array, pool)) + }) + .boxed(); + ArrayStreamExt::boxed(ArrayStreamAdapter::new(dtype, stop_on_error(arrays))) } fn progress(&self) -> f64 { @@ -550,17 +629,18 @@ impl ScanPool for UnorderedPool { } fn is_exhausted(&self) -> bool { - // Open slots hold senders, so the channel closes only once every unit is in it. - self.shared.limit.is_trimmed_out() - || (self.receiver.is_closed() && self.receiver.is_empty()) + // The lanes hold the output channel's senders, so it closes once every lane has ended. + self.outputs.is_closed() && self.outputs.is_empty() } } impl Drop for UnorderedPool { fn drop(&mut self) { - // Pending opens hold senders of the channel itself; drain them so it can be freed. - self.receiver.close(); - while self.receiver.try_recv().is_ok() {} + // Pending opens hold senders of the channel of units itself; drain them so it can be + // freed. The lanes are aborted when they are dropped. + self.units.close(); + while self.units.try_recv().is_ok() {} + self.outputs.close(); } } @@ -611,7 +691,7 @@ impl ScanPool for OrderedPool { .boxed(); ArrayStreamExt::boxed(ArrayStreamAdapter::new( dtype, - shared.output(outputs, true, self.splits_in_flight), + shared.output(outputs, self.splits_in_flight), )) } From 4272dca092545857bf60a0857155a134d78f7050 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Thu, 19 Nov 2026 20:17:12 -0500 Subject: [PATCH 20/80] Stop assuming a scan pool's workers own their work Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-datafusion/src/v2/source.rs | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/vortex-datafusion/src/v2/source.rs b/vortex-datafusion/src/v2/source.rs index 91783177691..919f1700ee4 100644 --- a/vortex-datafusion/src/v2/source.rs +++ b/vortex-datafusion/src/v2/source.rs @@ -409,15 +409,17 @@ impl VortexDataSource { /// /// The output partitions read the scan in one of two ways, chosen as DataFusion's own file scans /// choose whether to steal work. By default the scan is [opened] into a pool and every output -/// partition polls its own worker, so partitions that finish early take work from the others. +/// partition polls its own worker until it ends; the pool decides how work reaches the workers. /// When each partition must keep its rows in order, or when /// `datafusion.execution.enable_file_stream_work_stealing` is off, the scan is instead [split] /// into one piece per output partition, and partitions beyond the piece count return no rows. /// A direct [`DataSource::open`] without shared [`OpenArgs`] always splits, since its partition -/// cannot share a pool with the others. +/// cannot share a pool with the others. Setting [`SCAN_POOL_ENV`] to `0` instead reads the scan's +/// shared partition stream, for comparison. /// -/// As with DataFusion's work-stealing file scans, dropping an output partition before it ends -/// abandons the work it had taken, so a host drops one early only when it abandons the scan. +/// A pool may give up the work a worker had taken when that worker is dropped, so, as with +/// DataFusion's work-stealing file scans, a host drops an output partition early only when it +/// abandons the scan. /// /// [opened]: vortex::scan::DataSourceScan::open /// [split]: vortex::scan::DataSourceScan::split From 52a122f0f410f42128c26b61d66044fe93fa500b Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Thu, 19 Nov 2026 22:06:23 -0500 Subject: [PATCH 21/80] Run an unordered pool's units on the lane that takes them A lane is already a task on the session's runtime, so spawning each split and each deferred-file open as a second task and awaiting it only added a spawn and a cross-thread wake per unit. The ordered pool, whose units are polled by its worker on the host thread, still spawns them. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-layout/src/scan/pool.rs | 61 +++++++++++++++++++++++----------- 1 file changed, 42 insertions(+), 19 deletions(-) diff --git a/vortex-layout/src/scan/pool.rs b/vortex-layout/src/scan/pool.rs index fa58016a7dd..cd7fdfd9111 100644 --- a/vortex-layout/src/scan/pool.rs +++ b/vortex-layout/src/scan/pool.rs @@ -336,7 +336,7 @@ impl Shared { .collect() } - /// Opens a deferred file into its work on the session's runtime. A file that starts after + /// Opens a deferred file into its work, on the task that polls it. A file that starts after /// the limit is spent is not opened. fn open_file( self: &Arc, @@ -346,19 +346,28 @@ impl Shared { return future::ready(Ok(FileWork::empty())).boxed(); } let shared = Arc::clone(self); - self.session - .handle() - .spawn(async move { - let reader = factory - .open() - .instrument(tracing::info_span!("LayoutReaderFactory::open")) - .await?; - match (reader, &shared.prepare) { - (Some(reader), Some(prepare)) => prepare(reader), - _ => Ok(FileWork::empty()), - } - }) - .boxed() + async move { + let reader = factory + .open() + .instrument(tracing::info_span!("LayoutReaderFactory::open")) + .await?; + match (reader, &shared.prepare) { + (Some(reader), Some(prepare)) => prepare(reader), + _ => Ok(FileWork::empty()), + } + } + .boxed() + } + + /// Opens a deferred file into its work as a task on the session's runtime. + fn spawn_open_file( + self: &Arc, + factory: Arc, + ) -> BoxFuture<'static, VortexResult> { + if self.limit.is_spent() { + return future::ready(Ok(FileWork::empty())).boxed(); + } + self.session.handle().spawn(self.open_file(factory)).boxed() } /// The next deferred file of an unordered pool to open, if any is left and the limit is not @@ -372,8 +381,19 @@ impl Shared { deferred.pop_front() } - /// Takes a split and runs it on the session's runtime. - fn admit(self: &Arc, (file, index, progress): FileSplit) -> SplitOutput { + /// Takes a split and runs it as a task on the session's runtime. + fn admit(self: &Arc, split: FileSplit) -> SplitOutput { + self.take_split(split, true) + } + + /// Takes a split. A split of a scan with a filter and a limit is built and run as + /// [`spawn_lazy_split`] runs it; any other split runs as a task on the session's runtime when + /// `spawn` is set, or else on the task that polls it, such as a lane, which is already one. + fn take_split( + self: &Arc, + (file, index, progress): FileSplit, + spawn: bool, + ) -> SplitOutput { *self.progress.lock() += progress; let handle = self.session.handle(); if let PoolLimit::Trim(_) = &self.limit { @@ -387,7 +407,8 @@ impl Shared { async move { let task = file.tasks(&shared.limit).await?[index].lock().take(); match task { - Some(task) => handle.spawn(task).await, + Some(task) if spawn => handle.spawn(task).await, + Some(task) => task.await, None => Ok(None), } } @@ -519,9 +540,11 @@ struct UnorderedPool { } impl UnorderedPool { + /// Runs a unit on the lane that took it. The lane is already a task on the runtime, so + /// spawning the unit as another task would only add a hop. fn run(shared: &Arc, work: Work) -> SplitOutput { match work { - Work::Split(split) => shared.admit(split), + Work::Split(split) => shared.take_split(split, false), Work::Open(factory, slot) => async move { let opened = slot.shared.open_file(factory).await.map(|work| { for split in slot.shared.file_splits(work) { @@ -673,7 +696,7 @@ impl ScanPool for OrderedPool { let outputs = stream::iter(files) .map(move |file| match file { PoolFile::Opened(work) => future::ready(Ok(work)).boxed(), - PoolFile::Deferred(factory) => opener.open_file(factory), + PoolFile::Deferred(factory) => opener.spawn_open_file(factory), }) .buffered(self.open_concurrency) .flat_map(move |work| match work { From 530b9434c6cabeda141b6f35c9f494de2553edcf Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Thu, 19 Nov 2026 22:07:19 -0500 Subject: [PATCH 22/80] Recheck whole-file pruning when a pooled file's first split is taken A pool checks a file's statistics against the filter when the file starts, which for an opened scan is when the pool opens. A filter with dynamic parts, such as a join's, may reject the file by the time its splits run, and execute_stream checks when it starts reading. Check again, once per file, when the first split is taken. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-layout/src/scan/pool.rs | 39 +++++++++++++++++++++---- vortex-layout/src/scan/repeated_scan.rs | 7 +++++ 2 files changed, 41 insertions(+), 5 deletions(-) diff --git a/vortex-layout/src/scan/pool.rs b/vortex-layout/src/scan/pool.rs index cd7fdfd9111..01248d86547 100644 --- a/vortex-layout/src/scan/pool.rs +++ b/vortex-layout/src/scan/pool.rs @@ -75,6 +75,7 @@ use crate::scan::repeated_scan::MapFn; use crate::scan::repeated_scan::RepeatedScan; use crate::scan::repeated_scan::SplitConcurrency; use crate::scan::repeated_scan::can_prune_file; +use crate::scan::repeated_scan::recheck_prune_file; use crate::scan::repeated_scan::spawn_lazy_split; use crate::scan::repeated_scan::spawn_map_trimmed; use crate::scan::repeated_scan::stop_on_error; @@ -98,15 +99,33 @@ pub(crate) struct FileScan { /// The task of each split, built together when a worker first takes one of them. `None` /// where the split has no rows to read, or a worker has taken it. tasks: OnceCell>>>, + /// Whether whole-file statistics reject the filter when the file's first split is taken. + pruned: OnceCell, } impl FileScan { + /// Whether whole-file statistics reject the filter, checked again when the first split is + /// taken, as [`RepeatedScan::execute_stream`] checks when it starts: a filter with dynamic + /// parts may reject the file by then though it did not when the pool was opened. + async fn is_pruned(&self) -> VortexResult { + let pruned = self + .pruned + .get_or_try_init(|| future::ready(recheck_prune_file(&self.ctx))) + .await?; + Ok(*pruned) + } + /// The tasks of the file's splits, built on first use. A file whose tasks are built once a - /// reserved limit is spent builds none. + /// reserved limit is spent, or that statistics now reject, builds none. async fn tasks(&self, limit: &PoolLimit) -> VortexResult<&[Mutex>]> { let tasks = self .tasks - .get_or_try_init(|| future::ready(self.build_tasks(limit))) + .get_or_try_init(|| async { + if self.is_pruned().await? { + return Ok(Vec::new()); + } + self.build_tasks(limit) + }) .await?; Ok(tasks) } @@ -162,6 +181,7 @@ impl FileWork { ctx, ranges, tasks: OnceCell::new(), + pruned: OnceCell::new(), })), }) } @@ -400,12 +420,21 @@ impl Shared { let Some(mask) = file.scan.split_mask(&file.ranges[index]) else { return future::ready(Ok(None)).boxed(); }; - return spawn_lazy_split(&handle, move || split_exec(&file.ctx, mask).map(Some)) - .boxed(); + return async move { + if file.is_pruned().await? { + return Ok(None); + } + spawn_lazy_split(&handle, move || split_exec(&file.ctx, mask).map(Some)).await + } + .boxed(); } let shared = Arc::clone(self); async move { - let task = file.tasks(&shared.limit).await?[index].lock().take(); + let task = file + .tasks(&shared.limit) + .await? + .get(index) + .and_then(|task| task.lock().take()); match task { Some(task) if spawn => handle.spawn(task).await, Some(task) => task.await, diff --git a/vortex-layout/src/scan/repeated_scan.rs b/vortex-layout/src/scan/repeated_scan.rs index 4431e452ce9..e1654b05e98 100644 --- a/vortex-layout/src/scan/repeated_scan.rs +++ b/vortex-layout/src/scan/repeated_scan.rs @@ -417,6 +417,13 @@ fn selected_mask(selection: &Selection, range: &Range) -> Option { /// Counts a file scan attempt and returns whether whole-file statistics reject the filter. pub(crate) fn can_prune_file(ctx: &TaskContext) -> VortexResult { ctx.count::(ScanRecorder::attempt_file_scan); + recheck_prune_file(ctx) +} + +/// Returns whether whole-file statistics reject the filter, for a file whose scan attempt +/// [`can_prune_file`] has already counted. A filter with dynamic parts, such as a join's, may +/// reject a file later that it did not reject when the scan started. +pub(crate) fn recheck_prune_file(ctx: &TaskContext) -> VortexResult { if let Some(filter) = &ctx.filter && can_prune_conjuncts(filter, ctx.reader.as_ref())? { From 99967430e21b2cfebcb4dcc7f25057b423c6085a Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Thu, 19 Nov 2026 22:10:32 -0500 Subject: [PATCH 23/80] Start an unordered pool's lanes only as units are ready A pool started splits_in_flight lanes, four per core, when its first worker started, and woke every one of them to end, however few units the scan had. A TPC-H query scans several small single-file tables, so it paid that spawn and teardown once per table. Lanes now start one for each unit that no waiting lane will take, when the first worker starts and whenever a lane takes a unit with more queued behind it, up to splits_in_flight. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-layout/src/scan/pool.rs | 113 ++++++++++++++++++++++----------- 1 file changed, 77 insertions(+), 36 deletions(-) diff --git a/vortex-layout/src/scan/pool.rs b/vortex-layout/src/scan/pool.rs index 01248d86547..5f367d2883f 100644 --- a/vortex-layout/src/scan/pool.rs +++ b/vortex-layout/src/scan/pool.rs @@ -19,10 +19,11 @@ //! //! The pools differ in how workers share the work: //! -//! - An unordered pool runs `splits_in_flight` lanes on the runtime once its first worker starts. -//! Each lane takes the next unit from a channel of units, runs it, and sends its rows into one -//! bounded output channel; a lane that opens a deferred file sends the file's splits back into -//! the channel of units, followed by the next deferred file. Workers only take rows from the +//! - An unordered pool runs lanes on the runtime once its first worker starts: one for each unit +//! that is ready, more as units queue, and at most `splits_in_flight`. Each lane takes the next +//! unit from a channel of units, runs it, and sends its rows into one bounded output channel; a +//! lane that opens a deferred file sends the file's splits back into the channel of units, +//! followed by the next deferred file. Workers only take rows from the //! output channel, so whichever worker asks next gets the next rows, however many workers there //! are, and the number of workers is only the host's parallelism. The output channel closes //! once every lane has finished, which ends the workers. @@ -36,6 +37,7 @@ use std::num::NonZeroUsize; use std::ops::Range; use std::sync::Arc; use std::sync::atomic::AtomicBool; +use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering; use async_channel::Receiver; @@ -272,13 +274,21 @@ pub(crate) fn open_pool( } } let (output, outputs) = async_channel::bounded(splits_in_flight); + let lanes = Arc::new(Lanes { + shared: Arc::clone(&shared), + units: receiver.clone(), + max: splits_in_flight, + waiting: AtomicUsize::new(0), + started: AtomicUsize::new(0), + tasks: Mutex::new(Some(Vec::new())), + }); Arc::new(UnorderedPool { dtype: options.dtype, shared, units: receiver, outputs, - lanes: Mutex::new(Lanes::Idle(output)), - splits_in_flight, + lanes, + output: Mutex::new(Some(output)), }) } @@ -547,15 +557,49 @@ fn send(sender: &Sender, work: Work) { drop(sender.try_send(work)); } -/// The lanes of an unordered pool. -enum Lanes { - /// Not started: the sender of the output channel, for the lanes to hold once they start. - Idle(Sender>), - /// Running, until the pool is dropped, which aborts them. - Running( - #[expect(dead_code, reason = "held so that dropping the pool aborts the lanes")] - Vec>, - ), +/// The lanes of an unordered pool. They start when its first worker does, as many as there are +/// units ready, and grow while units wait for a lane, up to `splits_in_flight`, so a scan with +/// few units spawns and wakes few tasks. +struct Lanes { + shared: Arc, + units: Receiver, + /// The most lanes that run at once. + max: usize, + /// Lanes waiting for a unit. + waiting: AtomicUsize, + /// Lanes started, so a lane can see without a lock that no more may start. + started: AtomicUsize, + /// The lanes started, until the pool is dropped, which aborts them. `None` once it is. + tasks: Mutex>>>, +} + +impl Lanes { + /// Starts lanes for the units that no waiting lane will take, up to the most that run at + /// once. Each lane holds a sender of the output channel. + fn grow(self: &Arc, output: &Sender>) { + // Every lane calls this for every unit it takes, so it locks only to start lanes. + if self.started.load(Ordering::Acquire) >= self.max || self.unserved() == 0 { + return; + } + let mut tasks = self.tasks.lock(); + let Some(tasks) = tasks.as_mut() else { + return; + }; + let new = self.unserved().min(self.max.saturating_sub(tasks.len())); + if new == 0 { + return; + } + let handle = self.shared.session.handle(); + tasks.extend((0..new).map(|_| handle.spawn(lane(Arc::clone(self), output.clone())))); + self.started.store(tasks.len(), Ordering::Release); + } + + /// The units that the lanes waiting for one will not take. + fn unserved(&self) -> usize { + self.units + .len() + .saturating_sub(self.waiting.load(Ordering::Acquire)) + } } /// A pool whose lanes run its units on the runtime, and whose workers share their output. @@ -564,8 +608,10 @@ struct UnorderedPool { shared: Arc, units: Receiver, outputs: Receiver>, - lanes: Mutex, - splits_in_flight: usize, + lanes: Arc, + /// The sender of the output channel until the first worker starts the lanes, which hold it + /// from then on. + output: Mutex>>>, } impl UnorderedPool { @@ -588,38 +634,32 @@ impl UnorderedPool { } } - /// Starts the lanes, once. + /// Starts the lanes, once. With no units, it starts none, and the output channel closes. fn start_lanes(&self) { - let mut lanes = self.lanes.lock(); - let Lanes::Idle(output) = &*lanes else { - return; - }; - let output = output.clone(); - let handle = self.shared.session.handle(); - let running = (0..self.splits_in_flight) - .map(|_| { - handle.spawn(lane( - Arc::clone(&self.shared), - self.units.clone(), - output.clone(), - )) - }) - .collect(); // Dropping the pool's own sender leaves the lanes holding the output channel open. - *lanes = Lanes::Running(running); + if let Some(output) = self.output.lock().take() { + self.lanes.grow(&output); + } } } /// A lane: runs units one at a time and sends their rows to the workers, trimming them to a /// trimmed limit. Ends once the units run out, a limit is spent, a unit fails, or every worker /// is gone. -async fn lane(shared: Arc, units: Receiver, output: Sender>) { +async fn lane(lanes: Arc, output: Sender>) { + let shared = Arc::clone(&lanes.shared); let handle = shared.session.handle(); let identity: MapFn = Arc::new(Ok); while !shared.limit.is_trimmed_out() && !shared.failed.load(Ordering::Acquire) { - let Ok(work) = units.recv().await else { + lanes.waiting.fetch_add(1, Ordering::AcqRel); + let work = lanes.units.recv().await; + lanes.waiting.fetch_sub(1, Ordering::AcqRel); + let Ok(work) = work else { return; }; + // Units the waiting lanes will not take get lanes of their own, such as the splits an + // open has just queued. + lanes.grow(&output); let array = match UnorderedPool::run(&shared, work).await { Ok(Some(array)) => Ok(array), Ok(None) => continue, @@ -693,6 +733,7 @@ impl Drop for UnorderedPool { self.units.close(); while self.units.try_recv().is_ok() {} self.outputs.close(); + drop(self.lanes.tasks.lock().take()); } } From 235d5396e95e31d43a97ca08ff2088611e41b02e Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Thu, 19 Nov 2026 22:36:46 -0500 Subject: [PATCH 24/80] Read an unordered pool's opened files in turn An unordered pool queued each opened file's splits one after another, so its lanes read about one file at a time. A wide scan then waited on that file's read latency, and every split of the file was started before the first rows could tighten a dynamic filter. Each opened file is now one turn in the channel: a lane takes the file's next split and queues the turn again behind the other files', so the lanes read the open files' splits in turn. On ClickBench q23 through DataFusion this cut wall time from 169 to 114 ms (develop: 139 ms) and scan output rows from 886 to 400 (develop: 2,425); q22 returned to parity. Lanes now grow with the splits and opens pending rather than the units in the channel, since a file is a single unit. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-layout/src/scan/multi.rs | 18 ++++++ vortex-layout/src/scan/pool.rs | 107 +++++++++++++++++++++++--------- 2 files changed, 96 insertions(+), 29 deletions(-) diff --git a/vortex-layout/src/scan/multi.rs b/vortex-layout/src/scan/multi.rs index 9ccbe87712d..b2960e702bd 100644 --- a/vortex-layout/src/scan/multi.rs +++ b/vortex-layout/src/scan/multi.rs @@ -1345,6 +1345,24 @@ mod pool_tests { Ok(()) } + /// An unordered pool takes the opened files' splits in turn. With one lane, rows come out in + /// the order the lane takes splits. + #[test] + fn unordered_splits_interleave_across_files() -> VortexResult<()> { + let (source, gates) = gated_source(2, 3); + for gate in &gates { + gate.release(); + } + let request = ScanRequest { + split_concurrency: NonZeroUsize::new(1), + ..Default::default() + }; + let pool = plan(&source.with_concurrency(2), request)?.open()?; + let values = collect_scan_values(futures::executor::block_on_stream(pool.worker()))?; + assert_eq!(values, [0, 100, 1, 101, 2, 102]); + Ok(()) + } + /// An ordered worker emits files in file order, even when a later file opens first. #[test] fn ordered_worker_emits_files_in_order() -> VortexResult<()> { diff --git a/vortex-layout/src/scan/pool.rs b/vortex-layout/src/scan/pool.rs index 5f367d2883f..5abc7825de4 100644 --- a/vortex-layout/src/scan/pool.rs +++ b/vortex-layout/src/scan/pool.rs @@ -19,11 +19,12 @@ //! //! The pools differ in how workers share the work: //! -//! - An unordered pool runs lanes on the runtime once its first worker starts: one for each unit -//! that is ready, more as units queue, and at most `splits_in_flight`. Each lane takes the next -//! unit from a channel of units, runs it, and sends its rows into one bounded output channel; a -//! lane that opens a deferred file sends the file's splits back into the channel of units, -//! followed by the next deferred file. Workers only take rows from the +//! - An unordered pool runs lanes on the runtime once its first worker starts: one for each split +//! or open that is ready, more as they queue, and at most `splits_in_flight`. Each lane takes the +//! next unit from a channel of units, runs it, and sends its rows into one bounded output +//! channel. An opened file is one unit, its turn, which a lane queues again after taking the +//! file's next split, so the lanes read the opened files' splits in turn. A lane that opens a +//! deferred file queues the file's turn, followed by the next deferred file. Workers only take rows from the //! output channel, so whichever worker asks next gets the next rows, however many workers there //! are, and the number of workers is only the host's parallelism. The output channel closes //! once every lane has finished, which ends the workers. @@ -242,6 +243,7 @@ pub(crate) fn open_pool( progress: Mutex::new(0.0), deferred: Mutex::new(VecDeque::new()), failed: AtomicBool::new(false), + pending: AtomicUsize::new(0), }); if options.ordered { return Arc::new(OrderedPool { @@ -257,18 +259,14 @@ pub(crate) fn open_pool( let mut opens = 0; for file in files { match file { - PoolFile::Opened(work) => { - for split in shared.file_splits(work) { - send(&sender, Work::Split(split)); - } - } + PoolFile::Opened(work) => shared.queue_file(&sender, work), PoolFile::Deferred(factory) if opens < open_concurrency => { opens += 1; let slot = OpenSlot { shared: Arc::clone(&shared), sender: sender.clone(), }; - send(&sender, Work::Open(factory, slot)); + shared.queue(&sender, Work::Open(factory, slot)); } PoolFile::Deferred(factory) => shared.deferred.lock().push_back(factory), } @@ -338,6 +336,8 @@ struct Shared { deferred: Mutex>>, /// Whether a unit of an unordered pool failed, which stops its lanes. failed: AtomicBool, + /// The splits and opens of an unordered pool that are queued and not yet taken by a lane. + pending: AtomicUsize, } impl Shared { @@ -454,6 +454,24 @@ impl Shared { .boxed() } + /// Queues a unit of an unordered pool, counting the splits or open it holds as pending. + fn queue(&self, sender: &Sender, work: Work) { + let units = match &work { + Work::File(splits, _) => splits.len(), + Work::Open(..) => 1, + }; + self.pending.fetch_add(units, Ordering::AcqRel); + send(sender, work); + } + + /// Queues an opened file of an unordered pool as one turn among the files. + fn queue_file(&self, sender: &Sender, work: FileWork) { + let splits: VecDeque = self.file_splits(work).into(); + if !splits.is_empty() { + self.queue(sender, Work::File(splits, sender.clone())); + } + } + fn progress(&self) -> f64 { if self.limit.is_trimmed_out() { return 1.0; @@ -520,13 +538,41 @@ fn limit_output( .boxed() } -/// A unit of an unordered pool. +/// A unit of an unordered pool's channel. enum Work { + /// An opened file's turn: the splits not yet taken, in row order. The lane that takes the + /// turn takes the file's next split and queues the turn again behind the other files' turns, + /// so the lanes take splits from every opened file in turn rather than from one file after + /// another. Each file then has only a few splits in flight, which keeps its first rows, and + /// any dynamic filter they tighten, ahead of its later splits. + File(VecDeque, Sender), + /// A deferred file, and the open slot it holds until its turn is in the channel. + Open(Arc, OpenSlot), +} + +/// What a lane takes from a unit. +enum Taken { Split(FileSplit), - /// A deferred file, and the open slot it holds until its splits are in the channel. Open(Arc, OpenSlot), } +impl Work { + /// Takes the unit's split or open, queueing a file's turn again while it has splits left. + fn take(self) -> Option { + match self { + Work::File(mut splits, sender) => { + let split = splits.pop_front()?; + if !splits.is_empty() { + let requeue = sender.clone(); + send(&requeue, Work::File(splits, sender)); + } + Some(Taken::Split(split)) + } + Work::Open(factory, slot) => Some(Taken::Open(factory, slot)), + } + } +} + /// One of an unordered pool's `open_concurrency` open slots. Its sender keeps the channel open /// while the file that holds it is queued or opening. struct OpenSlot { @@ -535,8 +581,8 @@ struct OpenSlot { } impl Drop for OpenSlot { - /// Passes the slot to the next deferred file, queued behind the splits of the file that held - /// it, so opens keep pace with the workers. The slot passes on whether the open finished or a + /// Passes the slot to the next deferred file, queued behind the turns already in the channel, + /// so opens keep pace with the workers. The slot passes on whether the open finished or a /// dropped worker gave it up, so that worker strands only the file it was opening. fn drop(&mut self) { if self.sender.is_closed() { @@ -547,7 +593,7 @@ impl Drop for OpenSlot { shared: Arc::clone(&self.shared), sender: self.sender.clone(), }; - send(&self.sender, Work::Open(next, slot)); + self.shared.queue(&self.sender, Work::Open(next, slot)); } } } @@ -558,8 +604,8 @@ fn send(sender: &Sender, work: Work) { } /// The lanes of an unordered pool. They start when its first worker does, as many as there are -/// units ready, and grow while units wait for a lane, up to `splits_in_flight`, so a scan with -/// few units spawns and wakes few tasks. +/// splits and opens ready, and grow while those wait for a lane, up to `splits_in_flight`, so a +/// scan with few units spawns and wakes few tasks. struct Lanes { shared: Arc, units: Receiver, @@ -594,10 +640,11 @@ impl Lanes { self.started.store(tasks.len(), Ordering::Release); } - /// The units that the lanes waiting for one will not take. + /// The pending splits and opens that the lanes waiting for one will not take. fn unserved(&self) -> usize { - self.units - .len() + self.shared + .pending + .load(Ordering::Acquire) .saturating_sub(self.waiting.load(Ordering::Acquire)) } } @@ -617,14 +664,12 @@ struct UnorderedPool { impl UnorderedPool { /// Runs a unit on the lane that took it. The lane is already a task on the runtime, so /// spawning the unit as another task would only add a hop. - fn run(shared: &Arc, work: Work) -> SplitOutput { - match work { - Work::Split(split) => shared.take_split(split, false), - Work::Open(factory, slot) => async move { + fn run(shared: &Arc, taken: Taken) -> SplitOutput { + match taken { + Taken::Split(split) => shared.take_split(split, false), + Taken::Open(factory, slot) => async move { let opened = slot.shared.open_file(factory).await.map(|work| { - for split in slot.shared.file_splits(work) { - send(&slot.sender, Work::Split(split)); - } + slot.shared.queue_file(&slot.sender, work); None }); drop(slot); @@ -657,10 +702,14 @@ async fn lane(lanes: Arc, output: Sender>) { let Ok(work) = work else { return; }; + let Some(taken) = work.take() else { + continue; + }; + shared.pending.fetch_sub(1, Ordering::AcqRel); // Units the waiting lanes will not take get lanes of their own, such as the splits an // open has just queued. lanes.grow(&output); - let array = match UnorderedPool::run(&shared, work).await { + let array = match UnorderedPool::run(&shared, taken).await { Ok(Some(array)) => Ok(array), Ok(None) => continue, Err(err) => Err(err), From 3cd041935340438883ba4fc73f4e6884a9aa7cf8 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Thu, 19 Nov 2026 23:36:33 -0500 Subject: [PATCH 25/80] Hand out an unordered pool's files in runs of adjacent splits Reading opened files in turn handed each file's read driver one polled split at a time, so adjacent splits no longer coalesced into shared reads, and short filtered scans such as ClickBench q01 and q06 paid for many more object-store reads. A file's turn now gives a lane a run of adjacent splits, its share of the splits in flight (splits_in_flight / open_concurrency, four with the defaults), which the lane polls together. The files still rotate, a run at a time, and the lanes still hold splits_in_flight splits in all. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-layout/src/scan/pool.rs | 173 +++++++++++++++++++++------------ 1 file changed, 109 insertions(+), 64 deletions(-) diff --git a/vortex-layout/src/scan/pool.rs b/vortex-layout/src/scan/pool.rs index 5abc7825de4..2f37745a922 100644 --- a/vortex-layout/src/scan/pool.rs +++ b/vortex-layout/src/scan/pool.rs @@ -19,21 +19,24 @@ //! //! The pools differ in how workers share the work: //! -//! - An unordered pool runs lanes on the runtime once its first worker starts: one for each split -//! or open that is ready, more as they queue, and at most `splits_in_flight`. Each lane takes the -//! next unit from a channel of units, runs it, and sends its rows into one bounded output -//! channel. An opened file is one unit, its turn, which a lane queues again after taking the -//! file's next split, so the lanes read the opened files' splits in turn. A lane that opens a -//! deferred file queues the file's turn, followed by the next deferred file. Workers only take rows from the -//! output channel, so whichever worker asks next gets the next rows, however many workers there -//! are, and the number of workers is only the host's parallelism. The output channel closes -//! once every lane has finished, which ends the workers. +//! - An unordered pool runs lanes on the runtime once its first worker starts: one for each run +//! of splits or open that is ready, more as they queue, and at most enough to keep +//! `splits_in_flight` splits running. Each lane takes the next unit from a channel of units, +//! runs it, and sends its rows into one bounded output channel. An opened file is one unit, its +//! turn, which a lane queues again after taking the file's next run of adjacent splits, so the +//! lanes read the opened files in turn, a run at a time, and poll each run's splits together so +//! that their reads coalesce. A lane that opens a deferred file queues the file's turn, followed +//! by the next deferred file. Workers only take rows from the output channel, so whichever +//! worker asks next gets the next rows, however many workers there are, and the number of +//! workers is only the host's parallelism. The output channel closes once every lane has +//! finished, which ends the workers. //! - An ordered pool gives all of its units, in row order, to its first worker, which keeps //! `splits_in_flight` of them running at once; later workers get nothing. Parallel ordered reads //! cut the scan with `split` first. use std::any::Any; use std::collections::VecDeque; +use std::iter; use std::num::NonZeroUsize; use std::ops::Range; use std::sync::Arc; @@ -50,6 +53,7 @@ use futures::future; use futures::future::BoxFuture; use futures::stream; use futures::stream::BoxStream; +use futures::stream::FuturesUnordered; use parking_lot::Mutex; use tracing::Instrument; use vortex_array::ArrayRef; @@ -59,6 +63,7 @@ use vortex_array::stream::ArrayStreamAdapter; use vortex_array::stream::ArrayStreamExt; use vortex_array::stream::SendableArrayStream; use vortex_error::VortexResult; +use vortex_io::runtime::Handle; use vortex_io::runtime::Task; use vortex_io::session::RuntimeSessionExt; use vortex_scan::DataSourceScanRef; @@ -271,11 +276,18 @@ pub(crate) fn open_pool( PoolFile::Deferred(factory) => shared.deferred.lock().push_back(factory), } } + // Each open file gets an equal share of the splits in flight, and a lane takes a file's share + // as one run of adjacent splits that it polls together. The run's reads then reach the + // file's read driver together and coalesce, as they do when one scan stream polls its + // file's splits; a run of one would hand the driver one read at a time. The rotation moves + // between files after each run, and the lanes hold `splits_in_flight` splits in all. + let run = (splits_in_flight / open_concurrency).max(1); let (output, outputs) = async_channel::bounded(splits_in_flight); let lanes = Arc::new(Lanes { shared: Arc::clone(&shared), units: receiver.clone(), - max: splits_in_flight, + run, + max: (splits_in_flight / run).max(1), waiting: AtomicUsize::new(0), started: AtomicUsize::new(0), tasks: Mutex::new(Some(Vec::new())), @@ -541,9 +553,9 @@ fn limit_output( /// A unit of an unordered pool's channel. enum Work { /// An opened file's turn: the splits not yet taken, in row order. The lane that takes the - /// turn takes the file's next split and queues the turn again behind the other files' turns, - /// so the lanes take splits from every opened file in turn rather than from one file after - /// another. Each file then has only a few splits in flight, which keeps its first rows, and + /// turn takes the file's next run of splits and queues the turn again behind the other + /// files' turns, so the lanes take runs from every opened file in turn rather than from one + /// file after another. Each file then has only a few splits in flight, which keeps its first rows, and /// any dynamic filter they tighten, ahead of its later splits. File(VecDeque, Sender), /// A deferred file, and the open slot it holds until its turn is in the channel. @@ -552,21 +564,33 @@ enum Work { /// What a lane takes from a unit. enum Taken { - Split(FileSplit), + /// A run of a file's adjacent splits, in row order. + Splits(Vec), Open(Arc, OpenSlot), } +impl Taken { + /// The pending splits or open that this takes. + fn units(&self) -> usize { + match self { + Taken::Splits(splits) => splits.len(), + Taken::Open(..) => 1, + } + } +} + impl Work { - /// Takes the unit's split or open, queueing a file's turn again while it has splits left. - fn take(self) -> Option { + /// Takes the unit's next `run` splits, or its open, queueing a file's turn again while it + /// has splits left. + fn take(self, run: usize) -> Option { match self { Work::File(mut splits, sender) => { - let split = splits.pop_front()?; + let taken: Vec<_> = splits.drain(..run.min(splits.len())).collect(); if !splits.is_empty() { let requeue = sender.clone(); send(&requeue, Work::File(splits, sender)); } - Some(Taken::Split(split)) + (!taken.is_empty()).then_some(Taken::Splits(taken)) } Work::Open(factory, slot) => Some(Taken::Open(factory, slot)), } @@ -609,6 +633,8 @@ fn send(sender: &Sender, work: Work) { struct Lanes { shared: Arc, units: Receiver, + /// The most adjacent splits of a file that a lane takes and polls together. + run: usize, /// The most lanes that run at once. max: usize, /// Lanes waiting for a unit. @@ -631,7 +657,10 @@ impl Lanes { let Some(tasks) = tasks.as_mut() else { return; }; - let new = self.unserved().min(self.max.saturating_sub(tasks.len())); + let new = self + .unserved() + .div_ceil(self.run) + .min(self.max.saturating_sub(tasks.len())); if new == 0 { return; } @@ -640,12 +669,13 @@ impl Lanes { self.started.store(tasks.len(), Ordering::Release); } - /// The pending splits and opens that the lanes waiting for one will not take. + /// The pending splits and opens that the lanes waiting for a unit will not take, each of + /// which takes up to a run. fn unserved(&self) -> usize { self.shared .pending .load(Ordering::Acquire) - .saturating_sub(self.waiting.load(Ordering::Acquire)) + .saturating_sub(self.waiting.load(Ordering::Acquire) * self.run) } } @@ -664,18 +694,24 @@ struct UnorderedPool { impl UnorderedPool { /// Runs a unit on the lane that took it. The lane is already a task on the runtime, so /// spawning the unit as another task would only add a hop. - fn run(shared: &Arc, taken: Taken) -> SplitOutput { + fn run(shared: &Arc, taken: Taken) -> FuturesUnordered { match taken { - Taken::Split(split) => shared.take_split(split, false), - Taken::Open(factory, slot) => async move { - let opened = slot.shared.open_file(factory).await.map(|work| { - slot.shared.queue_file(&slot.sender, work); - None - }); - drop(slot); - opened - } - .boxed(), + Taken::Splits(splits) => splits + .into_iter() + .map(|split| shared.take_split(split, false)) + .collect(), + Taken::Open(factory, slot) => iter::once( + async move { + let opened = slot.shared.open_file(factory).await.map(|work| { + slot.shared.queue_file(&slot.sender, work); + None + }); + drop(slot); + opened + } + .boxed(), + ) + .collect(), } } @@ -702,47 +738,56 @@ async fn lane(lanes: Arc, output: Sender>) { let Ok(work) = work else { return; }; - let Some(taken) = work.take() else { + let Some(taken) = work.take(lanes.run) else { continue; }; - shared.pending.fetch_sub(1, Ordering::AcqRel); + shared.pending.fetch_sub(taken.units(), Ordering::AcqRel); // Units the waiting lanes will not take get lanes of their own, such as the splits an // open has just queued. lanes.grow(&output); - let array = match UnorderedPool::run(&shared, taken).await { - Ok(Some(array)) => Ok(array), - Ok(None) => continue, - Err(err) => Err(err), - }; - let array = match (&shared.limit, array) { - (PoolLimit::Trim(limit), Ok(array)) => { - let granted = limit.take(array.len()); - if granted == 0 { - return; - } - let array = if granted < array.len() { - array.slice(0..granted) - } else { - Ok(array) - }; - spawn_map_trimmed( - &handle, - shared.session.clone(), - Arc::clone(&identity), - array, - ) - .await + let mut running = UnorderedPool::run(&shared, taken); + while let Some(array) = running.next().await { + let array = match array { + Ok(Some(array)) => Ok(array), + Ok(None) => continue, + Err(err) => Err(err), + }; + if !emit(&shared, &handle, &identity, &output, array).await { + return; } - (_, array) => array, - }; - let failed = array.is_err(); - if failed { - shared.failed.store(true, Ordering::Release); } - if output.send(array).await.is_err() || failed { - return; + } +} + +/// Sends a lane's rows to the workers, trimmed to a trimmed limit. Returns whether the lane +/// should go on: not once the limit is spent, a unit failed, or every worker is gone. +async fn emit( + shared: &Shared, + handle: &Handle, + identity: &MapFn, + output: &Sender>, + array: VortexResult, +) -> bool { + let array = match (&shared.limit, array) { + (PoolLimit::Trim(limit), Ok(array)) => { + let granted = limit.take(array.len()); + if granted == 0 { + return false; + } + let array = if granted < array.len() { + array.slice(0..granted) + } else { + Ok(array) + }; + spawn_map_trimmed(handle, shared.session.clone(), Arc::clone(identity), array).await } + (_, array) => array, + }; + let failed = array.is_err(); + if failed { + shared.failed.store(true, Ordering::Release); } + output.send(array).await.is_ok() && !failed } impl ScanPool for UnorderedPool { From 03bc34a0188d7e1cfc53790429d486b4e9eefd8e Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Thu, 19 Nov 2026 23:55:47 -0500 Subject: [PATCH 26/80] Decode a single-file pool's splits on every core A single-file scan opens one file at a time, so its run was every split in flight and the pool started one lane, which polled the run's splits inline and decoded them on one thread. A run is now at most one core's share of the splits in flight, and each split of a run is spawned as `execute_stream` spawns it: the run still starts its splits together, so their reads coalesce, but they decode in parallel. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-layout/src/scan/pool.rs | 38 ++++++++++++++++------------------ 1 file changed, 18 insertions(+), 20 deletions(-) diff --git a/vortex-layout/src/scan/pool.rs b/vortex-layout/src/scan/pool.rs index 2f37745a922..f345e908c0a 100644 --- a/vortex-layout/src/scan/pool.rs +++ b/vortex-layout/src/scan/pool.rs @@ -74,6 +74,7 @@ use vortex_scan::pool::ScanPool; use vortex_scan::pool::ScanPoolRef; use vortex_scan::row_mask::RowMask; use vortex_session::VortexSession; +use vortex_utils::parallelism::get_available_parallelism; use crate::LayoutReaderRef; use crate::scan::limit::RowLimit; @@ -277,11 +278,16 @@ pub(crate) fn open_pool( } } // Each open file gets an equal share of the splits in flight, and a lane takes a file's share - // as one run of adjacent splits that it polls together. The run's reads then reach the + // as one run of adjacent splits that it starts together. The run's reads then reach the // file's read driver together and coalesce, as they do when one scan stream polls its // file's splits; a run of one would hand the driver one read at a time. The rotation moves - // between files after each run, and the lanes hold `splits_in_flight` splits in all. - let run = (splits_in_flight / open_concurrency).max(1); + // between files after each run, and the lanes hold `splits_in_flight` splits in all. A run is + // at most one core's share, so that a scan of few files, such as a single-file scan whose + // share is every split in flight, still has a lane per core. + let cores = get_available_parallelism().unwrap_or(1).max(1); + let run = (splits_in_flight / open_concurrency) + .min(splits_in_flight / cores) + .max(1); let (output, outputs) = async_channel::bounded(splits_in_flight); let lanes = Arc::new(Lanes { shared: Arc::clone(&shared), @@ -423,19 +429,10 @@ impl Shared { deferred.pop_front() } - /// Takes a split and runs it as a task on the session's runtime. - fn admit(self: &Arc, split: FileSplit) -> SplitOutput { - self.take_split(split, true) - } - /// Takes a split. A split of a scan with a filter and a limit is built and run as - /// [`spawn_lazy_split`] runs it; any other split runs as a task on the session's runtime when - /// `spawn` is set, or else on the task that polls it, such as a lane, which is already one. - fn take_split( - self: &Arc, - (file, index, progress): FileSplit, - spawn: bool, - ) -> SplitOutput { + /// [`spawn_lazy_split`] runs it; any other split runs as a task on the session's runtime, since + /// a split decodes inside its future. + fn admit(self: &Arc, (file, index, progress): FileSplit) -> SplitOutput { *self.progress.lock() += progress; let handle = self.session.handle(); if let PoolLimit::Trim(_) = &self.limit { @@ -458,8 +455,7 @@ impl Shared { .get(index) .and_then(|task| task.lock().take()); match task { - Some(task) if spawn => handle.spawn(task).await, - Some(task) => task.await, + Some(task) => handle.spawn(task).await, None => Ok(None), } } @@ -692,13 +688,15 @@ struct UnorderedPool { } impl UnorderedPool { - /// Runs a unit on the lane that took it. The lane is already a task on the runtime, so - /// spawning the unit as another task would only add a hop. + /// Runs a unit for the lane that took it. Each split of a run runs as a task of its own, as + /// [`RepeatedScan::execute_stream`] runs it, since a split decodes inside its future: the run's + /// splits start together, so their reads coalesce, and decode on as many threads as there + /// are splits. An open runs on the lane itself. fn run(shared: &Arc, taken: Taken) -> FuturesUnordered { match taken { Taken::Splits(splits) => splits .into_iter() - .map(|split| shared.take_split(split, false)) + .map(|split| shared.admit(split)) .collect(), Taken::Open(factory, slot) => iter::once( async move { From 794ac0c4cd896121afdba08c4c6215468276837f Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 13:12:31 -0500 Subject: [PATCH 27/80] 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 5d18c27db09862c09ad7a78b3c8d2ccfc3b37186 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 13:21:32 -0500 Subject: [PATCH 28/80] Read V1 layout scans through split and open on develop's pipeline Each host should get develop's execution unchanged, so this replaces the shared layout pool with develop's own paths. A single-file scan opens into a queue of its split futures from RepeatedScan::execute: a worker claims the next split and runs it outside the lock, one at a time, which is how DuckDB's threads read a file's splits on develop. A limited or ordered scan, and a multi-file scan, open into a PartitionPool over their unchanged partition pipeline. split cuts a file at its layout split boundaries, and a multi-file scan into groups of whole files, reading metadata only. The I/O and execute_stream changes that served the old pool are reverted. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-io/src/segments/shared.rs | 128 +--- vortex-layout/src/scan/layout.rs | 687 ++++-------------- vortex-layout/src/scan/multi.rs | 926 +++--------------------- vortex-layout/src/scan/pool.rs | 922 ++--------------------- vortex-layout/src/scan/repeated_scan.rs | 111 +-- vortex-layout/src/scan/scan_builder.rs | 5 +- vortex-layout/src/scan/test.rs | 59 -- 7 files changed, 320 insertions(+), 2518 deletions(-) diff --git a/vortex-io/src/segments/shared.rs b/vortex-io/src/segments/shared.rs index bed9394a9d2..dbaf553264a 100644 --- a/vortex-io/src/segments/shared.rs +++ b/vortex-io/src/segments/shared.rs @@ -6,7 +6,6 @@ use std::sync::Arc; use futures::FutureExt; use futures::TryFutureExt; use futures::future::BoxFuture; -use futures::future::Shared; use futures::future::WeakShared; use vortex_array::buffer::BufferHandle; use vortex_error::SharedVortexResult; @@ -21,11 +20,6 @@ use super::SegmentSource; /// A [`SegmentSource`] that allows multiple requesters to await the same underlying segment /// request. -/// -/// Many threads may request segments of one source at once, for example the workers of a scan -/// pool sharing one file's splits. Requests therefore look for a request in flight under a shared -/// lock, call the inner source outside any lock, and take an exclusive lock only to record a new -/// request. pub struct SharedSegmentSource { inner: S, in_flight: DashMap>, @@ -38,117 +32,33 @@ impl SharedSegmentSource { pub fn new(inner: S) -> Self { Self { inner, - // The default shard count scales with the machine's cores, as the requesters do. - in_flight: DashMap::default(), + in_flight: DashMap::with_hasher_and_shard_amount(Default::default(), 64), } } - - /// The request in flight for `id`, if any. - fn in_flight(&self, id: SegmentId) -> Option> { - self.in_flight.get(&id)?.upgrade() - } } impl SegmentSource for SharedSegmentSource { fn request(&self, id: SegmentId) -> SegmentFuture { - if let Some(future) = self.in_flight(id) { - return future.map_err(VortexError::from).boxed(); - } - - let future = self.inner.request(id).map_err(Arc::new).boxed().shared(); - let weak = future - .downgrade() - .vortex_expect("just created, cannot be polled to completion"); - match self.in_flight.entry(id) { - Entry::Occupied(mut entry) => { - if let Some(existing) = entry.get().upgrade() { - // Another requester recorded the same segment first. Its request reads the - // same bytes, so dropping this one changes nothing that is read or coalesced. - return existing.map_err(VortexError::from).boxed(); + loop { + match self.in_flight.entry(id) { + Entry::Occupied(e) => { + if let Some(shared_future) = e.get().upgrade() { + return shared_future.map_err(VortexError::from).boxed(); + } else { + // The future has been dropped, remove the entry and try again. + e.remove(); + } + } + Entry::Vacant(e) => { + let future = self.inner.request(id).map_err(Arc::new).boxed().shared(); + e.insert( + future + .downgrade() + .vortex_expect("just created, cannot be polled to completion"), + ); + return future.map_err(VortexError::from).boxed(); } - entry.insert(weak); - } - Entry::Vacant(entry) => { - entry.insert(weak); } } - future.map_err(VortexError::from).boxed() - } -} - -#[cfg(test)] -mod tests { - use std::sync::Arc; - use std::sync::atomic::AtomicUsize; - use std::sync::atomic::Ordering; - - use futures::FutureExt; - use futures::executor::block_on; - use vortex_array::buffer::BufferHandle; - use vortex_buffer::ByteBuffer; - use vortex_error::VortexResult; - - use super::*; - - /// Counts its requests, and answers each with the segment's id as one byte. - #[derive(Default)] - struct Counting(AtomicUsize); - - impl SegmentSource for Counting { - fn request(&self, id: SegmentId) -> SegmentFuture { - self.0.fetch_add(1, Ordering::SeqCst); - let byte = u8::try_from(*id).unwrap_or(u8::MAX); - async move { Ok(BufferHandle::new_host(ByteBuffer::from(vec![byte]))) }.boxed() - } - } - - #[test] - fn concurrent_requests_share_one_inner_request() -> VortexResult<()> { - let source = SharedSegmentSource::new(Counting::default()); - let first = source.request(SegmentId::from(7)); - let second = source.request(SegmentId::from(7)); - assert_eq!(source.inner.0.load(Ordering::SeqCst), 1); - assert_eq!(block_on(first)?.to_host_sync().as_slice(), [7]); - assert_eq!(block_on(second)?.to_host_sync().as_slice(), [7]); - Ok(()) - } - - #[test] - fn a_finished_request_is_made_again() -> VortexResult<()> { - let source = SharedSegmentSource::new(Counting::default()); - drop(block_on(source.request(SegmentId::from(3)))?); - drop(block_on(source.request(SegmentId::from(3)))?); - assert_eq!(source.inner.0.load(Ordering::SeqCst), 2); - Ok(()) - } - - /// Threads requesting the same segments at once each get their segment. - #[test] - fn racing_requesters_get_their_segments() -> VortexResult<()> { - let source = Arc::new(SharedSegmentSource::new(Counting::default())); - let futures = std::thread::scope(|scope| { - let handles: Vec<_> = (0..8) - .map(|_| { - let source = Arc::clone(&source); - scope.spawn(move || { - (0..64u32) - .map(|id| source.request(SegmentId::from(id))) - .collect::>() - }) - }) - .collect(); - handles - .into_iter() - .flat_map(|handle| handle.join().expect("requester panicked")) - .collect::>() - }); - // A requester that loses a race drops its own inner request, so there may be more than - // one per segment, but never fewer. - assert!(source.inner.0.load(Ordering::SeqCst) >= 64); - for (index, future) in futures.into_iter().enumerate() { - let id = u8::try_from(index % 64).unwrap_or(u8::MAX); - assert_eq!(block_on(future)?.to_host_sync().as_slice(), [id]); - } - Ok(()) } } diff --git a/vortex-layout/src/scan/layout.rs b/vortex-layout/src/scan/layout.rs index 38f801fd9a9..2b4ab2d1d5a 100644 --- a/vortex-layout/src/scan/layout.rs +++ b/vortex-layout/src/scan/layout.rs @@ -14,6 +14,7 @@ use futures::FutureExt; use futures::Stream; use futures::stream; use futures::stream::StreamExt; +use vortex_array::ArrayRef; use vortex_array::IntoArray; use vortex_array::arrays::ConstantArray; use vortex_array::dtype::DType; @@ -37,6 +38,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::selection::Selection; use vortex_session::VortexSession; @@ -45,19 +47,10 @@ use crate::LayoutReaderRef; use crate::scan::limit::RowLimit; use crate::scan::metrics::ScanMetrics; use crate::scan::metrics::ScanRecorder; -use crate::scan::pool::FileWork; -use crate::scan::pool::PiecePartition; -use crate::scan::pool::PoolFile; -use crate::scan::pool::PoolOptions; -use crate::scan::pool::PreparedScan; -use crate::scan::pool::open_pool; +use crate::scan::pool::SplitPool; use crate::scan::scan_builder::ScanBuilder; /// An implementation of a [`DataSource`] that reads data from a [`LayoutReaderRef`]. -/// -/// When a scan is [split](DataSourceScan::split) or [opened](DataSourceScan::open), its units are -/// the layout's splits. Workers of an opened scan share them, each keeping several in flight on -/// the session's runtime. pub struct LayoutReaderDataSource { reader: LayoutReaderRef, session: VortexSession, @@ -212,7 +205,6 @@ impl DataSource for LayoutReaderDataSource { dtype, projection, filter, - limit: scan_request.limit, remaining_limit: scan_request.limit, row_limit, selection: scan_request.selection, @@ -236,8 +228,6 @@ struct LayoutReaderScan { dtype: DType, projection: BoundExpression, filter: Option, - /// The request's limit. - limit: Option, /// Limit rows not yet covered by the splits produced so far; production stops at zero. /// Decremented only for filterless scans, where each split's output is exactly its /// selected row count. @@ -254,33 +244,35 @@ struct LayoutReaderScan { } impl LayoutReaderScan { - /// Prepares the scan once, for splitting or opening. - fn into_split_scan(self) -> VortexResult { - let row_count = DataSourceScan::row_count(&self); - let options = LayoutScanOptions { + /// The scan over the rows that remain, as develop's DuckDB scan builds it for a file. + fn builder(&self) -> ScanBuilder { + ScanBuilder::new(self.session.clone(), Arc::clone(&self.reader)) + .with_selection(self.selection.clone()) + .with_projection(self.projection.clone()) + .with_some_filter(self.filter.clone()) + .with_some_scan_metrics(self.metrics.clone()) + .with_some_max_splits_in_flight(self.split_concurrency) + } + + /// This scan over `rows` only. Only a scan without a limit is cut into pieces, so a piece + /// has no limit to share. + fn piece(&self, rows: Range) -> Self { + Self { + reader: Arc::clone(&self.reader), session: self.session.clone(), - dtype: self.dtype, + dtype: self.dtype.clone(), + projection: self.projection.clone(), + filter: self.filter.clone(), + remaining_limit: None, + row_limit: None, ordered: self.ordered, - limit: self.limit, - has_filter: self.filter.is_some(), split_concurrency: self.split_concurrency, - }; - let row_range = clamp_row_range(self.next_row..self.end_row, self.reader.row_count()); - let scan = ScanBuilder::new(self.session, self.reader) - .with_row_range(row_range) - .with_selection(self.selection) - .with_projection(self.projection) - .with_some_filter(self.filter) - .with_some_scan_metrics(self.metrics) - .with_ordered(self.ordered) - .prepare()?; - let ranges = scan.split_ranges(None); - Ok(LayoutSplitScan { - options, - row_count, - scan: Arc::new(scan), - ranges, - }) + selection: self.selection.clone(), + metrics: self.metrics.clone(), + next_row: rows.start, + end_row: rows.end, + split_size: self.split_size, + } } } @@ -289,24 +281,54 @@ impl DataSourceScan for LayoutReaderScan { &self.dtype } - fn partition_count(&self) -> Precision { - let (lower, upper) = self.size_hint(); - match upper { - Some(u) if u == lower => Precision::exact(lower), - Some(u) => Precision::inexact(u), - None => Precision::inexact(lower), + /// Cuts the scan at the layout's natural split boundaries, into pieces of about equal rows. + /// + /// A scan with a limit stays whole, because the limit is one budget across all its rows. + fn split(self: Box, n: NonZeroUsize) -> VortexResult> { + if n.get() == 1 || self.remaining_limit.is_some() || self.next_row >= self.end_row { + return Ok(vec![self]); + } + let ranges = self + .builder() + .prepare()? + .split_ranges(Some(self.next_row..self.end_row)); + let pieces: Vec> = group_contiguous(ranges, n) + .into_iter() + .filter_map(|group| Some(group.first()?.start..group.last()?.end)) + .collect(); + if pieces.len() <= 1 { + return Ok(vec![self]); } + Ok(pieces + .into_iter() + .map(|rows| Box::new(self.piece(rows)) as DataSourceScanRef) + .collect()) } - fn partitions(self: Box) -> PartitionStream { - (*self).boxed() + /// Opens the scan into a queue of its split futures, which workers claim one at a time and + /// run themselves: develop's DuckDB scan of a file. + /// + /// Split futures cannot share a limit, and workers of a queue finish splits out of row + /// order. So a scan with a limit, or an ordered one, keeps its partition pipeline and hands + /// its partitions to workers instead. + fn open(self: Box) -> VortexResult { + if self.remaining_limit.is_some() || self.ordered { + return Ok(Arc::new(PartitionPool::new(self))); + } + let splits = self + .builder() + .prepare()? + .execute(Some(self.next_row..self.end_row))?; + Ok(Arc::new(SplitPool::new(self.dtype, splits))) } fn row_count(&self) -> Precision { let selected = self .selection .row_count_in_range(&(self.next_row..self.end_row)); - let rows = self.limit.map_or(selected, |limit| selected.min(limit)); + let rows = self + .remaining_limit + .map_or(selected, |limit| selected.min(limit)); if self.filter.is_some() { Precision::inexact(rows) } else { @@ -314,129 +336,17 @@ impl DataSourceScan for LayoutReaderScan { } } - fn split(self: Box, n: NonZeroUsize) -> VortexResult> { - Box::new(self.into_split_scan()?).split(n) - } - - fn open(self: Box) -> VortexResult { - Box::new(self.into_split_scan()?).open() - } -} - -/// Clamps a requested row range to the rows of the source. -fn clamp_row_range(row_range: Range, total_rows: u64) -> Range { - let end = row_range.end.min(total_rows); - row_range.start.min(end)..end -} - -/// What a [`LayoutSplitScan`] and every piece cut from it share. -#[derive(Clone)] -struct LayoutScanOptions { - session: VortexSession, - dtype: DType, - ordered: bool, - limit: Option, - has_filter: bool, - split_concurrency: Option, -} - -/// A prepared scan of one layout reader over some of its splits: a [`LayoutReaderScan`] that was -/// split or opened, or a piece cut from one. -struct LayoutSplitScan { - options: LayoutScanOptions, - row_count: Precision, - scan: Arc, - /// The scan's units: its layout splits, in row order. - ranges: Vec>, -} - -impl LayoutSplitScan { - /// A piece over some of the prepared scan's split `ranges`. - fn piece( - options: &LayoutScanOptions, - scan: Arc, - ranges: Vec>, - ) -> Self { - let selected = ranges - .iter() - .map(|range| scan.selected_row_count(range)) - .sum::(); - Self { - options: options.clone(), - row_count: if options.has_filter { - Precision::inexact(selected) - } else { - Precision::exact(selected) - }, - scan, - ranges, - } - } -} - -impl DataSourceScan for LayoutSplitScan { - fn dtype(&self) -> &DType { - &self.options.dtype - } - fn partition_count(&self) -> Precision { - Precision::exact(1usize) - } - - fn partitions(self: Box) -> PartitionStream { - let index = self.ranges.first().map_or(0, |range| { - usize::try_from(range.start).unwrap_or(usize::MAX) - }); - PiecePartition::stream(self, index) - } - - fn row_count(&self) -> Precision { - self.row_count - } - - fn split(self: Box, n: NonZeroUsize) -> VortexResult> { - if self.options.limit.is_some() || self.ranges.len() <= 1 || n.get() == 1 { - return Ok(vec![self]); + let (lower, upper) = self.size_hint(); + match upper { + Some(u) if u == lower => Precision::exact(lower), + Some(u) => Precision::inexact(u), + None => Precision::inexact(lower), } - let LayoutSplitScan { - options, - scan, - ranges, - .. - } = *self; - Ok(group_contiguous(ranges, n) - .into_iter() - .map(|ranges| { - Box::new(LayoutSplitScan::piece(&options, Arc::clone(&scan), ranges)) - as DataSourceScanRef - }) - .collect()) } - fn open(self: Box) -> VortexResult { - let LayoutScanOptions { - session, - dtype, - ordered, - limit, - has_filter, - split_concurrency, - } = self.options; - if limit == Some(0) { - return Box::new(Empty::new(dtype, 0)).open(); - } - let work = FileWork::start(self.scan, self.ranges)?; - let options = PoolOptions { - session, - dtype, - ordered, - limit, - has_filter, - split_concurrency, - // A single opened file has nothing to open. - open_concurrency: 1, - }; - Ok(open_pool(options, vec![PoolFile::Opened(work)], None)) + fn partitions(self: Box) -> PartitionStream { + (*self).boxed() } } @@ -602,22 +512,24 @@ impl Partition for LayoutReaderSplit { } /// A scan that produces no data, only empty arrays with the correct row count. -pub(crate) struct Empty { +struct Empty { dtype: DType, row_count: u64, } -impl Empty { - pub(crate) fn new(dtype: DType, row_count: u64) -> Self { - Self { dtype, row_count } - } -} - impl DataSourceScan for Empty { fn dtype(&self) -> &DType { &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) } @@ -841,417 +753,94 @@ mod tests { } #[cfg(test)] -mod pool_tests { +mod split_open_tests { use std::num::NonZeroUsize; use std::sync::Arc; - use std::sync::atomic::AtomicUsize; - use std::sync::atomic::Ordering; - use futures::StreamExt; - use rstest::rstest; - use vortex_array::dtype::DType; - use vortex_array::dtype::Nullability; - use vortex_array::dtype::StructFields; - use vortex_array::expr::Expression; - use vortex_array::expr::root; - use vortex_buffer::Buffer; + use futures::TryStreamExt; + use futures::executor::block_on; + use futures::executor::block_on_stream; + use futures::future::try_join_all; + use vortex_array::expr::stats::Precision; use vortex_error::VortexResult; - use vortex_metrics::DefaultMetricsRegistry; - use vortex_metrics::MetricValue; - use vortex_metrics::MetricsRegistry; + use vortex_io::runtime::BlockingRuntime; + use vortex_io::runtime::single::SingleThreadRuntime; use vortex_scan::DataSource; - use vortex_scan::DataSourceScanRef; use vortex_scan::ScanRequest; - use vortex_scan::selection::Selection; - use vortex_scan::strict_sorted_buffer::StrictSortedBuffer; use super::LayoutReaderDataSource; use super::group_contiguous; use crate::scan::test::TestLayoutReader; use crate::scan::test::collect_scan_values; - use crate::scan::test::keep_odd; use crate::scan::test::new_session; - use crate::scan::test::read_with_one_worker; - use crate::scan::test::read_with_workers; - - fn counter_values(registry: &DefaultMetricsRegistry) -> Vec { - registry - .snapshot() - .iter() - .map(|metric| match metric.value() { - MetricValue::Counter(counter) => counter.value(), - _ => panic!("expected a scan counter"), - }) - .collect() - } - - fn plan( - source: &LayoutReaderDataSource, - request: ScanRequest, - ) -> VortexResult { - futures::executor::block_on(source.scan(request)) - } - - /// Earlier splits finish last, so completion order is the reverse of row order. - fn slow_start(row: u64) -> usize { - usize::try_from(32u64.saturating_sub(row)).unwrap_or(0) - } + use crate::scan::test::session_with_handle; - fn source(reader: TestLayoutReader) -> LayoutReaderDataSource { - LayoutReaderDataSource::new(Arc::new(reader), new_session()) + fn source() -> LayoutReaderDataSource { + LayoutReaderDataSource::new( + Arc::new(TestLayoutReader::new(64).with_split_size(4)), + new_session(), + ) } - /// Each opened scan is one execution: it counts one file scan, and one attempt per split. + /// Workers of an opened scan each claim splits until none is left, so together they read + /// every row once. #[test] - fn opened_executions_share_aggregate_handles() -> VortexResult<()> { - let registry = Arc::new(DefaultMetricsRegistry::default()); - let source = source(TestLayoutReader::new(8).with_split_size(2)) - .with_metrics_registry(Arc::::clone(®istry)); - for execution in 1..=2 { - let pool = plan(&source, ScanRequest::default())?.open()?; - let values = read_with_workers(&pool, 2)?.concat(); - assert_eq!(values.len(), 8); - assert_eq!( - counter_values(®istry), - [4 * execution, 0, 0, execution, 0] - ); - } - Ok(()) - } - - /// N workers on one pool read every split exactly once. - #[rstest] - #[case::ordered(true)] - #[case::unordered(false)] - fn workers_read_every_split_once(#[case] ordered: bool) -> VortexResult<()> { - let source = source(TestLayoutReader::new(64).with_split_size(1)); - let pool = plan( - &source, - ScanRequest { - ordered, - ..Default::default() - }, - )? - .open()?; - let per_worker = read_with_workers(&pool, 4)?; - - let mut values = per_worker.concat(); + fn opened_workers_read_every_row_once() -> VortexResult<()> { + let pool = block_on(source().scan(ScanRequest::default()))?.open()?; + let workers = (0..3).map(|_| Arc::clone(&pool).worker().try_collect::>()); + let arrays = block_on(try_join_all(workers))?; + let mut values = collect_scan_values(arrays.into_iter().flatten().map(Ok))?; values.sort_unstable(); assert_eq!(values, (0..64).collect::>()); - Ok(()) - } - - /// A worker of an ordered pool yields rows in row order, even when later splits finish - /// first, and later workers of the pool get nothing. - #[test] - fn ordered_worker_yields_row_order() -> VortexResult<()> { - let read = |ordered| { - let source = source( - TestLayoutReader::new(32) - .with_split_size(1) - .with_yields(slow_start), - ); - let pool = plan( - &source, - ScanRequest { - ordered, - ..Default::default() - }, - )? - .open()?; - let first = read_with_one_worker(Arc::clone(&pool))?; - let second = read_with_one_worker(pool)?; - assert!(second.is_empty()); - Ok::<_, vortex_error::VortexError>(first) - }; - - assert_eq!(read(true)?, (0..32).collect::>()); - // The same splits complete out of order, so an unordered worker does not keep row order. - assert_ne!(read(false)?, (0..32).collect::>()); - Ok(()) - } - - /// A limit holds across several workers of an unordered pool, whether splits reserve their - /// rows up front (no filter) or trim their output (filter). - #[rstest] - #[case::reserved(None)] - #[case::trimmed(Some(root()))] - fn unordered_limit_holds_across_workers( - #[case] filter: Option, - ) -> VortexResult<()> { - let source = source(TestLayoutReader::new(64).with_split_size(2)); - let pool = plan( - &source, - ScanRequest { - filter, - limit: Some(7), - ..Default::default() - }, - )? - .open()?; - let mut values = read_with_workers(&pool, 4)?.concat(); - values.sort_unstable(); - values.dedup(); - assert_eq!(values.len(), 7); - Ok(()) - } - - /// Split tasks are built as `execute_stream` builds them: all of a file's at once, so their - /// reads are registered together, when a worker takes its first split; but one at a time, as - /// workers take them, when the scan has both a filter and a limit. - #[rstest] - #[case::unfiltered(None, None, true)] - #[case::filtered(Some(root()), None, true)] - #[case::limited(None, Some(1000), true)] - #[case::filtered_and_limited(Some(root()), Some(1000), false)] - fn split_tasks_build_like_execute_stream( - #[case] filter: Option, - #[case] limit: Option, - #[case] up_front: bool, - ) -> VortexResult<()> { - let built = Arc::new(AtomicUsize::new(0)); - let source = source( - TestLayoutReader::new(16) - .with_split_size(1) - .with_built_projections(Arc::clone(&built)), - ); - let pool = plan( - &source, - ScanRequest { - filter, - limit, - split_concurrency: NonZeroUsize::new(1), - ..Default::default() - }, - )? - .open()?; - let mut worker = Arc::clone(&pool).worker(); - assert!(futures::executor::block_on(worker.next()).is_some()); - let built_after_first = built.load(Ordering::SeqCst); - if up_front { - assert_eq!(built_after_first, 16); - } else { - assert!( - built_after_first < 16, - "built {built_after_first} splits up front" - ); - } - - let rest = collect_scan_values(futures::executor::block_on_stream(worker))?; - assert_eq!(rest.len(), 15); - assert_eq!(built.load(Ordering::SeqCst), 16); - Ok(()) - } - - /// A pool reports the share of its splits that workers have taken, and is exhausted once - /// none are left to take. - #[rstest] - #[case::ordered(true)] - #[case::unordered(false)] - fn pools_report_progress_and_exhaustion(#[case] ordered: bool) -> VortexResult<()> { - let source = source(TestLayoutReader::new(8).with_split_size(2)); - let pool = plan( - &source, - ScanRequest { - ordered, - ..Default::default() - }, - )? - .open()?; - assert_eq!(pool.progress(), 0.0); - assert!(!pool.is_exhausted()); - - let values = read_with_one_worker(Arc::clone(&pool))?; - assert_eq!(values.len(), 8); - assert_eq!(pool.progress(), 1.0); assert!(pool.is_exhausted()); - assert!(read_with_one_worker(pool)?.is_empty()); - Ok(()) - } - - /// An ordered pool with a limit returns exactly the first `limit` rows. - #[rstest] - #[case::reserved(false, &[0, 1, 2, 3, 4])] - #[case::trimmed(true, &[1, 3, 5, 7, 9])] - fn ordered_limit_returns_the_first_rows( - #[case] filtered: bool, - #[case] expected: &[i32], - ) -> VortexResult<()> { - let source = source( - TestLayoutReader::new(32) - .with_split_size(2) - .with_keep_row(keep_odd) - .with_yields(slow_start), - ); - let pool = plan( - &source, - ScanRequest { - filter: filtered.then(root), - ordered: true, - limit: Some(5), - ..Default::default() - }, - )? - .open()?; - assert_eq!(read_with_one_worker(pool)?, expected); - Ok(()) - } - - /// With a sparse selection and no filter, each split contributes only its selected rows, so - /// the workers keep taking splits until the limit is actually filled. - #[rstest] - #[case::ordered(true)] - #[case::unordered(false)] - fn opened_sparse_selection_with_limit_fills_the_limit( - #[case] ordered: bool, - ) -> VortexResult<()> { - let source = source(TestLayoutReader::new(12).with_split_size(2)); - - // Every two-row split contains exactly one selected row (the even ones). - let selection = - Selection::IncludeByIndex(StrictSortedBuffer::try_new(Buffer::from_iter([ - 0u64, 2, 4, 6, 8, 10, - ]))?); - let pool = plan( - &source, - ScanRequest { - selection, - limit: Some(3), - ordered, - ..Default::default() - }, - )? - .open()?; - let mut values = read_with_one_worker(pool)?; - if !ordered { - values.sort_unstable(); - } - assert_eq!(values, [0, 2, 4]); + assert_eq!(pool.progress(), 1.0); Ok(()) } - /// `split(n)` pieces cover the scan exactly, are in row order, and never cut a layout split. - #[rstest] - #[case::fewer_pieces_than_splits(3, 3)] - #[case::more_pieces_than_splits(16, 7)] - fn split_pieces_cover_the_scan_on_split_boundaries( - #[case] n: usize, - #[case] expected_pieces: usize, - ) -> VortexResult<()> { - // Splits of three rows: [0, 3), [3, 6), ..., [18, 20). - let source = source(TestLayoutReader::new(20).with_split_size(3)); - let scan = plan(&source, ScanRequest::default())?; - let pieces = scan.split(NonZeroUsize::new(n).expect("non-zero"))?; - assert_eq!(pieces.len(), expected_pieces); - assert_eq!( - pieces - .iter() - .map(|piece| piece.row_count().as_exact()) - .sum::>(), - Some(20) - ); - + /// Splitting cuts at the layout's split boundaries, and the pieces read the rows in order. + #[test] + fn split_cuts_at_split_boundaries() -> VortexResult<()> { + let scan = block_on(source().scan(ScanRequest::default()))?; + let pieces = scan.split(NonZeroUsize::try_from(4)?)?; + assert_eq!(pieces.len(), 4); let mut values = Vec::new(); for piece in pieces { - // The scan is unordered, so a piece's splits may finish in any order. - let mut piece_values = read_with_one_worker(piece.open()?)?; - piece_values.sort_unstable(); - let first = *piece_values.first().expect("pieces are not empty"); - let last = *piece_values.last().expect("pieces are not empty"); - assert_eq!(first % 3, 0, "piece starts on a split boundary"); - assert!( - (last + 1) % 3 == 0 || last == 19, - "piece ends on a split boundary" - ); - values.extend(piece_values); + assert_eq!(piece.row_count(), Precision::exact(16u64)); + values.extend(collect_scan_values(block_on_stream( + piece.open()?.worker(), + ))?); } - assert_eq!(values, (0..20).collect::>()); + assert_eq!(values, (0..64).collect::>()); Ok(()) } - /// A piece read through the partitions API returns the same rows as its pool. + /// A limit is one budget across the scan, so a limited scan stays whole and opens into its + /// partitions, which apply the limit. #[test] - fn split_pieces_read_through_partitions() -> VortexResult<()> { - let source = source(TestLayoutReader::new(20).with_split_size(3)); - let scan = plan( - &source, - ScanRequest { - ordered: true, - ..Default::default() - }, - )?; - let mut values = Vec::new(); - for piece in scan.split(NonZeroUsize::new(3).expect("non-zero"))? { - let partitions = - futures::executor::block_on_stream(piece.partitions()).collect::>(); - assert_eq!(partitions.len(), 1); - for partition in partitions { - values.extend(collect_scan_values(futures::executor::block_on_stream( - partition?.execute()?, - ))?); - } - } - assert_eq!(values, (0..20).collect::>()); - Ok(()) - } + fn limited_scan_stays_whole() -> VortexResult<()> { + let runtime = SingleThreadRuntime::default(); + let source = LayoutReaderDataSource::new( + Arc::new(TestLayoutReader::new(64).with_split_size(4)), + session_with_handle(runtime.handle()), + ); + let request = || ScanRequest { + limit: Some(10), + ..Default::default() + }; + let scan = runtime.block_on(source.scan(request()))?; + assert_eq!(scan.split(NonZeroUsize::try_from(4)?)?.len(), 1); - #[test] - fn split_keeps_a_limited_scan_whole() -> VortexResult<()> { - let source = source(TestLayoutReader::new(20).with_split_size(3)); - let scan = plan( - &source, - ScanRequest { - limit: Some(4), - ..Default::default() - }, - )?; - let pieces = scan.split(NonZeroUsize::new(4).expect("non-zero"))?; - assert_eq!(pieces.len(), 1); + let pool = runtime.block_on(source.scan(request()))?.open()?; + let values = collect_scan_values(runtime.block_on_stream(pool.worker()))?; + assert_eq!(values.len(), 10); Ok(()) } #[test] - fn grouping_never_returns_more_groups_than_requested() { - let ranges = (0..10u64) - .map(|start| start * 10..start * 10 + 10) - .collect(); - let groups = group_contiguous(ranges, NonZeroUsize::new(3).expect("non-zero")); - assert_eq!(groups.len(), 3); - assert_eq!(groups.concat().len(), 10); - } - - /// A length-only scan opens into one pool whose workers together return its rows once. - #[test] - fn length_only_scan_returns_its_rows_once_across_workers() -> VortexResult<()> { - let source = source(TestLayoutReader::new(10).with_dtype(DType::Struct( - StructFields::empty(), - Nullability::NonNullable, - ))); - let pool = plan( - &source, - ScanRequest { - limit: Some(7), - ..Default::default() - }, - )? - .open()?; - let rows: usize = std::thread::scope(|scope| { - let handles = (0..3) - .map(|_| { - let worker = Arc::clone(&pool).worker(); - scope.spawn(move || { - futures::executor::block_on_stream(worker) - .map(|array| array.map(|array| array.len())) - .sum::>() - }) - }) - .collect::>(); - handles - .into_iter() - .map(|handle| handle.join().expect("worker thread panicked")) - .sum::>() - })?; - assert_eq!(rows, 7); + fn group_contiguous_keeps_ranges_whole() -> VortexResult<()> { + let ranges = vec![0..10, 10..12, 12..30, 30..31]; + let groups = group_contiguous(ranges, NonZeroUsize::try_from(2)?); + assert_eq!(groups, vec![vec![0..10, 10..12], vec![12..30, 30..31]]); Ok(()) } } diff --git a/vortex-layout/src/scan/multi.rs b/vortex-layout/src/scan/multi.rs index 87152745cc0..5d5b605bbe6 100644 --- a/vortex-layout/src/scan/multi.rs +++ b/vortex-layout/src/scan/multi.rs @@ -64,17 +64,7 @@ use vortex_session::VortexSession; use vortex_utils::parallelism::get_available_parallelism; use crate::LayoutReaderRef; -use crate::scan::layout::Empty; -use crate::scan::layout::group_contiguous; use crate::scan::limit::RowLimit; -use crate::scan::pool::FileWork; -use crate::scan::pool::PiecePartition; -use crate::scan::pool::PlannedSplits; -use crate::scan::pool::PoolFile; -use crate::scan::pool::PoolOptions; -use crate::scan::pool::PrepareFile; -use crate::scan::pool::PreparedScan; -use crate::scan::pool::open_pool; use crate::scan::scan_builder::ScanBuilder; /// Default concurrency for opening deferred readers. @@ -221,8 +211,8 @@ impl MultiLayoutDataSource { /// Sets the concurrency for opening deferred readers. /// - /// Controls how many file opens run in parallel, on the partitions path and in an opened - /// scan's pool alike. Defaults to the number of available CPU cores. + /// Controls how many file opens run in parallel via `buffer_unordered`. + /// Defaults to the number of available CPU cores. pub fn with_concurrency(mut self, concurrency: usize) -> Self { self.concurrency = concurrency; self @@ -334,6 +324,7 @@ impl DataSource for MultiLayoutDataSource { row_limit, ready, deferred, + handle: self.session.handle(), concurrency: self.concurrency, })) } @@ -385,17 +376,6 @@ impl BoundScanRequest { split_concurrency, }) } - - /// Whether the scan filters rows, so its output row count is unknown up front. A filter - /// that failed to bind counts as one. - fn has_filter(&self) -> bool { - !matches!(self.filter, Ok(None)) - } - - /// Whether the request selects partitions, which only the partitions path applies. - fn selects_partitions(&self) -> bool { - self.partition_range.is_some() || !matches!(self.partition_selection, Selection::All) - } } struct MultiLayoutScan { @@ -406,41 +386,64 @@ struct MultiLayoutScan { row_limit: Option, ready: VecDeque, deferred: VecDeque>, + handle: vortex_io::runtime::Handle, concurrency: usize, } -impl MultiLayoutScan { - /// The scan as files to split or open. Files keep their partition order. - fn into_split_scan(self) -> MultiLayoutSplitScan { - let children = self - .ready - .into_iter() - .map(ScanChild::Opened) - .chain(self.deferred.into_iter().map(ScanChild::Deferred)) - .collect(); - MultiLayoutSplitScan { - context: Arc::new(ScanContext { - session: self.session, - source_dtype: self.source_dtype, - dtype: self.dtype, - request: self.request, - open_concurrency: self.concurrency, - }), - children, - index: 0, - } - } -} - impl DataSourceScan for MultiLayoutScan { fn dtype(&self) -> &DType { &self.dtype } - fn split(self: Box, _n: NonZeroUsize) -> VortexResult> { - Ok(vec![self]) + /// Cuts the scan into pieces of whole files, in file order, without opening any. + /// + /// A scan with a limit stays whole, because the limit is one budget across all its files, + /// and so does one that selects partitions, because partition indices count from its first + /// file. + fn split(self: Box, n: NonZeroUsize) -> VortexResult> { + let files = self.ready.len() + self.deferred.len(); + if n.get() == 1 + || files <= 1 + || self.request.limit.is_some() + || self.request.partition_range.is_some() + || !matches!(self.request.partition_selection, Selection::All) + { + return Ok(vec![self]); + } + let Self { + session, + source_dtype, + dtype, + request, + row_limit, + mut ready, + mut deferred, + handle, + concurrency, + } = *self; + let pieces = n.get().min(files); + Ok((0..pieces) + .map(|piece| { + // Piece `piece` takes files `piece * files / pieces` up to the next piece's start. + let take = (piece + 1) * files / pieces - piece * files / pieces; + let from_ready = take.min(ready.len()); + Box::new(MultiLayoutScan { + session: session.clone(), + source_dtype: source_dtype.clone(), + dtype: dtype.clone(), + request: request.clone(), + row_limit: row_limit.clone(), + ready: ready.drain(..from_ready).collect(), + deferred: deferred.drain(..take - from_ready).collect(), + handle: handle.clone(), + concurrency, + }) as DataSourceScanRef + }) + .collect()) } + /// Opens the scan into its partition pipeline, which opens up to `concurrency` files ahead + /// and reads each file as one partition, handing the partitions to workers. fn open(self: Box) -> VortexResult { Ok(Arc::new(PartitionPool::new(self))) } @@ -454,35 +457,6 @@ impl DataSourceScan for MultiLayoutScan { } } - fn row_count(&self) -> Precision { - let estimate = estimate_row_count( - &self.request, - self.ready - .iter() - .map(|reader| file_row_count(&self.request, reader)), - self.ready.len() + self.deferred.len(), - ); - if self.request.selects_partitions() { - estimate.into_inexact() - } else { - estimate - } - } - - fn split(self: Box, n: NonZeroUsize) -> VortexResult> { - if self.request.selects_partitions() { - return Ok(vec![self]); - } - Box::new(self.into_split_scan()).split(n) - } - - fn open(self: Box) -> VortexResult { - if self.request.selects_partitions() { - return Ok(Arc::new(PartitionPool::new(self))); - } - Box::new(self.into_split_scan()).open() - } - fn partitions(self: Box) -> PartitionStream { let Self { session, @@ -492,9 +466,9 @@ impl DataSourceScan for MultiLayoutScan { row_limit, ready, deferred, + handle, concurrency, } = *self; - let handle = session.handle(); let ordered = request.ordered; @@ -704,283 +678,6 @@ impl Partition for MultiLayoutPartition { } } -/// The rows `request` selects from an opened file, before any filter or limit. -fn file_row_count(request: &BoundScanRequest, reader: &LayoutReaderRef) -> u64 { - let row_range = request - .row_range - .clone() - .unwrap_or_else(|| 0..reader.row_count()); - request.selection.row_count_in_range(&row_range) -} - -/// Estimates the rows a scan of `files` files returns from the rows of the files whose rows are -/// known, extrapolating to the rest. -fn estimate_row_count( - request: &BoundScanRequest, - known: impl Iterator, - files: usize, -) -> Precision { - let (rows, known_files) = known.fold((0u64, 0u64), |(rows, count), file_rows| { - (rows.saturating_add(file_rows), count + 1) - }); - let files = files as u64; - let (rows, is_exact) = if known_files == files { - (rows, !request.has_filter()) - } else if let Some(average) = rows.checked_div(known_files) { - (average.saturating_mul(files), false) - } else { - return Precision::Absent; - }; - let rows = request.limit.map_or(rows, |limit| rows.min(limit)); - if is_exact { - Precision::exact(rows) - } else { - Precision::inexact(rows) - } -} - -/// What every piece of a split or opened multi-layout scan shares. -struct ScanContext { - session: VortexSession, - source_dtype: DType, - dtype: DType, - request: BoundScanRequest, - /// The most deferred files that are opened at once. - open_concurrency: usize, -} - -impl ScanContext { - /// Plans the scan of one opened file: checks its dtype, prunes it on statistics, and - /// prepares its splits. Returns `None` when statistics reject the file. Reads metadata only. - fn plan_file(&self, reader: LayoutReaderRef) -> VortexResult> { - if reader.dtype() != &self.source_dtype { - return Err(vortex_err!( - "Multi-layout reader dtype mismatch: expected {}, got {}", - self.source_dtype, - reader.dtype() - )); - } - let filter = self.request.filter.clone()?; - let row_range = self - .request - .row_range - .clone() - .unwrap_or_else(|| 0..reader.row_count()); - - if let Some(filter) = &filter { - let mask_len = usize::try_from(row_range.end - row_range.start).unwrap_or(usize::MAX); - if let Ok(pruning) = - reader.pruning_evaluation(&row_range, filter, Mask::new_true(mask_len)) - && let Some(Ok(mask)) = pruning.now_or_never() - && mask.all_false() - { - return Ok(None); - } - } - - let scan = ScanBuilder::new(self.session.clone(), reader) - .with_row_range(row_range) - .with_selection(self.request.selection.clone()) - .with_projection(self.request.projection.clone()) - .with_some_filter(filter) - .with_ordered(self.request.ordered) - .prepare()?; - let ranges = scan.split_ranges(None); - Ok(Some((Arc::new(scan), ranges))) - } - - /// Starts reading an opened file for one execution. - fn start_file(&self, reader: LayoutReaderRef) -> VortexResult { - match self.plan_file(reader)? { - Some((scan, ranges)) => FileWork::start(scan, ranges), - None => Ok(FileWork::empty()), - } - } -} - -/// One file of a split or opened multi-layout scan. -enum ScanChild { - Opened(LayoutReaderRef), - /// An opened file whose splits are known: all of them, or the share of one piece. - Planned { - scan: Arc, - ranges: Vec>, - }, - Deferred(Arc), -} - -/// A multi-layout scan that was split or opened, or a piece cut from one. Its units are files, -/// then each file's splits. -struct MultiLayoutSplitScan { - context: Arc, - children: Vec, - /// The index of the piece's single partition. - index: usize, -} - -impl MultiLayoutSplitScan { - /// Splits a planned file's ranges into `pieces` contiguous groups. - fn split_child(child: ScanChild, pieces: usize) -> Vec { - match child { - ScanChild::Planned { scan, ranges } if pieces > 1 => group_contiguous( - ranges, - NonZeroUsize::new(pieces).unwrap_or(NonZeroUsize::MIN), - ) - .into_iter() - .map(|ranges| ScanChild::Planned { - scan: Arc::clone(&scan), - ranges, - }) - .collect(), - child => vec![child], - } - } -} - -impl DataSourceScan for MultiLayoutSplitScan { - fn dtype(&self) -> &DType { - &self.context.dtype - } - - fn partition_count(&self) -> Precision { - Precision::exact(1usize) - } - - fn partitions(self: Box) -> PartitionStream { - let index = self.index; - PiecePartition::stream(self, index) - } - - fn row_count(&self) -> Precision { - let request = &self.context.request; - let known = self.children.iter().filter_map(|child| match child { - ScanChild::Opened(reader) => Some(file_row_count(request, reader)), - ScanChild::Planned { scan, ranges } => Some( - ranges - .iter() - .map(|range| scan.selected_row_count(range)) - .sum(), - ), - ScanChild::Deferred(_) => None, - }); - estimate_row_count(request, known, self.children.len()) - } - - fn split(self: Box, n: NonZeroUsize) -> VortexResult> { - if self.context.request.limit.is_some() || n.get() == 1 || self.children.is_empty() { - return Ok(vec![self]); - } - let MultiLayoutSplitScan { - context, children, .. - } = *self; - - // Plan the opened files so they can be cut on their splits. Deferred files stay whole: - // splitting never opens a file. - let mut planned = Vec::with_capacity(children.len()); - for child in children { - match child { - ScanChild::Opened(reader) => { - if let Some((scan, ranges)) = context.plan_file(reader)? { - planned.push(ScanChild::Planned { scan, ranges }); - } - } - child => planned.push(child), - } - } - if planned.is_empty() { - return Ok(vec![Box::new(MultiLayoutSplitScan { - context, - children: planned, - index: 0, - })]); - } - - let n = n.get(); - let pieces: Vec> = if n <= planned.len() { - // Group whole files into contiguous pieces. - let files = planned.len(); - let mut pieces: Vec> = Vec::new(); - let mut current = None; - for (index, child) in planned.into_iter().enumerate() { - let piece = index * n / files; - if current != Some(piece) { - current = Some(piece); - pieces.push(Vec::new()); - } - if let Some(last) = pieces.last_mut() { - last.push(child); - } - } - pieces - } else { - // One piece per file, and the pieces left over cut planned files on their splits, in - // proportion to their rows. - let extra = (n - planned.len()) as u128; - let rows = |child: &ScanChild| match child { - ScanChild::Planned { ranges, .. } => ranges - .iter() - .map(|range| u128::from(range.end - range.start)) - .sum::(), - _ => 0, - }; - let total = planned.iter().map(rows).sum::().max(1); - planned - .into_iter() - .flat_map(|child| { - let pieces = 1 + usize::try_from(extra * rows(&child) / total).unwrap_or(0); - Self::split_child(child, pieces) - }) - .map(|child| vec![child]) - .collect() - }; - - Ok(pieces - .into_iter() - .enumerate() - .map(|(index, children)| { - Box::new(MultiLayoutSplitScan { - context: Arc::clone(&context), - children, - index, - }) as DataSourceScanRef - }) - .collect()) - } - - fn open(self: Box) -> VortexResult { - let MultiLayoutSplitScan { - context, children, .. - } = *self; - let request = &context.request; - if request.limit == Some(0) { - return Box::new(Empty::new(context.dtype.clone(), 0)).open(); - } - - let mut files = Vec::with_capacity(children.len()); - for child in children { - files.push(match child { - ScanChild::Opened(reader) => PoolFile::Opened(context.start_file(reader)?), - ScanChild::Planned { scan, ranges } => { - PoolFile::Opened(FileWork::start(scan, ranges)?) - } - ScanChild::Deferred(factory) => PoolFile::Deferred(factory), - }); - } - - let options = PoolOptions { - session: context.session.clone(), - dtype: context.dtype.clone(), - ordered: request.ordered, - limit: request.limit, - has_filter: request.has_filter(), - split_concurrency: request.split_concurrency, - open_concurrency: context.open_concurrency, - }; - let prepare: PrepareFile = Arc::new(move |reader| context.start_file(reader)); - Ok(open_pool(options, files, Some(prepare))) - } -} - #[cfg(test)] mod tests { use std::sync::Arc; @@ -1099,6 +796,48 @@ mod tests { Ok(()) } + /// Splitting hands out whole files in file order, without opening any. + #[test] + fn split_groups_whole_files() -> VortexResult<()> { + let runtime = SingleThreadRuntime::default(); + let session = session_with_handle(runtime.handle()); + let first: LayoutReaderRef = Arc::new(TestLayoutReader::new(2)); + let rest = (1..5) + .map(|file| { + Arc::new(StaticReaderFactory { + reader: Arc::new(TestLayoutReader::new(2).with_base(10 * file)), + }) as Arc + }) + .collect(); + let source = MultiLayoutDataSource::new_with_first(first, rest, vec![], &session); + + let scan = runtime.block_on(source.scan(ScanRequest { + ordered: true, + ..Default::default() + }))?; + let pieces = scan.split(NonZeroUsize::try_from(3)?)?; + let files: Vec<_> = pieces.iter().map(|piece| piece.partition_count()).collect(); + assert_eq!( + files, + [ + Precision::exact(1usize), + Precision::inexact(2usize), + Precision::inexact(2usize) + ] + ); + + let mut values = Vec::new(); + for piece in pieces { + for partition in runtime.block_on(piece.partitions().try_collect::>())? { + values.extend(collect_scan_values( + runtime.block_on_stream(partition.execute()?), + )?); + } + } + assert_eq!(values, [0, 1, 10, 11, 20, 21, 30, 31, 40, 41]); + Ok(()) + } + /// Scans 64 one-row splits, returning the rows and the most splits read at once. fn scan_with_split_concurrency( split_concurrency: Option, @@ -1157,480 +896,3 @@ mod tests { Ok(()) } } - -#[cfg(test)] -mod pool_tests { - use std::sync::Arc; - use std::sync::atomic::AtomicBool; - use std::sync::atomic::AtomicUsize; - use std::sync::atomic::Ordering; - use std::task::Context; - use std::task::Poll; - - use async_trait::async_trait; - use futures::StreamExt; - use futures::future::poll_fn; - use futures::task::AtomicWaker; - use futures::task::noop_waker_ref; - use rstest::rstest; - use vortex_array::ArrayRef; - use vortex_array::dtype::Nullability; - use vortex_array::dtype::PType; - use vortex_array::expr::root; - use vortex_array::stream::SendableArrayStream; - use vortex_buffer::Buffer; - use vortex_error::VortexResult; - use vortex_io::runtime::BlockingRuntime; - use vortex_io::runtime::single::SingleThreadRuntime; - use vortex_scan::DataSource; - use vortex_scan::ScanRequest; - use vortex_scan::strict_sorted_buffer::StrictSortedBuffer; - - use super::*; - use crate::scan::test::InFlight; - use crate::scan::test::TestLayoutReader; - use crate::scan::test::collect_scan_values; - use crate::scan::test::new_session; - use crate::scan::test::read_with_one_worker; - use crate::scan::test::read_with_workers; - use crate::scan::test::session_with_handle; - - fn plan( - source: &MultiLayoutDataSource, - request: ScanRequest, - ) -> VortexResult { - futures::executor::block_on(source.scan(request)) - } - - fn i32_dtype() -> DType { - DType::Primitive(PType::I32, Nullability::NonNullable) - } - - /// A factory whose open completes only once its gate is released. - #[derive(Default)] - struct Gate { - is_open: AtomicBool, - waker: AtomicWaker, - } - - impl Gate { - fn release(&self) { - self.is_open.store(true, Ordering::SeqCst); - self.waker.wake(); - } - } - - struct GatedFactory { - reader: LayoutReaderRef, - gate: Arc, - opens: Arc, - } - - #[async_trait] - impl LayoutReaderFactory for GatedFactory { - async fn open(&self) -> VortexResult> { - self.opens.fetch_add(1, Ordering::SeqCst); - poll_fn(|cx| { - self.gate.waker.register(cx.waker()); - if self.gate.is_open.load(Ordering::SeqCst) { - Poll::Ready(()) - } else { - Poll::Pending - } - }) - .await; - Ok(Some(Arc::clone(&self.reader))) - } - } - - fn gated_factory(reader: TestLayoutReader, gate: &Arc) -> Arc { - Arc::new(GatedFactory { - reader: Arc::new(reader), - gate: Arc::clone(gate), - opens: Arc::default(), - }) - } - - /// Deferred files of `rows` one-row splits, the `i`th producing `100 * i + row`. - fn gated_source(files: usize, rows: u64) -> (MultiLayoutDataSource, Vec>) { - let gates: Vec<_> = (0..files).map(|_| Arc::new(Gate::default())).collect(); - let factories = gates - .iter() - .enumerate() - .map(|(index, gate)| { - let base = 100 * i32::try_from(index).expect("few files"); - gated_factory( - TestLayoutReader::new(rows) - .with_split_size(1) - .with_base(base), - gate, - ) - }) - .collect(); - let source = - MultiLayoutDataSource::new_deferred(i32_dtype(), factories, vec![], &new_session()); - (source, gates) - } - - fn poll_worker( - worker: &mut SendableArrayStream, - cx: &mut Context<'_>, - ) -> Poll>> { - worker.poll_next_unpin(cx) - } - - /// An unordered pool opens at most the source's open concurrency of deferred files at once, - /// however many workers are waiting for splits. - #[test] - fn deferred_opens_are_bounded() -> VortexResult<()> { - let opens = Arc::new(AtomicUsize::new(0)); - let (source, gates) = counted_source(6, 4, &opens); - let source = source.with_concurrency(2); - let pool = plan(&source, ScanRequest::default())?.open()?; - let mut workers: Vec<_> = (0..4).map(|_| Arc::clone(&pool).worker()).collect(); - let mut noop = Context::from_waker(noop_waker_ref()); - for worker in &mut workers { - assert!(poll_worker(worker, &mut noop).is_pending()); - } - // Opens run on the session's runtime; give them time to start. - for _ in 0..200 { - if opens.load(Ordering::SeqCst) >= 2 { - break; - } - std::thread::sleep(std::time::Duration::from_millis(1)); - } - std::thread::sleep(std::time::Duration::from_millis(20)); - assert_eq!(opens.load(Ordering::SeqCst), 2); - - for gate in &gates { - gate.release(); - } - let mut values = std::thread::scope(|scope| { - let handles: Vec<_> = workers - .into_iter() - .map(|worker| { - scope.spawn(move || { - collect_scan_values(futures::executor::block_on_stream(worker)) - }) - }) - .collect(); - handles - .into_iter() - .map(|handle| handle.join().expect("worker thread panicked")) - .collect::>>() - })? - .concat(); - values.sort_unstable(); - let expected: Vec = (0..6) - .flat_map(|file| (0..4).map(move |row| 100 * file + row)) - .collect(); - assert_eq!(values, expected); - assert_eq!(opens.load(Ordering::SeqCst), 6); - Ok(()) - } - - /// Rows go to whichever worker asks for them: a worker that stops asking holds none back, - /// so another worker that waited while the file opened reads all of it. - #[test] - fn rows_go_to_whichever_worker_asks() -> VortexResult<()> { - let (source, gates) = gated_source(1, 16); - let pool = plan(&source, ScanRequest::default())?.open()?; - let mut idle = Arc::clone(&pool).worker(); - let mut waiter = Arc::clone(&pool).worker(); - let mut noop = Context::from_waker(noop_waker_ref()); - - // Both workers find only an open in progress, so both wait. - assert!(poll_worker(&mut idle, &mut noop).is_pending()); - assert!(poll_worker(&mut waiter, &mut noop).is_pending()); - - gates[0].release(); - let values = collect_scan_values(futures::executor::block_on_stream(waiter))?; - assert_eq!(values.len(), 16); - let mut sorted = values; - sorted.sort_unstable(); - assert_eq!(sorted, (0..16).collect::>()); - assert!(futures::executor::block_on(idle.next()).is_none()); - Ok(()) - } - - /// An unordered pool takes the opened files' splits in turn. With one lane, rows come out in - /// the order the lane takes splits. - #[test] - fn unordered_splits_interleave_across_files() -> VortexResult<()> { - let (source, gates) = gated_source(2, 3); - for gate in &gates { - gate.release(); - } - let request = ScanRequest { - split_concurrency: NonZeroUsize::new(1), - ..Default::default() - }; - let pool = plan(&source.with_concurrency(2), request)?.open()?; - let values = collect_scan_values(futures::executor::block_on_stream(pool.worker()))?; - assert_eq!(values, [0, 100, 1, 101, 2, 102]); - Ok(()) - } - - /// An ordered worker emits files in file order, even when a later file opens first. - #[test] - fn ordered_worker_emits_files_in_order() -> VortexResult<()> { - let (source, gates) = gated_source(3, 3); - let pool = plan( - &source, - ScanRequest { - ordered: true, - ..Default::default() - }, - )? - .open()?; - let mut worker = pool.worker(); - let mut noop = Context::from_waker(noop_waker_ref()); - assert!(poll_worker(&mut worker, &mut noop).is_pending()); - for gate in gates.iter().rev() { - gate.release(); - if !Arc::ptr_eq(gate, &gates[0]) { - assert!(poll_worker(&mut worker, &mut noop).is_pending()); - } - } - let values = collect_scan_values(futures::executor::block_on_stream(worker))?; - assert_eq!(values, [0, 1, 2, 100, 101, 102, 200, 201, 202]); - Ok(()) - } - - /// Deferred files of `rows` one-row splits whose opens are released, counted by `opens`; the - /// `i`th produces `100 * i + row`. - fn counted_source( - files: usize, - rows: u64, - opens: &Arc, - ) -> (MultiLayoutDataSource, Vec>) { - let gates: Vec<_> = (0..files).map(|_| Arc::new(Gate::default())).collect(); - let factories = gates - .iter() - .enumerate() - .map(|(index, gate)| { - let base = 100 * i32::try_from(index).expect("few files"); - Arc::new(GatedFactory { - reader: Arc::new( - TestLayoutReader::new(rows) - .with_split_size(1) - .with_base(base), - ), - gate: Arc::clone(gate), - opens: Arc::clone(opens), - }) as Arc - }) - .collect(); - let source = - MultiLayoutDataSource::new_deferred(i32_dtype(), factories, vec![], &new_session()); - (source, gates) - } - - /// An ordered pool reserves an unfiltered limit in row order across files, so it returns - /// exactly the first rows even when the limit ends inside a later file. - #[test] - fn ordered_reserved_limit_crosses_files() -> VortexResult<()> { - let (source, gates) = counted_source(3, 4, &Arc::default()); - for gate in &gates { - gate.release(); - } - let pool = plan( - &source, - ScanRequest { - ordered: true, - limit: Some(6), - ..Default::default() - }, - )? - .open()?; - assert_eq!(read_with_one_worker(pool)?, [0, 1, 2, 3, 100, 101]); - Ok(()) - } - - /// Once an unordered pool's reserved limit is spent, it opens no more files, and reports - /// that it is done. - #[test] - fn spent_limit_stops_opening_files() -> VortexResult<()> { - let opens = Arc::new(AtomicUsize::new(0)); - let (source, gates) = counted_source(6, 4, &opens); - for gate in &gates { - gate.release(); - } - let source = source.with_concurrency(1); - let pool = plan( - &source, - ScanRequest { - limit: Some(2), - ..Default::default() - }, - )? - .open()?; - let values = read_with_one_worker(Arc::clone(&pool))?; - assert_eq!(values.len(), 2); - assert!(opens.load(Ordering::SeqCst) < 6, "opened every file"); - assert!(pool.is_exhausted()); - assert_eq!(pool.progress(), 1.0); - Ok(()) - } - - /// Opens run in the pool's lanes, not in its workers, so dropping a worker that is waiting - /// on an open gives up nothing: the other workers still read every file. - #[test] - fn dropped_worker_gives_up_nothing() -> VortexResult<()> { - let (source, gates) = counted_source(3, 2, &Arc::default()); - let source = source.with_concurrency(1); - let pool = plan(&source, ScanRequest::default())?.open()?; - let mut dropped = Arc::clone(&pool).worker(); - let mut noop = Context::from_waker(noop_waker_ref()); - assert!(poll_worker(&mut dropped, &mut noop).is_pending()); - drop(dropped); - - for gate in &gates { - gate.release(); - } - let mut values = read_with_one_worker(pool)?; - values.sort_unstable(); - assert_eq!(values, [0, 1, 100, 101, 200, 201]); - Ok(()) - } - - /// A limit is shared by every worker and file of an unordered pool. - #[test] - fn pool_limit_is_shared_across_readers() -> VortexResult<()> { - let first: LayoutReaderRef = Arc::new(TestLayoutReader::new(4).with_split_size(1)); - let gate = Arc::new(Gate::default()); - gate.release(); - let source = MultiLayoutDataSource::new_with_first( - first, - vec![gated_factory( - TestLayoutReader::new(4).with_split_size(1).with_base(10), - &gate, - )], - vec![], - &new_session(), - ); - - let pool = plan( - &source, - ScanRequest { - filter: Some(root()), - limit: Some(3), - ..Default::default() - }, - )? - .open()?; - let values = read_with_workers(&pool, 3)?.concat(); - - assert_eq!(values.len(), 3); - Ok(()) - } - - /// Splitting cuts opened files on their splits and keeps deferred files whole, in order. - #[test] - fn split_cuts_opened_files_and_keeps_deferred_files_whole() -> VortexResult<()> { - let first: LayoutReaderRef = Arc::new(TestLayoutReader::new(6).with_split_size(2)); - let opens = Arc::new(AtomicUsize::new(0)); - let gate = Arc::new(Gate::default()); - gate.release(); - let source = MultiLayoutDataSource::new_with_first( - first, - vec![Arc::new(GatedFactory { - reader: Arc::new(TestLayoutReader::new(4).with_split_size(2).with_base(100)), - gate, - opens: Arc::clone(&opens), - })], - vec![], - &new_session(), - ); - let scan = plan( - &source, - ScanRequest { - ordered: true, - ..Default::default() - }, - )?; - let pieces = scan.split(NonZeroUsize::new(4).expect("non-zero"))?; - assert_eq!(opens.load(Ordering::SeqCst), 0, "splitting opens no file"); - // The opened file's three splits take three pieces; the deferred file stays whole. - assert_eq!(pieces.len(), 4); - - let mut values = Vec::new(); - for piece in pieces { - values.extend(read_with_one_worker(piece.open()?)?); - } - assert_eq!(values, [0, 1, 2, 3, 4, 5, 100, 101, 102, 103]); - Ok(()) - } - - /// A request that selects partitions is split and opened by its partitions, so both paths - /// read the same files. - #[rstest] - #[case::range(Some(1..2), None)] - #[case::selection(None, Some(1))] - fn selected_partitions_open_by_partition( - #[case] partition_range: Option>, - #[case] selected_partition: Option, - ) -> VortexResult<()> { - let partition_selection = match selected_partition { - Some(index) => { - Selection::IncludeByIndex(StrictSortedBuffer::try_new(Buffer::from_iter([index]))?) - } - None => Selection::All, - }; - // The partitions path spawns file opens onto the session's runtime. - let runtime = SingleThreadRuntime::default(); - let gate = Arc::new(Gate::default()); - gate.release(); - let source = MultiLayoutDataSource::new_with_first( - Arc::new(TestLayoutReader::new(3)), - vec![gated_factory(TestLayoutReader::new(3).with_base(10), &gate)], - vec![], - &session_with_handle(runtime.handle()), - ); - let request = ScanRequest { - partition_range, - partition_selection, - ordered: true, - ..Default::default() - }; - let pieces = plan(&source, request.clone())?.split(NonZeroUsize::new(4).expect("4"))?; - assert_eq!(pieces.len(), 1); - let pool = plan(&source, request)?.open()?; - let values = collect_scan_values(runtime.block_on_stream(pool.worker()))?; - assert_eq!(values, [10, 11, 12]); - Ok(()) - } - - /// A pool reads at most `split_concurrency` splits at once, however many workers read it. - #[rstest] - #[case::ordered(true, 1)] - #[case::ordered(true, 2)] - #[case::unordered(false, 1)] - #[case::unordered(false, 2)] - fn split_concurrency_bounds_the_pool( - #[case] ordered: bool, - #[case] max: usize, - ) -> VortexResult<()> { - let in_flight = Arc::new(InFlight::default()); - let reader: LayoutReaderRef = Arc::new( - TestLayoutReader::new(64) - .with_split_size(1) - .with_in_flight(Arc::clone(&in_flight)), - ); - let source = MultiLayoutDataSource::new_with_first(reader, vec![], vec![], &new_session()); - let pool = plan( - &source, - ScanRequest { - ordered, - split_concurrency: NonZeroUsize::new(max), - ..Default::default() - }, - )? - .open()?; - let mut values = read_with_workers(&pool, 4)?.concat(); - values.sort_unstable(); - assert_eq!(values, (0..64).collect::>()); - assert!(in_flight.peak() <= max, "peak {}", in_flight.peak()); - Ok(()) - } -} diff --git a/vortex-layout/src/scan/pool.rs b/vortex-layout/src/scan/pool.rs index f345e908c0a..002372a3d23 100644 --- a/vortex-layout/src/scan/pool.rs +++ b/vortex-layout/src/scan/pool.rs @@ -1,927 +1,89 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors -//! The work that the workers of an opened layout scan share. -//! -//! A pool's units are the splits of one or more files, and the files not yet opened. Its splits -//! run as tasks on the session's runtime, at most `splits_in_flight` at once across the whole -//! pool; it never starts threads of its own. Opening a deferred file is a unit like any other, and -//! at most `open_concurrency` opens are queued or running at once. -//! -//! Splits run as [`RepeatedScan::execute_stream`] runs them: -//! -//! - A scan with a filter and a limit builds each split on a CPU thread only once it is taken -//! to run ([`spawn_lazy_split`]), so no new split starts once the limit is spent, and optimizes the -//! rows the limit keeps on a second CPU task ([`spawn_map_trimmed`]). -//! - Every other scan builds all of a file's split tasks together, when the first of them is -//! taken, so the file's reads are registered at once and can coalesce. A limit is reserved -//! then, in split order. -//! -//! The pools differ in how workers share the work: -//! -//! - An unordered pool runs lanes on the runtime once its first worker starts: one for each run -//! of splits or open that is ready, more as they queue, and at most enough to keep -//! `splits_in_flight` splits running. Each lane takes the next unit from a channel of units, -//! runs it, and sends its rows into one bounded output channel. An opened file is one unit, its -//! turn, which a lane queues again after taking the file's next run of adjacent splits, so the -//! lanes read the opened files in turn, a run at a time, and poll each run's splits together so -//! that their reads coalesce. A lane that opens a deferred file queues the file's turn, followed -//! by the next deferred file. Workers only take rows from the output channel, so whichever -//! worker asks next gets the next rows, however many workers there are, and the number of -//! workers is only the host's parallelism. The output channel closes once every lane has -//! finished, which ends the workers. -//! - An ordered pool gives all of its units, in row order, to its first worker, which keeps -//! `splits_in_flight` of them running at once; later workers get nothing. Parallel ordered reads -//! cut the scan with `split` first. +//! The pool an opened layout scan shares among host threads. -use std::any::Any; -use std::collections::VecDeque; -use std::iter; -use std::num::NonZeroUsize; -use std::ops::Range; use std::sync::Arc; -use std::sync::atomic::AtomicBool; use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering; +use std::vec; -use async_channel::Receiver; -use async_channel::Sender; -use async_lock::OnceCell; -use futures::FutureExt; -use futures::StreamExt; -use futures::future; use futures::future::BoxFuture; use futures::stream; -use futures::stream::BoxStream; -use futures::stream::FuturesUnordered; use parking_lot::Mutex; -use tracing::Instrument; use vortex_array::ArrayRef; use vortex_array::dtype::DType; -use vortex_array::expr::stats::Precision; use vortex_array::stream::ArrayStreamAdapter; use vortex_array::stream::ArrayStreamExt; use vortex_array::stream::SendableArrayStream; use vortex_error::VortexResult; -use vortex_io::runtime::Handle; -use vortex_io::runtime::Task; -use vortex_io::session::RuntimeSessionExt; -use vortex_scan::DataSourceScanRef; -use vortex_scan::Partition; -use vortex_scan::PartitionRef; -use vortex_scan::PartitionStream; use vortex_scan::pool::ScanPool; -use vortex_scan::pool::ScanPoolRef; -use vortex_scan::row_mask::RowMask; -use vortex_session::VortexSession; -use vortex_utils::parallelism::get_available_parallelism; -use crate::LayoutReaderRef; -use crate::scan::limit::RowLimit; -use crate::scan::multi::LayoutReaderFactory; -use crate::scan::repeated_scan::DEFAULT_SPLITS_PER_THREAD; -use crate::scan::repeated_scan::MapFn; -use crate::scan::repeated_scan::RepeatedScan; -use crate::scan::repeated_scan::SplitConcurrency; -use crate::scan::repeated_scan::can_prune_file; -use crate::scan::repeated_scan::recheck_prune_file; -use crate::scan::repeated_scan::spawn_lazy_split; -use crate::scan::repeated_scan::spawn_map_trimmed; -use crate::scan::repeated_scan::stop_on_error; -use crate::scan::tasks::SplitFuture; -use crate::scan::tasks::TaskContext; -use crate::scan::tasks::split_exec; +use crate::scan::repeated_scan::ScanTasks; -/// A scan prepared once and shared by every piece and execution of it. -pub(crate) type PreparedScan = RepeatedScan; +/// One split of a scan, which returns the split's array, or `None` when the filter removes all +/// of its rows. +type SplitTask = BoxFuture<'static, VortexResult>>; -/// A prepared scan and the row ranges of its splits, in row order. -pub(crate) type PlannedSplits = (Arc, Vec>); - -/// One execution of one file's prepared scan over some of its splits. -pub(crate) struct FileScan { - scan: Arc, - /// Records this execution's events, so file events count once for each execution. - ctx: Arc, - /// The row ranges of the splits, in row order. - ranges: Vec>, - /// The task of each split, built together when a worker first takes one of them. `None` - /// where the split has no rows to read, or a worker has taken it. - tasks: OnceCell>>>, - /// Whether whole-file statistics reject the filter when the file's first split is taken. - pruned: OnceCell, -} - -impl FileScan { - /// Whether whole-file statistics reject the filter, checked again when the first split is - /// taken, as [`RepeatedScan::execute_stream`] checks when it starts: a filter with dynamic - /// parts may reject the file by then though it did not when the pool was opened. - async fn is_pruned(&self) -> VortexResult { - let pruned = self - .pruned - .get_or_try_init(|| future::ready(recheck_prune_file(&self.ctx))) - .await?; - Ok(*pruned) - } - - /// The tasks of the file's splits, built on first use. A file whose tasks are built once a - /// reserved limit is spent, or that statistics now reject, builds none. - async fn tasks(&self, limit: &PoolLimit) -> VortexResult<&[Mutex>]> { - let tasks = self - .tasks - .get_or_try_init(|| async { - if self.is_pruned().await? { - return Ok(Vec::new()); - } - self.build_tasks(limit) - }) - .await?; - Ok(tasks) - } - - /// Builds every split's task, which registers its reads, reserving a reserved limit in split - /// order. - fn build_tasks(&self, limit: &PoolLimit) -> VortexResult>>> { - self.ranges - .iter() - .map(|range| { - let mask = self.scan.split_mask(range).and_then(|mask| match limit { - PoolLimit::Reserve(limit) => { - let reserved = limit.limit(mask.mask().clone()); - (!reserved.all_false()).then(|| RowMask::new(range.start, reserved)) - } - PoolLimit::Unlimited | PoolLimit::Trim(_) => Some(mask), - }); - let task = mask - .map(|mask| self.scan.split_task(&self.ctx, mask)) - .transpose()?; - Ok(Mutex::new(task)) - }) - .collect() - } -} - -/// One file's splits for one execution, ready to be handed to workers. -pub(crate) struct FileWork { - file: Option>, -} - -impl FileWork { - /// A file with nothing to read, for example one that statistics pruned. - pub(crate) fn empty() -> Self { - Self { file: None } - } - - /// Starts an execution of `scan` over its split `ranges`. - /// - /// Counts a file scan attempt when the ranges select any row, and returns no work when - /// whole-file statistics reject the filter. - pub(crate) fn start(scan: Arc, ranges: Vec>) -> VortexResult { - if !ranges.iter().any(|range| scan.selects_rows(range)) { - return Ok(Self::empty()); - } - let ctx = scan.task_context(); - if can_prune_file(&ctx)? { - return Ok(Self::empty()); - } - Ok(Self { - file: Some(Arc::new(FileScan { - scan, - ctx, - ranges, - tasks: OnceCell::new(), - pruned: OnceCell::new(), - })), - }) - } -} - -/// Opens a deferred file's reader into its work for this execution. -pub(crate) type PrepareFile = Arc VortexResult + Send + Sync>; - -/// A file of a pool, in file order. -pub(crate) enum PoolFile { - Opened(FileWork), - Deferred(Arc), -} - -/// How a pool reads its splits. -pub(crate) struct PoolOptions { - pub(crate) session: VortexSession, - pub(crate) dtype: DType, - pub(crate) ordered: bool, - pub(crate) limit: Option, - /// Whether the scan filters rows, so a split's output row count is unknown up front. - pub(crate) has_filter: bool, - /// The request's bound on the splits each worker keeps in flight. - pub(crate) split_concurrency: Option, - /// The most deferred files that are queued or being opened at once. - pub(crate) open_concurrency: usize, -} - -/// Opens a pool over `files`, in file order. `prepare` turns an opened deferred file into work. -pub(crate) fn open_pool( - options: PoolOptions, - files: Vec, - prepare: Option, -) -> ScanPoolRef { - let limit = match options.limit { - None => PoolLimit::Unlimited, - Some(limit) if options.has_filter => PoolLimit::Trim(RowLimit::new(limit)), - Some(limit) => PoolLimit::Reserve(RowLimit::new(limit)), - }; - // The pool keeps as many splits in flight as one scan stream does by default: four per core, - // at most the request's `split_concurrency`, however many workers read it. The runtime's - // threads decode them, so more in flight would only read further ahead, and the file's - // registered reads already let I/O coalesce ahead of the splits being decoded. - let splits_in_flight = SplitConcurrency { - per_worker: DEFAULT_SPLITS_PER_THREAD, - max: options.split_concurrency, - } - .splits_in_flight() - .max(1); - let open_concurrency = options.open_concurrency.max(1); - let shared = Arc::new(Shared { - limit, - prepare, - session: options.session, - file_share: 1.0 / files.len().max(1) as f64, - progress: Mutex::new(0.0), - deferred: Mutex::new(VecDeque::new()), - failed: AtomicBool::new(false), - pending: AtomicUsize::new(0), - }); - if options.ordered { - return Arc::new(OrderedPool { - dtype: options.dtype, - shared, - files: Mutex::new(Some(files)), - splits_in_flight, - open_concurrency, - }); - } - - let (sender, receiver) = async_channel::unbounded(); - let mut opens = 0; - for file in files { - match file { - PoolFile::Opened(work) => shared.queue_file(&sender, work), - PoolFile::Deferred(factory) if opens < open_concurrency => { - opens += 1; - let slot = OpenSlot { - shared: Arc::clone(&shared), - sender: sender.clone(), - }; - shared.queue(&sender, Work::Open(factory, slot)); - } - PoolFile::Deferred(factory) => shared.deferred.lock().push_back(factory), - } - } - // Each open file gets an equal share of the splits in flight, and a lane takes a file's share - // as one run of adjacent splits that it starts together. The run's reads then reach the - // file's read driver together and coalesce, as they do when one scan stream polls its - // file's splits; a run of one would hand the driver one read at a time. The rotation moves - // between files after each run, and the lanes hold `splits_in_flight` splits in all. A run is - // at most one core's share, so that a scan of few files, such as a single-file scan whose - // share is every split in flight, still has a lane per core. - let cores = get_available_parallelism().unwrap_or(1).max(1); - let run = (splits_in_flight / open_concurrency) - .min(splits_in_flight / cores) - .max(1); - let (output, outputs) = async_channel::bounded(splits_in_flight); - let lanes = Arc::new(Lanes { - shared: Arc::clone(&shared), - units: receiver.clone(), - run, - max: (splits_in_flight / run).max(1), - waiting: AtomicUsize::new(0), - started: AtomicUsize::new(0), - tasks: Mutex::new(Some(Vec::new())), - }); - Arc::new(UnorderedPool { - dtype: options.dtype, - shared, - units: receiver, - outputs, - lanes, - output: Mutex::new(Some(output)), - }) -} - -/// How a pool's row limit is applied. -enum PoolLimit { - Unlimited, - /// A split's selected rows are its output rows, so a file reserves its splits' rows from the - /// budget in split order when it builds their tasks, and rows past the limit are never - /// decoded. Files build in row order in an ordered pool, so it returns exactly the first rows. - Reserve(RowLimit), - /// A split's output rows are unknown until its filter has run, so workers take rows from the - /// budget as they yield them and discard the excess. - Trim(RowLimit), -} - -impl PoolLimit { - /// Whether the budget is spent, so no file that has not started has rows to return. - fn is_spent(&self) -> bool { - match self { - PoolLimit::Unlimited => false, - PoolLimit::Reserve(limit) | PoolLimit::Trim(limit) => limit.is_exhausted(), - } - } - - /// Whether a trimmed budget is spent, so workers end without returning any more rows. - fn is_trimmed_out(&self) -> bool { - matches!(self, PoolLimit::Trim(limit) if limit.is_exhausted()) - } -} - -/// A split's output: `None` when it has no rows to return. -type SplitOutput = BoxFuture<'static, VortexResult>>; - -/// A split of a file by its index, with the progress that taking it adds. -type FileSplit = (Arc, usize, f64); - -/// What every worker of a pool shares. -struct Shared { - limit: PoolLimit, - prepare: Option, - /// The session whose runtime runs the pool's splits and opens. - session: VortexSession, - /// The progress that one file adds. - file_share: f64, - progress: Mutex, - /// An unordered pool's deferred files that are not yet queued for opening, in file order. - deferred: Mutex>>, - /// Whether a unit of an unordered pool failed, which stops its lanes. - failed: AtomicBool, - /// The splits and opens of an unordered pool that are queued and not yet taken by a lane. - pending: AtomicUsize, -} - -impl Shared { - /// The splits of an opened file, in row order. - fn file_splits(&self, work: FileWork) -> Vec { - let Some(file) = work.file else { - *self.progress.lock() += self.file_share; - return Vec::new(); - }; - let rows: u64 = file - .ranges - .iter() - .map(|range| range.end - range.start) - .sum(); - if rows == 0 { - *self.progress.lock() += self.file_share; - return Vec::new(); - } - let per_row = self.file_share / rows as f64; - (0..file.ranges.len()) - .map(|index| { - let range = &file.ranges[index]; - let progress = per_row * (range.end - range.start) as f64; - (Arc::clone(&file), index, progress) - }) - .collect() - } - - /// Opens a deferred file into its work, on the task that polls it. A file that starts after - /// the limit is spent is not opened. - fn open_file( - self: &Arc, - factory: Arc, - ) -> BoxFuture<'static, VortexResult> { - if self.limit.is_spent() { - return future::ready(Ok(FileWork::empty())).boxed(); - } - let shared = Arc::clone(self); - async move { - let reader = factory - .open() - .instrument(tracing::info_span!("LayoutReaderFactory::open")) - .await?; - match (reader, &shared.prepare) { - (Some(reader), Some(prepare)) => prepare(reader), - _ => Ok(FileWork::empty()), - } - } - .boxed() - } - - /// Opens a deferred file into its work as a task on the session's runtime. - fn spawn_open_file( - self: &Arc, - factory: Arc, - ) -> BoxFuture<'static, VortexResult> { - if self.limit.is_spent() { - return future::ready(Ok(FileWork::empty())).boxed(); - } - self.session.handle().spawn(self.open_file(factory)).boxed() - } - - /// The next deferred file of an unordered pool to open, if any is left and the limit is not - /// spent. Once it is spent, the files left count as read. - fn next_deferred(&self) -> Option> { - let mut deferred = self.deferred.lock(); - if self.limit.is_spent() && !deferred.is_empty() { - *self.progress.lock() += self.file_share * deferred.len() as f64; - deferred.clear(); - } - deferred.pop_front() - } - - /// Takes a split. A split of a scan with a filter and a limit is built and run as - /// [`spawn_lazy_split`] runs it; any other split runs as a task on the session's runtime, since - /// a split decodes inside its future. - fn admit(self: &Arc, (file, index, progress): FileSplit) -> SplitOutput { - *self.progress.lock() += progress; - let handle = self.session.handle(); - if let PoolLimit::Trim(_) = &self.limit { - let Some(mask) = file.scan.split_mask(&file.ranges[index]) else { - return future::ready(Ok(None)).boxed(); - }; - return async move { - if file.is_pruned().await? { - return Ok(None); - } - spawn_lazy_split(&handle, move || split_exec(&file.ctx, mask).map(Some)).await - } - .boxed(); - } - let shared = Arc::clone(self); - async move { - let task = file - .tasks(&shared.limit) - .await? - .get(index) - .and_then(|task| task.lock().take()); - match task { - Some(task) => handle.spawn(task).await, - None => Ok(None), - } - } - .boxed() - } - - /// Queues a unit of an unordered pool, counting the splits or open it holds as pending. - fn queue(&self, sender: &Sender, work: Work) { - let units = match &work { - Work::File(splits, _) => splits.len(), - Work::Open(..) => 1, - }; - self.pending.fetch_add(units, Ordering::AcqRel); - send(sender, work); - } - - /// Queues an opened file of an unordered pool as one turn among the files. - fn queue_file(&self, sender: &Sender, work: FileWork) { - let splits: VecDeque = self.file_splits(work).into(); - if !splits.is_empty() { - self.queue(sender, Work::File(splits, sender.clone())); - } - } - - fn progress(&self) -> f64 { - if self.limit.is_trimmed_out() { - return 1.0; - } - self.progress.lock().clamp(0.0, 1.0) - } - - /// An ordered worker's output: skips splits with no rows, trims to a trimmed limit, and ends - /// after the first error or once a trimmed limit is spent. A trimmed array is optimized again, - /// on a CPU task, `splits_in_flight` at a time. - fn output( - self: Arc, - outputs: BoxStream<'static, VortexResult>>, - splits_in_flight: usize, - ) -> BoxStream<'static, VortexResult> { - let trimmed = matches!(self.limit, PoolLimit::Trim(_)); - let handle = self.session.handle(); - let session = self.session.clone(); - let arrays = limit_output(outputs, self); - if !trimmed { - return arrays; - } - let identity: MapFn = Arc::new(Ok); - let mapped = arrays.map(move |array| { - spawn_map_trimmed(&handle, session.clone(), Arc::clone(&identity), array) - }); - stop_on_error(mapped.buffered(splits_in_flight).boxed()) - } -} - -/// Skips splits with no rows, trims to a trimmed limit, and ends after the first error or once -/// a trimmed limit is spent. -fn limit_output( - outputs: BoxStream<'static, VortexResult>>, - shared: Arc, -) -> BoxStream<'static, VortexResult> { - stream::unfold(Some(outputs), move |outputs| { - let shared = Arc::clone(&shared); - async move { - let mut outputs = outputs?; - loop { - if shared.limit.is_trimmed_out() { - return None; - } - let array = match outputs.next().await? { - Ok(Some(array)) => array, - Ok(None) => continue, - Err(err) => return Some((Err(err), None)), - }; - let PoolLimit::Trim(limit) = &shared.limit else { - return Some((Ok(array), Some(outputs))); - }; - let granted = limit.take(array.len()); - if granted == 0 { - return None; - } - if granted == array.len() { - return Some((Ok(array), Some(outputs))); - } - return Some((array.slice(0..granted), None)); - } - } - }) - .boxed() -} - -/// A unit of an unordered pool's channel. -enum Work { - /// An opened file's turn: the splits not yet taken, in row order. The lane that takes the - /// turn takes the file's next run of splits and queues the turn again behind the other - /// files' turns, so the lanes take runs from every opened file in turn rather than from one - /// file after another. Each file then has only a few splits in flight, which keeps its first rows, and - /// any dynamic filter they tighten, ahead of its later splits. - File(VecDeque, Sender), - /// A deferred file, and the open slot it holds until its turn is in the channel. - Open(Arc, OpenSlot), -} - -/// What a lane takes from a unit. -enum Taken { - /// A run of a file's adjacent splits, in row order. - Splits(Vec), - Open(Arc, OpenSlot), -} - -impl Taken { - /// The pending splits or open that this takes. - fn units(&self) -> usize { - match self { - Taken::Splits(splits) => splits.len(), - Taken::Open(..) => 1, - } - } -} - -impl Work { - /// Takes the unit's next `run` splits, or its open, queueing a file's turn again while it - /// has splits left. - fn take(self, run: usize) -> Option { - match self { - Work::File(mut splits, sender) => { - let taken: Vec<_> = splits.drain(..run.min(splits.len())).collect(); - if !splits.is_empty() { - let requeue = sender.clone(); - send(&requeue, Work::File(splits, sender)); - } - (!taken.is_empty()).then_some(Taken::Splits(taken)) - } - Work::Open(factory, slot) => Some(Taken::Open(factory, slot)), - } - } -} - -/// One of an unordered pool's `open_concurrency` open slots. Its sender keeps the channel open -/// while the file that holds it is queued or opening. -struct OpenSlot { - shared: Arc, - sender: Sender, -} - -impl Drop for OpenSlot { - /// Passes the slot to the next deferred file, queued behind the turns already in the channel, - /// so opens keep pace with the workers. The slot passes on whether the open finished or a - /// dropped worker gave it up, so that worker strands only the file it was opening. - fn drop(&mut self) { - if self.sender.is_closed() { - return; - } - if let Some(next) = self.shared.next_deferred() { - let slot = OpenSlot { - shared: Arc::clone(&self.shared), - sender: self.sender.clone(), - }; - self.shared.queue(&self.sender, Work::Open(next, slot)); - } - } -} - -fn send(sender: &Sender, work: Work) { - // The channel is unbounded and closes only once the pool is dropped, when the work is moot. - drop(sender.try_send(work)); -} - -/// The lanes of an unordered pool. They start when its first worker does, as many as there are -/// splits and opens ready, and grow while those wait for a lane, up to `splits_in_flight`, so a -/// scan with few units spawns and wakes few tasks. -struct Lanes { - shared: Arc, - units: Receiver, - /// The most adjacent splits of a file that a lane takes and polls together. - run: usize, - /// The most lanes that run at once. - max: usize, - /// Lanes waiting for a unit. - waiting: AtomicUsize, - /// Lanes started, so a lane can see without a lock that no more may start. - started: AtomicUsize, - /// The lanes started, until the pool is dropped, which aborts them. `None` once it is. - tasks: Mutex>>>, -} - -impl Lanes { - /// Starts lanes for the units that no waiting lane will take, up to the most that run at - /// once. Each lane holds a sender of the output channel. - fn grow(self: &Arc, output: &Sender>) { - // Every lane calls this for every unit it takes, so it locks only to start lanes. - if self.started.load(Ordering::Acquire) >= self.max || self.unserved() == 0 { - return; - } - let mut tasks = self.tasks.lock(); - let Some(tasks) = tasks.as_mut() else { - return; - }; - let new = self - .unserved() - .div_ceil(self.run) - .min(self.max.saturating_sub(tasks.len())); - if new == 0 { - return; - } - let handle = self.shared.session.handle(); - tasks.extend((0..new).map(|_| handle.spawn(lane(Arc::clone(self), output.clone())))); - self.started.store(tasks.len(), Ordering::Release); - } - - /// The pending splits and opens that the lanes waiting for a unit will not take, each of - /// which takes up to a run. - fn unserved(&self) -> usize { - self.shared - .pending - .load(Ordering::Acquire) - .saturating_sub(self.waiting.load(Ordering::Acquire) * self.run) - } -} - -/// A pool whose lanes run its units on the runtime, and whose workers share their output. -struct UnorderedPool { +/// A pool over the split futures of [`RepeatedScan::execute`], in row order. +/// +/// A worker claims the next split and then runs it itself, outside the lock, one split at a +/// time. This is how DuckDB's threads read a file's splits on develop, so a host that runs one +/// worker per thread reads as many splits at once as it has threads, with no read-ahead. +/// +/// [`RepeatedScan::execute`]: crate::scan::repeated_scan::RepeatedScan::execute +pub(crate) struct SplitPool { dtype: DType, - shared: Arc, - units: Receiver, - outputs: Receiver>, - lanes: Arc, - /// The sender of the output channel until the first worker starts the lanes, which hold it - /// from then on. - output: Mutex>>>, + splits: Mutex>, + total: usize, + claimed: AtomicUsize, } -impl UnorderedPool { - /// Runs a unit for the lane that took it. Each split of a run runs as a task of its own, as - /// [`RepeatedScan::execute_stream`] runs it, since a split decodes inside its future: the run's - /// splits start together, so their reads coalesce, and decode on as many threads as there - /// are splits. An open runs on the lane itself. - fn run(shared: &Arc, taken: Taken) -> FuturesUnordered { - match taken { - Taken::Splits(splits) => splits - .into_iter() - .map(|split| shared.admit(split)) - .collect(), - Taken::Open(factory, slot) => iter::once( - async move { - let opened = slot.shared.open_file(factory).await.map(|work| { - slot.shared.queue_file(&slot.sender, work); - None - }); - drop(slot); - opened - } - .boxed(), - ) - .collect(), - } - } - - /// Starts the lanes, once. With no units, it starts none, and the output channel closes. - fn start_lanes(&self) { - // Dropping the pool's own sender leaves the lanes holding the output channel open. - if let Some(output) = self.output.lock().take() { - self.lanes.grow(&output); +impl SplitPool { + pub(crate) fn new(dtype: DType, splits: ScanTasks) -> Self { + Self { + dtype, + total: splits.len(), + splits: Mutex::new(splits.into_iter()), + claimed: AtomicUsize::new(0), } } -} -/// A lane: runs units one at a time and sends their rows to the workers, trimming them to a -/// trimmed limit. Ends once the units run out, a limit is spent, a unit fails, or every worker -/// is gone. -async fn lane(lanes: Arc, output: Sender>) { - let shared = Arc::clone(&lanes.shared); - let handle = shared.session.handle(); - let identity: MapFn = Arc::new(Ok); - while !shared.limit.is_trimmed_out() && !shared.failed.load(Ordering::Acquire) { - lanes.waiting.fetch_add(1, Ordering::AcqRel); - let work = lanes.units.recv().await; - lanes.waiting.fetch_sub(1, Ordering::AcqRel); - let Ok(work) = work else { - return; - }; - let Some(taken) = work.take(lanes.run) else { - continue; - }; - shared.pending.fetch_sub(taken.units(), Ordering::AcqRel); - // Units the waiting lanes will not take get lanes of their own, such as the splits an - // open has just queued. - lanes.grow(&output); - let mut running = UnorderedPool::run(&shared, taken); - while let Some(array) = running.next().await { - let array = match array { - Ok(Some(array)) => Ok(array), - Ok(None) => continue, - Err(err) => Err(err), - }; - if !emit(&shared, &handle, &identity, &output, array).await { - return; - } - } + /// Claims the next split, if any is left. + fn claim(&self) -> Option { + let split = self.splits.lock().next()?; + self.claimed.fetch_add(1, Ordering::Release); + Some(split) } } -/// Sends a lane's rows to the workers, trimmed to a trimmed limit. Returns whether the lane -/// should go on: not once the limit is spent, a unit failed, or every worker is gone. -async fn emit( - shared: &Shared, - handle: &Handle, - identity: &MapFn, - output: &Sender>, - array: VortexResult, -) -> bool { - let array = match (&shared.limit, array) { - (PoolLimit::Trim(limit), Ok(array)) => { - let granted = limit.take(array.len()); - if granted == 0 { - return false; - } - let array = if granted < array.len() { - array.slice(0..granted) - } else { - Ok(array) - }; - spawn_map_trimmed(handle, shared.session.clone(), Arc::clone(identity), array).await - } - (_, array) => array, - }; - let failed = array.is_err(); - if failed { - shared.failed.store(true, Ordering::Release); - } - output.send(array).await.is_ok() && !failed -} - -impl ScanPool for UnorderedPool { +impl ScanPool for SplitPool { fn dtype(&self) -> &DType { &self.dtype } fn worker(self: Arc) -> SendableArrayStream { - self.start_lanes(); let dtype = self.dtype.clone(); - // The worker holds the pool, so the lanes run until the pool's last worker is dropped. let arrays = stream::unfold(self, |pool| async move { - let array = pool.outputs.recv().await.ok()?; - Some((array, pool)) - }) - .boxed(); - ArrayStreamExt::boxed(ArrayStreamAdapter::new(dtype, stop_on_error(arrays))) + loop { + match pool.claim()?.await { + Ok(Some(array)) => return Some((Ok(array), pool)), + Ok(None) => {} + Err(err) => return Some((Err(err), pool)), + } + } + }); + ArrayStreamExt::boxed(ArrayStreamAdapter::new(dtype, arrays)) } fn progress(&self) -> f64 { - if self.is_exhausted() { + if self.total == 0 { return 1.0; } - self.shared.progress() - } - - fn is_exhausted(&self) -> bool { - // The lanes hold the output channel's senders, so it closes once every lane has ended. - self.outputs.is_closed() && self.outputs.is_empty() - } -} - -impl Drop for UnorderedPool { - fn drop(&mut self) { - // Pending opens hold senders of the channel of units itself; drain them so it can be - // freed. The lanes are aborted when they are dropped. - self.units.close(); - while self.units.try_recv().is_ok() {} - self.outputs.close(); - drop(self.lanes.tasks.lock().take()); - } -} - -/// A pool that gives all of its units, in row order, to its first worker. -struct OrderedPool { - dtype: DType, - shared: Arc, - /// The files, until the first worker takes them. - files: Mutex>>, - splits_in_flight: usize, - open_concurrency: usize, -} - -impl ScanPool for OrderedPool { - fn dtype(&self) -> &DType { - &self.dtype - } - - fn worker(self: Arc) -> SendableArrayStream { - let dtype = self.dtype.clone(); - let Some(files) = self.files.lock().take() else { - return ArrayStreamExt::boxed(ArrayStreamAdapter::new(dtype, stream::empty())); - }; - let shared = Arc::clone(&self.shared); - let opener = Arc::clone(&shared); - let splitter = Arc::clone(&shared); - let admitter = Arc::clone(&shared); - let gate = Arc::clone(&shared); - // Deferred files open `open_concurrency` at a time, ahead of the splits being read. - let outputs = stream::iter(files) - .map(move |file| match file { - PoolFile::Opened(work) => future::ready(Ok(work)).boxed(), - PoolFile::Deferred(factory) => opener.spawn_open_file(factory), - }) - .buffered(self.open_concurrency) - .flat_map(move |work| match work { - Ok(work) => { - stream::iter(splitter.file_splits(work).into_iter().map(Ok)).left_stream() - } - Err(err) => stream::once(future::ready(Err(err))).right_stream(), - }) - .take_while(move |_| future::ready(!gate.limit.is_trimmed_out())) - .map(move |split| match split { - Ok(split) => admitter.admit(split), - Err(err) => future::ready(Err(err)).boxed(), - }) - .buffered(self.splits_in_flight) - .boxed(); - ArrayStreamExt::boxed(ArrayStreamAdapter::new( - dtype, - shared.output(outputs, self.splits_in_flight), - )) - } - - fn progress(&self) -> f64 { - self.shared.progress() + (self.claimed.load(Ordering::Acquire) as f64 / self.total as f64).clamp(0.0, 1.0) } fn is_exhausted(&self) -> bool { - // The first worker takes every file. - self.shared.limit.is_trimmed_out() || self.files.lock().is_none() - } -} - -/// The single partition of a scan piece that is read through the partitions API: it opens the -/// piece and reads it with one worker. -pub(crate) struct PiecePartition { - piece: DataSourceScanRef, - index: usize, -} - -impl PiecePartition { - /// The partitions of `piece`: one, whose index is `index`. - pub(crate) fn stream(piece: DataSourceScanRef, index: usize) -> PartitionStream { - stream::iter([Ok(Box::new(PiecePartition { piece, index }) as PartitionRef)]).boxed() - } -} - -impl Partition for PiecePartition { - fn as_any(&self) -> &dyn Any { - self - } - - fn index(&self) -> usize { - self.index - } - - fn row_count(&self) -> Precision { - self.piece.row_count() - } - - fn byte_size(&self) -> Precision { - self.piece.byte_size() - } - - fn execute(self: Box) -> VortexResult { - Ok(self.piece.open()?.worker()) + self.claimed.load(Ordering::Acquire) >= self.total } } diff --git a/vortex-layout/src/scan/repeated_scan.rs b/vortex-layout/src/scan/repeated_scan.rs index e1654b05e98..f13b4bc752d 100644 --- a/vortex-layout/src/scan/repeated_scan.rs +++ b/vortex-layout/src/scan/repeated_scan.rs @@ -31,8 +31,6 @@ use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_error::vortex_bail; use vortex_io::runtime::BlockingRuntime; -use vortex_io::runtime::Handle; -use vortex_io::runtime::Task; use vortex_io::session::RuntimeSessionExt; use vortex_scan::row_mask::RowMask; use vortex_scan::selection::Selection; @@ -86,7 +84,7 @@ pub struct RepeatedScan { pub type ScanTasks = Vec>>>; /// A function applied to each projected split array. -pub(crate) type MapFn = Arc VortexResult + Send + Sync>; +type MapFn = Arc VortexResult + Send + Sync>; impl RepeatedScan { pub fn execute_array_iter( @@ -177,7 +175,7 @@ impl RepeatedScan { } /// Each execution gets its own recorder, so file events count once for each execution. - pub(crate) fn task_context(&self) -> Arc { + fn task_context(&self) -> Arc { Arc::new(TaskContext { filter: self .filter @@ -190,9 +188,7 @@ impl RepeatedScan { }) } - /// The row ranges of the scan's splits within `row_range`, in row order. - /// - /// Ranges whose rows the selection excludes are included; [`Self::split_mask`] skips them. + /// The row ranges of the scan's natural splits within `row_range`, in row order. pub(crate) fn split_ranges(&self, row_range: Option>) -> Vec> { let selection_range: Option> = match &self.selection { Selection::IncludeByIndex(buf) if !buf.is_empty() => { @@ -249,33 +245,6 @@ impl RepeatedScan { } } - /// Whether the selection includes any row of `range`. - pub(crate) fn selects_rows(&self, range: &Range) -> bool { - self.selection.row_count_in_range(range) != 0 - } - - /// The number of rows of `range` that the selection includes. - pub(crate) fn selected_row_count(&self, range: &Range) -> u64 { - self.selection.row_count_in_range(range) - } - - /// The selected rows of the split over `range`, or `None` if the selection excludes them all. - pub(crate) fn split_mask(&self, range: &Range) -> Option { - selected_mask(&self.selection, range) - } - - /// Builds the task of one split. The task does no work until it is polled, but building it - /// may register the split's reads with the reader, so build it only when it is about to run. - /// - /// `mask` must select at least one row. - pub(crate) fn split_task( - &self, - ctx: &Arc, - mask: RowMask, - ) -> VortexResult>>> { - Ok(map_split(split_exec(ctx, mask)?, &self.map_fn)) - } - /// The non-empty row masks of the splits within `row_range`, in split order. fn split_masks(&self, row_range: Option>) -> impl Iterator + '_ { self.split_ranges(row_range) @@ -328,13 +297,21 @@ impl RepeatedScan { .map(move |split| { let ctx = Arc::clone(&ctx); let selection = selection.clone(); - spawn_lazy_split(&split_handle, move || { - let Some(row_mask) = - split.either(Some, |range| selected_mask(&selection, &range)) - else { - return Ok(None); - }; - split_exec(&ctx, row_mask).map(Some) + split_handle.spawn_nested(move |handle| async move { + let task = handle + .spawn_cpu(move || { + let Some(row_mask) = + split.either(Some, |range| selected_mask(&selection, &range)) + else { + return Ok(None); + }; + split_exec(&ctx, row_mask).map(Some) + }) + .await?; + match task { + Some(task) => task.await, + None => Ok(None), + } }) }); let map_fn = Arc::clone(map_fn); @@ -343,7 +320,9 @@ impl RepeatedScan { .boxed(); let session = self.session.clone(); let mapped = limit_rows(arrays, limit).map(move |array| { - spawn_map_trimmed(&handle, session.clone(), Arc::clone(&map_fn), array) + let map_fn = Arc::clone(&map_fn); + let session = session.clone(); + handle.spawn_cpu(move || map_fn(array?.optimize_ctx(&session)?)) }); buffer(mapped, ordered, concurrency) } @@ -378,52 +357,14 @@ impl RepeatedScan { } } -/// Builds a split's task on a CPU thread and runs it, both on the session's runtime. -/// -/// This is how scans with a filter and a limit run their splits: a split's output row count is -/// unknown until its filter has run, so each split is built only once it is about to run, and none -/// start once the limit is spent. `build` returns `None` when the split has nothing to read. Every -/// other scan builds all of its split tasks up front with [`RepeatedScan::split_task`], so that -/// their reads are registered together and can coalesce, and runs each with [`Handle::spawn`]. -pub(crate) fn spawn_lazy_split( - handle: &Handle, - build: impl FnOnce() -> VortexResult> + Send + 'static, -) -> Task>> { - handle.spawn_nested(move |handle| async move { - match handle.spawn_cpu(build).await? { - Some(task) => task.await, - None => Ok(None), - } - }) -} - -/// Optimizes an array that a limit may have trimmed and maps it, on a CPU thread: the second -/// stage of a scan with a filter and a limit, after [`spawn_lazy_split`]. -pub(crate) fn spawn_map_trimmed( - handle: &Handle, - session: VortexSession, - map_fn: MapFn, - array: VortexResult, -) -> Task> { - handle.spawn_cpu(move || map_fn(array?.optimize_ctx(&session)?)) -} - /// This function returns `None` if the selection excludes every row in `range`. fn selected_mask(selection: &Selection, range: &Range) -> Option { let mask = selection.row_mask(range); (!mask.mask().all_false()).then_some(mask) } -/// Counts a file scan attempt and returns whether whole-file statistics reject the filter. -pub(crate) fn can_prune_file(ctx: &TaskContext) -> VortexResult { +fn can_prune_file(ctx: &TaskContext) -> VortexResult { ctx.count::(ScanRecorder::attempt_file_scan); - recheck_prune_file(ctx) -} - -/// Returns whether whole-file statistics reject the filter, for a file whose scan attempt -/// [`can_prune_file`] has already counted. A filter with dynamic parts, such as a join's, may -/// reject a file later that it did not reject when the scan started. -pub(crate) fn recheck_prune_file(ctx: &TaskContext) -> VortexResult { if let Some(filter) = &ctx.filter && can_prune_conjuncts(filter, ctx.reader.as_ref())? { @@ -481,7 +422,7 @@ fn limit_rows( } /// Yield the first error and drop upstream without polling it again. -pub(crate) fn stop_on_error( +fn stop_on_error( stream: BoxStream<'static, VortexResult>, ) -> BoxStream<'static, VortexResult> { let mut stream = Some(stream); @@ -498,10 +439,6 @@ pub(crate) fn stop_on_error( .boxed() } -/// The splits a scan keeps in flight for each worker thread by default, which allows for some I/O -/// lookahead without too much impact on work-stealing. -pub(crate) const DEFAULT_SPLITS_PER_THREAD: usize = 4; - /// How many splits a scan makes progress on at once: `per_worker` for each worker thread, as /// [`get_available_parallelism`] counts them, and at most `max` in all when that is set. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -511,7 +448,7 @@ pub(crate) struct SplitConcurrency { } impl SplitConcurrency { - pub(crate) fn splits_in_flight(self) -> usize { + fn splits_in_flight(self) -> usize { let scaled = self .per_worker .saturating_mul(get_available_parallelism().unwrap_or(1)); diff --git a/vortex-layout/src/scan/scan_builder.rs b/vortex-layout/src/scan/scan_builder.rs index 96373ae3e72..3785489d710 100644 --- a/vortex-layout/src/scan/scan_builder.rs +++ b/vortex-layout/src/scan/scan_builder.rs @@ -40,7 +40,6 @@ use crate::scan::limit::RowLimit; use crate::scan::limit::ScanLimit; use crate::scan::metrics::ScanMetrics; use crate::scan::metrics::ScanUsage; -use crate::scan::repeated_scan::DEFAULT_SPLITS_PER_THREAD; use crate::scan::repeated_scan::RepeatedScan; use crate::scan::repeated_scan::ScanTasks; use crate::scan::repeated_scan::SplitConcurrency; @@ -104,8 +103,10 @@ impl ScanBuilder { selection: Default::default(), split_by: SplitBy::default(), natural_splits: None, + // We default to four tasks per worker thread, which allows for some I/O lookahead + // without too much impact on work-stealing. concurrency: SplitConcurrency { - per_worker: DEFAULT_SPLITS_PER_THREAD, + per_worker: 4, max: None, }, map_fn: Arc::new(Ok), diff --git a/vortex-layout/src/scan/test.rs b/vortex-layout/src/scan/test.rs index 0e15bcced80..85c4b25d8b1 100644 --- a/vortex-layout/src/scan/test.rs +++ b/vortex-layout/src/scan/test.rs @@ -23,13 +23,10 @@ use vortex_error::VortexResult; use vortex_error::vortex_err; use vortex_io::runtime::BlockingRuntime; use vortex_io::runtime::Handle; -use vortex_io::runtime::current::CurrentThreadRuntime; -use vortex_io::runtime::current::CurrentThreadWorkerPool; use vortex_io::runtime::single::SingleThreadRuntime; use vortex_io::session::RuntimeSession; use vortex_io::session::RuntimeSessionExt; use vortex_mask::Mask; -use vortex_scan::pool::ScanPoolRef; use vortex_session::VortexSession; use crate::ArrayFuture; @@ -40,20 +37,10 @@ use crate::session::LayoutSession; static SESSION: LazyLock = LazyLock::new(VortexSession::empty); -/// A runtime driven by background threads, so splits the pools spawn make progress while test -/// workers block on their streams with `futures::executor`. -static RUNTIME: LazyLock<(CurrentThreadRuntime, CurrentThreadWorkerPool)> = LazyLock::new(|| { - let runtime = CurrentThreadRuntime::new(); - let pool = runtime.new_pool(); - pool.set_workers(4); - (runtime, pool) -}); - pub fn new_session() -> VortexSession { VortexSession::empty() .with::() .with::() - .with_handle(RUNTIME.0.handle()) } pub fn session_with_handle(handle: Handle) -> VortexSession { @@ -83,8 +70,6 @@ pub struct TestLayoutReader { projection_masks: Option>>>, filter_exprs: Option>>>, in_flight: Option>, - yields: fn(u64) -> usize, - built_projections: Option>, } /// Counts projections running at once, and the most that ever were. @@ -116,8 +101,6 @@ impl TestLayoutReader { projection_masks: None, filter_exprs: None, in_flight: None, - yields: |_| 0, - built_projections: None, } } @@ -154,19 +137,6 @@ impl TestLayoutReader { self } - /// Makes the projection of the split starting at row `start` yield `yields(start)` times - /// before it finishes, so tests can make splits complete out of row order. - pub fn with_yields(mut self, yields: fn(u64) -> usize) -> Self { - self.yields = yields; - self - } - - /// Counts the projections built, which is when a split registers its reads. - pub fn with_built_projections(mut self, built: Arc) -> Self { - self.built_projections = Some(built); - self - } - pub fn with_filter_exprs(mut self, filter_exprs: Arc>>) -> Self { self.filter_exprs = Some(filter_exprs); self @@ -291,15 +261,8 @@ impl LayoutReader for TestLayoutReader { let projection_masks = self.projection_masks.clone(); let fail = self.fail_projection || (self.fail_first_projection && row_range.start == 0); let in_flight = self.in_flight.clone(); - let yields = (self.yields)(row_range.start); - if let Some(built) = &self.built_projections { - built.fetch_add(1, Ordering::SeqCst); - } Ok(Box::pin(async move { - for _ in 0..yields { - tokio::task::yield_now().await; - } if let Some(in_flight) = &in_flight { let now = in_flight.now.fetch_add(1, Ordering::SeqCst) + 1; in_flight.peak.fetch_max(now, Ordering::SeqCst); @@ -350,28 +313,6 @@ where Ok(values) } -/// Reads `pool` with `workers` workers, each polled on its own thread, returning each worker's -/// values in the order it yielded them. -pub fn read_with_workers(pool: &ScanPoolRef, workers: usize) -> VortexResult>> { - std::thread::scope(|scope| { - let handles = (0..workers) - .map(|_| { - let worker = Arc::clone(pool).worker(); - scope.spawn(move || collect_scan_values(futures::executor::block_on_stream(worker))) - }) - .collect::>(); - handles - .into_iter() - .map(|handle| handle.join().expect("worker thread panicked")) - .collect() - }) -} - -/// Reads `pool` with a single worker polled on the calling thread. -pub fn read_with_one_worker(pool: ScanPoolRef) -> VortexResult> { - collect_scan_values(futures::executor::block_on_stream(pool.worker())) -} - /// Let already-spawned scan tasks run to completion after the stream has been dropped. pub fn drain_runtime(runtime: &SingleThreadRuntime) { for _ in 0..4 { From a68063c45e636de7b07532089742d1ab08e774da Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 13:33:58 -0500 Subject: [PATCH 29/80] Test group_contiguous against ranges grouped by their first row Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-layout/src/scan/layout.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/vortex-layout/src/scan/layout.rs b/vortex-layout/src/scan/layout.rs index 2b4ab2d1d5a..52464361851 100644 --- a/vortex-layout/src/scan/layout.rs +++ b/vortex-layout/src/scan/layout.rs @@ -838,9 +838,10 @@ mod split_open_tests { #[test] fn group_contiguous_keeps_ranges_whole() -> VortexResult<()> { - let ranges = vec![0..10, 10..12, 12..30, 30..31]; + // Each range joins the group its first row falls in. + let ranges = vec![0..10, 10..16, 16..26, 26..32]; let groups = group_contiguous(ranges, NonZeroUsize::try_from(2)?); - assert_eq!(groups, vec![vec![0..10, 10..12], vec![12..30, 30..31]]); + assert_eq!(groups, vec![vec![0..10, 10..16], vec![16..26, 26..32]]); Ok(()) } } From b414761130cc32f6e26da001c2ff1f336c4a5f11 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 13:41:19 -0500 Subject: [PATCH 30/80] Keep develop's splits in flight when opening a file, and split inside files An opened single-file scan's workers each keep the stream pipeline's per-thread count of splits in flight, spawned on the session runtime, so a host polling one worker per core keeps as many in flight as the stream does. A worker yields only the splits it claimed, so no worker waits on another's. A multi-file scan split into more pieces than it has files cuts its open files at their layout split boundaries, sharing the pieces by row count. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-layout/src/scan/layout.rs | 50 ++++-- vortex-layout/src/scan/multi.rs | 198 ++++++++++++++++++++---- vortex-layout/src/scan/pool.rs | 44 ++++-- vortex-layout/src/scan/repeated_scan.rs | 4 + vortex-layout/src/scan/scan_builder.rs | 5 +- 5 files changed, 236 insertions(+), 65 deletions(-) diff --git a/vortex-layout/src/scan/layout.rs b/vortex-layout/src/scan/layout.rs index 52464361851..5833a9001bb 100644 --- a/vortex-layout/src/scan/layout.rs +++ b/vortex-layout/src/scan/layout.rs @@ -29,6 +29,7 @@ use vortex_array::stream::ArrayStreamExt; use vortex_array::stream::SendableArrayStream; use vortex_error::VortexResult; use vortex_error::vortex_bail; +use vortex_io::session::RuntimeSessionExt; use vortex_mask::Mask; use vortex_metrics::MetricsRegistry; use vortex_scan::DataSource; @@ -48,6 +49,7 @@ use crate::scan::limit::RowLimit; use crate::scan::metrics::ScanMetrics; use crate::scan::metrics::ScanRecorder; use crate::scan::pool::SplitPool; +use crate::scan::repeated_scan::DEFAULT_SPLITS_PER_THREAD; use crate::scan::scan_builder::ScanBuilder; /// An implementation of a [`DataSource`] that reads data from a [`LayoutReaderRef`]. @@ -305,21 +307,32 @@ impl DataSourceScan for LayoutReaderScan { .collect()) } - /// Opens the scan into a queue of its split futures, which workers claim one at a time and - /// run themselves: develop's DuckDB scan of a file. + /// Opens the scan into a [`SplitPool`] over its split futures, each worker keeping the + /// stream pipeline's per-thread count of them in flight. /// - /// Split futures cannot share a limit, and workers of a queue finish splits out of row - /// order. So a scan with a limit, or an ordered one, keeps its partition pipeline and hands - /// its partitions to workers instead. + /// Split futures cannot share a limit, and the workers of a queue finish splits out of row + /// order. So a scan with a limit, or an ordered one, opens into its partition pipeline and + /// hands its partitions to workers. fn open(self: Box) -> VortexResult { if self.remaining_limit.is_some() || self.ordered { return Ok(Arc::new(PartitionPool::new(self))); } + // A cap on the scan's splits in flight also caps each worker's. + let per_worker = self + .split_concurrency + .map_or(DEFAULT_SPLITS_PER_THREAD, |max| { + max.get().min(DEFAULT_SPLITS_PER_THREAD) + }); let splits = self .builder() .prepare()? .execute(Some(self.next_row..self.end_row))?; - Ok(Arc::new(SplitPool::new(self.dtype, splits))) + Ok(Arc::new(SplitPool::new( + self.dtype, + self.session.handle(), + per_worker, + splits, + ))) } fn row_count(&self) -> Precision { @@ -758,8 +771,6 @@ mod split_open_tests { use std::sync::Arc; use futures::TryStreamExt; - use futures::executor::block_on; - use futures::executor::block_on_stream; use futures::future::try_join_all; use vortex_array::expr::stats::Precision; use vortex_error::VortexResult; @@ -772,13 +783,12 @@ mod split_open_tests { use super::group_contiguous; use crate::scan::test::TestLayoutReader; use crate::scan::test::collect_scan_values; - use crate::scan::test::new_session; use crate::scan::test::session_with_handle; - fn source() -> LayoutReaderDataSource { + fn source(runtime: &SingleThreadRuntime) -> LayoutReaderDataSource { LayoutReaderDataSource::new( Arc::new(TestLayoutReader::new(64).with_split_size(4)), - new_session(), + session_with_handle(runtime.handle()), ) } @@ -786,9 +796,12 @@ mod split_open_tests { /// every row once. #[test] fn opened_workers_read_every_row_once() -> VortexResult<()> { - let pool = block_on(source().scan(ScanRequest::default()))?.open()?; + let runtime = SingleThreadRuntime::default(); + let pool = runtime + .block_on(source(&runtime).scan(ScanRequest::default()))? + .open()?; let workers = (0..3).map(|_| Arc::clone(&pool).worker().try_collect::>()); - let arrays = block_on(try_join_all(workers))?; + let arrays = runtime.block_on(try_join_all(workers))?; let mut values = collect_scan_values(arrays.into_iter().flatten().map(Ok))?; values.sort_unstable(); assert_eq!(values, (0..64).collect::>()); @@ -800,15 +813,18 @@ mod split_open_tests { /// Splitting cuts at the layout's split boundaries, and the pieces read the rows in order. #[test] fn split_cuts_at_split_boundaries() -> VortexResult<()> { - let scan = block_on(source().scan(ScanRequest::default()))?; + let runtime = SingleThreadRuntime::default(); + let scan = runtime.block_on(source(&runtime).scan(ScanRequest::default()))?; let pieces = scan.split(NonZeroUsize::try_from(4)?)?; assert_eq!(pieces.len(), 4); let mut values = Vec::new(); for piece in pieces { assert_eq!(piece.row_count(), Precision::exact(16u64)); - values.extend(collect_scan_values(block_on_stream( - piece.open()?.worker(), - ))?); + let mut piece_values = + collect_scan_values(runtime.block_on_stream(piece.open()?.worker()))?; + // A worker yields its splits as they finish. + piece_values.sort_unstable(); + values.extend(piece_values); } assert_eq!(values, (0..64).collect::>()); Ok(()) diff --git a/vortex-layout/src/scan/multi.rs b/vortex-layout/src/scan/multi.rs index 5d5b605bbe6..576528c87de 100644 --- a/vortex-layout/src/scan/multi.rs +++ b/vortex-layout/src/scan/multi.rs @@ -26,6 +26,7 @@ use std::any::Any; use std::collections::VecDeque; +use std::mem; use std::num::NonZeroUsize; use std::ops::Range; use std::sync::Arc; @@ -64,6 +65,7 @@ use vortex_session::VortexSession; use vortex_utils::parallelism::get_available_parallelism; use crate::LayoutReaderRef; +use crate::scan::layout::group_contiguous; use crate::scan::limit::RowLimit; use crate::scan::scan_builder::ScanBuilder; @@ -390,12 +392,139 @@ struct MultiLayoutScan { concurrency: usize, } +impl MultiLayoutScan { + /// This scan over `ready` and `deferred` files only, reading `row_range` of each. + fn piece( + &self, + ready: VecDeque, + deferred: VecDeque>, + row_range: Option>, + ) -> DataSourceScanRef { + Box::new(MultiLayoutScan { + session: self.session.clone(), + source_dtype: self.source_dtype.clone(), + dtype: self.dtype.clone(), + request: BoundScanRequest { + row_range, + ..self.request.clone() + }, + row_limit: self.row_limit.clone(), + ready, + deferred, + handle: self.handle.clone(), + concurrency: self.concurrency, + }) + } + + /// Cuts the scan into `pieces` runs of whole files, in file order. `pieces` is at most the + /// number of files. + fn split_files(mut self: Box, pieces: usize) -> Vec { + let files = self.ready.len() + self.deferred.len(); + let mut ready = mem::take(&mut self.ready); + let mut deferred = mem::take(&mut self.deferred); + let row_range = self.request.row_range.clone(); + (0..pieces) + .map(|piece| { + // Piece `piece` takes files `piece * files / pieces` up to the next piece's start. + let take = (piece + 1) * files / pieces - piece * files / pieces; + let from_ready = take.min(ready.len()); + self.piece( + ready.drain(..from_ready).collect(), + deferred.drain(..take - from_ready).collect(), + row_range.clone(), + ) + }) + .collect() + } + + /// Cuts every open file at its layout's split boundaries into `extra` more pieces than it has + /// files in all, shared among the open files by row count. Each unopened file is one piece. + fn split_within_files(self: Box, extra: usize) -> Vec { + fn rows(ranges: &[Range]) -> u64 { + ranges.iter().map(|range| range.end - range.start).sum() + } + + let file_ranges: Vec>>> = self + .ready + .iter() + .map(|reader| self.file_split_ranges(reader)) + .collect(); + let total_rows = file_ranges + .iter() + .flatten() + .map(|ranges| u128::from(rows(ranges))) + .sum::() + .max(1); + let budget = (self.ready.len() + extra) as u128; + + let mut pieces = Vec::new(); + for (reader, ranges) in self.ready.iter().zip(file_ranges) { + let Some(ranges) = ranges else { + // The file's splits could not be planned, so its partition reports why when read. + pieces.push(self.piece( + [Arc::clone(reader)].into(), + VecDeque::new(), + self.request.row_range.clone(), + )); + continue; + }; + let share = u128::from(rows(&ranges)) * budget / total_rows; + let share = NonZeroUsize::new(usize::try_from(share).unwrap_or(usize::MAX)) + .unwrap_or(NonZeroUsize::MIN); + for group in group_contiguous(ranges, share) { + if let (Some(first), Some(last)) = (group.first(), group.last()) { + pieces.push(self.piece( + [Arc::clone(reader)].into(), + VecDeque::new(), + Some(first.start..last.end), + )); + } + } + } + for factory in &self.deferred { + pieces.push(self.piece( + VecDeque::new(), + [Arc::clone(factory)].into(), + self.request.row_range.clone(), + )); + } + if pieces.is_empty() { + // Every open file's selection is empty and no file is unopened. + return vec![self]; + } + pieces + } + + /// The row ranges of `reader`'s natural splits that the scan reads, or `None` if they cannot + /// be planned, such as when the request does not bind to the file. + fn file_split_ranges(&self, reader: &LayoutReaderRef) -> Option>> { + let row_range = self + .request + .row_range + .clone() + .unwrap_or(0..reader.row_count()); + let filter = self.request.filter.clone().ok()?; + let scan = ScanBuilder::new(self.session.clone(), Arc::clone(reader)) + .with_selection(self.request.selection.clone()) + .with_projection(self.request.projection.clone()) + .with_some_filter(filter) + .prepare() + .ok()?; + Some(scan.split_ranges(Some(row_range))) + } +} + impl DataSourceScan for MultiLayoutScan { fn dtype(&self) -> &DType { &self.dtype } - /// Cuts the scan into pieces of whole files, in file order, without opening any. + /// Cuts the scan into up to `n` contiguous pieces in file order, reading metadata only. + /// + /// With no more pieces than files, each piece is a run of whole files. With more, each file + /// whose reader is open is cut further at its layout's split boundaries, with pieces shared + /// among the open files by row count. A file not yet opened is one piece, since cutting it + /// would mean opening it. /// /// A scan with a limit stays whole, because the limit is one budget across all its files, /// and so does one that selects partitions, because partition indices count from its first @@ -403,43 +532,17 @@ impl DataSourceScan for MultiLayoutScan { fn split(self: Box, n: NonZeroUsize) -> VortexResult> { let files = self.ready.len() + self.deferred.len(); if n.get() == 1 - || files <= 1 + || files == 0 || self.request.limit.is_some() || self.request.partition_range.is_some() || !matches!(self.request.partition_selection, Selection::All) { return Ok(vec![self]); } - let Self { - session, - source_dtype, - dtype, - request, - row_limit, - mut ready, - mut deferred, - handle, - concurrency, - } = *self; - let pieces = n.get().min(files); - Ok((0..pieces) - .map(|piece| { - // Piece `piece` takes files `piece * files / pieces` up to the next piece's start. - let take = (piece + 1) * files / pieces - piece * files / pieces; - let from_ready = take.min(ready.len()); - Box::new(MultiLayoutScan { - session: session.clone(), - source_dtype: source_dtype.clone(), - dtype: dtype.clone(), - request: request.clone(), - row_limit: row_limit.clone(), - ready: ready.drain(..from_ready).collect(), - deferred: deferred.drain(..take - from_ready).collect(), - handle: handle.clone(), - concurrency, - }) as DataSourceScanRef - }) - .collect()) + if n.get() <= files { + return Ok(self.split_files(n.get())); + } + Ok(self.split_within_files(n.get() - files)) } /// Opens the scan into its partition pipeline, which opens up to `concurrency` files ahead @@ -838,6 +941,37 @@ mod tests { Ok(()) } + /// With more pieces than files, an open file is cut at its split boundaries, and an + /// unopened file stays one piece. + #[test] + fn split_cuts_open_files_at_split_boundaries() -> VortexResult<()> { + let runtime = SingleThreadRuntime::default(); + let session = session_with_handle(runtime.handle()); + let first: LayoutReaderRef = Arc::new(TestLayoutReader::new(8).with_split_size(2)); + let rest: Vec> = vec![Arc::new(StaticReaderFactory { + reader: Arc::new(TestLayoutReader::new(2).with_base(10)), + })]; + let source = MultiLayoutDataSource::new_with_first(first, rest, vec![], &session); + + let scan = runtime.block_on(source.scan(ScanRequest { + ordered: true, + ..Default::default() + }))?; + let pieces = scan.split(NonZeroUsize::try_from(4)?)?; + assert_eq!(pieces.len(), 4); + + let mut values = Vec::new(); + for piece in pieces { + for partition in runtime.block_on(piece.partitions().try_collect::>())? { + values.extend(collect_scan_values( + runtime.block_on_stream(partition.execute()?), + )?); + } + } + assert_eq!(values, [0, 1, 2, 3, 4, 5, 6, 7, 10, 11]); + Ok(()) + } + /// Scans 64 one-row splits, returning the rows and the most splits read at once. fn scan_with_split_concurrency( split_concurrency: Option, diff --git a/vortex-layout/src/scan/pool.rs b/vortex-layout/src/scan/pool.rs index 002372a3d23..207c55c41bf 100644 --- a/vortex-layout/src/scan/pool.rs +++ b/vortex-layout/src/scan/pool.rs @@ -3,11 +3,14 @@ //! The pool an opened layout scan shares among host threads. +use std::iter; use std::sync::Arc; use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering; use std::vec; +use futures::StreamExt; +use futures::future; use futures::future::BoxFuture; use futures::stream; use parking_lot::Mutex; @@ -17,6 +20,7 @@ use vortex_array::stream::ArrayStreamAdapter; use vortex_array::stream::ArrayStreamExt; use vortex_array::stream::SendableArrayStream; use vortex_error::VortexResult; +use vortex_io::runtime::Handle; use vortex_scan::pool::ScanPool; use crate::scan::repeated_scan::ScanTasks; @@ -27,22 +31,37 @@ type SplitTask = BoxFuture<'static, VortexResult>>; /// A pool over the split futures of [`RepeatedScan::execute`], in row order. /// -/// A worker claims the next split and then runs it itself, outside the lock, one split at a -/// time. This is how DuckDB's threads read a file's splits on develop, so a host that runs one -/// worker per thread reads as many splits at once as it has threads, with no read-ahead. +/// Each worker claims splits from the shared queue and keeps up to `per_worker` of its own in +/// flight, spawned on the session's runtime, yielding them as they finish. This is the scan's +/// stream pipeline with its in-flight bound split across workers: `per_worker` is the per-thread +/// count that the stream multiplies by the cores, so a host polling one worker per core keeps as +/// many splits in flight as the stream does. +/// +/// A worker yields only the splits it claimed, and claims a split only when it has room for one. +/// So [`is_exhausted`](ScanPool::is_exhausted) turns true once every split has been claimed, and +/// a host can move a thread to other work then: no worker waits on a split another one claimed. /// /// [`RepeatedScan::execute`]: crate::scan::repeated_scan::RepeatedScan::execute pub(crate) struct SplitPool { dtype: DType, + handle: Handle, + per_worker: usize, splits: Mutex>, total: usize, claimed: AtomicUsize, } impl SplitPool { - pub(crate) fn new(dtype: DType, splits: ScanTasks) -> Self { + pub(crate) fn new( + dtype: DType, + handle: Handle, + per_worker: usize, + splits: ScanTasks, + ) -> Self { Self { dtype, + handle, + per_worker: per_worker.max(1), total: splits.len(), splits: Mutex::new(splits.into_iter()), claimed: AtomicUsize::new(0), @@ -64,15 +83,14 @@ impl ScanPool for SplitPool { fn worker(self: Arc) -> SendableArrayStream { let dtype = self.dtype.clone(); - let arrays = stream::unfold(self, |pool| async move { - loop { - match pool.claim()?.await { - Ok(Some(array)) => return Some((Ok(array), pool)), - Ok(None) => {} - Err(err) => return Some((Err(err), pool)), - } - } - }); + let handle = self.handle.clone(); + let per_worker = self.per_worker; + // `buffer_unordered` pulls a split only when it has room, so a worker claims no more + // than it runs. + let arrays = stream::iter(iter::from_fn(move || self.claim())) + .map(move |split| handle.spawn(split)) + .buffer_unordered(per_worker) + .filter_map(|array| future::ready(array.transpose())); ArrayStreamExt::boxed(ArrayStreamAdapter::new(dtype, arrays)) } diff --git a/vortex-layout/src/scan/repeated_scan.rs b/vortex-layout/src/scan/repeated_scan.rs index f13b4bc752d..1a950fec418 100644 --- a/vortex-layout/src/scan/repeated_scan.rs +++ b/vortex-layout/src/scan/repeated_scan.rs @@ -439,6 +439,10 @@ fn stop_on_error( .boxed() } +/// The splits a scan keeps in flight for each worker thread by default, which allows for some I/O +/// lookahead without too much impact on work-stealing. +pub(crate) const DEFAULT_SPLITS_PER_THREAD: usize = 4; + /// How many splits a scan makes progress on at once: `per_worker` for each worker thread, as /// [`get_available_parallelism`] counts them, and at most `max` in all when that is set. #[derive(Clone, Copy, Debug, PartialEq, Eq)] diff --git a/vortex-layout/src/scan/scan_builder.rs b/vortex-layout/src/scan/scan_builder.rs index 3785489d710..96373ae3e72 100644 --- a/vortex-layout/src/scan/scan_builder.rs +++ b/vortex-layout/src/scan/scan_builder.rs @@ -40,6 +40,7 @@ use crate::scan::limit::RowLimit; use crate::scan::limit::ScanLimit; use crate::scan::metrics::ScanMetrics; use crate::scan::metrics::ScanUsage; +use crate::scan::repeated_scan::DEFAULT_SPLITS_PER_THREAD; use crate::scan::repeated_scan::RepeatedScan; use crate::scan::repeated_scan::ScanTasks; use crate::scan::repeated_scan::SplitConcurrency; @@ -103,10 +104,8 @@ impl ScanBuilder { selection: Default::default(), split_by: SplitBy::default(), natural_splits: None, - // We default to four tasks per worker thread, which allows for some I/O lookahead - // without too much impact on work-stealing. concurrency: SplitConcurrency { - per_worker: 4, + per_worker: DEFAULT_SPLITS_PER_THREAD, max: None, }, map_fn: Arc::new(Ok), From 93e06a51da97bf048ce95b673e57552bcfd4acc7 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 13:47:24 -0500 Subject: [PATCH 31/80] 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 168533026beffd121fb3ade15b1d1bce2b85ccb5 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 13:47:43 -0500 Subject: [PATCH 32/80] Keep multi-file split to runs of whole files A multi-file scan splits into runs of whole files only, so the path stays small until multi-file reading moves to a composite over child sources. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-layout/src/scan/multi.rs | 198 ++++++-------------------------- 1 file changed, 32 insertions(+), 166 deletions(-) diff --git a/vortex-layout/src/scan/multi.rs b/vortex-layout/src/scan/multi.rs index 576528c87de..5d5b605bbe6 100644 --- a/vortex-layout/src/scan/multi.rs +++ b/vortex-layout/src/scan/multi.rs @@ -26,7 +26,6 @@ use std::any::Any; use std::collections::VecDeque; -use std::mem; use std::num::NonZeroUsize; use std::ops::Range; use std::sync::Arc; @@ -65,7 +64,6 @@ use vortex_session::VortexSession; use vortex_utils::parallelism::get_available_parallelism; use crate::LayoutReaderRef; -use crate::scan::layout::group_contiguous; use crate::scan::limit::RowLimit; use crate::scan::scan_builder::ScanBuilder; @@ -392,139 +390,12 @@ struct MultiLayoutScan { concurrency: usize, } -impl MultiLayoutScan { - /// This scan over `ready` and `deferred` files only, reading `row_range` of each. - fn piece( - &self, - ready: VecDeque, - deferred: VecDeque>, - row_range: Option>, - ) -> DataSourceScanRef { - Box::new(MultiLayoutScan { - session: self.session.clone(), - source_dtype: self.source_dtype.clone(), - dtype: self.dtype.clone(), - request: BoundScanRequest { - row_range, - ..self.request.clone() - }, - row_limit: self.row_limit.clone(), - ready, - deferred, - handle: self.handle.clone(), - concurrency: self.concurrency, - }) - } - - /// Cuts the scan into `pieces` runs of whole files, in file order. `pieces` is at most the - /// number of files. - fn split_files(mut self: Box, pieces: usize) -> Vec { - let files = self.ready.len() + self.deferred.len(); - let mut ready = mem::take(&mut self.ready); - let mut deferred = mem::take(&mut self.deferred); - let row_range = self.request.row_range.clone(); - (0..pieces) - .map(|piece| { - // Piece `piece` takes files `piece * files / pieces` up to the next piece's start. - let take = (piece + 1) * files / pieces - piece * files / pieces; - let from_ready = take.min(ready.len()); - self.piece( - ready.drain(..from_ready).collect(), - deferred.drain(..take - from_ready).collect(), - row_range.clone(), - ) - }) - .collect() - } - - /// Cuts every open file at its layout's split boundaries into `extra` more pieces than it has - /// files in all, shared among the open files by row count. Each unopened file is one piece. - fn split_within_files(self: Box, extra: usize) -> Vec { - fn rows(ranges: &[Range]) -> u64 { - ranges.iter().map(|range| range.end - range.start).sum() - } - - let file_ranges: Vec>>> = self - .ready - .iter() - .map(|reader| self.file_split_ranges(reader)) - .collect(); - let total_rows = file_ranges - .iter() - .flatten() - .map(|ranges| u128::from(rows(ranges))) - .sum::() - .max(1); - let budget = (self.ready.len() + extra) as u128; - - let mut pieces = Vec::new(); - for (reader, ranges) in self.ready.iter().zip(file_ranges) { - let Some(ranges) = ranges else { - // The file's splits could not be planned, so its partition reports why when read. - pieces.push(self.piece( - [Arc::clone(reader)].into(), - VecDeque::new(), - self.request.row_range.clone(), - )); - continue; - }; - let share = u128::from(rows(&ranges)) * budget / total_rows; - let share = NonZeroUsize::new(usize::try_from(share).unwrap_or(usize::MAX)) - .unwrap_or(NonZeroUsize::MIN); - for group in group_contiguous(ranges, share) { - if let (Some(first), Some(last)) = (group.first(), group.last()) { - pieces.push(self.piece( - [Arc::clone(reader)].into(), - VecDeque::new(), - Some(first.start..last.end), - )); - } - } - } - for factory in &self.deferred { - pieces.push(self.piece( - VecDeque::new(), - [Arc::clone(factory)].into(), - self.request.row_range.clone(), - )); - } - if pieces.is_empty() { - // Every open file's selection is empty and no file is unopened. - return vec![self]; - } - pieces - } - - /// The row ranges of `reader`'s natural splits that the scan reads, or `None` if they cannot - /// be planned, such as when the request does not bind to the file. - fn file_split_ranges(&self, reader: &LayoutReaderRef) -> Option>> { - let row_range = self - .request - .row_range - .clone() - .unwrap_or(0..reader.row_count()); - let filter = self.request.filter.clone().ok()?; - let scan = ScanBuilder::new(self.session.clone(), Arc::clone(reader)) - .with_selection(self.request.selection.clone()) - .with_projection(self.request.projection.clone()) - .with_some_filter(filter) - .prepare() - .ok()?; - Some(scan.split_ranges(Some(row_range))) - } -} - impl DataSourceScan for MultiLayoutScan { fn dtype(&self) -> &DType { &self.dtype } - /// Cuts the scan into up to `n` contiguous pieces in file order, reading metadata only. - /// - /// With no more pieces than files, each piece is a run of whole files. With more, each file - /// whose reader is open is cut further at its layout's split boundaries, with pieces shared - /// among the open files by row count. A file not yet opened is one piece, since cutting it - /// would mean opening it. + /// Cuts the scan into pieces of whole files, in file order, without opening any. /// /// A scan with a limit stays whole, because the limit is one budget across all its files, /// and so does one that selects partitions, because partition indices count from its first @@ -532,17 +403,43 @@ impl DataSourceScan for MultiLayoutScan { fn split(self: Box, n: NonZeroUsize) -> VortexResult> { let files = self.ready.len() + self.deferred.len(); if n.get() == 1 - || files == 0 + || files <= 1 || self.request.limit.is_some() || self.request.partition_range.is_some() || !matches!(self.request.partition_selection, Selection::All) { return Ok(vec![self]); } - if n.get() <= files { - return Ok(self.split_files(n.get())); - } - Ok(self.split_within_files(n.get() - files)) + let Self { + session, + source_dtype, + dtype, + request, + row_limit, + mut ready, + mut deferred, + handle, + concurrency, + } = *self; + let pieces = n.get().min(files); + Ok((0..pieces) + .map(|piece| { + // Piece `piece` takes files `piece * files / pieces` up to the next piece's start. + let take = (piece + 1) * files / pieces - piece * files / pieces; + let from_ready = take.min(ready.len()); + Box::new(MultiLayoutScan { + session: session.clone(), + source_dtype: source_dtype.clone(), + dtype: dtype.clone(), + request: request.clone(), + row_limit: row_limit.clone(), + ready: ready.drain(..from_ready).collect(), + deferred: deferred.drain(..take - from_ready).collect(), + handle: handle.clone(), + concurrency, + }) as DataSourceScanRef + }) + .collect()) } /// Opens the scan into its partition pipeline, which opens up to `concurrency` files ahead @@ -941,37 +838,6 @@ mod tests { Ok(()) } - /// With more pieces than files, an open file is cut at its split boundaries, and an - /// unopened file stays one piece. - #[test] - fn split_cuts_open_files_at_split_boundaries() -> VortexResult<()> { - let runtime = SingleThreadRuntime::default(); - let session = session_with_handle(runtime.handle()); - let first: LayoutReaderRef = Arc::new(TestLayoutReader::new(8).with_split_size(2)); - let rest: Vec> = vec![Arc::new(StaticReaderFactory { - reader: Arc::new(TestLayoutReader::new(2).with_base(10)), - })]; - let source = MultiLayoutDataSource::new_with_first(first, rest, vec![], &session); - - let scan = runtime.block_on(source.scan(ScanRequest { - ordered: true, - ..Default::default() - }))?; - let pieces = scan.split(NonZeroUsize::try_from(4)?)?; - assert_eq!(pieces.len(), 4); - - let mut values = Vec::new(); - for piece in pieces { - for partition in runtime.block_on(piece.partitions().try_collect::>())? { - values.extend(collect_scan_values( - runtime.block_on_stream(partition.execute()?), - )?); - } - } - assert_eq!(values, [0, 1, 2, 3, 4, 5, 6, 7, 10, 11]); - Ok(()) - } - /// Scans 64 one-row splits, returning the rows and the most splits read at once. fn scan_with_split_concurrency( split_concurrency: Option, From 1d002df04bdbc1741bdadf8af021f7588868851f Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 13:53:39 -0500 Subject: [PATCH 33/80] 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 570b1c334208b7ca1804b985dc55cb3823d4d202 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 13:54:08 -0500 Subject: [PATCH 34/80] Drop the layout pools' unused size and progress methods Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-layout/src/scan/layout.rs | 22 ---------------------- vortex-layout/src/scan/pool.rs | 26 +++----------------------- 2 files changed, 3 insertions(+), 45 deletions(-) diff --git a/vortex-layout/src/scan/layout.rs b/vortex-layout/src/scan/layout.rs index 5833a9001bb..f8505c8fb98 100644 --- a/vortex-layout/src/scan/layout.rs +++ b/vortex-layout/src/scan/layout.rs @@ -335,20 +335,6 @@ impl DataSourceScan for LayoutReaderScan { ))) } - fn row_count(&self) -> Precision { - let selected = self - .selection - .row_count_in_range(&(self.next_row..self.end_row)); - let rows = self - .remaining_limit - .map_or(selected, |limit| selected.min(limit)); - if self.filter.is_some() { - Precision::inexact(rows) - } else { - Precision::exact(rows) - } - } - fn partition_count(&self) -> Precision { let (lower, upper) = self.size_hint(); match upper { @@ -550,10 +536,6 @@ impl DataSourceScan for Empty { fn partitions(self: Box) -> PartitionStream { stream::iter([Ok(self as _)]).boxed() } - - fn row_count(&self) -> Precision { - Precision::exact(self.row_count) - } } impl Partition for Empty { @@ -772,7 +754,6 @@ mod split_open_tests { use futures::TryStreamExt; use futures::future::try_join_all; - use vortex_array::expr::stats::Precision; use vortex_error::VortexResult; use vortex_io::runtime::BlockingRuntime; use vortex_io::runtime::single::SingleThreadRuntime; @@ -805,8 +786,6 @@ mod split_open_tests { let mut values = collect_scan_values(arrays.into_iter().flatten().map(Ok))?; values.sort_unstable(); assert_eq!(values, (0..64).collect::>()); - assert!(pool.is_exhausted()); - assert_eq!(pool.progress(), 1.0); Ok(()) } @@ -819,7 +798,6 @@ mod split_open_tests { assert_eq!(pieces.len(), 4); let mut values = Vec::new(); for piece in pieces { - assert_eq!(piece.row_count(), Precision::exact(16u64)); let mut piece_values = collect_scan_values(runtime.block_on_stream(piece.open()?.worker()))?; // A worker yields its splits as they finish. diff --git a/vortex-layout/src/scan/pool.rs b/vortex-layout/src/scan/pool.rs index 207c55c41bf..dd0ba0e9fed 100644 --- a/vortex-layout/src/scan/pool.rs +++ b/vortex-layout/src/scan/pool.rs @@ -5,8 +5,6 @@ use std::iter; use std::sync::Arc; -use std::sync::atomic::AtomicUsize; -use std::sync::atomic::Ordering; use std::vec; use futures::StreamExt; @@ -37,9 +35,8 @@ type SplitTask = BoxFuture<'static, VortexResult>>; /// count that the stream multiplies by the cores, so a host polling one worker per core keeps as /// many splits in flight as the stream does. /// -/// A worker yields only the splits it claimed, and claims a split only when it has room for one. -/// So [`is_exhausted`](ScanPool::is_exhausted) turns true once every split has been claimed, and -/// a host can move a thread to other work then: no worker waits on a split another one claimed. +/// A worker yields only the splits it claimed, and claims a split only when it has room for one, +/// so no worker waits on a split another one claimed. /// /// [`RepeatedScan::execute`]: crate::scan::repeated_scan::RepeatedScan::execute pub(crate) struct SplitPool { @@ -47,8 +44,6 @@ pub(crate) struct SplitPool { handle: Handle, per_worker: usize, splits: Mutex>, - total: usize, - claimed: AtomicUsize, } impl SplitPool { @@ -62,17 +57,13 @@ impl SplitPool { dtype, handle, per_worker: per_worker.max(1), - total: splits.len(), splits: Mutex::new(splits.into_iter()), - claimed: AtomicUsize::new(0), } } /// Claims the next split, if any is left. fn claim(&self) -> Option { - let split = self.splits.lock().next()?; - self.claimed.fetch_add(1, Ordering::Release); - Some(split) + self.splits.lock().next() } } @@ -93,15 +84,4 @@ impl ScanPool for SplitPool { .filter_map(|array| future::ready(array.transpose())); ArrayStreamExt::boxed(ArrayStreamAdapter::new(dtype, arrays)) } - - fn progress(&self) -> f64 { - if self.total == 0 { - return 1.0; - } - (self.claimed.load(Ordering::Acquire) as f64 / self.total as f64).clamp(0.0, 1.0) - } - - fn is_exhausted(&self) -> bool { - self.claimed.load(Ordering::Acquire) >= self.total - } } From b40dc55cc37cef7d0292a7126bbce9a409a93cd6 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 14:02:41 -0500 Subject: [PATCH 35/80] Read each VortexTable output partition from its own split piece DataFusion runs output partitions independently, so output partition i of n now splits the scan into at most n pieces and reads piece i with one worker. Partitions share no state, which keeps them correct when they run in separate processes. VORTEX_SCAN_POOL=0 keeps the shared partition stream for comparison. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- Cargo.lock | 1 - vortex-datafusion/Cargo.toml | 1 - vortex-datafusion/src/v2/source.rs | 396 +++++++++++------------------ 3 files changed, 153 insertions(+), 245 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 09694b71a38..1baac90bd38 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -11734,7 +11734,6 @@ dependencies = [ "insta", "itertools 0.14.0", "object_store 0.13.2", - "parking_lot", "rstest", "tempfile", "tokio", diff --git a/vortex-datafusion/Cargo.toml b/vortex-datafusion/Cargo.toml index e4d046a523d..fa73a69b0e9 100644 --- a/vortex-datafusion/Cargo.toml +++ b/vortex-datafusion/Cargo.toml @@ -32,7 +32,6 @@ datafusion-pruning = { workspace = true } futures = { workspace = true } itertools = { workspace = true } object_store = { workspace = true } -parking_lot = { workspace = true } tokio = { workspace = true, features = ["rt-multi-thread", "fs"] } tokio-stream = { workspace = true } tracing = { workspace = true, features = ["std", "attributes"] } diff --git a/vortex-datafusion/src/v2/source.rs b/vortex-datafusion/src/v2/source.rs index bdbad992e62..95c114ec652 100644 --- a/vortex-datafusion/src/v2/source.rs +++ b/vortex-datafusion/src/v2/source.rs @@ -116,7 +116,6 @@ use futures::future::try_join_all; use futures::lock::Mutex as AsyncMutex; use futures::stream; use futures::stream::BoxStream; -use parking_lot::Mutex; use tokio::sync::OnceCell; use vortex::array::stream::ArrayStreamAdapter; use vortex::array::stream::ArrayStreamExt; @@ -135,11 +134,9 @@ use vortex::expr::root; use vortex::expr::stats::Precision; use vortex::expr::transform::replace; use vortex::scan::DataSourceRef; -use vortex::scan::DataSourceScanRef; use vortex::scan::PartitionRef; use vortex::scan::PartitionStream; use vortex::scan::ScanRequest; -use vortex::scan::pool::ScanPoolRef; use vortex::session::VortexSession; use vortex_arrow::ArrowArrayStreamExt; use vortex_arrow::ArrowSessionExt; @@ -199,16 +196,17 @@ pub struct VortexDataSourceBuilder { projection: Option>, expression_converter: Arc, output_ordering: Option, - scan_pool: bool, + split_scan: bool, } -/// The environment variable that selects how [`VortexDataSource`] reads its scan: `0` keeps the -/// shared partition stream, anything else (the default) splits or opens the scan. +/// The environment variable that selects how [`VortexDataSource`] reads its scan: `0` reads the +/// scan's shared partition stream, anything else (the default) splits it into one piece per output +/// partition. /// /// It exists to compare the two in one binary, and goes away with the partition stream. pub const SCAN_POOL_ENV: &str = "VORTEX_SCAN_POOL"; -fn scan_pool_from_env() -> bool { +fn split_scan_from_env() -> bool { std::env::var(SCAN_POOL_ENV).map_or(true, |value| value != "0") } @@ -267,10 +265,11 @@ impl VortexDataSourceBuilder { self } - /// Selects whether the scan is split or opened (`true`) or read through its shared partition - /// stream (`false`). Defaults to [`SCAN_POOL_ENV`], read when the builder is created. - pub fn with_scan_pool(mut self, scan_pool: bool) -> Self { - self.scan_pool = scan_pool; + /// Selects whether each output partition reads its own piece of the split scan (`true`) or + /// takes partitions from the scan's shared partition stream (`false`). Defaults to + /// [`SCAN_POOL_ENV`], read when the builder is created. + pub fn with_split_scan(mut self, split_scan: bool) -> Self { + self.split_scan = split_scan; self } @@ -373,7 +372,7 @@ impl VortexDataSourceBuilder { ordered: self.output_ordering.is_some(), preserve_order: false, target_parallelism: get_available_parallelism().unwrap_or(1), - scan_pool: self.scan_pool, + split_scan: self.split_scan, }) } } @@ -388,7 +387,7 @@ impl VortexDataSource { arrow_schema: None, projection: None, output_ordering: None, - scan_pool: scan_pool_from_env(), + split_scan: split_scan_from_env(), } } } @@ -403,26 +402,18 @@ impl VortexDataSource { /// During execution, it builds the final Vortex [`ScanRequest`] from the /// current projection, pushed filters, ordering hints, and row limit. /// -/// Unordered scans expose the requested DataFusion output partitions, which share one lazy scan -/// per execution through [`DataSource::create_sibling_state`]. A scan with a declared global -/// ordering uses one output partition. +/// Unordered scans expose the requested DataFusion output partitions; a scan with a declared +/// global ordering uses one output partition. /// -/// The output partitions read the scan in one of two ways, chosen as DataFusion's own file scans -/// choose whether to steal work. By default the scan is [opened] into a pool and every output -/// partition polls its own worker until it ends; the pool decides how work reaches the workers. -/// When each partition must keep its rows in order, or when -/// `datafusion.execution.enable_file_stream_work_stealing` is off, the scan is instead [split] -/// into one piece per output partition, and partitions beyond the piece count return no rows. -/// A direct [`DataSource::open`] without shared [`OpenArgs`] always splits, since its partition -/// cannot share a pool with the others. Setting [`SCAN_POOL_ENV`] to `0` instead reads the scan's +/// DataFusion runs each output partition on its own, so each one reads its own piece of the scan: +/// output partition `i` of `n` starts the scan, [splits] it into at most `n` pieces, and reads +/// piece `i` with one worker. Partitions share no state, so they behave the same whether they run +/// in one process or several, and partitions beyond the piece count return no rows. Splitting reads +/// metadata only and cuts a scan the same way each time, so every partition sees the same pieces. +/// Setting [`SCAN_POOL_ENV`] to `0` instead has the output partitions take partitions from one /// shared partition stream, for comparison. /// -/// A pool may give up the work a worker had taken when that worker is dropped, so, as with -/// DataFusion's work-stealing file scans, a host drops an output partition early only when it -/// abandons the scan. -/// -/// [opened]: vortex::scan::DataSourceScan::open -/// [split]: vortex::scan::DataSourceScan::split +/// [splits]: vortex::scan::DataSourceScan::split /// /// Use [`crate::VortexSource`] instead when DataFusion should discover and plan /// `.vortex` files on its own. @@ -481,9 +472,10 @@ pub struct VortexDataSource { /// Target Arrow conversion concurrency when only one output partition is exposed. target_parallelism: usize, - /// Whether to split or open the scan rather than read its shared partition stream, which - /// keeps one output partition for a limited scan. - scan_pool: bool, + /// Whether each output partition reads its own piece of the split scan rather than taking + /// partitions from the scan's shared partition stream, which keeps one output partition for a + /// limited scan. + split_scan: bool, } impl fmt::Debug for VortexDataSource { @@ -499,32 +491,13 @@ impl fmt::Debug for VortexDataSource { impl VortexDataSource { fn output_partition_count(&self) -> usize { - if self.ordered || (!self.scan_pool && self.limit.is_some()) { + if self.ordered || (!self.split_scan && self.limit.is_some()) { 1 } else { self.output_partitions } } - /// Whether output partition `i` reads its own piece of a split scan rather than taking work - /// from a pool shared by every output partition. - /// - /// This mirrors when DataFusion's `FileScanConfig` turns off work stealing: an order-sensitive - /// scan must keep each partition's rows in sequence, and a host that runs partitions in - /// isolation disables stealing through `enable_file_stream_work_stealing`. - fn scan_mode(&self, config: &ConfigOptions) -> ScanMode { - if !self.scan_pool { - ScanMode::Partitions - } else if self.ordered - || self.preserve_order - || !config.execution.enable_file_stream_work_stealing - { - ScanMode::Split - } else { - ScanMode::Open - } - } - fn scan_request(&self) -> ScanRequest { ScanRequest { projection: self.projected_projection.clone(), @@ -535,20 +508,81 @@ impl VortexDataSource { } } - fn open_partition( + /// Output partition `partition`, reading its own piece of the split scan. + fn open_piece(&self, partition: usize) -> DFResult { + let pieces = self.output_partition_count(); + if partition >= pieces { + return Err(invalid_partition(partition)); + } + let data_source = Arc::clone(&self.data_source); + let request = self.scan_request(); + let session = self.session.clone(); + let schema = Arc::clone(&self.projected_schema); + let concurrency = self.conversion_concurrency(); + let batches = stream::once(async move { + let scan = data_source.scan(request).await?; + let pieces = NonZeroUsize::new(pieces).unwrap_or(NonZeroUsize::MIN); + // Output partitions beyond the scan's pieces have nothing to read. + let Some(piece) = scan.split(pieces)?.into_iter().nth(partition) else { + return VortexResult::Ok(stream::empty().boxed()); + }; + Ok(piece + .open()? + .worker() + .to_arrow(&session, Some(schema), concurrency)) + }) + .try_flatten() + .boxed(); + self.output_stream(batches, partition) + } + + /// Output partition `partition`, taking partitions from the scan shared by `execution`. + fn open_shared( &self, partition: usize, execution: Arc, ) -> DFResult { - let claimed = execution.claimed.get(partition).ok_or_else(|| { - DataFusionError::Execution(format!("invalid scan output partition {partition}")) - })?; + let claimed = execution + .claimed + .get(partition) + .ok_or_else(|| invalid_partition(partition))?; if claimed.swap(true, Ordering::AcqRel) { return Err(DataFusionError::Execution( "scan output partition already opened; reset the execution plan before replay" .into(), )); } + let data_source = Arc::clone(&self.data_source); + let request = self.scan_request(); + let session = self.session.clone(); + let schema = Arc::clone(&self.projected_schema); + let concurrency = self.conversion_concurrency(); + let ordered = self.ordered; + let batches = stream::once(async move { + let partitions = execution + .partitions + .get_or_init(|| SharedPartitions::start(data_source, request)) + .await + .as_ref() + .map_err(Clone::clone)?; + VortexResult::Ok(Arc::clone(partitions).arrays(ordered).to_arrow( + &session, + Some(schema), + concurrency, + )) + }) + .try_flatten() + .boxed(); + self.output_stream(batches, partition) + } + + /// Applies the limit and leftover projection to an output partition's batches and records its + /// metrics. A zero limit reads nothing. + fn output_stream( + &self, + batches: BoxStream<'static, VortexResult>, + partition: usize, + ) -> DFResult { let metrics = BaselineMetrics::new(&self.metrics, partition); let stream = if self.limit == Some(0) { Box::pin(RecordBatchStreamAdapter::new( @@ -556,40 +590,6 @@ impl VortexDataSource { stream::empty(), )) as SendableRecordBatchStream } else { - let data_source = Arc::clone(&self.data_source); - let request = self.scan_request(); - let session = self.session.clone(); - let schema = Arc::clone(&self.projected_schema); - let concurrency = self.conversion_concurrency(); - let ordered = self.ordered; - let batches = stream::once(async move { - let work = execution - .work - .get_or_init(|| execution.start(data_source, request)) - .await - .as_ref() - .map_err(Clone::clone)?; - let worker = match work { - ScanWork::Partitions(partitions) => { - Some(Arc::clone(partitions).arrays(ordered)) - } - ScanWork::Pool(pool) => Some(Arc::clone(pool).worker()), - ScanWork::Pieces(pieces) => { - let piece = pieces.get(partition).and_then(|piece| piece.lock().take()); - piece - .map(|piece| piece.open()) - .transpose()? - .map(|pool| pool.worker()) - } - }; - // Output partitions beyond the scan's pieces have nothing to read. - VortexResult::Ok(match worker { - Some(worker) => worker.to_arrow(&session, Some(schema), concurrency), - None => stream::empty().boxed(), - }) - }) - .try_flatten() - .boxed(); self.batch_stream(batches, partition)? }; Ok(Box::pin(OutputPartitionStream { @@ -630,8 +630,7 @@ impl VortexDataSource { // With one output partition DataFusion drops its own limit operator once `with_fetch` // accepts the limit, so the fetch must be exact here. With several, the fetch bounds each - // partition and DataFusion keeps a global limit above. An unordered scan shares its limit - // across partitions, but ordered pieces each apply it locally and rely on this trim. + // partition and DataFusion keeps a global limit above. let stream = match limit { Some(limit) => LimitStream::new( Box::pin(RecordBatchStreamAdapter::new(projected_schema, stream)), @@ -661,69 +660,26 @@ impl VortexDataSource { } } -/// The scan shared by every output partition of one execution of the exec. +fn invalid_partition(partition: usize) -> DataFusionError { + DataFusionError::Execution(format!("invalid scan output partition {partition}")) +} + +/// The scan whose partition stream every output partition of one execution shares. /// /// The first output partition polled starts the scan; every other partition reads the same one. struct ScanExecution { - mode: ScanMode, claimed: Vec, - work: OnceCell>, -} - -/// How the output partitions of one execution read the scan. -#[derive(Clone, Copy, PartialEq, Eq)] -enum ScanMode { - /// Every output partition takes partitions from the scan's one shared partition stream. - Partitions, - /// Every output partition polls its own worker of the opened scan. - Open, - /// Output partition `i` reads piece `i` of the split scan. - Split, -} - -enum ScanWork { - /// Every output partition takes partitions from this shared stream. - Partitions(Arc), - /// Every output partition polls its own worker of this pool. - Pool(ScanPoolRef), - /// Output partition `i` takes piece `i`, if there is one. - Pieces(Vec>>), + partitions: OnceCell>>, } impl ScanExecution { - fn new(output_partitions: usize, mode: ScanMode) -> Self { + fn new(output_partitions: usize) -> Self { Self { - mode, claimed: (0..output_partitions) .map(|_| AtomicBool::new(false)) .collect(), - work: OnceCell::new(), - } - } - - async fn start( - &self, - data_source: DataSourceRef, - request: ScanRequest, - ) -> VortexResult { - let scan = data_source.scan(request).await?; - match self.mode { - ScanMode::Partitions => { - return Ok(ScanWork::Partitions(Arc::new(SharedPartitions { - dtype: scan.dtype().clone(), - partitions: AsyncMutex::new(Some(scan.partitions())), - }))); - } - ScanMode::Open => return Ok(ScanWork::Pool(scan.open()?)), - ScanMode::Split => {} + partitions: OnceCell::new(), } - let pieces = NonZeroUsize::new(self.claimed.len()).unwrap_or(NonZeroUsize::MIN); - Ok(ScanWork::Pieces( - scan.split(pieces)? - .into_iter() - .map(|piece| Mutex::new(Some(piece))) - .collect(), - )) } } @@ -737,6 +693,14 @@ struct SharedPartitions { const SCAN_PARTITION_READ_AHEAD: usize = 2; impl SharedPartitions { + async fn start(data_source: DataSourceRef, request: ScanRequest) -> VortexResult> { + let scan = data_source.scan(request).await?; + Ok(Arc::new(Self { + dtype: scan.dtype().clone(), + partitions: AsyncMutex::new(Some(scan.partitions())), + })) + } + /// Takes the next partition, dropping the stream once it ends. async fn next(&self) -> Option> { let mut partitions = self.partitions.lock().await; @@ -802,28 +766,24 @@ impl DataSource for VortexDataSource { partition: usize, _context: Arc, ) -> DFResult { - // Without sibling state this partition cannot share work with the others, so it scans - // on its own and reads only its piece. - let mode = if self.scan_pool { - ScanMode::Split - } else if self.output_partition_count() == 1 { - ScanMode::Partitions - } else { + if self.split_scan { + return self.open_piece(partition); + } + // Several partitions can share the partition stream only through sibling state. + if self.output_partition_count() > 1 { return Err(DataFusionError::Execution( "multiple scan output partitions require sibling execution state".into(), )); - }; - self.open_partition( - partition, - Arc::new(ScanExecution::new(self.output_partition_count(), mode)), - ) + } + self.open_shared(partition, Arc::new(ScanExecution::new(1))) } - fn create_sibling_state(&self, config: &ConfigOptions) -> Option> { - Some(Arc::new(ScanExecution::new( - self.output_partition_count(), - self.scan_mode(config), - ))) + fn create_sibling_state(&self, _config: &ConfigOptions) -> Option> { + // Split pieces need no state shared between output partitions. + (!self.split_scan).then(|| { + Arc::new(ScanExecution::new(self.output_partition_count())) + as Arc + }) } fn open_with_args(&self, args: OpenArgs) -> DFResult { @@ -832,7 +792,7 @@ impl DataSource for VortexDataSource { let execution = state.downcast::().map_err(|_| { DataFusionError::Execution("incompatible scan execution state".into()) })?; - self.open_partition(args.partition, execution) + self.open_shared(args.partition, execution) } None => self.open(args.partition, args.context), } @@ -918,7 +878,7 @@ impl DataSource for VortexDataSource { // bounds each output partition and DataFusion keeps a global limit above several. if limit.is_some() && (!self.dynamic_filters.is_empty() - || (!self.scan_pool && self.output_partition_count() > 1)) + || (!self.split_scan && self.output_partition_count() > 1)) { return None; } @@ -933,7 +893,7 @@ impl DataSource for VortexDataSource { } fn with_preserve_order(&self, preserve_order: bool) -> Option> { - if !self.scan_pool { + if !self.split_scan { return None; } let mut this = self.clone(); @@ -1434,8 +1394,10 @@ mod tests { Ok(()) } + /// Each output partition scans on its own, lazily, and reads only its piece; partitions beyond + /// the piece count return no rows. #[tokio::test] - async fn output_partitions_share_one_lazy_scan_and_reset_reopens_it() -> anyhow::Result<()> { + async fn each_output_partition_reads_its_own_piece() -> anyhow::Result<()> { let scans = Arc::new(AtomicUsize::new(0)); let data_source: DataSourceRef = Arc::new(TestDataSource { dtype: test_dtype(), @@ -1443,7 +1405,7 @@ mod tests { scans: Arc::clone(&scans), }); let source = VortexDataSource::builder(data_source, VortexSession::default()) - .with_scan_pool(true) + .with_split_scan(true) .build() .await?; for requested in [0, 1, 257] { @@ -1465,47 +1427,29 @@ mod tests { .with_fetch(Some(1)) .expect("fetch bounds each partition"); assert_eq!(fetched.output_partitioning().partition_count(), 4); + let plan = Arc::new(DataSourceExec::new(Arc::clone(&source))) as Arc; - assert_eq!(scans.load(Ordering::Relaxed), 0); let context = Arc::new(TaskContext::default()); - let values = |batches: Vec| { - let mut values = batches - .iter() - .flat_map(|batch| { - batch - .column(0) - .as_primitive::() - .values() - .iter() - .copied() - }) - .collect::>(); - values.sort_unstable(); - values - }; + let streams = (0..4) + .map(|partition| plan.execute(partition, Arc::clone(&context))) + .collect::>>()?; + assert_eq!(scans.load(Ordering::Relaxed), 0); + let mut partitions = Vec::new(); + for stream in streams { + let batches: Vec = stream.try_collect().await?; + partitions.push(partition_values(&batches)); + } + assert_eq!(partitions, [vec![0, 1], vec![100, 101], vec![], vec![]]); + assert_eq!(scans.load(Ordering::Relaxed), 4); + assert_eq!(plan.metrics().expect("scan metrics").output_rows(), Some(4)); + assert!(plan.execute(4, Arc::clone(&context)).is_err()); + + // A partition holds no state, so it can be read again, here without sibling state. + let direct = source.open(1, context)?; assert_eq!( - values(collect(Arc::clone(&plan), Arc::clone(&context)).await?), - [0, 1, 100, 101] + partition_values(&direct.try_collect::>().await?), + [100, 101] ); - assert_eq!(scans.load(Ordering::Relaxed), 1); - assert_eq!(plan.metrics().expect("scan metrics").output_rows(), Some(4)); - assert!(plan.execute(0, Arc::clone(&context)).is_err()); - let reset = Arc::clone(&plan).reset_state()?; - let independent = - Arc::new(DataSourceExec::new(Arc::clone(&source))) as Arc; - let (reset, independent) = futures::try_join!( - collect(reset, Arc::clone(&context)), - collect(independent, context) - )?; - assert_eq!(values(reset), [0, 1, 100, 101]); - assert_eq!(values(independent), [0, 1, 100, 101]); - assert_eq!(scans.load(Ordering::Relaxed), 3); - - // Without sibling state a partition scans on its own and reads only its piece. - let direct = |partition| source.open(partition, Arc::new(TaskContext::default())); - assert_eq!(values(direct(0)?.try_collect().await?), [0, 1]); - assert_eq!(values(direct(1)?.try_collect().await?), [100, 101]); - assert!(values(direct(2)?.try_collect().await?).is_empty()); Ok(()) } @@ -1545,17 +1489,17 @@ mod tests { .collect() } - /// With the pool off, output partitions share the scan's partition stream as on develop: a + /// Without the split, output partitions share the scan's partition stream: a /// fetch keeps one partition, and direct opens need a single partition. #[tokio::test] - async fn without_scan_pool_partitions_share_the_partition_stream() -> anyhow::Result<()> { + async fn without_split_scan_partitions_share_the_partition_stream() -> anyhow::Result<()> { let data_source: DataSourceRef = Arc::new(TestDataSource { dtype: test_dtype(), polls: Arc::default(), scans: Arc::default(), }); let source = VortexDataSource::builder(data_source, VortexSession::default()) - .with_scan_pool(false) + .with_split_scan(false) .build() .await? .repartitioned(4, 0, None)? @@ -1571,48 +1515,14 @@ mod tests { Ok(()) } - /// With work stealing off, each output partition reads its own piece in order, and - /// partitions beyond the piece count return no rows. - #[tokio::test] - async fn without_work_stealing_partitions_read_split_pieces() -> anyhow::Result<()> { - let data_source: DataSourceRef = Arc::new(TestDataSource { - dtype: test_dtype(), - polls: Arc::default(), - scans: Arc::default(), - }); - let source = VortexDataSource::builder(data_source, VortexSession::default()) - .with_scan_pool(true) - .build() - .await? - .repartitioned(4, 0, None)? - .expect("repartitioning supported"); - let plan = Arc::new(DataSourceExec::new(source)) as Arc; - let mut config = datafusion::prelude::SessionConfig::new(); - config - .options_mut() - .execution - .enable_file_stream_work_stealing = false; - let context = Arc::new(TaskContext::default().with_session_config(config)); - - let mut partitions = Vec::new(); - for partition in 0..4 { - let batches: Vec = plan - .execute(partition, Arc::clone(&context))? - .try_collect() - .await?; - partitions.push(partition_values(&batches)); - } - assert_eq!(partitions, [vec![0, 1], vec![100, 101], vec![], vec![]]); - Ok(()) - } - - /// A fetch bounds each of several output partitions, and the pooled scan shares its limit. + /// A fetch bounds each of several output partitions. A limited scan cannot be cut, so its + /// one piece goes to the first partition. #[tokio::test] async fn fetch_bounds_each_of_several_partitions() -> anyhow::Result<()> { let (data_source, session, schema) = split_file_source().await?; let source = VortexDataSource::builder(data_source, session) .with_arrow_schema(schema) - .with_scan_pool(true) + .with_split_scan(true) .build() .await? .repartitioned(4, 0, None)? From 39b4ebec4d1cb5b58d2a807f5f0d18fa8d9240fa Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 14:05:17 -0500 Subject: [PATCH 36/80] 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 40d7b336aa58403b989d9d08223ad310c198ac95 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 14:05:31 -0500 Subject: [PATCH 37/80] Drop dtype from the split pool Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-layout/src/scan/pool.rs | 4 ---- 1 file changed, 4 deletions(-) diff --git a/vortex-layout/src/scan/pool.rs b/vortex-layout/src/scan/pool.rs index dd0ba0e9fed..64e09524dba 100644 --- a/vortex-layout/src/scan/pool.rs +++ b/vortex-layout/src/scan/pool.rs @@ -68,10 +68,6 @@ impl SplitPool { } impl ScanPool for SplitPool { - fn dtype(&self) -> &DType { - &self.dtype - } - fn worker(self: Arc) -> SendableArrayStream { let dtype = self.dtype.clone(); let handle = self.handle.clone(); From 6697509ac89f25894d77de1be3a7532abf7ace5a Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 14:09:31 -0500 Subject: [PATCH 38/80] 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 17ddf3427570b5ea7a0983fc965459ad396e513f Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 14:13:36 -0500 Subject: [PATCH 39/80] Cut multi-file scans inside files when there are fewer files than pieces Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-layout/src/scan/multi.rs | 440 +++++++++++++++++++++++++++++--- 1 file changed, 406 insertions(+), 34 deletions(-) diff --git a/vortex-layout/src/scan/multi.rs b/vortex-layout/src/scan/multi.rs index 5d5b605bbe6..6c87fa662ba 100644 --- a/vortex-layout/src/scan/multi.rs +++ b/vortex-layout/src/scan/multi.rs @@ -64,6 +64,7 @@ use vortex_session::VortexSession; use vortex_utils::parallelism::get_available_parallelism; use crate::LayoutReaderRef; +use crate::scan::layout::group_contiguous; use crate::scan::limit::RowLimit; use crate::scan::scan_builder::ScanBuilder; @@ -296,15 +297,23 @@ impl DataSource for MultiLayoutDataSource { async fn scan(&self, scan_request: ScanRequest) -> VortexResult { let mut ready = VecDeque::new(); let mut deferred = VecDeque::new(); + let mut ready_sizes = VecDeque::new(); + let mut deferred_sizes = VecDeque::new(); for child in self.children.iter() { match child { - MultiLayoutChild::Opened { reader, .. } => ready.push_back(Arc::clone(reader)), - MultiLayoutChild::Deferred { factory, .. } => { - deferred.push_back(Arc::clone(factory)) + MultiLayoutChild::Opened { reader, byte_size } => { + ready.push_back(Arc::clone(reader)); + ready_sizes.push_back(*byte_size); + } + MultiLayoutChild::Deferred { factory, byte_size } => { + deferred.push_back(Arc::clone(factory)); + deferred_sizes.push_back(*byte_size); } } } + // The scan reads its opened files first, so its sizes follow that order too. + let byte_sizes = ready_sizes.into_iter().chain(deferred_sizes).collect(); let request = BoundScanRequest::try_new(scan_request, &self.dtype)?; let dtype = request.projection.dtype().clone(); @@ -324,6 +333,8 @@ impl DataSource for MultiLayoutDataSource { row_limit, ready, deferred, + byte_sizes, + fraction: None, handle: self.session.handle(), concurrency: self.concurrency, })) @@ -386,16 +397,63 @@ struct MultiLayoutScan { row_limit: Option, ready: VecDeque, deferred: VecDeque>, + /// The on-storage size of each file, if known: the `ready` files, then the `deferred` ones. + byte_sizes: VecDeque>, + /// The part of its one unopened file that a piece of a split reads; `None` reads every file + /// whole. See [`FileFraction`]. + fraction: Option, handle: vortex_io::runtime::Handle, concurrency: usize, } +/// Piece `index` of `count` equal parts of a file's rows, for a piece cut from a file that was +/// not opened when the scan was split. +/// +/// The rows are resolved once the file is opened. The part's row range is computed from the +/// file's row count, and then each of the file's splits goes to the part whose range holds the +/// split's first row. So the parts of a file read each of its splits exactly once, whole. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct FileFraction { + index: u64, + count: u64, +} + +impl FileFraction { + /// The rows of `rows` that this part reads, given the start rows of the file's splits within + /// `rows`, in order. + fn resolve(self, rows: Range, split_starts: impl IntoIterator) -> Range { + let len = u128::from(rows.end - rows.start); + let at = |part: u64| { + rows.start + + u64::try_from(len * u128::from(part) / u128::from(self.count)).unwrap_or(u64::MAX) + }; + let (from, to) = (at(self.index), at(self.index + 1)); + let mut start = None; + for split in split_starts { + if split >= to { + return start.map_or(to..to, |start| start..split); + } + if split >= from && start.is_none() { + start = Some(split); + } + } + start.map_or(rows.end..rows.end, |start| start..rows.end) + } +} + impl DataSourceScan for MultiLayoutScan { fn dtype(&self) -> &DType { &self.dtype } - /// Cuts the scan into pieces of whole files, in file order, without opening any. + /// Cuts the scan into at most `n` pieces, in file order, reading metadata only. + /// + /// With at least `n` files, each piece is a run of whole files. The runs balance the files' + /// byte sizes when every size is known, and their counts otherwise. With fewer files, each + /// file gets a share of the `n` pieces in proportion to its size, at least one, and no piece + /// holds parts of two files. An opened file is cut at its natural split boundaries. A file + /// that is not opened is cut into equal fractions of its rows, which are resolved to whole + /// splits when the piece opens it; see [`FileFraction`]. /// /// A scan with a limit stays whole, because the limit is one budget across all its files, /// and so does one that selects partitions, because partition indices count from its first @@ -403,7 +461,8 @@ impl DataSourceScan for MultiLayoutScan { fn split(self: Box, n: NonZeroUsize) -> VortexResult> { let files = self.ready.len() + self.deferred.len(); if n.get() == 1 - || files <= 1 + || files == 0 + || self.fraction.is_some() || self.request.limit.is_some() || self.request.partition_range.is_some() || !matches!(self.request.partition_selection, Selection::All) @@ -418,28 +477,127 @@ impl DataSourceScan for MultiLayoutScan { row_limit, mut ready, mut deferred, + mut byte_sizes, + fraction: _, handle, concurrency, } = *self; - let pieces = n.get().min(files); - Ok((0..pieces) - .map(|piece| { - // Piece `piece` takes files `piece * files / pieces` up to the next piece's start. - let take = (piece + 1) * files / pieces - piece * files / pieces; - let from_ready = take.min(ready.len()); - Box::new(MultiLayoutScan { - session: session.clone(), - source_dtype: source_dtype.clone(), - dtype: dtype.clone(), - request: request.clone(), - row_limit: row_limit.clone(), - ready: ready.drain(..from_ready).collect(), - deferred: deferred.drain(..take - from_ready).collect(), - handle: handle.clone(), - concurrency, - }) as DataSourceScanRef - }) - .collect()) + + let weights: Vec = byte_sizes + .iter() + .map(|size| size.map(|size| u128::from(size.max(1)))) + .collect::>() + .unwrap_or_else(|| vec![1; files]); + let total = weights.iter().sum::(); + let n = n.get(); + + let piece = |ready: VecDeque, + deferred: VecDeque>, + byte_sizes: VecDeque>, + fraction: Option, + request: BoundScanRequest| { + Box::new(MultiLayoutScan { + session: session.clone(), + source_dtype: source_dtype.clone(), + dtype: dtype.clone(), + request, + row_limit: row_limit.clone(), + ready, + deferred, + byte_sizes, + fraction, + handle: handle.clone(), + concurrency, + }) as DataSourceScanRef + }; + + if files >= n { + // Each file joins the piece in which its first byte falls. + let mut runs: Vec = Vec::with_capacity(n); + let mut last_group = None; + let mut before = 0u128; + for weight in &weights { + let group = before * n as u128 / total; + before += weight; + match runs.last_mut() { + Some(run) if last_group == Some(group) => *run += 1, + _ => runs.push(1), + } + last_group = Some(group); + } + return Ok(runs + .into_iter() + .map(|take| { + let from_ready = take.min(ready.len()); + piece( + ready.drain(..from_ready).collect(), + deferred.drain(..take - from_ready).collect(), + byte_sizes.drain(..take).collect(), + None, + request.clone(), + ) + }) + .collect()); + } + + let spare = (n - files) as u128; + let shares = weights + .iter() + .map(|weight| 1 + u64::try_from(weight * spare / total).unwrap_or(0)); + let mut pieces = Vec::with_capacity(n); + let mut sizes = byte_sizes.into_iter(); + let ready_len = ready.len(); + for (file, share) in shares.enumerate() { + let size = sizes.next().flatten(); + if file < ready_len { + let Some(reader) = ready.pop_front() else { + break; + }; + let cuts = (share > 1) + .then(|| opened_file_cuts(&session, &reader, &request, share)) + .flatten(); + match cuts { + Some(cuts) => { + for rows in cuts { + let mut request = request.clone(); + request.row_range = Some(rows); + pieces.push(piece( + VecDeque::from([Arc::clone(&reader)]), + VecDeque::new(), + VecDeque::from([size]), + None, + request, + )); + } + } + None => pieces.push(piece( + VecDeque::from([reader]), + VecDeque::new(), + VecDeque::from([size]), + None, + request.clone(), + )), + } + } else { + let Some(factory) = deferred.pop_front() else { + break; + }; + for index in 0..share { + let fraction = (share > 1).then_some(FileFraction { + index, + count: share, + }); + pieces.push(piece( + VecDeque::new(), + VecDeque::from([Arc::clone(&factory)]), + VecDeque::from([size]), + fraction, + request.clone(), + )); + } + } + } + Ok(pieces) } /// Opens the scan into its partition pipeline, which opens up to `concurrency` files ahead @@ -466,6 +624,8 @@ impl DataSourceScan for MultiLayoutScan { row_limit, ready, deferred, + byte_sizes: _, + fraction, handle, concurrency, } = *self; @@ -525,6 +685,7 @@ impl DataSourceScan for MultiLayoutScan { &source_dtype, request.clone(), row_limit.clone(), + fraction, ), Err(e) => stream::once(async move { Err(e) }).boxed(), }) @@ -532,6 +693,66 @@ impl DataSourceScan for MultiLayoutScan { } } +/// The row ranges of `reader`'s natural splits within `rows` that `request` reads, or `None` if +/// they cannot be planned, such as when the request does not bind to the file. Reads metadata +/// only. +fn file_split_ranges( + session: &VortexSession, + reader: &LayoutReaderRef, + request: &BoundScanRequest, + rows: Range, +) -> Option>> { + let filter = request.filter.clone().ok()?; + let scan = ScanBuilder::new(session.clone(), Arc::clone(reader)) + .with_selection(request.selection.clone()) + .with_projection(request.projection.clone()) + .with_some_filter(filter) + .prepare() + .ok()?; + Some(scan.split_ranges(Some(rows))) +} + +/// Cuts the rows of an opened file that `request` reads into at most `share` ranges that cover +/// them in order, at the file's natural split boundaries. `None` if the file cannot be cut. +fn opened_file_cuts( + session: &VortexSession, + reader: &LayoutReaderRef, + request: &BoundScanRequest, + share: u64, +) -> Option>> { + let row_count = reader.row_count(); + let rows = request.row_range.clone().map_or(0..row_count, |rows| { + rows.start.min(row_count)..rows.end.min(row_count) + }); + let share = NonZeroUsize::new(usize::try_from(share).ok()?)?; + let splits = file_split_ranges(session, reader, request, rows.clone())?; + let groups = group_contiguous(splits, share); + if groups.len() <= 1 { + return None; + } + let last = groups.len() - 1; + Some( + groups + .iter() + .enumerate() + .filter_map(|(i, group)| { + // The cuts start and end where `rows` does, so no row is lost at either edge. + let start = if i == 0 { + rows.start + } else { + group.first()?.start + }; + let end = if i == last { + rows.end + } else { + group.last()?.end + }; + Some(start..end) + }) + .collect(), + ) +} + /// Generates a partition stream for a single layout reader. /// /// Checks file-level pruning first (via `pruning_evaluation`). If the filter proves no rows @@ -544,6 +765,7 @@ fn reader_partition( source_dtype: &DType, request: BoundScanRequest, row_limit: Option, + fraction: Option, ) -> PartitionStream { if reader.dtype() != source_dtype { let error = vortex_err!( @@ -555,7 +777,20 @@ fn reader_partition( } let row_count = reader.row_count(); - let row_range = request.row_range.clone().unwrap_or(0..row_count); + let mut row_range = request.row_range.clone().unwrap_or(0..row_count); + if let Some(fraction) = fraction { + let rows = row_range.start.min(row_count)..row_range.end.min(row_count); + // A file whose splits cannot be planned is one split, which the first part reads. + let split_starts = file_split_ranges(&session, &reader, &request, rows.clone()) + .map_or_else( + || vec![rows.start], + |splits| splits.into_iter().map(|s| s.start).collect(), + ); + row_range = fraction.resolve(rows, split_starts); + if row_range.is_empty() { + return stream::empty().boxed(); + } + } let partition_idx_u64: u64 = partition_idx as u64; if let Some(range) = &request.partition_range @@ -708,7 +943,7 @@ mod tests { #[async_trait] impl LayoutReaderFactory for NeverOpened { async fn open(&self) -> VortexResult> { - unreachable!("byte_size must not open readers") + unreachable!("byte_size and split must not open readers") } } @@ -796,7 +1031,39 @@ mod tests { Ok(()) } - /// Splitting hands out whole files in file order, without opening any. + /// Reads every partition of `piece`, in order. + fn piece_values( + runtime: &SingleThreadRuntime, + piece: DataSourceScanRef, + ) -> VortexResult> { + let mut values = Vec::new(); + for partition in runtime.block_on(piece.partitions().try_collect::>())? { + values.extend(collect_scan_values( + runtime.block_on_stream(partition.execute()?), + )?); + } + Ok(values) + } + + /// A source of files that are never opened, whose scans run on `runtime`. + fn unopened_files( + runtime: &SingleThreadRuntime, + byte_sizes: Vec>, + ) -> MultiLayoutDataSource { + let factories = byte_sizes + .iter() + .map(|_| Arc::new(NeverOpened) as Arc) + .collect(); + MultiLayoutDataSource::new_deferred( + DType::Bool(Nullability::NonNullable), + factories, + byte_sizes, + &session_with_handle(runtime.handle()), + ) + } + + /// With at least `n` files, splitting hands out runs of whole files in file order, without + /// opening any. #[test] fn split_groups_whole_files() -> VortexResult<()> { let runtime = SingleThreadRuntime::default(); @@ -820,24 +1087,129 @@ mod tests { assert_eq!( files, [ - Precision::exact(1usize), Precision::inexact(2usize), - Precision::inexact(2usize) + Precision::inexact(2usize), + Precision::inexact(1usize) ] ); let mut values = Vec::new(); for piece in pieces { - for partition in runtime.block_on(piece.partitions().try_collect::>())? { - values.extend(collect_scan_values( - runtime.block_on_stream(partition.execute()?), - )?); - } + values.extend(piece_values(&runtime, piece)?); } assert_eq!(values, [0, 1, 10, 11, 20, 21, 30, 31, 40, 41]); Ok(()) } + /// Known file sizes balance the runs by bytes rather than by file count. `NeverOpened` + /// panics if splitting opens a file. + #[test] + fn split_balances_whole_files_by_size() -> VortexResult<()> { + let runtime = SingleThreadRuntime::default(); + let scan = runtime.block_on( + unopened_files(&runtime, vec![Some(80), Some(10), Some(10)]) + .scan(ScanRequest::default()), + )?; + let files: Vec<_> = scan + .split(NonZeroUsize::try_from(2)?)? + .iter() + .map(|piece| piece.partition_count()) + .collect(); + assert_eq!( + files, + [Precision::inexact(1usize), Precision::inexact(2usize)] + ); + Ok(()) + } + + /// With fewer files than `n`, each file gets a share of the pieces by size, still without + /// opening any. + #[test] + fn split_shares_pieces_among_unopened_files_by_size() -> VortexResult<()> { + let runtime = SingleThreadRuntime::default(); + let scan = runtime.block_on( + unopened_files(&runtime, vec![Some(30), Some(10)]).scan(ScanRequest::default()), + )?; + // Two spare pieces: the larger file takes one of them, the smaller none. + assert_eq!(scan.split(NonZeroUsize::try_from(4)?)?.len(), 3); + Ok(()) + } + + /// An opened file is cut at its split boundaries. + #[test] + fn split_cuts_an_opened_file_at_splits() -> VortexResult<()> { + let runtime = SingleThreadRuntime::default(); + let session = session_with_handle(runtime.handle()); + let reader: LayoutReaderRef = Arc::new(TestLayoutReader::new(8).with_split_size(2)); + let source = MultiLayoutDataSource::new_with_first(reader, vec![], vec![], &session); + + let scan = runtime.block_on(source.scan(ScanRequest { + ordered: true, + ..Default::default() + }))?; + let pieces = scan + .split(NonZeroUsize::try_from(4)?)? + .into_iter() + .map(|piece| piece_values(&runtime, piece)) + .collect::>>()?; + assert_eq!(pieces, [vec![0, 1], vec![2, 3], vec![4, 5], vec![6, 7]]); + Ok(()) + } + + /// An unopened file is cut into fractions of its rows, resolved to whole splits once it is + /// opened. The fractions of this file meet at row 4, inside the split of rows 3..6, which + /// the first fraction reads whole because the split starts in it. + #[test] + fn split_reads_each_split_of_an_unopened_file_once() -> VortexResult<()> { + let runtime = SingleThreadRuntime::default(); + let session = session_with_handle(runtime.handle()); + let first: LayoutReaderRef = Arc::new(TestLayoutReader::new(2)); + let deferred = Arc::new(StaticReaderFactory { + reader: Arc::new(TestLayoutReader::new(9).with_split_size(3).with_base(100)), + }) as Arc; + let source = MultiLayoutDataSource::new_with_first(first, vec![deferred], vec![], &session); + + let scan = runtime.block_on(source.scan(ScanRequest { + ordered: true, + ..Default::default() + }))?; + let pieces = scan + .split(NonZeroUsize::try_from(4)?)? + .into_iter() + .map(|piece| piece_values(&runtime, piece)) + .collect::>>()?; + // The opened file has one split, so it stays one piece of the two it was given. + assert_eq!( + pieces, + [ + vec![0, 1], + vec![100, 101, 102, 103, 104, 105], + vec![106, 107, 108] + ] + ); + Ok(()) + } + + /// Each split goes to the fraction whose rows hold the split's first row, and a fraction in + /// which no split starts reads nothing. + #[rstest] + #[case::boundary_inside_a_split(0..9, vec![0, 3, 6], 2, vec![0..6, 6..9])] + #[case::fraction_without_a_split(0..9, vec![0, 6], 3, vec![0..6, 6..6, 6..9])] + #[case::one_split(10..20, vec![10], 2, vec![10..20, 20..20])] + fn file_fraction_resolves_to_whole_splits( + #[case] rows: Range, + #[case] split_starts: Vec, + #[case] count: u64, + #[case] expected: Vec>, + ) { + let resolved: Vec<_> = (0..count) + .map(|index| { + FileFraction { index, count }.resolve(rows.clone(), split_starts.iter().copied()) + }) + .collect(); + assert_eq!(resolved, expected); + } + /// Scans 64 one-row splits, returning the rows and the most splits read at once. fn scan_with_split_concurrency( split_concurrency: Option, From 4f3b62b6df5c6ba10ddb657db972789a9f79a509 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 14:19:51 -0500 Subject: [PATCH 40/80] Split each VortexTable execution once and share its pieces An unordered source may have the pieces of one split share a queue of work, so the pieces must come from a single split call. The first output partition polled scans and splits through the execution's sibling state, and output partition i reads piece i. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-datafusion/src/v2/source.rs | 162 +++++++++++++++-------------- 1 file changed, 84 insertions(+), 78 deletions(-) diff --git a/vortex-datafusion/src/v2/source.rs b/vortex-datafusion/src/v2/source.rs index 95c114ec652..669a1cb0c5c 100644 --- a/vortex-datafusion/src/v2/source.rs +++ b/vortex-datafusion/src/v2/source.rs @@ -134,6 +134,7 @@ use vortex::expr::root; use vortex::expr::stats::Precision; use vortex::expr::transform::replace; use vortex::scan::DataSourceRef; +use vortex::scan::DataSourceScanRef; use vortex::scan::PartitionRef; use vortex::scan::PartitionStream; use vortex::scan::ScanRequest; @@ -405,13 +406,13 @@ impl VortexDataSource { /// Unordered scans expose the requested DataFusion output partitions; a scan with a declared /// global ordering uses one output partition. /// -/// DataFusion runs each output partition on its own, so each one reads its own piece of the scan: -/// output partition `i` of `n` starts the scan, [splits] it into at most `n` pieces, and reads -/// piece `i` with one worker. Partitions share no state, so they behave the same whether they run -/// in one process or several, and partitions beyond the piece count return no rows. Splitting reads -/// metadata only and cuts a scan the same way each time, so every partition sees the same pieces. -/// Setting [`SCAN_POOL_ENV`] to `0` instead has the output partitions take partitions from one -/// shared partition stream, for comparison. +/// Each execution [splits] the scan once into one piece per output partition, through +/// [`DataSource::create_sibling_state`]: the first output partition polled starts the scan and +/// splits it, and output partition `i` reads piece `i`. Partitions beyond the piece count return +/// no rows. The source decides what the pieces are: the pieces of an unordered scan may share one +/// queue of work, so partitions that finish early keep reading, while an ordered scan's pieces are +/// fixed and in order. Setting [`SCAN_POOL_ENV`] to `0` instead has the output partitions take +/// partitions from one shared partition stream, for comparison. /// /// [splits]: vortex::scan::DataSourceScan::split /// @@ -508,36 +509,8 @@ impl VortexDataSource { } } - /// Output partition `partition`, reading its own piece of the split scan. - fn open_piece(&self, partition: usize) -> DFResult { - let pieces = self.output_partition_count(); - if partition >= pieces { - return Err(invalid_partition(partition)); - } - let data_source = Arc::clone(&self.data_source); - let request = self.scan_request(); - let session = self.session.clone(); - let schema = Arc::clone(&self.projected_schema); - let concurrency = self.conversion_concurrency(); - let batches = stream::once(async move { - let scan = data_source.scan(request).await?; - let pieces = NonZeroUsize::new(pieces).unwrap_or(NonZeroUsize::MIN); - // Output partitions beyond the scan's pieces have nothing to read. - let Some(piece) = scan.split(pieces)?.into_iter().nth(partition) else { - return VortexResult::Ok(stream::empty().boxed()); - }; - Ok(piece - .open()? - .worker() - .to_arrow(&session, Some(schema), concurrency)) - }) - .try_flatten() - .boxed(); - self.output_stream(batches, partition) - } - - /// Output partition `partition`, taking partitions from the scan shared by `execution`. - fn open_shared( + /// Output partition `partition` of the execution `execution`. + fn open_partition( &self, partition: usize, execution: Arc, @@ -559,17 +532,27 @@ impl VortexDataSource { let concurrency = self.conversion_concurrency(); let ordered = self.ordered; let batches = stream::once(async move { - let partitions = execution - .partitions - .get_or_init(|| SharedPartitions::start(data_source, request)) + let work = execution + .work + .get_or_init(|| execution.start(data_source, request)) .await .as_ref() .map_err(Clone::clone)?; - VortexResult::Ok(Arc::clone(partitions).arrays(ordered).to_arrow( - &session, - Some(schema), - concurrency, - )) + let arrays = match work { + ScanWork::Partitions(partitions) => Arc::clone(partitions).arrays(ordered), + ScanWork::Pieces(pieces) => { + let piece = match pieces.get(partition) { + Some(piece) => piece.lock().await.take(), + None => None, + }; + // Output partitions beyond the scan's pieces have nothing to read. + let Some(piece) = piece else { + return VortexResult::Ok(stream::empty().boxed()); + }; + piece.open()?.worker() + } + }; + Ok(arrays.to_arrow(&session, Some(schema), concurrency)) }) .try_flatten() .boxed(); @@ -664,23 +647,55 @@ fn invalid_partition(partition: usize) -> DataFusionError { DataFusionError::Execution(format!("invalid scan output partition {partition}")) } -/// The scan whose partition stream every output partition of one execution shares. +/// The scan that every output partition of one execution reads. /// /// The first output partition polled starts the scan; every other partition reads the same one. +/// The pieces of a split must come from one call to `split`: an unordered source may have its +/// pieces share one queue of work, so pieces from separate calls would each read every row. struct ScanExecution { + split: bool, claimed: Vec, - partitions: OnceCell>>, + work: OnceCell>, +} + +enum ScanWork { + /// Every output partition takes partitions from this shared stream. + Partitions(Arc), + /// Output partition `i` takes piece `i`, if there is one. + Pieces(Vec>>), } impl ScanExecution { - fn new(output_partitions: usize) -> Self { + fn new(output_partitions: usize, split: bool) -> Self { Self { + split, claimed: (0..output_partitions) .map(|_| AtomicBool::new(false)) .collect(), - partitions: OnceCell::new(), + work: OnceCell::new(), } } + + async fn start( + &self, + data_source: DataSourceRef, + request: ScanRequest, + ) -> VortexResult { + let scan = data_source.scan(request).await?; + if !self.split { + return Ok(ScanWork::Partitions(Arc::new(SharedPartitions { + dtype: scan.dtype().clone(), + partitions: AsyncMutex::new(Some(scan.partitions())), + }))); + } + let pieces = NonZeroUsize::new(self.claimed.len()).unwrap_or(NonZeroUsize::MIN); + Ok(ScanWork::Pieces( + scan.split(pieces)? + .into_iter() + .map(|piece| AsyncMutex::new(Some(piece))) + .collect(), + )) + } } /// Scan API partitions shared by every output partition, each taking the next one it needs. @@ -693,14 +708,6 @@ struct SharedPartitions { const SCAN_PARTITION_READ_AHEAD: usize = 2; impl SharedPartitions { - async fn start(data_source: DataSourceRef, request: ScanRequest) -> VortexResult> { - let scan = data_source.scan(request).await?; - Ok(Arc::new(Self { - dtype: scan.dtype().clone(), - partitions: AsyncMutex::new(Some(scan.partitions())), - })) - } - /// Takes the next partition, dropping the stream once it ends. async fn next(&self) -> Option> { let mut partitions = self.partitions.lock().await; @@ -766,24 +773,20 @@ impl DataSource for VortexDataSource { partition: usize, _context: Arc, ) -> DFResult { - if self.split_scan { - return self.open_piece(partition); - } - // Several partitions can share the partition stream only through sibling state. + // Several partitions read one scan only through sibling state. if self.output_partition_count() > 1 { return Err(DataFusionError::Execution( "multiple scan output partitions require sibling execution state".into(), )); } - self.open_shared(partition, Arc::new(ScanExecution::new(1))) + self.open_partition(partition, Arc::new(ScanExecution::new(1, self.split_scan))) } fn create_sibling_state(&self, _config: &ConfigOptions) -> Option> { - // Split pieces need no state shared between output partitions. - (!self.split_scan).then(|| { - Arc::new(ScanExecution::new(self.output_partition_count())) - as Arc - }) + Some(Arc::new(ScanExecution::new( + self.output_partition_count(), + self.split_scan, + ))) } fn open_with_args(&self, args: OpenArgs) -> DFResult { @@ -792,7 +795,7 @@ impl DataSource for VortexDataSource { let execution = state.downcast::().map_err(|_| { DataFusionError::Execution("incompatible scan execution state".into()) })?; - self.open_shared(args.partition, execution) + self.open_partition(args.partition, execution) } None => self.open(args.partition, args.context), } @@ -1394,10 +1397,10 @@ mod tests { Ok(()) } - /// Each output partition scans on its own, lazily, and reads only its piece; partitions beyond - /// the piece count return no rows. + /// One execution scans and splits once, lazily, and output partition `i` reads piece `i`; + /// partitions beyond the piece count return no rows, and a reset execution scans again. #[tokio::test] - async fn each_output_partition_reads_its_own_piece() -> anyhow::Result<()> { + async fn output_partitions_read_the_pieces_of_one_split() -> anyhow::Result<()> { let scans = Arc::new(AtomicUsize::new(0)); let data_source: DataSourceRef = Arc::new(TestDataSource { dtype: test_dtype(), @@ -1440,16 +1443,19 @@ mod tests { partitions.push(partition_values(&batches)); } assert_eq!(partitions, [vec![0, 1], vec![100, 101], vec![], vec![]]); - assert_eq!(scans.load(Ordering::Relaxed), 4); + assert_eq!(scans.load(Ordering::Relaxed), 1); assert_eq!(plan.metrics().expect("scan metrics").output_rows(), Some(4)); + assert!(plan.execute(0, Arc::clone(&context)).is_err()); assert!(plan.execute(4, Arc::clone(&context)).is_err()); - // A partition holds no state, so it can be read again, here without sibling state. - let direct = source.open(1, context)?; - assert_eq!( - partition_values(&direct.try_collect::>().await?), - [100, 101] - ); + let reset = Arc::clone(&plan).reset_state()?; + let mut values = partition_values(&collect(reset, Arc::clone(&context)).await?); + values.sort_unstable(); + assert_eq!(values, [0, 1, 100, 101]); + assert_eq!(scans.load(Ordering::Relaxed), 2); + + // Without sibling state, several partitions cannot share one split. + assert!(source.open(0, context).is_err()); Ok(()) } From e36740da35f02051c311eeceed1eec201ff3d74b Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 14:20:22 -0500 Subject: [PATCH 41/80] 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 42/80] 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 1569d399e11833d012d2cbf362f3c5750916b19a Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 14:39:30 -0500 Subject: [PATCH 43/80] Describe to_arrow's input as a piece of a split scan Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-arrow/src/stream.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vortex-arrow/src/stream.rs b/vortex-arrow/src/stream.rs index cfdca8fd618..84a6331d943 100644 --- a/vortex-arrow/src/stream.rs +++ b/vortex-arrow/src/stream.rs @@ -23,7 +23,7 @@ use vortex_session::VortexSession; use crate::ArrowSessionExt; use crate::ExecuteArrowExt; -/// Arrow record-batch output for an [`ArrayStream`], such as a scan worker. +/// Arrow record-batch output for an [`ArrayStream`], such as a piece of a split scan. pub trait ArrowArrayStreamExt: ArrayStream + Send + Sized + 'static { /// Converts each array of the stream to an Arrow [`RecordBatch`] with `schema`. /// From cef16c63b49f9f423a8f60307ea269b2bcb99420 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 14:44:33 -0500 Subject: [PATCH 44/80] 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 426cb196aca229e417ac9227c9308386d6534f44 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 14:44:41 -0500 Subject: [PATCH 45/80] Say what LayoutReaderScan::builder builds Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-layout/src/scan/layout.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/vortex-layout/src/scan/layout.rs b/vortex-layout/src/scan/layout.rs index b3d930d06ff..24755112d6f 100644 --- a/vortex-layout/src/scan/layout.rs +++ b/vortex-layout/src/scan/layout.rs @@ -246,7 +246,8 @@ struct LayoutReaderScan { } impl LayoutReaderScan { - /// The scan over the rows that remain, as develop's DuckDB scan builds it for a file. + /// A scan builder over this scan's reader, with its selection, projection, filter, metrics + /// and split concurrency. Callers give it the row range to read. fn builder(&self) -> ScanBuilder { ScanBuilder::new(self.session.clone(), Arc::clone(&self.reader)) .with_selection(self.selection.clone()) From 7f804216e9fc815b9d26544c063c98f47c351144 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 14:45:58 -0500 Subject: [PATCH 46/80] Cancel a scan execution when an unfinished output partition drops Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-datafusion/src/v2/source.rs | 183 +++++++++++++++++++++++++++-- 1 file changed, 171 insertions(+), 12 deletions(-) diff --git a/vortex-datafusion/src/v2/source.rs b/vortex-datafusion/src/v2/source.rs index 9db85afa9fd..b704cdb3cb5 100644 --- a/vortex-datafusion/src/v2/source.rs +++ b/vortex-datafusion/src/v2/source.rs @@ -116,6 +116,7 @@ use futures::future::try_join_all; use futures::lock::Mutex as AsyncMutex; use futures::stream; use futures::stream::BoxStream; +use futures::task::AtomicWaker; use tokio::sync::OnceCell; use vortex::array::stream::ArrayStreamAdapter; use vortex::array::stream::ArrayStreamExt; @@ -414,6 +415,11 @@ impl VortexDataSource { /// fixed and in order. Setting [`SCAN_POOL_ENV`] to `0` instead has the output partitions take /// partitions from one shared partition stream, for comparison. /// +/// In either mode an output partition holds work that no other partition reads: its piece, or the +/// partitions it has taken. Dropping an output partition before it finishes therefore cancels its +/// execution, and the other output partitions report an error rather than finish without those +/// rows. +/// /// [splits]: vortex::scan::DataSourceScan::split /// /// Use [`crate::VortexSource`] instead when DataFusion should discover and plan @@ -515,11 +521,14 @@ impl VortexDataSource { partition: usize, execution: Arc, ) -> DFResult { - let claimed = execution - .claimed + if execution.cancelled.load(Ordering::Acquire) { + return Err(cancelled()); + } + let output = execution + .output_partitions .get(partition) .ok_or_else(|| invalid_partition(partition))?; - if claimed.swap(true, Ordering::AcqRel) { + if output.claimed.swap(true, Ordering::AcqRel) { return Err(DataFusionError::Execution( "scan output partition already opened; reset the execution plan before replay" .into(), @@ -531,6 +540,7 @@ impl VortexDataSource { let schema = Arc::clone(&self.projected_schema); let concurrency = self.conversion_concurrency(); let ordered = self.ordered; + let shared = Arc::clone(&execution); let batches = stream::once(async move { let work = execution .work @@ -556,7 +566,7 @@ impl VortexDataSource { }) .try_flatten() .boxed(); - self.output_stream(batches, partition) + self.output_stream(batches, partition, shared) } /// Applies the limit and leftover projection to an output partition's batches and records its @@ -565,6 +575,7 @@ impl VortexDataSource { &self, batches: BoxStream<'static, VortexResult>, partition: usize, + execution: Arc, ) -> DFResult { let metrics = BaselineMetrics::new(&self.metrics, partition); let stream = if self.limit == Some(0) { @@ -576,8 +587,10 @@ impl VortexDataSource { self.batch_stream(batches, partition)? }; Ok(Box::pin(OutputPartitionStream { + partition, schema: Arc::clone(&self.leftover_schema), - stream, + stream: Some(stream), + execution, metrics, })) } @@ -654,10 +667,17 @@ fn invalid_partition(partition: usize) -> DataFusionError { /// pieces share one queue of work, so pieces from separate calls would each read every row. struct ScanExecution { split: bool, - claimed: Vec, + output_partitions: Vec, + cancelled: AtomicBool, work: OnceCell>, } +#[derive(Default)] +struct OutputPartitionState { + claimed: AtomicBool, + waker: AtomicWaker, +} + enum ScanWork { /// Every output partition takes partitions from this shared stream. Partitions(Arc), @@ -669,13 +689,42 @@ impl ScanExecution { fn new(output_partitions: usize, split: bool) -> Self { Self { split, - claimed: (0..output_partitions) - .map(|_| AtomicBool::new(false)) + output_partitions: (0..output_partitions) + .map(|_| OutputPartitionState::default()) .collect(), + cancelled: AtomicBool::new(false), work: OnceCell::new(), } } + /// Cancels the execution and wakes every output partition, so each reports the error. + fn cancel(&self) { + if !self.cancelled.swap(true, Ordering::AcqRel) { + for output in &self.output_partitions { + output.waker.wake(); + } + } + } + + /// Drops the scan work that no output partition holds, once the execution is cancelled. + fn release(&self) { + match self.work.get() { + Some(Ok(ScanWork::Partitions(shared))) => { + if let Some(mut partitions) = shared.partitions.try_lock() { + drop(partitions.take()); + } + } + Some(Ok(ScanWork::Pieces(pieces))) => { + for piece in pieces { + if let Some(mut piece) = piece.try_lock() { + drop(piece.take()); + } + } + } + Some(Err(_)) | None => {} + } + } + async fn start( &self, data_source: DataSourceRef, @@ -688,7 +737,7 @@ impl ScanExecution { partitions: AsyncMutex::new(Some(scan.partitions())), }))); } - let pieces = NonZeroUsize::new(self.claimed.len()).unwrap_or(NonZeroUsize::MIN); + let pieces = NonZeroUsize::new(self.output_partitions.len()).unwrap_or(NonZeroUsize::MIN); Ok(ScanWork::Pieces( scan.split(pieces)? .into_iter() @@ -738,20 +787,55 @@ impl SharedPartitions { } } +/// One output partition of a [`ScanExecution`], which cancels the execution when it fails or is +/// dropped before it finishes. struct OutputPartitionStream { + partition: usize, schema: SchemaRef, - stream: SendableRecordBatchStream, + /// The partition's batches, until it finishes. + stream: Option, + execution: Arc, metrics: BaselineMetrics, } +impl OutputPartitionStream { + fn finish(&mut self) { + self.stream = None; + drop( + self.execution.output_partitions[self.partition] + .waker + .take(), + ); + } +} + impl Stream for OutputPartitionStream { type Item = DFResult; fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { let metrics = self.metrics.clone(); let _timer = metrics.elapsed_compute().timer(); - let poll = self.stream.as_mut().poll_next(cx); - metrics.record_poll(poll) + self.execution.output_partitions[self.partition] + .waker + .register(cx.waker()); + let mut result = if self.execution.cancelled.load(Ordering::Acquire) { + Poll::Ready(None) + } else { + match self.stream.as_mut() { + Some(stream) => stream.as_mut().poll_next(cx), + None => Poll::Ready(None), + } + }; + if self.stream.is_some() && self.execution.cancelled.load(Ordering::Acquire) { + result = Poll::Ready(Some(Err(cancelled()))); + } + if matches!(result, Poll::Ready(Some(Err(_)))) { + self.execution.cancel(); + } + if matches!(result, Poll::Ready(None | Some(Err(_)))) { + self.finish(); + } + metrics.record_poll(result) } } @@ -763,10 +847,21 @@ impl RecordBatchStream for OutputPartitionStream { impl Drop for OutputPartitionStream { fn drop(&mut self) { + if self.stream.is_some() { + self.execution.cancel(); + } + self.finish(); + if self.execution.cancelled.load(Ordering::Acquire) { + self.execution.release(); + } self.metrics.done(); } } +fn cancelled() -> DataFusionError { + DataFusionError::Execution("scan execution cancelled".into()) +} + impl DataSource for VortexDataSource { fn open( &self, @@ -1094,6 +1189,8 @@ mod tests { use datafusion_physical_plan::expressions::BinaryExpr; use datafusion_physical_plan::expressions::lit; use futures::TryStreamExt; + use futures::task::ArcWake; + use futures::task::waker_ref; use rstest::rstest; use vortex::VortexSessionDefault; use vortex::array::IntoArray; @@ -1520,6 +1617,68 @@ mod tests { Ok(()) } + #[derive(Default)] + struct WakeCounter(AtomicUsize); + + impl ArcWake for WakeCounter { + fn wake_by_ref(arc_self: &Arc) { + arc_self.0.fetch_add(1, Ordering::Relaxed); + } + } + + /// Dropping an output partition before it finishes cancels the execution, so the other + /// partitions report an error rather than finish without the rows it held. + #[rstest] + #[case::split(true)] + #[case::shared_partitions(false)] + #[tokio::test] + async fn dropping_an_unfinished_partition_cancels_the_execution( + #[case] split: bool, + ) -> anyhow::Result<()> { + let data_source: DataSourceRef = Arc::new(TestDataSource { + dtype: test_dtype(), + polls: Arc::default(), + scans: Arc::default(), + }); + let source = VortexDataSource::builder(data_source, VortexSession::default()) + .with_split_scan(split) + .build() + .await? + .repartitioned(2, 0, None)? + .expect("repartitioning supported"); + let plan = Arc::new(DataSourceExec::new(source)) as Arc; + let mut output = plan.execute(0, Arc::new(TaskContext::default()))?; + assert!(output.try_next().await?.is_some()); + drop(output); + assert!(plan.execute(1, Arc::new(TaskContext::default())).is_err()); + + // A partition already waiting is woken and reports the cancellation. + let execution = Arc::new(ScanExecution::new(2, split)); + let output = |partition| OutputPartitionStream { + partition, + schema: plan.schema(), + stream: Some(Box::pin(RecordBatchStreamAdapter::new( + plan.schema(), + stream::pending(), + ))), + execution: Arc::clone(&execution), + metrics: BaselineMetrics::new(&ExecutionPlanMetricsSet::new(), partition), + }; + let dropped = output(0); + let mut pending = Box::pin(output(1)); + let wakes = Arc::new(WakeCounter::default()); + let waker = waker_ref(&wakes); + let mut cx = Context::from_waker(&waker); + assert!(pending.as_mut().poll_next(&mut cx).is_pending()); + drop(dropped); + assert_eq!(wakes.0.load(Ordering::Relaxed), 1); + assert!(matches!( + pending.as_mut().poll_next(&mut cx), + Poll::Ready(Some(Err(_))) + )); + Ok(()) + } + /// A fetch bounds each of several output partitions. A limited scan cannot be cut, so its /// one piece goes to the first partition. #[tokio::test] From 00011de85945e4adf14000b2cdadbbc129fc307d Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 14:47:34 -0500 Subject: [PATCH 47/80] Read two files at once per clone of an unordered multi-file scan Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-layout/src/scan/multi.rs | 77 ++++++++++++++++++++++++++++++++- vortex-scan/src/lib.rs | 9 ++-- 2 files changed, 81 insertions(+), 5 deletions(-) diff --git a/vortex-layout/src/scan/multi.rs b/vortex-layout/src/scan/multi.rs index dc2e7094e65..00d35271434 100644 --- a/vortex-layout/src/scan/multi.rs +++ b/vortex-layout/src/scan/multi.rs @@ -33,6 +33,7 @@ use std::sync::Arc; use async_trait::async_trait; use futures::FutureExt; use futures::StreamExt; +use futures::TryStreamExt; use futures::stream; use itertools::Itertools; use tracing::Instrument; @@ -68,6 +69,13 @@ use crate::scan::layout::group_contiguous; use crate::scan::limit::RowLimit; use crate::scan::scan_builder::ScanBuilder; +/// How many files each clone of an unordered scan's opened stream reads at once. +/// +/// This matches the read-ahead of the DataFusion `VortexTable` path on develop +/// (`SCAN_PARTITION_READ_AHEAD`), so that reading a scan through `open` and through `split` +/// behaves the same. +const PARTITION_READ_AHEAD: usize = 2; + /// Default concurrency for opening deferred readers. const DEFAULT_CONCURRENCY: usize = 8; @@ -554,8 +562,28 @@ impl DataSourceScan for MultiLayoutScan { /// Opens the scan into its partition pipeline, which opens up to `concurrency` files ahead /// and reads each file as one partition, handing the partitions to the stream's clones. + /// + /// Each clone of an unordered scan without a limit reads [`PARTITION_READ_AHEAD`] files at + /// once, each with its own split concurrency, so that one file's last splits overlap the + /// next file's first. An ordered scan must finish a file before it starts the next, and a + /// limited one would read files the limit may never need, so both read one at a time. fn open(self: Box) -> VortexResult { - Ok(ScanStream::from_partitions(self)) + if self.request.ordered || self.request.limit.is_some() { + return Ok(ScanStream::from_partitions(self)); + } + let dtype = self.dtype.clone(); + let partitions = Arc::new(futures::lock::Mutex::new(self.partitions())); + Ok(ScanStream::new(dtype, move || { + stream::unfold(Arc::clone(&partitions), |shared| async move { + let next = shared.lock().await.next().await?; + Some((next, shared)) + }) + .map(|partition| partition.and_then(|partition| partition.execute())) + // Matches the DataFusion `VortexTable` path's read-ahead on develop, so a scan read + // through `open` behaves as one read through `split`. + .try_flatten_unordered(Some(PARTITION_READ_AHEAD)) + .boxed() + })) } fn partition_count(&self) -> Precision { @@ -1122,6 +1150,53 @@ mod tests { Ok(()) } + /// A clone of an unordered scan's opened stream reads two files at once, each with its own + /// split concurrency. An ordered scan reads one file at a time. + #[rstest] + #[case::unordered(false, 2)] + #[case::ordered(true, 1)] + fn opened_stream_reads_files_ahead( + #[case] ordered: bool, + #[case] expected_peak: usize, + ) -> VortexResult<()> { + let runtime = SingleThreadRuntime::default(); + let session = session_with_handle(runtime.handle()); + let in_flight = Arc::new(InFlight::default()); + let file = |base: i32| { + Arc::new( + TestLayoutReader::new(8) + .with_split_size(1) + .with_base(base) + .with_in_flight(Arc::clone(&in_flight)), + ) as LayoutReaderRef + }; + let rest = (1..3) + .map(|i| { + Arc::new(StaticReaderFactory { + reader: file(10 * i), + }) as Arc + }) + .collect(); + let source = MultiLayoutDataSource::new_with_first(file(0), rest, vec![], &session); + + let stream = runtime + .block_on(source.scan(ScanRequest { + ordered, + split_concurrency: NonZeroUsize::new(1), + ..Default::default() + }))? + .open()?; + let mut values = collect_scan_values(runtime.block_on_stream(stream))?; + values.sort_unstable(); + let expected: Vec = [0, 10, 20] + .into_iter() + .flat_map(|base| base..base + 8) + .collect(); + assert_eq!(values, expected); + assert_eq!(in_flight.peak(), expected_peak, "splits read at once"); + Ok(()) + } + /// Scans 64 one-row splits, returning the rows and the most splits read at once. fn scan_with_split_concurrency( split_concurrency: Option, diff --git a/vortex-scan/src/lib.rs b/vortex-scan/src/lib.rs index 1838ff10157..369f2edfb79 100644 --- a/vortex-scan/src/lib.rs +++ b/vortex-scan/src/lib.rs @@ -178,11 +178,12 @@ 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 worker decodes at once, where a worker is a partition or a - /// clone of an opened scan's stream. + /// The most splits decoded at once for each partition being read, or for each clone of an + /// opened scan's stream that reads a single queue of splits. /// - /// 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 + /// It does not bound the whole scan: a scan read by several workers decodes up to this many + /// splits for each partition each worker is reading, and a worker may read more than one + /// partition at once. `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 From 9d5c2fad216f4f33785b02743a03fa14bc6443cb Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 14:37:53 -0500 Subject: [PATCH 48/80] Report an opened scan's progress on its stream A host reading an opened scan, such as DuckDB showing a progress bar per file, asks its stream how much of the work its clones have taken. A layout scan's stream reports the fraction of its splits claimed; a stream over partitions reports none. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-layout/src/scan/layout.rs | 9 ++++++--- vortex-layout/src/scan/split_queue.rs | 18 +++++++++++++++++- vortex-scan/src/stream.rs | 19 +++++++++++++++++++ 3 files changed, 42 insertions(+), 4 deletions(-) diff --git a/vortex-layout/src/scan/layout.rs b/vortex-layout/src/scan/layout.rs index 24755112d6f..07cf1e5860a 100644 --- a/vortex-layout/src/scan/layout.rs +++ b/vortex-layout/src/scan/layout.rs @@ -334,9 +334,11 @@ impl DataSourceScan for LayoutReaderScan { .prepare()? .execute(Some(self.next_row..self.end_row))?; let queue = Arc::new(SplitQueue::new(self.session.handle(), per_worker, splits)); - Ok(ScanStream::new(self.dtype, move || { - Arc::clone(&queue).worker() - })) + let progress = Arc::clone(&queue); + Ok( + ScanStream::new(self.dtype, move || Arc::clone(&queue).worker()) + .with_progress(move || progress.progress()), + ) } fn partition_count(&self) -> Precision { @@ -790,6 +792,7 @@ mod split_open_tests { let mut values = collect_scan_values(arrays.into_iter().flatten().map(Ok))?; values.sort_unstable(); assert_eq!(values, (0..64).collect::>()); + assert_eq!(stream.progress(), Some(1.0)); Ok(()) } diff --git a/vortex-layout/src/scan/split_queue.rs b/vortex-layout/src/scan/split_queue.rs index ba46fe3a263..49afc813c56 100644 --- a/vortex-layout/src/scan/split_queue.rs +++ b/vortex-layout/src/scan/split_queue.rs @@ -5,6 +5,8 @@ use std::iter; use std::sync::Arc; +use std::sync::atomic::AtomicUsize; +use std::sync::atomic::Ordering; use std::vec; use futures::StreamExt; @@ -40,6 +42,8 @@ pub(crate) struct SplitQueue { handle: Handle, per_worker: usize, splits: Mutex>, + total: usize, + claimed: AtomicUsize, } impl SplitQueue { @@ -47,13 +51,25 @@ impl SplitQueue { Self { handle, per_worker: per_worker.max(1), + total: splits.len(), splits: Mutex::new(splits.into_iter()), + claimed: AtomicUsize::new(0), } } /// Claims the next split, if any is left. fn claim(&self) -> Option { - self.splits.lock().next() + let split = self.splits.lock().next()?; + self.claimed.fetch_add(1, Ordering::Relaxed); + Some(split) + } + + /// The fraction of the splits that the stream's clones have claimed. + pub(crate) fn progress(&self) -> f64 { + if self.total == 0 { + return 1.0; + } + (self.claimed.load(Ordering::Relaxed) as f64 / self.total as f64).min(1.0) } /// A new worker over the shared queue, which one clone of the scan's stream polls. diff --git a/vortex-scan/src/stream.rs b/vortex-scan/src/stream.rs index 957b01407df..7c2ec623c5d 100644 --- a/vortex-scan/src/stream.rs +++ b/vortex-scan/src/stream.rs @@ -30,6 +30,9 @@ use crate::PartitionStream; /// Starts a new worker over the shared work of an opened scan. type NewWorker = dyn Fn() -> BoxStream<'static, VortexResult> + Send + Sync; +/// Reads the fraction of an opened scan's work that its clones have taken. +type Progress = dyn Fn() -> f64 + Send + Sync; + /// The arrays of an opened scan, which host threads read by each polling a clone. /// /// A clone is another worker over the same remaining work, like a clone of a channel's receiver: @@ -43,6 +46,7 @@ type NewWorker = dyn Fn() -> BoxStream<'static, VortexResult> + Send + pub struct ScanStream { dtype: DType, new_worker: Arc, + progress: Option>, worker: Option>>, } @@ -58,10 +62,24 @@ impl ScanStream { Self { dtype, new_worker: Arc::new(new_worker), + progress: None, worker: None, } } + /// This stream, reporting its progress through `progress`, which returns the fraction of the + /// scan's work that its clones have taken, from 0.0 to 1.0, and must never block. + pub fn with_progress(mut self, progress: impl Fn() -> f64 + Send + Sync + 'static) -> Self { + self.progress = Some(Arc::new(progress)); + self + } + + /// The fraction of the scan's work that its clones have taken, from 0.0 to 1.0, for a host's + /// progress bar, or `None` when the scan does not track it. Never blocks. + pub fn progress(&self) -> Option { + self.progress.as_ref().map(|progress| progress()) + } + /// A stream whose clones 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. @@ -90,6 +108,7 @@ impl Clone for ScanStream { Self { dtype: self.dtype.clone(), new_worker: Arc::clone(&self.new_worker), + progress: self.progress.clone(), worker: None, } } From cdb5fadd2c0869dd140dca4af3715529b24e08f2 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 14:37:53 -0500 Subject: [PATCH 49/80] Read DuckDB's V1 scans through open Each file DuckDB's MultiFileReader opens is opened once as a V1 layout scan, and every DuckDB thread that joins the file polls a clone of its stream. A thread joins a file until the first clone ends, which happens only once no split is left to claim, so threads move on to the next file without waiting for the last splits to finish. DuckDB's private per-file split list is removed. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-duckdb/src/file_reader.rs | 176 +++++++++++++++++++--------- vortex-duckdb/src/projection.rs | 7 +- vortex-duckdb/src/table_function.rs | 19 ++- 3 files changed, 141 insertions(+), 61 deletions(-) diff --git a/vortex-duckdb/src/file_reader.rs b/vortex-duckdb/src/file_reader.rs index 70d8d30c6cb..24d609e7217 100644 --- a/vortex-duckdb/src/file_reader.rs +++ b/vortex-duckdb/src/file_reader.rs @@ -1,12 +1,14 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +use std::ops::Range; use std::sync::Arc; use std::sync::OnceLock; use std::sync::atomic::AtomicBool; use std::sync::atomic::Ordering; use futures::FutureExt; +use futures::StreamExt; use object_store::registry::ObjectStoreRegistry; use url::Url; use vortex::array::ArrayRef; @@ -31,10 +33,14 @@ use vortex::io::object_store::ObjectStoreFileSystem; use vortex::io::runtime::BlockingRuntime as _; use vortex::io::std_file::StdFileSystem; use vortex::layout::LayoutReaderRef; +use vortex::layout::scan::layout::LayoutReaderDataSource; use vortex::layout::scan::scan_builder::ScanBuilder; use vortex::layout::scan::v2::ScanBuilder as V2ScanBuilder; use vortex::layout::scan::v2::ScanFile; use vortex::mask::Mask; +use vortex::scan::DataSource as _; +use vortex::scan::ScanRequest; +use vortex::scan::stream::ScanStream; use vortex::session::SessionExt as _; use crate::REGISTRY; @@ -111,17 +117,14 @@ fn resolve_filesystem(url: &Url) -> VortexResult<(FileSystemRef, String)> { } pub struct OpenFileReader { - /// The layout reader and conversion cache of the file. `None` after the file is skipped or - /// all its splits are taken. + /// The layout reader, scan and conversion cache of the file. `None` after the file is skipped + /// or no thread can join it any more. /// /// DuckDB releases its last reference to a file while it holds the global lock of the /// multi-file scan, and dropping this state takes long. So every local state that scans the /// file holds a reference too, and the file gives its own reference to a local state before /// DuckDB releases the file. The last local state drops the state outside the lock. scan_state: Option>, - /// File splits stored in inverse order - pub splits: Vec, - total_splits: usize, } /// The state of an open file that the threads scanning it share. @@ -132,9 +135,31 @@ pub struct FileScanState { /// The file's V2 scan, which every thread scanning the file drives. Set when the file is /// initialized for a V2 scan. v2: OnceLock, + /// The opened stream of the file's V1 scan, which each thread scanning the file polls a clone + /// of. Set when the file is initialized for a V1 scan. + stream: OnceLock, + /// Whether a clone of `stream` has ended, so no split of the file is left to claim. + finished: AtomicBool, cache: ConversionCache, } +impl FileScanState { + /// The scan work a thread joining the file would take, or `None` once the file has none. + fn next_split(&self) -> Option { + if let Some(scan) = self.v2.get() { + return (!scan.is_exhausted()).then_some(Split::V2); + } + // A clone of the file's stream ends only once no split is left to claim and its own + // splits are done. So a thread joins the file until the first clone ends, and threads + // then move on to the next file while the clones holding the last splits finish them: + // no thread waits for the rest of a file to drain. + if self.finished.load(Ordering::Acquire) { + return None; + } + self.stream.get().cloned().map(Split::V1) + } +} + impl OpenFileReader { async fn open(path: String) -> VortexResult { let (fs, fs_path) = resolve_filesystem(&parse_uri_or_path(&path)?)?; @@ -147,10 +172,10 @@ impl OpenFileReader { reader: file.layout_reader()?, scan_file, v2: OnceLock::new(), + stream: OnceLock::new(), + finished: AtomicBool::new(false), cache: ConversionCache::default(), })), - splits: vec![], - total_splits: 0, }) } @@ -219,7 +244,7 @@ pub fn reader_initialize(file: &mut OpenFileReader, global: &GlobalState) -> Vor return Ok(true); } - // Getting splits, or planning a V2 scan, is non-trivial work so we prefer + // Opening the file's scan, or planning a V2 scan, is non-trivial work so we prefer // doing it here under file lock and not in reader_try_initialize_scan under // global lock. if global.scan_v2 { @@ -240,33 +265,42 @@ pub fn reader_initialize(file: &mut OpenFileReader, global: &GlobalState) -> Vor return Ok(false); } - let reader = Arc::clone(file.reader()); + let state = file.scan_state(); let filter = &global.filter; - let builder = ScanBuilder::new(SESSION.clone(), reader) - .with_projection(global.projection.clone()) - .with_some_filter(filter.filter.clone()) - .with_selection(filter.row_selection.clone()); - let scan = builder.prepare()?; - let mut splits: Vec = scan - .execute(filter.row_range.clone())? - .into_iter() - .map(Split::V1) - .collect(); - - // threads take last element of file.splits so we need to reverse - splits.reverse(); - file.total_splits = splits.len(); - file.splits = splits; + let request = ScanRequest { + projection: global.projection_expr.clone(), + filter: filter.expr.clone(), + row_range: Some(file_rows(state, filter)), + selection: filter.row_selection.clone(), + ordered: false, + ..ScanRequest::default() + }; + // An unordered scan without a limit opens into a stream over a queue of the file's splits. + // Each clone claims splits as it has room for them, keeps a few in flight on the runtime, + // and yields each as it finishes, so the threads polling clones decode while their reads are + // pending. + let source = LayoutReaderDataSource::new(Arc::clone(&state.reader), SESSION.clone()); + let stream = RUNTIME.block_on(source.scan(request))?.open()?; + if state.stream.set(stream).is_err() { + vortex_panic!("file initialized twice"); + } Ok(false) } +/// The rows of the file that the scan's row range keeps. A `file_row_number` filter can bound +/// the range past the end of the file, up to `u64::MAX`. +fn file_rows(state: &FileScanState, filter: &Filter) -> Range { + let row_count = state.reader.row_count(); + filter.row_range.as_ref().map_or(0..row_count, |range| { + let end = range.end.min(row_count); + range.start.min(end)..end + }) +} + /// The V2 scan of the file's rows that the scan's row range and selection keep. fn v2_builder(state: &FileScanState, global: &GlobalState) -> V2ScanBuilder { let filter = &global.filter; - let row_count = state.reader.row_count(); - let rows = filter.row_range.as_ref().map_or(0..row_count, |range| { - range.start.min(row_count)..range.end.min(row_count) - }); + let rows = file_rows(state, filter); V2ScanBuilder::new(SESSION.clone(), state.scan_file.clone()) .with_projection(global.projection.clone()) .with_some_filter(filter.filter.clone()) @@ -287,9 +321,32 @@ enum SplitItem { fn next_split_item(local: &mut LocalState) -> VortexResult { match local.split.take() { None => Ok(SplitItem::Done), - Some(Split::V1(task)) => Ok(RUNTIME - .block_on(task)? - .map_or(SplitItem::Empty, SplitItem::Array)), + Some(Split::V1(mut stream)) => { + let array = match local.pending.pop() { + Some(array) => array, + None => { + let Some(array) = RUNTIME.block_on(stream.next()).transpose()? else { + local + .file + .as_ref() + .vortex_expect("split without a file") + .finished + .store(true, Ordering::Release); + // Dropping the last clone drops the file's split queue; do that outside + // DuckDB's locks. + local.retired_splits.push(Split::V1(stream)); + return Ok(SplitItem::Done); + }; + split_chunks(&mut local.pending, array) + } + }; + local.split = Some(Split::V1(stream)); + Ok(if array.is_empty() { + SplitItem::Empty + } else { + SplitItem::Array(array) + }) + } Some(Split::V2) => { let file = local.file.as_ref().vortex_expect("split without a file"); let scan = file @@ -302,16 +359,7 @@ fn next_split_item(local: &mut LocalState) -> VortexResult { let Some(array) = scan.next_array(&mut local.run)? else { return Ok(SplitItem::Done); }; - // A V2 batch can join chunks of several layout chunks. Canonicalizing it - // would decode their dictionaries, so export each chunk on its own, as a V1 - // scan yields them. - match array.as_opt::() { - Some(chunked) => { - local.pending.extend(chunked.chunks().into_iter().rev()); - local.pending.pop().unwrap_or(array) - } - None => array, - } + split_chunks(&mut local.pending, array) } }; local.split = Some(Split::V2); @@ -324,6 +372,20 @@ fn next_split_item(local: &mut LocalState) -> VortexResult { } } +/// The first chunk of `array`, leaving the rest in `pending` in reverse order. +/// +/// An array can join chunks of several layout chunks. Canonicalizing it would decode their +/// dictionaries, so export each chunk on its own. +fn split_chunks(pending: &mut Vec, array: ArrayRef) -> ArrayRef { + match array.as_opt::() { + Some(chunked) => { + pending.extend(chunked.chunks().into_iter().rev()); + pending.pop().unwrap_or(array) + } + None => array, + } +} + /// Called by all threads under global lock. If this function returns true, /// thread calls reader_scan on this file. If this function returns false, /// duckdb thinks file is exhausted, closes the file, and the first thread to @@ -333,14 +395,14 @@ fn next_split_item(local: &mut LocalState) -> VortexResult { /// the global lock. It only moves references between the file and the local /// state, and reader_scan drops the retired ones. pub fn reader_try_initialize_scan(file: &mut OpenFileReader, local: &mut LocalState) -> bool { - // A V2 scan's threads take chunks from the file's scan until it has spawned - // them all, so the file has work for another thread until then. - let v2 = file + // A thread joins a file while its V2 scan has chunks left to spawn or its V1 + // stream has a split left to claim. Cloning the stream only clones its handles, + // so it is cheap under the global lock. + let split = file .scan_state .as_ref() - .and_then(|state| state.v2.get()) - .map(|scan| (!scan.is_exhausted()).then_some(Split::V2)); - let Some(split) = v2.unwrap_or_else(|| file.splits.pop()) else { + .and_then(|state| state.next_split()); + let Some(split) = split else { // DuckDB releases the file after this call, under the global lock. // Give the reference of the file to this thread so it drops outside. local.retired_files.extend(file.scan_state.take()); @@ -360,7 +422,7 @@ pub fn reader_try_initialize_scan(file: &mut OpenFileReader, local: &mut LocalSt local.retired_files.extend(previous); } - local.split = Some(split); + local.retired_splits.extend(local.split.replace(split)); true } @@ -372,7 +434,8 @@ pub fn reader_scan( local: &mut LocalState, chunk: &mut DataChunkRef, ) -> VortexResult { - // No lock is held here, so drop the scan states of files this thread left. + // No lock is held here, so drop the splits and scan states this thread left. + local.retired_splits.clear(); local.retired_files.clear(); if !global.aggregates.is_empty() { @@ -453,13 +516,18 @@ pub fn reader_get_statistics( /// Called from a separate thread (not related to threads for Vortex /// table function) under global lock. pub fn reader_get_progress_in_file(file: &OpenFileReader) -> f64 { - if let Some(scan) = file.scan_state.as_ref().and_then(|state| state.v2.get()) { + // A file without a scan state was skipped or has every split taken. + let Some(state) = file.scan_state.as_ref() else { + return 100.0; + }; + if let Some(scan) = state.v2.get() { return scan.progress(); } - let total = file.total_splits; - let left = file.splits.len(); - let denom = total + (total == 0) as usize; - 100.0 * (total - left) as f64 / denom as f64 + state + .stream + .get() + .and_then(ScanStream::progress) + .map_or(0.0, |progress| 100.0 * progress) } /// Called by one thread in planning phase diff --git a/vortex-duckdb/src/projection.rs b/vortex-duckdb/src/projection.rs index 68a7c8cd454..afa76f59635 100644 --- a/vortex-duckdb/src/projection.rs +++ b/vortex-duckdb/src/projection.rs @@ -191,6 +191,8 @@ impl Projection { pub struct Filter { pub filter: Option, + /// `filter` before binding, for scans that bind it against each file. + pub expr: Option, pub row_selection: Selection, pub row_range: Option>, pub has_non_optional_filter: bool, @@ -257,12 +259,15 @@ impl Filter { } }; - let filter = and_collect(table_filter_exprs) + let expr = and_collect(table_filter_exprs); + let filter = expr + .as_ref() .map(|expr| expr.bind(dtype)?.optimize_recursive()) .transpose()?; let out = Self { filter, + expr, row_selection, row_range, has_non_optional_filter, diff --git a/vortex-duckdb/src/table_function.rs b/vortex-duckdb/src/table_function.rs index e96dd83d12c..02e9446bfbf 100644 --- a/vortex-duckdb/src/table_function.rs +++ b/vortex-duckdb/src/table_function.rs @@ -11,7 +11,6 @@ use std::sync::atomic::Ordering; #[cfg(unix)] use custom_labels::CURRENT_LABELSET; -use futures::future::BoxFuture; use itertools::Itertools; use num_traits::AsPrimitive; use parking_lot::Mutex; @@ -43,6 +42,7 @@ use vortex::metrics::tracing::get_global_labels; use vortex::proto::expr as expr_pb; use vortex::scalar::Scalar; use vortex::scan::planning::driver::Run; +use vortex::scan::stream::ScanStream; use vortex_utils::aliases::hash_map::HashMap; use crate::SESSION; @@ -183,6 +183,8 @@ impl<'a> TableInitInput<'a> { pub struct GlobalState { pub projection: BoundExpression, + /// The projection before binding, for scans that bind it against each file. + pub projection_expr: Expression, pub filter: Filter, pub file_row_number_column_pos: Option, /// Whether the scan runs on the planner-driven V2 executor. @@ -203,10 +205,11 @@ pub struct AggregateState { } assert_impl_all!(GlobalState: Send, Sync); -/// A unit of scan work that one thread takes at a time. +/// The scan work that one thread does on a file. pub enum Split { - /// A V1 scan task yielding one array, or `None` if the filter removed every row. - V1(BoxFuture<'static, VortexResult>>), + /// A clone of the file's V1 scan stream, which the thread polls inline. It claims the file's + /// splits as it has room for them until none is left, and yields only the splits it claimed. + V1(ScanStream), /// Chunks of the file's V2 scan, taken by the thread until the scan has none left. V2, } @@ -220,12 +223,13 @@ pub struct LocalState { pub split: Option, /// The scan state of the file that this thread scans. pub(crate) file: Option>, - /// Scan states that this thread no longer uses. They are dropped outside + /// Scan states and splits that this thread no longer uses. They are dropped outside /// DuckDB's global multi-file lock; see `OpenFileReader`. pub(crate) retired_files: Vec>, + pub(crate) retired_splits: Vec, /// The planning run on which this thread runs the chunks of V2 scans. pub(crate) run: Run, - /// Chunks of a V2 batch that this thread has yet to export, in reverse order. + /// Chunks of an array that this thread has yet to export, in reverse order. pub(crate) pending: Vec, /// Empty for non-aggregate scan @@ -352,9 +356,11 @@ pub fn init_global(init_input: &TableInitInput) -> VortexResult { "table function scan input" ); + let projection_expr = projection.clone(); let projection = optimize_and_bind(projection, &bind_data.dtype)?; Ok(GlobalState { projection, + projection_expr, filter, aggregates: bind_data.aggregates.clone(), has_count_star, @@ -430,6 +436,7 @@ pub fn init_local(bind_data: &BindState, global: &GlobalState) -> LocalState { split: None, file: None, retired_files: Vec::new(), + retired_splits: Vec::new(), run: Run::new(), pending: Vec::new(), finished: false, From c7656fcd872abc44d1aa8e0b5d3ee96742c770f0 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 14:59:48 -0500 Subject: [PATCH 50/80] Clone a DuckDB file's scan stream under a lock A ScanStream is Send but not Sync, so the file state that every thread scanning the file shares holds it behind a mutex, and each thread clones it there. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-duckdb/src/file_reader.rs | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/vortex-duckdb/src/file_reader.rs b/vortex-duckdb/src/file_reader.rs index 24d609e7217..f080714a07a 100644 --- a/vortex-duckdb/src/file_reader.rs +++ b/vortex-duckdb/src/file_reader.rs @@ -10,6 +10,7 @@ use std::sync::atomic::Ordering; use futures::FutureExt; use futures::StreamExt; use object_store::registry::ObjectStoreRegistry; +use parking_lot::Mutex; use url::Url; use vortex::array::ArrayRef; use vortex::array::VortexSessionExecute as _; @@ -136,8 +137,9 @@ pub struct FileScanState { /// initialized for a V2 scan. v2: OnceLock, /// The opened stream of the file's V1 scan, which each thread scanning the file polls a clone - /// of. Set when the file is initialized for a V1 scan. - stream: OnceLock, + /// of. Set when the file is initialized for a V1 scan. A stream is `Send` but not `Sync`, so + /// threads clone it under the lock. + stream: OnceLock>, /// Whether a clone of `stream` has ended, so no split of the file is left to claim. finished: AtomicBool, cache: ConversionCache, @@ -156,7 +158,9 @@ impl FileScanState { if self.finished.load(Ordering::Acquire) { return None; } - self.stream.get().cloned().map(Split::V1) + self.stream + .get() + .map(|stream| Split::V1(stream.lock().clone())) } } @@ -281,7 +285,7 @@ pub fn reader_initialize(file: &mut OpenFileReader, global: &GlobalState) -> Vor // pending. let source = LayoutReaderDataSource::new(Arc::clone(&state.reader), SESSION.clone()); let stream = RUNTIME.block_on(source.scan(request))?.open()?; - if state.stream.set(stream).is_err() { + if state.stream.set(Mutex::new(stream)).is_err() { vortex_panic!("file initialized twice"); } Ok(false) @@ -526,7 +530,7 @@ pub fn reader_get_progress_in_file(file: &OpenFileReader) -> f64 { state .stream .get() - .and_then(ScanStream::progress) + .and_then(|stream| stream.lock().progress()) .map_or(0.0, |progress| 100.0 * progress) } From f869fdbd4d8373757e261fb0ae4fb64268205922 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 15:05:01 -0500 Subject: [PATCH 51/80] Run one split at a time on each DuckDB thread DuckDB runs one thread per core, and each polls its own clone of a file's scan stream. A clone that keeps several splits in flight claims splits that other threads could have run, so on a file with few splits, such as TPC-H's smaller tables, most threads find the queue empty. Capping each clone at one split matches DuckDB's own parallelism. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-duckdb/src/file_reader.rs | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/vortex-duckdb/src/file_reader.rs b/vortex-duckdb/src/file_reader.rs index f080714a07a..1ce1c813478 100644 --- a/vortex-duckdb/src/file_reader.rs +++ b/vortex-duckdb/src/file_reader.rs @@ -1,6 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +use std::num::NonZeroUsize; use std::ops::Range; use std::sync::Arc; use std::sync::OnceLock; @@ -277,12 +278,14 @@ pub fn reader_initialize(file: &mut OpenFileReader, global: &GlobalState) -> Vor row_range: Some(file_rows(state, filter)), selection: filter.row_selection.clone(), ordered: false, + // DuckDB runs one thread per core, so its threads are the scan's parallelism: each runs + // one split at a time. A clone with room for more would claim splits other threads could + // have run, leaving them nothing on a file with few splits. + split_concurrency: Some(NonZeroUsize::MIN), ..ScanRequest::default() }; - // An unordered scan without a limit opens into a stream over a queue of the file's splits. - // Each clone claims splits as it has room for them, keeps a few in flight on the runtime, - // and yields each as it finishes, so the threads polling clones decode while their reads are - // pending. + // An unordered scan without a limit opens into a stream over a queue of the file's splits, + // whose clones each claim the next split once they have finished their last. let source = LayoutReaderDataSource::new(Arc::clone(&state.reader), SESSION.clone()); let stream = RUNTIME.block_on(source.scan(request))?.open()?; if state.stream.set(Mutex::new(stream)).is_err() { From 28c6b76c34d7fa3e553c6986c3101e0360af1e85 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 15:14:47 -0500 Subject: [PATCH 52/80] Poll a DuckDB thread's split on that thread Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-duckdb/src/file_reader.rs | 57 +++++++++++---------------- vortex-layout/src/scan/split_queue.rs | 13 +++++- 2 files changed, 35 insertions(+), 35 deletions(-) diff --git a/vortex-duckdb/src/file_reader.rs b/vortex-duckdb/src/file_reader.rs index 1ce1c813478..c6c1969fcda 100644 --- a/vortex-duckdb/src/file_reader.rs +++ b/vortex-duckdb/src/file_reader.rs @@ -279,8 +279,8 @@ pub fn reader_initialize(file: &mut OpenFileReader, global: &GlobalState) -> Vor selection: filter.row_selection.clone(), ordered: false, // DuckDB runs one thread per core, so its threads are the scan's parallelism: each runs - // one split at a time. A clone with room for more would claim splits other threads could - // have run, leaving them nothing on a file with few splits. + // one split at a time, polling it itself. A clone with room for more would claim splits + // other threads could have run, leaving them nothing on a file with few splits. split_concurrency: Some(NonZeroUsize::MIN), ..ScanRequest::default() }; @@ -329,23 +329,17 @@ fn next_split_item(local: &mut LocalState) -> VortexResult { match local.split.take() { None => Ok(SplitItem::Done), Some(Split::V1(mut stream)) => { - let array = match local.pending.pop() { - Some(array) => array, - None => { - let Some(array) = RUNTIME.block_on(stream.next()).transpose()? else { - local - .file - .as_ref() - .vortex_expect("split without a file") - .finished - .store(true, Ordering::Release); - // Dropping the last clone drops the file's split queue; do that outside - // DuckDB's locks. - local.retired_splits.push(Split::V1(stream)); - return Ok(SplitItem::Done); - }; - split_chunks(&mut local.pending, array) - } + let Some(array) = RUNTIME.block_on(stream.next()).transpose()? else { + local + .file + .as_ref() + .vortex_expect("split without a file") + .finished + .store(true, Ordering::Release); + // Dropping the last clone drops the file's split queue; do that outside DuckDB's + // locks. + local.retired_splits.push(Split::V1(stream)); + return Ok(SplitItem::Done); }; local.split = Some(Split::V1(stream)); Ok(if array.is_empty() { @@ -366,7 +360,16 @@ fn next_split_item(local: &mut LocalState) -> VortexResult { let Some(array) = scan.next_array(&mut local.run)? else { return Ok(SplitItem::Done); }; - split_chunks(&mut local.pending, array) + // A V2 batch can join chunks of several layout chunks. Canonicalizing it + // would decode their dictionaries, so export each chunk on its own, as a V1 + // scan yields them. + match array.as_opt::() { + Some(chunked) => { + local.pending.extend(chunked.chunks().into_iter().rev()); + local.pending.pop().unwrap_or(array) + } + None => array, + } } }; local.split = Some(Split::V2); @@ -379,20 +382,6 @@ fn next_split_item(local: &mut LocalState) -> VortexResult { } } -/// The first chunk of `array`, leaving the rest in `pending` in reverse order. -/// -/// An array can join chunks of several layout chunks. Canonicalizing it would decode their -/// dictionaries, so export each chunk on its own. -fn split_chunks(pending: &mut Vec, array: ArrayRef) -> ArrayRef { - match array.as_opt::() { - Some(chunked) => { - pending.extend(chunked.chunks().into_iter().rev()); - pending.pop().unwrap_or(array) - } - None => array, - } -} - /// Called by all threads under global lock. If this function returns true, /// thread calls reader_scan on this file. If this function returns false, /// duckdb thinks file is exhausted, closes the file, and the first thread to diff --git a/vortex-layout/src/scan/split_queue.rs b/vortex-layout/src/scan/split_queue.rs index 49afc813c56..463eeb72828 100644 --- a/vortex-layout/src/scan/split_queue.rs +++ b/vortex-layout/src/scan/split_queue.rs @@ -37,6 +37,10 @@ type SplitTask = BoxFuture<'static, VortexResult>>; /// A worker yields only the splits it claimed, and claims a split only when it has room for one, /// so no worker waits on a split another one claimed. /// +/// A worker with room for one split has nothing to overlap it with, so it polls the split itself +/// rather than spawning it. The split then runs on the thread that polls the worker, which also +/// consumes its array, and no other thread driving the runtime picks it up. +/// /// [`RepeatedScan::execute`]: crate::scan::repeated_scan::RepeatedScan::execute pub(crate) struct SplitQueue { handle: Handle, @@ -76,9 +80,16 @@ impl SplitQueue { pub(crate) fn worker(self: Arc) -> BoxStream<'static, VortexResult> { let handle = self.handle.clone(); let per_worker = self.per_worker; + let splits = stream::iter(iter::from_fn(move || self.claim())); + if per_worker == 1 { + return splits + .then(|split| split) + .filter_map(|array| future::ready(array.transpose())) + .boxed(); + } // `buffer_unordered` pulls a split only when it has room, so a worker claims no more // than it runs. - stream::iter(iter::from_fn(move || self.claim())) + splits .map(move |split| handle.spawn(split)) .buffer_unordered(per_worker) .filter_map(|array| future::ready(array.transpose())) From db19654ba524ea507a1648dfb15312996077f7c6 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 15:26:23 -0500 Subject: [PATCH 53/80] Poll a worker's only split on the thread that reads it Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-layout/src/scan/split_queue.rs | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/vortex-layout/src/scan/split_queue.rs b/vortex-layout/src/scan/split_queue.rs index ba46fe3a263..c92071300fd 100644 --- a/vortex-layout/src/scan/split_queue.rs +++ b/vortex-layout/src/scan/split_queue.rs @@ -35,6 +35,10 @@ type SplitTask = BoxFuture<'static, VortexResult>>; /// A worker yields only the splits it claimed, and claims a split only when it has room for one, /// so no worker waits on a split another one claimed. /// +/// A worker with room for one split has nothing to overlap it with, so it polls the split itself +/// rather than spawning it. The split then runs on the thread that polls the worker, which also +/// consumes its array, and no other thread driving the runtime picks it up. +/// /// [`RepeatedScan::execute`]: crate::scan::repeated_scan::RepeatedScan::execute pub(crate) struct SplitQueue { handle: Handle, @@ -60,9 +64,16 @@ impl SplitQueue { pub(crate) fn worker(self: Arc) -> BoxStream<'static, VortexResult> { let handle = self.handle.clone(); let per_worker = self.per_worker; + let splits = stream::iter(iter::from_fn(move || self.claim())); + if per_worker == 1 { + return splits + .then(|split| split) + .filter_map(|array| future::ready(array.transpose())) + .boxed(); + } // `buffer_unordered` pulls a split only when it has room, so a worker claims no more // than it runs. - stream::iter(iter::from_fn(move || self.claim())) + splits .map(move |split| handle.spawn(split)) .buffer_unordered(per_worker) .filter_map(|array| future::ready(array.transpose())) From f93a16d78954c8f1bf1b5cdd4cdc69206cc9e4ef Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 16:26:21 -0500 Subject: [PATCH 54/80] 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 1c91d119b4366a5dc76e2dd107cd86224e1ae7ad Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 16:26:56 -0500 Subject: [PATCH 55/80] Cut layout scans into fixed pieces for every request Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-layout/src/scan/layout.rs | 31 ++++++++--------------- vortex-layout/src/scan/multi.rs | 43 +++++++++++++++----------------- 2 files changed, 30 insertions(+), 44 deletions(-) diff --git a/vortex-layout/src/scan/layout.rs b/vortex-layout/src/scan/layout.rs index 24755112d6f..ce883a459a5 100644 --- a/vortex-layout/src/scan/layout.rs +++ b/vortex-layout/src/scan/layout.rs @@ -41,7 +41,6 @@ use vortex_scan::PartitionStream; use vortex_scan::ScanRequest; use vortex_scan::selection::Selection; use vortex_scan::stream::ScanStream; -use vortex_scan::stream::split_shared; use vortex_session::VortexSession; use crate::LayoutReaderRef; @@ -284,18 +283,14 @@ impl DataSourceScan for LayoutReaderScan { &self.dtype } - /// Splits an unordered scan into `n` pieces that share its opened stream, and so its - /// splits. Cuts an ordered scan at the layout's natural split boundaries, into contiguous - /// pieces of about equal rows. + /// Cuts the scan at the layout's natural split boundaries, into contiguous pieces of about + /// equal rows. /// /// A scan with a limit stays whole, because the limit is one budget across all its rows. fn split(self: Box, n: NonZeroUsize) -> VortexResult> { if n.get() == 1 || self.remaining_limit.is_some() || self.next_row >= self.end_row { return Ok(vec![self]); } - if !self.ordered { - return split_shared(self, n); - } let ranges = self .builder() .prepare()? @@ -793,25 +788,19 @@ mod split_open_tests { Ok(()) } - /// The pieces of an unordered scan share its splits, so together they read every row once. + /// The pieces of an unordered scan are fixed too: each owns a contiguous run of splits, + /// which it may return in any order. #[test] - fn unordered_pieces_share_the_splits() -> VortexResult<()> { + fn unordered_pieces_own_their_rows() -> VortexResult<()> { let runtime = SingleThreadRuntime::default(); let scan = runtime.block_on(source(&runtime).scan(ScanRequest::default()))?; let pieces = scan.split(NonZeroUsize::try_from(4)?)?; assert_eq!(pieces.len(), 4); - let streams = pieces - .into_iter() - .map(|piece| piece.open()) - .collect::>>()?; - let arrays = runtime.block_on(try_join_all( - streams - .into_iter() - .map(|stream| stream.try_collect::>()), - ))?; - let mut values = collect_scan_values(arrays.into_iter().flatten().map(Ok))?; - values.sort_unstable(); - assert_eq!(values, (0..64).collect::>()); + for (i, piece) in (0i32..).zip(pieces) { + let mut values = collect_scan_values(runtime.block_on_stream(piece.open()?))?; + values.sort_unstable(); + assert_eq!(values, (16 * i..16 * (i + 1)).collect::>()); + } Ok(()) } diff --git a/vortex-layout/src/scan/multi.rs b/vortex-layout/src/scan/multi.rs index 00d35271434..9e9ad36264b 100644 --- a/vortex-layout/src/scan/multi.rs +++ b/vortex-layout/src/scan/multi.rs @@ -60,7 +60,6 @@ use vortex_scan::PartitionStream; use vortex_scan::ScanRequest; use vortex_scan::selection::Selection; use vortex_scan::stream::ScanStream; -use vortex_scan::stream::split_shared; use vortex_session::VortexSession; use vortex_utils::parallelism::get_available_parallelism; @@ -415,11 +414,9 @@ impl DataSourceScan for MultiLayoutScan { &self.dtype } - /// Splits an unordered scan into `n` clones of its opened partition stream, which share its - /// files. Cuts an ordered scan into at most `n` contiguous pieces in file order, reading - /// metadata only. + /// Cuts the scan into at most `n` contiguous pieces in file order, reading metadata only. /// - /// With at least `n` files, each ordered piece is a run of whole files. The runs balance the + /// With at least `n` files, each piece is a run of whole files. The runs balance the /// files' byte sizes when every size is known, and their counts otherwise. With fewer files, /// each file gets a share of the `n` pieces in proportion to its size, at least one, and no /// piece holds parts of two files. A file that is open is cut at its natural split @@ -427,17 +424,14 @@ impl DataSourceScan for MultiLayoutScan { /// opening it, so the scan may return fewer than `n` pieces. /// /// A scan with a limit stays whole, because the limit is one budget across all its files. - /// So does an ordered one that selects partitions, because partition indices count from its - /// first file. + /// So does one that selects partitions, because partition indices count from its first + /// file. fn split(self: Box, n: NonZeroUsize) -> VortexResult> { let files = self.ready.len() + self.deferred.len(); - if n.get() == 1 || files == 0 || self.request.limit.is_some() { - return Ok(vec![self]); - } - if !self.request.ordered { - return split_shared(self, n); - } - if self.request.partition_range.is_some() + if n.get() == 1 + || files == 0 + || self.request.limit.is_some() + || self.request.partition_range.is_some() || !matches!(self.request.partition_selection, Selection::All) { return Ok(vec![self]); @@ -1123,9 +1117,10 @@ mod tests { Ok(()) } - /// The pieces of an unordered scan share its files, so together they read every row once. + /// The pieces of an unordered scan are fixed: each owns its files' rows. Files that cannot + /// be cut stay whole, so there may be fewer pieces than asked for. #[test] - fn unordered_pieces_share_the_files() -> VortexResult<()> { + fn unordered_pieces_own_their_files() -> VortexResult<()> { let runtime = SingleThreadRuntime::default(); let session = session_with_handle(runtime.handle()); let first: LayoutReaderRef = Arc::new(TestLayoutReader::new(2)); @@ -1140,13 +1135,15 @@ mod tests { let scan = runtime.block_on(source.scan(ScanRequest::default()))?; let pieces = scan.split(NonZeroUsize::try_from(5)?)?; - assert_eq!(pieces.len(), 5); - let mut values = Vec::new(); - for piece in pieces { - values.extend(piece_values(&runtime, piece)?); - } - values.sort_unstable(); - assert_eq!(values, [0, 1, 10, 11, 20, 21]); + let pieces = pieces + .into_iter() + .map(|piece| { + let mut values = piece_values(&runtime, piece)?; + values.sort_unstable(); + Ok(values) + }) + .collect::>>()?; + assert_eq!(pieces, [vec![0, 1], vec![10, 11], vec![20, 21]]); Ok(()) } From 9d11499b18c9ec04f75dcd53290a94af5072a459 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 16:27:47 -0500 Subject: [PATCH 56/80] Share unordered scan work through clones of one opened stream Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-datafusion/src/v2/source.rs | 85 ++++++++++++++++++++---------- 1 file changed, 58 insertions(+), 27 deletions(-) diff --git a/vortex-datafusion/src/v2/source.rs b/vortex-datafusion/src/v2/source.rs index b704cdb3cb5..1a3f3fe9cd9 100644 --- a/vortex-datafusion/src/v2/source.rs +++ b/vortex-datafusion/src/v2/source.rs @@ -139,6 +139,7 @@ use vortex::scan::DataSourceScanRef; use vortex::scan::PartitionRef; use vortex::scan::PartitionStream; use vortex::scan::ScanRequest; +use vortex::scan::stream::ScanStream; use vortex::session::VortexSession; use vortex_arrow::ArrowArrayStreamExt; use vortex_arrow::ArrowSessionExt; @@ -202,8 +203,9 @@ pub struct VortexDataSourceBuilder { } /// The environment variable that selects how [`VortexDataSource`] reads its scan: `0` reads the -/// scan's shared partition stream, anything else (the default) splits it into one piece per output -/// partition. +/// scan's shared partition stream, anything else (the default) reads it through +/// [`DataSourceScan::open`](vortex::scan::DataSourceScan::open) and +/// [`DataSourceScan::split`](vortex::scan::DataSourceScan::split). /// /// It exists to compare the two in one binary, and goes away with the partition stream. pub const SCAN_POOL_ENV: &str = "VORTEX_SCAN_POOL"; @@ -267,8 +269,8 @@ impl VortexDataSourceBuilder { self } - /// Selects whether each output partition reads its own piece of the split scan (`true`) or - /// takes partitions from the scan's shared partition stream (`false`). Defaults to + /// Selects whether output partitions read the scan through its `open` and `split` (`true`) or + /// take partitions from the scan's shared partition stream (`false`). Defaults to /// [`SCAN_POOL_ENV`], read when the builder is created. pub fn with_split_scan(mut self, split_scan: bool) -> Self { self.split_scan = split_scan; @@ -407,20 +409,26 @@ impl VortexDataSource { /// Unordered scans expose the requested DataFusion output partitions; a scan with a declared /// global ordering uses one output partition. /// -/// Each execution [splits] the scan once into one piece per output partition, through -/// [`DataSource::create_sibling_state`]: the first output partition polled starts the scan and -/// splits it, and output partition `i` reads piece `i`. Partitions beyond the piece count return -/// no rows. The source decides what the pieces are: the pieces of an unordered scan may share one -/// queue of work, so partitions that finish early keep reading, while an ordered scan's pieces are -/// fixed and in order. Setting [`SCAN_POOL_ENV`] to `0` instead has the output partitions take -/// partitions from one shared partition stream, for comparison. +/// Each execution scans once, through [`DataSource::create_sibling_state`], and the first output +/// partition polled starts the scan. Like DataFusion's own file scans, the output partitions share +/// the work unless each must keep its rows in order: /// -/// In either mode an output partition holds work that no other partition reads: its piece, or the -/// partitions it has taken. Dropping an output partition before it finishes therefore cancels its +/// - An unordered scan is [opened] once, and every output partition reads a clone of its stream, +/// so partitions that finish early keep taking work. +/// - A scan whose output partitions must each keep their order is [split] into one fixed piece per +/// output partition, and output partition `i` reads piece `i` in order. Partitions beyond the +/// piece count return no rows. +/// +/// Setting [`SCAN_POOL_ENV`] to `0` instead has the output partitions take partitions from one +/// shared partition stream, for comparison. +/// +/// In every mode an output partition holds work that no other partition reads: the work its clone +/// has taken, its piece, or the partitions it has taken. Dropping an output partition before it finishes therefore cancels its /// execution, and the other output partitions report an error rather than finish without those /// rows. /// -/// [splits]: vortex::scan::DataSourceScan::split +/// [opened]: vortex::scan::DataSourceScan::open +/// [split]: vortex::scan::DataSourceScan::split /// /// Use [`crate::VortexSource`] instead when DataFusion should discover and plan /// `.vortex` files on its own. @@ -479,7 +487,7 @@ pub struct VortexDataSource { /// Target Arrow conversion concurrency when only one output partition is exposed. target_parallelism: usize, - /// Whether each output partition reads its own piece of the split scan rather than taking + /// Whether output partitions read the scan through its `open` and `split` rather than taking /// partitions from the scan's shared partition stream, which keeps one output partition for a /// limited scan. split_scan: bool, @@ -550,6 +558,7 @@ impl VortexDataSource { .map_err(Clone::clone)?; let arrays = match work { ScanWork::Partitions(partitions) => Arc::clone(partitions).arrays(ordered), + ScanWork::Stream(shared) => ArrayStreamExt::boxed(shared.clone()), ScanWork::Pieces(pieces) => { let piece = match pieces.get(partition) { Some(piece) => piece.lock().await.take(), @@ -663,8 +672,6 @@ fn invalid_partition(partition: usize) -> DataFusionError { /// The scan that every output partition of one execution reads. /// /// The first output partition polled starts the scan; every other partition reads the same one. -/// The pieces of a split must come from one call to `split`: an unordered source may have its -/// pieces share one queue of work, so pieces from separate calls would each read every row. struct ScanExecution { split: bool, output_partitions: Vec, @@ -681,6 +688,8 @@ struct OutputPartitionState { enum ScanWork { /// Every output partition takes partitions from this shared stream. Partitions(Arc), + /// Every output partition reads a clone of the opened scan's stream. + Stream(ScanStream), /// Output partition `i` takes piece `i`, if there is one. Pieces(Vec>>), } @@ -721,7 +730,8 @@ impl ScanExecution { } } } - Some(Err(_)) | None => {} + // The clones that output partitions hold end with the execution's error. + Some(Ok(ScanWork::Stream(_)) | Err(_)) | None => {} } } @@ -730,6 +740,7 @@ impl ScanExecution { data_source: DataSourceRef, request: ScanRequest, ) -> VortexResult { + let ordered = request.ordered; let scan = data_source.scan(request).await?; if !self.split { return Ok(ScanWork::Partitions(Arc::new(SharedPartitions { @@ -737,6 +748,9 @@ impl ScanExecution { partitions: AsyncMutex::new(Some(scan.partitions())), }))); } + if !ordered { + return Ok(ScanWork::Stream(scan.open()?)); + } let pieces = NonZeroUsize::new(self.output_partitions.len()).unwrap_or(NonZeroUsize::MIN); Ok(ScanWork::Pieces( scan.split(pieces)? @@ -1217,7 +1231,6 @@ mod tests { use vortex::scan::Partition; use vortex::scan::PartitionRef; use vortex::scan::PartitionStream; - use vortex::scan::stream::ScanStream; use vortex::session::VortexSession; use vortex_arrow::ArrowSessionExt; @@ -1493,10 +1506,16 @@ mod tests { Ok(()) } - /// One execution scans and splits once, lazily, and output partition `i` reads piece `i`; - /// partitions beyond the piece count return no rows, and a reset execution scans again. + /// One execution scans once, lazily, and a reset execution scans again. Unordered output + /// partitions share the opened scan's work; output partitions that keep their order read piece + /// `i` of one split, and partitions beyond the piece count return no rows. + #[rstest] + #[case::shared_work(false)] + #[case::ordered_pieces(true)] #[tokio::test] - async fn output_partitions_read_the_pieces_of_one_split() -> anyhow::Result<()> { + async fn output_partitions_read_one_scan_per_execution( + #[case] preserve_order: bool, + ) -> anyhow::Result<()> { let scans = Arc::new(AtomicUsize::new(0)); let data_source: DataSourceRef = Arc::new(TestDataSource { dtype: test_dtype(), @@ -1526,6 +1545,13 @@ mod tests { .with_fetch(Some(1)) .expect("fetch bounds each partition"); assert_eq!(fetched.output_partitioning().partition_count(), 4); + let source = if preserve_order { + source + .with_preserve_order(true) + .expect("order preserved per partition") + } else { + source + }; let plan = Arc::new(DataSourceExec::new(Arc::clone(&source))) as Arc; let context = Arc::new(TaskContext::default()); @@ -1538,7 +1564,13 @@ mod tests { let batches: Vec = stream.try_collect().await?; partitions.push(partition_values(&batches)); } - assert_eq!(partitions, [vec![0, 1], vec![100, 101], vec![], vec![]]); + if preserve_order { + assert_eq!(partitions, [vec![0, 1], vec![100, 101], vec![], vec![]]); + } else { + let mut values = partitions.concat(); + values.sort_unstable(); + assert_eq!(values, [0, 1, 100, 101]); + } assert_eq!(scans.load(Ordering::Relaxed), 1); assert_eq!(plan.metrics().expect("scan metrics").output_rows(), Some(4)); assert!(plan.execute(0, Arc::clone(&context)).is_err()); @@ -1550,7 +1582,7 @@ mod tests { assert_eq!(values, [0, 1, 100, 101]); assert_eq!(scans.load(Ordering::Relaxed), 2); - // Without sibling state, several partitions cannot share one split. + // Without sibling state, several partitions cannot share one scan. assert!(source.open(0, context).is_err()); Ok(()) } @@ -1591,7 +1623,7 @@ mod tests { .collect() } - /// Without the split, output partitions share the scan's partition stream: a + /// Without `open` and `split`, output partitions share the scan's partition stream: a /// fetch keeps one partition, and direct opens need a single partition. #[tokio::test] async fn without_split_scan_partitions_share_the_partition_stream() -> anyhow::Result<()> { @@ -1679,8 +1711,7 @@ mod tests { Ok(()) } - /// A fetch bounds each of several output partitions. A limited scan cannot be cut, so its - /// one piece goes to the first partition. + /// A fetch bounds each of several output partitions, which share the opened scan's work. #[tokio::test] async fn fetch_bounds_each_of_several_partitions() -> anyhow::Result<()> { let (data_source, session, schema) = split_file_source().await?; From 4fa814171a2d24e7111bc5089e6c4eba3318f790 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 16:27:48 -0500 Subject: [PATCH 57/80] Describe the read-ahead without reference to split Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-layout/src/scan/multi.rs | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/vortex-layout/src/scan/multi.rs b/vortex-layout/src/scan/multi.rs index 9e9ad36264b..c092f37eca7 100644 --- a/vortex-layout/src/scan/multi.rs +++ b/vortex-layout/src/scan/multi.rs @@ -71,8 +71,7 @@ use crate::scan::scan_builder::ScanBuilder; /// How many files each clone of an unordered scan's opened stream reads at once. /// /// This matches the read-ahead of the DataFusion `VortexTable` path on develop -/// (`SCAN_PARTITION_READ_AHEAD`), so that reading a scan through `open` and through `split` -/// behaves the same. +/// (`SCAN_PARTITION_READ_AHEAD`), whose partitions share one stream of files as the clones do. const PARTITION_READ_AHEAD: usize = 2; /// Default concurrency for opening deferred readers. @@ -573,8 +572,7 @@ impl DataSourceScan for MultiLayoutScan { Some((next, shared)) }) .map(|partition| partition.and_then(|partition| partition.execute())) - // Matches the DataFusion `VortexTable` path's read-ahead on develop, so a scan read - // through `open` behaves as one read through `split`. + // Matches the read-ahead of the DataFusion `VortexTable` path on develop. .try_flatten_unordered(Some(PARTITION_READ_AHEAD)) .boxed() })) From c102c2c5ab43e9cff1a550a7d7146ed6db71204b Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 16:30:10 -0500 Subject: [PATCH 58/80] Read declared orderings through one ordered split piece per partition Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-datafusion/src/v2/source.rs | 40 ++++++++++++++++++++++++------ 1 file changed, 32 insertions(+), 8 deletions(-) diff --git a/vortex-datafusion/src/v2/source.rs b/vortex-datafusion/src/v2/source.rs index 1a3f3fe9cd9..437482921e9 100644 --- a/vortex-datafusion/src/v2/source.rs +++ b/vortex-datafusion/src/v2/source.rs @@ -406,8 +406,9 @@ impl VortexDataSource { /// During execution, it builds the final Vortex [`ScanRequest`] from the /// current projection, pushed filters, ordering hints, and row limit. /// -/// Unordered scans expose the requested DataFusion output partitions; a scan with a declared -/// global ordering uses one output partition. +/// A scan exposes the requested DataFusion output partitions. With a declared ordering, each output +/// partition keeps that ordering, as a sorted file group does in DataFusion's own file scans, and +/// DataFusion merges the partitions where it needs one global order. /// /// Each execution scans once, through [`DataSource::create_sibling_state`], and the first output /// partition polled starts the scan. Like DataFusion's own file scans, the output partitions share @@ -415,8 +416,9 @@ impl VortexDataSource { /// /// - An unordered scan is [opened] once, and every output partition reads a clone of its stream, /// so partitions that finish early keep taking work. -/// - A scan whose output partitions must each keep their order is [split] into one fixed piece per -/// output partition, and output partition `i` reads piece `i` in order. Partitions beyond the +/// - A scan with a declared ordering, or whose output partitions DataFusion asks to keep their +/// order, is [split] into one fixed piece per output partition, and output partition `i` reads +/// piece `i` in order. The pieces are contiguous, so each partition keeps the ordering. Partitions beyond the /// piece count return no rows. /// /// Setting [`SCAN_POOL_ENV`] to `0` instead has the output partitions take partitions from one @@ -479,7 +481,7 @@ pub struct VortexDataSource { dynamic_filters: Vec>, /// An optional row limit populated by [`DataSource::with_fetch`]. limit: Option, - /// Whether to preserve a declared global order, which keeps one output partition. + /// Whether to preserve a declared ordering in each output partition. ordered: bool, /// Whether each output partition must return its rows in order, as DataFusion requests /// through [`DataSource::with_preserve_order`]. @@ -506,7 +508,8 @@ impl fmt::Debug for VortexDataSource { impl VortexDataSource { fn output_partition_count(&self) -> usize { - if self.ordered || (!self.split_scan && self.limit.is_some()) { + // The shared partition stream keeps an ordering only in one output partition. + if !self.split_scan && (self.ordered || self.limit.is_some()) { 1 } else { self.output_partitions @@ -1746,7 +1749,7 @@ mod tests { } #[tokio::test] - async fn proven_ordering_keeps_one_output_partition_and_remaps_identity_outputs() + async fn proven_ordering_holds_in_each_output_partition_and_remaps_identity_outputs() -> anyhow::Result<()> { let data_source: DataSourceRef = Arc::new(TestDataSource { dtype: test_dtype(), @@ -1759,12 +1762,33 @@ mod tests { LexOrdering::new([PhysicalSortExpr::new_default(Arc::clone(&key))]) .expect("one key"), ) + .with_split_scan(true) .build() .await?; + let mut shared_partitions = source.clone(); + shared_partitions.split_scan = false; + let shared_partitions = shared_partitions + .repartitioned(4, 0, None)? + .expect("repartitioning supported"); + assert_eq!(shared_partitions.output_partitioning().partition_count(), 1); + + // Output partition `i` reads piece `i` of the split, in order. let source = source .repartitioned(4, 0, None)? .expect("repartitioning supported"); - assert_eq!(source.output_partitioning().partition_count(), 1); + assert_eq!(source.output_partitioning().partition_count(), 4); + let plan = Arc::new(DataSourceExec::new(Arc::clone(&source))) as Arc; + let context = Arc::new(TaskContext::default()); + let mut partitions = Vec::new(); + for partition in 0..4 { + let batches: Vec = plan + .execute(partition, Arc::clone(&context))? + .try_collect() + .await?; + partitions.push(partition_values(&batches)); + } + assert_eq!(partitions, [vec![0, 1], vec![100, 101], vec![], vec![]]); + let projected = source .try_swapping_with_projection(&ProjectionExprs::from(vec![ProjectionExpr::new( Arc::clone(&key), From c55c0471036ec36811bcb788b6063046ca0ea83d Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 16:39:07 -0500 Subject: [PATCH 59/80] Hold the shared scan stream behind a mutex so the execution is Sync Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-datafusion/src/v2/source.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/vortex-datafusion/src/v2/source.rs b/vortex-datafusion/src/v2/source.rs index 437482921e9..8dfd5fdb4c3 100644 --- a/vortex-datafusion/src/v2/source.rs +++ b/vortex-datafusion/src/v2/source.rs @@ -561,7 +561,7 @@ impl VortexDataSource { .map_err(Clone::clone)?; let arrays = match work { ScanWork::Partitions(partitions) => Arc::clone(partitions).arrays(ordered), - ScanWork::Stream(shared) => ArrayStreamExt::boxed(shared.clone()), + ScanWork::Stream(shared) => ArrayStreamExt::boxed(shared.lock().await.clone()), ScanWork::Pieces(pieces) => { let piece = match pieces.get(partition) { Some(piece) => piece.lock().await.take(), @@ -691,8 +691,8 @@ struct OutputPartitionState { enum ScanWork { /// Every output partition takes partitions from this shared stream. Partitions(Arc), - /// Every output partition reads a clone of the opened scan's stream. - Stream(ScanStream), + /// Every output partition reads a clone of the opened scan's stream, which is not `Sync`. + Stream(AsyncMutex), /// Output partition `i` takes piece `i`, if there is one. Pieces(Vec>>), } @@ -752,7 +752,7 @@ impl ScanExecution { }))); } if !ordered { - return Ok(ScanWork::Stream(scan.open()?)); + return Ok(ScanWork::Stream(AsyncMutex::new(scan.open()?))); } let pieces = NonZeroUsize::new(self.output_partitions.len()).unwrap_or(NonZeroUsize::MIN); Ok(ScanWork::Pieces( From 2322eea54874c9a70e92546157564dca6000db54 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 16:46:29 -0500 Subject: [PATCH 60/80] Move RowLimit and limit_rows into vortex-scan Scans in vortex-scan need the row budget that layout scans share, so the budget and the stream adapter that trims to it move down a crate and vortex-layout uses them from there. Signed-off-by: Nicholas Gates Co-Authored-By: Claude Fable 5.2 --- vortex-layout/src/scan/limit.rs | 123 +---------------- vortex-layout/src/scan/repeated_scan.rs | 41 +----- vortex-scan/src/lib.rs | 1 + vortex-scan/src/limit.rs | 173 ++++++++++++++++++++++++ 4 files changed, 177 insertions(+), 161 deletions(-) create mode 100644 vortex-scan/src/limit.rs diff --git a/vortex-layout/src/scan/limit.rs b/vortex-layout/src/scan/limit.rs index e7791e5961f..42e69a54a56 100644 --- a/vortex-layout/src/scan/limit.rs +++ b/vortex-layout/src/scan/limit.rs @@ -1,22 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors -use std::sync::Arc; -use std::sync::atomic::AtomicU64; -use std::sync::atomic::Ordering; - -use vortex_error::VortexExpect; -use vortex_mask::Mask; - -/// A cloneable row budget shared by all work that can contribute rows to one scan. -/// -/// Filterless scans reserve each split's selected rows before constructing its projection, so -/// rows past the limit are never decoded. Filtered scans cannot know a split's row count up front, -/// so they take rows from the budget as arrays are emitted and discard the excess. Either way, -/// the order in which rows are taken decides which rows are returned: an ordered scan takes them -/// in split order, an unordered one in completion order. -#[derive(Clone)] -pub(crate) struct RowLimit(Arc); +pub(crate) use vortex_scan::limit::RowLimit; /// The row limit of a scan. #[derive(Clone)] @@ -36,109 +21,3 @@ impl ScanLimit { } } } - -impl RowLimit { - pub(crate) fn new(limit: u64) -> Self { - Self(Arc::new(AtomicU64::new(limit))) - } - - /// Reserve rows selected by `mask` and retain only the earliest granted rows in that mask. - pub(crate) fn limit(&self, mask: Mask) -> Mask { - let granted = self.take(mask.true_count()); - mask.limit(granted) - } - - /// Reserve up to `rows` rows, returning how many the remaining budget granted. - pub(crate) fn take(&self, rows: usize) -> usize { - let requested = u64::try_from(rows).unwrap_or(u64::MAX); - usize::try_from(self.reserve(requested)).unwrap_or(usize::MAX) - } - - pub(crate) fn is_exhausted(&self) -> bool { - self.0.load(Ordering::Relaxed) == 0 - } - - fn reserve(&self, requested: u64) -> u64 { - let remaining = self - .0 - .try_update(Ordering::Relaxed, Ordering::Relaxed, |remaining| { - Some(remaining.saturating_sub(requested)) - }) - .ok() - .vortex_expect("row reservation always updates the budget"); - remaining.min(requested) - } -} - -#[cfg(test)] -mod tests { - use std::sync::Arc; - use std::sync::Barrier; - use std::sync::atomic::AtomicU64; - use std::sync::atomic::Ordering; - use std::thread; - - use vortex_mask::Mask; - - use super::RowLimit; - - #[test] - fn reserve_grants_up_to_the_remaining_budget() { - let limit = RowLimit::new(5); - assert_eq!(limit.reserve(3), 3); - assert!(!limit.is_exhausted()); - // Only two rows remain, so a larger request saturates at what is left. - assert_eq!(limit.reserve(10), 2); - assert!(limit.is_exhausted()); - // Once exhausted, further requests grant nothing. - assert_eq!(limit.reserve(1), 0); - } - - #[test] - fn limit_keeps_the_earliest_granted_rows() { - let limit = RowLimit::new(2); - // Rows 0, 2, 3, 5 are selected; only the first two survive the budget of 2. - let mask = Mask::from_iter([true, false, true, true, false, true]); - let limited = limit.limit(mask); - - assert_eq!(limited.true_count(), 2); - assert!(limited.value(0)); - assert!(limited.value(2)); - assert!(!limited.value(3)); - assert!(!limited.value(5)); - assert!(limit.is_exhausted()); - } - - #[test] - fn concurrent_reservations_never_exceed_the_budget() { - const THREADS: usize = 8; - const PER_THREAD: u64 = 10_000; - const LIMIT: u64 = 25_000; - - let limit = RowLimit::new(LIMIT); - let granted_total = Arc::new(AtomicU64::new(0)); - let barrier = Arc::new(Barrier::new(THREADS)); - - thread::scope(|scope| { - for _ in 0..THREADS { - let limit = limit.clone(); - let granted_total = Arc::clone(&granted_total); - let barrier = Arc::clone(&barrier); - scope.spawn(move || { - // Start all threads together to maximize contention on the atomic. - barrier.wait(); - let mut local = 0; - for _ in 0..PER_THREAD { - local += limit.reserve(1); - } - granted_total.fetch_add(local, Ordering::Relaxed); - }); - } - }); - - // Total requested (THREADS * PER_THREAD = 80_000) exceeds the budget, so exactly the - // budget is granted across all threads — no double-grant, over-grant, or lost reservation. - assert_eq!(granted_total.load(Ordering::Relaxed), LIMIT); - assert!(limit.is_exhausted()); - } -} diff --git a/vortex-layout/src/scan/repeated_scan.rs b/vortex-layout/src/scan/repeated_scan.rs index 1a950fec418..2d82f283dc4 100644 --- a/vortex-layout/src/scan/repeated_scan.rs +++ b/vortex-layout/src/scan/repeated_scan.rs @@ -14,7 +14,6 @@ use futures::Stream; use futures::StreamExt; use futures::future; use futures::future::BoxFuture; -use futures::ready; use futures::stream; use futures::stream::BoxStream; use itertools::Either; @@ -32,6 +31,7 @@ use vortex_error::VortexResult; use vortex_error::vortex_bail; use vortex_io::runtime::BlockingRuntime; use vortex_io::session::RuntimeSessionExt; +use vortex_scan::limit::limit_rows; use vortex_scan::row_mask::RowMask; use vortex_scan::selection::Selection; use vortex_session::VortexSession; @@ -384,43 +384,6 @@ fn map_split( .boxed() } -/// Trim arrays to the budget and drop upstream work as soon as it is exhausted. -fn limit_rows( - arrays: BoxStream<'static, VortexResult>, - limit: RowLimit, -) -> BoxStream<'static, VortexResult> { - let mut arrays = Some(arrays); - stream::poll_fn(move |cx| { - loop { - if limit.is_exhausted() { - arrays = None; - } - let Some(stream) = arrays.as_mut() else { - return Poll::Ready(None); - }; - let array = match ready!(stream.poll_next_unpin(cx)) { - Some(Ok(array)) => array, - end => { - arrays = None; - return Poll::Ready(end); - } - }; - let granted = limit.take(array.len()); - if limit.is_exhausted() { - arrays = None; - } - if granted != 0 { - return Poll::Ready(Some(if granted < array.len() { - array.slice(0..granted) - } else { - Ok(array) - })); - } - } - }) - .boxed() -} - /// Yield the first error and drop upstream without polling it again. fn stop_on_error( stream: BoxStream<'static, VortexResult>, @@ -505,9 +468,9 @@ mod tests { use vortex_array::arrays::PrimitiveArray; use vortex_error::VortexResult; use vortex_error::vortex_err; + use vortex_scan::limit::limit_rows; use super::SplitConcurrency; - use super::limit_rows; use super::stop_on_error; use crate::scan::limit::RowLimit; diff --git a/vortex-scan/src/lib.rs b/vortex-scan/src/lib.rs index 0c355a1a428..d693b1d3bb8 100644 --- a/vortex-scan/src/lib.rs +++ b/vortex-scan/src/lib.rs @@ -24,6 +24,7 @@ pub mod arrays; pub mod execution; +pub mod limit; pub mod plan; pub mod planning; pub mod prepare; diff --git a/vortex-scan/src/limit.rs b/vortex-scan/src/limit.rs new file mode 100644 index 00000000000..845a7525d89 --- /dev/null +++ b/vortex-scan/src/limit.rs @@ -0,0 +1,173 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Row limits that the work of one scan shares. + +use std::sync::Arc; +use std::sync::atomic::AtomicU64; +use std::sync::atomic::Ordering; +use std::task::Poll; + +use futures::StreamExt; +use futures::ready; +use futures::stream; +use futures::stream::BoxStream; +use vortex_array::ArrayRef; +use vortex_error::VortexExpect; +use vortex_error::VortexResult; +use vortex_mask::Mask; + +/// A cloneable row budget shared by all work that can contribute rows to one scan. +/// +/// Filterless scans reserve each split's selected rows before constructing its projection, so +/// rows past the limit are never decoded. Filtered scans cannot know a split's row count up front, +/// so they take rows from the budget as arrays are emitted and discard the excess. Either way, +/// the order in which rows are taken decides which rows are returned: an ordered scan takes them +/// in split order, an unordered one in completion order. +#[derive(Clone)] +pub struct RowLimit(Arc); + +impl RowLimit { + /// A budget of `limit` rows. + pub fn new(limit: u64) -> Self { + Self(Arc::new(AtomicU64::new(limit))) + } + + /// Reserve rows selected by `mask` and retain only the earliest granted rows in that mask. + pub fn limit(&self, mask: Mask) -> Mask { + let granted = self.take(mask.true_count()); + mask.limit(granted) + } + + /// Reserve up to `rows` rows, returning how many the remaining budget granted. + pub fn take(&self, rows: usize) -> usize { + let requested = u64::try_from(rows).unwrap_or(u64::MAX); + usize::try_from(self.reserve(requested)).unwrap_or(usize::MAX) + } + + /// Whether the budget is spent. + pub fn is_exhausted(&self) -> bool { + self.0.load(Ordering::Relaxed) == 0 + } + + fn reserve(&self, requested: u64) -> u64 { + let remaining = self + .0 + .try_update(Ordering::Relaxed, Ordering::Relaxed, |remaining| { + Some(remaining.saturating_sub(requested)) + }) + .ok() + .vortex_expect("row reservation always updates the budget"); + remaining.min(requested) + } +} + +/// Trim arrays to the budget and drop upstream work as soon as it is exhausted. +pub fn limit_rows( + arrays: BoxStream<'static, VortexResult>, + limit: RowLimit, +) -> BoxStream<'static, VortexResult> { + let mut arrays = Some(arrays); + stream::poll_fn(move |cx| { + loop { + if limit.is_exhausted() { + arrays = None; + } + let Some(stream) = arrays.as_mut() else { + return Poll::Ready(None); + }; + let array = match ready!(stream.poll_next_unpin(cx)) { + Some(Ok(array)) => array, + end => { + arrays = None; + return Poll::Ready(end); + } + }; + let granted = limit.take(array.len()); + if limit.is_exhausted() { + arrays = None; + } + if granted != 0 { + return Poll::Ready(Some(if granted < array.len() { + array.slice(0..granted) + } else { + Ok(array) + })); + } + } + }) + .boxed() +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + use std::sync::Barrier; + use std::sync::atomic::AtomicU64; + use std::sync::atomic::Ordering; + use std::thread; + + use vortex_mask::Mask; + + use super::RowLimit; + + #[test] + fn reserve_grants_up_to_the_remaining_budget() { + let limit = RowLimit::new(5); + assert_eq!(limit.reserve(3), 3); + assert!(!limit.is_exhausted()); + // Only two rows remain, so a larger request saturates at what is left. + assert_eq!(limit.reserve(10), 2); + assert!(limit.is_exhausted()); + // Once exhausted, further requests grant nothing. + assert_eq!(limit.reserve(1), 0); + } + + #[test] + fn limit_keeps_the_earliest_granted_rows() { + let limit = RowLimit::new(2); + // Rows 0, 2, 3, 5 are selected; only the first two survive the budget of 2. + let mask = Mask::from_iter([true, false, true, true, false, true]); + let limited = limit.limit(mask); + + assert_eq!(limited.true_count(), 2); + assert!(limited.value(0)); + assert!(limited.value(2)); + assert!(!limited.value(3)); + assert!(!limited.value(5)); + assert!(limit.is_exhausted()); + } + + #[test] + fn concurrent_reservations_never_exceed_the_budget() { + const THREADS: usize = 8; + const PER_THREAD: u64 = 10_000; + const LIMIT: u64 = 25_000; + + let limit = RowLimit::new(LIMIT); + let granted_total = Arc::new(AtomicU64::new(0)); + let barrier = Arc::new(Barrier::new(THREADS)); + + thread::scope(|scope| { + for _ in 0..THREADS { + let limit = limit.clone(); + let granted_total = Arc::clone(&granted_total); + let barrier = Arc::clone(&barrier); + scope.spawn(move || { + // Start all threads together to maximize contention on the atomic. + barrier.wait(); + let mut local = 0; + for _ in 0..PER_THREAD { + local += limit.reserve(1); + } + granted_total.fetch_add(local, Ordering::Relaxed); + }); + } + }); + + // Total requested (THREADS * PER_THREAD = 80_000) exceeds the budget, so exactly the + // budget is granted across all threads — no double-grant, over-grant, or lost reservation. + assert_eq!(granted_total.load(Ordering::Relaxed), LIMIT); + assert!(limit.is_exhausted()); + } +} From 8c50bcffba13740439e569127263e49c1c043822 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 16:46:59 -0500 Subject: [PATCH 61/80] Move the V2 part planner into vortex-scan Every host that reads a prepared V2 scan in parts should cut it the same way, so DuckDB's part planner becomes vortex_scan::prepare::part_root and DuckDB calls it. The code moves unchanged. Signed-off-by: Nicholas Gates Co-Authored-By: Claude Fable 5.2 --- vortex-duckdb/src/scan_v2.rs | 159 +-------------------------- vortex-scan/src/execution/mod.rs | 2 + vortex-scan/src/execution/parts.rs | 170 +++++++++++++++++++++++++++++ vortex-scan/src/prepare.rs | 1 + 4 files changed, 175 insertions(+), 157 deletions(-) create mode 100644 vortex-scan/src/execution/parts.rs diff --git a/vortex-duckdb/src/scan_v2.rs b/vortex-duckdb/src/scan_v2.rs index 4c778d14acf..cc8fc4305d5 100644 --- a/vortex-duckdb/src/scan_v2.rs +++ b/vortex-duckdb/src/scan_v2.rs @@ -14,7 +14,6 @@ use std::collections::VecDeque; use std::future; -use std::ops::Range; use std::sync::Arc; use std::sync::atomic::AtomicBool; use std::sync::atomic::AtomicU64; @@ -22,25 +21,16 @@ use std::sync::atomic::Ordering; use parking_lot::Mutex; use vortex::array::ArrayRef; -use vortex::error::VortexExpect; use vortex::error::VortexResult; -use vortex::io::request::IoConsumer; -use vortex::io::request::IoRequestId; -use vortex::io::request::IoResult; use vortex::io::request::IoService; use vortex::io::runtime::BlockingRuntime as _; use vortex::layout::scan::v2::ScanBuilder; -use vortex::mask::Mask; use vortex::scan::planning::driver::Progress; use vortex::scan::planning::driver::Run; use vortex::scan::planning::planner::Planner; -use vortex::scan::planning::planner::PlannerOutput; -use vortex::scan::planning::planner::State; use vortex::scan::planning::planner::WorkScope; -use vortex::scan::prepare::ChunkPlanner; use vortex::scan::prepare::PreparedScan; -use vortex::scan::prepare::PrunePlanner; -use vortex::scan::selection::Selection; +use vortex::scan::prepare::part_root; use crate::RUNTIME; @@ -89,7 +79,7 @@ impl FileScan { let rows = scan.rows().clone(); let mut root = Run::new(); root.admit( - compose(&scan, splits, dynamic), + part_root(&scan, splits, dynamic), WorkScope { file_ordinal: 0, rows, @@ -174,148 +164,3 @@ impl FileScan { Some(work) } } - -/// The planners of a scan, composed: with a dynamic filter, its pruning plans first over the scan's -/// rows, continuing into the parts of the rows they keep; otherwise, the parts directly. -fn compose(scan: &Arc, splits: &[u64], dynamic: bool) -> Box { - let rows = scan.rows().clone(); - let parts = { - let scan = Arc::clone(scan); - let parts = part_ranges(rows.clone(), splits); - let first_row = rows.start; - move |kept: Option| -> Box { - Box::new(PartPlanner::new(scan, parts, first_row, kept)) - } - }; - if dynamic && scan.filter().is_some() { - Box::new(PrunePlanner::new(Arc::clone(scan), rows, Box::new(parts))) - } else { - parts(None) - } -} - -/// Spawns a planner per part of a scan's rows that zone pruning left something of, in row order. -/// Parts are the file's layout splits, so a layout chunk, and the dictionary it carries, is -/// exported by one thread, which lets DuckDB evaluate an expression over that dictionary once. -/// -/// With a filter, each part prunes over its own rows before its chunks, on the thread that takes -/// it, like the per-split pruning of a V1 scan, so the pruning of a file's parts runs in parallel. -/// A dynamic filter, such as the bound a top-N pushes down, also prunes the scan as a whole before -/// any part is taken, so a file whose zones it rules out takes no thread. It has tightened by the -/// time a later part is taken, so pruning that part again skips more, from the zone maps the -/// scan-wide pruning read. -struct PartPlanner { - scan: Arc, - selection: Selection, - parts: std::vec::IntoIter>, - /// The first row of `kept`. - first_row: u64, - /// The rows scan-wide pruning kept, from `first_row`, or `None` when nothing was pruned. - kept: Option, -} - -impl PartPlanner { - fn new( - scan: Arc, - parts: Vec>, - first_row: u64, - kept: Option, - ) -> Self { - Self { - selection: scan.selection().clone(), - scan, - parts: parts.into_iter(), - first_row, - kept, - } - } - - /// The rows of `part` that scan-wide pruning kept, or `None` when nothing was pruned. - fn kept_in(&self, part: &Range) -> Option { - let kept = self.kept.as_ref()?; - let offset = - |row: u64| usize::try_from(row - self.first_row).vortex_expect("a part fits usize"); - Some(kept.slice(offset(part.start)..offset(part.end))) - } -} - -impl IoConsumer for PartPlanner { - fn set_io_result(&mut self, _request: IoRequestId, _result: IoResult) {} -} - -impl Planner for PartPlanner { - fn state(&self) -> State { - if self.parts.as_slice().is_empty() { - State::Done - } else { - State::NeedsCompute - } - } - - fn compute(&mut self) -> VortexResult { - while let Some(part) = self.parts.next() { - let kept = self.kept_in(&part); - if kept.as_ref().is_some_and(Mask::all_false) { - continue; - } - let chunks = { - let scan = Arc::clone(&self.scan); - let selection = self.selection.clone(); - let part = part.clone(); - move |again: Option| -> Box { - let kept = match (kept, again) { - (Some(kept), Some(again)) => Some(kept & &again), - (kept, again) => kept.or(again), - }; - Box::new(ChunkPlanner::new(scan, part, selection, kept)) - } - }; - let planner: Box = if self.scan.filter().is_some() { - Box::new(PrunePlanner::new( - Arc::clone(&self.scan), - part.clone(), - Box::new(chunks), - )) - } else { - chunks(None) - }; - let scope = WorkScope { - file_ordinal: 0, - rows: part, - }; - return Ok(PlannerOutput::Spawn(scope, planner)); - } - Ok(PlannerOutput::Done) - } -} - -/// The ranges between adjacent `splits`, clipped to `rows`, leaving out empty ones. -fn part_ranges(rows: Range, splits: &[u64]) -> Vec> { - splits - .windows(2) - .map(|w| w[0].max(rows.start)..w[1].min(rows.end)) - .filter(|part| part.start < part.end) - .collect() -} - -#[cfg(test)] -mod tests { - use std::ops::Range; - - use rstest::rstest; - - use super::part_ranges; - - #[rstest] - #[case::whole(0..30, &[0, 10, 20, 30], vec![0..10, 10..20, 20..30])] - #[case::clipped(5..25, &[0, 10, 20, 30], vec![5..10, 10..20, 20..25])] - #[case::inside_one_split(12..18, &[0, 10, 20, 30], vec![12..18])] - #[case::empty(5..5, &[0, 10], vec![])] - fn parts_follow_splits( - #[case] rows: Range, - #[case] splits: &[u64], - #[case] expected: Vec>, - ) { - assert_eq!(part_ranges(rows, splits), expected); - } -} diff --git a/vortex-scan/src/execution/mod.rs b/vortex-scan/src/execution/mod.rs index caa6a7ce099..577c1058e84 100644 --- a/vortex-scan/src/execution/mod.rs +++ b/vortex-scan/src/execution/mod.rs @@ -25,6 +25,7 @@ pub(crate) mod zone_map; mod adaptor; mod chunk; mod filter; +mod parts; mod projection; mod prune; mod selection; @@ -49,6 +50,7 @@ pub(crate) use self::chunk::rows_per_chunk; pub(crate) use self::chunk::scan_chunks; use self::filter::FilterPlanner; pub use self::filter::FilterPlans; +pub use self::parts::part_root; use self::projection::ProjectionPlanner; pub use self::prune::PruneNext; pub use self::prune::PrunePlanner; diff --git a/vortex-scan/src/execution/parts.rs b/vortex-scan/src/execution/parts.rs new file mode 100644 index 00000000000..606167b6878 --- /dev/null +++ b/vortex-scan/src/execution/parts.rs @@ -0,0 +1,170 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Cutting a prepared scan into parts, the units a host's threads take. + +use std::ops::Range; +use std::sync::Arc; + +use vortex_error::VortexExpect; +use vortex_error::VortexResult; +use vortex_io::request::IoConsumer; +use vortex_io::request::IoRequestId; +use vortex_io::request::IoResult; +use vortex_mask::Mask; + +use super::ChunkPlanner; +use super::PreparedScan; +use super::PrunePlanner; +use crate::planning::planner::Planner; +use crate::planning::planner::PlannerOutput; +use crate::planning::planner::State; +use crate::planning::planner::WorkScope; +use crate::selection::Selection; + +/// The root planner of a scan cut into parts on `splits`, such as a file's layout split +/// boundaries: it spawns one planner per part, in row order. With a dynamic filter, its pruning +/// plans first over the scan's rows, continuing into the parts of the rows they keep; otherwise, +/// the parts directly. +pub fn part_root(scan: &Arc, splits: &[u64], dynamic: bool) -> Box { + let rows = scan.rows().clone(); + let parts = { + let scan = Arc::clone(scan); + let parts = part_ranges(rows.clone(), splits); + let first_row = rows.start; + move |kept: Option| -> Box { + Box::new(PartPlanner::new(scan, parts, first_row, kept)) + } + }; + if dynamic && scan.filter().is_some() { + Box::new(PrunePlanner::new(Arc::clone(scan), rows, Box::new(parts))) + } else { + parts(None) + } +} + +/// Spawns a planner per part of a scan's rows that zone pruning left something of, in row order. +/// Parts are the file's layout splits, so a layout chunk, and the dictionary it carries, is +/// read by one thread, which lets a host evaluate an expression over that dictionary once. +/// +/// With a filter, each part prunes over its own rows before its chunks, on the thread that takes +/// it, like the per-split pruning of a V1 scan, so the pruning of a file's parts runs in parallel. +/// A dynamic filter, such as the bound a top-N pushes down, also prunes the scan as a whole before +/// any part is taken, so a file whose zones it rules out takes no thread. It has tightened by the +/// time a later part is taken, so pruning that part again skips more, from the zone maps the +/// scan-wide pruning read. +struct PartPlanner { + scan: Arc, + selection: Selection, + parts: std::vec::IntoIter>, + /// The first row of `kept`. + first_row: u64, + /// The rows scan-wide pruning kept, from `first_row`, or `None` when nothing was pruned. + kept: Option, +} + +impl PartPlanner { + fn new( + scan: Arc, + parts: Vec>, + first_row: u64, + kept: Option, + ) -> Self { + Self { + selection: scan.selection().clone(), + scan, + parts: parts.into_iter(), + first_row, + kept, + } + } + + /// The rows of `part` that scan-wide pruning kept, or `None` when nothing was pruned. + fn kept_in(&self, part: &Range) -> Option { + let kept = self.kept.as_ref()?; + let offset = + |row: u64| usize::try_from(row - self.first_row).vortex_expect("a part fits usize"); + Some(kept.slice(offset(part.start)..offset(part.end))) + } +} + +impl IoConsumer for PartPlanner { + fn set_io_result(&mut self, _request: IoRequestId, _result: IoResult) {} +} + +impl Planner for PartPlanner { + fn state(&self) -> State { + if self.parts.as_slice().is_empty() { + State::Done + } else { + State::NeedsCompute + } + } + + fn compute(&mut self) -> VortexResult { + while let Some(part) = self.parts.next() { + let kept = self.kept_in(&part); + if kept.as_ref().is_some_and(Mask::all_false) { + continue; + } + let chunks = { + let scan = Arc::clone(&self.scan); + let selection = self.selection.clone(); + let part = part.clone(); + move |again: Option| -> Box { + let kept = match (kept, again) { + (Some(kept), Some(again)) => Some(kept & &again), + (kept, again) => kept.or(again), + }; + Box::new(ChunkPlanner::new(scan, part, selection, kept)) + } + }; + let planner: Box = if self.scan.filter().is_some() { + Box::new(PrunePlanner::new( + Arc::clone(&self.scan), + part.clone(), + Box::new(chunks), + )) + } else { + chunks(None) + }; + let scope = WorkScope { + file_ordinal: 0, + rows: part, + }; + return Ok(PlannerOutput::Spawn(scope, planner)); + } + Ok(PlannerOutput::Done) + } +} + +/// The ranges between adjacent `splits`, clipped to `rows`, leaving out empty ones. +fn part_ranges(rows: Range, splits: &[u64]) -> Vec> { + splits + .windows(2) + .map(|w| w[0].max(rows.start)..w[1].min(rows.end)) + .filter(|part| part.start < part.end) + .collect() +} + +#[cfg(test)] +mod tests { + use std::ops::Range; + + use rstest::rstest; + + use super::part_ranges; + + #[rstest] + #[case::whole(0..30, &[0, 10, 20, 30], vec![0..10, 10..20, 20..30])] + #[case::clipped(5..25, &[0, 10, 20, 30], vec![5..10, 10..20, 20..25])] + #[case::inside_one_split(12..18, &[0, 10, 20, 30], vec![12..18])] + #[case::empty(5..5, &[0, 10], vec![])] + fn parts_follow_splits( + #[case] rows: Range, + #[case] splits: &[u64], + #[case] expected: Vec>, + ) { + assert_eq!(part_ranges(rows, splits), expected); + } +} diff --git a/vortex-scan/src/prepare.rs b/vortex-scan/src/prepare.rs index 62de742a81b..625f614f7d9 100644 --- a/vortex-scan/src/prepare.rs +++ b/vortex-scan/src/prepare.rs @@ -24,6 +24,7 @@ pub use crate::execution::SegmentLocation; pub use crate::execution::cache::ScanCache; pub use crate::execution::cache::WeakScanCache; use crate::execution::io::segment_ranges; +pub use crate::execution::part_root; use crate::execution::rows_per_chunk; use crate::plan::optimize; use crate::plan::plan_row_idx_expression; From 6520fcd61bb755a1ed8de022ce703b2d4e23cd98 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 17:12:25 -0500 Subject: [PATCH 62/80] Add a Scan API source over V2 plans whose open returns a ScanStream PlanDataSource exposes anything that lowers its data to plans over placed segments through the Scan API. Opening an unordered scan prepares each child once and cuts it into parts with part_root, queued for every clone of the returned ScanStream. Each clone drives a Run of its own on the task that polls it, one part at a time, and spawns nothing. An ordered scan runs in order on ScanDriver through the first clone polled. split returns the scan whole. Signed-off-by: Nicholas Gates Co-Authored-By: Claude Fable 5.2 --- Cargo.lock | 1 + vortex-scan/Cargo.toml | 1 + vortex-scan/src/execution/mod.rs | 1 - vortex-scan/src/source.rs | 14 +- vortex-scan/src/source/plan.rs | 404 ++++++++++++++++++++++++++ vortex-scan/src/source/plan_stream.rs | 359 +++++++++++++++++++++++ vortex-scan/src/source/tests.rs | 204 +++++++++++++ 7 files changed, 982 insertions(+), 2 deletions(-) create mode 100644 vortex-scan/src/source/plan.rs create mode 100644 vortex-scan/src/source/plan_stream.rs create mode 100644 vortex-scan/src/source/tests.rs diff --git a/Cargo.lock b/Cargo.lock index 1baac90bd38..f05a00d3e7d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -12358,6 +12358,7 @@ dependencies = [ name = "vortex-scan" version = "0.1.0" dependencies = [ + "async-channel", "async-lock", "async-trait", "bit-vec 0.10.2", diff --git a/vortex-scan/Cargo.toml b/vortex-scan/Cargo.toml index 9c1d41b1aa2..b2e0df7138b 100644 --- a/vortex-scan/Cargo.toml +++ b/vortex-scan/Cargo.toml @@ -15,6 +15,7 @@ version = { workspace = true } all-features = true [dependencies] +async-channel = { workspace = true } async-lock = { workspace = true } async-trait = { workspace = true } bit-vec = { workspace = true } diff --git a/vortex-scan/src/execution/mod.rs b/vortex-scan/src/execution/mod.rs index 577c1058e84..2bd2cd06a95 100644 --- a/vortex-scan/src/execution/mod.rs +++ b/vortex-scan/src/execution/mod.rs @@ -46,7 +46,6 @@ pub(crate) use self::chunk::ROW_BLOCK_SIZE; #[cfg(test)] pub(crate) use self::chunk::row_chunks; pub(crate) use self::chunk::rows_per_chunk; -#[cfg(test)] pub(crate) use self::chunk::scan_chunks; use self::filter::FilterPlanner; pub use self::filter::FilterPlans; diff --git a/vortex-scan/src/source.rs b/vortex-scan/src/source.rs index 08a3f38c296..34a6f819b1a 100644 --- a/vortex-scan/src/source.rs +++ b/vortex-scan/src/source.rs @@ -1,7 +1,8 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors -//! Source inputs and byte access for scans. +//! Source inputs and byte access for scans, and the [`DataSource`](crate::DataSource) that scans +//! them. use std::sync::Arc; @@ -32,3 +33,14 @@ pub struct ScanInput { /// State shared by repeated scans of this input. pub cache: Option, } + +mod plan; +mod plan_stream; + +pub use plan::FilePruner; +pub use plan::PlanChild; +pub use plan::PlanDataSource; +pub use plan::PlanSplitter; + +#[cfg(test)] +mod tests; diff --git a/vortex-scan/src/source/plan.rs b/vortex-scan/src/source/plan.rs new file mode 100644 index 00000000000..b4926a083b3 --- /dev/null +++ b/vortex-scan/src/source/plan.rs @@ -0,0 +1,404 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! [`PlanDataSource`]: a [`DataSource`] over plan children, scanned by the planner-driven +//! executor. +//! +//! Nothing here is about one format. A child is a [`ScanInput`], a plan over placed segments, +//! from a Vortex file, a Parquet file whose column chunks are segments, or any store that lowers +//! its data to plans. + +use std::any::Any; +use std::num::NonZeroUsize; +use std::ops::Range; +use std::sync::Arc; + +use async_trait::async_trait; +use futures::StreamExt; +use futures::stream; +use vortex_array::dtype::DType; +use vortex_array::dtype::FieldPath; +use vortex_array::expr::BoundExpression; +use vortex_array::expr::stats::Precision; +use vortex_array::stats::StatsSet; +use vortex_array::stream::SendableArrayStream; +use vortex_error::VortexResult; +use vortex_session::VortexSession; + +use super::ScanInput; +use super::plan_stream; +use crate::DataSource; +use crate::DataSourceScan; +use crate::DataSourceScanRef; +use crate::Partition; +use crate::PartitionRef; +use crate::PartitionStream; +use crate::ScanRequest; +use crate::prepare::ScanBuilder; +use crate::selection::Selection; +use crate::stream::ScanStream; + +/// Whether a child's own statistics, such as a file footer's, prove a filter, bound to the +/// child's dtype, false for every row of the child. +pub type FilePruner = Arc VortexResult + Send + Sync>; + +/// The row boundaries an opened scan cuts a child's work at, for the scan's projection and filter, +/// both bound to the child's dtype: ascending, covering the child's rows. A Vortex file gives its +/// layout splits over the fields the scan reads, as a V1 scan of the same fields cuts it. +pub type PlanSplitter = + Arc) -> VortexResult> + Send + Sync>; + +/// A child of a [`PlanDataSource`]: its [`ScanInput`] and what the source knows of it without +/// reading payloads. +#[derive(Clone)] +pub struct PlanChild { + input: ScanInput, + row_count: Option, + splitter: Option, + pruner: Option, +} + +impl PlanChild { + /// A child scanning `input`. Without a cache, the input gets a fresh one that every scan of + /// the child shares. + pub fn new(mut input: ScanInput) -> Self { + input.cache.get_or_insert_default(); + Self { + input, + row_count: None, + splitter: None, + pruner: None, + } + } + + /// Sets the child's exact row count. Without it, the source lowers the child's root plan to + /// learn the count when a scan needs it. + pub fn with_row_count(mut self, row_count: u64) -> Self { + self.row_count = Some(row_count); + self + } + + /// Sets fixed row boundaries that an opened scan cuts the child's work at, whatever it reads, + /// ascending and covering the child's rows. Without boundaries, the work is cut on the scan's + /// chunk grid. + pub fn with_splits(self, splits: Arc<[u64]>) -> Self { + self.with_splitter(Arc::new(move |_, _| Ok(splits.to_vec()))) + } + + /// Sets how an opened scan finds the row boundaries to cut the child's work at, from the + /// fields it reads. Without boundaries, the work is cut on the scan's chunk grid. + pub fn with_splitter(mut self, splitter: PlanSplitter) -> Self { + self.splitter = Some(splitter); + self + } + + /// Sets how the child's statistics rule out a scan's filter, so a scan they rule out reads + /// nothing of the child. + pub fn with_pruner(mut self, pruner: FilePruner) -> Self { + self.pruner = Some(pruner); + self + } + + /// The input this child scans. + pub fn input(&self) -> &ScanInput { + &self.input + } + + /// The child's rows, from the row count when set, else from its root plan. + fn rows(&self) -> VortexResult { + match self.row_count { + Some(rows) => Ok(rows), + None => Ok(self.input.root.get()?.row_count()), + } + } + + /// The bytes of all of the child's segments. + fn byte_size(&self) -> u64 { + self.input + .locations + .iter() + .map(|location| u64::from(location.length)) + .sum() + } + + /// The boundaries an opened scan of `projection` and `filter` cuts the child's work at, if the + /// child has them. + pub(super) fn splits( + &self, + projection: &BoundExpression, + filter: Option<&BoundExpression>, + ) -> VortexResult>> { + self.splitter + .as_ref() + .map(|splitter| splitter(projection, filter)) + .transpose() + } + + fn is_pruned(&self, filter: Option<&BoundExpression>) -> VortexResult { + match (&self.pruner, filter) { + (Some(pruner), Some(filter)) => pruner(filter), + _ => Ok(false), + } + } +} + +/// A [`DataSource`] over plan children, scanned by the planner-driven executor. +/// +/// This is the standard way to expose sources that can lower their data to plans over placed +/// segments, whatever their format. Every scan of a child shares the child's [`ScanCache`], so +/// scans that overlap in time plan it once. +/// +/// A scan's request applies to each child: its row range and row selection are in the child's +/// own rows, and its `partition_range` and `partition_selection` select children by ordinal. A +/// scan reads its children in order. +/// +/// [`split`](DataSourceScan::split) returns a scan whole. [`open`](DataSourceScan::open) runs it +/// on V2's planners and [`Run`](crate::planning::driver::Run) driver; see `plan_stream.rs`. A +/// scan's one partition reads its opened stream. +/// +/// [`ScanCache`]: crate::prepare::ScanCache +#[derive(Clone)] +pub struct PlanDataSource { + session: VortexSession, + dtype: DType, + children: Arc<[PlanChild]>, + row_count: Precision, + byte_size: Precision, +} + +impl PlanDataSource { + /// A source scanning one `input` with `session`. + pub fn new(session: VortexSession, input: ScanInput) -> Self { + Self::from_child(session, PlanChild::new(input)) + } + + /// A source scanning one `child` with `session`. + pub fn from_child(session: VortexSession, child: PlanChild) -> Self { + let dtype = child.input.dtype.clone(); + Self::from_children(session, dtype, vec![child]) + } + + /// A source scanning `children` in order with `session`. Every child must have `dtype`. + pub fn from_children(session: VortexSession, dtype: DType, children: Vec) -> Self { + let row_count = children + .iter() + .map(|child| child.row_count) + .sum::>() + .map_or(Precision::Absent, Precision::exact); + let byte_size = Precision::inexact(children.iter().map(PlanChild::byte_size).sum()); + Self { + session, + dtype, + children: children.into(), + row_count, + byte_size, + } + } + + /// Sets the exact row count of a one-child source, which scans report. + pub fn with_row_count(mut self, row_count: u64) -> Self { + if let [child] = &*self.children { + self.children = Arc::new([child.clone().with_row_count(row_count)]); + } + self.row_count = Precision::exact(row_count); + self + } + + /// Sets an estimate of the source's byte size. + pub fn with_byte_size(mut self, byte_size: Precision) -> Self { + self.byte_size = byte_size; + self + } + + /// The children this source scans, in order. + pub fn children(&self) -> &[PlanChild] { + &self.children + } + + /// The session scans of this source run with. + pub fn session(&self) -> &VortexSession { + &self.session + } +} + +#[async_trait] +impl DataSource for PlanDataSource { + fn dtype(&self) -> &DType { + &self.dtype + } + + fn row_count(&self) -> Precision { + self.row_count + } + + fn byte_size(&self) -> Precision { + self.byte_size + } + + async fn scan(&self, request: ScanRequest) -> VortexResult { + let projection = request.projection.bind(&self.dtype)?.optimize_recursive()?; + let filter = request + .filter + .map(|filter| filter.bind(&self.dtype)?.optimize_recursive()) + .transpose()?; + let mut units = Vec::new(); + let scans_rows = + request.limit != Some(0) && !request.row_range.as_ref().is_some_and(Range::is_empty); + for (ordinal, child) in self.children.iter().enumerate().filter(|_| scans_rows) { + let index = ordinal as u64; + let selected = request + .partition_range + .as_ref() + .is_none_or(|range| range.contains(&index)) + && request + .partition_selection + .row_count_in_range(&(index..index + 1)) + == 1; + if !selected || child.is_pruned(filter.as_ref())? { + continue; + } + let rows = child + .row_count + .map(|count| clamp_rows(request.row_range.clone(), count)); + if rows.as_ref().is_some_and(Range::is_empty) { + continue; + } + units.push(Unit { + child: ordinal, + rows, + }); + } + let state = ScanState { + session: self.session.clone(), + children: Arc::clone(&self.children), + dtype: projection.dtype().clone(), + projection, + filter, + row_range: request.row_range, + selection: request.selection, + ordered: request.ordered, + limit: request.limit, + }; + Ok(Box::new(PlanScan { + state: Arc::new(state), + units, + })) + } + + async fn field_statistics(&self, _field_path: &FieldPath) -> VortexResult { + Ok(StatsSet::default()) + } +} + +/// The request's `rows`, or all of them, clamped to a child of `count` rows. +fn clamp_rows(rows: Option>, count: u64) -> Range { + let rows = rows.unwrap_or(0..count); + let end = rows.end.min(count); + rows.start.min(end)..end +} + +/// What every piece and stream of one scan of a [`PlanDataSource`] shares. +pub(super) struct ScanState { + pub(super) session: VortexSession, + children: Arc<[PlanChild]>, + /// The dtype of the scan's output. + pub(super) dtype: DType, + pub(super) projection: BoundExpression, + pub(super) filter: Option, + row_range: Option>, + selection: Selection, + pub(super) ordered: bool, + pub(super) limit: Option, +} + +impl ScanState { + /// The source's child at `ordinal`. + pub(super) fn child(&self, ordinal: usize) -> &PlanChild { + &self.children[ordinal] + } + + /// The rows of `unit` this scan reads: its own, or else the request's row range clamped to + /// its child. + pub(super) fn unit_rows(&self, unit: &Unit) -> VortexResult> { + match &unit.rows { + Some(rows) => Ok(rows.clone()), + None => Ok(clamp_rows( + self.row_range.clone(), + self.child(unit.child).rows()?, + )), + } + } + + /// A builder of this scan's `rows` of `child`. + pub(super) fn builder(&self, child: &PlanChild, rows: Range) -> ScanBuilder { + ScanBuilder::new(self.session.clone(), child.input.clone()) + .with_projection(self.projection.clone()) + .with_some_filter(self.filter.clone()) + .with_selection(self.selection.clone()) + .with_row_range(rows) + } +} + +/// Rows of one child that a scan reads. +#[derive(Clone, Debug)] +pub(super) struct Unit { + /// The child's ordinal in the source. + pub(super) child: usize, + /// The child's rows, or `None` for the request's rows of a child whose row count is not known + /// until its plan is lowered. + pub(super) rows: Option>, +} + +/// A scan of a [`PlanDataSource`], or a piece split from one. +struct PlanScan { + state: Arc, + /// The scan's units, in child and row order. + units: Vec, +} + +impl DataSourceScan for PlanScan { + fn dtype(&self) -> &DType { + &self.state.dtype + } + + fn split(self: Box, _n: NonZeroUsize) -> VortexResult> { + Ok(vec![self]) + } + + fn open(self: Box) -> VortexResult { + plan_stream::open(self.state, self.units) + } + + fn partition_count(&self) -> Precision { + Precision::exact(1usize) + } + + fn partitions(self: Box) -> PartitionStream { + stream::iter([Ok(Box::new(PlanPartition(self)) as PartitionRef)]).boxed() + } +} + +/// A scan of a [`PlanDataSource`] as its one partition, which reads the scan's opened stream. +struct PlanPartition(Box); + +impl Partition for PlanPartition { + fn as_any(&self) -> &dyn Any { + self + } + + fn index(&self) -> usize { + 0 + } + + fn row_count(&self) -> Precision { + Precision::Absent + } + + fn byte_size(&self) -> Precision { + Precision::Absent + } + + fn execute(self: Box) -> VortexResult { + Ok(Box::pin(self.0.open()?)) + } +} diff --git a/vortex-scan/src/source/plan_stream.rs b/vortex-scan/src/source/plan_stream.rs new file mode 100644 index 00000000000..bd58a2da7cc --- /dev/null +++ b/vortex-scan/src/source/plan_stream.rs @@ -0,0 +1,359 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! The stream of an opened [`PlanDataSource`](super::PlanDataSource) scan: V2's planners and +//! [`Run`] driver behind [`ScanStream`]. +//! +//! An unordered scan prepares each child once and runs its [`part_root`], which cuts the child +//! into parts: the rows between the child's splits for the fields the scan reads, such as a +//! file's layout splits, or the scan's chunks for a child without splits. The parts go into one +//! queue that every clone of the stream takes from. Each clone owns a [`Run`], driven on the task +//! that polls the clone, and runs one part on it at a time: the part's chunks run side by side, +//! so one chunk's reads overlap another's compute, batches are returned as they are produced, and +//! reads are awaited with [`Run::poll_completion`]. Nothing is spawned, so a host that polls a +//! clone with `block_on` runs the scan's compute on its own thread. +//! +//! With a dynamic filter, such as the bound a top-N pushes down, a child's root prunes the child as +//! a whole before it cuts parts, which reads zone maps. Opening reads nothing, so such a root is +//! queued work too: the first clone to take it runs it and queues its parts. +//! +//! An ordered scan returns its rows in order through the first clone to be polled, running one +//! child after another on [`ScanDriver`], which keeps a scan's chunks in order. Later clones +//! return nothing. A host that reads an ordered scan in parallel +//! [splits](crate::DataSourceScan::split) it first. +//! +//! A limit is one [`RowLimit`] for the whole stream: clones stop taking parts once it is spent, +//! and each clone's output is trimmed to it. + +use std::future; +use std::iter; +use std::ops::Range; +use std::sync::Arc; +use std::sync::atomic::AtomicU64; +use std::sync::atomic::Ordering; + +use async_channel::Receiver; +use async_channel::Sender; +use futures::FutureExt; +use futures::StreamExt; +use futures::future::BoxFuture; +use futures::stream; +use futures::stream::BoxStream; +use parking_lot::Mutex; +use vortex_array::ArrayRef; +use vortex_array::scalar_fn::fns::dynamic::DynamicExprUpdates; +use vortex_error::VortexExpect; +use vortex_error::VortexResult; +use vortex_io::request::IoService; +use vortex_io::session::RuntimeSessionExt; + +use super::plan::ScanState; +use super::plan::Unit; +use crate::execution::driver::ScanDriver; +use crate::execution::scan_chunks; +use crate::limit::RowLimit; +use crate::limit::limit_rows; +use crate::planning::driver::Progress; +use crate::planning::driver::Run; +use crate::planning::planner::Planner; +use crate::planning::planner::WorkScope; +use crate::prepare::PreparedScan; +use crate::prepare::part_root; +use crate::stream::ScanStream; + +/// Opens the stream of the scan's `units`. +pub(super) fn open(state: Arc, units: Vec) -> VortexResult { + let dtype = state.dtype.clone(); + let limit = state.limit.map(RowLimit::new); + if state.ordered { + let arrays = Arc::new(Mutex::new(Some(in_order(state, units)))); + return Ok(ScanStream::new(dtype, move || { + let arrays = arrays + .lock() + .take() + .unwrap_or_else(|| stream::empty().boxed()); + limited(arrays, limit.clone()) + })); + } + + let (sender, receiver) = async_channel::unbounded(); + let mut total_rows = 0; + for unit in &units { + let rows = state.unit_rows(unit)?; + if rows.is_empty() { + continue; + } + total_rows += rows.end - rows.start; + let (child, root, dynamic) = prepare(&state, unit, rows)?; + let parts = run_root(child, root); + if dynamic { + send(&sender, Work::Root(parts, sender.clone())); + continue; + } + let work = parts + .now_or_never() + .vortex_expect("a root that only cuts parts reads nothing")?; + for work in work { + send(&sender, work); + } + } + // Only queued roots hold senders now, so the queue closes once it is empty and no root is + // left that could add to it. + drop(sender); + + let queue = Arc::new(Queue { + receiver, + total_rows, + rows_taken: AtomicU64::new(0), + }); + let progress = Arc::clone(&queue); + Ok(ScanStream::new(dtype, move || { + let worker = Worker { + queue: Arc::clone(&queue), + limit: limit.clone(), + run: Run::new(), + child: None, + }; + let arrays = stream::unfold(Some(worker), |worker| async move { + let mut worker = worker?; + match worker.next_array().await { + Ok(Some(array)) => Some((Ok(array), Some(worker))), + Ok(None) => None, + Err(err) => Some((Err(err), None)), + } + }) + .boxed(); + limited(arrays, limit.clone()) + }) + .with_progress(move || progress.progress())) +} + +/// One child's prepared scan, shared by the parts of it that clones run. +struct PreparedChild { + rows: Range, + io: Arc, +} + +/// A part of a child: the planner its root spawned for some of its rows. +struct Part { + child: Arc, + scope: WorkScope, + planner: Box, +} + +/// Prepares the scan of `rows` of the unit's child once and composes its root, returning whether +/// the root reads before it spawns parts. +fn prepare( + state: &ScanState, + unit: &Unit, + rows: Range, +) -> VortexResult<(Arc, Box, bool)> { + let child = state.child(unit.child); + let splits = child.splits(&state.projection, state.filter.as_ref())?; + let scan = Arc::new(state.builder(child, rows).prepare()?); + let splits = splits.unwrap_or_else(|| chunk_bounds(&scan)); + let dynamic = state + .filter + .as_ref() + .is_some_and(|filter| DynamicExprUpdates::new(filter).is_some()); + let root = part_root(&scan, &splits, dynamic); + let prepared = PreparedChild { + rows: scan.rows().clone(), + io: scan.io(), + }; + Ok((Arc::new(prepared), root, dynamic && scan.filter().is_some())) +} + +/// The boundaries of `scan`'s chunks, which cut the work of a child without splits of its own. +fn chunk_bounds(scan: &PreparedScan) -> Vec { + let rows = scan.rows().clone(); + let chunks = scan_chunks(rows.clone(), scan.chunk_rows); + iter::once(rows.start) + .chain(chunks.iter().map(|chunk| chunk.end)) + .collect() +} + +/// Runs a child's root on a run of its own, awaiting only its reads, and returns the work it +/// produces, in row order: the parts it spawns, and any batch it returns itself. +fn run_root( + child: Arc, + root: Box, +) -> BoxFuture<'static, VortexResult>> { + async move { + let mut run = Run::new(); + let scope = WorkScope { + file_ordinal: 0, + rows: child.rows.clone(), + }; + run.admit(root, scope, child.io.session()); + let mut work = Vec::new(); + loop { + match run.advance()? { + Progress::Spawn(scope, planner) => work.push(Work::Part(Part { + child: Arc::clone(&child), + scope, + planner, + })), + Progress::Batch(batch) => work.push(Work::Batch(batch.array)), + Progress::RootDone(_) if run.live_roots() > 0 => {} + Progress::RootDone(_) | Progress::Idle => break, + Progress::Waiting => future::poll_fn(|cx| run.poll_completion(cx)).await?, + } + } + Ok(work) + } + .boxed() +} + +/// A unit of work in the queue of an unordered scan. +enum Work { + Part(Part), + /// A batch a root returned itself. + Batch(ArrayRef), + /// A root that reads before it spawns parts, and the queue to send its parts to. The sender + /// keeps the queue open until they are in it. + Root(BoxFuture<'static, VortexResult>>, Sender), +} + +fn send(sender: &Sender, work: Work) { + // The queue is unbounded and closes only once every clone is dropped, when the work is moot. + drop(sender.try_send(work)); +} + +/// The queue of an unordered scan, which every clone of its stream takes from. +struct Queue { + receiver: Receiver, + /// The rows of the scan's units. + total_rows: u64, + /// The rows of the parts clones have taken. + rows_taken: AtomicU64, +} + +impl Queue { + /// The fraction of the scan's rows whose parts clones have taken. Pruning can leave rows that + /// no part covers, so a queue with nothing left to take has made all of its progress. + fn progress(&self) -> f64 { + if self.total_rows == 0 || self.is_drained() { + return 1.0; + } + (self.rows_taken.load(Ordering::Relaxed) as f64 / self.total_rows as f64).min(1.0) + } + + /// Whether the queue is empty and no root is left that could add to it. + fn is_drained(&self) -> bool { + self.receiver.is_empty() && self.receiver.sender_count() == 0 + } +} + +impl Drop for Queue { + fn drop(&mut self) { + // Queued roots hold senders of the queue itself; drain them so it can be freed. + self.receiver.close(); + while self.receiver.try_recv().is_ok() {} + } +} + +/// One clone's worker: a run of its own, fed one part at a time from the scan's queue, and driven +/// on the task that polls the clone. +struct Worker { + queue: Arc, + limit: Option, + run: Run, + /// The child of the part live on the run, whose I/O the planners that part spawns read through. + child: Option>, +} + +impl Worker { + /// The worker's next array, or `None` once the scan has no more work for it. + async fn next_array(&mut self) -> VortexResult> { + loop { + if self.run.live_roots() == 0 { + if self.limit.as_ref().is_some_and(RowLimit::is_exhausted) { + return Ok(None); + } + match self.take().await? { + None => return Ok(None), + Some(Taken::Batch(array)) => return Ok(Some(array)), + Some(Taken::Part(part)) => { + self.run + .admit(part.planner, part.scope, part.child.io.session()); + self.child = Some(part.child); + } + } + } + match self.run.advance()? { + Progress::Batch(batch) => return Ok(Some(batch.array)), + Progress::Spawn(scope, planner) => { + let child = self + .child + .as_ref() + .vortex_expect("a planner is spawned by a live part"); + self.run.admit(planner, scope, child.io.session()); + } + Progress::RootDone(_) | Progress::Idle => {} + Progress::Waiting => { + future::poll_fn(|cx| self.run.poll_completion(cx)).await?; + } + } + } + } + + /// Takes the next part or batch from the scan's queue, running the roots it finds there + /// first, or `None` once the queue is closed and empty. + async fn take(&mut self) -> VortexResult> { + loop { + let Ok(work) = self.queue.receiver.recv().await else { + return Ok(None); + }; + match work { + Work::Part(part) => { + self.queue.rows_taken.fetch_add( + part.scope.rows.end - part.scope.rows.start, + Ordering::Relaxed, + ); + return Ok(Some(Taken::Part(part))); + } + Work::Batch(array) => return Ok(Some(Taken::Batch(array))), + Work::Root(work, sender) => { + for work in work.await? { + send(&sender, work); + } + } + } + } + } +} + +/// What a worker takes from the queue. +enum Taken { + Part(Part), + Batch(ArrayRef), +} + +/// The arrays of an ordered scan: each unit's rows in order, one unit after another. +fn in_order(state: Arc, units: Vec) -> BoxStream<'static, VortexResult> { + stream::iter(units) + .flat_map(move |unit| { + let rows = match state.unit_rows(&unit) { + Ok(rows) => rows, + Err(err) => return stream::once(future::ready(Err(err))).boxed(), + }; + if rows.is_empty() { + return stream::empty().boxed(); + } + ScanDriver::new(state.session.handle(), 1, true) + .run(state.builder(state.child(unit.child), rows)) + }) + .boxed() +} + +/// `arrays`, trimmed to the scan's limit. +fn limited( + arrays: BoxStream<'static, VortexResult>, + limit: Option, +) -> BoxStream<'static, VortexResult> { + match limit { + Some(limit) => limit_rows(arrays, limit), + None => arrays, + } +} diff --git a/vortex-scan/src/source/tests.rs b/vortex-scan/src/source/tests.rs new file mode 100644 index 00000000000..daeb32082b5 --- /dev/null +++ b/vortex-scan/src/source/tests.rs @@ -0,0 +1,204 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +use std::ops::Range; +use std::sync::Arc; + +use futures::TryStreamExt; +use futures::future::try_join_all; +use roaring::RoaringTreemap; +use rstest::rstest; +use vortex_array::ArrayRef; +use vortex_array::IntoArray; +use vortex_array::VortexSessionExecute; +use vortex_array::arrays::ChunkedArray; +use vortex_array::arrays::PrimitiveArray; +use vortex_array::assert_arrays_eq; +use vortex_array::expr::checked_add; +use vortex_array::expr::gt; +use vortex_array::expr::lit; +use vortex_array::expr::root; +use vortex_buffer::Buffer; +use vortex_error::VortexResult; +use vortex_error::vortex_bail; +use vortex_io::session::RuntimeSessionExt; +use vortex_session::VortexSession; + +use super::PlanDataSource; +use super::ScanInput; +use super::SegmentFuture; +use super::SegmentId; +use super::SegmentSource; +use crate::DataSource; +use crate::PartitionRef; +use crate::ScanRequest; +use crate::execution::pipeline::synthetic::RowSource; +use crate::plan::LazyPlanRef; +use crate::selection::Selection; + +struct NoSegments; + +impl SegmentSource for NoSegments { + fn request(&self, _id: SegmentId) -> SegmentFuture { + Box::pin(async { vortex_bail!("an in-memory source must not request bytes") }) + } +} + +fn source() -> PlanDataSource { + source_of(20) +} + +fn source_of(row_count: u64) -> PlanDataSource { + let plan = RowSource::plan(row_count, vec![4, 7, 9], None, false); + let input = ScanInput { + dtype: plan.dtype().clone(), + root: LazyPlanRef::ready(plan), + locations: Arc::new([]), + segments: Arc::new(NoSegments), + cache: None, + }; + PlanDataSource::new(VortexSession::empty().with_tokio(), input).with_row_count(row_count) +} + +async fn partitions(request: ScanRequest) -> VortexResult> { + partitions_of(&source(), request).await +} + +async fn partitions_of( + source: &PlanDataSource, + request: ScanRequest, +) -> VortexResult> { + source.scan(request).await?.partitions().try_collect().await +} + +async fn collect(partitions: Vec) -> VortexResult { + let dtype = source().dtype().clone(); + let mut arrays = Vec::new(); + for partition in partitions { + let batches: Vec = partition.execute()?.try_collect().await?; + arrays.extend(batches); + } + Ok(ChunkedArray::try_new(arrays, dtype)?.into_array()) +} + +#[rstest] +#[case::unordered(false)] +#[case::ordered(true)] +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn execute_applies_the_request(#[case] ordered: bool) -> VortexResult<()> { + let partitions = partitions(ScanRequest { + projection: checked_add(root(), lit(100_u64)), + filter: Some(gt(root(), lit(5_u64))), + row_range: Some(2..18), + ordered, + ..Default::default() + }) + .await?; + assert_eq!(partitions.len(), 1); + let mut ctx = VortexSession::empty().create_execution_ctx(); + let actual = collect(partitions) + .await? + .execute::(&mut ctx)?; + let mut values = actual.as_slice::().to_vec(); + if !ordered { + values.sort_unstable(); + } + assert_eq!(values, (106_u64..118).collect::>()); + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn execute_applies_the_limit() -> VortexResult<()> { + let partitions = partitions(ScanRequest { + filter: Some(gt(root(), lit(5_u64))), + ordered: true, + limit: Some(5), + ..Default::default() + }) + .await?; + assert_arrays_eq!( + collect(partitions).await?, + Buffer::from_iter(6_u64..11).into_array(), + &mut VortexSession::empty().create_execution_ctx() + ); + Ok(()) +} + +/// A request that selects no rows of the source scans one partition, which reads nothing. +#[rstest] +#[case::zero_limit(ScanRequest { limit: Some(0), ..Default::default() })] +#[case::empty_rows(ScanRequest { row_range: Some(30..40), ..Default::default() })] +#[case::other_units(ScanRequest { partition_range: Some(1..4), ..Default::default() })] +#[case::unit_excluded(ScanRequest { + partition_selection: Selection::ExcludeRoaring(RoaringTreemap::from_iter([0_u64])), + ..Default::default() +})] +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn requests_without_rows_read_nothing(#[case] request: ScanRequest) -> VortexResult<()> { + let scan = source().scan(request).await?; + let partitions: Vec = scan.partitions().try_collect().await?; + assert_eq!(collect(partitions).await?.len(), 0); + Ok(()) +} + +/// The sorted values of every partition's output. +async fn sorted_values(partitions: Vec) -> VortexResult> { + let mut ctx = VortexSession::empty().create_execution_ctx(); + let mut values = collect(partitions) + .await? + .execute::(&mut ctx)? + .as_slice::() + .to_vec(); + values.sort_unstable(); + Ok(values) +} + +/// Selecting the source's unit, by range or by selection, returns its one partition. +#[rstest] +#[case::range(Some(0..1), Selection::All)] +#[case::wide_range(Some(0..5), Selection::All)] +#[case::selection(None, Selection::IncludeRoaring(RoaringTreemap::from_iter([0_u64, 3])))] +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn selecting_the_unit_returns_its_partition( + #[case] partition_range: Option>, + #[case] partition_selection: Selection, +) -> VortexResult<()> { + let partitions = partitions(ScanRequest { + partition_selection, + partition_range, + ..Default::default() + }) + .await?; + assert_eq!(partitions.len(), 1); + assert_eq!(partitions[0].index(), 0); + assert_eq!( + sorted_values(partitions).await?, + (0..20).collect::>() + ); + Ok(()) +} + +/// Clones of an opened scan share its parts: polled together, they return every row once. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn clones_share_the_scan() -> VortexResult<()> { + let stream = source_of(100_000) + .scan(ScanRequest::default()) + .await? + .open()?; + let clones = [stream.clone(), stream.clone(), stream.clone()]; + let batches = try_join_all( + clones + .into_iter() + .map(|clone| clone.try_collect::>()), + ) + .await?; + assert_eq!(stream.progress(), Some(1.0)); + let mut ctx = VortexSession::empty().create_execution_ctx(); + let mut values = Vec::new(); + for batch in batches.into_iter().flatten() { + values.extend_from_slice(batch.execute::(&mut ctx)?.as_slice::()); + } + values.sort_unstable(); + assert_eq!(values, (0..100_000).collect::>()); + Ok(()) +} From d07b031d55233632c7e3ff9ec5133315f0588725 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 17:13:00 -0500 Subject: [PATCH 63/80] Expose Vortex files as Scan API sources over V2 plans VortexFile::plan_data_source scans one file through PlanDataSource and plan_child makes a file a child of one, with the file's statistics pruning scans they rule out and its layout splits over the fields a scan reads cutting the scan's parts, as a V1 scan cuts its splits. Both are opt-in: data_source() still scans with the layout reader, which layout_reader_data_source names explicitly. Signed-off-by: Nicholas Gates Co-Authored-By: Claude Fable 5.2 --- vortex-file/src/file.rs | 67 +++++- vortex-file/src/lib.rs | 2 + vortex-file/src/plan_tests.rs | 349 +++++++++++++++++++++++++++++++ vortex-file/src/source.rs | 12 +- vortex-file/src/tests.rs | 62 ++++++ vortex-file/src/v2/scan/tests.rs | 54 +++++ 6 files changed, 535 insertions(+), 11 deletions(-) create mode 100644 vortex-file/src/plan_tests.rs diff --git a/vortex-file/src/file.rs b/vortex-file/src/file.rs index f610495f90a..fb466d62ebe 100644 --- a/vortex-file/src/file.rs +++ b/vortex-file/src/file.rs @@ -14,6 +14,7 @@ use itertools::Itertools; use vortex_array::ArrayRef; use vortex_array::dtype::DType; use vortex_array::dtype::FieldMask; +use vortex_array::expr::BoundExpression; use vortex_array::expr::Expression; use vortex_buffer::ByteBuffer; use vortex_error::VortexResult; @@ -21,6 +22,7 @@ use vortex_layout::LayoutReader; use vortex_layout::scan::layout::LayoutReaderDataSource; use vortex_layout::scan::metrics::ScanUsage; use vortex_layout::scan::scan_builder::ScanBuilder; +use vortex_layout::scan::scan_builder::referenced_field_masks; use vortex_layout::scan::split_by::SplitBy; use vortex_layout::scan::v2::ScanFile; use vortex_layout::segments::SegmentSource; @@ -28,6 +30,8 @@ use vortex_layout::segments::UsageSegmentSource; use vortex_scan::DataSourceRef; use vortex_scan::prepare::ScanCache; use vortex_scan::prepare::SegmentLocation; +use vortex_scan::source::PlanChild; +use vortex_scan::source::PlanDataSource; use vortex_session::VortexSession; use vortex_utils::aliases::hash_map::HashMap; @@ -116,7 +120,8 @@ impl VortexFile { /// /// Repeated calls to [`layout_reader`](Self::layout_reader), [`scan`](Self::scan), and /// [`data_source`](Self::data_source) will share the same reader tree. Repeated V2 scans of - /// [`scan_file`](Self::scan_file) will share its segment locations and a [`ScanCache`]. + /// [`scan_file`](Self::scan_file), and so of the plan data sources, will share its segment + /// locations and a [`ScanCache`]. pub fn with_caching(self) -> Self { let scan_cache = FileScanCache { locations: self.footer.segment_locations(), @@ -245,18 +250,70 @@ impl VortexFile { /// Create a [`DataSource`](vortex_scan::DataSource) from this file for scanning. /// - /// Wraps the file's layout reader with [`FileStatsLayoutReader`] (when file-level - /// statistics are available) and [`LayoutReaderDataSource`]. Stored footer aggregates are - /// available through the source statistics methods without reading payloads. + /// Scans run on the file's [layout reader](Self::layout_reader), as with + /// [`layout_reader_data_source`](Self::layout_reader_data_source). Stored footer aggregates + /// are available through the source statistics methods without reading payloads. pub fn data_source(&self) -> VortexResult { - let reader = self.layout_reader()?; + self.layout_reader_data_source() + } + /// Create a [`DataSource`](vortex_scan::DataSource) that scans this file with its + /// [layout reader](Self::layout_reader), whatever its layouts. + /// + /// Use [`data_source`](Self::data_source) unless the layout reader is required, for example + /// to compare it with [`plan_data_source`](Self::plan_data_source). Stored footer aggregates + /// are available through the source statistics methods without reading payloads. + pub fn layout_reader_data_source(&self) -> VortexResult { + let reader = self.layout_reader()?; Ok(Arc::new(FileDataSource::new( LayoutReaderDataSource::new(reader, self.session.clone()), self.file_stats().cloned(), ))) } + /// Create a [`DataSource`](vortex_scan::DataSource) from this file whose scans run on the + /// planner-driven executor. + /// + /// The source is a [`PlanDataSource`] over [`plan_child`](Self::plan_child). Every scan of + /// the source shares one [`ScanCache`]: the file's, with [caching](Self::with_caching), or else + /// one of its own. A scan whose filter the file-level statistics prove false reads nothing. + /// Stored footer aggregates are available through the source statistics methods. Opening the + /// source reads nothing and builds no layout reader. + pub fn plan_data_source(&self) -> DataSourceRef { + let source = PlanDataSource::from_child(self.session.clone(), self.plan_child()); + Arc::new(FileDataSource::new(source, self.file_stats().cloned())) + } + + /// This file as a child of a [`PlanDataSource`]: its V2 scan input, row count, and a pruner + /// that skips scans whose filter the file-level statistics prove false. + /// + /// An opened scan of the child cuts its work on the file's layout splits over the fields it + /// reads, as a V1 scan of the same fields does. + pub fn plan_child(&self) -> PlanChild { + let splitter = { + let file = self.clone(); + Arc::new( + move |projection: &BoundExpression, filter: Option<&BoundExpression>| { + SplitBy::default().splits( + file.layout_reader()?.as_ref(), + &(0..file.row_count()), + &referenced_field_masks(projection, filter)?, + ) + }, + ) + }; + let file = PlanChild::new(self.scan_file().into()) + .with_row_count(self.row_count()) + .with_splitter(splitter); + let Some(statistics) = self.file_stats().cloned() else { + return file; + }; + let (row_count, session) = (self.row_count(), self.session.clone()); + file.with_pruner(Arc::new(move |filter| { + is_falsified_by_file_stats(filter, row_count, &statistics, &session) + })) + } + /// Initiate a scan of the file, returning a builder for projection, filtering, selection, and /// execution options. pub fn scan(&self) -> VortexResult> { diff --git a/vortex-file/src/lib.rs b/vortex-file/src/lib.rs index 0321127a3d3..48caddbd245 100644 --- a/vortex-file/src/lib.rs +++ b/vortex-file/src/lib.rs @@ -109,6 +109,8 @@ pub mod flatbuffers; mod footer; pub mod multi; mod open; +#[cfg(test)] +mod plan_tests; mod pruning; /// Segment sources, caches, and sinks used by file readers and writers. pub mod segments; diff --git a/vortex-file/src/plan_tests.rs b/vortex-file/src/plan_tests.rs new file mode 100644 index 00000000000..0a468e31990 --- /dev/null +++ b/vortex-file/src/plan_tests.rs @@ -0,0 +1,349 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Plan data sources read through the Scan API's `split` and `open`, over real files whose +//! segments are read through the session's I/O. + +use std::num::NonZeroUsize; +use std::ops::Range; +use std::sync::Arc; +use std::sync::LazyLock; +use std::sync::atomic::AtomicU32; +use std::sync::atomic::Ordering; + +use futures::FutureExt; +use futures::TryStreamExt; +use futures::future::BoxFuture; +use rstest::rstest; +use vortex_array::ArrayRef; +use vortex_array::IntoArray; +use vortex_array::VortexSessionExecute; +use vortex_array::arrays::PrimitiveArray; +use vortex_array::arrays::StructArray; +use vortex_array::buffer::BufferHandle; +use vortex_array::dtype::DType; +use vortex_array::dtype::Nullability; +use vortex_array::dtype::PType; +use vortex_array::expr::Expression; +use vortex_array::expr::dynamic; +use vortex_array::expr::get_item; +use vortex_array::expr::gt; +use vortex_array::expr::lit; +use vortex_array::expr::root; +use vortex_array::scalar_fn::fns::operators::CompareOperator; +use vortex_buffer::Alignment; +use vortex_buffer::Buffer; +use vortex_buffer::ByteBuffer; +use vortex_buffer::ByteBufferMut; +use vortex_error::VortexResult; +use vortex_error::vortex_err; +use vortex_io::VortexReadAt; +use vortex_io::session::RuntimeSession; +use vortex_layout::scan::scan_builder::ScanBuilder; +use vortex_layout::session::LayoutSession; +use vortex_scan::DataSourceRef; +use vortex_scan::ScanRequest; +use vortex_scan::source::PlanDataSource; +use vortex_scan::stream::ScanStream; +use vortex_session::VortexSession; + +use crate::OpenOptionsSessionExt; +use crate::VortexFile; +use crate::WriteOptionsSessionExt; +use crate::multi::MultiFileSession; + +static SESSION: LazyLock = LazyLock::new(|| { + let session = VortexSession::empty() + .with::() + .with::() + .with::(); + crate::register_default_encodings(&session); + crate::enable_all_registered_array_encodings(&session); + session +}); + +/// The rows of a one-file source: several parts of the scan, filtered or not. +const ROWS: u32 = 600_000; + +/// The `m` value of row `n`: scrambled, so the column does not compress away and its segments +/// are read during the scan rather than with the footer. +fn scramble(n: u32) -> u32 { + n.wrapping_mul(2_654_435_761) +} + +const THRESHOLD: u32 = u32::MAX / 2; + +/// The filter of filtered cases, which keeps about half of the rows and, with the `n` +/// projection, makes the scan read two columns. +fn m_filter() -> Expression { + gt(get_item("m", root()), lit(THRESHOLD)) +} + +/// The values of `n` in `rows` that a scan returns, with [`m_filter`] when `filtered`. +fn expected(rows: Range, filtered: bool) -> Vec { + rows.filter(|&n| !filtered || scramble(n) > THRESHOLD) + .collect() +} + +/// A file of an `n` column holding `values` and an `m` column of their scrambles. +async fn file_bytes(values: Range) -> VortexResult { + let m = Buffer::from_iter(values.clone().map(scramble)).into_array(); + let array = + StructArray::from_fields(&[("n", Buffer::from_iter(values).into_array()), ("m", m)])? + .into_array(); + let mut buf = ByteBufferMut::empty(); + SESSION + .write_options() + .write(&mut buf, array.to_array_stream()) + .await?; + Ok(buf.freeze()) +} + +/// A reader of in-memory bytes whose reads pend once before they complete, as storage reads do. +#[derive(Clone)] +struct YieldingRead(ByteBuffer); + +impl VortexReadAt for YieldingRead { + fn concurrency(&self) -> usize { + self.0.concurrency() + } + + fn size(&self) -> BoxFuture<'static, VortexResult> { + self.0.size() + } + + fn read_at( + &self, + offset: u64, + length: usize, + alignment: Alignment, + ) -> BoxFuture<'static, VortexResult> { + let read = self.0.read_at(offset, length, alignment); + async move { + tokio::task::yield_now().await; + read.await + } + .boxed() + } +} + +async fn open_one_file() -> VortexResult { + SESSION + .open_options() + .open_read(YieldingRead(file_bytes(0..ROWS).await?)) + .await +} + +async fn one_file() -> VortexResult { + Ok(open_one_file().await?.plan_data_source()) +} + +fn n() -> Expression { + get_item("n", root()) +} + +fn request(ordered: bool) -> ScanRequest { + ScanRequest { + projection: n(), + ordered, + ..Default::default() + } +} + +async fn values(stream: ScanStream) -> VortexResult> { + let arrays: Vec = stream.try_collect().await?; + let mut ctx = SESSION.create_execution_ctx(); + let mut values = Vec::new(); + for array in arrays { + values.extend_from_slice(array.execute::(&mut ctx)?.as_slice::()); + } + Ok(values) +} + +/// Reads `stream` with `workers` clones, each polled on a task of its own. +async fn read_stream(stream: ScanStream, workers: usize) -> VortexResult>> { + let tasks: Vec<_> = (0..workers) + .map(|_| tokio::spawn(values(stream.clone()))) + .collect(); + let mut out = Vec::with_capacity(workers); + for task in tasks { + out.push( + task.await + .map_err(|err| vortex_err!("worker task failed: {err}"))??, + ); + } + Ok(out) +} + +fn sorted(workers: Vec>) -> Vec { + let mut all: Vec = workers.into_iter().flatten().collect(); + all.sort_unstable(); + all +} + +/// The clones of an unordered scan's stream together read every selected row once. +#[rstest] +#[case::projection(false)] +#[case::filter(true)] +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[cfg_attr(miri, ignore)] +async fn open_reads_every_row_once(#[case] filtered: bool) -> VortexResult<()> { + let source = one_file().await?; + let scan = source + .scan(ScanRequest { + filter: filtered.then(m_filter), + ..request(false) + }) + .await?; + let workers = read_stream(scan.open()?, 4).await?; + assert_eq!(sorted(workers), expected(0..ROWS, filtered)); + Ok(()) +} + +/// A child's splits are its parts, each of several chunks, and the workers read every row of them once. +#[rstest] +#[case::unordered(false, false)] +#[case::unordered_filter(false, true)] +#[case::ordered(true, false)] +#[case::ordered_filter(true, true)] +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[cfg_attr(miri, ignore)] +async fn open_cuts_parts_on_file_splits( + #[case] ordered: bool, + #[case] filtered: bool, +) -> VortexResult<()> { + let file = open_one_file().await?; + let splits: Arc<[u64]> = Arc::from([0, 150_000, 400_000, u64::from(ROWS)]); + let source: DataSourceRef = Arc::new(PlanDataSource::from_child( + SESSION.clone(), + file.plan_child().with_splits(splits), + )); + let scan = source + .scan(ScanRequest { + filter: filtered.then(m_filter), + ..request(ordered) + }) + .await?; + let workers = read_stream(scan.open()?, 3).await?; + if ordered { + let reader = workers.iter().find(|values| !values.is_empty()); + assert_eq!(reader, Some(&expected(0..ROWS, filtered))); + } else { + // Each worker returns its parts' rows in order within each part. + assert_eq!(sorted(workers), expected(0..ROWS, filtered)); + } + Ok(()) +} + +/// A file's parts are its layout splits over the fields the scan reads, as a V1 scan of the same +/// fields cuts it: no batch of an unordered scan crosses one. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[cfg_attr(miri, ignore)] +async fn open_cuts_parts_on_layout_splits() -> VortexResult<()> { + let file = open_one_file().await?; + let splits = ScanBuilder::new(SESSION.clone(), file.layout_reader()?) + .with_projection(n().bind(file.dtype())?) + .full_file_splits()?; + assert!(splits.len() > 2, "the file has several layout splits"); + + // One worker takes the parts in row order and finishes each before the next. + let scan = file.plan_data_source().scan(request(false)).await?; + let arrays: Vec = scan.open()?.try_collect().await?; + let mut boundaries = vec![0u64]; + for array in &arrays { + let end = boundaries.last().copied().unwrap_or(0) + array.len() as u64; + boundaries.push(end); + } + for split in splits { + assert!( + boundaries.contains(&split), + "a batch crosses layout split {split}" + ); + } + Ok(()) +} + +/// A dynamic filter, such as a top-N's bound, prunes a file as a whole before its parts are cut, +/// as queued work rather than in `open`. The rows follow the bound as it stands when the workers +/// read, not as it stood when the scan was opened. +#[rstest] +#[case::unordered(false)] +#[case::ordered(true)] +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[cfg_attr(miri, ignore)] +async fn open_prunes_the_file_first_for_a_dynamic_filter( + #[case] ordered: bool, +) -> VortexResult<()> { + let bound = Arc::new(AtomicU32::new(0)); + let value = Arc::clone(&bound); + let filter = dynamic( + CompareOperator::Gt, + move || Some(value.load(Ordering::Relaxed).into()), + DType::Primitive(PType::U32, Nullability::NonNullable), + true, + n(), + ); + let scan = one_file() + .await? + .scan(ScanRequest { + filter: Some(filter), + ..request(ordered) + }) + .await?; + let stream = scan.open()?; + bound.store(ROWS - 10, Ordering::Relaxed); + assert_eq!( + sorted(read_stream(stream, 3).await?), + (ROWS - 9..ROWS).collect::>() + ); + Ok(()) +} + +/// An ordered scan gives all of its rows, in order, to the first clone polled. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[cfg_attr(miri, ignore)] +async fn ordered_open_reads_in_order_on_one_clone() -> VortexResult<()> { + let source = one_file().await?; + let mut workers = read_stream(source.scan(request(true)).await?.open()?, 3).await?; + workers.sort_by_key(|values| std::cmp::Reverse(values.len())); + assert_eq!(workers[0], (0..ROWS).collect::>()); + assert!(workers[1..].iter().all(Vec::is_empty)); + Ok(()) +} + +/// A scan's limit holds across the clones of its stream; an ordered scan returns the first rows. +#[rstest] +#[case::unordered(false, false)] +#[case::unordered_filter(false, true)] +#[case::ordered(true, false)] +#[case::ordered_filter(true, true)] +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[cfg_attr(miri, ignore)] +async fn open_applies_the_limit(#[case] ordered: bool, #[case] filtered: bool) -> VortexResult<()> { + const LIMIT: usize = 150_000; + let rows = expected(0..ROWS, filtered); + let source = one_file().await?; + let scan = source + .scan(ScanRequest { + filter: filtered.then(m_filter), + limit: Some(LIMIT as u64), + ..request(ordered) + }) + .await?; + // A limit holds across the whole scan, so a limited scan is not split. + let scan = { + let mut pieces = scan.split(NonZeroUsize::new(4).unwrap_or(NonZeroUsize::MIN))?; + assert_eq!(pieces.len(), 1); + pieces.remove(0) + }; + let workers = read_stream(scan.open()?, 3).await?; + if ordered { + let reader = workers.iter().find(|values| !values.is_empty()); + assert_eq!(reader.map(Vec::as_slice), Some(&rows[..LIMIT])); + } + let all = sorted(workers); + assert_eq!(all.len(), LIMIT); + all.windows(2).for_each(|w| assert!(w[0] < w[1])); + assert!(all.iter().all(|value| rows.binary_search(value).is_ok())); + Ok(()) +} diff --git a/vortex-file/src/source.rs b/vortex-file/src/source.rs index 1088a61de88..713278b20d9 100644 --- a/vortex-file/src/source.rs +++ b/vortex-file/src/source.rs @@ -9,7 +9,6 @@ use vortex_array::expr::stats::Precision; use vortex_array::scalar::Scalar; use vortex_array::stats::StatsSet; use vortex_error::VortexResult; -use vortex_layout::scan::layout::LayoutReaderDataSource; use vortex_scan::DataSource; use vortex_scan::DataSourceScanRef; use vortex_scan::PartitionRef; @@ -18,19 +17,20 @@ use vortex_session::VortexSession; use crate::FileStatistics; -pub(crate) struct FileDataSource { - source: LayoutReaderDataSource, +/// A file's scans with the statistics of its footer. +pub(crate) struct FileDataSource { + source: S, statistics: Option, } -impl FileDataSource { - pub(crate) fn new(source: LayoutReaderDataSource, statistics: Option) -> Self { +impl FileDataSource { + pub(crate) fn new(source: S, statistics: Option) -> Self { Self { source, statistics } } } #[async_trait] -impl DataSource for FileDataSource { +impl DataSource for FileDataSource { fn dtype(&self) -> &DType { self.source.dtype() } diff --git a/vortex-file/src/tests.rs b/vortex-file/src/tests.rs index 111abcf6745..1ceb7dd355a 100644 --- a/vortex-file/src/tests.rs +++ b/vortex-file/src/tests.rs @@ -121,6 +121,9 @@ use vortex_layout::scan::scan_builder::ScanBuilder; use vortex_layout::scan::split_by::DEFAULT_MAX_SPLIT_ROWS; use vortex_layout::scan::split_by::SplitBy; use vortex_layout::session::LayoutSession; +use vortex_scan::DataSourceRef; +use vortex_scan::PartitionRef; +use vortex_scan::ScanRequest; use vortex_scan::strict_sorted_buffer::StrictSortedBuffer; use vortex_session::VortexSession; use vortex_session::registry::Id; @@ -2595,6 +2598,65 @@ async fn file_data_source_returns_mergeable_partials() -> VortexResult<()> { Ok(()) } +/// Scans `source` and concatenates the rows of all its partitions, returning how many partitions +/// the scan had. +async fn scan_source( + source: &DataSourceRef, + request: ScanRequest, +) -> VortexResult<(usize, ArrayRef)> { + let scan = source.scan(request).await?; + let dtype = scan.dtype().clone(); + let partitions: Vec = scan.partitions().try_collect().await?; + let partition_count = partitions.len(); + let mut chunks = Vec::new(); + for partition in partitions { + chunks.push(partition.execute()?.read_all().await?); + } + Ok(( + partition_count, + ChunkedArray::try_new(chunks, dtype)?.into_array(), + )) +} + +/// Both of a file's executors are reachable through the Scan API and read the same rows. +#[rstest] +#[case::plan(false)] +#[case::layout_reader(true)] +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[cfg_attr(miri, ignore)] +async fn file_sources_scan_with_either_executor(#[case] layout_reader: bool) -> VortexResult<()> { + let array = StructArray::from_fields(&[("numbers", buffer![1u32, 2, 3, 4, 5].into_array())])? + .into_array(); + let mut buf = ByteBufferMut::empty(); + SESSION + .write_options() + .write(&mut buf, array.to_array_stream()) + .await?; + let file = SESSION.open_options().open_buffer(buf)?; + let source = if layout_reader { + file.layout_reader_data_source()? + } else { + file.plan_data_source() + }; + + let (_, actual) = scan_source( + &source, + ScanRequest { + projection: get_item("numbers", root()), + filter: Some(gt(get_item("numbers", root()), lit(3u32))), + ordered: true, + ..Default::default() + }, + ) + .await?; + assert_arrays_eq!( + actual, + buffer![4u32, 5].into_array(), + &mut SESSION.create_execution_ctx() + ); + Ok(()) +} + #[tokio::test] async fn test_writer_with_statistics() -> VortexResult<()> { let array = StructArray::from_fields(&[("numbers", buffer![1u32, 2, 3, 4, 5].into_array())])? diff --git a/vortex-file/src/v2/scan/tests.rs b/vortex-file/src/v2/scan/tests.rs index 6b3b030b971..7235c566165 100644 --- a/vortex-file/src/v2/scan/tests.rs +++ b/vortex-file/src/v2/scan/tests.rs @@ -14,16 +14,25 @@ use vortex_array::VortexSessionExecute; use vortex_array::arrays::ChunkedArray; use vortex_array::arrays::StructArray; use vortex_array::arrays::VarBinArray; +use vortex_array::assert_arrays_eq; +use vortex_array::expr::get_item; +use vortex_array::expr::gt; +use vortex_array::expr::lit; +use vortex_array::expr::root; +use vortex_array::expr::stats::Precision; use vortex_arrow::ArrowScanExt; use vortex_arrow::ArrowSessionExt; use vortex_arrow::ExecuteArrowExt; use vortex_buffer::ByteBufferMut; use vortex_buffer::buffer; +use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_io::runtime::tokio::TokioRuntime; use vortex_io::session::RuntimeSession; use vortex_layout::scan::v2::ScanBuilder; use vortex_layout::session::LayoutSession; +use vortex_scan::PartitionRef; +use vortex_scan::ScanRequest; use vortex_session::VortexSession; use super::ScanDriver; @@ -93,3 +102,48 @@ async fn record_batches_match_arrays() -> VortexResult<()> { assert_eq!(given, expected); Ok(()) } + +/// A file's plan data source scans the rows the request asks for, as a V2 scan built from +/// the file directly does. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn plan_data_source_scans_like_the_file() -> VortexResult<()> { + let file = file().await?; + let source = file.plan_data_source(); + assert_eq!(source.row_count(), Precision::exact(file.row_count())); + + let request = || ScanRequest { + projection: get_item("numbers", root()), + filter: Some(gt(get_item("numbers", root()), lit(4))), + row_range: Some(4..28), + ordered: true, + ..Default::default() + }; + let dtype = file.dtype().clone(); + let expected = ScanBuilder::new(SESSION.clone(), file.scan_file()) + .with_projection(request().projection.bind(&dtype)?) + .with_some_filter(request().filter.map(|f| f.bind(&dtype)).transpose()?) + .with_row_range(4..28); + let scan_dtype = expected.dtype().clone(); + let collect = |arrays: Vec| ChunkedArray::try_new(arrays, scan_dtype.clone()); + let expected = collect(driver().run(expected).try_collect().await?)?; + + let partitions: Vec = source + .scan(request()) + .await? + .partitions() + .try_collect() + .await?; + assert_eq!(partitions.len(), 1); + let executed = collect( + partitions + .into_iter() + .next() + .vortex_expect("one partition") + .execute()? + .try_collect() + .await?, + )?; + assert_arrays_eq!(executed, expected, &mut SESSION.create_execution_ctx()); + + Ok(()) +} From d1b14dfb331fd7c5db197713968da260648eba4d Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 17:14:15 -0500 Subject: [PATCH 64/80] Read DuckDB V2 scans through the Scan API's open DuckDB's V2 scan builds the same ScanRequest as its V1 scan, scans the file's plan data source and opens it, and each thread polls a clone of the stream, as for V1. The private V2 queue in scan_v2.rs goes away, and progress comes from ScanStream::progress for both executors. Signed-off-by: Nicholas Gates Co-Authored-By: Claude Fable 5.2 --- vortex-duckdb/src/file_reader.rs | 195 +++++++++++----------------- vortex-duckdb/src/lib.rs | 1 - vortex-duckdb/src/scan_v2.rs | 166 ----------------------- vortex-duckdb/src/table_function.rs | 16 +-- 4 files changed, 77 insertions(+), 301 deletions(-) delete mode 100644 vortex-duckdb/src/scan_v2.rs diff --git a/vortex-duckdb/src/file_reader.rs b/vortex-duckdb/src/file_reader.rs index c6c1969fcda..ac7c83b63b3 100644 --- a/vortex-duckdb/src/file_reader.rs +++ b/vortex-duckdb/src/file_reader.rs @@ -18,7 +18,6 @@ use vortex::array::VortexSessionExecute as _; use vortex::array::arrays::Chunked; use vortex::array::arrays::chunked::ChunkedArrayExt as _; use vortex::array::arrays::struct_::StructArrayExt as _; -use vortex::array::scalar_fn::fns::dynamic::DynamicExprUpdates; use vortex::dtype::FieldPath; use vortex::error::VortexExpect; use vortex::error::VortexResult; @@ -36,11 +35,9 @@ use vortex::io::runtime::BlockingRuntime as _; use vortex::io::std_file::StdFileSystem; use vortex::layout::LayoutReaderRef; use vortex::layout::scan::layout::LayoutReaderDataSource; -use vortex::layout::scan::scan_builder::ScanBuilder; -use vortex::layout::scan::v2::ScanBuilder as V2ScanBuilder; -use vortex::layout::scan::v2::ScanFile; use vortex::mask::Mask; use vortex::scan::DataSource as _; +use vortex::scan::DataSourceRef; use vortex::scan::ScanRequest; use vortex::scan::stream::ScanStream; use vortex::session::SessionExt as _; @@ -56,7 +53,6 @@ use crate::exporter::ArrayExporter; use crate::exporter::ConversionCache; use crate::projection::Filter; use crate::projection::extract_schema_from_dtype; -use crate::scan_v2::FileScan; use crate::table_function::BindState; use crate::table_function::GlobalState; use crate::table_function::LocalState; @@ -132,36 +128,37 @@ pub struct OpenFileReader { /// The state of an open file that the threads scanning it share. pub struct FileScanState { reader: LayoutReaderRef, - /// The file as the V2 executor reads it. - scan_file: ScanFile, - /// The file's V2 scan, which every thread scanning the file drives. Set when the file is - /// initialized for a V2 scan. - v2: OnceLock, - /// The opened stream of the file's V1 scan, which each thread scanning the file polls a clone - /// of. Set when the file is initialized for a V1 scan. A stream is `Send` but not `Sync`, so - /// threads clone it under the lock. - stream: OnceLock>, - /// Whether a clone of `stream` has ended, so no split of the file is left to claim. + /// The file as a source whose scans run on the V2 executor. + plan_source: DataSourceRef, + /// The opened stream of the file's scan, which each thread scanning the file polls a clone + /// of. Set when the file is initialized. + stream: OnceLock, + /// Whether a clone of `stream` has ended, so no work of the file is left to take. finished: AtomicBool, cache: ConversionCache, } +/// The opened scan of a file. +struct FileStream { + /// A stream is `Send` but not `Sync`, so threads clone it under the lock. + stream: Mutex, + /// Whether a batch can join chunks of several layout chunks, as a V2 batch can. + joins_chunks: bool, +} + impl FileScanState { /// The scan work a thread joining the file would take, or `None` once the file has none. fn next_split(&self) -> Option { - if let Some(scan) = self.v2.get() { - return (!scan.is_exhausted()).then_some(Split::V2); - } - // A clone of the file's stream ends only once no split is left to claim and its own - // splits are done. So a thread joins the file until the first clone ends, and threads - // then move on to the next file while the clones holding the last splits finish them: - // no thread waits for the rest of a file to drain. + // A clone of the file's stream ends only once no work is left to take and its own work + // is done. So a thread joins the file until the first clone ends, and threads then move + // on to the next file while the clones holding the last work finish it: no thread waits + // for the rest of a file to drain. if self.finished.load(Ordering::Acquire) { return None; } self.stream .get() - .map(|stream| Split::V1(stream.lock().clone())) + .map(|stream| Split(stream.stream.lock().clone())) } } @@ -169,14 +166,15 @@ impl OpenFileReader { async fn open(path: String) -> VortexResult { let (fs, fs_path) = resolve_filesystem(&parse_uri_or_path(&path)?)?; let source = fs.open_read(&fs_path).await?; - let file = open_cached(&SESSION, Some(&path), source, None, &|options| options).await?; - let mut scan_file = file.scan_file(); - scan_file.cache.get_or_insert_default(); + // Caching lets the V2 source cut its parts on the layout reader built here, and gives + // every V2 scan of the file one plan cache. + let file = open_cached(&SESSION, Some(&path), source, None, &|options| options) + .await? + .with_caching(); Ok(OpenFileReader { scan_state: Some(Arc::new(FileScanState { reader: file.layout_reader()?, - scan_file, - v2: OnceLock::new(), + plan_source: file.plan_data_source(), stream: OnceLock::new(), finished: AtomicBool::new(false), cache: ConversionCache::default(), @@ -249,27 +247,8 @@ pub fn reader_initialize(file: &mut OpenFileReader, global: &GlobalState) -> Vor return Ok(true); } - // Opening the file's scan, or planning a V2 scan, is non-trivial work so we prefer - // doing it here under file lock and not in reader_try_initialize_scan under - // global lock. - if global.scan_v2 { - let state = file.scan_state(); - let splits = ScanBuilder::new(SESSION.clone(), Arc::clone(&state.reader)) - .with_projection(global.projection.clone()) - .with_some_filter(global.filter.filter.clone()) - .full_file_splits()?; - let dynamic = global - .filter - .filter - .as_ref() - .is_some_and(|filter| DynamicExprUpdates::new(filter).is_some()); - let scan = FileScan::try_new(v2_builder(state, global), &splits, dynamic)?; - if state.v2.set(scan).is_err() { - vortex_panic!("file initialized twice"); - } - return Ok(false); - } - + // Opening the file's scan is non-trivial work so we prefer doing it here under file lock and + // not in reader_try_initialize_scan under global lock. let state = file.scan_state(); let filter = &global.filter; let request = ScanRequest { @@ -280,15 +259,24 @@ pub fn reader_initialize(file: &mut OpenFileReader, global: &GlobalState) -> Vor ordered: false, // DuckDB runs one thread per core, so its threads are the scan's parallelism: each runs // one split at a time, polling it itself. A clone with room for more would claim splits - // other threads could have run, leaving them nothing on a file with few splits. + // other threads could have run, leaving them nothing on a file with few splits. A V2 + // clone always runs one part at a time. split_concurrency: Some(NonZeroUsize::MIN), ..ScanRequest::default() }; - // An unordered scan without a limit opens into a stream over a queue of the file's splits, - // whose clones each claim the next split once they have finished their last. - let source = LayoutReaderDataSource::new(Arc::clone(&state.reader), SESSION.clone()); - let stream = RUNTIME.block_on(source.scan(request))?.open()?; - if state.stream.set(Mutex::new(stream)).is_err() { + // An unordered scan without a limit opens into a stream over a queue of the file's work, V1 + // splits or V2 parts, whose clones each take the next once they have finished their last. + let stream = if global.scan_v2 { + RUNTIME.block_on(state.plan_source.scan(request))?.open()? + } else { + let source = LayoutReaderDataSource::new(Arc::clone(&state.reader), SESSION.clone()); + RUNTIME.block_on(source.scan(request))?.open()? + }; + let stream = FileStream { + stream: Mutex::new(stream), + joins_chunks: global.scan_v2, + }; + if state.stream.set(stream).is_err() { vortex_panic!("file initialized twice"); } Ok(false) @@ -304,17 +292,6 @@ fn file_rows(state: &FileScanState, filter: &Filter) -> Range { }) } -/// The V2 scan of the file's rows that the scan's row range and selection keep. -fn v2_builder(state: &FileScanState, global: &GlobalState) -> V2ScanBuilder { - let filter = &global.filter; - let rows = file_rows(state, filter); - V2ScanBuilder::new(SESSION.clone(), state.scan_file.clone()) - .with_projection(global.projection.clone()) - .with_some_filter(filter.filter.clone()) - .with_selection(filter.row_selection.clone()) - .with_row_range(rows) -} - /// What a thread's split yields next. enum SplitItem { /// The split has no more rows. @@ -326,60 +303,38 @@ enum SplitItem { /// Takes the next array of the thread's split, keeping the split while it has more to yield. fn next_split_item(local: &mut LocalState) -> VortexResult { - match local.split.take() { - None => Ok(SplitItem::Done), - Some(Split::V1(mut stream)) => { - let Some(array) = RUNTIME.block_on(stream.next()).transpose()? else { - local - .file - .as_ref() - .vortex_expect("split without a file") - .finished - .store(true, Ordering::Release); - // Dropping the last clone drops the file's split queue; do that outside DuckDB's - // locks. - local.retired_splits.push(Split::V1(stream)); + let array = match local.pending.pop() { + Some(array) => array, + None => { + let Some(Split(mut stream)) = local.split.take() else { return Ok(SplitItem::Done); }; - local.split = Some(Split::V1(stream)); - Ok(if array.is_empty() { - SplitItem::Empty - } else { - SplitItem::Array(array) - }) - } - Some(Split::V2) => { let file = local.file.as_ref().vortex_expect("split without a file"); - let scan = file - .v2 - .get() - .vortex_expect("V2 split of a file without a V2 scan"); - let array = match local.pending.pop() { - Some(array) => array, - None => { - let Some(array) = scan.next_array(&mut local.run)? else { - return Ok(SplitItem::Done); - }; - // A V2 batch can join chunks of several layout chunks. Canonicalizing it - // would decode their dictionaries, so export each chunk on its own, as a V1 - // scan yields them. - match array.as_opt::() { - Some(chunked) => { - local.pending.extend(chunked.chunks().into_iter().rev()); - local.pending.pop().unwrap_or(array) - } - None => array, - } - } + let Some(array) = RUNTIME.block_on(stream.next()).transpose()? else { + file.finished.store(true, Ordering::Release); + // Dropping the last clone drops the file's queue of work; do that outside + // DuckDB's locks. + local.retired_splits.push(Split(stream)); + return Ok(SplitItem::Done); }; - local.split = Some(Split::V2); - Ok(if array.is_empty() { - SplitItem::Empty - } else { - SplitItem::Array(array) - }) + local.split = Some(Split(stream)); + let joins_chunks = file.stream.get().is_some_and(|stream| stream.joins_chunks); + // A V2 batch can join chunks of several layout chunks. Canonicalizing it would decode + // their dictionaries, so export each chunk on its own, as a V1 scan yields them. + match array.as_opt::().filter(|_| joins_chunks) { + Some(chunked) => { + local.pending.extend(chunked.chunks().into_iter().rev()); + local.pending.pop().unwrap_or(array) + } + None => array, + } } - } + }; + Ok(if array.is_empty() { + SplitItem::Empty + } else { + SplitItem::Array(array) + }) } /// Called by all threads under global lock. If this function returns true, @@ -391,9 +346,8 @@ fn next_split_item(local: &mut LocalState) -> VortexResult { /// the global lock. It only moves references between the file and the local /// state, and reader_scan drops the retired ones. pub fn reader_try_initialize_scan(file: &mut OpenFileReader, local: &mut LocalState) -> bool { - // A thread joins a file while its V2 scan has chunks left to spawn or its V1 - // stream has a split left to claim. Cloning the stream only clones its handles, - // so it is cheap under the global lock. + // A thread joins a file while its stream has work left to take. Cloning the + // stream only clones its handles, so it is cheap under the global lock. let split = file .scan_state .as_ref() @@ -516,13 +470,10 @@ pub fn reader_get_progress_in_file(file: &OpenFileReader) -> f64 { let Some(state) = file.scan_state.as_ref() else { return 100.0; }; - if let Some(scan) = state.v2.get() { - return scan.progress(); - } state .stream .get() - .and_then(|stream| stream.lock().progress()) + .and_then(|stream| stream.stream.lock().progress()) .map_or(0.0, |progress| 100.0 * progress) } diff --git a/vortex-duckdb/src/lib.rs b/vortex-duckdb/src/lib.rs index 57712698666..73eba2133f0 100644 --- a/vortex-duckdb/src/lib.rs +++ b/vortex-duckdb/src/lib.rs @@ -31,7 +31,6 @@ mod exporter; mod ffi; mod file_reader; mod projection; -mod scan_v2; mod table_function; #[rustfmt::skip] diff --git a/vortex-duckdb/src/scan_v2.rs b/vortex-duckdb/src/scan_v2.rs deleted file mode 100644 index cc8fc4305d5..00000000000 --- a/vortex-duckdb/src/scan_v2.rs +++ /dev/null @@ -1,166 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// SPDX-FileCopyrightText: Copyright the Vortex contributors - -//! Drives a V2 scan for DuckDB. -//! -//! A planner says what it needs: compute, or reads. This driver decides where each runs, and -//! DuckDB's own threads run all of it. Each file is prepared once, and the thread that initializes -//! it cuts the scanned rows into parts on the file's layout splits, the units a V1 scan hands its -//! threads, after pruning the scan as a whole when its filter is dynamic. A thread takes the next -//! part and runs it on a run of its own, inline, waiting only for its reads: with a filter, the -//! part's pruning plans first, continuing into the chunks of the rows pruning kept; without, the -//! chunks directly. Threads join the file only while parts are left, so the threads a file -//! cannot use move on to the next file. - -use std::collections::VecDeque; -use std::future; -use std::sync::Arc; -use std::sync::atomic::AtomicBool; -use std::sync::atomic::AtomicU64; -use std::sync::atomic::Ordering; - -use parking_lot::Mutex; -use vortex::array::ArrayRef; -use vortex::error::VortexResult; -use vortex::io::request::IoService; -use vortex::io::runtime::BlockingRuntime as _; -use vortex::layout::scan::v2::ScanBuilder; -use vortex::scan::planning::driver::Progress; -use vortex::scan::planning::driver::Run; -use vortex::scan::planning::planner::Planner; -use vortex::scan::planning::planner::WorkScope; -use vortex::scan::prepare::PreparedScan; -use vortex::scan::prepare::part_root; - -use crate::RUNTIME; - -/// The chunks a thread runs beside each other on its run, so one chunk's reads overlap another's -/// compute. -const CHUNKS_PER_THREAD: usize = 1; - -/// One file's V2 scan, shared by the threads scanning it. -pub(crate) struct FileScan { - scan: Arc, - io: Arc, - /// The work the root spawned, in row order, that no thread has taken yet. - queue: Mutex>, - /// Set once a thread has taken the last of `queue`. - exhausted: AtomicBool, - /// The rows of the chunks taken so far, for DuckDB's progress bar. - rows_taken: AtomicU64, -} - -/// What a thread takes from the file next. -enum Work { - /// A chunk to run on the thread's run. - Chunk(WorkScope, Box), - /// A batch the root produced itself. - Batch(ArrayRef), -} - -impl FileScan { - /// Prepares `builder`, composes its planners, and runs the root until it has spawned the - /// planner of every part. The root only prunes the scan, for a dynamic filter, and cuts parts, - /// so this reads zone maps at most. - /// - /// Running the root up front leaves the file with a known list of parts, like the splits of a - /// V1 scan: a thread joins the file only while a part is left, and the threads DuckDB has to - /// spare move on to the next file instead of waiting for this file's root. - /// - /// `splits` are the file's layout split boundaries, as a V1 scan of the same fields cuts it. - /// `dynamic` says the filter's value changes while the scan runs, as a top-N's bound does. - pub(crate) fn try_new( - builder: ScanBuilder, - splits: &[u64], - dynamic: bool, - ) -> VortexResult { - let scan = Arc::new(builder.prepare()?); - let io = scan.io(); - let rows = scan.rows().clone(); - let mut root = Run::new(); - root.admit( - part_root(&scan, splits, dynamic), - WorkScope { - file_ordinal: 0, - rows, - }, - io.session(), - ); - let mut queue = VecDeque::new(); - loop { - match root.advance()? { - Progress::Batch(batch) => queue.push_back(Work::Batch(batch.array)), - Progress::Spawn(scope, chunk) => queue.push_back(Work::Chunk(scope, chunk)), - Progress::RootDone(_) if root.live_roots() > 0 => {} - Progress::RootDone(_) | Progress::Idle => break, - Progress::Waiting => { - RUNTIME.block_on(future::poll_fn(|cx| root.poll_completion(cx)))?; - } - } - } - Ok(Self { - scan, - io, - exhausted: AtomicBool::new(queue.is_empty()), - queue: Mutex::new(queue), - rows_taken: AtomicU64::new(0), - }) - } - - /// Whether every chunk has been taken, so a thread joining the scan finds no work. - pub(crate) fn is_exhausted(&self) -> bool { - self.exhausted.load(Ordering::Acquire) - } - - /// The percentage of the scanned rows whose chunks threads have taken. - pub(crate) fn progress(&self) -> f64 { - let rows = self.scan.rows(); - let total = rows.end - rows.start; - if total == 0 || self.exhausted.load(Ordering::Relaxed) { - return 100.0; - } - 100.0 * self.rows_taken.load(Ordering::Relaxed) as f64 / total as f64 - } - - /// The next array of this file for the thread whose run is `run`, or `None` once the file has - /// no more work for the thread. Keeps the thread's run fed with chunks from the file, and - /// waits for reads on the calling thread. - pub(crate) fn next_array(&self, run: &mut Run) -> VortexResult> { - loop { - while run.live_roots() < CHUNKS_PER_THREAD { - match self.next_work() { - Some(Work::Chunk(scope, chunk)) => { - run.admit(chunk, scope, self.io.session()); - } - Some(Work::Batch(array)) => return Ok(Some(array)), - None => break, - } - } - match run.advance()? { - Progress::Batch(batch) => return Ok(Some(batch.array)), - Progress::Spawn(scope, child) => { - run.admit(child, scope, self.io.session()); - } - Progress::RootDone(_) => {} - Progress::Idle => return Ok(None), - Progress::Waiting => { - RUNTIME.block_on(future::poll_fn(|cx| run.poll_completion(cx)))?; - } - } - } - } - - /// Takes the next chunk or batch of the file, or `None` once every one has been taken. - fn next_work(&self) -> Option { - let mut queue = self.queue.lock(); - let work = queue.pop_front()?; - if queue.is_empty() { - self.exhausted.store(true, Ordering::Release); - } - if let Work::Chunk(scope, _) = &work { - self.rows_taken - .fetch_add(scope.rows.end - scope.rows.start, Ordering::Relaxed); - } - Some(work) - } -} diff --git a/vortex-duckdb/src/table_function.rs b/vortex-duckdb/src/table_function.rs index 02e9446bfbf..60cc0587576 100644 --- a/vortex-duckdb/src/table_function.rs +++ b/vortex-duckdb/src/table_function.rs @@ -41,7 +41,6 @@ use vortex::expr::proto::ExprSerializeProtoExt; use vortex::metrics::tracing::get_global_labels; use vortex::proto::expr as expr_pb; use vortex::scalar::Scalar; -use vortex::scan::planning::driver::Run; use vortex::scan::stream::ScanStream; use vortex_utils::aliases::hash_map::HashMap; @@ -205,14 +204,10 @@ pub struct AggregateState { } assert_impl_all!(GlobalState: Send, Sync); -/// The scan work that one thread does on a file. -pub enum Split { - /// A clone of the file's V1 scan stream, which the thread polls inline. It claims the file's - /// splits as it has room for them until none is left, and yields only the splits it claimed. - V1(ScanStream), - /// Chunks of the file's V2 scan, taken by the thread until the scan has none left. - V2, -} +/// The scan work that one thread does on a file: a clone of the file's opened scan stream, which +/// the thread polls inline. It takes the file's work as it has room for it until none is left, +/// and yields only the work it took. +pub struct Split(pub ScanStream); /// field position, accumulator pub type Partials = Vec<(usize, Box)>; @@ -227,8 +222,6 @@ pub struct LocalState { /// DuckDB's global multi-file lock; see `OpenFileReader`. pub(crate) retired_files: Vec>, pub(crate) retired_splits: Vec, - /// The planning run on which this thread runs the chunks of V2 scans. - pub(crate) run: Run, /// Chunks of an array that this thread has yet to export, in reverse order. pub(crate) pending: Vec, @@ -437,7 +430,6 @@ pub fn init_local(bind_data: &BindState, global: &GlobalState) -> LocalState { file: None, retired_files: Vec::new(), retired_splits: Vec::new(), - run: Run::new(), pending: Vec::new(), finished: false, } From 08ef4677ac185cb661fa6dd1f8a2a524b0acd533 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 17:20:44 -0500 Subject: [PATCH 65/80] Keep the futures::ready import that repeated_scan still uses Signed-off-by: Nicholas Gates Co-Authored-By: Claude Opus 5.5 --- vortex-layout/src/scan/repeated_scan.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/vortex-layout/src/scan/repeated_scan.rs b/vortex-layout/src/scan/repeated_scan.rs index 2d82f283dc4..be849306f4a 100644 --- a/vortex-layout/src/scan/repeated_scan.rs +++ b/vortex-layout/src/scan/repeated_scan.rs @@ -14,6 +14,7 @@ use futures::Stream; use futures::StreamExt; use futures::future; use futures::future::BoxFuture; +use futures::ready; use futures::stream; use futures::stream::BoxStream; use itertools::Either; From 5f32c1bf53517c0923ed107109b18e5e7b74104e Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 17:28:18 -0500 Subject: [PATCH 66/80] Name the sum type of a plan source's byte size Signed-off-by: Nicholas Gates Co-Authored-By: Claude Opus 5.5 --- vortex-scan/src/source/plan.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vortex-scan/src/source/plan.rs b/vortex-scan/src/source/plan.rs index b4926a083b3..c70e5f410fb 100644 --- a/vortex-scan/src/source/plan.rs +++ b/vortex-scan/src/source/plan.rs @@ -185,7 +185,7 @@ impl PlanDataSource { .map(|child| child.row_count) .sum::>() .map_or(Precision::Absent, Precision::exact); - let byte_size = Precision::inexact(children.iter().map(PlanChild::byte_size).sum()); + let byte_size = Precision::inexact(children.iter().map(PlanChild::byte_size).sum::()); Self { session, dtype, From 50e2dffd4a950c0c60f6a86bb0d84fda1d6c80da Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 17:41:36 -0500 Subject: [PATCH 67/80] Drop DuckDB's globally bound projection, which only the V2 queue read Both executors now bind the projection against each file through ScanRequest, so the bound copy in GlobalState and its helper go. Signed-off-by: Nicholas Gates Co-Authored-By: Claude Opus 5.5 --- vortex-duckdb/src/table_function.rs | 13 ++----------- 1 file changed, 2 insertions(+), 11 deletions(-) diff --git a/vortex-duckdb/src/table_function.rs b/vortex-duckdb/src/table_function.rs index 60cc0587576..18e1681a0a0 100644 --- a/vortex-duckdb/src/table_function.rs +++ b/vortex-duckdb/src/table_function.rs @@ -33,7 +33,6 @@ use vortex::error::VortexResult; use vortex::error::vortex_bail; use vortex::error::vortex_ensure; use vortex::error::vortex_err; -use vortex::expr::BoundExpression; use vortex::expr::Expression; use vortex::expr::col; use vortex::expr::proto::ExprSerializeProtoExt; @@ -181,8 +180,7 @@ impl<'a> TableInitInput<'a> { } pub struct GlobalState { - pub projection: BoundExpression, - /// The projection before binding, for scans that bind it against each file. + /// The projection before binding, which each file's scan binds against the file. pub projection_expr: Expression, pub filter: Filter, pub file_row_number_column_pos: Option, @@ -349,11 +347,8 @@ pub fn init_global(init_input: &TableInitInput) -> VortexResult { "table function scan input" ); - let projection_expr = projection.clone(); - let projection = optimize_and_bind(projection, &bind_data.dtype)?; Ok(GlobalState { - projection, - projection_expr, + projection_expr: projection, filter, aggregates: bind_data.aggregates.clone(), has_count_star, @@ -435,10 +430,6 @@ pub fn init_local(bind_data: &BindState, global: &GlobalState) -> LocalState { } } -pub(crate) fn optimize_and_bind(expr: Expression, dtype: &DType) -> VortexResult { - expr.bind(dtype)?.optimize_recursive() -} - pub(crate) fn convert_result(array: ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult { // By the time we got here, array is fully optimized, don't call // optimize_recursive or similar functions here. From 9411ff75ab532c1d5252cbe2cae63ed4e26ff702 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 20:55:34 -0500 Subject: [PATCH 68/80] Cut a V2 plan scan's parts in scan, so open reads nothing A dynamic filter's root reads zone maps before it cuts a child into parts. Running it in the async scan, which the host awaits, means opening only queues the parts, and no clone of the stream waits on another for its first work. The scan's work is known before it is opened, so the queue is a plain list. Signed-off-by: Nicholas Gates Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 1 - vortex-scan/Cargo.toml | 1 - vortex-scan/src/lib.rs | 5 + vortex-scan/src/source/plan.rs | 15 +- vortex-scan/src/source/plan_stream.rs | 228 +++++++++++--------------- 5 files changed, 116 insertions(+), 134 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index f05a00d3e7d..1baac90bd38 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -12358,7 +12358,6 @@ dependencies = [ name = "vortex-scan" version = "0.1.0" dependencies = [ - "async-channel", "async-lock", "async-trait", "bit-vec 0.10.2", diff --git a/vortex-scan/Cargo.toml b/vortex-scan/Cargo.toml index b2e0df7138b..9c1d41b1aa2 100644 --- a/vortex-scan/Cargo.toml +++ b/vortex-scan/Cargo.toml @@ -15,7 +15,6 @@ version = { workspace = true } all-features = true [dependencies] -async-channel = { workspace = true } async-lock = { workspace = true } async-trait = { workspace = true } bit-vec = { workspace = true } diff --git a/vortex-scan/src/lib.rs b/vortex-scan/src/lib.rs index d693b1d3bb8..aacdd3de337 100644 --- a/vortex-scan/src/lib.rs +++ b/vortex-scan/src/lib.rs @@ -222,6 +222,11 @@ pub type DataSourceScanRef = Box; /// order or a limit, on the [`ScanRequest`], and the source decides what the pieces are and how /// they run. /// +/// A source does the reads it needs to know a scan's units of work, such as pruning against zone +/// maps before cutting the scan into pieces, in the async [`DataSource::scan`], which the host +/// awaits. [`split`](Self::split) and [`open`](Self::open) are synchronous and read nothing, so +/// no clone of an opened stream waits on another for its first work. +/// /// A scan never starts threads. Its work may run as tasks on the session's runtime, which the /// host owns. pub trait DataSourceScan: 'static + Send { diff --git a/vortex-scan/src/source/plan.rs b/vortex-scan/src/source/plan.rs index c70e5f410fb..d65fcf16ba2 100644 --- a/vortex-scan/src/source/plan.rs +++ b/vortex-scan/src/source/plan.rs @@ -152,6 +152,9 @@ impl PlanChild { /// own rows, and its `partition_range` and `partition_selection` select children by ordinal. A /// scan reads its children in order. /// +/// Making an unordered scan does the reads it needs to know its units of work: it prepares each +/// child and cuts it into parts, which for a dynamic filter reads zone maps. +/// [`split`](DataSourceScan::split) and [`open`](DataSourceScan::open) read nothing. /// [`split`](DataSourceScan::split) returns a scan whole. [`open`](DataSourceScan::open) runs it /// on V2's planners and [`Run`](crate::planning::driver::Run) driver; see `plan_stream.rs`. A /// scan's one partition reads its opened stream. @@ -279,9 +282,17 @@ impl DataSource for PlanDataSource { ordered: request.ordered, limit: request.limit, }; + // An unordered scan's parts are its units of work, and cutting them can read zone maps, + // so it happens here, where the host awaits the scan, and opening reads nothing. + let planned = if state.ordered { + None + } else { + Some(plan_stream::plan(&state, &units).await?) + }; Ok(Box::new(PlanScan { state: Arc::new(state), units, + planned, })) } @@ -354,6 +365,8 @@ struct PlanScan { state: Arc, /// The scan's units, in child and row order. units: Vec, + /// The parts of an unordered scan, cut when the scan was made. + planned: Option, } impl DataSourceScan for PlanScan { @@ -366,7 +379,7 @@ impl DataSourceScan for PlanScan { } fn open(self: Box) -> VortexResult { - plan_stream::open(self.state, self.units) + plan_stream::open(self.state, self.units, self.planned) } fn partition_count(&self) -> Precision { diff --git a/vortex-scan/src/source/plan_stream.rs b/vortex-scan/src/source/plan_stream.rs index bd58a2da7cc..ef2b3e7f996 100644 --- a/vortex-scan/src/source/plan_stream.rs +++ b/vortex-scan/src/source/plan_stream.rs @@ -4,18 +4,21 @@ //! The stream of an opened [`PlanDataSource`](super::PlanDataSource) scan: V2's planners and //! [`Run`] driver behind [`ScanStream`]. //! -//! An unordered scan prepares each child once and runs its [`part_root`], which cuts the child -//! into parts: the rows between the child's splits for the fields the scan reads, such as a -//! file's layout splits, or the scan's chunks for a child without splits. The parts go into one -//! queue that every clone of the stream takes from. Each clone owns a [`Run`], driven on the task -//! that polls the clone, and runs one part on it at a time: the part's chunks run side by side, -//! so one chunk's reads overlap another's compute, batches are returned as they are produced, and -//! reads are awaited with [`Run::poll_completion`]. Nothing is spawned, so a host that polls a -//! clone with `block_on` runs the scan's compute on its own thread. +//! When an unordered scan is made, it prepares each child once and runs its [`part_root`], which +//! cuts the child into parts: the rows between the child's splits for the fields the scan reads, +//! such as a file's layout splits, or the scan's chunks for a child without splits. With a dynamic +//! filter, such as the bound a top-N pushes down, the root first prunes the child as a whole +//! against the bound as it stands, which reads zone maps. Those are the reads the scan needs to +//! know its units of work, so they run in the async [`scan`](crate::DataSource::scan), which the +//! host awaits. Opening the scan reads nothing: it only queues the parts, so no clone waits on +//! another for its work. Each part prunes again against the bound as it stands when a clone takes +//! it. //! -//! With a dynamic filter, such as the bound a top-N pushes down, a child's root prunes the child as -//! a whole before it cuts parts, which reads zone maps. Opening reads nothing, so such a root is -//! queued work too: the first clone to take it runs it and queues its parts. +//! Every clone of the stream takes parts from the one queue. Each clone owns a [`Run`], driven on +//! the task that polls the clone, and runs one part on it at a time: the part's chunks run side by +//! side, so one chunk's reads overlap another's compute, batches are returned as they are +//! produced, and reads are awaited with [`Run::poll_completion`]. Nothing is spawned, so a host +//! that polls a clone with `block_on` runs the scan's compute on its own thread. //! //! An ordered scan returns its rows in order through the first clone to be polled, running one //! child after another on [`ScanDriver`], which keeps a scan's chunks in order. Later clones @@ -25,18 +28,16 @@ //! A limit is one [`RowLimit`] for the whole stream: clones stop taking parts once it is spent, //! and each clone's output is trimmed to it. +use std::collections::VecDeque; use std::future; use std::iter; use std::ops::Range; use std::sync::Arc; +use std::sync::atomic::AtomicBool; use std::sync::atomic::AtomicU64; use std::sync::atomic::Ordering; -use async_channel::Receiver; -use async_channel::Sender; -use futures::FutureExt; use futures::StreamExt; -use futures::future::BoxFuture; use futures::stream; use futures::stream::BoxStream; use parking_lot::Mutex; @@ -61,8 +62,36 @@ use crate::prepare::PreparedScan; use crate::prepare::part_root; use crate::stream::ScanStream; -/// Opens the stream of the scan's `units`. -pub(super) fn open(state: Arc, units: Vec) -> VortexResult { +/// The parts of an unordered scan, cut when the scan is made. +pub(super) struct Planned { + work: Vec, + /// The rows of the scan's units. + total_rows: u64, +} + +/// Prepares each of the scan's `units` once and runs its root, awaiting the zone maps a dynamic +/// filter's root reads, and returns the work the roots produce, in unit and row order. +pub(super) async fn plan(state: &ScanState, units: &[Unit]) -> VortexResult { + let mut work = Vec::new(); + let mut total_rows = 0; + for unit in units { + let rows = state.unit_rows(unit)?; + if rows.is_empty() { + continue; + } + total_rows += rows.end - rows.start; + let (child, root) = prepare(state, unit, rows)?; + work.extend(run_root(child, root).await?); + } + Ok(Planned { work, total_rows }) +} + +/// Opens the stream of a scan of `units`. An unordered scan reads the parts it `planned`. +pub(super) fn open( + state: Arc, + units: Vec, + planned: Option, +) -> VortexResult { let dtype = state.dtype.clone(); let limit = state.limit.map(RowLimit::new); if state.ordered { @@ -76,34 +105,11 @@ pub(super) fn open(state: Arc, units: Vec) -> VortexResult, } -/// Prepares the scan of `rows` of the unit's child once and composes its root, returning whether -/// the root reads before it spawns parts. +/// Prepares the scan of `rows` of the unit's child once and composes its root. fn prepare( state: &ScanState, unit: &Unit, rows: Range, -) -> VortexResult<(Arc, Box, bool)> { +) -> VortexResult<(Arc, Box)> { let child = state.child(unit.child); let splits = child.splits(&state.projection, state.filter.as_ref())?; let scan = Arc::new(state.builder(child, rows).prepare()?); @@ -161,7 +166,7 @@ fn prepare( rows: scan.rows().clone(), io: scan.io(), }; - Ok((Arc::new(prepared), root, dynamic && scan.filter().is_some())) + Ok((Arc::new(prepared), root)) } /// The boundaries of `scan`'s chunks, which cut the work of a child without splits of its own. @@ -175,34 +180,28 @@ fn chunk_bounds(scan: &PreparedScan) -> Vec { /// Runs a child's root on a run of its own, awaiting only its reads, and returns the work it /// produces, in row order: the parts it spawns, and any batch it returns itself. -fn run_root( - child: Arc, - root: Box, -) -> BoxFuture<'static, VortexResult>> { - async move { - let mut run = Run::new(); - let scope = WorkScope { - file_ordinal: 0, - rows: child.rows.clone(), - }; - run.admit(root, scope, child.io.session()); - let mut work = Vec::new(); - loop { - match run.advance()? { - Progress::Spawn(scope, planner) => work.push(Work::Part(Part { - child: Arc::clone(&child), - scope, - planner, - })), - Progress::Batch(batch) => work.push(Work::Batch(batch.array)), - Progress::RootDone(_) if run.live_roots() > 0 => {} - Progress::RootDone(_) | Progress::Idle => break, - Progress::Waiting => future::poll_fn(|cx| run.poll_completion(cx)).await?, - } +async fn run_root(child: Arc, root: Box) -> VortexResult> { + let mut run = Run::new(); + let scope = WorkScope { + file_ordinal: 0, + rows: child.rows.clone(), + }; + run.admit(root, scope, child.io.session()); + let mut work = Vec::new(); + loop { + match run.advance()? { + Progress::Spawn(scope, planner) => work.push(Work::Part(Part { + child: Arc::clone(&child), + scope, + planner, + })), + Progress::Batch(batch) => work.push(Work::Batch(batch.array)), + Progress::RootDone(_) if run.live_roots() > 0 => {} + Progress::RootDone(_) | Progress::Idle => break, + Progress::Waiting => future::poll_fn(|cx| run.poll_completion(cx)).await?, } - Ok(work) } - .boxed() + Ok(work) } /// A unit of work in the queue of an unordered scan. @@ -210,19 +209,14 @@ enum Work { Part(Part), /// A batch a root returned itself. Batch(ArrayRef), - /// A root that reads before it spawns parts, and the queue to send its parts to. The sender - /// keeps the queue open until they are in it. - Root(BoxFuture<'static, VortexResult>>, Sender), -} - -fn send(sender: &Sender, work: Work) { - // The queue is unbounded and closes only once every clone is dropped, when the work is moot. - drop(sender.try_send(work)); } /// The queue of an unordered scan, which every clone of its stream takes from. struct Queue { - receiver: Receiver, + /// The work no clone has taken yet, in unit and row order. + work: Mutex>, + /// Set once a clone has taken the last of `work`. + exhausted: AtomicBool, /// The rows of the scan's units. total_rows: u64, /// The rows of the parts clones have taken. @@ -230,27 +224,30 @@ struct Queue { } impl Queue { + /// Takes the next work, or `None` once every one has been taken. + fn take(&self) -> Option { + let mut queue = self.work.lock(); + let work = queue.pop_front()?; + if queue.is_empty() { + self.exhausted.store(true, Ordering::Release); + } + if let Work::Part(part) = &work { + self.rows_taken.fetch_add( + part.scope.rows.end - part.scope.rows.start, + Ordering::Relaxed, + ); + } + Some(work) + } + /// The fraction of the scan's rows whose parts clones have taken. Pruning can leave rows that /// no part covers, so a queue with nothing left to take has made all of its progress. fn progress(&self) -> f64 { - if self.total_rows == 0 || self.is_drained() { + if self.total_rows == 0 || self.exhausted.load(Ordering::Relaxed) { return 1.0; } (self.rows_taken.load(Ordering::Relaxed) as f64 / self.total_rows as f64).min(1.0) } - - /// Whether the queue is empty and no root is left that could add to it. - fn is_drained(&self) -> bool { - self.receiver.is_empty() && self.receiver.sender_count() == 0 - } -} - -impl Drop for Queue { - fn drop(&mut self) { - // Queued roots hold senders of the queue itself; drain them so it can be freed. - self.receiver.close(); - while self.receiver.try_recv().is_ok() {} - } } /// One clone's worker: a run of its own, fed one part at a time from the scan's queue, and driven @@ -271,10 +268,10 @@ impl Worker { if self.limit.as_ref().is_some_and(RowLimit::is_exhausted) { return Ok(None); } - match self.take().await? { + match self.queue.take() { None => return Ok(None), - Some(Taken::Batch(array)) => return Ok(Some(array)), - Some(Taken::Part(part)) => { + Some(Work::Batch(array)) => return Ok(Some(array)), + Some(Work::Part(part)) => { self.run .admit(part.planner, part.scope, part.child.io.session()); self.child = Some(part.child); @@ -297,37 +294,6 @@ impl Worker { } } } - - /// Takes the next part or batch from the scan's queue, running the roots it finds there - /// first, or `None` once the queue is closed and empty. - async fn take(&mut self) -> VortexResult> { - loop { - let Ok(work) = self.queue.receiver.recv().await else { - return Ok(None); - }; - match work { - Work::Part(part) => { - self.queue.rows_taken.fetch_add( - part.scope.rows.end - part.scope.rows.start, - Ordering::Relaxed, - ); - return Ok(Some(Taken::Part(part))); - } - Work::Batch(array) => return Ok(Some(Taken::Batch(array))), - Work::Root(work, sender) => { - for work in work.await? { - send(&sender, work); - } - } - } - } - } -} - -/// What a worker takes from the queue. -enum Taken { - Part(Part), - Batch(ArrayRef), } /// The arrays of an ordered scan: each unit's rows in order, one unit after another. From e572270dbf031c84d2b221ae89d1386f74b82801 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 20:55:41 -0500 Subject: [PATCH 69/80] Describe when a dynamic filter prunes a file in the plan source tests Signed-off-by: Nicholas Gates Co-Authored-By: Claude Opus 5.5 --- vortex-file/src/plan_tests.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/vortex-file/src/plan_tests.rs b/vortex-file/src/plan_tests.rs index 0a468e31990..66267ff6776 100644 --- a/vortex-file/src/plan_tests.rs +++ b/vortex-file/src/plan_tests.rs @@ -263,15 +263,15 @@ async fn open_cuts_parts_on_layout_splits() -> VortexResult<()> { Ok(()) } -/// A dynamic filter, such as a top-N's bound, prunes a file as a whole before its parts are cut, -/// as queued work rather than in `open`. The rows follow the bound as it stands when the workers -/// read, not as it stood when the scan was opened. +/// A dynamic filter, such as a top-N's bound, prunes a file as a whole when the scan is made, +/// before its parts are cut. The rows follow the bound as it stands when the clones read, not as +/// it stood when the scan was made. #[rstest] #[case::unordered(false)] #[case::ordered(true)] #[tokio::test(flavor = "multi_thread", worker_threads = 4)] #[cfg_attr(miri, ignore)] -async fn open_prunes_the_file_first_for_a_dynamic_filter( +async fn scan_prunes_the_file_first_for_a_dynamic_filter( #[case] ordered: bool, ) -> VortexResult<()> { let bound = Arc::new(AtomicU32::new(0)); From 7fb994d718cc86047bfb33a02300cb2db1a6a764 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 21:01:50 -0500 Subject: [PATCH 70/80] Stop DuckDB threads joining a file once its splits are covered Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-duckdb/src/file_reader.rs | 29 ++++++++++++++--- vortex-layout/src/scan/layout.rs | 20 ++++++++++-- vortex-layout/src/scan/split_queue.rs | 11 ++++--- vortex-scan/src/stream.rs | 46 +++++++++++++++++++-------- 4 files changed, 80 insertions(+), 26 deletions(-) diff --git a/vortex-duckdb/src/file_reader.rs b/vortex-duckdb/src/file_reader.rs index c6c1969fcda..07f0c4b3c38 100644 --- a/vortex-duckdb/src/file_reader.rs +++ b/vortex-duckdb/src/file_reader.rs @@ -6,6 +6,7 @@ use std::ops::Range; use std::sync::Arc; use std::sync::OnceLock; use std::sync::atomic::AtomicBool; +use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering; use futures::FutureExt; @@ -42,6 +43,7 @@ use vortex::layout::scan::v2::ScanFile; use vortex::mask::Mask; use vortex::scan::DataSource as _; use vortex::scan::ScanRequest; +use vortex::scan::stream::Claims; use vortex::scan::stream::ScanStream; use vortex::session::SessionExt as _; @@ -143,6 +145,8 @@ pub struct FileScanState { stream: OnceLock>, /// Whether a clone of `stream` has ended, so no split of the file is left to claim. finished: AtomicBool, + /// How many threads have joined the file, each with its own clone of `stream`. + joined: AtomicUsize, cache: ConversionCache, } @@ -159,9 +163,17 @@ impl FileScanState { if self.finished.load(Ordering::Acquire) { return None; } - self.stream - .get() - .map(|stream| Split::V1(stream.lock().clone())) + let stream = self.stream.get()?.lock(); + // A clone claims its first split only when its thread first polls it, outside DuckDB's + // lock, so without a bound every thread would join before any had claimed. As many + // clones as splits drain the file, so a later thread moves on instead. + if let Some(Claims { claimed, total }) = stream.claims() + && (claimed >= total || self.joined.load(Ordering::Relaxed) >= total) + { + return None; + } + self.joined.fetch_add(1, Ordering::Relaxed); + Some(Split::V1(stream.clone())) } } @@ -179,6 +191,7 @@ impl OpenFileReader { v2: OnceLock::new(), stream: OnceLock::new(), finished: AtomicBool::new(false), + joined: AtomicUsize::new(0), cache: ConversionCache::default(), })), }) @@ -522,8 +535,14 @@ pub fn reader_get_progress_in_file(file: &OpenFileReader) -> f64 { state .stream .get() - .and_then(|stream| stream.lock().progress()) - .map_or(0.0, |progress| 100.0 * progress) + .and_then(|stream| stream.lock().claims()) + .map_or(0.0, |Claims { claimed, total }| { + if total == 0 { + 100.0 + } else { + 100.0 * claimed as f64 / total as f64 + } + }) } /// Called by one thread in planning phase diff --git a/vortex-layout/src/scan/layout.rs b/vortex-layout/src/scan/layout.rs index 9f555b7a1bc..a05e8519f1f 100644 --- a/vortex-layout/src/scan/layout.rs +++ b/vortex-layout/src/scan/layout.rs @@ -329,10 +329,10 @@ impl DataSourceScan for LayoutReaderScan { .prepare()? .execute(Some(self.next_row..self.end_row))?; let queue = Arc::new(SplitQueue::new(self.session.handle(), per_worker, splits)); - let progress = Arc::clone(&queue); + let claims = Arc::clone(&queue); Ok( ScanStream::new(self.dtype, move || Arc::clone(&queue).worker()) - .with_progress(move || progress.progress()), + .with_claims(move || claims.claims()), ) } @@ -760,6 +760,7 @@ mod split_open_tests { use vortex_io::runtime::single::SingleThreadRuntime; use vortex_scan::DataSource; use vortex_scan::ScanRequest; + use vortex_scan::stream::Claims; use super::LayoutReaderDataSource; use super::group_contiguous; @@ -782,12 +783,25 @@ mod split_open_tests { let stream = runtime .block_on(source(&runtime).scan(ScanRequest::default()))? .open()?; + assert_eq!( + stream.claims(), + Some(Claims { + claimed: 0, + total: 16 + }) + ); let workers = (0..3).map(|_| stream.clone().try_collect::>()); let arrays = runtime.block_on(try_join_all(workers))?; let mut values = collect_scan_values(arrays.into_iter().flatten().map(Ok))?; values.sort_unstable(); assert_eq!(values, (0..64).collect::>()); - assert_eq!(stream.progress(), Some(1.0)); + assert_eq!( + stream.claims(), + Some(Claims { + claimed: 16, + total: 16 + }) + ); Ok(()) } diff --git a/vortex-layout/src/scan/split_queue.rs b/vortex-layout/src/scan/split_queue.rs index 463eeb72828..ab1c0a977e2 100644 --- a/vortex-layout/src/scan/split_queue.rs +++ b/vortex-layout/src/scan/split_queue.rs @@ -18,6 +18,7 @@ use parking_lot::Mutex; use vortex_array::ArrayRef; use vortex_error::VortexResult; use vortex_io::runtime::Handle; +use vortex_scan::stream::Claims; use crate::scan::repeated_scan::ScanTasks; @@ -68,12 +69,12 @@ impl SplitQueue { Some(split) } - /// The fraction of the splits that the stream's clones have claimed. - pub(crate) fn progress(&self) -> f64 { - if self.total == 0 { - return 1.0; + /// How many of the splits the stream's clones have claimed, out of how many in all. + pub(crate) fn claims(&self) -> Claims { + Claims { + claimed: self.claimed.load(Ordering::Relaxed).min(self.total), + total: self.total, } - (self.claimed.load(Ordering::Relaxed) as f64 / self.total as f64).min(1.0) } /// A new worker over the shared queue, which one clone of the scan's stream polls. diff --git a/vortex-scan/src/stream.rs b/vortex-scan/src/stream.rs index 27dfc53ebdf..cadc8fcc3e3 100644 --- a/vortex-scan/src/stream.rs +++ b/vortex-scan/src/stream.rs @@ -21,8 +21,20 @@ use crate::DataSourceScanRef; /// Starts a new worker over the shared work of an opened scan. type NewWorker = dyn Fn() -> BoxStream<'static, VortexResult> + Send + Sync; -/// Reads the fraction of an opened scan's work that its clones have taken. -type Progress = dyn Fn() -> f64 + Send + Sync; +/// Reads how many units of an opened scan's work its clones have claimed. +type ReadClaims = dyn Fn() -> Claims + Send + Sync; + +/// How many units of an opened scan's work its clones have claimed, out of how many in all. +/// +/// A unit is what one clone claims at a time, such as a split of a layout scan. Claims only grow, +/// and `claimed` never exceeds `total`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Claims { + /// The units that clones have claimed so far. + pub claimed: usize, + /// The units of the scan in all. + pub total: usize, +} /// The arrays of an opened scan, which host threads read by each polling a clone. /// @@ -37,7 +49,7 @@ type Progress = dyn Fn() -> f64 + Send + Sync; pub struct ScanStream { dtype: DType, new_worker: Arc, - progress: Option>, + claims: Option>, worker: Option>>, } @@ -53,22 +65,30 @@ impl ScanStream { Self { dtype, new_worker: Arc::new(new_worker), - progress: None, + claims: None, worker: None, } } - /// This stream, reporting its progress through `progress`, which returns the fraction of the - /// scan's work that its clones have taken, from 0.0 to 1.0, and must never block. - pub fn with_progress(mut self, progress: impl Fn() -> f64 + Send + Sync + 'static) -> Self { - self.progress = Some(Arc::new(progress)); + /// This stream, reporting through `claims` how many units of its work its clones have + /// claimed, out of how many in all. `claims` must never block. + pub fn with_claims(mut self, claims: impl Fn() -> Claims + Send + Sync + 'static) -> Self { + self.claims = Some(Arc::new(claims)); self } - /// The fraction of the scan's work that its clones have taken, from 0.0 to 1.0, for a host's - /// progress bar, or `None` when the scan does not track it. Never blocks. - pub fn progress(&self) -> Option { - self.progress.as_ref().map(|progress| progress()) + /// How many units of the scan's work its clones have claimed, out of how many in all, or + /// `None` when the source does not know its total up front, as for a stream from + /// [`Self::from_partitions`]. Never blocks. + /// + /// A host derives its progress from this. It also bounds how many clones a host needs: a + /// host that hands out clones under its own lock may stop once it has handed out `total` + /// clones, or once `claimed` reaches `total`, because the clones already handed out keep + /// claiming units until none is left and so drain the rest. A clone handed out after that + /// would find nothing to claim. When this is `None` the host cannot bound its clones this + /// way, and learns that no work is left only when a clone ends. + pub fn claims(&self) -> Option { + self.claims.as_ref().map(|claims| claims()) } /// A stream whose clones take the partitions of `scan` one at a time. @@ -99,7 +119,7 @@ impl Clone for ScanStream { Self { dtype: self.dtype.clone(), new_worker: Arc::clone(&self.new_worker), - progress: self.progress.clone(), + claims: self.claims.clone(), worker: None, } } From a4c5be8b55e2911b65ace44e0bf5ecb7b24a8824 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Mon, 23 Nov 2026 17:48:03 -0500 Subject: [PATCH 71/80] Skip the executor in block_on when the future is already ready Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-io/src/runtime/current.rs | 32 ++++++++++++++++++++++++++++++-- 1 file changed, 30 insertions(+), 2 deletions(-) diff --git a/vortex-io/src/runtime/current.rs b/vortex-io/src/runtime/current.rs index 203d7858359..adea7c77386 100644 --- a/vortex-io/src/runtime/current.rs +++ b/vortex-io/src/runtime/current.rs @@ -2,9 +2,11 @@ // SPDX-FileCopyrightText: Copyright the Vortex contributors use std::future::Future; +use std::pin::pin; use std::sync::Arc; use async_channel::TryRecvError; +use futures::FutureExt; use futures::SinkExt; use futures::Stream; use futures::StreamExt; @@ -136,7 +138,7 @@ impl BlockingRuntime for CurrentThreadRuntime { where Fut: Future, { - block_on(self.executor.run(fut)) + drive(&self.executor, fut) } fn block_on_stream<'a, S, R>(&self, stream: S) -> Self::BlockingIterator<'a, R> @@ -151,6 +153,22 @@ impl BlockingRuntime for CurrentThreadRuntime { } } +/// Drives `fut` to completion on the calling thread. +/// +/// The future is polled once before entering the executor and returned from directly if it is +/// ready. Each entry into [`smol::Executor::run`] registers the thread with the executor's shared +/// state, under a write lock that every thread entering the runtime contends on, and a caller that +/// blocks on many futures which are mostly ready already, such as one batch of a scan after +/// another, would otherwise pay that for each of them. A future that is not ready is polled again +/// inside the executor, which runs the runtime's tasks while the thread waits for it. +fn drive(executor: &SmolExecutor, fut: Fut) -> Fut::Output { + let mut fut = pin!(fut); + if let Some(output) = fut.as_mut().now_or_never() { + return output; + } + block_on(executor.run(fut)) +} + /// An iterator that wraps up a stream to drive it using the current thread execution. pub struct CurrentThreadIterator<'a, T> { executor: Arc, @@ -161,7 +179,7 @@ impl Iterator for CurrentThreadIterator<'_, T> { type Item = T; fn next(&mut self) -> Option { - block_on(self.executor.run(self.stream.next())) + drive(&self.executor, self.stream.next()) } } @@ -259,6 +277,16 @@ mod tests { use super::*; + #[test] + fn block_on_runs_tasks_for_a_future_that_is_not_ready() { + let runtime = CurrentThreadRuntime::new(); + assert_eq!(runtime.block_on(async { 7 }), 7); + // The spawned task has not run when the future is first polled, so it is ready only once + // block_on enters the executor, which runs the task. + let task = runtime.handle().spawn(async { 11 }); + assert_eq!(runtime.block_on(task), 11); + } + #[test] fn test_worker_thread() { let runtime = CurrentThreadRuntime::new(); From c5d9897a6d6db6419a0964d47e84b1fdb16fd2f3 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Mon, 23 Nov 2026 19:15:22 -0500 Subject: [PATCH 72/80] Report a V2 plan scan's claimed parts on its stream Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-scan/src/source/plan_stream.rs | 53 +++++++++------------------ vortex-scan/src/source/tests.rs | 6 ++- 2 files changed, 23 insertions(+), 36 deletions(-) diff --git a/vortex-scan/src/source/plan_stream.rs b/vortex-scan/src/source/plan_stream.rs index ef2b3e7f996..ba2013921e1 100644 --- a/vortex-scan/src/source/plan_stream.rs +++ b/vortex-scan/src/source/plan_stream.rs @@ -33,8 +33,7 @@ use std::future; use std::iter; use std::ops::Range; use std::sync::Arc; -use std::sync::atomic::AtomicBool; -use std::sync::atomic::AtomicU64; +use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering; use futures::StreamExt; @@ -60,30 +59,27 @@ use crate::planning::planner::Planner; use crate::planning::planner::WorkScope; use crate::prepare::PreparedScan; use crate::prepare::part_root; +use crate::stream::Claims; use crate::stream::ScanStream; /// The parts of an unordered scan, cut when the scan is made. pub(super) struct Planned { work: Vec, - /// The rows of the scan's units. - total_rows: u64, } /// Prepares each of the scan's `units` once and runs its root, awaiting the zone maps a dynamic /// filter's root reads, and returns the work the roots produce, in unit and row order. pub(super) async fn plan(state: &ScanState, units: &[Unit]) -> VortexResult { let mut work = Vec::new(); - let mut total_rows = 0; for unit in units { let rows = state.unit_rows(unit)?; if rows.is_empty() { continue; } - total_rows += rows.end - rows.start; let (child, root) = prepare(state, unit, rows)?; work.extend(run_root(child, root).await?); } - Ok(Planned { work, total_rows }) + Ok(Planned { work }) } /// Opens the stream of a scan of `units`. An unordered scan reads the parts it `planned`. @@ -107,12 +103,11 @@ pub(super) fn open( let planned = planned.vortex_expect("an unordered scan cuts its parts when it is made"); let queue = Arc::new(Queue { - exhausted: AtomicBool::new(planned.work.is_empty()), + total: planned.work.len(), work: Mutex::new(planned.work.into()), - total_rows: planned.total_rows, - rows_taken: AtomicU64::new(0), + taken: AtomicUsize::new(0), }); - let progress = Arc::clone(&queue); + let claims = Arc::clone(&queue); Ok(ScanStream::new(dtype, move || { let worker = Worker { queue: Arc::clone(&queue), @@ -131,7 +126,7 @@ pub(super) fn open( .boxed(); limited(arrays, limit.clone()) }) - .with_progress(move || progress.progress())) + .with_claims(move || claims.claims())) } /// One child's prepared scan, shared by the parts of it that clones run. @@ -215,38 +210,26 @@ enum Work { struct Queue { /// The work no clone has taken yet, in unit and row order. work: Mutex>, - /// Set once a clone has taken the last of `work`. - exhausted: AtomicBool, - /// The rows of the scan's units. - total_rows: u64, - /// The rows of the parts clones have taken. - rows_taken: AtomicU64, + /// The work the queue started with. + total: usize, + /// The work clones have taken. + taken: AtomicUsize, } impl Queue { /// Takes the next work, or `None` once every one has been taken. fn take(&self) -> Option { - let mut queue = self.work.lock(); - let work = queue.pop_front()?; - if queue.is_empty() { - self.exhausted.store(true, Ordering::Release); - } - if let Work::Part(part) = &work { - self.rows_taken.fetch_add( - part.scope.rows.end - part.scope.rows.start, - Ordering::Relaxed, - ); - } + let work = self.work.lock().pop_front()?; + self.taken.fetch_add(1, Ordering::Relaxed); Some(work) } - /// The fraction of the scan's rows whose parts clones have taken. Pruning can leave rows that - /// no part covers, so a queue with nothing left to take has made all of its progress. - fn progress(&self) -> f64 { - if self.total_rows == 0 || self.exhausted.load(Ordering::Relaxed) { - return 1.0; + /// How much of the queue's work clones have taken, out of how much in all. + fn claims(&self) -> Claims { + Claims { + claimed: self.taken.load(Ordering::Relaxed).min(self.total), + total: self.total, } - (self.rows_taken.load(Ordering::Relaxed) as f64 / self.total_rows as f64).min(1.0) } } diff --git a/vortex-scan/src/source/tests.rs b/vortex-scan/src/source/tests.rs index daeb32082b5..3f5793abdaa 100644 --- a/vortex-scan/src/source/tests.rs +++ b/vortex-scan/src/source/tests.rs @@ -192,7 +192,11 @@ async fn clones_share_the_scan() -> VortexResult<()> { .map(|clone| clone.try_collect::>()), ) .await?; - assert_eq!(stream.progress(), Some(1.0)); + assert!( + stream + .claims() + .is_some_and(|claims| claims.total > 0 && claims.claimed == claims.total) + ); let mut ctx = VortexSession::empty().create_execution_ctx(); let mut values = Vec::new(); for batch in batches.into_iter().flatten() { From ae8d4bb31edd02e5e8984a81a73eb8422b193381 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Mon, 23 Nov 2026 19:48:54 -0500 Subject: [PATCH 73/80] Re-run pull request checks GitHub did not rebuild this pull request's merge ref after the previous push. Signed-off-by: Nicholas Gates Co-Authored-By: Claude Opus 5.5 From e946027690e0e91c230d0d1ce31b28c584e92ab5 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Mon, 23 Nov 2026 21:06:42 -0500 Subject: [PATCH 74/80] Import DynamicExprUpdates from vortex-functions, where develop moved it Signed-off-by: Nicholas Gates Co-Authored-By: Claude Opus 5.5 --- vortex-scan/src/source/plan_stream.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vortex-scan/src/source/plan_stream.rs b/vortex-scan/src/source/plan_stream.rs index ba2013921e1..d1d193e96b6 100644 --- a/vortex-scan/src/source/plan_stream.rs +++ b/vortex-scan/src/source/plan_stream.rs @@ -41,9 +41,9 @@ use futures::stream; use futures::stream::BoxStream; use parking_lot::Mutex; use vortex_array::ArrayRef; -use vortex_array::scalar_fn::fns::dynamic::DynamicExprUpdates; use vortex_error::VortexExpect; use vortex_error::VortexResult; +use vortex_functions::dynamic::DynamicExprUpdates; use vortex_io::request::IoService; use vortex_io::session::RuntimeSessionExt; From 211d1b149c290cb0c190bf6d0bba830aaca469a3 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Mon, 23 Nov 2026 21:06:49 -0500 Subject: [PATCH 75/80] 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 ee738658d603ee671461ec54e9db439f0af5027a Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Mon, 23 Nov 2026 21:12:02 -0500 Subject: [PATCH 76/80] Import the moved dynamic and CompareOperator in the plan source tests Signed-off-by: Nicholas Gates Co-Authored-By: Claude Opus 5.5 --- vortex-file/src/plan_tests.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/vortex-file/src/plan_tests.rs b/vortex-file/src/plan_tests.rs index 66267ff6776..61ff6843143 100644 --- a/vortex-file/src/plan_tests.rs +++ b/vortex-file/src/plan_tests.rs @@ -25,18 +25,18 @@ use vortex_array::dtype::DType; use vortex_array::dtype::Nullability; use vortex_array::dtype::PType; use vortex_array::expr::Expression; -use vortex_array::expr::dynamic; use vortex_array::expr::get_item; use vortex_array::expr::gt; use vortex_array::expr::lit; use vortex_array::expr::root; -use vortex_array::scalar_fn::fns::operators::CompareOperator; +use vortex_array::scalar_fn::builtin::operators::CompareOperator; use vortex_buffer::Alignment; use vortex_buffer::Buffer; use vortex_buffer::ByteBuffer; use vortex_buffer::ByteBufferMut; use vortex_error::VortexResult; use vortex_error::vortex_err; +use vortex_functions::expr::dynamic; use vortex_io::VortexReadAt; use vortex_io::session::RuntimeSession; use vortex_layout::scan::scan_builder::ScanBuilder; From 911088f9ddabb4e35c87e14ffa177ff0723bff5b Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Mon, 23 Nov 2026 21:12:02 -0500 Subject: [PATCH 77/80] Drop DuckDB's unused DynamicExprUpdates import Signed-off-by: Nicholas Gates Co-Authored-By: Claude Opus 5.5 --- vortex-duckdb/src/file_reader.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/vortex-duckdb/src/file_reader.rs b/vortex-duckdb/src/file_reader.rs index 3e11994a43e..a11e9a6a25a 100644 --- a/vortex-duckdb/src/file_reader.rs +++ b/vortex-duckdb/src/file_reader.rs @@ -29,7 +29,6 @@ use vortex::file::multi::MultiFileSession; use vortex::file::multi::open_cached; use vortex::file::multi::parse_uri_or_path; use vortex::file::v2::FileStatsLayoutReader; -use vortex::functions::dynamic::DynamicExprUpdates; use vortex::io::compat::Compat; use vortex::io::filesystem::FileSystemRef; use vortex::io::object_store::ObjectStoreFileSystem; From db074535f821efa8b15bb540b02292e0cd4ea9de Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Mon, 23 Nov 2026 22:10:48 -0500 Subject: [PATCH 78/80] 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 { From c722c017c3eea2bba39a4008a59d53e215f2d408 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Mon, 23 Nov 2026 22:15:59 -0500 Subject: [PATCH 79/80] Open a plan source scan into a ScanExec The queue marks the scan exhausted when its last part is taken or its limit is spent, and an ordered scan once its first stream exists. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-scan/src/source/plan.rs | 8 +-- vortex-scan/src/source/plan_stream.rs | 85 ++++++++++++++++----------- vortex-scan/src/source/tests.rs | 18 +++--- 3 files changed, 66 insertions(+), 45 deletions(-) diff --git a/vortex-scan/src/source/plan.rs b/vortex-scan/src/source/plan.rs index d65fcf16ba2..aaefdce7c9a 100644 --- a/vortex-scan/src/source/plan.rs +++ b/vortex-scan/src/source/plan.rs @@ -36,7 +36,7 @@ use crate::PartitionStream; use crate::ScanRequest; use crate::prepare::ScanBuilder; use crate::selection::Selection; -use crate::stream::ScanStream; +use crate::stream::ScanExec; /// Whether a child's own statistics, such as a file footer's, prove a filter, bound to the /// child's dtype, false for every row of the child. @@ -378,7 +378,7 @@ impl DataSourceScan for PlanScan { Ok(vec![self]) } - fn open(self: Box) -> VortexResult { + fn open(self: Box) -> VortexResult { plan_stream::open(self.state, self.units, self.planned) } @@ -391,7 +391,7 @@ impl DataSourceScan for PlanScan { } } -/// A scan of a [`PlanDataSource`] as its one partition, which reads the scan's opened stream. +/// A scan of a [`PlanDataSource`] as its one partition, which reads one stream of the opened scan. struct PlanPartition(Box); impl Partition for PlanPartition { @@ -412,6 +412,6 @@ impl Partition for PlanPartition { } fn execute(self: Box) -> VortexResult { - Ok(Box::pin(self.0.open()?)) + Ok(Box::pin(self.0.open()?.stream())) } } diff --git a/vortex-scan/src/source/plan_stream.rs b/vortex-scan/src/source/plan_stream.rs index d1d193e96b6..549294bb694 100644 --- a/vortex-scan/src/source/plan_stream.rs +++ b/vortex-scan/src/source/plan_stream.rs @@ -1,8 +1,8 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors -//! The stream of an opened [`PlanDataSource`](super::PlanDataSource) scan: V2's planners and -//! [`Run`] driver behind [`ScanStream`]. +//! An opened [`PlanDataSource`](super::PlanDataSource) scan: V2's planners and [`Run`] driver +//! behind [`ScanExec`] and its [`ScanStream`](crate::stream::ScanStream)s. //! //! When an unordered scan is made, it prepares each child once and runs its [`part_root`], which //! cuts the child into parts: the rows between the child's splits for the fields the scan reads, @@ -10,23 +10,24 @@ //! filter, such as the bound a top-N pushes down, the root first prunes the child as a whole //! against the bound as it stands, which reads zone maps. Those are the reads the scan needs to //! know its units of work, so they run in the async [`scan`](crate::DataSource::scan), which the -//! host awaits. Opening the scan reads nothing: it only queues the parts, so no clone waits on -//! another for its work. Each part prunes again against the bound as it stands when a clone takes -//! it. +//! host awaits. Opening the scan reads nothing: it only queues the parts, so no stream waits on +//! another for its work. Each part prunes again against the bound as it stands when a stream +//! takes it. //! -//! Every clone of the stream takes parts from the one queue. Each clone owns a [`Run`], driven on -//! the task that polls the clone, and runs one part on it at a time: the part's chunks run side by -//! side, so one chunk's reads overlap another's compute, batches are returned as they are -//! produced, and reads are awaited with [`Run::poll_completion`]. Nothing is spawned, so a host -//! that polls a clone with `block_on` runs the scan's compute on its own thread. +//! Every stream of the scan takes parts from the one queue, and the scan is exhausted once the +//! last part is taken. Each stream owns a [`Run`], driven on the task that polls the stream, and +//! runs one part on it at a time: the part's chunks run side by side, so one chunk's reads overlap +//! another's compute, batches are returned as they are produced, and reads are awaited with +//! [`Run::poll_completion`]. Nothing is spawned, so a host that polls a stream with `block_on` +//! runs the scan's compute on its own thread. //! -//! An ordered scan returns its rows in order through the first clone to be polled, running one -//! child after another on [`ScanDriver`], which keeps a scan's chunks in order. Later clones -//! return nothing. A host that reads an ordered scan in parallel -//! [splits](crate::DataSourceScan::split) it first. +//! An ordered scan returns its rows in order through its first stream, running one child after +//! another on [`ScanDriver`], which keeps a scan's chunks in order. The scan is exhausted once +//! that stream exists, and later streams return nothing. A host that reads an ordered scan in +//! parallel [splits](crate::DataSourceScan::split) it first. //! -//! A limit is one [`RowLimit`] for the whole stream: clones stop taking parts once it is spent, -//! and each clone's output is trimmed to it. +//! A limit is one [`RowLimit`] for the whole scan: streams stop taking parts once it is spent, +//! which also exhausts the scan, and each stream's output is trimmed to it. use std::collections::VecDeque; use std::future; @@ -60,7 +61,8 @@ use crate::planning::planner::WorkScope; use crate::prepare::PreparedScan; use crate::prepare::part_root; use crate::stream::Claims; -use crate::stream::ScanStream; +use crate::stream::ExhaustedFlag; +use crate::stream::ScanExec; /// The parts of an unordered scan, cut when the scan is made. pub(super) struct Planned { @@ -82,17 +84,21 @@ pub(super) async fn plan(state: &ScanState, units: &[Unit]) -> VortexResult, units: Vec, planned: Option, -) -> VortexResult { +) -> VortexResult { let dtype = state.dtype.clone(); let limit = state.limit.map(RowLimit::new); + let exhausted = ExhaustedFlag::new(); if state.ordered { let arrays = Arc::new(Mutex::new(Some(in_order(state, units)))); - return Ok(ScanStream::new(dtype, move || { + let flag = exhausted.clone(); + return Ok(ScanExec::new(dtype, exhausted, move || { + // The first stream returns every row, so later ones would find nothing. + flag.set(); let arrays = arrays .lock() .take() @@ -102,13 +108,17 @@ pub(super) fn open( } let planned = planned.vortex_expect("an unordered scan cuts its parts when it is made"); + if planned.work.is_empty() { + exhausted.set(); + } let queue = Arc::new(Queue { total: planned.work.len(), work: Mutex::new(planned.work.into()), taken: AtomicUsize::new(0), + exhausted: exhausted.clone(), }); - let claims = Arc::clone(&queue); - Ok(ScanStream::new(dtype, move || { + let progress = Arc::clone(&queue); + Ok(ScanExec::new(dtype, exhausted, move || { let worker = Worker { queue: Arc::clone(&queue), limit: limit.clone(), @@ -126,10 +136,10 @@ pub(super) fn open( .boxed(); limited(arrays, limit.clone()) }) - .with_claims(move || claims.claims())) + .with_progress(move || progress.claims())) } -/// One child's prepared scan, shared by the parts of it that clones run. +/// One child's prepared scan, shared by the parts of it that streams run. struct PreparedChild { rows: Range, io: Arc, @@ -206,25 +216,33 @@ enum Work { Batch(ArrayRef), } -/// The queue of an unordered scan, which every clone of its stream takes from. +/// The queue of an unordered scan, which every stream of it takes from. struct Queue { - /// The work no clone has taken yet, in unit and row order. + /// The work no stream has taken yet, in unit and row order. work: Mutex>, /// The work the queue started with. total: usize, - /// The work clones have taken. + /// The work streams have taken. taken: AtomicUsize, + /// Set once the last work is taken, or the scan's limit is spent. + exhausted: ExhaustedFlag, } impl Queue { - /// Takes the next work, or `None` once every one has been taken. + /// Takes the next work, or `None` once every one has been taken, and marks the scan exhausted + /// when it takes the last. fn take(&self) -> Option { - let work = self.work.lock().pop_front()?; + let mut work = self.work.lock(); + let next = work.pop_front()?; + if work.is_empty() { + self.exhausted.set(); + } + drop(work); self.taken.fetch_add(1, Ordering::Relaxed); - Some(work) + Some(next) } - /// How much of the queue's work clones have taken, out of how much in all. + /// How much of the queue's work streams have taken, out of how much in all. fn claims(&self) -> Claims { Claims { claimed: self.taken.load(Ordering::Relaxed).min(self.total), @@ -233,8 +251,8 @@ impl Queue { } } -/// One clone's worker: a run of its own, fed one part at a time from the scan's queue, and driven -/// on the task that polls the clone. +/// One stream's worker: a run of its own, fed one part at a time from the scan's queue, and driven +/// on the task that polls the stream. struct Worker { queue: Arc, limit: Option, @@ -249,6 +267,7 @@ impl Worker { loop { if self.run.live_roots() == 0 { if self.limit.as_ref().is_some_and(RowLimit::is_exhausted) { + self.queue.exhausted.set(); return Ok(None); } match self.queue.take() { diff --git a/vortex-scan/src/source/tests.rs b/vortex-scan/src/source/tests.rs index 3f5793abdaa..3319640e543 100644 --- a/vortex-scan/src/source/tests.rs +++ b/vortex-scan/src/source/tests.rs @@ -178,23 +178,25 @@ async fn selecting_the_unit_returns_its_partition( Ok(()) } -/// Clones of an opened scan share its parts: polled together, they return every row once. +/// The streams of an opened scan share its parts: polled together, they return every row once, +/// and the scan is exhausted once they have taken every part. #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn clones_share_the_scan() -> VortexResult<()> { - let stream = source_of(100_000) +async fn streams_share_the_scan() -> VortexResult<()> { + let exec = source_of(100_000) .scan(ScanRequest::default()) .await? .open()?; - let clones = [stream.clone(), stream.clone(), stream.clone()]; + assert!(!exec.is_exhausted()); + let streams = [exec.stream(), exec.stream(), exec.stream()]; let batches = try_join_all( - clones + streams .into_iter() - .map(|clone| clone.try_collect::>()), + .map(|stream| stream.try_collect::>()), ) .await?; + assert!(exec.is_exhausted()); assert!( - stream - .claims() + exec.progress() .is_some_and(|claims| claims.total > 0 && claims.claimed == claims.total) ); let mut ctx = VortexSession::empty().create_execution_ctx(); From 3e0c43178f7aa99dd6c79cda34f9c119f0e2dc58 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Mon, 23 Nov 2026 22:17:31 -0500 Subject: [PATCH 80/80] Describe opened scans as handing out streams Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-scan/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vortex-scan/src/lib.rs b/vortex-scan/src/lib.rs index 2180ad171c5..ffe9af7b216 100644 --- a/vortex-scan/src/lib.rs +++ b/vortex-scan/src/lib.rs @@ -229,7 +229,7 @@ pub type DataSourceScanRef = Box; /// A source does the reads it needs to know a scan's units of work, such as pruning against zone /// maps before cutting the scan into pieces, in the async [`DataSource::scan`], which the host /// awaits. [`split`](Self::split) and [`open`](Self::open) are synchronous and read nothing, so -/// no clone of an opened stream waits on another for its first work. +/// no stream of an opened scan waits on another for its first work. /// /// A scan never starts threads. Its work may run as tasks on the session's runtime, which the /// host owns.