From e468b71e2cb5bbc44725d4801ed5afd1572c7fb8 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Thu, 19 Nov 2026 15:54:11 -0500 Subject: [PATCH 01/15] 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 02/15] 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 03/15] 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 04/15] 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 05/15] 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 06/15] 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 2d3e3e7f46e4e7869ad01e49785a3b5b968d56a9 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Thu, 19 Nov 2026 19:07:56 -0500 Subject: [PATCH 07/15] 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 4272dca092545857bf60a0857155a134d78f7050 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Thu, 19 Nov 2026 20:17:12 -0500 Subject: [PATCH 08/15] 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 b40dc55cc37cef7d0292a7126bbce9a409a93cd6 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 14:02:41 -0500 Subject: [PATCH 09/15] 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 4f3b62b6df5c6ba10ddb657db972789a9f79a509 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 14:19:51 -0500 Subject: [PATCH 10/15] 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 1569d399e11833d012d2cbf362f3c5750916b19a Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 14:39:30 -0500 Subject: [PATCH 11/15] 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 7f804216e9fc815b9d26544c063c98f47c351144 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 14:45:58 -0500 Subject: [PATCH 12/15] 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 9d11499b18c9ec04f75dcd53290a94af5072a459 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 16:27:47 -0500 Subject: [PATCH 13/15] 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 c102c2c5ab43e9cff1a550a7d7146ed6db71204b Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 16:30:10 -0500 Subject: [PATCH 14/15] 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 15/15] 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(