From d86256942c5fcbb0d5b51988fa7245d2942e05e3 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Thu, 19 Nov 2026 15:54:11 -0500 Subject: [PATCH 01/14] 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 ec103cb6506..e2710b899ec 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`]. @@ -32,17 +33,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 85bec55e2dd38eb2bd41f476aa1e9a3f36d37b34 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Thu, 19 Nov 2026 12:35:07 -0500 Subject: [PATCH 02/14] Scan Vortex files on the V2 scan through the Scan API Engines that consume the Scan API still scanned Vortex files with the V1 layout reader. PlanDataSource exposes any ScanInput as a DataSource whose single partition runs on the planner-driven ScanDriver, and VortexFile::data_source now uses it, falling back to the layout reader for files with list layouts, which the V2 executor cannot read yet. As the layout reader did, a planned file scan whose filter the footer statistics prove false reads nothing. Signed-off-by: Nicholas Gates Co-Authored-By: Claude Opus 5.5 --- vortex-file/src/file.rs | 83 ++++++++- vortex-file/src/source.rs | 87 ++++++++- vortex-file/src/tests.rs | 145 +++++++++++++++ vortex-file/src/v2/scan/tests.rs | 54 ++++++ vortex-scan/src/execution/driver.rs | 13 ++ vortex-scan/src/source.rs | 277 +++++++++++++++++++++++++++- vortex-scan/src/source/tests.rs | 190 +++++++++++++++++++ 7 files changed, 833 insertions(+), 16 deletions(-) create mode 100644 vortex-scan/src/source/tests.rs diff --git a/vortex-file/src/file.rs b/vortex-file/src/file.rs index f610495f90a..9955892760a 100644 --- a/vortex-file/src/file.rs +++ b/vortex-file/src/file.rs @@ -18,6 +18,7 @@ use vortex_array::expr::Expression; use vortex_buffer::ByteBuffer; use vortex_error::VortexResult; use vortex_layout::LayoutReader; +use vortex_layout::layouts::list::List; use vortex_layout::scan::layout::LayoutReaderDataSource; use vortex_layout::scan::metrics::ScanUsage; use vortex_layout::scan::scan_builder::ScanBuilder; @@ -28,6 +29,7 @@ use vortex_layout::segments::UsageSegmentSource; use vortex_scan::DataSourceRef; use vortex_scan::prepare::ScanCache; use vortex_scan::prepare::SegmentLocation; +use vortex_scan::source::PlanDataSource; use vortex_session::VortexSession; use vortex_utils::aliases::hash_map::HashMap; @@ -68,6 +70,29 @@ struct FileScanCache { plans: ScanCache, } +/// Whether a layout tree of `dtype` may contain a list layout. +/// +/// A list layout only ever holds a [`DType::List`], and the writer only decomposes the lists it +/// reaches through struct fields and list elements. Maps and variants are conservatively assumed +/// to contain one too, since their storage may be laid out as lists. +fn may_contain_list_layout(dtype: &DType) -> bool { + match dtype { + DType::List(..) | DType::Map(..) | DType::Variant(_) => true, + DType::Null + | DType::Bool(_) + | DType::Primitive(..) + | DType::Decimal(..) + | DType::Utf8(_) + | DType::Binary(_) => false, + DType::FixedSizeList(element, ..) => may_contain_list_layout(element), + DType::Struct(fields, _) => fields.fields().any(|field| may_contain_list_layout(&field)), + DType::Union(variants, _) => variants + .variants() + .any(|variant| may_contain_list_layout(&variant)), + DType::Extension(ext) => may_contain_list_layout(ext.storage_dtype()), + } +} + fn layout_reader( segment_source: Arc, footer: &Footer, @@ -114,9 +139,10 @@ impl VortexFile { /// Enable layout reader and V2 scan caching. /// - /// Repeated calls to [`layout_reader`](Self::layout_reader), [`scan`](Self::scan), and - /// [`data_source`](Self::data_source) will share the same reader tree. Repeated V2 scans of - /// [`scan_file`](Self::scan_file) will share its segment locations and a [`ScanCache`]. + /// Repeated calls to [`layout_reader`](Self::layout_reader) and [`scan`](Self::scan), and to + /// [`data_source`](Self::data_source) for a file it scans with the layout reader, will share the + /// same reader tree. Repeated V2 scans of [`scan_file`](Self::scan_file), and so of the plan + /// data sources, will share its segment locations and a [`ScanCache`]. pub fn with_caching(self) -> Self { let scan_cache = FileScanCache { locations: self.footer.segment_locations(), @@ -245,18 +271,61 @@ impl VortexFile { /// Create a [`DataSource`](vortex_scan::DataSource) from this file for scanning. /// - /// Wraps the file's layout reader with [`FileStatsLayoutReader`] (when file-level - /// statistics are available) and [`LayoutReaderDataSource`]. Stored footer aggregates are - /// available through the source statistics methods without reading payloads. + /// Scans run on the planner-driven executor, as with + /// [`plan_data_source`](Self::plan_data_source), unless the file has a layout that + /// executor cannot read yet. Such files are scanned by a [`LayoutReaderDataSource`] over the + /// file's [layout reader](Self::layout_reader) instead. Either way, a scan whose filter the + /// file-level statistics prove false reads nothing, and stored footer aggregates are available + /// through the source statistics methods without reading payloads. pub fn data_source(&self) -> VortexResult { - let reader = self.layout_reader()?; + if self.planned_scan_supported()? { + return Ok(self.plan_data_source()); + } + let reader = self.layout_reader()?; Ok(Arc::new(FileDataSource::new( LayoutReaderDataSource::new(reader, self.session.clone()), self.file_stats().cloned(), ))) } + /// Whether the planner-driven executor can scan this file, which + /// [`data_source`](Self::data_source) uses to choose its executor. + /// + /// The planner-driven executor cannot read list layouts yet (tracked with making it the + /// default in #11502), so files that contain one are scanned by the layout reader instead. The + /// layout tree is only walked when the file's dtype could hold a list layout. + pub(crate) fn planned_scan_supported(&self) -> VortexResult { + if !may_contain_list_layout(self.dtype()) { + return Ok(true); + } + for layout in self.footer.layout().depth_first_traversal() { + if layout?.is::() { + return Ok(false); + } + } + Ok(true) + } + + /// Create a [`DataSource`](vortex_scan::DataSource) from this file whose scans run on the + /// planner-driven executor. + /// + /// A scan has one partition covering the requested rows, which runs it with + /// [`ScanDriver`](crate::v2::ScanDriver) from + /// [`Partition::execute`](vortex_scan::Partition::execute). Every scan of the source shares + /// one [`ScanCache`]: the file's, with [caching](Self::with_caching), or else one of its own. + /// A scan whose filter the file-level statistics prove false has no partitions. Stored footer + /// aggregates are available through the source statistics methods. Opening the source reads + /// nothing and builds no layout reader. + pub fn plan_data_source(&self) -> DataSourceRef { + let source = PlanDataSource::new(self.session.clone(), self.scan_file().into()) + .with_row_count(self.row_count()); + Arc::new( + FileDataSource::new(source, self.file_stats().cloned()) + .with_file_pruning(self.row_count(), self.session.clone()), + ) + } + /// Initiate a scan of the file, returning a builder for projection, filtering, selection, and /// execution options. pub fn scan(&self) -> VortexResult> { diff --git a/vortex-file/src/source.rs b/vortex-file/src/source.rs index 1088a61de88..84d5c121718 100644 --- a/vortex-file/src/source.rs +++ b/vortex-file/src/source.rs @@ -2,35 +2,79 @@ // SPDX-FileCopyrightText: Copyright the Vortex contributors use async_trait::async_trait; +use futures::StreamExt; +use futures::stream; use vortex_array::aggregate_fn::AggregateFnRef; use vortex_array::dtype::DType; use vortex_array::dtype::FieldPath; +use vortex_array::expr::Expression; use vortex_array::expr::stats::Precision; use vortex_array::scalar::Scalar; use vortex_array::stats::StatsSet; use vortex_error::VortexResult; -use vortex_layout::scan::layout::LayoutReaderDataSource; use vortex_scan::DataSource; +use vortex_scan::DataSourceScan; use vortex_scan::DataSourceScanRef; use vortex_scan::PartitionRef; +use vortex_scan::PartitionStream; use vortex_scan::ScanRequest; use vortex_session::VortexSession; use crate::FileStatistics; +use crate::pruning::is_falsified_by_file_stats; -pub(crate) struct FileDataSource { - source: LayoutReaderDataSource, +/// A file's scans with the statistics of its footer. +pub(crate) struct FileDataSource { + source: S, statistics: Option, + /// Set when the inner source does not prune with the file's statistics itself. + pruning: Option, } -impl FileDataSource { - pub(crate) fn new(source: LayoutReaderDataSource, statistics: Option) -> Self { - Self { source, statistics } +/// What [`FileDataSource`] needs to prove a scan's filter false over the whole file. +struct FilePruning { + row_count: u64, + session: VortexSession, +} + +impl FileDataSource { + pub(crate) fn new(source: S, statistics: Option) -> Self { + Self { + source, + statistics, + pruning: None, + } + } + + /// Skip scans whose filter the file's statistics prove false over all `row_count` rows of + /// the file, before the inner source reads anything. + pub(crate) fn with_file_pruning(mut self, row_count: u64, session: VortexSession) -> Self { + self.pruning = Some(FilePruning { row_count, session }); + self + } + + /// Whether the file's statistics prove `filter` false for every row of the file, and so for + /// every row range of it. + /// + /// A filter that does not bind is not pruned: the inner scan reports the error. + fn is_pruned(&self, filter: Option<&Expression>) -> VortexResult { + let (Some(pruning), Some(statistics), Some(filter)) = + (&self.pruning, &self.statistics, filter) + else { + return Ok(false); + }; + let Ok(filter) = filter + .bind(self.source.dtype()) + .and_then(|filter| filter.optimize_recursive()) + else { + return Ok(false); + }; + is_falsified_by_file_stats(&filter, pruning.row_count, statistics, &pruning.session) } } #[async_trait] -impl DataSource for FileDataSource { +impl DataSource for FileDataSource { fn dtype(&self) -> &DType { self.source.dtype() } @@ -52,7 +96,15 @@ impl DataSource for FileDataSource { } async fn scan(&self, request: ScanRequest) -> VortexResult { - self.source.scan(request).await + let filter = request.filter.clone(); + let scan = self.source.scan(request).await?; + Ok(if self.is_pruned(filter.as_ref())? { + Box::new(PrunedScan { + dtype: scan.dtype().clone(), + }) + } else { + scan + }) } async fn field_statistics(&self, field_path: &FieldPath) -> VortexResult { @@ -84,3 +136,22 @@ impl DataSource for FileDataSource { .map_or(Precision::Absent, Precision::Exact)) } } + +/// A scan of a file whose statistics rule out every row: it has no partitions. +struct PrunedScan { + dtype: DType, +} + +impl DataSourceScan for PrunedScan { + fn dtype(&self) -> &DType { + &self.dtype + } + + fn partition_count(&self) -> Precision { + Precision::exact(0usize) + } + + fn partitions(self: Box) -> PartitionStream { + stream::empty().boxed() + } +} diff --git a/vortex-file/src/tests.rs b/vortex-file/src/tests.rs index 111abcf6745..c266fe479cd 100644 --- a/vortex-file/src/tests.rs +++ b/vortex-file/src/tests.rs @@ -113,6 +113,7 @@ use vortex_layout::layouts::buffered::BufferedStrategy; use vortex_layout::layouts::chunked::writer::ChunkedLayoutStrategy; use vortex_layout::layouts::file_stats::AggregateStats; use vortex_layout::layouts::flat::writer::FlatLayoutStrategy; +use vortex_layout::layouts::list::List; use vortex_layout::layouts::struct_::StructStrategy; use vortex_layout::layouts::table::TableStrategy; use vortex_layout::layouts::zoned::LegacyStats; @@ -121,6 +122,9 @@ use vortex_layout::scan::scan_builder::ScanBuilder; use vortex_layout::scan::split_by::DEFAULT_MAX_SPLIT_ROWS; use vortex_layout::scan::split_by::SplitBy; use vortex_layout::session::LayoutSession; +use vortex_scan::DataSourceRef; +use vortex_scan::PartitionRef; +use vortex_scan::ScanRequest; use vortex_scan::strict_sorted_buffer::StrictSortedBuffer; use vortex_session::VortexSession; use vortex_session::registry::Id; @@ -2595,6 +2599,147 @@ async fn file_data_source_returns_mergeable_partials() -> VortexResult<()> { Ok(()) } +/// Scans `source` and concatenates the rows of all its partitions, returning how many partitions +/// the scan had. +async fn scan_source( + source: &DataSourceRef, + request: ScanRequest, +) -> VortexResult<(usize, ArrayRef)> { + let scan = source.scan(request).await?; + let dtype = scan.dtype().clone(); + let partitions: Vec = scan.partitions().try_collect().await?; + let partition_count = partitions.len(); + let mut chunks = Vec::new(); + for partition in partitions { + chunks.push(partition.execute()?.read_all().await?); + } + Ok(( + partition_count, + ChunkedArray::try_new(chunks, dtype)?.into_array(), + )) +} + +/// A file whose statistics rule out a filter is scanned with no partitions, which the layout +/// reader's source never returns, so this also shows the file is scanned on the planner-driven +/// executor. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[cfg_attr(miri, ignore)] +async fn data_source_prunes_files_with_statistics() -> VortexResult<()> { + let array = StructArray::from_fields(&[("numbers", buffer![1u32, 2, 3, 4, 5].into_array())])? + .into_array(); + let mut buf = ByteBufferMut::empty(); + SESSION + .write_options() + .with_file_statistics(pruning_aggregate_fns()) + .write(&mut buf, array.to_array_stream()) + .await?; + let file = SESSION.open_options().open_buffer(buf)?; + assert!(file.planned_scan_supported()?); + let source = file.data_source()?; + let request = |filter: Expression| ScanRequest { + projection: get_item("numbers", root()), + filter: Some(filter), + ordered: true, + ..Default::default() + }; + + let pruned = source + .scan(request(gt(get_item("numbers", root()), lit(10u32)))) + .await?; + assert_eq!( + pruned.dtype(), + &DType::Primitive(PType::U32, Nullability::NonNullable) + ); + assert_eq!(pruned.partition_count(), Precision::exact(0usize)); + assert_eq!(pruned.partitions().try_collect::>().await?.len(), 0); + + let (partitions, actual) = + scan_source(&source, request(gt(get_item("numbers", root()), lit(3u32)))).await?; + assert_eq!(partitions, 1); + assert_arrays_eq!( + actual, + buffer![4u32, 5].into_array(), + &mut SESSION.create_execution_ctx() + ); + + // A filter that does not bind is not pruned away: the scan reports the error. + assert!( + source + .scan(request(gt(get_item("missing", root()), lit(10u32)))) + .await + .is_err() + ); + Ok(()) +} + +/// A file with a list layout, which the planner-driven executor cannot read yet, is scanned with +/// the layout reader instead, list column included. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[cfg_attr(miri, ignore)] +async fn data_source_scans_list_layouts_with_the_layout_reader() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let lists = ListArray::try_new( + buffer![1i32, 2, 3, 4, 5, 6].into_array(), + buffer![0u32, 2, 5, 5, 6].into_array(), + Validity::NonNullable, + &mut ctx, + )? + .into_array(); + let array = StructArray::from_fields(&[ + ("numbers", buffer![1i32, 2, 3, 4].into_array()), + ("lists", lists), + ])? + .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 mut has_list_layout = false; + for layout in file.footer().layout().depth_first_traversal() { + has_list_layout |= layout?.is::(); + } + assert!(has_list_layout); + assert!(!file.planned_scan_supported()?); + + let planned = scan_source(&file.plan_data_source(), ScanRequest::default()).await; + let error = planned.expect_err("the planner-driven executor rejects list layouts"); + assert!(error.to_string().contains("vortex.plan.list_pack")); + + let (_, actual) = scan_source(&file.data_source()?, ScanRequest::default()).await?; + assert_arrays_eq!(actual, array, &mut ctx); + Ok(()) +} + +/// A file with list columns but no list layout is scanned on the planner-driven executor. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[cfg_attr(miri, ignore)] +async fn data_source_scans_flat_lists_with_the_planner() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let lists = ListArray::try_new( + buffer![1i32, 2, 3, 4, 5, 6].into_array(), + buffer![0u32, 2, 5, 5, 6].into_array(), + Validity::NonNullable, + &mut ctx, + )? + .into_array(); + let array = StructArray::from_fields(&[("lists", lists)])?.into_array(); + let mut buf = ByteBufferMut::empty(); + SESSION + .write_options() + .with_strategy(Arc::new(FlatLayoutStrategy::default())) + .write(&mut buf, array.to_array_stream()) + .await?; + let file = SESSION.open_options().open_buffer(buf)?; + assert!(file.planned_scan_supported()?); + + let (partitions, actual) = scan_source(&file.data_source()?, ScanRequest::default()).await?; + assert_eq!(partitions, 1); + assert_arrays_eq!(actual, array, &mut ctx); + Ok(()) +} + #[tokio::test] async fn test_writer_with_statistics() -> VortexResult<()> { let array = StructArray::from_fields(&[("numbers", buffer![1u32, 2, 3, 4, 5].into_array())])? diff --git a/vortex-file/src/v2/scan/tests.rs b/vortex-file/src/v2/scan/tests.rs index 6b3b030b971..7235c566165 100644 --- a/vortex-file/src/v2/scan/tests.rs +++ b/vortex-file/src/v2/scan/tests.rs @@ -14,16 +14,25 @@ use vortex_array::VortexSessionExecute; use vortex_array::arrays::ChunkedArray; use vortex_array::arrays::StructArray; use vortex_array::arrays::VarBinArray; +use vortex_array::assert_arrays_eq; +use vortex_array::expr::get_item; +use vortex_array::expr::gt; +use vortex_array::expr::lit; +use vortex_array::expr::root; +use vortex_array::expr::stats::Precision; use vortex_arrow::ArrowScanExt; use vortex_arrow::ArrowSessionExt; use vortex_arrow::ExecuteArrowExt; use vortex_buffer::ByteBufferMut; use vortex_buffer::buffer; +use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_io::runtime::tokio::TokioRuntime; use vortex_io::session::RuntimeSession; use vortex_layout::scan::v2::ScanBuilder; use vortex_layout::session::LayoutSession; +use vortex_scan::PartitionRef; +use vortex_scan::ScanRequest; use vortex_session::VortexSession; use super::ScanDriver; @@ -93,3 +102,48 @@ async fn record_batches_match_arrays() -> VortexResult<()> { assert_eq!(given, expected); Ok(()) } + +/// A file's plan data source scans the rows the request asks for, as a V2 scan built from +/// the file directly does. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn plan_data_source_scans_like_the_file() -> VortexResult<()> { + let file = file().await?; + let source = file.plan_data_source(); + assert_eq!(source.row_count(), Precision::exact(file.row_count())); + + let request = || ScanRequest { + projection: get_item("numbers", root()), + filter: Some(gt(get_item("numbers", root()), lit(4))), + row_range: Some(4..28), + ordered: true, + ..Default::default() + }; + let dtype = file.dtype().clone(); + let expected = ScanBuilder::new(SESSION.clone(), file.scan_file()) + .with_projection(request().projection.bind(&dtype)?) + .with_some_filter(request().filter.map(|f| f.bind(&dtype)).transpose()?) + .with_row_range(4..28); + let scan_dtype = expected.dtype().clone(); + let collect = |arrays: Vec| ChunkedArray::try_new(arrays, scan_dtype.clone()); + let expected = collect(driver().run(expected).try_collect().await?)?; + + let partitions: Vec = source + .scan(request()) + .await? + .partitions() + .try_collect() + .await?; + assert_eq!(partitions.len(), 1); + let executed = collect( + partitions + .into_iter() + .next() + .vortex_expect("one partition") + .execute()? + .try_collect() + .await?, + )?; + assert_arrays_eq!(executed, expected, &mut SESSION.create_execution_ctx()); + + Ok(()) +} diff --git a/vortex-scan/src/execution/driver.rs b/vortex-scan/src/execution/driver.rs index 7a904f80343..fd19cc9f485 100644 --- a/vortex-scan/src/execution/driver.rs +++ b/vortex-scan/src/execution/driver.rs @@ -12,6 +12,7 @@ //! produced the batch, beside the scan's other chunks. use std::future; +use std::num::NonZeroUsize; use std::sync::Arc; use std::task::Poll; @@ -42,6 +43,7 @@ use crate::prepare::ScanBuilder; pub struct ScanDriver { handle: Handle, concurrency: usize, + max_in_flight: Option, ordered: bool, } @@ -54,10 +56,18 @@ impl ScanDriver { Self { handle, concurrency, + max_in_flight: None, ordered, } } + /// Caps the chunks the scan decodes at once, in all, below the per-worker limit. `None` + /// keeps the per-worker limit only. + pub fn with_max_in_flight(mut self, max_in_flight: Option) -> Self { + self.max_in_flight = max_in_flight; + self + } + /// Prepares `builder` where compute runs, composes its planners, and streams their batches. /// Preparation errors are the stream's first item. pub fn run( @@ -101,6 +111,9 @@ impl ScanDriver { let scan = Arc::new(scan); let map_fn: MapFn = Arc::new(map_fn); let in_flight = self.concurrency * get_available_parallelism().unwrap_or(1); + let in_flight = self + .max_in_flight + .map_or(in_flight, |max| in_flight.min(max.get())); let inline = in_flight <= 1; let scope = WorkScope { file_ordinal: 0, diff --git a/vortex-scan/src/source.rs b/vortex-scan/src/source.rs index 08a3f38c296..f9ec2c97069 100644 --- a/vortex-scan/src/source.rs +++ b/vortex-scan/src/source.rs @@ -1,18 +1,47 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors -//! Source inputs and byte access for scans. +//! Source inputs and byte access for scans, and the [`DataSource`] that scans them. +use std::any::Any; +use std::num::NonZeroUsize; +use std::ops::Range; use std::sync::Arc; +use async_trait::async_trait; +use futures::StreamExt; +use futures::future; +use futures::stream; +use futures::stream::BoxStream; +use vortex_array::ArrayRef; use vortex_array::dtype::DType; +use vortex_array::dtype::FieldPath; +use vortex_array::expr::BoundExpression; +use vortex_array::expr::stats::Precision; +use vortex_array::stats::StatsSet; +use vortex_array::stream::ArrayStreamAdapter; +use vortex_array::stream::ArrayStreamExt; +use vortex_array::stream::SendableArrayStream; +use vortex_error::VortexResult; pub use vortex_io::segments::SegmentFuture; pub use vortex_io::segments::SegmentId; pub use vortex_io::segments::SegmentSource; +use vortex_io::session::RuntimeSessionExt; +use vortex_session::VortexSession; +use crate::DataSource; +use crate::DataSourceScan; +use crate::DataSourceScanRef; +use crate::Partition; +use crate::PartitionRef; +use crate::PartitionStream; +use crate::ScanRequest; use crate::execution::SegmentLocation; use crate::execution::cache::ScanCache; +use crate::execution::driver::ScanDriver; use crate::plan::LazyPlanRef; +use crate::prepare::ScanBuilder; +use crate::selection::Selection; /// The plan and byte source used to prepare a scan. /// @@ -32,3 +61,249 @@ pub struct ScanInput { /// State shared by repeated scans of this input. pub cache: Option, } + +/// A [`DataSource`] over one [`ScanInput`], scanned by the planner-driven executor. +/// +/// This is the standard way to expose a source that can name its segments, whatever its format: +/// a Vortex file, a Parquet file whose column chunks are placed segments, or any store that can +/// lower its data to plans. Every scan of the source shares the input's [`ScanCache`], so scans +/// that overlap in time plan the input and register its reader once. +/// +/// A scan of the source has one partition covering the request's row range, clamped to the +/// input's rows when the row count is known. The partition has [`index`](Partition::index) 0, so a +/// request's `partition_range` and `partition_selection` either select it or leave the scan with +/// no partitions. +/// +/// The partition's [`execute`](Partition::execute) runs the planner-driven scan of its rows with a +/// [`ScanDriver`] on the session's runtime and applies the request's limit. +#[derive(Clone)] +pub struct PlanDataSource { + session: VortexSession, + input: ScanInput, + row_count: Precision, + byte_size: Precision, +} + +impl PlanDataSource { + /// A source scanning `input` with `session`. Without a cache, the input gets a fresh one that + /// all of the source's scans share. + pub fn new(session: VortexSession, mut input: ScanInput) -> Self { + input.cache.get_or_insert_default(); + Self { + session, + input, + row_count: Precision::Absent, + byte_size: Precision::Absent, + } + } + + /// Sets the exact row count of the input, which scans and partitions report. + pub fn with_row_count(mut self, row_count: u64) -> Self { + self.row_count = Precision::exact(row_count); + self + } + + /// Sets an estimate of the input's byte size. + pub fn with_byte_size(mut self, byte_size: Precision) -> Self { + self.byte_size = byte_size; + self + } + + /// The input this source scans. + pub fn input(&self) -> &ScanInput { + &self.input + } + + /// The session scans of this source run with. + pub fn session(&self) -> &VortexSession { + &self.session + } +} + +#[async_trait] +impl DataSource for PlanDataSource { + fn dtype(&self) -> &DType { + &self.input.dtype + } + + fn row_count(&self) -> Precision { + self.row_count + } + + fn byte_size(&self) -> Precision { + self.byte_size + } + + async fn scan(&self, request: ScanRequest) -> VortexResult { + let projection = request + .projection + .bind(&self.input.dtype)? + .optimize_recursive()?; + let filter = request + .filter + .map(|filter| filter.bind(&self.input.dtype)?.optimize_recursive()) + .transpose()?; + let dtype = projection.dtype().clone(); + let row_range = match (request.row_range, self.row_count.as_exact()) { + (Some(rows), Some(count)) => Some(rows.start.min(count)..rows.end.min(count)), + (rows, _) => rows, + }; + // The source is the single unit 0, so a request that does not select it scans nothing. + let selected = request + .partition_range + .as_ref() + .is_none_or(|range| range.contains(&0)) + && request.partition_selection.row_count_in_range(&(0..1)) == 1; + if !selected || request.limit == Some(0) || row_range.as_ref().is_some_and(Range::is_empty) + { + return Ok(Box::new(PlanScan { + dtype, + partitions: Vec::new(), + })); + } + let partition = PlanPartition { + session: self.session.clone(), + input: self.input.clone(), + row_count: self.row_count, + projection, + filter, + row_range, + selection: request.selection, + ordered: request.ordered, + limit: request.limit, + split_concurrency: request.split_concurrency, + }; + Ok(Box::new(PlanScan { + dtype, + partitions: vec![partition], + })) + } + + async fn field_statistics(&self, _field_path: &FieldPath) -> VortexResult { + Ok(StatsSet::default()) + } +} + +struct PlanScan { + dtype: DType, + partitions: Vec, +} + +impl DataSourceScan for PlanScan { + fn dtype(&self) -> &DType { + &self.dtype + } + + fn partition_count(&self) -> Precision { + Precision::exact(self.partitions.len()) + } + + fn partitions(self: Box) -> PartitionStream { + stream::iter( + self.partitions + .into_iter() + .map(|partition| Ok(Box::new(partition) as PartitionRef)), + ) + .boxed() + } +} + +/// The rows of a [`PlanDataSource`] that one partition of a scan reads. +struct PlanPartition { + session: VortexSession, + input: ScanInput, + row_count: Precision, + projection: BoundExpression, + filter: Option, + row_range: Option>, + selection: Selection, + ordered: bool, + limit: Option, + split_concurrency: Option, +} + +impl PlanPartition { + fn builder(self) -> ScanBuilder { + let mut builder = ScanBuilder::new(self.session, self.input) + .with_projection(self.projection) + .with_some_filter(self.filter) + .with_selection(self.selection); + if let Some(rows) = self.row_range { + builder = builder.with_row_range(rows); + } + builder + } +} + +impl Partition for PlanPartition { + fn as_any(&self) -> &dyn Any { + self + } + + fn index(&self) -> usize { + 0 + } + + fn row_count(&self) -> Precision { + let rows = match (&self.row_range, self.row_count.as_exact()) { + (Some(rows), _) => rows.clone(), + (None, Some(count)) => 0..count, + (None, None) => return Precision::Absent, + }; + let rows = self.selection.row_count_in_range(&rows); + let rows = self.limit.map_or(rows, |limit| rows.min(limit)); + if self.filter.is_some() { + Precision::inexact(rows) + } else { + Precision::exact(rows) + } + } + + fn byte_size(&self) -> Precision { + Precision::Absent + } + + fn execute(self: Box) -> VortexResult { + let dtype = self.projection.dtype().clone(); + let (ordered, limit, max_in_flight) = (self.ordered, self.limit, self.split_concurrency); + let driver = + ScanDriver::new(self.session.handle(), 1, ordered).with_max_in_flight(max_in_flight); + let arrays = driver.run(self.builder()); + let arrays = match limit { + Some(limit) => limit_arrays(arrays, limit), + None => arrays, + }; + Ok(ArrayStreamExt::boxed(ArrayStreamAdapter::new( + dtype, arrays, + ))) + } +} + +/// Ends `arrays` after its first `limit` rows. +fn limit_arrays( + arrays: BoxStream<'static, VortexResult>, + limit: u64, +) -> BoxStream<'static, VortexResult> { + arrays + .scan(limit, |remaining, array| { + if *remaining == 0 { + return future::ready(None); + } + let array = array.and_then(|array| { + let len = array.len() as u64; + if len <= *remaining { + *remaining -= len; + Ok(array) + } else { + let keep = usize::try_from(*remaining).unwrap_or(usize::MAX); + *remaining = 0; + array.slice(0..keep) + } + }); + future::ready(Some(array)) + }) + .boxed() +} + +#[cfg(test)] +mod tests; diff --git a/vortex-scan/src/source/tests.rs b/vortex-scan/src/source/tests.rs new file mode 100644 index 00000000000..ad8c09f6aa9 --- /dev/null +++ b/vortex-scan/src/source/tests.rs @@ -0,0 +1,190 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +use std::ops::Range; +use std::sync::Arc; + +use futures::TryStreamExt; +use roaring::RoaringTreemap; +use rstest::rstest; +use vortex_array::ArrayRef; +use vortex_array::IntoArray; +use vortex_array::VortexSessionExecute; +use vortex_array::arrays::ChunkedArray; +use vortex_array::arrays::PrimitiveArray; +use vortex_array::assert_arrays_eq; +use vortex_array::expr::checked_add; +use vortex_array::expr::gt; +use vortex_array::expr::lit; +use vortex_array::expr::root; +use vortex_array::expr::stats::Precision; +use vortex_buffer::Buffer; +use vortex_error::VortexResult; +use vortex_error::vortex_bail; +use vortex_io::request::SegmentReader; +use vortex_io::session::RuntimeSessionExt; +use vortex_session::VortexSession; + +use super::PlanDataSource; +use super::ScanInput; +use super::SegmentFuture; +use super::SegmentId; +use super::SegmentSource; +use crate::DataSource; +use crate::PartitionRef; +use crate::ScanRequest; +use crate::execution::pipeline::synthetic::RowSource; +use crate::plan::LazyPlanRef; +use crate::selection::Selection; + +struct NoSegments; + +impl SegmentSource for NoSegments { + fn request(&self, _id: SegmentId) -> SegmentFuture { + Box::pin(async { vortex_bail!("an in-memory source must not request bytes") }) + } +} + +fn source() -> PlanDataSource { + source_of(20) +} + +fn source_of(row_count: u64) -> PlanDataSource { + let plan = RowSource::plan(row_count, vec![4, 7, 9], None, false); + let input = ScanInput { + dtype: plan.dtype().clone(), + root: LazyPlanRef::ready(plan), + locations: Arc::new([]), + reader: SegmentReader::Opaque(Arc::new(NoSegments)), + cache: None, + }; + PlanDataSource::new(VortexSession::empty().with_tokio(), input).with_row_count(row_count) +} + +async fn partitions(request: ScanRequest) -> VortexResult> { + partitions_of(&source(), request).await +} + +async fn partitions_of( + source: &PlanDataSource, + request: ScanRequest, +) -> VortexResult> { + source.scan(request).await?.partitions().try_collect().await +} + +async fn collect(partitions: Vec) -> VortexResult { + let dtype = source().dtype().clone(); + let mut arrays = Vec::new(); + for partition in partitions { + let batches: Vec = partition.execute()?.try_collect().await?; + arrays.extend(batches); + } + Ok(ChunkedArray::try_new(arrays, dtype)?.into_array()) +} + +#[rstest] +#[case::unordered(false)] +#[case::ordered(true)] +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn execute_applies_the_request(#[case] ordered: bool) -> VortexResult<()> { + let partitions = partitions(ScanRequest { + projection: checked_add(root(), lit(100_u64)), + filter: Some(gt(root(), lit(5_u64))), + row_range: Some(2..18), + ordered, + ..Default::default() + }) + .await?; + assert_eq!(partitions.len(), 1); + let mut ctx = VortexSession::empty().create_execution_ctx(); + let actual = collect(partitions) + .await? + .execute::(&mut ctx)?; + let mut values = actual.as_slice::().to_vec(); + if !ordered { + values.sort_unstable(); + } + assert_eq!(values, (106_u64..118).collect::>()); + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn execute_applies_the_limit() -> VortexResult<()> { + let partitions = partitions(ScanRequest { + filter: Some(gt(root(), lit(5_u64))), + ordered: true, + limit: Some(5), + ..Default::default() + }) + .await?; + assert_arrays_eq!( + collect(partitions).await?, + Buffer::from_iter(6_u64..11).into_array(), + &mut VortexSession::empty().create_execution_ctx() + ); + Ok(()) +} + +#[tokio::test] +async fn partitions_report_their_rows() -> VortexResult<()> { + let partitions = partitions(ScanRequest { + row_range: Some(4..9), + ..Default::default() + }) + .await?; + assert_eq!(partitions[0].row_count(), Precision::exact(5_u64)); + Ok(()) +} + +#[rstest] +#[case::zero_limit(ScanRequest { limit: Some(0), ..Default::default() })] +#[case::empty_rows(ScanRequest { row_range: Some(30..40), ..Default::default() })] +#[case::other_units(ScanRequest { partition_range: Some(1..4), ..Default::default() })] +#[case::unit_excluded(ScanRequest { + partition_selection: Selection::ExcludeRoaring(RoaringTreemap::from_iter([0_u64])), + ..Default::default() +})] +#[tokio::test] +async fn requests_without_rows_have_no_partitions( + #[case] request: ScanRequest, +) -> VortexResult<()> { + assert!(partitions(request).await?.is_empty()); + Ok(()) +} + +/// The sorted values of every partition's output. +async fn sorted_values(partitions: Vec) -> VortexResult> { + let mut ctx = VortexSession::empty().create_execution_ctx(); + let mut values = collect(partitions) + .await? + .execute::(&mut ctx)? + .as_slice::() + .to_vec(); + values.sort_unstable(); + Ok(values) +} + +/// Selecting the source's unit, by range or by selection, returns its one partition. +#[rstest] +#[case::range(Some(0..1), Selection::All)] +#[case::wide_range(Some(0..5), Selection::All)] +#[case::selection(None, Selection::IncludeRoaring(RoaringTreemap::from_iter([0_u64, 3])))] +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn selecting_the_unit_returns_its_partition( + #[case] partition_range: Option>, + #[case] partition_selection: Selection, +) -> VortexResult<()> { + let partitions = partitions(ScanRequest { + partition_selection, + partition_range, + ..Default::default() + }) + .await?; + assert_eq!(partitions.len(), 1); + assert_eq!(partitions[0].index(), 0); + assert_eq!( + sorted_values(partitions).await?, + (0..20).collect::>() + ); + Ok(()) +} From 05fd3f36db2fd8341d9d58a45dc6449875174d6e Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Thu, 19 Nov 2026 14:56:42 -0500 Subject: [PATCH 03/14] Expose a file's layout-reader Scan API source on its own Engines that keep a V1/V2 switch while they move onto the Scan API, and benchmarks comparing the two executors, need each one as a DataSource. layout_reader_data_source() returns the layout-reader source that data_source() already falls back to, with the same footer statistics, and data_source() now calls it. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-file/src/file.rs | 17 +++++++++++++---- vortex-file/src/tests.rs | 39 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+), 4 deletions(-) diff --git a/vortex-file/src/file.rs b/vortex-file/src/file.rs index 9955892760a..be225e62808 100644 --- a/vortex-file/src/file.rs +++ b/vortex-file/src/file.rs @@ -273,15 +273,24 @@ impl VortexFile { /// /// Scans run on the planner-driven executor, as with /// [`plan_data_source`](Self::plan_data_source), unless the file has a layout that - /// executor cannot read yet. Such files are scanned by a [`LayoutReaderDataSource`] over the - /// file's [layout reader](Self::layout_reader) instead. Either way, a scan whose filter the - /// file-level statistics prove false reads nothing, and stored footer aggregates are available - /// through the source statistics methods without reading payloads. + /// executor cannot read yet. Such files are scanned on the layout reader instead, as with + /// [`layout_reader_data_source`](Self::layout_reader_data_source). Either way, a scan whose + /// filter the file-level statistics prove false reads nothing, and stored footer aggregates + /// are available through the source statistics methods without reading payloads. pub fn data_source(&self) -> VortexResult { if self.planned_scan_supported()? { return Ok(self.plan_data_source()); } + self.layout_reader_data_source() + } + /// Create a [`DataSource`](vortex_scan::DataSource) that scans this file with its + /// [layout reader](Self::layout_reader), whatever its layouts. + /// + /// Use [`data_source`](Self::data_source) unless the layout reader is required, for example + /// to compare it with [`plan_data_source`](Self::plan_data_source). Stored footer aggregates + /// are available through the source statistics methods without reading payloads. + pub fn layout_reader_data_source(&self) -> VortexResult { let reader = self.layout_reader()?; Ok(Arc::new(FileDataSource::new( LayoutReaderDataSource::new(reader, self.session.clone()), diff --git a/vortex-file/src/tests.rs b/vortex-file/src/tests.rs index c266fe479cd..fb35ccf94fa 100644 --- a/vortex-file/src/tests.rs +++ b/vortex-file/src/tests.rs @@ -2619,6 +2619,45 @@ async fn scan_source( )) } +/// Both of a file's executors are reachable through the Scan API and read the same rows. +#[rstest] +#[case::plan(false)] +#[case::layout_reader(true)] +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[cfg_attr(miri, ignore)] +async fn file_sources_scan_with_either_executor(#[case] layout_reader: bool) -> VortexResult<()> { + let array = StructArray::from_fields(&[("numbers", buffer![1u32, 2, 3, 4, 5].into_array())])? + .into_array(); + let mut buf = ByteBufferMut::empty(); + SESSION + .write_options() + .write(&mut buf, array.to_array_stream()) + .await?; + let file = SESSION.open_options().open_buffer(buf)?; + let source = if layout_reader { + file.layout_reader_data_source()? + } else { + file.plan_data_source() + }; + + let (_, actual) = scan_source( + &source, + ScanRequest { + projection: get_item("numbers", root()), + filter: Some(gt(get_item("numbers", root()), lit(3u32))), + ordered: true, + ..Default::default() + }, + ) + .await?; + assert_arrays_eq!( + actual, + buffer![4u32, 5].into_array(), + &mut SESSION.create_execution_ctx() + ); + Ok(()) +} + /// A file whose statistics rule out a filter is scanned with no partitions, which the layout /// reader's source never returns, so this also shows the file is scanned on the planner-driven /// executor. From ac7cd966e19b87564064991f8ab1f0f9c84a2560 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Thu, 19 Nov 2026 15:59:21 -0500 Subject: [PATCH 04/14] Read plan data sources through the base's segment sources Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-scan/src/source/tests.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/vortex-scan/src/source/tests.rs b/vortex-scan/src/source/tests.rs index ad8c09f6aa9..f0a98a3c8d6 100644 --- a/vortex-scan/src/source/tests.rs +++ b/vortex-scan/src/source/tests.rs @@ -21,7 +21,6 @@ use vortex_array::expr::stats::Precision; use vortex_buffer::Buffer; use vortex_error::VortexResult; use vortex_error::vortex_bail; -use vortex_io::request::SegmentReader; use vortex_io::session::RuntimeSessionExt; use vortex_session::VortexSession; @@ -55,7 +54,7 @@ fn source_of(row_count: u64) -> PlanDataSource { dtype: plan.dtype().clone(), root: LazyPlanRef::ready(plan), locations: Arc::new([]), - reader: SegmentReader::Opaque(Arc::new(NoSegments)), + segments: Arc::new(NoSegments), cache: None, }; PlanDataSource::new(VortexSession::empty().with_tokio(), input).with_row_count(row_count) From 044da4d47168e259f1ab991826df4f8299d64112 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Thu, 19 Nov 2026 16:14:02 -0500 Subject: [PATCH 05/14] Give V2 plan sources a native split and open PlanDataSource now covers one or many files, the later ones opened during scans, and implements the Scan API's split and open natively. split cuts the scan's known rows on the 8,192-row block grid into contiguous pieces of about equal rows, from metadata only, keeping unopened files whole. open prepares each open file once and hands its parts (its chunks, or its splits when given) to workers through the V1 pool's pattern: a channel of units, deferred files as queued opens that push their parts back, and up to split_concurrency parts in flight per worker, each driven on a planning run on the worker's own thread. MultiFileDataSource::build_plan builds the multi-file source. RowLimit, group_contiguous and the in-flight default move from vortex-layout into vortex-scan so both pools share them. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- Cargo.lock | 1 + vortex-file/src/file.rs | 31 +- vortex-file/src/lib.rs | 2 + vortex-file/src/multi/mod.rs | 129 ++++- vortex-file/src/plan_tests.rs | 389 +++++++++++++++ vortex-file/src/source.rs | 75 +-- vortex-layout/src/scan/layout.rs | 22 +- vortex-layout/src/scan/limit.rs | 123 +---- vortex-layout/src/scan/pool.rs | 5 +- vortex-scan/Cargo.toml | 1 + vortex-scan/src/execution/driver.rs | 8 +- vortex-scan/src/execution/mod.rs | 1 - vortex-scan/src/pool.rs | 208 +++++++- vortex-scan/src/source.rs | 280 +---------- vortex-scan/src/source/plan.rs | 713 ++++++++++++++++++++++++++++ vortex-scan/src/source/plan_pool.rs | 361 ++++++++++++++ 16 files changed, 1815 insertions(+), 534 deletions(-) create mode 100644 vortex-file/src/plan_tests.rs create mode 100644 vortex-scan/src/source/plan.rs create mode 100644 vortex-scan/src/source/plan_pool.rs diff --git a/Cargo.lock b/Cargo.lock index ab273f5e43d..1ffbead0ccc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -12357,6 +12357,7 @@ dependencies = [ name = "vortex-scan" version = "0.1.0" dependencies = [ + "async-channel", "async-lock", "async-trait", "bit-vec 0.10.2", diff --git a/vortex-file/src/file.rs b/vortex-file/src/file.rs index be225e62808..99381f2711c 100644 --- a/vortex-file/src/file.rs +++ b/vortex-file/src/file.rs @@ -30,6 +30,7 @@ use vortex_scan::DataSourceRef; use vortex_scan::prepare::ScanCache; use vortex_scan::prepare::SegmentLocation; use vortex_scan::source::PlanDataSource; +use vortex_scan::source::PlanFile; use vortex_session::VortexSession; use vortex_utils::aliases::hash_map::HashMap; @@ -75,7 +76,7 @@ struct FileScanCache { /// A list layout only ever holds a [`DType::List`], and the writer only decomposes the lists it /// reaches through struct fields and list elements. Maps and variants are conservatively assumed /// to contain one too, since their storage may be laid out as lists. -fn may_contain_list_layout(dtype: &DType) -> bool { +pub(crate) fn may_contain_list_layout(dtype: &DType) -> bool { match dtype { DType::List(..) | DType::Map(..) | DType::Variant(_) => true, DType::Null @@ -319,20 +320,30 @@ impl VortexFile { /// Create a [`DataSource`](vortex_scan::DataSource) from this file whose scans run on the /// planner-driven executor. /// - /// A scan has one partition covering the requested rows, which runs it with - /// [`ScanDriver`](crate::v2::ScanDriver) from + /// The source is a [`PlanDataSource`] over [`plan_file`](Self::plan_file): hosts read its + /// scans through native `split` and `open`, or through one partition covering the requested + /// rows, which runs it with [`ScanDriver`](crate::v2::ScanDriver) from /// [`Partition::execute`](vortex_scan::Partition::execute). Every scan of the source shares /// one [`ScanCache`]: the file's, with [caching](Self::with_caching), or else one of its own. - /// A scan whose filter the file-level statistics prove false has no partitions. Stored footer + /// A scan whose filter the file-level statistics prove false reads nothing. Stored footer /// aggregates are available through the source statistics methods. Opening the source reads /// nothing and builds no layout reader. pub fn plan_data_source(&self) -> DataSourceRef { - let source = PlanDataSource::new(self.session.clone(), self.scan_file().into()) - .with_row_count(self.row_count()); - Arc::new( - FileDataSource::new(source, self.file_stats().cloned()) - .with_file_pruning(self.row_count(), self.session.clone()), - ) + let source = PlanDataSource::from_file(self.session.clone(), self.plan_file()); + Arc::new(FileDataSource::new(source, self.file_stats().cloned())) + } + + /// This file as a file of a [`PlanDataSource`]: its V2 scan input, row count, and a pruner + /// that skips scans whose filter the file-level statistics prove false. + pub fn plan_file(&self) -> PlanFile { + let file = PlanFile::new(self.scan_file().into()).with_row_count(self.row_count()); + let Some(statistics) = self.file_stats().cloned() else { + return file; + }; + let (row_count, session) = (self.row_count(), self.session.clone()); + file.with_pruner(Arc::new(move |filter| { + is_falsified_by_file_stats(filter, row_count, &statistics, &session) + })) } /// Initiate a scan of the file, returning a builder for projection, filtering, selection, and diff --git a/vortex-file/src/lib.rs b/vortex-file/src/lib.rs index 0321127a3d3..48caddbd245 100644 --- a/vortex-file/src/lib.rs +++ b/vortex-file/src/lib.rs @@ -109,6 +109,8 @@ pub mod flatbuffers; mod footer; pub mod multi; mod open; +#[cfg(test)] +mod plan_tests; mod pruning; /// Segment sources, caches, and sinks used by file readers and writers. pub mod segments; diff --git a/vortex-file/src/multi/mod.rs b/vortex-file/src/multi/mod.rs index 03a80171ec5..f00a7584e12 100644 --- a/vortex-file/src/multi/mod.rs +++ b/vortex-file/src/multi/mod.rs @@ -26,11 +26,20 @@ use vortex_layout::LayoutReaderRef; use vortex_layout::scan::multi::LayoutReaderFactory; use vortex_layout::scan::multi::MultiLayoutDataSource; use vortex_scan::DataSource; +use vortex_scan::DataSourceRef; +use vortex_scan::source::DeferredPlanFile; +use vortex_scan::source::PlanDataSource; +use vortex_scan::source::PlanFile; +use vortex_scan::source::PlanSourceFile; use vortex_session::VortexSession; use crate::OpenOptionsSessionExt; use crate::VortexFile; use crate::VortexOpenOptions; +use crate::file::may_contain_list_layout; + +/// Adjusts the options each file of a [`MultiFileDataSource`] is opened with. +type OpenOptionsFn = Arc VortexOpenOptions + Send + Sync>; /// A builder that discovers multiple Vortex files from glob patterns and constructs a /// [`MultiLayoutDataSource`] to scan them as a single data source. @@ -122,6 +131,52 @@ impl MultiFileDataSource { /// Discovers files via glob, opens the first file eagerly to determine the schema, /// and creates lazy factories for the remaining files. pub async fn build(self) -> VortexResult { + let session = self.session.clone(); + let open_options_fn = Arc::clone(&self.open_options_fn); + let (first_file, all_files) = self.discover().await?; + layout_source(&session, &open_options_fn, &first_file, &all_files) + } + + /// Build a [`DataSource`] whose scans run on the planner-driven executor. + /// + /// Discovers files as [`build`](Self::build) does and opens the first file for the schema. + /// The source is a [`PlanDataSource`] whose remaining files are opened when a scan reaches + /// them, as units of the scan's work. The planner-driven executor cannot read list layouts + /// yet, so when the schema could hold one, this returns [`build`](Self::build)'s layout + /// reader source instead. + pub async fn build_plan(self) -> VortexResult { + let session = self.session.clone(); + let open_options_fn = Arc::clone(&self.open_options_fn); + let (first_file, all_files) = self.discover().await?; + if may_contain_list_layout(first_file.dtype()) { + return Ok(Arc::new(layout_source( + &session, + &open_options_fn, + &first_file, + &all_files, + )?)); + } + let mut files = vec![PlanSourceFile::Opened(first_file.plan_file())]; + files.extend( + all_files[1..] + .iter() + .map(|(file, fs)| PlanSourceFile::Deferred { + file: Arc::new(DeferredVortexPlanFile { + fs: Arc::clone(fs), + file: file.clone(), + session: session.clone(), + open_options_fn: Arc::clone(&open_options_fn), + }), + byte_size: file.size, + }), + ); + let source = PlanDataSource::from_files(session, first_file.dtype().clone(), files); + debug!(file_count = all_files.len(), dtype = %source.dtype(), "built a plan MultiFileDataSource"); + Ok(Arc::new(source)) + } + + /// Discovers the files of the globs, in order, and opens the first. + async fn discover(self) -> VortexResult<(VortexFile, Vec<(FileListing, FileSystemRef)>)> { if self.glob_sources.is_empty() { vortex_bail!("MultiFileDataSource requires at least one glob pattern"); } @@ -173,35 +228,35 @@ impl MultiFileDataSource { let (first_file_listing, first_fs) = &all_files[0]; let open_fn = self.open_options_fn.as_ref(); let first_file = open_file(first_fs, first_file_listing, &self.session, open_fn).await?; - let first_reader = first_file.layout_reader()?; - - let byte_sizes: Vec> = all_files.iter().map(|(file, _)| file.size).collect(); - - let factories: Vec> = all_files[1..] - .iter() - .map(|(file, fs)| { - Arc::new(VortexFileReaderFactory { - fs: Arc::clone(fs), - file: file.clone(), - session: self.session.clone(), - open_options_fn: Arc::clone(&self.open_options_fn), - }) as Arc - }) - .collect(); - - let inner = MultiLayoutDataSource::new_with_first( - first_reader, - factories, - byte_sizes, - &self.session, - ); - - debug!(file_count, dtype = %inner.dtype(), "built MultiFileDataSource"); - - Ok(inner) + Ok((first_file, all_files)) } } +/// The layout reader source over `all_files`, whose first is open as `first_file`. +fn layout_source( + session: &VortexSession, + open_options_fn: &OpenOptionsFn, + first_file: &VortexFile, + all_files: &[(FileListing, FileSystemRef)], +) -> VortexResult { + let first_reader = first_file.layout_reader()?; + let byte_sizes: Vec> = all_files.iter().map(|(file, _)| file.size).collect(); + let factories: Vec> = all_files[1..] + .iter() + .map(|(file, fs)| { + Arc::new(VortexFileReaderFactory { + fs: Arc::clone(fs), + file: file.clone(), + session: session.clone(), + open_options_fn: Arc::clone(open_options_fn), + }) as Arc + }) + .collect(); + let inner = MultiLayoutDataSource::new_with_first(first_reader, factories, byte_sizes, session); + debug!(file_count = all_files.len(), dtype = %inner.dtype(), "built MultiFileDataSource"); + Ok(inner) +} + /// Creates a local filesystem backed by `object_store::local::LocalFileSystem`. // TODO(ngates): create a native file system without an object_store dependency. // Turns out it's not a trivial change because we have always used object_store with its own @@ -297,6 +352,28 @@ impl LayoutReaderFactory for VortexFileReaderFactory { } } +/// A [`DeferredPlanFile`] that opens a single Vortex file when a scan reaches it. +struct DeferredVortexPlanFile { + fs: FileSystemRef, + file: FileListing, + session: VortexSession, + open_options_fn: OpenOptionsFn, +} + +#[async_trait] +impl DeferredPlanFile for DeferredVortexPlanFile { + async fn open(&self) -> VortexResult> { + let file = open_file( + &self.fs, + &self.file, + &self.session, + self.open_options_fn.as_ref(), + ) + .await?; + Ok(Some(file.plan_file())) + } +} + #[cfg(test)] mod tests { use std::fmt; diff --git a/vortex-file/src/plan_tests.rs b/vortex-file/src/plan_tests.rs new file mode 100644 index 00000000000..80473adc551 --- /dev/null +++ b/vortex-file/src/plan_tests.rs @@ -0,0 +1,389 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Plan data sources read through the Scan API's `split` and `open`, over real files whose +//! segments are read through the session's I/O. + +use std::fmt; +use std::num::NonZeroUsize; +use std::ops::Range; +use std::sync::Arc; +use std::sync::LazyLock; + +use async_trait::async_trait; +use futures::StreamExt; +use futures::TryStreamExt; +use futures::stream; +use rstest::rstest; +use vortex_array::ArrayRef; +use vortex_array::IntoArray; +use vortex_array::VortexSessionExecute; +use vortex_array::arrays::PrimitiveArray; +use vortex_array::arrays::StructArray; +use vortex_array::expr::Expression; +use vortex_array::expr::get_item; +use vortex_array::expr::gt; +use vortex_array::expr::lit; +use vortex_array::expr::root; +use vortex_array::expr::stats::Precision; +use vortex_array::stream::SendableArrayStream; +use vortex_buffer::Buffer; +use vortex_buffer::ByteBuffer; +use vortex_buffer::ByteBufferMut; +use vortex_error::VortexResult; +use vortex_error::vortex_err; +use vortex_io::VortexReadAt; +use vortex_io::filesystem::FileListing; +use vortex_io::filesystem::FileSystem; +use vortex_io::filesystem::FileSystemRef; +use vortex_io::session::RuntimeSession; +use vortex_layout::session::LayoutSession; +use vortex_scan::DataSourceRef; +use vortex_scan::DataSourceScanRef; +use vortex_scan::PartitionRef; +use vortex_scan::ScanRequest; +use vortex_scan::pool::ScanPoolRef; +use vortex_session::VortexSession; + +use crate::OpenOptionsSessionExt; +use crate::WriteOptionsSessionExt; +use crate::multi::MultiFileDataSource; +use crate::multi::MultiFileSession; + +static SESSION: LazyLock = LazyLock::new(|| { + let session = VortexSession::empty() + .with::() + .with::() + .with::(); + crate::register_default_encodings(&session); + crate::enable_all_registered_array_encodings(&session); + session +}); + +/// The rows of a one-file source: several chunks of the scan's chunk grid. +const ROWS: u32 = 200_000; + +/// A file of one `n` column holding `values`, with file statistics. +async fn file_bytes(values: Range) -> VortexResult { + let array = + StructArray::from_fields(&[("n", Buffer::from_iter(values).into_array())])?.into_array(); + let mut buf = ByteBufferMut::empty(); + SESSION + .write_options() + .write(&mut buf, array.to_array_stream()) + .await?; + Ok(buf.freeze()) +} + +async fn one_file() -> VortexResult { + let file = SESSION + .open_options() + .open_buffer(file_bytes(0..ROWS).await?)?; + Ok(file.plan_data_source()) +} + +fn n() -> Expression { + get_item("n", root()) +} + +fn request(ordered: bool) -> ScanRequest { + ScanRequest { + projection: n(), + ordered, + ..Default::default() + } +} + +async fn values(stream: SendableArrayStream) -> VortexResult> { + let arrays: Vec = stream.try_collect().await?; + let mut ctx = SESSION.create_execution_ctx(); + let mut values = Vec::new(); + for array in arrays { + values.extend_from_slice(array.execute::(&mut ctx)?.as_slice::()); + } + Ok(values) +} + +/// Reads `pool` with `workers` workers, each polled on a task of its own, in the order the +/// workers were taken. +async fn read_pool(pool: ScanPoolRef, workers: usize) -> VortexResult>> { + let tasks: Vec<_> = (0..workers) + .map(|_| tokio::spawn(values(Arc::clone(&pool).worker()))) + .collect(); + let mut out = Vec::with_capacity(workers); + for task in tasks { + out.push( + task.await + .map_err(|err| vortex_err!("worker task failed: {err}"))??, + ); + } + Ok(out) +} + +/// Reads a scan with one worker of its pool. +async fn read_one(scan: DataSourceScanRef) -> VortexResult> { + values(scan.open()?.worker()).await +} + +fn sorted(workers: Vec>) -> Vec { + let mut all: Vec = workers.into_iter().flatten().collect(); + all.sort_unstable(); + all +} + +/// Split pieces are contiguous, never empty, and read every row in order. +#[rstest] +#[case::one(1)] +#[case::two(2)] +#[case::seven(7)] +#[case::many(1000)] +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[cfg_attr(miri, ignore)] +async fn split_pieces_cover_all_rows_in_order(#[case] n: usize) -> VortexResult<()> { + let source = one_file().await?; + let scan = source.scan(request(true)).await?; + assert_eq!(scan.row_count(), Precision::exact(u64::from(ROWS))); + let pieces = scan.split(NonZeroUsize::new(n).unwrap_or(NonZeroUsize::MIN))?; + assert!(!pieces.is_empty() && pieces.len() <= n); + if n > 1 { + assert!(pieces.len() > 1); + } + let mut counted = 0; + let mut read = Vec::new(); + for piece in pieces { + let rows = piece.row_count(); + let rows = rows + .as_exact() + .ok_or_else(|| vortex_err!("inexact {rows:?}"))?; + assert!(rows > 0); + counted += rows; + let values = read_one(piece).await?; + assert_eq!(values.len() as u64, rows); + read.extend(values); + } + assert_eq!(counted, u64::from(ROWS)); + assert_eq!(read, (0..ROWS).collect::>()); + Ok(()) +} + +/// The workers of an unordered pool together read every selected row once. +#[rstest] +#[case::projection(None)] +#[case::filter(Some(gt(n(), lit(1_000u32))))] +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[cfg_attr(miri, ignore)] +async fn open_reads_every_row_once(#[case] filter: Option) -> VortexResult<()> { + let first = if filter.is_some() { 1_001 } else { 0 }; + let source = one_file().await?; + let scan = source + .scan(ScanRequest { + filter, + split_concurrency: NonZeroUsize::new(2), + ..request(false) + }) + .await?; + let workers = read_pool(scan.open()?, 4).await?; + assert_eq!(sorted(workers), (first..ROWS).collect::>()); + Ok(()) +} + +/// An ordered pool gives all of its rows, in order, to its first worker. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[cfg_attr(miri, ignore)] +async fn ordered_open_reads_in_order_on_the_first_worker() -> VortexResult<()> { + let source = one_file().await?; + let workers = read_pool(source.scan(request(true)).await?.open()?, 3).await?; + assert_eq!(workers[0], (0..ROWS).collect::>()); + assert!(workers[1..].iter().all(Vec::is_empty)); + Ok(()) +} + +/// A pool's limit holds across its workers; an ordered pool returns the first rows. +#[rstest] +#[case::unordered(false, None)] +#[case::unordered_filter(false, Some(gt(n(), lit(1_000u32))))] +#[case::ordered(true, None)] +#[case::ordered_filter(true, Some(gt(n(), lit(1_000u32))))] +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[cfg_attr(miri, ignore)] +async fn open_applies_the_limit( + #[case] ordered: bool, + #[case] filter: Option, +) -> VortexResult<()> { + const LIMIT: u32 = 70_000; + let first = if filter.is_some() { 1_001 } else { 0 }; + let source = one_file().await?; + let scan = source + .scan(ScanRequest { + filter, + limit: Some(u64::from(LIMIT)), + ..request(ordered) + }) + .await?; + // A limit holds across the whole scan, so a limited scan is not split. + let scan = { + let mut pieces = scan.split(NonZeroUsize::new(4).unwrap_or(NonZeroUsize::MIN))?; + assert_eq!(pieces.len(), 1); + pieces.remove(0) + }; + let workers = read_pool(scan.open()?, 3).await?; + if ordered { + assert_eq!(workers[0], (first..first + LIMIT).collect::>()); + } + let all = sorted(workers); + assert_eq!(all.len(), LIMIT as usize); + all.windows(2).for_each(|w| assert!(w[0] < w[1])); + assert!(all.iter().all(|value| (first..ROWS).contains(value))); + Ok(()) +} + +/// An in-memory file system over named files. +struct MemoryFileSystem { + files: Vec<(String, ByteBuffer)>, +} + +impl fmt::Debug for MemoryFileSystem { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("MemoryFileSystem").finish() + } +} + +impl MemoryFileSystem { + fn file(&self, path: &str) -> Option<&ByteBuffer> { + self.files + .iter() + .find(|(name, _)| name == path) + .map(|(_, bytes)| bytes) + } +} + +#[async_trait] +impl FileSystem for MemoryFileSystem { + fn list(&self, _prefix: &str) -> stream::BoxStream<'_, VortexResult> { + stream::empty().boxed() + } + + async fn head(&self, path: &str) -> VortexResult> { + Ok(self.file(path).map(|bytes| FileListing { + path: path.to_string(), + size: Some(bytes.len() as u64), + })) + } + + async fn open_read(&self, path: &str) -> VortexResult> { + let bytes = self + .file(path) + .ok_or_else(|| vortex_err!("no file {path}"))? + .clone(); + Ok(Arc::new(bytes)) + } + + async fn delete(&self, _path: &str) -> VortexResult<()> { + Ok(()) + } +} + +/// The values of the files of [`three_files`]. +const FILES: [Range; 3] = [0..70_000, 70_000..140_000, 140_000..210_000]; + +/// A V2 source over three files, of which all but the first are opened during scans. +async fn three_files() -> VortexResult { + let mut files = Vec::new(); + for (i, values) in FILES.into_iter().enumerate() { + files.push((format!("{i}.vortex"), file_bytes(values).await?)); + } + let fs: FileSystemRef = Arc::new(MemoryFileSystem { files }); + let mut builder = MultiFileDataSource::new(SESSION.clone()); + for i in 0..FILES.len() { + builder = builder.with_glob(format!("{i}.vortex"), Some(Arc::clone(&fs))); + } + builder.build_plan().await +} + +/// Deferred files are opened by the workers that take them, and every row of every file is read +/// once. +#[rstest] +#[case::all(None, 0)] +#[case::filter(Some(gt(n(), lit(100_000u32))), 100_001)] +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[cfg_attr(miri, ignore)] +async fn open_reads_deferred_files( + #[case] filter: Option, + #[case] first: u32, +) -> VortexResult<()> { + let source = three_files().await?; + assert_eq!(source.row_count(), Precision::inexact(210_000u64)); + let request = ScanRequest { + filter, + ..request(false) + }; + let workers = read_pool(source.scan(request.clone()).await?.open()?, 4).await?; + assert_eq!(sorted(workers), (first..210_000).collect::>()); + + // Ordered, the files are read in order. + let ordered = ScanRequest { + ordered: true, + ..request + }; + let workers = read_pool(source.scan(ordered).await?.open()?, 2).await?; + assert_eq!(workers[0], (first..210_000).collect::>()); + Ok(()) +} + +/// A multi-file scan splits on files that are not open yet and on the rows of the open one. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[cfg_attr(miri, ignore)] +async fn split_keeps_deferred_files_whole() -> VortexResult<()> { + let source = three_files().await?; + let scan = source.scan(request(true)).await?; + let pieces = scan.split(NonZeroUsize::new(4).unwrap_or(NonZeroUsize::MIN))?; + assert!(pieces.len() > 1 && pieces.len() <= 4); + let mut read = Vec::new(); + for piece in pieces { + let values = read_one(piece).await?; + assert!(!values.is_empty()); + read.extend(values); + } + assert_eq!(read, (0..210_000).collect::>()); + Ok(()) +} + +/// An unordered multi-file limit holds across files and workers. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[cfg_attr(miri, ignore)] +async fn open_limits_across_deferred_files() -> VortexResult<()> { + let source = three_files().await?; + let scan = source + .scan(ScanRequest { + limit: Some(100_000), + ..request(false) + }) + .await?; + let all = sorted(read_pool(scan.open()?, 4).await?); + assert_eq!(all.len(), 100_000); + all.windows(2).for_each(|w| assert!(w[0] < w[1])); + Ok(()) +} + +/// The partitions of a multi-file scan are its files, deferred ones included. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[cfg_attr(miri, ignore)] +async fn partitions_are_files() -> VortexResult<()> { + let source = three_files().await?; + let partitions: Vec = source + .scan(request(true)) + .await? + .partitions() + .try_collect() + .await?; + assert_eq!( + partitions.iter().map(|p| p.index()).collect::>(), + vec![0, 1, 2] + ); + let mut read = Vec::new(); + for partition in partitions { + read.extend(values(partition.execute()?).await?); + } + assert_eq!(read, (0..210_000).collect::>()); + Ok(()) +} diff --git a/vortex-file/src/source.rs b/vortex-file/src/source.rs index 84d5c121718..713278b20d9 100644 --- a/vortex-file/src/source.rs +++ b/vortex-file/src/source.rs @@ -2,74 +2,30 @@ // SPDX-FileCopyrightText: Copyright the Vortex contributors use async_trait::async_trait; -use futures::StreamExt; -use futures::stream; use vortex_array::aggregate_fn::AggregateFnRef; use vortex_array::dtype::DType; use vortex_array::dtype::FieldPath; -use vortex_array::expr::Expression; use vortex_array::expr::stats::Precision; use vortex_array::scalar::Scalar; use vortex_array::stats::StatsSet; use vortex_error::VortexResult; use vortex_scan::DataSource; -use vortex_scan::DataSourceScan; use vortex_scan::DataSourceScanRef; use vortex_scan::PartitionRef; -use vortex_scan::PartitionStream; use vortex_scan::ScanRequest; use vortex_session::VortexSession; use crate::FileStatistics; -use crate::pruning::is_falsified_by_file_stats; /// A file's scans with the statistics of its footer. pub(crate) struct FileDataSource { source: S, statistics: Option, - /// Set when the inner source does not prune with the file's statistics itself. - pruning: Option, -} - -/// What [`FileDataSource`] needs to prove a scan's filter false over the whole file. -struct FilePruning { - row_count: u64, - session: VortexSession, } impl FileDataSource { pub(crate) fn new(source: S, statistics: Option) -> Self { - Self { - source, - statistics, - pruning: None, - } - } - - /// Skip scans whose filter the file's statistics prove false over all `row_count` rows of - /// the file, before the inner source reads anything. - pub(crate) fn with_file_pruning(mut self, row_count: u64, session: VortexSession) -> Self { - self.pruning = Some(FilePruning { row_count, session }); - self - } - - /// Whether the file's statistics prove `filter` false for every row of the file, and so for - /// every row range of it. - /// - /// A filter that does not bind is not pruned: the inner scan reports the error. - fn is_pruned(&self, filter: Option<&Expression>) -> VortexResult { - let (Some(pruning), Some(statistics), Some(filter)) = - (&self.pruning, &self.statistics, filter) - else { - return Ok(false); - }; - let Ok(filter) = filter - .bind(self.source.dtype()) - .and_then(|filter| filter.optimize_recursive()) - else { - return Ok(false); - }; - is_falsified_by_file_stats(&filter, pruning.row_count, statistics, &pruning.session) + Self { source, statistics } } } @@ -96,15 +52,7 @@ impl DataSource for FileDataSource { } async fn scan(&self, request: ScanRequest) -> VortexResult { - let filter = request.filter.clone(); - let scan = self.source.scan(request).await?; - Ok(if self.is_pruned(filter.as_ref())? { - Box::new(PrunedScan { - dtype: scan.dtype().clone(), - }) - } else { - scan - }) + self.source.scan(request).await } async fn field_statistics(&self, field_path: &FieldPath) -> VortexResult { @@ -136,22 +84,3 @@ impl DataSource for FileDataSource { .map_or(Precision::Absent, Precision::Exact)) } } - -/// A scan of a file whose statistics rule out every row: it has no partitions. -struct PrunedScan { - dtype: DType, -} - -impl DataSourceScan for PrunedScan { - fn dtype(&self) -> &DType { - &self.dtype - } - - fn partition_count(&self) -> Precision { - Precision::exact(0usize) - } - - fn partitions(self: Box) -> PartitionStream { - stream::empty().boxed() - } -} diff --git a/vortex-layout/src/scan/layout.rs b/vortex-layout/src/scan/layout.rs index 926ea7cc8e8..32312aa8732 100644 --- a/vortex-layout/src/scan/layout.rs +++ b/vortex-layout/src/scan/layout.rs @@ -438,27 +438,7 @@ impl DataSourceScan for LayoutSplitScan { /// /// 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 + vortex_scan::pool::group_contiguous(ranges, n, |range| range.end - range.start) } impl Stream for LayoutReaderScan { diff --git a/vortex-layout/src/scan/limit.rs b/vortex-layout/src/scan/limit.rs index e7791e5961f..2fa6a25e638 100644 --- a/vortex-layout/src/scan/limit.rs +++ b/vortex-layout/src/scan/limit.rs @@ -1,22 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors -use std::sync::Arc; -use std::sync::atomic::AtomicU64; -use std::sync::atomic::Ordering; - -use vortex_error::VortexExpect; -use vortex_mask::Mask; - -/// A cloneable row budget shared by all work that can contribute rows to one scan. -/// -/// Filterless scans reserve each split's selected rows before constructing its projection, so -/// rows past the limit are never decoded. Filtered scans cannot know a split's row count up front, -/// so they take rows from the budget as arrays are emitted and discard the excess. Either way, -/// the order in which rows are taken decides which rows are returned: an ordered scan takes them -/// in split order, an unordered one in completion order. -#[derive(Clone)] -pub(crate) struct RowLimit(Arc); +pub(crate) use vortex_scan::pool::RowLimit; /// The row limit of a scan. #[derive(Clone)] @@ -36,109 +21,3 @@ impl ScanLimit { } } } - -impl RowLimit { - pub(crate) fn new(limit: u64) -> Self { - Self(Arc::new(AtomicU64::new(limit))) - } - - /// Reserve rows selected by `mask` and retain only the earliest granted rows in that mask. - pub(crate) fn limit(&self, mask: Mask) -> Mask { - let granted = self.take(mask.true_count()); - mask.limit(granted) - } - - /// Reserve up to `rows` rows, returning how many the remaining budget granted. - pub(crate) fn take(&self, rows: usize) -> usize { - let requested = u64::try_from(rows).unwrap_or(u64::MAX); - usize::try_from(self.reserve(requested)).unwrap_or(usize::MAX) - } - - pub(crate) fn is_exhausted(&self) -> bool { - self.0.load(Ordering::Relaxed) == 0 - } - - fn reserve(&self, requested: u64) -> u64 { - let remaining = self - .0 - .try_update(Ordering::Relaxed, Ordering::Relaxed, |remaining| { - Some(remaining.saturating_sub(requested)) - }) - .ok() - .vortex_expect("row reservation always updates the budget"); - remaining.min(requested) - } -} - -#[cfg(test)] -mod tests { - use std::sync::Arc; - use std::sync::Barrier; - use std::sync::atomic::AtomicU64; - use std::sync::atomic::Ordering; - use std::thread; - - use vortex_mask::Mask; - - use super::RowLimit; - - #[test] - fn reserve_grants_up_to_the_remaining_budget() { - let limit = RowLimit::new(5); - assert_eq!(limit.reserve(3), 3); - assert!(!limit.is_exhausted()); - // Only two rows remain, so a larger request saturates at what is left. - assert_eq!(limit.reserve(10), 2); - assert!(limit.is_exhausted()); - // Once exhausted, further requests grant nothing. - assert_eq!(limit.reserve(1), 0); - } - - #[test] - fn limit_keeps_the_earliest_granted_rows() { - let limit = RowLimit::new(2); - // Rows 0, 2, 3, 5 are selected; only the first two survive the budget of 2. - let mask = Mask::from_iter([true, false, true, true, false, true]); - let limited = limit.limit(mask); - - assert_eq!(limited.true_count(), 2); - assert!(limited.value(0)); - assert!(limited.value(2)); - assert!(!limited.value(3)); - assert!(!limited.value(5)); - assert!(limit.is_exhausted()); - } - - #[test] - fn concurrent_reservations_never_exceed_the_budget() { - const THREADS: usize = 8; - const PER_THREAD: u64 = 10_000; - const LIMIT: u64 = 25_000; - - let limit = RowLimit::new(LIMIT); - let granted_total = Arc::new(AtomicU64::new(0)); - let barrier = Arc::new(Barrier::new(THREADS)); - - thread::scope(|scope| { - for _ in 0..THREADS { - let limit = limit.clone(); - let granted_total = Arc::clone(&granted_total); - let barrier = Arc::clone(&barrier); - scope.spawn(move || { - // Start all threads together to maximize contention on the atomic. - barrier.wait(); - let mut local = 0; - for _ in 0..PER_THREAD { - local += limit.reserve(1); - } - granted_total.fetch_add(local, Ordering::Relaxed); - }); - } - }); - - // Total requested (THREADS * PER_THREAD = 80_000) exceeds the budget, so exactly the - // budget is granted across all threads — no double-grant, over-grant, or lost reservation. - assert_eq!(granted_total.load(Ordering::Relaxed), LIMIT); - assert!(limit.is_exhausted()); - } -} diff --git a/vortex-layout/src/scan/pool.rs b/vortex-layout/src/scan/pool.rs index fcfea905b7a..50ce33a45f7 100644 --- a/vortex-layout/src/scan/pool.rs +++ b/vortex-layout/src/scan/pool.rs @@ -40,6 +40,7 @@ use vortex_scan::DataSourceScanRef; use vortex_scan::Partition; use vortex_scan::PartitionRef; use vortex_scan::PartitionStream; +use vortex_scan::pool::SPLITS_IN_FLIGHT_PER_WORKER; use vortex_scan::pool::ScanPool; use vortex_scan::pool::ScanPoolRef; use vortex_scan::row_mask::RowMask; @@ -57,10 +58,6 @@ 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, diff --git a/vortex-scan/Cargo.toml b/vortex-scan/Cargo.toml index 9c1d41b1aa2..b2e0df7138b 100644 --- a/vortex-scan/Cargo.toml +++ b/vortex-scan/Cargo.toml @@ -15,6 +15,7 @@ version = { workspace = true } all-features = true [dependencies] +async-channel = { workspace = true } async-lock = { workspace = true } async-trait = { workspace = true } bit-vec = { workspace = true } diff --git a/vortex-scan/src/execution/driver.rs b/vortex-scan/src/execution/driver.rs index fd19cc9f485..f30c75467fe 100644 --- a/vortex-scan/src/execution/driver.rs +++ b/vortex-scan/src/execution/driver.rs @@ -13,6 +13,7 @@ use std::future; use std::num::NonZeroUsize; +use std::ops::Range; use std::sync::Arc; use std::task::Poll; @@ -120,7 +121,7 @@ impl ScanDriver { rows: scan.rows().clone(), }; let io = scan.io(); - let root = compose(&scan); + let root = compose(&scan, scan.rows().clone()); let (chunk_handle, chunk_io, chunk_map) = (self.handle.clone(), Arc::clone(&io), Arc::clone(&map_fn)); let batches = run_stream(self.handle, root, scope, io, map_fn, inline) @@ -157,10 +158,9 @@ impl ScanDriver { } } -/// The planners of a scan, composed: with a filter, its pruning plans first over the whole scan, +/// The planners of a scan's `rows`, composed: with a filter, its pruning plans first over `rows`, /// continuing into the chunks of the rows they keep; without, the chunks directly. -fn compose(scan: &Arc) -> Box { - let rows = scan.rows().clone(); +pub(crate) fn compose(scan: &Arc, rows: Range) -> Box { let chunks = { let scan = Arc::clone(scan); let rows = rows.clone(); diff --git a/vortex-scan/src/execution/mod.rs b/vortex-scan/src/execution/mod.rs index caa6a7ce099..6baffdda7bc 100644 --- a/vortex-scan/src/execution/mod.rs +++ b/vortex-scan/src/execution/mod.rs @@ -45,7 +45,6 @@ pub(crate) use self::chunk::ROW_BLOCK_SIZE; #[cfg(test)] pub(crate) use self::chunk::row_chunks; pub(crate) use self::chunk::rows_per_chunk; -#[cfg(test)] pub(crate) use self::chunk::scan_chunks; use self::filter::FilterPlanner; pub use self::filter::FilterPlans; diff --git a/vortex-scan/src/pool.rs b/vortex-scan/src/pool.rs index e2710b899ec..eb6ebb9ecdc 100644 --- a/vortex-scan/src/pool.rs +++ b/vortex-scan/src/pool.rs @@ -1,17 +1,27 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors -//! Pools of work that host threads share by each polling a worker. +//! Pools of work that host threads share by each polling a worker, and the pieces that sources +//! build their own pools from. +use std::num::NonZeroUsize; use std::sync::Arc; +use std::sync::atomic::AtomicU64; +use std::sync::atomic::Ordering; use async_lock::Mutex; use futures::StreamExt; +use futures::future; use futures::stream; +use futures::stream::BoxStream; +use vortex_array::ArrayRef; use vortex_array::dtype::DType; use vortex_array::stream::ArrayStreamAdapter; use vortex_array::stream::ArrayStreamExt; use vortex_array::stream::SendableArrayStream; +use vortex_error::VortexExpect; +use vortex_error::VortexResult; +use vortex_mask::Mask; use crate::DataSourceScanRef; use crate::PartitionStream; @@ -33,6 +43,118 @@ pub trait ScanPool: 'static + Send + Sync { fn worker(self: Arc) -> SendableArrayStream; } +/// The most units each worker of a pool keeps in flight when the request's +/// [`split_concurrency`](crate::ScanRequest::split_concurrency) does not say. Stands in for the +/// scan engine's memory budget. +pub const SPLITS_IN_FLIGHT_PER_WORKER: usize = 4; + +/// A cloneable row budget shared by all work that can contribute rows to one scan. +/// +/// Filterless scans can reserve each unit's selected rows before decoding it, so rows past the +/// limit are never decoded. Filtered scans cannot know a unit's row count up front, so they take +/// rows from the budget as arrays are emitted and discard the excess. Either way, the order in +/// which rows are taken decides which rows are returned: an ordered scan takes them in row order, +/// an unordered one in completion order. +#[derive(Clone, Debug)] +pub struct RowLimit(Arc); + +impl RowLimit { + /// A budget of `limit` rows. + pub fn new(limit: u64) -> Self { + Self(Arc::new(AtomicU64::new(limit))) + } + + /// Reserves the rows selected by `mask` and keeps only the earliest granted rows of it. + pub fn limit(&self, mask: Mask) -> Mask { + let granted = self.take(mask.true_count()); + mask.limit(granted) + } + + /// Reserves up to `rows` rows, returning how many the remaining budget granted. + pub fn take(&self, rows: usize) -> usize { + let requested = u64::try_from(rows).unwrap_or(u64::MAX); + usize::try_from(self.reserve(requested)).unwrap_or(usize::MAX) + } + + /// Whether the budget is spent. + pub fn is_exhausted(&self) -> bool { + self.0.load(Ordering::Relaxed) == 0 + } + + fn reserve(&self, requested: u64) -> u64 { + let remaining = self + .0 + .try_update(Ordering::Relaxed, Ordering::Relaxed, |remaining| { + Some(remaining.saturating_sub(requested)) + }) + .ok() + .vortex_expect("row reservation always updates the budget"); + remaining.min(requested) + } +} + +/// Ends `arrays` once `limit` is spent, taking each array's rows from it as the array is yielded +/// and slicing the array that spends it. Also ends after the first error. +pub fn trim_to_limit( + arrays: BoxStream<'static, VortexResult>, + limit: RowLimit, +) -> BoxStream<'static, VortexResult> { + stream::unfold(Some(arrays), move |arrays| { + let limit = limit.clone(); + async move { + let mut arrays = arrays?; + if limit.is_exhausted() { + return None; + } + let array = match arrays.next().await? { + Ok(array) => array, + Err(err) => return Some((Err(err), None)), + }; + let granted = limit.take(array.len()); + if granted == array.len() { + return Some((Ok(array), Some(arrays))); + } + if granted == 0 { + return None; + } + Some((array.slice(0..granted), None)) + } + }) + .filter(|array| future::ready(array.as_ref().map_or(true, |array| !array.is_empty()))) + .boxed() +} + +/// Groups consecutive `items` into at most `n` contiguous groups of about equal total `weight`. +/// +/// Never cuts an item: each lands whole in one group. Every group is non-empty. +pub fn group_contiguous( + items: Vec, + n: NonZeroUsize, + weight: impl Fn(&T) -> u64, +) -> Vec> { + let total = items + .iter() + .map(|item| u128::from(weight(item))) + .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 item in items { + let group = (before * n_groups / total).min(n_groups - 1); + before += u128::from(weight(&item)); + if current_group != Some(group) { + current_group = Some(group); + groups.push(Vec::new()); + } + if let Some(last) = groups.last_mut() { + last.push(item); + } + } + groups +} + /// 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. @@ -77,6 +199,10 @@ mod tests { use std::any::Any; use std::num::NonZeroUsize; use std::sync::Arc; + use std::sync::Barrier; + use std::sync::atomic::AtomicU64; + use std::sync::atomic::Ordering; + use std::thread; use futures::StreamExt; use futures::TryStreamExt; @@ -93,7 +219,11 @@ mod tests { use vortex_array::stream::SendableArrayStream; use vortex_buffer::Buffer; use vortex_error::VortexResult; + use vortex_mask::Mask; + use super::RowLimit; + use super::group_contiguous; + use super::trim_to_limit; use crate::DataSourceScan; use crate::Partition; use crate::PartitionRef; @@ -125,7 +255,8 @@ mod tests { } fn execute(self: Box) -> VortexResult { - let array = Buffer::from_iter(0..self.rows as i32).into_array(); + let rows = i32::try_from(self.rows).unwrap_or(i32::MAX); + let array = Buffer::from_iter(0..rows).into_array(); Ok(ArrayStreamExt::boxed(ArrayStreamAdapter::new( DTYPE.clone(), stream::iter([Ok(array)]), @@ -173,6 +304,79 @@ mod tests { Ok(()) } + #[test] + fn reserve_grants_up_to_the_remaining_budget() { + let limit = RowLimit::new(5); + assert_eq!(limit.reserve(3), 3); + assert!(!limit.is_exhausted()); + assert_eq!(limit.reserve(10), 2); + assert!(limit.is_exhausted()); + assert_eq!(limit.reserve(1), 0); + } + + #[test] + fn limit_keeps_the_earliest_granted_rows() { + let limit = RowLimit::new(2); + let mask = Mask::from_iter([true, false, true, true, false, true]); + let limited = limit.limit(mask); + assert_eq!(limited.true_count(), 2); + assert!(limited.value(0)); + assert!(limited.value(2)); + assert!(!limited.value(3)); + assert!(!limited.value(5)); + assert!(limit.is_exhausted()); + } + + #[test] + fn concurrent_reservations_never_exceed_the_budget() { + const THREADS: usize = 8; + const PER_THREAD: u64 = 10_000; + const LIMIT: u64 = 25_000; + + let limit = RowLimit::new(LIMIT); + let granted_total = Arc::new(AtomicU64::new(0)); + let barrier = Arc::new(Barrier::new(THREADS)); + thread::scope(|scope| { + for _ in 0..THREADS { + let limit = limit.clone(); + let granted_total = Arc::clone(&granted_total); + let barrier = Arc::clone(&barrier); + scope.spawn(move || { + barrier.wait(); + let mut local = 0; + for _ in 0..PER_THREAD { + local += limit.reserve(1); + } + granted_total.fetch_add(local, Ordering::Relaxed); + }); + } + }); + assert_eq!(granted_total.load(Ordering::Relaxed), LIMIT); + assert!(limit.is_exhausted()); + } + + #[test] + fn trim_to_limit_slices_the_array_that_spends_it() -> VortexResult<()> { + let arrays = stream::iter((0..4).map(|_| Ok(Buffer::from_iter(0..3i32).into_array()))); + let trimmed: Vec<_> = + block_on(trim_to_limit(arrays.boxed(), RowLimit::new(7)).try_collect())?; + assert_eq!( + trimmed.iter().map(|a| a.len()).collect::>(), + vec![3, 3, 1] + ); + Ok(()) + } + + #[test] + fn group_contiguous_balances_weights() { + let groups = group_contiguous( + vec![4u64, 4, 4, 4, 1, 1], + NonZeroUsize::new(3).unwrap_or(NonZeroUsize::MIN), + |w| *w, + ); + assert_eq!(groups, vec![vec![4, 4], vec![4], vec![4, 1, 1]]); + } + #[test] fn default_split_returns_the_scan() -> VortexResult<()> { let scan = Box::new(PartitionOnlyScan { rows: vec![2, 3] }); diff --git a/vortex-scan/src/source.rs b/vortex-scan/src/source.rs index f9ec2c97069..52e9cedf616 100644 --- a/vortex-scan/src/source.rs +++ b/vortex-scan/src/source.rs @@ -1,47 +1,19 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors -//! Source inputs and byte access for scans, and the [`DataSource`] that scans them. +//! Source inputs and byte access for scans, and the [`DataSource`](crate::DataSource) that scans +//! them. -use std::any::Any; -use std::num::NonZeroUsize; -use std::ops::Range; use std::sync::Arc; -use async_trait::async_trait; -use futures::StreamExt; -use futures::future; -use futures::stream; -use futures::stream::BoxStream; -use vortex_array::ArrayRef; use vortex_array::dtype::DType; -use vortex_array::dtype::FieldPath; -use vortex_array::expr::BoundExpression; -use vortex_array::expr::stats::Precision; -use vortex_array::stats::StatsSet; -use vortex_array::stream::ArrayStreamAdapter; -use vortex_array::stream::ArrayStreamExt; -use vortex_array::stream::SendableArrayStream; -use vortex_error::VortexResult; pub use vortex_io::segments::SegmentFuture; pub use vortex_io::segments::SegmentId; pub use vortex_io::segments::SegmentSource; -use vortex_io::session::RuntimeSessionExt; -use vortex_session::VortexSession; -use crate::DataSource; -use crate::DataSourceScan; -use crate::DataSourceScanRef; -use crate::Partition; -use crate::PartitionRef; -use crate::PartitionStream; -use crate::ScanRequest; use crate::execution::SegmentLocation; use crate::execution::cache::ScanCache; -use crate::execution::driver::ScanDriver; use crate::plan::LazyPlanRef; -use crate::prepare::ScanBuilder; -use crate::selection::Selection; /// The plan and byte source used to prepare a scan. /// @@ -62,248 +34,14 @@ pub struct ScanInput { pub cache: Option, } -/// A [`DataSource`] over one [`ScanInput`], scanned by the planner-driven executor. -/// -/// This is the standard way to expose a source that can name its segments, whatever its format: -/// a Vortex file, a Parquet file whose column chunks are placed segments, or any store that can -/// lower its data to plans. Every scan of the source shares the input's [`ScanCache`], so scans -/// that overlap in time plan the input and register its reader once. -/// -/// A scan of the source has one partition covering the request's row range, clamped to the -/// input's rows when the row count is known. The partition has [`index`](Partition::index) 0, so a -/// request's `partition_range` and `partition_selection` either select it or leave the scan with -/// no partitions. -/// -/// The partition's [`execute`](Partition::execute) runs the planner-driven scan of its rows with a -/// [`ScanDriver`] on the session's runtime and applies the request's limit. -#[derive(Clone)] -pub struct PlanDataSource { - session: VortexSession, - input: ScanInput, - row_count: Precision, - byte_size: Precision, -} - -impl PlanDataSource { - /// A source scanning `input` with `session`. Without a cache, the input gets a fresh one that - /// all of the source's scans share. - pub fn new(session: VortexSession, mut input: ScanInput) -> Self { - input.cache.get_or_insert_default(); - Self { - session, - input, - row_count: Precision::Absent, - byte_size: Precision::Absent, - } - } - - /// Sets the exact row count of the input, which scans and partitions report. - pub fn with_row_count(mut self, row_count: u64) -> Self { - self.row_count = Precision::exact(row_count); - self - } - - /// Sets an estimate of the input's byte size. - pub fn with_byte_size(mut self, byte_size: Precision) -> Self { - self.byte_size = byte_size; - self - } - - /// The input this source scans. - pub fn input(&self) -> &ScanInput { - &self.input - } - - /// The session scans of this source run with. - pub fn session(&self) -> &VortexSession { - &self.session - } -} - -#[async_trait] -impl DataSource for PlanDataSource { - fn dtype(&self) -> &DType { - &self.input.dtype - } - - fn row_count(&self) -> Precision { - self.row_count - } - - fn byte_size(&self) -> Precision { - self.byte_size - } - - async fn scan(&self, request: ScanRequest) -> VortexResult { - let projection = request - .projection - .bind(&self.input.dtype)? - .optimize_recursive()?; - let filter = request - .filter - .map(|filter| filter.bind(&self.input.dtype)?.optimize_recursive()) - .transpose()?; - let dtype = projection.dtype().clone(); - let row_range = match (request.row_range, self.row_count.as_exact()) { - (Some(rows), Some(count)) => Some(rows.start.min(count)..rows.end.min(count)), - (rows, _) => rows, - }; - // The source is the single unit 0, so a request that does not select it scans nothing. - let selected = request - .partition_range - .as_ref() - .is_none_or(|range| range.contains(&0)) - && request.partition_selection.row_count_in_range(&(0..1)) == 1; - if !selected || request.limit == Some(0) || row_range.as_ref().is_some_and(Range::is_empty) - { - return Ok(Box::new(PlanScan { - dtype, - partitions: Vec::new(), - })); - } - let partition = PlanPartition { - session: self.session.clone(), - input: self.input.clone(), - row_count: self.row_count, - projection, - filter, - row_range, - selection: request.selection, - ordered: request.ordered, - limit: request.limit, - split_concurrency: request.split_concurrency, - }; - Ok(Box::new(PlanScan { - dtype, - partitions: vec![partition], - })) - } - - async fn field_statistics(&self, _field_path: &FieldPath) -> VortexResult { - Ok(StatsSet::default()) - } -} +mod plan; +mod plan_pool; -struct PlanScan { - dtype: DType, - partitions: Vec, -} - -impl DataSourceScan for PlanScan { - fn dtype(&self) -> &DType { - &self.dtype - } - - fn partition_count(&self) -> Precision { - Precision::exact(self.partitions.len()) - } - - fn partitions(self: Box) -> PartitionStream { - stream::iter( - self.partitions - .into_iter() - .map(|partition| Ok(Box::new(partition) as PartitionRef)), - ) - .boxed() - } -} - -/// The rows of a [`PlanDataSource`] that one partition of a scan reads. -struct PlanPartition { - session: VortexSession, - input: ScanInput, - row_count: Precision, - projection: BoundExpression, - filter: Option, - row_range: Option>, - selection: Selection, - ordered: bool, - limit: Option, - split_concurrency: Option, -} - -impl PlanPartition { - fn builder(self) -> ScanBuilder { - let mut builder = ScanBuilder::new(self.session, self.input) - .with_projection(self.projection) - .with_some_filter(self.filter) - .with_selection(self.selection); - if let Some(rows) = self.row_range { - builder = builder.with_row_range(rows); - } - builder - } -} - -impl Partition for PlanPartition { - fn as_any(&self) -> &dyn Any { - self - } - - fn index(&self) -> usize { - 0 - } - - fn row_count(&self) -> Precision { - let rows = match (&self.row_range, self.row_count.as_exact()) { - (Some(rows), _) => rows.clone(), - (None, Some(count)) => 0..count, - (None, None) => return Precision::Absent, - }; - let rows = self.selection.row_count_in_range(&rows); - let rows = self.limit.map_or(rows, |limit| rows.min(limit)); - if self.filter.is_some() { - Precision::inexact(rows) - } else { - Precision::exact(rows) - } - } - - fn byte_size(&self) -> Precision { - Precision::Absent - } - - fn execute(self: Box) -> VortexResult { - let dtype = self.projection.dtype().clone(); - let (ordered, limit, max_in_flight) = (self.ordered, self.limit, self.split_concurrency); - let driver = - ScanDriver::new(self.session.handle(), 1, ordered).with_max_in_flight(max_in_flight); - let arrays = driver.run(self.builder()); - let arrays = match limit { - Some(limit) => limit_arrays(arrays, limit), - None => arrays, - }; - Ok(ArrayStreamExt::boxed(ArrayStreamAdapter::new( - dtype, arrays, - ))) - } -} - -/// Ends `arrays` after its first `limit` rows. -fn limit_arrays( - arrays: BoxStream<'static, VortexResult>, - limit: u64, -) -> BoxStream<'static, VortexResult> { - arrays - .scan(limit, |remaining, array| { - if *remaining == 0 { - return future::ready(None); - } - let array = array.and_then(|array| { - let len = array.len() as u64; - if len <= *remaining { - *remaining -= len; - Ok(array) - } else { - let keep = usize::try_from(*remaining).unwrap_or(usize::MAX); - *remaining = 0; - array.slice(0..keep) - } - }); - future::ready(Some(array)) - }) - .boxed() -} +pub use plan::DeferredPlanFile; +pub use plan::FilePruner; +pub use plan::PlanDataSource; +pub use plan::PlanFile; +pub use plan::PlanSourceFile; #[cfg(test)] mod tests; diff --git a/vortex-scan/src/source/plan.rs b/vortex-scan/src/source/plan.rs new file mode 100644 index 00000000000..0300ea0d870 --- /dev/null +++ b/vortex-scan/src/source/plan.rs @@ -0,0 +1,713 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! [`PlanDataSource`]: a [`DataSource`] over one or more [`ScanInput`]s, scanned by the +//! planner-driven executor. + +use std::any::Any; +use std::num::NonZeroUsize; +use std::ops::Range; +use std::sync::Arc; + +use async_trait::async_trait; +use futures::StreamExt; +use futures::TryStreamExt; +use futures::stream; +use vortex_array::dtype::DType; +use vortex_array::dtype::FieldPath; +use vortex_array::expr::BoundExpression; +use vortex_array::expr::stats::Precision; +use vortex_array::stats::StatsSet; +use vortex_array::stream::ArrayStreamAdapter; +use vortex_array::stream::ArrayStreamExt; +use vortex_array::stream::SendableArrayStream; +use vortex_error::VortexResult; +use vortex_error::vortex_bail; +use vortex_io::session::RuntimeSessionExt; +use vortex_session::VortexSession; + +use super::ScanInput; +use super::plan_pool; +use crate::DataSource; +use crate::DataSourceScan; +use crate::DataSourceScanRef; +use crate::Partition; +use crate::PartitionRef; +use crate::PartitionStream; +use crate::ScanRequest; +use crate::execution::ROW_BLOCK_SIZE; +use crate::execution::driver::ScanDriver; +use crate::pool::RowLimit; +use crate::pool::ScanPoolRef; +use crate::pool::group_contiguous; +use crate::pool::trim_to_limit; +use crate::prepare::ScanBuilder; +use crate::selection::Selection; + +/// Whether a file's own statistics prove a filter, bound to the file's dtype, false for every +/// row of the file. +pub type FilePruner = Arc VortexResult + Send + Sync>; + +/// One open file of a [`PlanDataSource`]: its [`ScanInput`] and what the source knows of it +/// without reading payloads. +#[derive(Clone)] +pub struct PlanFile { + input: ScanInput, + row_count: Option, + splits: Option>, + pruner: Option, +} + +impl PlanFile { + /// A file scanning `input`. Without a cache, the input gets a fresh one that every scan of + /// the file shares. + pub fn new(mut input: ScanInput) -> Self { + input.cache.get_or_insert_default(); + Self { + input, + row_count: None, + splits: None, + pruner: None, + } + } + + /// Sets the file's exact row count. Without it, the source lowers the file's root plan to + /// learn the count when a scan needs it. + pub fn with_row_count(mut self, row_count: u64) -> Self { + self.row_count = Some(row_count); + self + } + + /// Sets the row boundaries that an opened scan cuts the file's work at, such as the file's + /// layout splits, ascending and covering the file's rows. Without them, the work is cut on + /// the scan's chunk grid. + pub fn with_splits(mut self, splits: Arc<[u64]>) -> Self { + self.splits = Some(splits); + self + } + + /// Sets how the file's statistics rule out a scan's filter, so a scan they rule out reads + /// nothing of the file. + pub fn with_pruner(mut self, pruner: FilePruner) -> Self { + self.pruner = Some(pruner); + self + } + + /// The input this file scans. + pub fn input(&self) -> &ScanInput { + &self.input + } + + /// The file's rows, from the row count when set, else from its root plan. + pub(super) fn rows(&self) -> VortexResult { + match self.row_count { + Some(rows) => Ok(rows), + None => Ok(self.input.root.get()?.row_count()), + } + } + + /// The bytes of all of the file's segments. + fn byte_size(&self) -> u64 { + self.input + .locations + .iter() + .map(|location| u64::from(location.length)) + .sum() + } + + pub(super) fn splits(&self) -> Option<&[u64]> { + self.splits.as_deref() + } + + fn is_pruned(&self, filter: Option<&BoundExpression>) -> VortexResult { + match (&self.pruner, filter) { + (Some(pruner), Some(filter)) => pruner(filter), + _ => Ok(false), + } + } +} + +/// Opens a file of a [`PlanDataSource`] when a scan reaches it. +#[async_trait] +pub trait DeferredPlanFile: 'static + Send + Sync { + /// Opens the file, or returns `None` when the scan should skip it. + async fn open(&self) -> VortexResult>; +} + +/// A file of a [`PlanDataSource`]. +#[derive(Clone)] +pub enum PlanSourceFile { + /// A file that is already open. + Opened(PlanFile), + /// A file that a scan opens when it reaches it, so a source over many files reads only the + /// footers its scans need. + Deferred { + /// Opens the file. + file: Arc, + /// The file's size in bytes, if known. + byte_size: Option, + }, +} + +/// A [`DataSource`] over the files of [`ScanInput`]s, scanned by the planner-driven executor. +/// +/// This is the standard way to expose sources that can name their segments, whatever their +/// format: Vortex files, Parquet files whose column chunks are placed segments, or any store that +/// can lower its data to plans. Every scan of a file shares the file's [`ScanCache`], so scans +/// that overlap in time plan the file once. +/// +/// A scan's request applies to each file: its row range and row selection are in the file's own +/// rows. A scan reads its files in order. +/// +/// # Splitting and opening +/// +/// [`split`](DataSourceScan::split) cuts a scan on the 8,192-row block grid of its files, which +/// every chunk boundary of the executor lies on, into contiguous pieces of about equal row +/// counts. It reads nothing; a file that is not open yet is one indivisible unit. +/// +/// [`open`](DataSourceScan::open) prepares each open file of the scan once and hands its parts, +/// the chunks of the scan, or the file's [splits](PlanFile::with_splits) when it has them, to +/// workers, which run several at a time on their own thread. A file that is not open yet is a +/// unit of work too: the worker that takes it opens and prepares it, and puts its parts back for +/// any worker to take. See the pool's documentation in `plan_pool.rs`. +/// +/// # Partitions +/// +/// A scan has one partition per file, whose [`index`](Partition::index) is the file's ordinal, +/// so a request's `partition_range` and `partition_selection` select files. A partition runs its +/// file's scan with a [`ScanDriver`] on the session's runtime. +/// +/// [`ScanCache`]: crate::prepare::ScanCache +#[derive(Clone)] +pub struct PlanDataSource { + session: VortexSession, + dtype: DType, + files: Arc<[PlanSourceFile]>, + row_count: Precision, + byte_size: Precision, +} + +impl PlanDataSource { + /// A source scanning one open `input` with `session`. + pub fn new(session: VortexSession, input: ScanInput) -> Self { + Self::from_file(session, PlanFile::new(input)) + } + + /// A source scanning one open `file` with `session`. + pub fn from_file(session: VortexSession, file: PlanFile) -> Self { + let dtype = file.input.dtype.clone(); + let row_count = file.row_count.map_or(Precision::Absent, Precision::exact); + Self { + session, + dtype, + files: Arc::new([PlanSourceFile::Opened(file)]), + row_count, + byte_size: Precision::Absent, + } + } + + /// A source scanning `files` in order with `session`. Every file must have `dtype`; a scan + /// that opens a file of another dtype fails. + pub fn from_files(session: VortexSession, dtype: DType, files: Vec) -> Self { + let mut rows = Some(0u64); + let mut bytes = Some(0u64); + let mut known_rows = 0; + let mut known_files = 0; + for file in &files { + match file { + PlanSourceFile::Opened(file) => { + match file.row_count { + Some(count) => { + known_rows += count; + known_files += 1; + } + None => rows = None, + } + bytes = bytes.map(|bytes| bytes + file.byte_size()); + } + PlanSourceFile::Deferred { byte_size, .. } => { + rows = None; + bytes = bytes.zip(*byte_size).map(|(bytes, size)| bytes + size); + } + } + } + // Files not open yet are estimated at the average row count of the open ones. + let row_count = match rows { + Some(rows) => Precision::exact(rows + known_rows), + None if known_files > 0 => { + Precision::inexact(known_rows / known_files * files.len() as u64) + } + None => Precision::Absent, + }; + Self { + session, + dtype, + files: files.into(), + row_count, + byte_size: bytes.map_or(Precision::Absent, Precision::inexact), + } + } + + /// Sets the exact row count of a one-file source, which scans and partitions report. + pub fn with_row_count(mut self, row_count: u64) -> Self { + if let [PlanSourceFile::Opened(file)] = &*self.files { + self.files = Arc::new([PlanSourceFile::Opened( + file.clone().with_row_count(row_count), + )]); + } + self.row_count = Precision::exact(row_count); + self + } + + /// Sets an estimate of the source's byte size. + pub fn with_byte_size(mut self, byte_size: Precision) -> Self { + self.byte_size = byte_size; + self + } + + /// The files this source scans, in order. + pub fn files(&self) -> &[PlanSourceFile] { + &self.files + } + + /// The session scans of this source run with. + pub fn session(&self) -> &VortexSession { + &self.session + } +} + +#[async_trait] +impl DataSource for PlanDataSource { + fn dtype(&self) -> &DType { + &self.dtype + } + + fn row_count(&self) -> Precision { + self.row_count + } + + fn byte_size(&self) -> Precision { + self.byte_size + } + + async fn scan(&self, request: ScanRequest) -> VortexResult { + let projection = request.projection.bind(&self.dtype)?.optimize_recursive()?; + let filter = request + .filter + .map(|filter| filter.bind(&self.dtype)?.optimize_recursive()) + .transpose()?; + let mut units = Vec::new(); + let scans_rows = + request.limit != Some(0) && !request.row_range.as_ref().is_some_and(Range::is_empty); + for (ordinal, file) in self.files.iter().enumerate().filter(|_| scans_rows) { + let index = ordinal as u64; + let selected = request + .partition_range + .as_ref() + .is_none_or(|range| range.contains(&index)) + && request + .partition_selection + .row_count_in_range(&(index..index + 1)) + == 1; + if !selected { + continue; + } + let rows = match file { + PlanSourceFile::Opened(file) => { + if file.is_pruned(filter.as_ref())? { + continue; + } + file.row_count + .map(|count| clamp_rows(request.row_range.clone(), count)) + } + PlanSourceFile::Deferred { .. } => None, + }; + if rows.as_ref().is_some_and(Range::is_empty) { + continue; + } + units.push(Unit { + file: ordinal, + rows, + }); + } + let state = ScanState { + session: self.session.clone(), + source_dtype: self.dtype.clone(), + files: Arc::clone(&self.files), + dtype: projection.dtype().clone(), + projection, + filter, + row_range: request.row_range, + selection: request.selection, + ordered: request.ordered, + limit: request.limit, + split_concurrency: request.split_concurrency, + }; + Ok(Box::new(PlanScan { + state: Arc::new(state), + units, + })) + } + + async fn field_statistics(&self, _field_path: &FieldPath) -> VortexResult { + Ok(StatsSet::default()) + } +} + +/// The request's `rows`, or all of them, clamped to a file of `count` rows. +fn clamp_rows(rows: Option>, count: u64) -> Range { + let rows = rows.unwrap_or(0..count); + let end = rows.end.min(count); + rows.start.min(end)..end +} + +/// What every piece, partition and pool of one scan of a [`PlanDataSource`] shares. +pub(super) struct ScanState { + pub(super) session: VortexSession, + source_dtype: DType, + files: Arc<[PlanSourceFile]>, + /// The dtype of the scan's output. + pub(super) dtype: DType, + projection: BoundExpression, + filter: Option, + row_range: Option>, + pub(super) selection: Selection, + pub(super) ordered: bool, + pub(super) limit: Option, + pub(super) split_concurrency: Option, +} + +impl ScanState { + /// The file at `ordinal` if it is open. + pub(super) fn opened(&self, ordinal: usize) -> Option<&PlanFile> { + match &self.files[ordinal] { + PlanSourceFile::Opened(file) => Some(file), + PlanSourceFile::Deferred { .. } => None, + } + } + + /// Opens the file at `ordinal`, or returns `None` when the file is skipped or its statistics + /// rule out the filter. An open file was checked against the filter when the scan began. + pub(super) async fn open_file(&self, ordinal: usize) -> VortexResult> { + let file = match &self.files[ordinal] { + PlanSourceFile::Opened(file) => return Ok(Some(file.clone())), + PlanSourceFile::Deferred { file, .. } => file.open().await?, + }; + let Some(file) = file else { + return Ok(None); + }; + if file.input.dtype != self.source_dtype { + vortex_bail!( + "file {ordinal} of the source has dtype {}, but the source has dtype {}", + file.input.dtype, + self.source_dtype + ); + } + if file.is_pruned(self.filter.as_ref())? { + return Ok(None); + } + Ok(Some(file)) + } + + /// The rows of `file` this scan reads: the request's row range, clamped to the file. + pub(super) fn file_rows(&self, file: &PlanFile) -> VortexResult> { + Ok(clamp_rows(self.row_range.clone(), file.rows()?)) + } + + /// A builder of this scan's `rows` of `file`. + pub(super) fn builder(&self, file: &PlanFile, rows: Range) -> ScanBuilder { + ScanBuilder::new(self.session.clone(), file.input.clone()) + .with_projection(self.projection.clone()) + .with_some_filter(self.filter.clone()) + .with_selection(self.selection.clone()) + .with_row_range(rows) + } +} + +/// Rows of one file that a scan reads. +#[derive(Clone, Debug)] +pub(super) struct Unit { + /// The file's ordinal in the source. + pub(super) file: usize, + /// The file's rows, or `None` for the request's rows of a file whose row count is not known + /// until it is open. + pub(super) rows: Option>, +} + +/// A scan of a [`PlanDataSource`], or a piece split from one. +struct PlanScan { + state: Arc, + /// The scan's units, in file and row order. + units: Vec, +} + +impl PlanScan { + /// The rows of `unit` the scan selects before filtering, or `None` when not known yet. + fn unit_rows(&self, unit: &Unit) -> Option { + let rows = unit.rows.as_ref()?; + Some(self.state.selection.row_count_in_range(rows)) + } + + /// The bytes of `unit`, in proportion to its share of its file's rows. + fn unit_bytes(&self, unit: &Unit) -> Option { + match &self.state.files[unit.file] { + PlanSourceFile::Opened(file) => { + let bytes = file.byte_size(); + match (&unit.rows, file.row_count) { + (Some(rows), Some(count)) if count > 0 => Some( + u64::try_from( + u128::from(bytes) * u128::from(rows.end - rows.start) + / u128::from(count), + ) + .unwrap_or(u64::MAX), + ), + _ => Some(bytes), + } + } + PlanSourceFile::Deferred { byte_size, .. } => *byte_size, + } + } +} + +impl DataSourceScan for PlanScan { + fn dtype(&self) -> &DType { + &self.state.dtype + } + + fn partition_count(&self) -> Precision { + Precision::exact(self.units.len()) + } + + fn partitions(self: Box) -> PartitionStream { + // An unordered scan's partitions share one budget; an ordered scan's each apply the limit + // locally, and the caller trims the concatenated result. + let shared = (!self.state.ordered) + .then(|| self.state.limit.map(RowLimit::new)) + .flatten(); + let state = self.state; + stream::iter(self.units.into_iter().map(move |unit| { + let limit = shared.clone().or_else(|| state.limit.map(RowLimit::new)); + Ok(Box::new(PlanPartition { + state: Arc::clone(&state), + unit, + limit, + }) as PartitionRef) + })) + .boxed() + } + + fn row_count(&self) -> Precision { + let Some(rows) = self + .units + .iter() + .map(|unit| self.unit_rows(unit)) + .sum::>() + else { + return Precision::Absent; + }; + let rows = self.state.limit.map_or(rows, |limit| rows.min(limit)); + if self.state.filter.is_some() { + Precision::inexact(rows) + } else { + Precision::exact(rows) + } + } + + fn byte_size(&self) -> Precision { + self.units + .iter() + .map(|unit| self.unit_bytes(unit)) + .sum::>() + .map_or(Precision::Absent, Precision::inexact) + } + + fn split(self: Box, n: NonZeroUsize) -> VortexResult> { + // A limit holds across the whole scan, which pieces read independently cannot share. + if self.state.limit.is_some() || n.get() == 1 { + return Ok(vec![self]); + } + let atoms = split_atoms(&self.units, n); + if atoms.len() <= 1 { + return Ok(vec![self]); + } + let known: Vec = atoms + .iter() + .filter_map(|unit| unit.rows.as_ref().map(|rows| rows.end - rows.start)) + .collect(); + // A file that is not open yet weighs as much as the average open unit. + let unknown = (known.iter().sum::() / known.len().max(1) as u64).max(1); + let weight = |unit: &Unit| { + unit.rows + .as_ref() + .map_or(unknown, |rows| rows.end - rows.start) + }; + let state = self.state; + Ok(group_contiguous(atoms, n, weight) + .into_iter() + .map(|atoms| { + Box::new(PlanScan { + state: Arc::clone(&state), + units: join_atoms(atoms), + }) as DataSourceScanRef + }) + .collect()) + } + + fn open(self: Box) -> VortexResult { + plan_pool::open(self.state, self.units) + } +} + +/// The pieces a split may not cut further: the scan's known rows on a grid of whole 8,192-row +/// blocks, coarse enough that each of `n` pieces gets about 64 of them, and each unit whose rows +/// are not known yet whole. +fn split_atoms(units: &[Unit], n: NonZeroUsize) -> Vec { + let block = ROW_BLOCK_SIZE as u64; + let known: u64 = units + .iter() + .filter_map(|unit| unit.rows.as_ref().map(|rows| rows.end - rows.start)) + .sum(); + let per_atom = known.div_ceil(n.get() as u64 * 64).div_ceil(block).max(1) * block; + let mut atoms = Vec::new(); + for unit in units { + let Some(rows) = &unit.rows else { + atoms.push(unit.clone()); + continue; + }; + let mut start = rows.start; + while start < rows.end { + let end = ((start / per_atom + 1) * per_atom).min(rows.end); + atoms.push(Unit { + file: unit.file, + rows: Some(start..end), + }); + start = end; + } + } + atoms +} + +/// Joins adjacent atoms of the same file back into one unit. +fn join_atoms(atoms: Vec) -> Vec { + let mut units: Vec = Vec::new(); + for atom in atoms { + if let Some(last) = units.last_mut() + && last.file == atom.file + && let (Some(rows), Some(next)) = (&mut last.rows, &atom.rows) + && rows.end == next.start + { + rows.end = next.end; + continue; + } + units.push(atom); + } + units +} + +/// One file's rows of a scan of a [`PlanDataSource`]. +struct PlanPartition { + state: Arc, + unit: Unit, + limit: Option, +} + +impl Partition for PlanPartition { + fn as_any(&self) -> &dyn Any { + self + } + + fn index(&self) -> usize { + self.unit.file + } + + fn row_count(&self) -> Precision { + let rows = match (&self.unit.rows, self.state.opened(self.unit.file)) { + (Some(rows), _) => rows.clone(), + (None, Some(file)) if file.row_count.is_some() => match self.state.file_rows(file) { + Ok(rows) => rows, + Err(_) => return Precision::Absent, + }, + _ => return Precision::Absent, + }; + let rows = self.state.selection.row_count_in_range(&rows); + let rows = self.state.limit.map_or(rows, |limit| rows.min(limit)); + if self.state.filter.is_some() { + Precision::inexact(rows) + } else { + Precision::exact(rows) + } + } + + fn byte_size(&self) -> Precision { + Precision::Absent + } + + fn execute(self: Box) -> VortexResult { + let PlanPartition { state, unit, limit } = *self; + let dtype = state.dtype.clone(); + let arrays = stream::once(async move { + let Some(file) = state.open_file(unit.file).await? else { + return Ok(stream::empty().boxed()); + }; + let rows = match unit.rows { + Some(rows) => rows, + None => state.file_rows(&file)?, + }; + if rows.is_empty() { + return Ok(stream::empty().boxed()); + } + let driver = ScanDriver::new(state.session.handle(), 1, state.ordered) + .with_max_in_flight(state.split_concurrency); + VortexResult::Ok(driver.run(state.builder(&file, rows))) + }) + .try_flatten() + .boxed(); + let arrays = match limit { + Some(limit) => trim_to_limit(arrays, limit), + None => arrays, + }; + Ok(ArrayStreamExt::boxed(ArrayStreamAdapter::new( + dtype, arrays, + ))) + } +} + +#[cfg(test)] +mod tests { + use std::num::NonZeroUsize; + + use rstest::rstest; + + use super::Unit; + use super::join_atoms; + use super::split_atoms; + + fn unit(file: usize, rows: std::ops::Range) -> Unit { + Unit { + file, + rows: Some(rows), + } + } + + #[rstest] + #[case::one_block(vec![unit(0, 0..100)], 4, 1)] + #[case::grid_aligned(vec![unit(0, 10..40_000)], 1, 5)] + fn atoms_lie_on_the_block_grid( + #[case] units: Vec, + #[case] n: usize, + #[case] expected: usize, + ) { + let n = NonZeroUsize::new(n).unwrap_or(NonZeroUsize::MIN); + let atoms = split_atoms(&units, n); + assert_eq!(atoms.len(), expected); + for atom in &atoms[1..] { + let start = atom.rows.as_ref().map_or(0, |rows| rows.start); + assert_eq!(start % 8192, 0); + } + let joined = join_atoms(atoms); + assert_eq!( + joined.iter().map(|u| u.rows.clone()).collect::>(), + units.iter().map(|u| u.rows.clone()).collect::>() + ); + } +} diff --git a/vortex-scan/src/source/plan_pool.rs b/vortex-scan/src/source/plan_pool.rs new file mode 100644 index 00000000000..c1c30c6a8d2 --- /dev/null +++ b/vortex-scan/src/source/plan_pool.rs @@ -0,0 +1,361 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! The work that the workers of an opened [`PlanDataSource`](super::PlanDataSource) scan share. +//! +//! This is the V1 layout pool's pattern (`vortex-layout/src/scan/pool.rs`) over the V2 executor. +//! A pool's units are the parts of its files, and the files not yet opened. Opening the scan +//! prepares each open file once, which plans without reading, and cuts its rows into parts: the +//! file's splits when it has them, else the scan's chunks. A worker takes parts and keeps up to +//! `split_concurrency` of them running on its own thread, each on a planning run of its own that +//! awaits only its reads: with a filter, the part's pruning plans first, continuing into the +//! chunks of the rows pruning kept; without, the chunks directly. A worker 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 parts 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. +//! +//! A limit is a [`RowLimit`] the workers take rows from as they yield them; workers stop taking +//! units once it is spent. + +use std::future; +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::BoxFuture; +use futures::stream; +use futures::stream::BoxStream; +use parking_lot::Mutex; +use vortex_array::ArrayRef; +use vortex_array::dtype::DType; +use vortex_array::stream::ArrayStreamAdapter; +use vortex_array::stream::ArrayStreamExt; +use vortex_array::stream::SendableArrayStream; +use vortex_error::VortexResult; +use vortex_io::request::IoService; + +use super::plan::PlanFile; +use super::plan::ScanState; +use super::plan::Unit; +use crate::execution::driver::compose; +use crate::execution::planning::driver::Progress; +use crate::execution::planning::driver::Run; +use crate::execution::planning::planner::WorkScope; +use crate::execution::scan_chunks; +use crate::pool::RowLimit; +use crate::pool::SPLITS_IN_FLIGHT_PER_WORKER; +use crate::pool::ScanPool; +use crate::pool::ScanPoolRef; +use crate::pool::trim_to_limit; +use crate::prepare::PreparedScan; + +/// One file's prepared scan, shared by the workers running its parts. +struct PreparedFile { + scan: Arc, + io: Arc, +} + +/// A part of a file: rows that one worker runs on one planning run. +type Part = (Arc, Range); + +/// A part's batches, in row order. +type PartFuture = BoxFuture<'static, VortexResult>>; + +/// A file of a pool, in file order. +enum PoolFile { + Prepared(Vec), + /// A file to open, by its ordinal in the source. + Deferred(usize), +} + +/// Opens a pool over the scan's `units`, preparing each of its open files. +pub(super) fn open(state: Arc, units: Vec) -> VortexResult { + let mut files = Vec::with_capacity(units.len()); + for unit in units { + files.push(match state.opened(unit.file) { + Some(file) => PoolFile::Prepared(prepare(&state, file, unit.rows)?), + None => PoolFile::Deferred(unit.file), + }); + } + let dtype = state.dtype.clone(); + let parts_in_flight = state + .split_concurrency + .map_or(SPLITS_IN_FLIGHT_PER_WORKER, NonZeroUsize::get); + let shared = Arc::new(Shared { + limit: state.limit.map(RowLimit::new), + state, + }); + if shared.state.ordered { + return Ok(Arc::new(OrderedPool { + dtype, + shared, + files: Mutex::new(Some(files)), + parts_in_flight, + })); + } + + let (sender, receiver) = async_channel::unbounded(); + for file in files { + match file { + PoolFile::Prepared(parts) => { + for part in parts { + send(&sender, Work::Part(part)); + } + } + PoolFile::Deferred(ordinal) => send(&sender, Work::Open(ordinal, sender.clone())), + } + } + Ok(Arc::new(UnorderedPool { + dtype, + shared, + receiver, + parts_in_flight, + })) +} + +/// Prepares the scan of `rows` of `file`, or of the request's rows when `None`, and cuts them +/// into parts, leaving out parts the selection selects nothing of. +fn prepare( + state: &ScanState, + file: &PlanFile, + rows: Option>, +) -> VortexResult> { + let rows = match rows { + Some(rows) => rows, + None => state.file_rows(file)?, + }; + if rows.is_empty() { + return Ok(Vec::new()); + } + let scan = Arc::new(state.builder(file, rows.clone()).prepare()?); + let ranges = match file.splits() { + Some(splits) => part_ranges(rows, splits), + None => scan_chunks(rows, scan.chunk_rows), + }; + let io = scan.io(); + let file = Arc::new(PreparedFile { scan, io }); + Ok(ranges + .into_iter() + .filter(|part| state.selection.row_count_in_range(part) > 0) + .map(|part| (Arc::clone(&file), part)) + .collect()) +} + +/// The ranges between adjacent `splits`, clipped to `rows`, leaving out empty ones. +fn part_ranges(rows: Range, splits: &[u64]) -> Vec> { + splits + .windows(2) + .map(|w| w[0].max(rows.start)..w[1].min(rows.end)) + .filter(|part| part.start < part.end) + .collect() +} + +/// Runs a part on a planning run of its own, on the polling thread, awaiting only its reads, and +/// returns its batches in row order. +fn run_part((file, rows): Part) -> PartFuture { + async move { + let mut run = Run::new(); + run.admit( + compose(&file.scan, rows.clone()), + WorkScope { + file_ordinal: 0, + rows, + }, + file.io.session(), + ); + let mut batches = Vec::new(); + loop { + match run.advance()? { + Progress::Batch(batch) => batches.push((batch.scope.rows.start, batch.array)), + Progress::Spawn(scope, child) => { + run.admit(child, scope, file.io.session()); + } + Progress::RootDone(_) if run.live_roots() > 0 => {} + Progress::RootDone(_) | Progress::Idle => break, + Progress::Waiting => future::poll_fn(|cx| run.poll_completion(cx)).await?, + } + } + // A part's chunks finish in whatever order their reads arrive. + batches.sort_by_key(|(start, _)| *start); + Ok(batches.into_iter().map(|(_, array)| array).collect()) + } + .boxed() +} + +/// What every worker of a pool shares. +struct Shared { + state: Arc, + limit: Option, +} + +impl Shared { + fn is_exhausted(&self) -> bool { + self.limit.as_ref().is_some_and(RowLimit::is_exhausted) + } + + /// Opens and prepares the deferred file at `ordinal` into its parts. + async fn open_file(self: Arc, ordinal: usize) -> VortexResult> { + match self.state.open_file(ordinal).await? { + Some(file) => prepare(&self.state, &file, None), + None => Ok(Vec::new()), + } + } + + /// A worker's output: the batches of its parts, trimmed to the limit. + fn output( + &self, + outputs: BoxStream<'static, VortexResult>>, + ) -> SendableArrayStream { + let arrays = outputs + .flat_map(|arrays| match arrays { + Ok(arrays) => stream::iter(arrays.into_iter().map(Ok)).left_stream(), + Err(err) => stream::once(future::ready(Err(err))).right_stream(), + }) + .boxed(); + let arrays = match &self.limit { + Some(limit) => trim_to_limit(arrays, limit.clone()), + None => arrays, + }; + ArrayStreamExt::boxed(ArrayStreamAdapter::new(self.state.dtype.clone(), arrays)) + } +} + +/// A unit of an unordered pool. +enum Work { + Part(Part), + /// A deferred file, and where to send its parts once it is open. The sender keeps the + /// channel open until the file's parts are in it. + Open(usize, 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, + parts_in_flight: usize, +} + +impl UnorderedPool { + fn run(shared: &Arc, work: Work) -> PartFuture { + match work { + Work::Part(part) => run_part(part), + Work::Open(ordinal, sender) => { + let shared = Arc::clone(shared); + async move { + for part in shared.open_file(ordinal).await? { + send(&sender, Work::Part(part)); + } + Ok(Vec::new()) + } + .boxed() + } + } + } +} + +impl ScanPool for UnorderedPool { + fn dtype(&self) -> &DType { + &self.dtype + } + + fn worker(self: Arc) -> SendableArrayStream { + let shared = Arc::clone(&self.shared); + let runner = Arc::clone(&shared); + let receiver = self.receiver.clone(); + let parts_in_flight = self.parts_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.is_exhausted())) + .map(move |work| UnorderedPool::run(&runner, work)) + .buffer_unordered(parts_in_flight) + .boxed(); + shared.output(outputs) + } +} + +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>>, + parts_in_flight: usize, +} + +impl ScanPool for OrderedPool { + fn dtype(&self) -> &DType { + &self.dtype + } + + fn worker(self: Arc) -> SendableArrayStream { + let Some(files) = self.files.lock().take() else { + return ArrayStreamExt::boxed(ArrayStreamAdapter::new( + self.dtype.clone(), + stream::empty(), + )); + }; + let opener = Arc::clone(&self.shared); + let shared = Arc::clone(&self.shared); + let outputs = stream::iter(files) + .then(move |file| match file { + PoolFile::Prepared(parts) => future::ready(Ok(parts)).boxed(), + PoolFile::Deferred(ordinal) => Arc::clone(&opener).open_file(ordinal).boxed(), + }) + .flat_map(|parts| match parts { + Ok(parts) => stream::iter(parts.into_iter().map(Ok)).left_stream(), + Err(err) => stream::once(future::ready(Err(err))).right_stream(), + }) + .take_while(move |_| future::ready(!shared.is_exhausted())) + .map(|part| match part { + Ok(part) => run_part(part), + Err(err) => future::ready(Err(err)).boxed(), + }) + .buffered(self.parts_in_flight) + .boxed(); + self.shared.output(outputs) + } +} + +#[cfg(test)] +mod tests { + use std::ops::Range; + + use rstest::rstest; + + use super::part_ranges; + + #[rstest] + #[case::whole(0..30, &[0, 10, 20, 30], vec![0..10, 10..20, 20..30])] + #[case::clipped(5..25, &[0, 10, 20, 30], vec![5..10, 10..20, 20..25])] + #[case::inside_one_split(12..18, &[0, 10, 20, 30], vec![12..18])] + #[case::empty(5..5, &[0, 10], vec![])] + fn parts_follow_splits( + #[case] rows: Range, + #[case] splits: &[u64], + #[case] expected: Vec>, + ) { + assert_eq!(part_ranges(rows, splits), expected); + } +} From 5a87d7fba8ba1ec3f064d430855b239e62f35d69 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Thu, 19 Nov 2026 16:20:07 -0500 Subject: [PATCH 06/14] Test V2 split and open over reads that pend and multi-chunk parts The plan source tests read files small and compressible enough that the footer read held every segment, so no part ever waited on a read, and every filtered scan was a single part. They now read larger files with a scrambled second column through a reader whose reads pend once, filter on that column, and cover parts cut on a file's splits. A worker's output also ends after its first error, as the V1 pool's does. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-file/src/plan_tests.rs | 179 +++++++++++++++++++++------- vortex-scan/src/source/plan_pool.rs | 10 +- 2 files changed, 142 insertions(+), 47 deletions(-) diff --git a/vortex-file/src/plan_tests.rs b/vortex-file/src/plan_tests.rs index 80473adc551..410f5ebae12 100644 --- a/vortex-file/src/plan_tests.rs +++ b/vortex-file/src/plan_tests.rs @@ -11,8 +11,10 @@ use std::sync::Arc; use std::sync::LazyLock; use async_trait::async_trait; +use futures::FutureExt; use futures::StreamExt; use futures::TryStreamExt; +use futures::future::BoxFuture; use futures::stream; use rstest::rstest; use vortex_array::ArrayRef; @@ -20,6 +22,7 @@ use vortex_array::IntoArray; use vortex_array::VortexSessionExecute; use vortex_array::arrays::PrimitiveArray; use vortex_array::arrays::StructArray; +use vortex_array::buffer::BufferHandle; use vortex_array::expr::Expression; use vortex_array::expr::get_item; use vortex_array::expr::gt; @@ -27,6 +30,7 @@ use vortex_array::expr::lit; use vortex_array::expr::root; use vortex_array::expr::stats::Precision; use vortex_array::stream::SendableArrayStream; +use vortex_buffer::Alignment; use vortex_buffer::Buffer; use vortex_buffer::ByteBuffer; use vortex_buffer::ByteBufferMut; @@ -43,9 +47,11 @@ use vortex_scan::DataSourceScanRef; use vortex_scan::PartitionRef; use vortex_scan::ScanRequest; use vortex_scan::pool::ScanPoolRef; +use vortex_scan::source::PlanDataSource; use vortex_session::VortexSession; use crate::OpenOptionsSessionExt; +use crate::VortexFile; use crate::WriteOptionsSessionExt; use crate::multi::MultiFileDataSource; use crate::multi::MultiFileSession; @@ -60,13 +66,35 @@ static SESSION: LazyLock = LazyLock::new(|| { session }); -/// The rows of a one-file source: several chunks of the scan's chunk grid. -const ROWS: u32 = 200_000; +/// The rows of a one-file source: several parts of the scan, filtered or not. +const ROWS: u32 = 600_000; -/// A file of one `n` column holding `values`, with file statistics. +/// The `m` value of row `n`: scrambled, so the column does not compress away and its segments +/// are read during the scan rather than with the footer. +fn scramble(n: u32) -> u32 { + n.wrapping_mul(2_654_435_761) +} + +const THRESHOLD: u32 = u32::MAX / 2; + +/// The filter of filtered cases, which keeps about half of the rows and, with the `n` +/// projection, makes the scan read two columns. +fn m_filter() -> Expression { + gt(get_item("m", root()), lit(THRESHOLD)) +} + +/// The values of `n` in `rows` that a scan returns, with [`m_filter`] when `filtered`. +fn expected(rows: Range, filtered: bool) -> Vec { + rows.filter(|&n| !filtered || scramble(n) > THRESHOLD) + .collect() +} + +/// A file of an `n` column holding `values` and an `m` column of their scrambles. async fn file_bytes(values: Range) -> VortexResult { + let m = Buffer::from_iter(values.clone().map(scramble)).into_array(); let array = - StructArray::from_fields(&[("n", Buffer::from_iter(values).into_array())])?.into_array(); + StructArray::from_fields(&[("n", Buffer::from_iter(values).into_array()), ("m", m)])? + .into_array(); let mut buf = ByteBufferMut::empty(); SESSION .write_options() @@ -75,11 +103,43 @@ async fn file_bytes(values: Range) -> VortexResult { Ok(buf.freeze()) } -async fn one_file() -> VortexResult { - let file = SESSION +/// A reader of in-memory bytes whose reads pend once before they complete, as storage reads do. +#[derive(Clone)] +struct YieldingRead(ByteBuffer); + +impl VortexReadAt for YieldingRead { + fn concurrency(&self) -> usize { + self.0.concurrency() + } + + fn size(&self) -> BoxFuture<'static, VortexResult> { + self.0.size() + } + + fn read_at( + &self, + offset: u64, + length: usize, + alignment: Alignment, + ) -> BoxFuture<'static, VortexResult> { + let read = self.0.read_at(offset, length, alignment); + async move { + tokio::task::yield_now().await; + read.await + } + .boxed() + } +} + +async fn open_one_file() -> VortexResult { + SESSION .open_options() - .open_buffer(file_bytes(0..ROWS).await?)?; - Ok(file.plan_data_source()) + .open_read(YieldingRead(file_bytes(0..ROWS).await?)) + .await +} + +async fn one_file() -> VortexResult { + Ok(open_one_file().await?.plan_data_source()) } fn n() -> Expression { @@ -168,22 +228,55 @@ async fn split_pieces_cover_all_rows_in_order(#[case] n: usize) -> VortexResult< /// The workers of an unordered pool together read every selected row once. #[rstest] -#[case::projection(None)] -#[case::filter(Some(gt(n(), lit(1_000u32))))] +#[case::projection(false)] +#[case::filter(true)] #[tokio::test(flavor = "multi_thread", worker_threads = 4)] #[cfg_attr(miri, ignore)] -async fn open_reads_every_row_once(#[case] filter: Option) -> VortexResult<()> { - let first = if filter.is_some() { 1_001 } else { 0 }; +async fn open_reads_every_row_once(#[case] filtered: bool) -> VortexResult<()> { let source = one_file().await?; let scan = source .scan(ScanRequest { - filter, + filter: filtered.then(m_filter), split_concurrency: NonZeroUsize::new(2), ..request(false) }) .await?; let workers = read_pool(scan.open()?, 4).await?; - assert_eq!(sorted(workers), (first..ROWS).collect::>()); + assert_eq!(sorted(workers), expected(0..ROWS, filtered)); + Ok(()) +} + +/// A file's splits are its parts, each of several chunks, which a worker returns in row order. +#[rstest] +#[case::unordered(false, false)] +#[case::unordered_filter(false, true)] +#[case::ordered(true, false)] +#[case::ordered_filter(true, true)] +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[cfg_attr(miri, ignore)] +async fn open_cuts_parts_on_file_splits( + #[case] ordered: bool, + #[case] filtered: bool, +) -> VortexResult<()> { + let file = open_one_file().await?; + let splits: Arc<[u64]> = Arc::from([0, 150_000, 400_000, u64::from(ROWS)]); + let source: DataSourceRef = Arc::new(PlanDataSource::from_file( + SESSION.clone(), + file.plan_file().with_splits(splits), + )); + let scan = source + .scan(ScanRequest { + filter: filtered.then(m_filter), + ..request(ordered) + }) + .await?; + let workers = read_pool(scan.open()?, 3).await?; + if ordered { + assert_eq!(workers[0], expected(0..ROWS, filtered)); + } else { + // Each worker returns its parts' rows in order within each part. + assert_eq!(sorted(workers), expected(0..ROWS, filtered)); + } Ok(()) } @@ -200,23 +293,20 @@ async fn ordered_open_reads_in_order_on_the_first_worker() -> VortexResult<()> { /// A pool's limit holds across its workers; an ordered pool returns the first rows. #[rstest] -#[case::unordered(false, None)] -#[case::unordered_filter(false, Some(gt(n(), lit(1_000u32))))] -#[case::ordered(true, None)] -#[case::ordered_filter(true, Some(gt(n(), lit(1_000u32))))] +#[case::unordered(false, false)] +#[case::unordered_filter(false, true)] +#[case::ordered(true, false)] +#[case::ordered_filter(true, true)] #[tokio::test(flavor = "multi_thread", worker_threads = 4)] #[cfg_attr(miri, ignore)] -async fn open_applies_the_limit( - #[case] ordered: bool, - #[case] filter: Option, -) -> VortexResult<()> { - const LIMIT: u32 = 70_000; - let first = if filter.is_some() { 1_001 } else { 0 }; +async fn open_applies_the_limit(#[case] ordered: bool, #[case] filtered: bool) -> VortexResult<()> { + const LIMIT: usize = 150_000; + let rows = expected(0..ROWS, filtered); let source = one_file().await?; let scan = source .scan(ScanRequest { - filter, - limit: Some(u64::from(LIMIT)), + filter: filtered.then(m_filter), + limit: Some(LIMIT as u64), ..request(ordered) }) .await?; @@ -228,12 +318,12 @@ async fn open_applies_the_limit( }; let workers = read_pool(scan.open()?, 3).await?; if ordered { - assert_eq!(workers[0], (first..first + LIMIT).collect::>()); + assert_eq!(workers[0], rows[..LIMIT]); } let all = sorted(workers); - assert_eq!(all.len(), LIMIT as usize); + assert_eq!(all.len(), LIMIT); all.windows(2).for_each(|w| assert!(w[0] < w[1])); - assert!(all.iter().all(|value| (first..ROWS).contains(value))); + assert!(all.iter().all(|value| rows.binary_search(value).is_ok())); Ok(()) } @@ -275,7 +365,7 @@ impl FileSystem for MemoryFileSystem { .file(path) .ok_or_else(|| vortex_err!("no file {path}"))? .clone(); - Ok(Arc::new(bytes)) + Ok(Arc::new(YieldingRead(bytes))) } async fn delete(&self, _path: &str) -> VortexResult<()> { @@ -284,7 +374,7 @@ impl FileSystem for MemoryFileSystem { } /// The values of the files of [`three_files`]. -const FILES: [Range; 3] = [0..70_000, 70_000..140_000, 140_000..210_000]; +const FILES: [Range; 3] = [0..200_000, 200_000..400_000, 400_000..600_000]; /// A V2 source over three files, of which all but the first are opened during scans. async fn three_files() -> VortexResult { @@ -301,24 +391,21 @@ async fn three_files() -> VortexResult { } /// Deferred files are opened by the workers that take them, and every row of every file is read -/// once. +/// once. A file the filter rules out by its statistics is skipped. #[rstest] -#[case::all(None, 0)] -#[case::filter(Some(gt(n(), lit(100_000u32))), 100_001)] +#[case::all(false)] +#[case::filter(true)] #[tokio::test(flavor = "multi_thread", worker_threads = 4)] #[cfg_attr(miri, ignore)] -async fn open_reads_deferred_files( - #[case] filter: Option, - #[case] first: u32, -) -> VortexResult<()> { +async fn open_reads_deferred_files(#[case] filtered: bool) -> VortexResult<()> { let source = three_files().await?; - assert_eq!(source.row_count(), Precision::inexact(210_000u64)); + assert_eq!(source.row_count(), Precision::inexact(u64::from(ROWS))); let request = ScanRequest { - filter, + filter: filtered.then(m_filter), ..request(false) }; let workers = read_pool(source.scan(request.clone()).await?.open()?, 4).await?; - assert_eq!(sorted(workers), (first..210_000).collect::>()); + assert_eq!(sorted(workers), expected(0..ROWS, filtered)); // Ordered, the files are read in order. let ordered = ScanRequest { @@ -326,7 +413,7 @@ async fn open_reads_deferred_files( ..request }; let workers = read_pool(source.scan(ordered).await?.open()?, 2).await?; - assert_eq!(workers[0], (first..210_000).collect::>()); + assert_eq!(workers[0], expected(0..ROWS, filtered)); Ok(()) } @@ -344,7 +431,7 @@ async fn split_keeps_deferred_files_whole() -> VortexResult<()> { assert!(!values.is_empty()); read.extend(values); } - assert_eq!(read, (0..210_000).collect::>()); + assert_eq!(read, expected(0..ROWS, false)); Ok(()) } @@ -355,12 +442,12 @@ async fn open_limits_across_deferred_files() -> VortexResult<()> { let source = three_files().await?; let scan = source .scan(ScanRequest { - limit: Some(100_000), + limit: Some(300_000), ..request(false) }) .await?; let all = sorted(read_pool(scan.open()?, 4).await?); - assert_eq!(all.len(), 100_000); + assert_eq!(all.len(), 300_000); all.windows(2).for_each(|w| assert!(w[0] < w[1])); Ok(()) } @@ -384,6 +471,6 @@ async fn partitions_are_files() -> VortexResult<()> { for partition in partitions { read.extend(values(partition.execute()?).await?); } - assert_eq!(read, (0..210_000).collect::>()); + assert_eq!(read, expected(0..ROWS, false)); Ok(()) } diff --git a/vortex-scan/src/source/plan_pool.rs b/vortex-scan/src/source/plan_pool.rs index c1c30c6a8d2..8fac76aad0b 100644 --- a/vortex-scan/src/source/plan_pool.rs +++ b/vortex-scan/src/source/plan_pool.rs @@ -209,12 +209,20 @@ impl Shared { } } - /// A worker's output: the batches of its parts, trimmed to the limit. + /// A worker's output: the batches of its parts, trimmed to the limit, ending after the first + /// error. fn output( &self, outputs: BoxStream<'static, VortexResult>>, ) -> SendableArrayStream { let arrays = outputs + .scan(false, |failed, output| { + if *failed { + return future::ready(None); + } + *failed = output.is_err(); + future::ready(Some(output)) + }) .flat_map(|arrays| match arrays { Ok(arrays) => stream::iter(arrays.into_iter().map(Ok)).left_stream(), Err(err) => stream::once(future::ready(Err(err))).right_stream(), From de0e5c23f82637b682026c046b0cbecb33589667 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Thu, 19 Nov 2026 18:00:01 -0500 Subject: [PATCH 07/14] Expand deferred plan children rather than open deferred files The Scan API sits between any host and any format, so the V2 source's pool should not be about Vortex files. A deferred child now expands into children, which may be deferred in turn, as a table format's manifest lists files; the pool queues the work of whatever a child expands into, and an ordered read expands each child in its place. PlanFile, DeferredPlanFile and PlanSourceFile become PlanChild, DeferredPlanChild and PlanSourceChild; a multi-file Vortex scan is one deferred child per file. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-file/src/file.rs | 12 +- vortex-file/src/multi/mod.rs | 23 +- vortex-file/src/plan_tests.rs | 134 ++++++++++- vortex-scan/src/source.rs | 6 +- vortex-scan/src/source/plan.rs | 343 ++++++++++++++++------------ vortex-scan/src/source/plan_pool.rs | 148 +++++++----- 6 files changed, 444 insertions(+), 222 deletions(-) diff --git a/vortex-file/src/file.rs b/vortex-file/src/file.rs index 99381f2711c..b6379c7c8d1 100644 --- a/vortex-file/src/file.rs +++ b/vortex-file/src/file.rs @@ -29,8 +29,8 @@ use vortex_layout::segments::UsageSegmentSource; use vortex_scan::DataSourceRef; use vortex_scan::prepare::ScanCache; use vortex_scan::prepare::SegmentLocation; +use vortex_scan::source::PlanChild; use vortex_scan::source::PlanDataSource; -use vortex_scan::source::PlanFile; use vortex_session::VortexSession; use vortex_utils::aliases::hash_map::HashMap; @@ -320,7 +320,7 @@ impl VortexFile { /// Create a [`DataSource`](vortex_scan::DataSource) from this file whose scans run on the /// planner-driven executor. /// - /// The source is a [`PlanDataSource`] over [`plan_file`](Self::plan_file): hosts read its + /// The source is a [`PlanDataSource`] over [`plan_file`](Self::plan_child): hosts read its /// scans through native `split` and `open`, or through one partition covering the requested /// rows, which runs it with [`ScanDriver`](crate::v2::ScanDriver) from /// [`Partition::execute`](vortex_scan::Partition::execute). Every scan of the source shares @@ -329,14 +329,14 @@ impl VortexFile { /// aggregates are available through the source statistics methods. Opening the source reads /// nothing and builds no layout reader. pub fn plan_data_source(&self) -> DataSourceRef { - let source = PlanDataSource::from_file(self.session.clone(), self.plan_file()); + let source = PlanDataSource::from_child(self.session.clone(), self.plan_child()); Arc::new(FileDataSource::new(source, self.file_stats().cloned())) } - /// This file as a file of a [`PlanDataSource`]: its V2 scan input, row count, and a pruner + /// This file as a child of a [`PlanDataSource`]: its V2 scan input, row count, and a pruner /// that skips scans whose filter the file-level statistics prove false. - pub fn plan_file(&self) -> PlanFile { - let file = PlanFile::new(self.scan_file().into()).with_row_count(self.row_count()); + pub fn plan_child(&self) -> PlanChild { + let file = PlanChild::new(self.scan_file().into()).with_row_count(self.row_count()); let Some(statistics) = self.file_stats().cloned() else { return file; }; diff --git a/vortex-file/src/multi/mod.rs b/vortex-file/src/multi/mod.rs index f00a7584e12..a7c58a2fc4e 100644 --- a/vortex-file/src/multi/mod.rs +++ b/vortex-file/src/multi/mod.rs @@ -27,10 +27,9 @@ use vortex_layout::scan::multi::LayoutReaderFactory; use vortex_layout::scan::multi::MultiLayoutDataSource; use vortex_scan::DataSource; use vortex_scan::DataSourceRef; -use vortex_scan::source::DeferredPlanFile; +use vortex_scan::source::DeferredPlanChild; use vortex_scan::source::PlanDataSource; -use vortex_scan::source::PlanFile; -use vortex_scan::source::PlanSourceFile; +use vortex_scan::source::PlanSourceChild; use vortex_session::VortexSession; use crate::OpenOptionsSessionExt; @@ -156,12 +155,12 @@ impl MultiFileDataSource { &all_files, )?)); } - let mut files = vec![PlanSourceFile::Opened(first_file.plan_file())]; + let mut files = vec![PlanSourceChild::Ready(first_file.plan_child())]; files.extend( all_files[1..] .iter() - .map(|(file, fs)| PlanSourceFile::Deferred { - file: Arc::new(DeferredVortexPlanFile { + .map(|(file, fs)| PlanSourceChild::Deferred { + child: Arc::new(DeferredVortexFile { fs: Arc::clone(fs), file: file.clone(), session: session.clone(), @@ -170,7 +169,7 @@ impl MultiFileDataSource { byte_size: file.size, }), ); - let source = PlanDataSource::from_files(session, first_file.dtype().clone(), files); + let source = PlanDataSource::from_children(session, first_file.dtype().clone(), files); debug!(file_count = all_files.len(), dtype = %source.dtype(), "built a plan MultiFileDataSource"); Ok(Arc::new(source)) } @@ -352,8 +351,8 @@ impl LayoutReaderFactory for VortexFileReaderFactory { } } -/// A [`DeferredPlanFile`] that opens a single Vortex file when a scan reaches it. -struct DeferredVortexPlanFile { +/// A [`DeferredPlanChild`] that opens a single Vortex file when a scan reaches it. +struct DeferredVortexFile { fs: FileSystemRef, file: FileListing, session: VortexSession, @@ -361,8 +360,8 @@ struct DeferredVortexPlanFile { } #[async_trait] -impl DeferredPlanFile for DeferredVortexPlanFile { - async fn open(&self) -> VortexResult> { +impl DeferredPlanChild for DeferredVortexFile { + async fn expand(&self) -> VortexResult> { let file = open_file( &self.fs, &self.file, @@ -370,7 +369,7 @@ impl DeferredPlanFile for DeferredVortexPlanFile { self.open_options_fn.as_ref(), ) .await?; - Ok(Some(file.plan_file())) + Ok(vec![PlanSourceChild::Ready(file.plan_child())]) } } diff --git a/vortex-file/src/plan_tests.rs b/vortex-file/src/plan_tests.rs index 410f5ebae12..c772dc29a93 100644 --- a/vortex-file/src/plan_tests.rs +++ b/vortex-file/src/plan_tests.rs @@ -42,12 +42,15 @@ use vortex_io::filesystem::FileSystem; use vortex_io::filesystem::FileSystemRef; use vortex_io::session::RuntimeSession; use vortex_layout::session::LayoutSession; +use vortex_scan::DataSource; use vortex_scan::DataSourceRef; use vortex_scan::DataSourceScanRef; use vortex_scan::PartitionRef; use vortex_scan::ScanRequest; use vortex_scan::pool::ScanPoolRef; +use vortex_scan::source::DeferredPlanChild; use vortex_scan::source::PlanDataSource; +use vortex_scan::source::PlanSourceChild; use vortex_session::VortexSession; use crate::OpenOptionsSessionExt; @@ -260,9 +263,9 @@ async fn open_cuts_parts_on_file_splits( ) -> VortexResult<()> { let file = open_one_file().await?; let splits: Arc<[u64]> = Arc::from([0, 150_000, 400_000, u64::from(ROWS)]); - let source: DataSourceRef = Arc::new(PlanDataSource::from_file( + let source: DataSourceRef = Arc::new(PlanDataSource::from_child( SESSION.clone(), - file.plan_file().with_splits(splits), + file.plan_child().with_splits(splits), )); let scan = source .scan(ScanRequest { @@ -474,3 +477,130 @@ async fn partitions_are_files() -> VortexResult<()> { assert_eq!(read, expected(0..ROWS, false)); Ok(()) } + +/// A deferred child that expands into `children`, as a manifest lists its files. +struct Manifest(Vec); + +#[async_trait] +impl DeferredPlanChild for Manifest { + async fn expand(&self) -> VortexResult> { + Ok(self.0.clone()) + } +} + +/// A deferred child that opens a file of `values` when expanded. +struct LazyFile(Range); + +#[async_trait] +impl DeferredPlanChild for LazyFile { + async fn expand(&self) -> VortexResult> { + let file = SESSION + .open_options() + .open_read(YieldingRead(file_bytes(self.0.clone()).await?)) + .await?; + Ok(vec![PlanSourceChild::Ready(file.plan_child())]) + } +} + +fn deferred(child: impl DeferredPlanChild) -> PlanSourceChild { + PlanSourceChild::Deferred { + child: Arc::new(child), + byte_size: None, + } +} + +/// A source whose second child is a manifest of deferred files: expanding a child queues its +/// children's work, however deep, and reads them in the manifest's place. +async fn nested() -> VortexResult { + let first = open_one_file_of(0..200_000).await?; + let dtype = first.dtype().clone(); + let manifest = Manifest(vec![ + deferred(LazyFile(200_000..400_000)), + deferred(Manifest(vec![deferred(LazyFile(400_000..600_000))])), + ]); + Ok(Arc::new(PlanDataSource::from_children( + SESSION.clone(), + dtype, + vec![ + PlanSourceChild::Ready(first.plan_child()), + deferred(manifest), + ], + ))) +} + +async fn open_one_file_of(values: Range) -> VortexResult { + SESSION + .open_options() + .open_read(YieldingRead(file_bytes(values).await?)) + .await +} + +#[rstest] +#[case::unordered(false, false)] +#[case::unordered_filter(false, true)] +#[case::ordered(true, false)] +#[case::ordered_filter(true, true)] +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[cfg_attr(miri, ignore)] +async fn open_expands_nested_children( + #[case] ordered: bool, + #[case] filtered: bool, +) -> VortexResult<()> { + let source = nested().await?; + let request = ScanRequest { + filter: filtered.then(m_filter), + ..request(ordered) + }; + let workers = read_pool(source.scan(request.clone()).await?.open()?, 4).await?; + if ordered { + assert_eq!(workers[0], expected(0..ROWS, filtered)); + } else { + assert_eq!(sorted(workers), expected(0..ROWS, filtered)); + } + + // The partitions are the source's two children; the manifest's runs all of its files. + let partitions: Vec = source + .scan(ScanRequest { + ordered: true, + ..request + }) + .await? + .partitions() + .try_collect() + .await?; + assert_eq!(partitions.len(), 2); + let mut read = Vec::new(); + for partition in partitions { + read.extend(values(partition.execute()?).await?); + } + assert_eq!(read, expected(0..ROWS, filtered)); + Ok(()) +} + +/// A child whose dtype is not the source's fails the scan that expands it. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[cfg_attr(miri, ignore)] +async fn expanding_a_child_of_another_dtype_fails() -> VortexResult<()> { + let first = open_one_file_of(0..10).await?; + let other = SESSION.open_options().open_buffer({ + let array = StructArray::from_fields(&[("n", Buffer::from_iter(0..10u64).into_array())])? + .into_array(); + let mut buf = ByteBufferMut::empty(); + SESSION + .write_options() + .write(&mut buf, array.to_array_stream()) + .await?; + buf.freeze() + })?; + let source = PlanDataSource::from_children( + SESSION.clone(), + first.dtype().clone(), + vec![ + PlanSourceChild::Ready(first.plan_child()), + deferred(Manifest(vec![PlanSourceChild::Ready(other.plan_child())])), + ], + ); + let scan = source.scan(request(false)).await?; + assert!(read_pool(scan.open()?, 2).await.is_err()); + Ok(()) +} diff --git a/vortex-scan/src/source.rs b/vortex-scan/src/source.rs index 52e9cedf616..c27666ae799 100644 --- a/vortex-scan/src/source.rs +++ b/vortex-scan/src/source.rs @@ -37,11 +37,11 @@ pub struct ScanInput { mod plan; mod plan_pool; -pub use plan::DeferredPlanFile; +pub use plan::DeferredPlanChild; pub use plan::FilePruner; +pub use plan::PlanChild; pub use plan::PlanDataSource; -pub use plan::PlanFile; -pub use plan::PlanSourceFile; +pub use plan::PlanSourceChild; #[cfg(test)] mod tests; diff --git a/vortex-scan/src/source/plan.rs b/vortex-scan/src/source/plan.rs index 0300ea0d870..0ecbbdd2a71 100644 --- a/vortex-scan/src/source/plan.rs +++ b/vortex-scan/src/source/plan.rs @@ -1,10 +1,17 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors -//! [`PlanDataSource`]: a [`DataSource`] over one or more [`ScanInput`]s, scanned by the -//! planner-driven executor. +//! [`PlanDataSource`]: a [`DataSource`] over plan children, scanned by the planner-driven +//! executor. +//! +//! Nothing here is about one format. A child is a [`ScanInput`], a plan over placed segments, +//! from a Vortex file, a Parquet file whose column chunks are segments, or any store that lowers +//! its data to plans; a deferred child is anything that expands into children, such as a file to +//! open, a table format's manifest, or a partition to list. use std::any::Any; +use std::collections::VecDeque; +use std::future; use std::num::NonZeroUsize; use std::ops::Range; use std::sync::Arc; @@ -13,6 +20,8 @@ use async_trait::async_trait; use futures::StreamExt; use futures::TryStreamExt; use futures::stream; +use futures::stream::BoxStream; +use vortex_array::ArrayRef; use vortex_array::dtype::DType; use vortex_array::dtype::FieldPath; use vortex_array::expr::BoundExpression; @@ -44,23 +53,23 @@ use crate::pool::trim_to_limit; use crate::prepare::ScanBuilder; use crate::selection::Selection; -/// Whether a file's own statistics prove a filter, bound to the file's dtype, false for every -/// row of the file. +/// Whether a child's own statistics, such as a file footer's, prove a filter, bound to the +/// child's dtype, false for every row of the child. pub type FilePruner = Arc VortexResult + Send + Sync>; -/// One open file of a [`PlanDataSource`]: its [`ScanInput`] and what the source knows of it -/// without reading payloads. +/// A child of a [`PlanDataSource`] whose plan is ready to prepare: its [`ScanInput`] and what the +/// source knows of it without reading payloads. #[derive(Clone)] -pub struct PlanFile { +pub struct PlanChild { input: ScanInput, row_count: Option, splits: Option>, pruner: Option, } -impl PlanFile { - /// A file scanning `input`. Without a cache, the input gets a fresh one that every scan of - /// the file shares. +impl PlanChild { + /// A child scanning `input`. Without a cache, the input gets a fresh one that every scan of + /// the child shares. pub fn new(mut input: ScanInput) -> Self { input.cache.get_or_insert_default(); Self { @@ -71,34 +80,34 @@ impl PlanFile { } } - /// Sets the file's exact row count. Without it, the source lowers the file's root plan to + /// Sets the child's exact row count. Without it, the source lowers the child's root plan to /// learn the count when a scan needs it. pub fn with_row_count(mut self, row_count: u64) -> Self { self.row_count = Some(row_count); self } - /// Sets the row boundaries that an opened scan cuts the file's work at, such as the file's - /// layout splits, ascending and covering the file's rows. Without them, the work is cut on + /// Sets the row boundaries that an opened scan cuts the child's work at, such as the child's + /// layout splits, ascending and covering the child's rows. Without them, the work is cut on /// the scan's chunk grid. pub fn with_splits(mut self, splits: Arc<[u64]>) -> Self { self.splits = Some(splits); self } - /// Sets how the file's statistics rule out a scan's filter, so a scan they rule out reads - /// nothing of the file. + /// Sets how the child's statistics rule out a scan's filter, so a scan they rule out reads + /// nothing of the child. pub fn with_pruner(mut self, pruner: FilePruner) -> Self { self.pruner = Some(pruner); self } - /// The input this file scans. + /// The input this child scans. pub fn input(&self) -> &ScanInput { &self.input } - /// The file's rows, from the row count when set, else from its root plan. + /// The child's rows, from the row count when set, else from its root plan. pub(super) fn rows(&self) -> VortexResult { match self.row_count { Some(rows) => Ok(rows), @@ -106,7 +115,7 @@ impl PlanFile { } } - /// The bytes of all of the file's segments. + /// The bytes of all of the child's segments. fn byte_size(&self) -> u64 { self.input .locations @@ -127,95 +136,107 @@ impl PlanFile { } } -/// Opens a file of a [`PlanDataSource`] when a scan reaches it. +/// A child of a [`PlanDataSource`] that a scan expands when it reaches it: a file to open, a +/// manifest entry to read, a table partition to list. +/// +/// Expanding is work like any other unit of an opened scan: the worker that takes the child +/// expands it and queues the work of what it expanded into, for any worker to take. #[async_trait] -pub trait DeferredPlanFile: 'static + Send + Sync { - /// Opens the file, or returns `None` when the scan should skip it. - async fn open(&self) -> VortexResult>; +pub trait DeferredPlanChild: 'static + Send + Sync { + /// The children this child stands for, in row order. They may be deferred in turn, as a + /// manifest's children are. An empty list skips the child. + async fn expand(&self) -> VortexResult>; } -/// A file of a [`PlanDataSource`]. +/// A child of a [`PlanDataSource`]. #[derive(Clone)] -pub enum PlanSourceFile { - /// A file that is already open. - Opened(PlanFile), - /// A file that a scan opens when it reaches it, so a source over many files reads only the - /// footers its scans need. +pub enum PlanSourceChild { + /// A child whose plan is ready to prepare. + Ready(PlanChild), + /// A child that a scan expands when it reaches it, so a source over many children reads only + /// the metadata its scans need. Deferred { - /// Opens the file. - file: Arc, - /// The file's size in bytes, if known. + /// Expands the child. + child: Arc, + /// The child's size in bytes, if known. byte_size: Option, }, } -/// A [`DataSource`] over the files of [`ScanInput`]s, scanned by the planner-driven executor. +/// A [`DataSource`] over plan children, scanned by the planner-driven executor. /// -/// This is the standard way to expose sources that can name their segments, whatever their -/// format: Vortex files, Parquet files whose column chunks are placed segments, or any store that -/// can lower its data to plans. Every scan of a file shares the file's [`ScanCache`], so scans -/// that overlap in time plan the file once. +/// This is the standard way to expose sources that can lower their data to plans over placed +/// segments, whatever their format. Every scan of a ready child shares the child's +/// [`ScanCache`], so scans that overlap in time plan it once. /// -/// A scan's request applies to each file: its row range and row selection are in the file's own -/// rows. A scan reads its files in order. +/// A scan's request applies to each child: its row range and row selection are in the child's +/// own rows. A scan reads its children in order, and a deferred child's children in its place. /// /// # Splitting and opening /// -/// [`split`](DataSourceScan::split) cuts a scan on the 8,192-row block grid of its files, which -/// every chunk boundary of the executor lies on, into contiguous pieces of about equal row -/// counts. It reads nothing; a file that is not open yet is one indivisible unit. +/// The work of a scan is plan work: chunks of a prepared plan, and the expansion of deferred +/// children, which queues the work of their children. A Vortex multi-file scan is one case. +/// +/// [`split`](DataSourceScan::split) cuts a scan into contiguous pieces of about equal row counts, +/// each a list of children and row ranges of them, on the 8,192-row block grid that every chunk +/// boundary of the executor lies on. It reads nothing; a deferred child is one indivisible unit. /// -/// [`open`](DataSourceScan::open) prepares each open file of the scan once and hands its parts, -/// the chunks of the scan, or the file's [splits](PlanFile::with_splits) when it has them, to -/// workers, which run several at a time on their own thread. A file that is not open yet is a -/// unit of work too: the worker that takes it opens and prepares it, and puts its parts back for +/// [`open`](DataSourceScan::open) prepares each ready child of the scan once and hands its parts, +/// the chunks of its plan, or the child's [splits](PlanChild::with_splits) when it has them, to +/// workers, which run several at a time on their own thread. Expanding a deferred child is a unit +/// of work too: the worker that takes it expands it and puts the work of its children back for /// any worker to take. See the pool's documentation in `plan_pool.rs`. /// /// # Partitions /// -/// A scan has one partition per file, whose [`index`](Partition::index) is the file's ordinal, -/// so a request's `partition_range` and `partition_selection` select files. A partition runs its -/// file's scan with a [`ScanDriver`] on the session's runtime. +/// A scan has one partition per child, whose [`index`](Partition::index) is the child's ordinal, +/// so a request's `partition_range` and `partition_selection` select children. A partition runs +/// its child, or each child a deferred one expands into, with a [`ScanDriver`] on the session's +/// runtime. /// /// [`ScanCache`]: crate::prepare::ScanCache #[derive(Clone)] pub struct PlanDataSource { session: VortexSession, dtype: DType, - files: Arc<[PlanSourceFile]>, + children: Arc<[PlanSourceChild]>, row_count: Precision, byte_size: Precision, } impl PlanDataSource { - /// A source scanning one open `input` with `session`. + /// A source scanning one ready `input` with `session`. pub fn new(session: VortexSession, input: ScanInput) -> Self { - Self::from_file(session, PlanFile::new(input)) + Self::from_child(session, PlanChild::new(input)) } - /// A source scanning one open `file` with `session`. - pub fn from_file(session: VortexSession, file: PlanFile) -> Self { - let dtype = file.input.dtype.clone(); - let row_count = file.row_count.map_or(Precision::Absent, Precision::exact); + /// A source scanning one ready `child` with `session`. + pub fn from_child(session: VortexSession, child: PlanChild) -> Self { + let dtype = child.input.dtype.clone(); + let row_count = child.row_count.map_or(Precision::Absent, Precision::exact); Self { session, dtype, - files: Arc::new([PlanSourceFile::Opened(file)]), + children: Arc::new([PlanSourceChild::Ready(child)]), row_count, byte_size: Precision::Absent, } } - /// A source scanning `files` in order with `session`. Every file must have `dtype`; a scan - /// that opens a file of another dtype fails. - pub fn from_files(session: VortexSession, dtype: DType, files: Vec) -> Self { + /// A source scanning `children` in order with `session`. Every child must have `dtype`; a + /// scan that expands a child of another dtype fails. + pub fn from_children( + session: VortexSession, + dtype: DType, + children: Vec, + ) -> Self { let mut rows = Some(0u64); let mut bytes = Some(0u64); let mut known_rows = 0; let mut known_files = 0; - for file in &files { + for file in &children { match file { - PlanSourceFile::Opened(file) => { + PlanSourceChild::Ready(file) => { match file.row_count { Some(count) => { known_rows += count; @@ -225,33 +246,33 @@ impl PlanDataSource { } bytes = bytes.map(|bytes| bytes + file.byte_size()); } - PlanSourceFile::Deferred { byte_size, .. } => { + PlanSourceChild::Deferred { byte_size, .. } => { rows = None; bytes = bytes.zip(*byte_size).map(|(bytes, size)| bytes + size); } } } - // Files not open yet are estimated at the average row count of the open ones. + // Deferred children are estimated at the average row count of the ready ones. let row_count = match rows { Some(rows) => Precision::exact(rows + known_rows), None if known_files > 0 => { - Precision::inexact(known_rows / known_files * files.len() as u64) + Precision::inexact(known_rows / known_files * children.len() as u64) } None => Precision::Absent, }; Self { session, dtype, - files: files.into(), + children: children.into(), row_count, byte_size: bytes.map_or(Precision::Absent, Precision::inexact), } } - /// Sets the exact row count of a one-file source, which scans and partitions report. + /// Sets the exact row count of a one-child source, which scans and partitions report. pub fn with_row_count(mut self, row_count: u64) -> Self { - if let [PlanSourceFile::Opened(file)] = &*self.files { - self.files = Arc::new([PlanSourceFile::Opened( + if let [PlanSourceChild::Ready(file)] = &*self.children { + self.children = Arc::new([PlanSourceChild::Ready( file.clone().with_row_count(row_count), )]); } @@ -265,9 +286,9 @@ impl PlanDataSource { self } - /// The files this source scans, in order. - pub fn files(&self) -> &[PlanSourceFile] { - &self.files + /// The children this source scans, in order. + pub fn children(&self) -> &[PlanSourceChild] { + &self.children } /// The session scans of this source run with. @@ -299,7 +320,7 @@ impl DataSource for PlanDataSource { let mut units = Vec::new(); let scans_rows = request.limit != Some(0) && !request.row_range.as_ref().is_some_and(Range::is_empty); - for (ordinal, file) in self.files.iter().enumerate().filter(|_| scans_rows) { + for (ordinal, file) in self.children.iter().enumerate().filter(|_| scans_rows) { let index = ordinal as u64; let selected = request .partition_range @@ -313,27 +334,27 @@ impl DataSource for PlanDataSource { continue; } let rows = match file { - PlanSourceFile::Opened(file) => { + PlanSourceChild::Ready(file) => { if file.is_pruned(filter.as_ref())? { continue; } file.row_count .map(|count| clamp_rows(request.row_range.clone(), count)) } - PlanSourceFile::Deferred { .. } => None, + PlanSourceChild::Deferred { .. } => None, }; if rows.as_ref().is_some_and(Range::is_empty) { continue; } units.push(Unit { - file: ordinal, + child: ordinal, rows, }); } let state = ScanState { session: self.session.clone(), source_dtype: self.dtype.clone(), - files: Arc::clone(&self.files), + children: Arc::clone(&self.children), dtype: projection.dtype().clone(), projection, filter, @@ -354,7 +375,7 @@ impl DataSource for PlanDataSource { } } -/// The request's `rows`, or all of them, clamped to a file of `count` rows. +/// The request's `rows`, or all of them, clamped to a child of `count` rows. fn clamp_rows(rows: Option>, count: u64) -> Range { let rows = rows.unwrap_or(0..count); let end = rows.end.min(count); @@ -365,7 +386,7 @@ fn clamp_rows(rows: Option>, count: u64) -> Range { pub(super) struct ScanState { pub(super) session: VortexSession, source_dtype: DType, - files: Arc<[PlanSourceFile]>, + children: Arc<[PlanSourceChild]>, /// The dtype of the scan's output. pub(super) dtype: DType, projection: BoundExpression, @@ -378,45 +399,91 @@ pub(super) struct ScanState { } impl ScanState { - /// The file at `ordinal` if it is open. - pub(super) fn opened(&self, ordinal: usize) -> Option<&PlanFile> { - match &self.files[ordinal] { - PlanSourceFile::Opened(file) => Some(file), - PlanSourceFile::Deferred { .. } => None, + /// The source's child at `ordinal`. + pub(super) fn child(&self, ordinal: usize) -> &PlanSourceChild { + &self.children[ordinal] + } + + /// The child at `ordinal` if it is ready. + pub(super) fn ready(&self, ordinal: usize) -> Option<&PlanChild> { + match &self.children[ordinal] { + PlanSourceChild::Ready(child) => Some(child), + PlanSourceChild::Deferred { .. } => None, } } - /// Opens the file at `ordinal`, or returns `None` when the file is skipped or its statistics - /// rule out the filter. An open file was checked against the filter when the scan began. - pub(super) async fn open_file(&self, ordinal: usize) -> VortexResult> { - let file = match &self.files[ordinal] { - PlanSourceFile::Opened(file) => return Ok(Some(file.clone())), - PlanSourceFile::Deferred { file, .. } => file.open().await?, - }; - let Some(file) = file else { - return Ok(None); - }; - if file.input.dtype != self.source_dtype { + /// Admits a child that expanding produced: `None` when its statistics rule out the filter, + /// and an error when its dtype is not the source's. + pub(super) fn admit(&self, child: PlanChild) -> VortexResult> { + if child.input.dtype != self.source_dtype { vortex_bail!( - "file {ordinal} of the source has dtype {}, but the source has dtype {}", - file.input.dtype, + "a child of the source has dtype {}, but the source has dtype {}", + child.input.dtype, self.source_dtype ); } - if file.is_pruned(self.filter.as_ref())? { + if child.is_pruned(self.filter.as_ref())? { return Ok(None); } - Ok(Some(file)) + Ok(Some(child)) + } + + /// Expands `children` depth-first, in order, into the admitted ready children they stand for, + /// expanding each deferred child only once the children before it are taken. + pub(super) fn expand_in_order( + self: &Arc, + children: Vec, + ) -> BoxStream<'static, VortexResult> { + let state = Arc::clone(self); + stream::try_unfold(VecDeque::from(children), move |mut queue| { + let state = Arc::clone(&state); + async move { + while let Some(child) = queue.pop_front() { + match child { + PlanSourceChild::Ready(child) => { + if let Some(child) = state.admit(child)? { + return Ok(Some((child, queue))); + } + } + PlanSourceChild::Deferred { child, .. } => { + for child in child.expand().await?.into_iter().rev() { + queue.push_front(child); + } + } + } + } + Ok(None) + } + }) + .boxed() + } + + /// Runs `rows` of `child`, or the request's rows of it when `None`, with a [`ScanDriver`]. + fn drive( + &self, + child: &PlanChild, + rows: Option>, + ) -> BoxStream<'static, VortexResult> { + let rows = match rows.map_or_else(|| self.child_rows(child), Ok) { + Ok(rows) => rows, + Err(err) => return stream::once(future::ready(Err(err))).boxed(), + }; + if rows.is_empty() { + return stream::empty().boxed(); + } + ScanDriver::new(self.session.handle(), 1, self.ordered) + .with_max_in_flight(self.split_concurrency) + .run(self.builder(child, rows)) } - /// The rows of `file` this scan reads: the request's row range, clamped to the file. - pub(super) fn file_rows(&self, file: &PlanFile) -> VortexResult> { - Ok(clamp_rows(self.row_range.clone(), file.rows()?)) + /// The rows of `child` this scan reads: the request's row range, clamped to the child. + pub(super) fn child_rows(&self, child: &PlanChild) -> VortexResult> { + Ok(clamp_rows(self.row_range.clone(), child.rows()?)) } - /// A builder of this scan's `rows` of `file`. - pub(super) fn builder(&self, file: &PlanFile, rows: Range) -> ScanBuilder { - ScanBuilder::new(self.session.clone(), file.input.clone()) + /// A builder of this scan's `rows` of `child`. + pub(super) fn builder(&self, child: &PlanChild, rows: Range) -> ScanBuilder { + ScanBuilder::new(self.session.clone(), child.input.clone()) .with_projection(self.projection.clone()) .with_some_filter(self.filter.clone()) .with_selection(self.selection.clone()) @@ -424,12 +491,12 @@ impl ScanState { } } -/// Rows of one file that a scan reads. +/// Rows of one child that a scan reads. #[derive(Clone, Debug)] pub(super) struct Unit { - /// The file's ordinal in the source. - pub(super) file: usize, - /// The file's rows, or `None` for the request's rows of a file whose row count is not known + /// The child's ordinal in the source. + pub(super) child: usize, + /// The child's rows, or `None` for the request's rows of a child whose row count is not known /// until it is open. pub(super) rows: Option>, } @@ -437,7 +504,7 @@ pub(super) struct Unit { /// A scan of a [`PlanDataSource`], or a piece split from one. struct PlanScan { state: Arc, - /// The scan's units, in file and row order. + /// The scan's units, in child and row order. units: Vec, } @@ -448,10 +515,10 @@ impl PlanScan { Some(self.state.selection.row_count_in_range(rows)) } - /// The bytes of `unit`, in proportion to its share of its file's rows. + /// The bytes of `unit`, in proportion to its share of its child's rows. fn unit_bytes(&self, unit: &Unit) -> Option { - match &self.state.files[unit.file] { - PlanSourceFile::Opened(file) => { + match &self.state.children[unit.child] { + PlanSourceChild::Ready(file) => { let bytes = file.byte_size(); match (&unit.rows, file.row_count) { (Some(rows), Some(count)) if count > 0 => Some( @@ -464,7 +531,7 @@ impl PlanScan { _ => Some(bytes), } } - PlanSourceFile::Deferred { byte_size, .. } => *byte_size, + PlanSourceChild::Deferred { byte_size, .. } => *byte_size, } } } @@ -534,7 +601,7 @@ impl DataSourceScan for PlanScan { .iter() .filter_map(|unit| unit.rows.as_ref().map(|rows| rows.end - rows.start)) .collect(); - // A file that is not open yet weighs as much as the average open unit. + // A deferred child weighs as much as the average ready unit. let unknown = (known.iter().sum::() / known.len().max(1) as u64).max(1); let weight = |unit: &Unit| { unit.rows @@ -578,7 +645,7 @@ fn split_atoms(units: &[Unit], n: NonZeroUsize) -> Vec { while start < rows.end { let end = ((start / per_atom + 1) * per_atom).min(rows.end); atoms.push(Unit { - file: unit.file, + child: unit.child, rows: Some(start..end), }); start = end; @@ -587,12 +654,12 @@ fn split_atoms(units: &[Unit], n: NonZeroUsize) -> Vec { atoms } -/// Joins adjacent atoms of the same file back into one unit. +/// Joins adjacent atoms of the same child back into one unit. fn join_atoms(atoms: Vec) -> Vec { let mut units: Vec = Vec::new(); for atom in atoms { if let Some(last) = units.last_mut() - && last.file == atom.file + && last.child == atom.child && let (Some(rows), Some(next)) = (&mut last.rows, &atom.rows) && rows.end == next.start { @@ -604,7 +671,7 @@ fn join_atoms(atoms: Vec) -> Vec { units } -/// One file's rows of a scan of a [`PlanDataSource`]. +/// One child's rows of a scan of a [`PlanDataSource`]. struct PlanPartition { state: Arc, unit: Unit, @@ -617,13 +684,13 @@ impl Partition for PlanPartition { } fn index(&self) -> usize { - self.unit.file + self.unit.child } fn row_count(&self) -> Precision { - let rows = match (&self.unit.rows, self.state.opened(self.unit.file)) { + let rows = match (&self.unit.rows, self.state.ready(self.unit.child)) { (Some(rows), _) => rows.clone(), - (None, Some(file)) if file.row_count.is_some() => match self.state.file_rows(file) { + (None, Some(file)) if file.row_count.is_some() => match self.state.child_rows(file) { Ok(rows) => rows, Err(_) => return Precision::Absent, }, @@ -645,23 +712,19 @@ impl Partition for PlanPartition { fn execute(self: Box) -> VortexResult { let PlanPartition { state, unit, limit } = *self; let dtype = state.dtype.clone(); - let arrays = stream::once(async move { - let Some(file) = state.open_file(unit.file).await? else { - return Ok(stream::empty().boxed()); - }; - let rows = match unit.rows { - Some(rows) => rows, - None => state.file_rows(&file)?, - }; - if rows.is_empty() { - return Ok(stream::empty().boxed()); - } - let driver = ScanDriver::new(state.session.handle(), 1, state.ordered) - .with_max_in_flight(state.split_concurrency); - VortexResult::Ok(driver.run(state.builder(&file, rows))) - }) - .try_flatten() - .boxed(); + // A ready child runs as it is; a deferred one runs each child it expands into, in order. + let children = match state.ready(unit.child) { + Some(child) => stream::iter([Ok((child.clone(), unit.rows))]).boxed(), + None => state + .expand_in_order(vec![state.child(unit.child).clone()]) + .map_ok(|child| (child, None)) + .boxed(), + }; + let driver = Arc::clone(&state); + let arrays = children + .map_ok(move |(child, rows)| driver.drive(&child, rows)) + .try_flatten() + .boxed(); let arrays = match limit { Some(limit) => trim_to_limit(arrays, limit), None => arrays, @@ -682,9 +745,9 @@ mod tests { use super::join_atoms; use super::split_atoms; - fn unit(file: usize, rows: std::ops::Range) -> Unit { + fn unit(child: usize, rows: std::ops::Range) -> Unit { Unit { - file, + child, rows: Some(rows), } } diff --git a/vortex-scan/src/source/plan_pool.rs b/vortex-scan/src/source/plan_pool.rs index 8fac76aad0b..c27e5f64927 100644 --- a/vortex-scan/src/source/plan_pool.rs +++ b/vortex-scan/src/source/plan_pool.rs @@ -3,20 +3,25 @@ //! The work that the workers of an opened [`PlanDataSource`](super::PlanDataSource) scan share. //! -//! This is the V1 layout pool's pattern (`vortex-layout/src/scan/pool.rs`) over the V2 executor. -//! A pool's units are the parts of its files, and the files not yet opened. Opening the scan -//! prepares each open file once, which plans without reading, and cuts its rows into parts: the -//! file's splits when it has them, else the scan's chunks. A worker takes parts and keeps up to -//! `split_concurrency` of them running on its own thread, each on a planning run of its own that -//! awaits only its reads: with a filter, the part's pruning plans first, continuing into the -//! chunks of the rows pruning kept; without, the chunks directly. A worker never spawns. Opening -//! a deferred file is a unit like any other. +//! This is the V1 layout pool's pattern (`vortex-layout/src/scan/pool.rs`) over the V2 executor, +//! with plan work for units. A pool's units are parts, rows of a prepared child's plan, and +//! deferred children not yet expanded. Opening the scan prepares each ready child once, which +//! plans without reading, and cuts its rows into parts: the child's splits when it has them, +//! else the scan's chunks. A worker takes parts and keeps up to `split_concurrency` of them +//! running on its own thread, each on a planning run of its own that awaits only its reads: with +//! a filter, the part's pruning plans first, continuing into the chunks of the rows pruning kept; +//! without, the chunks directly. A worker never spawns. //! -//! - An unordered pool hands units out through a channel. The worker that opens a deferred file -//! sends the file's parts 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. +//! Work creates work: expanding a deferred child, whether a file to open, a manifest entry or a +//! table partition, is a unit like any other, and queues the work of the children it expands +//! into, which may be deferred in turn. +//! +//! - An unordered pool hands units out through a channel. The worker that expands a deferred +//! child sends its children's units back into the channel, where any worker can take them. The +//! channel closes once every expansion has finished, which ends the workers. +//! - An ordered pool gives all of its units, in row order, to its first worker, which expands +//! each deferred child in its place; later workers get nothing. Parallel ordered reads cut the +//! scan with `split` first. //! //! A limit is a [`RowLimit`] the workers take rows from as they yield them; workers stop taking //! units once it is spent. @@ -42,7 +47,9 @@ use vortex_array::stream::SendableArrayStream; use vortex_error::VortexResult; use vortex_io::request::IoService; -use super::plan::PlanFile; +use super::plan::DeferredPlanChild; +use super::plan::PlanChild; +use super::plan::PlanSourceChild; use super::plan::ScanState; use super::plan::Unit; use crate::execution::driver::compose; @@ -57,32 +64,33 @@ use crate::pool::ScanPoolRef; use crate::pool::trim_to_limit; use crate::prepare::PreparedScan; -/// One file's prepared scan, shared by the workers running its parts. -struct PreparedFile { +/// One child's prepared scan, shared by the workers running its parts. +struct PreparedChild { scan: Arc, io: Arc, } -/// A part of a file: rows that one worker runs on one planning run. -type Part = (Arc, Range); +/// A part of a child: rows of its plan that one worker runs on one planning run. +type Part = (Arc, Range); /// A part's batches, in row order. type PartFuture = BoxFuture<'static, VortexResult>>; -/// A file of a pool, in file order. -enum PoolFile { +/// A child of a pool, in row order. +enum PoolChild { Prepared(Vec), - /// A file to open, by its ordinal in the source. - Deferred(usize), + Deferred(Arc), } -/// Opens a pool over the scan's `units`, preparing each of its open files. +/// Opens a pool over the scan's `units`, preparing each of its ready children. pub(super) fn open(state: Arc, units: Vec) -> VortexResult { - let mut files = Vec::with_capacity(units.len()); + let mut children = Vec::with_capacity(units.len()); for unit in units { - files.push(match state.opened(unit.file) { - Some(file) => PoolFile::Prepared(prepare(&state, file, unit.rows)?), - None => PoolFile::Deferred(unit.file), + children.push(match state.child(unit.child) { + PlanSourceChild::Ready(child) => { + PoolChild::Prepared(prepare(&state, child, unit.rows)?) + } + PlanSourceChild::Deferred { child, .. } => PoolChild::Deferred(Arc::clone(child)), }); } let dtype = state.dtype.clone(); @@ -97,20 +105,20 @@ pub(super) fn open(state: Arc, units: Vec) -> VortexResult { + for child in children { + match child { + PoolChild::Prepared(parts) => { for part in parts { send(&sender, Work::Part(part)); } } - PoolFile::Deferred(ordinal) => send(&sender, Work::Open(ordinal, sender.clone())), + PoolChild::Deferred(child) => send(&sender, Work::Expand(child, sender.clone())), } } Ok(Arc::new(UnorderedPool { @@ -121,31 +129,31 @@ pub(super) fn open(state: Arc, units: Vec) -> VortexResult>, ) -> VortexResult> { let rows = match rows { Some(rows) => rows, - None => state.file_rows(file)?, + None => state.child_rows(child)?, }; if rows.is_empty() { return Ok(Vec::new()); } - let scan = Arc::new(state.builder(file, rows.clone()).prepare()?); - let ranges = match file.splits() { + let scan = Arc::new(state.builder(child, rows.clone()).prepare()?); + let ranges = match child.splits() { Some(splits) => part_ranges(rows, splits), None => scan_chunks(rows, scan.chunk_rows), }; let io = scan.io(); - let file = Arc::new(PreparedFile { scan, io }); + let prepared = Arc::new(PreparedChild { scan, io }); Ok(ranges .into_iter() .filter(|part| state.selection.row_count_in_range(part) > 0) - .map(|part| (Arc::clone(&file), part)) + .map(|part| (Arc::clone(&prepared), part)) .collect()) } @@ -201,12 +209,17 @@ impl Shared { self.limit.as_ref().is_some_and(RowLimit::is_exhausted) } - /// Opens and prepares the deferred file at `ordinal` into its parts. - async fn open_file(self: Arc, ordinal: usize) -> VortexResult> { - match self.state.open_file(ordinal).await? { - Some(file) => prepare(&self.state, &file, None), - None => Ok(Vec::new()), - } + /// The parts of the children that `children` expand into, in row order, expanding each + /// deferred child only once the parts before it are taken. + fn parts_in_order( + self: &Arc, + children: Vec, + ) -> BoxStream<'static, VortexResult>> { + let shared = Arc::clone(self); + self.state + .expand_in_order(children) + .map(move |child| child.and_then(|child| prepare(&shared.state, &child, None))) + .boxed() } /// A worker's output: the batches of its parts, trimmed to the limit, ending after the first @@ -239,9 +252,9 @@ impl Shared { /// A unit of an unordered pool. enum Work { Part(Part), - /// A deferred file, and where to send its parts once it is open. The sender keeps the - /// channel open until the file's parts are in it. - Open(usize, Sender), + /// A deferred child, and where to send the units of its children once it is expanded. The + /// sender keeps the channel open until they are in it. + Expand(Arc, Sender), } fn send(sender: &Sender, work: Work) { @@ -261,11 +274,23 @@ impl UnorderedPool { fn run(shared: &Arc, work: Work) -> PartFuture { match work { Work::Part(part) => run_part(part), - Work::Open(ordinal, sender) => { + Work::Expand(child, sender) => { let shared = Arc::clone(shared); async move { - for part in shared.open_file(ordinal).await? { - send(&sender, Work::Part(part)); + for child in child.expand().await? { + match child { + PlanSourceChild::Ready(child) => { + let Some(child) = shared.state.admit(child)? else { + continue; + }; + for part in prepare(&shared.state, &child, None)? { + send(&sender, Work::Part(part)); + } + } + PlanSourceChild::Deferred { child, .. } => { + send(&sender, Work::Expand(child, sender.clone())); + } + } } Ok(Vec::new()) } @@ -307,8 +332,8 @@ impl Drop for UnorderedPool { struct OrderedPool { dtype: DType, shared: Arc, - /// The files, until the first worker takes them. - files: Mutex>>, + /// The children, until the first worker takes them. + children: Mutex>>, parts_in_flight: usize, } @@ -318,18 +343,23 @@ impl ScanPool for OrderedPool { } fn worker(self: Arc) -> SendableArrayStream { - let Some(files) = self.files.lock().take() else { + let Some(children) = self.children.lock().take() else { return ArrayStreamExt::boxed(ArrayStreamAdapter::new( self.dtype.clone(), stream::empty(), )); }; - let opener = Arc::clone(&self.shared); + let expander = Arc::clone(&self.shared); let shared = Arc::clone(&self.shared); - let outputs = stream::iter(files) - .then(move |file| match file { - PoolFile::Prepared(parts) => future::ready(Ok(parts)).boxed(), - PoolFile::Deferred(ordinal) => Arc::clone(&opener).open_file(ordinal).boxed(), + let outputs = stream::iter(children) + .flat_map(move |child| match child { + PoolChild::Prepared(parts) => stream::iter([Ok(parts)]).boxed(), + PoolChild::Deferred(child) => { + expander.parts_in_order(vec![PlanSourceChild::Deferred { + child, + byte_size: None, + }]) + } }) .flat_map(|parts| match parts { Ok(parts) => stream::iter(parts.into_iter().map(Ok)).left_stream(), From e468b71e2cb5bbc44725d4801ed5afd1572c7fb8 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Thu, 19 Nov 2026 15:54:11 -0500 Subject: [PATCH 08/14] 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 09/14] 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 e3e3a74a1efcee7e7751a32ad66d8d3ec26ba117 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Thu, 19 Nov 2026 18:47:42 -0500 Subject: [PATCH 10/14] Drive V1 pool tests on a runtime that runs spawned splits The base now spawns each split onto the session runtime, but the test session had no runtime handle. Give it a current-thread runtime with background workers, and stop assuming an unordered piece completes in order or that a spawned split is ready on the first poll. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-layout/src/scan/layout.rs | 4 +++- vortex-layout/src/scan/multi.rs | 3 ++- vortex-layout/src/scan/test.rs | 12 ++++++++++++ 3 files changed, 17 insertions(+), 2 deletions(-) diff --git a/vortex-layout/src/scan/layout.rs b/vortex-layout/src/scan/layout.rs index 32312aa8732..453621116ee 100644 --- a/vortex-layout/src/scan/layout.rs +++ b/vortex-layout/src/scan/layout.rs @@ -1051,7 +1051,9 @@ mod pool_tests { let mut values = Vec::new(); for piece in pieces { - let piece_values = read_with_one_worker(piece.open()?)?; + // The scan is unordered, so a piece's splits may finish in any order. + let mut piece_values = read_with_one_worker(piece.open()?)?; + piece_values.sort_unstable(); let first = *piece_values.first().expect("pieces are not empty"); let last = *piece_values.last().expect("pieces are not empty"); assert_eq!(first % 3, 0, "piece starts on a split boundary"); diff --git a/vortex-layout/src/scan/multi.rs b/vortex-layout/src/scan/multi.rs index be41497e0ad..5acaa3a9063 100644 --- a/vortex-layout/src/scan/multi.rs +++ b/vortex-layout/src/scan/multi.rs @@ -1296,7 +1296,8 @@ mod pool_tests { assert!(poll_worker(&mut waiter, &mut flagged).is_pending()); gates[0].release(); - let Poll::Ready(Some(first)) = poll_worker(&mut opener, &mut noop) else { + // The opener's split runs on the session runtime, so wait for it rather than polling once. + let Some(first) = futures::executor::block_on(opener.next()) else { panic!("the opener reads a split of the file it opened"); }; assert!(flag.0.load(Ordering::SeqCst), "the waiter is woken"); diff --git a/vortex-layout/src/scan/test.rs b/vortex-layout/src/scan/test.rs index 41c9ce19e1e..3e0b70465e6 100644 --- a/vortex-layout/src/scan/test.rs +++ b/vortex-layout/src/scan/test.rs @@ -23,6 +23,8 @@ use vortex_error::VortexResult; use vortex_error::vortex_err; use vortex_io::runtime::BlockingRuntime; use vortex_io::runtime::Handle; +use vortex_io::runtime::current::CurrentThreadRuntime; +use vortex_io::runtime::current::CurrentThreadWorkerPool; use vortex_io::runtime::single::SingleThreadRuntime; use vortex_io::session::RuntimeSession; use vortex_io::session::RuntimeSessionExt; @@ -38,10 +40,20 @@ use crate::session::LayoutSession; static SESSION: LazyLock = LazyLock::new(VortexSession::empty); +/// A runtime driven by background threads, so splits the pools spawn make progress while test +/// workers block on their streams with `futures::executor`. +static RUNTIME: LazyLock<(CurrentThreadRuntime, CurrentThreadWorkerPool)> = LazyLock::new(|| { + let runtime = CurrentThreadRuntime::new(); + let pool = runtime.new_pool(); + pool.set_workers(4); + (runtime, pool) +}); + pub fn new_session() -> VortexSession { VortexSession::empty() .with::() .with::() + .with_handle(RUNTIME.0.handle()) } pub fn session_with_handle(handle: Handle) -> VortexSession { From c6602d5268f732946c9fb1b176b51f7628de6aef Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Thu, 19 Nov 2026 18:56:08 -0500 Subject: [PATCH 11/14] Cut V2 pool parts on layout splits and prune dynamic filters first Match develop's V2 DuckDB scan: each child is prepared once and its root runs up front, spawning one part per layout split over the fields the scan reads. A dynamic filter prunes the child as a whole before its parts are cut, as queued work since it reads zone maps. PartPlanner moves into vortex-scan as part_root so hosts can share it. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-file/src/file.rs | 21 ++- vortex-file/src/plan_tests.rs | 71 ++++++++++ vortex-scan/src/execution/driver.rs | 8 +- vortex-scan/src/execution/mod.rs | 2 + vortex-scan/src/execution/parts.rs | 178 +++++++++++++++++++++++ vortex-scan/src/prepare.rs | 1 + vortex-scan/src/source.rs | 1 + vortex-scan/src/source/plan.rs | 43 ++++-- vortex-scan/src/source/plan_pool.rs | 210 +++++++++++++++++----------- 9 files changed, 440 insertions(+), 95 deletions(-) create mode 100644 vortex-scan/src/execution/parts.rs diff --git a/vortex-file/src/file.rs b/vortex-file/src/file.rs index b6379c7c8d1..1e584ec7bb7 100644 --- a/vortex-file/src/file.rs +++ b/vortex-file/src/file.rs @@ -14,6 +14,7 @@ use itertools::Itertools; use vortex_array::ArrayRef; use vortex_array::dtype::DType; use vortex_array::dtype::FieldMask; +use vortex_array::expr::BoundExpression; use vortex_array::expr::Expression; use vortex_buffer::ByteBuffer; use vortex_error::VortexResult; @@ -22,6 +23,7 @@ use vortex_layout::layouts::list::List; use vortex_layout::scan::layout::LayoutReaderDataSource; use vortex_layout::scan::metrics::ScanUsage; use vortex_layout::scan::scan_builder::ScanBuilder; +use vortex_layout::scan::scan_builder::referenced_field_masks; use vortex_layout::scan::split_by::SplitBy; use vortex_layout::scan::v2::ScanFile; use vortex_layout::segments::SegmentSource; @@ -335,8 +337,25 @@ impl VortexFile { /// This file as a child of a [`PlanDataSource`]: its V2 scan input, row count, and a pruner /// that skips scans whose filter the file-level statistics prove false. + /// + /// An opened scan of the child cuts its work on the file's layout splits over the fields it + /// reads, as a V1 scan of the same fields does. pub fn plan_child(&self) -> PlanChild { - let file = PlanChild::new(self.scan_file().into()).with_row_count(self.row_count()); + let splitter = { + let file = self.clone(); + Arc::new( + move |projection: &BoundExpression, filter: Option<&BoundExpression>| { + SplitBy::default().splits( + file.layout_reader()?.as_ref(), + &(0..file.row_count()), + &referenced_field_masks(projection, filter)?, + ) + }, + ) + }; + let file = PlanChild::new(self.scan_file().into()) + .with_row_count(self.row_count()) + .with_splitter(splitter); let Some(statistics) = self.file_stats().cloned() else { return file; }; diff --git a/vortex-file/src/plan_tests.rs b/vortex-file/src/plan_tests.rs index c772dc29a93..5c3803ae2f2 100644 --- a/vortex-file/src/plan_tests.rs +++ b/vortex-file/src/plan_tests.rs @@ -9,6 +9,8 @@ use std::num::NonZeroUsize; use std::ops::Range; use std::sync::Arc; use std::sync::LazyLock; +use std::sync::atomic::AtomicU32; +use std::sync::atomic::Ordering; use async_trait::async_trait; use futures::FutureExt; @@ -23,12 +25,17 @@ use vortex_array::VortexSessionExecute; use vortex_array::arrays::PrimitiveArray; use vortex_array::arrays::StructArray; use vortex_array::buffer::BufferHandle; +use vortex_array::dtype::DType; +use vortex_array::dtype::Nullability; +use vortex_array::dtype::PType; use vortex_array::expr::Expression; +use vortex_array::expr::dynamic; use vortex_array::expr::get_item; use vortex_array::expr::gt; use vortex_array::expr::lit; use vortex_array::expr::root; use vortex_array::expr::stats::Precision; +use vortex_array::scalar_fn::fns::operators::CompareOperator; use vortex_array::stream::SendableArrayStream; use vortex_buffer::Alignment; use vortex_buffer::Buffer; @@ -41,6 +48,7 @@ use vortex_io::filesystem::FileListing; use vortex_io::filesystem::FileSystem; use vortex_io::filesystem::FileSystemRef; use vortex_io::session::RuntimeSession; +use vortex_layout::scan::scan_builder::ScanBuilder; use vortex_layout::session::LayoutSession; use vortex_scan::DataSource; use vortex_scan::DataSourceRef; @@ -283,6 +291,69 @@ async fn open_cuts_parts_on_file_splits( Ok(()) } +/// A file's parts are its layout splits over the fields the scan reads, as a V1 scan of the same +/// fields cuts it: no batch crosses one. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[cfg_attr(miri, ignore)] +async fn open_cuts_parts_on_layout_splits() -> VortexResult<()> { + let file = open_one_file().await?; + let splits = ScanBuilder::new(SESSION.clone(), file.layout_reader()?) + .with_projection(n().bind(file.dtype())?) + .full_file_splits()?; + assert!(splits.len() > 2, "the file has several layout splits"); + + let scan = file.plan_data_source().scan(request(true)).await?; + let arrays: Vec = scan.open()?.worker().try_collect().await?; + let mut boundaries = vec![0u64]; + for array in &arrays { + let end = boundaries.last().copied().unwrap_or(0) + array.len() as u64; + boundaries.push(end); + } + for split in splits { + assert!( + boundaries.contains(&split), + "a batch crosses layout split {split}" + ); + } + Ok(()) +} + +/// A dynamic filter, such as a top-N's bound, prunes a file as a whole before its parts are cut, +/// as queued work rather than in `open`. The rows follow the bound as it stands when the workers +/// read, not as it stood when the scan was opened. +#[rstest] +#[case::unordered(false)] +#[case::ordered(true)] +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[cfg_attr(miri, ignore)] +async fn open_prunes_the_file_first_for_a_dynamic_filter( + #[case] ordered: bool, +) -> VortexResult<()> { + let bound = Arc::new(AtomicU32::new(0)); + let value = Arc::clone(&bound); + let filter = dynamic( + CompareOperator::Gt, + move || Some(value.load(Ordering::Relaxed).into()), + DType::Primitive(PType::U32, Nullability::NonNullable), + true, + n(), + ); + let scan = one_file() + .await? + .scan(ScanRequest { + filter: Some(filter), + ..request(ordered) + }) + .await?; + let pool = scan.open()?; + bound.store(ROWS - 10, Ordering::Relaxed); + assert_eq!( + sorted(read_pool(pool, 3).await?), + (ROWS - 9..ROWS).collect::>() + ); + Ok(()) +} + /// An ordered pool gives all of its rows, in order, to its first worker. #[tokio::test(flavor = "multi_thread", worker_threads = 4)] #[cfg_attr(miri, ignore)] diff --git a/vortex-scan/src/execution/driver.rs b/vortex-scan/src/execution/driver.rs index f30c75467fe..fd19cc9f485 100644 --- a/vortex-scan/src/execution/driver.rs +++ b/vortex-scan/src/execution/driver.rs @@ -13,7 +13,6 @@ use std::future; use std::num::NonZeroUsize; -use std::ops::Range; use std::sync::Arc; use std::task::Poll; @@ -121,7 +120,7 @@ impl ScanDriver { rows: scan.rows().clone(), }; let io = scan.io(); - let root = compose(&scan, scan.rows().clone()); + let root = compose(&scan); let (chunk_handle, chunk_io, chunk_map) = (self.handle.clone(), Arc::clone(&io), Arc::clone(&map_fn)); let batches = run_stream(self.handle, root, scope, io, map_fn, inline) @@ -158,9 +157,10 @@ impl ScanDriver { } } -/// The planners of a scan's `rows`, composed: with a filter, its pruning plans first over `rows`, +/// The planners of a scan, composed: with a filter, its pruning plans first over the whole scan, /// continuing into the chunks of the rows they keep; without, the chunks directly. -pub(crate) fn compose(scan: &Arc, rows: Range) -> Box { +fn compose(scan: &Arc) -> Box { + let rows = scan.rows().clone(); let chunks = { let scan = Arc::clone(scan); let rows = rows.clone(); diff --git a/vortex-scan/src/execution/mod.rs b/vortex-scan/src/execution/mod.rs index 6baffdda7bc..2bd2cd06a95 100644 --- a/vortex-scan/src/execution/mod.rs +++ b/vortex-scan/src/execution/mod.rs @@ -25,6 +25,7 @@ pub(crate) mod zone_map; mod adaptor; mod chunk; mod filter; +mod parts; mod projection; mod prune; mod selection; @@ -48,6 +49,7 @@ pub(crate) use self::chunk::rows_per_chunk; pub(crate) use self::chunk::scan_chunks; use self::filter::FilterPlanner; pub use self::filter::FilterPlans; +pub use self::parts::part_root; use self::projection::ProjectionPlanner; pub use self::prune::PruneNext; pub use self::prune::PrunePlanner; diff --git a/vortex-scan/src/execution/parts.rs b/vortex-scan/src/execution/parts.rs new file mode 100644 index 00000000000..441808df489 --- /dev/null +++ b/vortex-scan/src/execution/parts.rs @@ -0,0 +1,178 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Cutting a prepared scan into parts, the units its threads take. + +use std::ops::Range; +use std::sync::Arc; + +use vortex_error::VortexExpect; +use vortex_error::VortexResult; +use vortex_io::request::IoConsumer; +use vortex_io::request::IoRequestId; +use vortex_io::request::IoResult; +use vortex_mask::Mask; + +use super::ChunkPlanner; +use super::PreparedScan; +use super::PrunePlanner; +use super::scan_chunks; +use crate::planning::planner::Planner; +use crate::planning::planner::PlannerOutput; +use crate::planning::planner::State; +use crate::planning::planner::WorkScope; + +/// The root planner of a scan cut into parts: it spawns one planner per part, in row order. +/// +/// Parts are the ranges between `splits`, such as a file's layout splits, so that a layout chunk, +/// and the dictionary it carries, is read by one thread; without splits, they are the scan's +/// chunks. With a `dynamic` filter, such as the bound a top-N pushes down, the root first prunes +/// the scan as a whole, so a scan whose zones the filter rules out spawns nothing, reading zone +/// maps to do so. Otherwise the root only cuts parts and reads nothing. +pub fn part_root( + scan: &Arc, + splits: Option<&[u64]>, + dynamic: bool, +) -> Box { + let rows = scan.rows().clone(); + let parts = match splits { + Some(splits) => part_ranges(rows.clone(), splits), + None => scan_chunks(rows.clone(), scan.chunk_rows), + }; + let parts = { + let scan = Arc::clone(scan); + let first_row = rows.start; + move |kept: Option| -> Box { + Box::new(PartPlanner::new(scan, parts, first_row, kept)) + } + }; + if dynamic && scan.filter().is_some() { + Box::new(PrunePlanner::new(Arc::clone(scan), rows, Box::new(parts))) + } else { + parts(None) + } +} + +/// Spawns a planner per part of a scan's rows that the selection and scan-wide pruning left +/// something of, in row order. +/// +/// With a filter, each part prunes over its own rows before its chunks, on the thread that takes +/// it, like the per-split pruning of a V1 scan, so the pruning of a scan's parts runs in parallel. +/// A dynamic filter has tightened by the time a later part is taken, so pruning that part again +/// skips more than the scan-wide pruning did. +struct PartPlanner { + scan: Arc, + parts: std::vec::IntoIter>, + /// The first row of `kept`. + first_row: u64, + /// The rows scan-wide pruning kept, from `first_row`, or `None` when nothing was pruned. + kept: Option, +} + +impl PartPlanner { + fn new( + scan: Arc, + parts: Vec>, + first_row: u64, + kept: Option, + ) -> Self { + Self { + scan, + parts: parts.into_iter(), + first_row, + kept, + } + } + + /// The rows of `part` that scan-wide pruning kept, or `None` when nothing was pruned. + fn kept_in(&self, part: &Range) -> Option { + let kept = self.kept.as_ref()?; + let offset = + |row: u64| usize::try_from(row - self.first_row).vortex_expect("a part fits usize"); + Some(kept.slice(offset(part.start)..offset(part.end))) + } +} + +impl IoConsumer for PartPlanner { + fn set_io_result(&mut self, _request: IoRequestId, _result: IoResult) {} +} + +impl Planner for PartPlanner { + fn state(&self) -> State { + if self.parts.as_slice().is_empty() { + State::Done + } else { + State::NeedsCompute + } + } + + fn compute(&mut self) -> VortexResult { + while let Some(part) = self.parts.next() { + if self.scan.selection().row_count_in_range(&part) == 0 { + continue; + } + let kept = self.kept_in(&part); + if kept.as_ref().is_some_and(Mask::all_false) { + continue; + } + let chunks = { + let scan = Arc::clone(&self.scan); + let part = part.clone(); + move |again: Option| -> Box { + let kept = match (kept, again) { + (Some(kept), Some(again)) => Some(kept & &again), + (kept, again) => kept.or(again), + }; + let selection = scan.selection().clone(); + Box::new(ChunkPlanner::new(scan, part, selection, kept)) + } + }; + let planner: Box = if self.scan.filter().is_some() { + Box::new(PrunePlanner::new( + Arc::clone(&self.scan), + part.clone(), + Box::new(chunks), + )) + } else { + chunks(None) + }; + let scope = WorkScope { + file_ordinal: 0, + rows: part, + }; + return Ok(PlannerOutput::Spawn(scope, planner)); + } + Ok(PlannerOutput::Done) + } +} + +/// The ranges between adjacent `splits`, clipped to `rows`, leaving out empty ones. +fn part_ranges(rows: Range, splits: &[u64]) -> Vec> { + splits + .windows(2) + .map(|w| w[0].max(rows.start)..w[1].min(rows.end)) + .filter(|part| part.start < part.end) + .collect() +} + +#[cfg(test)] +mod tests { + use std::ops::Range; + + use rstest::rstest; + + use super::part_ranges; + + #[rstest] + #[case::whole(0..30, &[0, 10, 20, 30], vec![0..10, 10..20, 20..30])] + #[case::clipped(5..25, &[0, 10, 20, 30], vec![5..10, 10..20, 20..25])] + #[case::inside_one_split(12..18, &[0, 10, 20, 30], vec![12..18])] + #[case::empty(5..5, &[0, 10], vec![])] + fn parts_follow_splits( + #[case] rows: Range, + #[case] splits: &[u64], + #[case] expected: Vec>, + ) { + assert_eq!(part_ranges(rows, splits), expected); + } +} diff --git a/vortex-scan/src/prepare.rs b/vortex-scan/src/prepare.rs index 62de742a81b..625f614f7d9 100644 --- a/vortex-scan/src/prepare.rs +++ b/vortex-scan/src/prepare.rs @@ -24,6 +24,7 @@ pub use crate::execution::SegmentLocation; pub use crate::execution::cache::ScanCache; pub use crate::execution::cache::WeakScanCache; use crate::execution::io::segment_ranges; +pub use crate::execution::part_root; use crate::execution::rows_per_chunk; use crate::plan::optimize; use crate::plan::plan_row_idx_expression; diff --git a/vortex-scan/src/source.rs b/vortex-scan/src/source.rs index c27666ae799..d42871ec920 100644 --- a/vortex-scan/src/source.rs +++ b/vortex-scan/src/source.rs @@ -42,6 +42,7 @@ pub use plan::FilePruner; pub use plan::PlanChild; pub use plan::PlanDataSource; pub use plan::PlanSourceChild; +pub use plan::PlanSplitter; #[cfg(test)] mod tests; diff --git a/vortex-scan/src/source/plan.rs b/vortex-scan/src/source/plan.rs index cc2858884b8..335cba3f455 100644 --- a/vortex-scan/src/source/plan.rs +++ b/vortex-scan/src/source/plan.rs @@ -57,13 +57,19 @@ use crate::selection::Selection; /// child's dtype, false for every row of the child. pub type FilePruner = Arc VortexResult + Send + Sync>; +/// The row boundaries an opened scan cuts a child's work at, for the scan's projection and filter, +/// both bound to the child's dtype: ascending, covering the child's rows. A Vortex file gives its +/// layout splits over the fields the scan reads, as a V1 scan of the same fields cuts it. +pub type PlanSplitter = + Arc) -> VortexResult> + Send + Sync>; + /// A child of a [`PlanDataSource`] whose plan is ready to prepare: its [`ScanInput`] and what the /// source knows of it without reading payloads. #[derive(Clone)] pub struct PlanChild { input: ScanInput, row_count: Option, - splits: Option>, + splitter: Option, pruner: Option, } @@ -75,7 +81,7 @@ impl PlanChild { Self { input, row_count: None, - splits: None, + splitter: None, pruner: None, } } @@ -87,11 +93,17 @@ impl PlanChild { self } - /// Sets the row boundaries that an opened scan cuts the child's work at, such as the child's - /// layout splits, ascending and covering the child's rows. Without them, the work is cut on - /// the scan's chunk grid. - pub fn with_splits(mut self, splits: Arc<[u64]>) -> Self { - self.splits = Some(splits); + /// Sets fixed row boundaries that an opened scan cuts the child's work at, whatever it reads, + /// ascending and covering the child's rows. Without boundaries, the work is cut on the scan's + /// chunk grid. + pub fn with_splits(self, splits: Arc<[u64]>) -> Self { + self.with_splitter(Arc::new(move |_, _| Ok(splits.to_vec()))) + } + + /// Sets how an opened scan finds the row boundaries to cut the child's work at, from the + /// fields it reads. Without boundaries, the work is cut on the scan's chunk grid. + pub fn with_splitter(mut self, splitter: PlanSplitter) -> Self { + self.splitter = Some(splitter); self } @@ -124,8 +136,17 @@ impl PlanChild { .sum() } - pub(super) fn splits(&self) -> Option<&[u64]> { - self.splits.as_deref() + /// The boundaries an opened scan of `projection` and `filter` cuts the child's work at, if the + /// child has them. + pub(super) fn splits( + &self, + projection: &BoundExpression, + filter: Option<&BoundExpression>, + ) -> VortexResult>> { + self.splitter + .as_ref() + .map(|splitter| splitter(projection, filter)) + .transpose() } fn is_pruned(&self, filter: Option<&BoundExpression>) -> VortexResult { @@ -389,8 +410,8 @@ pub(super) struct ScanState { children: Arc<[PlanSourceChild]>, /// The dtype of the scan's output. pub(super) dtype: DType, - projection: BoundExpression, - filter: Option, + pub(super) projection: BoundExpression, + pub(super) filter: Option, row_range: Option>, pub(super) selection: Selection, pub(super) ordered: bool, diff --git a/vortex-scan/src/source/plan_pool.rs b/vortex-scan/src/source/plan_pool.rs index ff178d6e56f..e2dfb36ebb4 100644 --- a/vortex-scan/src/source/plan_pool.rs +++ b/vortex-scan/src/source/plan_pool.rs @@ -6,8 +6,11 @@ //! This is the V1 layout pool's pattern (`vortex-layout/src/scan/pool.rs`) over the V2 executor, //! with plan work for units. A pool's units are parts, rows of a prepared child's plan, and //! deferred children not yet expanded. Opening the scan prepares each ready child once, which -//! plans without reading, and cuts its rows into parts: the child's splits when it has them, -//! else the scan's chunks. A worker takes parts and keeps up to `split_concurrency` of them +//! plans without reading, and runs its root up front, which spawns its parts, as develop's V2 +//! DuckDB scan does: a part is the rows between two of the child's splits for the fields the scan +//! reads, such as a file's layout splits, else one of the scan's chunks. A root whose filter +//! changes while the scan runs, as a top-N's bound does, prunes the child as a whole before it +//! spawns parts; it reads zone maps to do so, so it runs as a unit of work instead. A worker takes parts and keeps up to `split_concurrency` of them //! in flight, each spawned onto the session's runtime when the worker takes it, as the V1 pool's //! splits are, and driven there on a planning run of its own that awaits only its reads: with a //! filter, the part's pruning plans first, continuing into the chunks of the rows pruning kept; @@ -42,10 +45,13 @@ use futures::stream::BoxStream; use parking_lot::Mutex; use vortex_array::ArrayRef; use vortex_array::dtype::DType; +use vortex_array::scalar_fn::fns::dynamic::DynamicExprUpdates; use vortex_array::stream::ArrayStreamAdapter; use vortex_array::stream::ArrayStreamExt; use vortex_array::stream::SendableArrayStream; +use vortex_error::VortexExpect; use vortex_error::VortexResult; +use vortex_error::vortex_bail; use vortex_io::request::IoService; use vortex_io::session::RuntimeSessionExt; @@ -54,17 +60,17 @@ use super::plan::PlanChild; use super::plan::PlanSourceChild; use super::plan::ScanState; use super::plan::Unit; -use crate::execution::driver::compose; use crate::execution::planning::driver::Progress; use crate::execution::planning::driver::Run; +use crate::execution::planning::planner::Planner; use crate::execution::planning::planner::WorkScope; -use crate::execution::scan_chunks; use crate::pool::RowLimit; use crate::pool::SPLITS_IN_FLIGHT_PER_WORKER; use crate::pool::ScanPool; use crate::pool::ScanPoolRef; use crate::pool::trim_to_limit; use crate::prepare::PreparedScan; +use crate::prepare::part_root; /// One child's prepared scan, shared by the workers running its parts. struct PreparedChild { @@ -72,26 +78,46 @@ struct PreparedChild { io: Arc, } -/// A part of a child: rows of its plan that one worker runs on one planning run. -type Part = (Arc, Range); +/// A part of a child: the planner its root spawned for some of its rows, which one worker runs on +/// a planning run of its own. +struct Part { + child: Arc, + scope: WorkScope, + planner: Box, +} /// A part's batches, in row order. type PartFuture = BoxFuture<'static, VortexResult>>; +/// The parts a child's root spawns, in row order. +type PartsFuture = BoxFuture<'static, VortexResult>>; + /// A child of a pool, in row order. enum PoolChild { - Prepared(Vec), + /// A child whose root has run, with the parts it spawned. + Parts(Vec), + /// A child whose root reads before it spawns parts: it prunes the child as a whole first. + Root(PartsFuture), Deferred(Arc), } +impl PoolChild { + /// The child's parts once its root has run. + fn into_parts(self) -> PartsFuture { + match self { + Self::Parts(parts) => future::ready(Ok(parts)).boxed(), + Self::Root(parts) => parts, + Self::Deferred(_) => unreachable!("a deferred child has no root"), + } + } +} + /// Opens a pool over the scan's `units`, preparing each of its ready children. pub(super) fn open(state: Arc, units: Vec) -> VortexResult { let mut children = Vec::with_capacity(units.len()); for unit in units { children.push(match state.child(unit.child) { - PlanSourceChild::Ready(child) => { - PoolChild::Prepared(prepare(&state, child, unit.rows)?) - } + PlanSourceChild::Ready(child) => prepare(&state, child, unit.rows)?, PlanSourceChild::Deferred { child, .. } => PoolChild::Deferred(Arc::clone(child)), }); } @@ -114,14 +140,7 @@ pub(super) fn open(state: Arc, units: Vec) -> VortexResult { - for part in parts { - send(&sender, Work::Part(part)); - } - } - PoolChild::Deferred(child) => send(&sender, Work::Expand(child, sender.clone())), - } + queue(&sender, child); } Ok(Arc::new(UnorderedPool { dtype, @@ -131,62 +150,92 @@ pub(super) fn open(state: Arc, units: Vec) -> VortexResult>, -) -> VortexResult> { +) -> VortexResult { let rows = match rows { Some(rows) => rows, None => state.child_rows(child)?, }; if rows.is_empty() { - return Ok(Vec::new()); + return Ok(PoolChild::Parts(Vec::new())); } - let scan = Arc::new(state.builder(child, rows.clone()).prepare()?); - let ranges = match child.splits() { - Some(splits) => part_ranges(rows, splits), - None => scan_chunks(rows, scan.chunk_rows), - }; + let splits = child.splits(&state.projection, state.filter.as_ref())?; + let scan = Arc::new(state.builder(child, rows).prepare()?); + let dynamic = state + .filter + .as_ref() + .is_some_and(|filter| DynamicExprUpdates::new(filter).is_some()); + let root = part_root(&scan, splits.as_deref(), dynamic); let io = scan.io(); - let prepared = Arc::new(PreparedChild { scan, io }); - Ok(ranges - .into_iter() - .filter(|part| state.selection.row_count_in_range(part) > 0) - .map(|part| (Arc::clone(&prepared), part)) - .collect()) -} - -/// The ranges between adjacent `splits`, clipped to `rows`, leaving out empty ones. -fn part_ranges(rows: Range, splits: &[u64]) -> Vec> { - splits - .windows(2) - .map(|w| w[0].max(rows.start)..w[1].min(rows.end)) - .filter(|part| part.start < part.end) - .collect() + let child = Arc::new(PreparedChild { scan, io }); + let parts = run_root(child, root); + if dynamic { + return Ok(PoolChild::Root(parts)); + } + let parts = parts + .now_or_never() + .vortex_expect("a root that only cuts parts reads nothing")?; + Ok(PoolChild::Parts(parts)) } -/// Runs a part on a planning run of its own, awaiting only its reads, and returns its batches in -/// row order. -fn run_part((file, rows): Part) -> PartFuture { +/// Runs a child's root on a planning run of its own, awaiting only its reads, and returns the +/// parts it spawns, in row order. +fn run_root(child: Arc, root: Box) -> PartsFuture { async move { let mut run = Run::new(); run.admit( - compose(&file.scan, rows.clone()), + root, WorkScope { file_ordinal: 0, - rows, + rows: child.scan.rows().clone(), }, - file.io.session(), + child.io.session(), ); + let mut parts = Vec::new(); + loop { + match run.advance()? { + Progress::Spawn(scope, planner) => parts.push(Part { + child: Arc::clone(&child), + scope, + planner, + }), + Progress::Batch(_) => vortex_bail!("a scan's root produced a batch"), + Progress::RootDone(_) if run.live_roots() > 0 => {} + Progress::RootDone(_) | Progress::Idle => break, + Progress::Waiting => future::poll_fn(|cx| run.poll_completion(cx)).await?, + } + } + Ok(parts) + } + .boxed() +} + +/// Runs a part on a planning run of its own, awaiting only its reads, and returns its batches in +/// row order. +fn run_part(part: Part) -> PartFuture { + async move { + let Part { + child, + scope, + planner, + } = part; + let mut run = Run::new(); + run.admit(planner, scope, child.io.session()); let mut batches = Vec::new(); loop { match run.advance()? { Progress::Batch(batch) => batches.push((batch.scope.rows.start, batch.array)), - Progress::Spawn(scope, child) => { - run.admit(child, scope, file.io.session()); + Progress::Spawn(scope, planner) => { + run.admit(planner, scope, child.io.session()); } Progress::RootDone(_) if run.live_roots() > 0 => {} Progress::RootDone(_) | Progress::Idle => break, @@ -226,7 +275,12 @@ impl Shared { let shared = Arc::clone(self); self.state .expand_in_order(children) - .map(move |child| child.and_then(|child| prepare(&shared.state, &child, None))) + .then( + move |child| match child.and_then(|child| prepare(&shared.state, &child, None)) { + Ok(child) => child.into_parts(), + Err(err) => future::ready(Err(err)).boxed(), + }, + ) .boxed() } @@ -260,8 +314,10 @@ impl Shared { /// A unit of an unordered pool. enum Work { Part(Part), - /// A deferred child, and where to send the units of its children once it is expanded. The - /// sender keeps the channel open until they are in it. + /// A child's root that reads before it spawns parts, and where to send the parts. The sender + /// keeps the channel open until they are in it. + Root(PartsFuture, Sender), + /// A deferred child, and where to send the units of its children once it is expanded. Expand(Arc, Sender), } @@ -270,6 +326,19 @@ fn send(sender: &Sender, work: Work) { drop(sender.try_send(work)); } +/// Queues the units of `child`. +fn queue(sender: &Sender, child: PoolChild) { + match child { + PoolChild::Parts(parts) => { + for part in parts { + send(sender, Work::Part(part)); + } + } + PoolChild::Root(parts) => send(sender, Work::Root(parts, sender.clone())), + PoolChild::Deferred(child) => send(sender, Work::Expand(child, sender.clone())), + } +} + /// A pool whose workers share its units through a channel. struct UnorderedPool { dtype: DType, @@ -282,6 +351,13 @@ impl UnorderedPool { fn run(shared: &Arc, work: Work) -> PartFuture { match work { Work::Part(part) => shared.spawn_part(part), + Work::Root(parts, sender) => async move { + for part in parts.await? { + send(&sender, Work::Part(part)); + } + Ok(Vec::new()) + } + .boxed(), Work::Expand(child, sender) => { let shared = Arc::clone(shared); async move { @@ -291,9 +367,7 @@ impl UnorderedPool { let Some(child) = shared.state.admit(child)? else { continue; }; - for part in prepare(&shared.state, &child, None)? { - send(&sender, Work::Part(part)); - } + queue(&sender, prepare(&shared.state, &child, None)?); } PlanSourceChild::Deferred { child, .. } => { send(&sender, Work::Expand(child, sender.clone())); @@ -362,13 +436,13 @@ impl ScanPool for OrderedPool { let shared = Arc::clone(&self.shared); let outputs = stream::iter(children) .flat_map(move |child| match child { - PoolChild::Prepared(parts) => stream::iter([Ok(parts)]).boxed(), PoolChild::Deferred(child) => { expander.parts_in_order(vec![PlanSourceChild::Deferred { child, byte_size: None, }]) } + child => stream::once(child.into_parts()).boxed(), }) .flat_map(|parts| match parts { Ok(parts) => stream::iter(parts.into_iter().map(Ok)).left_stream(), @@ -384,25 +458,3 @@ impl ScanPool for OrderedPool { self.shared.output(outputs) } } - -#[cfg(test)] -mod tests { - use std::ops::Range; - - use rstest::rstest; - - use super::part_ranges; - - #[rstest] - #[case::whole(0..30, &[0, 10, 20, 30], vec![0..10, 10..20, 20..30])] - #[case::clipped(5..25, &[0, 10, 20, 30], vec![5..10, 10..20, 20..25])] - #[case::inside_one_split(12..18, &[0, 10, 20, 30], vec![12..18])] - #[case::empty(5..5, &[0, 10], vec![])] - fn parts_follow_splits( - #[case] rows: Range, - #[case] splits: &[u64], - #[case] expected: Vec>, - ) { - assert_eq!(part_ranges(rows, splits), expected); - } -} From fb19d835fed17767f08d6e91867d19a3e02badf6 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 11:00:49 -0500 Subject: [PATCH 12/14] Bind a request once per (expression, dtype) in each session Requests stay unbound, as vortex#11654 settled: each source binds them against its own dtype in scan(). An engine that opens a plan source per file, as DuckDB does, therefore bound and optimized the same projection and filter once per file, where the V2 DuckDB path bound them once per query. A small per-session cache keyed by expression and dtype restores binding once per (expression, dtype). Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-scan/src/source.rs | 1 + vortex-scan/src/source/bind_cache.rs | 172 +++++++++++++++++++++++++++ vortex-scan/src/source/plan.rs | 5 +- 3 files changed, 176 insertions(+), 2 deletions(-) create mode 100644 vortex-scan/src/source/bind_cache.rs diff --git a/vortex-scan/src/source.rs b/vortex-scan/src/source.rs index d42871ec920..7988ac2b72f 100644 --- a/vortex-scan/src/source.rs +++ b/vortex-scan/src/source.rs @@ -34,6 +34,7 @@ pub struct ScanInput { pub cache: Option, } +mod bind_cache; mod plan; mod plan_pool; diff --git a/vortex-scan/src/source/bind_cache.rs b/vortex-scan/src/source/bind_cache.rs new file mode 100644 index 00000000000..8e297c73bcc --- /dev/null +++ b/vortex-scan/src/source/bind_cache.rs @@ -0,0 +1,172 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Bound request expressions, shared by the sources of one session. + +use std::any::Any; +use std::collections::VecDeque; +use std::fmt; +use std::sync::Arc; + +use parking_lot::Mutex; +use vortex_array::dtype::DType; +use vortex_array::expr::BoundExpression; +use vortex_array::expr::Expression; +use vortex_error::VortexResult; +use vortex_session::SessionExt; +use vortex_session::SessionVar; +use vortex_session::VortexSession; + +/// How many bound expressions a session keeps. +/// +/// Each scan of a source looks up two entries, its projection and its filter, so 32 entries hold +/// the expressions of about 16 queries scanning at once against one dtype each, or fewer queries +/// over tables whose files differ in dtype. A miss costs only the bind the cache saves, so the +/// bound need not be tight; it keeps each lookup a short scan and the session's memory small. +const ENTRIES: usize = 32; + +/// The expressions recently bound against a dtype and optimized, most recently used last. One +/// cache lives on each [`VortexSession`], shared by every source scanned in it. +/// +/// Requests stay unbound so that every source binds them against its own dtype. Binding and +/// optimizing a wide projection is real CPU, which an engine opening a source per file would +/// otherwise pay once per file rather than once per query. With this cache, each (expression, +/// dtype) pair binds once. +/// +/// A lookup hashes nothing: it compares the request against each entry. Expression children and +/// struct fields sit behind [`Arc`]s whose equality first compares pointers, so the clones of one +/// request an engine sends to each file compare in a few pointer checks, and files whose dtypes +/// share their fields, as files opened from one cached footer do, compare likewise. Distinct but +/// equal dtypes compare field by field, which is still a fraction of the bind that walks the same +/// fields and builds a tree. +/// +/// Dynamic expressions compare by identity, so an entry is only found again for the same +/// dynamic value, never for an equal-looking one of another query. +#[derive(Clone, Default)] +pub(super) struct BindCache(Arc>>); + +struct Entry { + dtype: DType, + expr: Expression, + bound: BoundExpression, +} + +impl BindCache { + /// `expr` bound against `dtype` and optimized, from an earlier scan of the session where one + /// bound it already. + pub(super) fn bind( + session: &VortexSession, + expr: &Expression, + dtype: &DType, + ) -> VortexResult { + let cache = BindCache::clone(&session.get::()); + if let Some(bound) = cache.find(expr, dtype) { + return Ok(bound); + } + let bound = expr.bind(dtype)?.optimize_recursive()?; + let mut entries = cache.0.lock(); + if entries.len() == ENTRIES { + entries.pop_front(); + } + entries.push_back(Entry { + dtype: dtype.clone(), + expr: expr.clone(), + bound: bound.clone(), + }); + Ok(bound) + } + + fn find(&self, expr: &Expression, dtype: &DType) -> Option { + let mut entries = self.0.lock(); + let index = entries + .iter() + .rposition(|entry| entry.expr == *expr && entry.dtype == *dtype)?; + // Keep entries in use at the back, so the least recently used is evicted first. + let entry = entries.remove(index)?; + let bound = entry.bound.clone(); + entries.push_back(entry); + Some(bound) + } +} + +impl fmt::Debug for BindCache { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("BindCache") + .field("entries", &self.0.lock().len()) + .finish() + } +} + +impl SessionVar for BindCache { + fn as_any(&self) -> &dyn Any { + self + } + + fn as_any_mut(&mut self) -> &mut dyn Any { + self + } +} + +#[cfg(test)] +mod tests { + use vortex_array::dtype::DType; + use vortex_array::dtype::Nullability; + use vortex_array::dtype::PType; + use vortex_array::expr::Expression; + use vortex_array::expr::get_item; + use vortex_array::expr::gt; + use vortex_array::expr::lit; + use vortex_array::expr::root; + use vortex_error::VortexResult; + use vortex_session::SessionExt; + use vortex_session::VortexSession; + + use super::BindCache; + + fn ints() -> Expression { + get_item("ints", root()) + } + + fn table(ints: PType) -> DType { + DType::struct_( + [("ints", DType::Primitive(ints, Nullability::NonNullable))], + Nullability::NonNullable, + ) + } + + fn entries(session: &VortexSession) -> usize { + session.get::().0.lock().len() + } + + #[test] + fn files_sharing_a_dtype_bind_once() -> VortexResult<()> { + let session = VortexSession::empty(); + let filter = gt(ints(), lit(5i32)); + let first = BindCache::bind(&session, &filter, &table(PType::I32))?; + let second = BindCache::bind(&session, &filter, &table(PType::I32))?; + assert_eq!(first, second); + assert_eq!( + first, + filter.bind(&table(PType::I32))?.optimize_recursive()? + ); + assert_eq!(entries(&session), 1); + Ok(()) + } + + #[test] + fn another_dtype_binds_again() -> VortexResult<()> { + let session = VortexSession::empty(); + let narrow = BindCache::bind(&session, &ints(), &table(PType::I32))?; + let wide = BindCache::bind(&session, &ints(), &table(PType::I64))?; + assert_eq!( + narrow.dtype(), + &DType::Primitive(PType::I32, Nullability::NonNullable) + ); + assert_eq!( + wide.dtype(), + &DType::Primitive(PType::I64, Nullability::NonNullable) + ); + assert_eq!(entries(&session), 2); + Ok(()) + } +} diff --git a/vortex-scan/src/source/plan.rs b/vortex-scan/src/source/plan.rs index f9039a388ae..7c613ef3748 100644 --- a/vortex-scan/src/source/plan.rs +++ b/vortex-scan/src/source/plan.rs @@ -36,6 +36,7 @@ use vortex_io::session::RuntimeSessionExt; use vortex_session::VortexSession; use super::ScanInput; +use super::bind_cache::BindCache; use super::plan_pool; use crate::DataSource; use crate::DataSourceScan; @@ -333,10 +334,10 @@ impl DataSource for PlanDataSource { } async fn scan(&self, request: ScanRequest) -> VortexResult { - let projection = request.projection.bind(&self.dtype)?.optimize_recursive()?; + let projection = BindCache::bind(&self.session, &request.projection, &self.dtype)?; let filter = request .filter - .map(|filter| filter.bind(&self.dtype)?.optimize_recursive()) + .map(|filter| BindCache::bind(&self.session, &filter, &self.dtype)) .transpose()?; let mut units = Vec::new(); let scans_rows = From bdc7a3397c978e331520d097bd54200b6f32040f Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 12:54:56 -0500 Subject: [PATCH 13/14] Run DataFusion's Scan API tables on the V2 scan With `--scan-api true --scan-v1 false`, datafusion-bench registers a `VortexTable` over `MultiFileDataSource::build_plan`, so the datasource integration can run the V2 scan. The orchestrator now accepts datafusion datasource-v2 targets, and every-scan coverage runs them. Folds in #11626. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- .../bench_orchestrator/ci_matrix/catalog.py | 6 +++- .../bench_orchestrator/config.py | 9 +----- bench-orchestrator/tests/test_config.py | 2 +- bench-orchestrator/tests/test_matrix.py | 10 +++++-- benchmarks/datafusion-bench/src/main.rs | 28 +++++++++++-------- 5 files changed, 30 insertions(+), 25 deletions(-) diff --git a/bench-orchestrator/bench_orchestrator/ci_matrix/catalog.py b/bench-orchestrator/bench_orchestrator/ci_matrix/catalog.py index e905cd85c91..a28b2a373c8 100644 --- a/bench-orchestrator/bench_orchestrator/ci_matrix/catalog.py +++ b/bench-orchestrator/bench_orchestrator/ci_matrix/catalog.py @@ -70,7 +70,7 @@ # Vortex targets name an integration (`file`, `datasource`) and a scan engine (`v1`, `v2`); see # `BenchmarkTarget`. Declared targets run the file integration on the suite's default engine. # `ScanCoverage.ALL` adds every other valid combination for the `vortex` format: DataFusion file-v1 and -# datasource-v1 beside file-v2, and DuckDB file-v1 beside file-v2, on V2 suites. Each combination runs +# datasource-v2 and datasource-v1 beside file-v2, and DuckDB file-v1 beside file-v2, on V2 suites. Each combination runs # as a matrix entry, and so a machine, of its own, so covering them all adds machines, not wall time. @@ -108,6 +108,10 @@ def with_all_scans(coverage: Coverage) -> Coverage: BenchmarkTarget(Engine.DATAFUSION, Format.VORTEX, Integration.FILE, ScanEngine.V1), "DataFusion, Vortex, file v1", ), + ( + BenchmarkTarget(Engine.DATAFUSION, Format.VORTEX, Integration.DATASOURCE, ScanEngine.V2), + "DataFusion, Vortex, datasource v2", + ), ( BenchmarkTarget(Engine.DATAFUSION, Format.VORTEX, Integration.DATASOURCE, ScanEngine.V1), "DataFusion, Vortex, datasource v1", diff --git a/bench-orchestrator/bench_orchestrator/config.py b/bench-orchestrator/bench_orchestrator/config.py index 7be6cff9e29..38a4ce09e10 100644 --- a/bench-orchestrator/bench_orchestrator/config.py +++ b/bench-orchestrator/bench_orchestrator/config.py @@ -132,9 +132,7 @@ class Benchmark(Enum): SUPPORTED_SCANS: dict[Engine, dict[Integration, frozenset[ScanEngine]]] = { Engine.DATAFUSION: { Integration.FILE: frozenset({ScanEngine.V1, ScanEngine.V2}), - # `VortexTable` reaches only V1: `MultiFileDataSource` opens `LayoutReader`s. V2 needs the V2 - # scan behind `split`/`open` (#11626). - Integration.DATASOURCE: frozenset({ScanEngine.V1}), + Integration.DATASOURCE: frozenset({ScanEngine.V1, ScanEngine.V2}), }, Engine.DUCKDB: { Integration.FILE: frozenset({ScanEngine.V1, ScanEngine.V2}), @@ -168,11 +166,6 @@ def scan_support_error(engine: Engine, integration: Integration, scan: ScanEngin return "duckdb has no DataSource table function yet, so it has no datasource targets" return f"{engine.value} has no {integration.value} integration" if scan is not None and scan not in integrations[integration]: - if engine is Engine.DATAFUSION and integration is Integration.DATASOURCE and scan is ScanEngine.V2: - return ( - "datafusion datasource targets run only the v1 scan: MultiFileDataSource opens " - "LayoutReaders, and v2 needs the V2 scan behind split/open (#11626)" - ) return f"{engine.value} {integration.value} targets cannot run the {scan.value} scan" return None diff --git a/bench-orchestrator/tests/test_config.py b/bench-orchestrator/tests/test_config.py index f73b8bffaf7..68fa7c33094 100644 --- a/bench-orchestrator/tests/test_config.py +++ b/bench-orchestrator/tests/test_config.py @@ -202,9 +202,9 @@ def test_parse_targets_json_rejects_unknown_axes() -> None: (Engine.DATAFUSION, Integration.FILE, ScanEngine.V1, None), (Engine.DATAFUSION, Integration.FILE, ScanEngine.V2, None), (Engine.DATAFUSION, Integration.DATASOURCE, ScanEngine.V1, None), + (Engine.DATAFUSION, Integration.DATASOURCE, ScanEngine.V2, None), (Engine.DUCKDB, Integration.FILE, ScanEngine.V1, None), (Engine.DUCKDB, Integration.FILE, ScanEngine.V2, None), - (Engine.DATAFUSION, Integration.DATASOURCE, ScanEngine.V2, "datasource targets run only the v1 scan"), (Engine.DUCKDB, Integration.DATASOURCE, ScanEngine.V1, "duckdb has no DataSource table function yet"), (Engine.DUCKDB, Integration.DATASOURCE, ScanEngine.V2, "duckdb has no DataSource table function yet"), ], diff --git a/bench-orchestrator/tests/test_matrix.py b/bench-orchestrator/tests/test_matrix.py index 67abe1b8812..a96f0a487c2 100644 --- a/bench-orchestrator/tests/test_matrix.py +++ b/bench-orchestrator/tests/test_matrix.py @@ -75,6 +75,7 @@ "duckdb-parquet", "duckdb-vortex", "datafusion-vortex-file-v1", + "datafusion-vortex-datasource-v2", "datafusion-vortex-datasource-v1", "duckdb-vortex-file-v1", ) @@ -83,7 +84,7 @@ "tpch-nested-s3", ), } -SCAN_SUFFIXES = ("datafusion-file-v1", "datafusion-datasource-v1", "duckdb-file-v1") +SCAN_SUFFIXES = ("datafusion-file-v1", "datafusion-datasource-v2", "datafusion-datasource-v1", "duckdb-file-v1") def _entries(preset: str) -> list[dict[str, object]]: @@ -121,6 +122,7 @@ def _group_targets(preset: str) -> dict[str, set[tuple[str, str]]]: ("datafusion", "parquet"), ("datafusion", "vortex [file, v2]"), ("datafusion", "vortex [file, v1]"), + ("datafusion", "vortex [datasource, v2]"), ("datafusion", "vortex [datasource, v1]"), ("duckdb", "parquet"), ("duckdb", "vortex [file, v2]"), @@ -197,11 +199,11 @@ def test_tpcds_sf100_runs_one_target_per_job() -> None: entry for entry in _entries("nightly") if str(entry["id"]).startswith("tpcds-") and "-100-" in str(entry["id"]) ] - assert len(nightly) == 14 + assert len(nightly) == 16 assert all(len(_targets(entry)) == 1 for entry in nightly) assert {target for entry in nightly for target in _targets(entry)} == ALL_SCANS s3_keys = [entry["remote_key"] for entry in nightly if "remote_key" in entry] - assert len(s3_keys) == len(set(s3_keys)) == 7 + assert len(s3_keys) == len(set(s3_keys)) == 8 def test_nightly_runs_every_scan() -> None: @@ -251,6 +253,8 @@ def test_nightly_runs_every_valid_scan() -> None: ) if not benchmark_id.startswith("tpch-nested"): expected |= {(engine, "vortex [file, v2]") for engine in engines} + if "datafusion" in engines: + expected.add(("datafusion", "vortex [datasource, v2]")) assert scans == expected, benchmark_id diff --git a/benchmarks/datafusion-bench/src/main.rs b/benchmarks/datafusion-bench/src/main.rs index d5d6d328513..9b140a6ed86 100644 --- a/benchmarks/datafusion-bench/src/main.rs +++ b/benchmarks/datafusion-bench/src/main.rs @@ -30,7 +30,6 @@ use vortex::file::multi::MultiFileDataSource; use vortex::io::filesystem::FileSystemRef; use vortex::io::object_store::ObjectStoreFileSystem; use vortex::io::session::RuntimeSessionExt; -use vortex::scan::DataSource as _; use vortex::scan::DataSourceRef; use vortex_arrow::ArrowSessionExt; use vortex_bench::Benchmark; @@ -125,8 +124,7 @@ struct Args { scan_v1: bool, /// Register Vortex tables through the Scan API (`VortexTable` over a `MultiFileDataSource`) - /// instead of a listing table, whatever `--scan-v1` says. `MultiFileDataSource` runs the V1 - /// scan. + /// instead of a listing table. `--scan-v1` still picks the scan the tables run on. #[arg(long, default_value_t = false, action = clap::ArgAction::Set)] scan_api: bool, @@ -268,7 +266,7 @@ async fn register_benchmark_tables( scan_api: bool, ) -> anyhow::Result<()> { if scan_api && matches!(format, Format::OnDiskVortex | Format::VortexCompact) { - register_v2_tables(session, benchmark, format).await + register_scan_api_tables(session, benchmark, format, scan_v2).await } else { let benchmark_base = benchmark.data_url().join(&format!("{}/", format.name()))?; let file_format = format_to_df_format(format, scan_v2)?; @@ -304,11 +302,16 @@ async fn register_benchmark_tables( } } -/// Register tables using the Scan API path: a `VortexTable` over a `MultiFileDataSource`. -async fn register_v2_tables( +/// Register tables through the Scan API: a `VortexTable` over a `MultiFileDataSource`. +/// +/// With `scan_v2`, the table scans its files on the planner-driven scan through +/// [`MultiFileDataSource::build_plan`], whose files open as the scan reaches them. Otherwise it +/// scans them on layout readers through [`MultiFileDataSource::build`]. +async fn register_scan_api_tables( session: &SessionContext, benchmark: &B, format: Format, + scan_v2: bool, ) -> anyhow::Result<()> { let benchmark_base = benchmark.data_url().join(&format!("{}/", format.name()))?; @@ -332,13 +335,14 @@ async fn register_v2_tables( None => format!("*.{}", format.ext()), }; - let multi_ds = MultiFileDataSource::new(SESSION.clone()) - .with_glob(glob_pattern, Some(fs)) - .build() - .await?; + let builder = MultiFileDataSource::new(SESSION.clone()).with_glob(glob_pattern, Some(fs)); + let data_source: DataSourceRef = if scan_v2 { + builder.build_plan().await? + } else { + Arc::new(builder.build().await?) + }; - let arrow_schema = Arc::new(SESSION.arrow().to_arrow_schema(multi_ds.dtype())?); - let data_source: DataSourceRef = Arc::new(multi_ds); + let arrow_schema = Arc::new(SESSION.arrow().to_arrow_schema(data_source.dtype())?); let table_provider = Arc::new(VortexTable::new(data_source, SESSION.clone(), arrow_schema)); session.register_table(table.name, table_provider)?; From 5b0d39e6a40ba17763b5759360e1d9237338eeef Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 13:14:07 -0500 Subject: [PATCH 14/14] Run opened V2 plan scans on V2's own driver An opened PlanDataSource scan now runs as develop's V2 DuckDB scan does: each worker owns a planning run, driven on the task that polls it, fed with parts from a queue every worker shares, yielding batches as they are produced. Parts are no longer spawned onto the runtime with several in flight per worker; a worker runs one part at a time unless the request's split_concurrency says otherwise, as a DuckDB thread runs one chunk at a time. Ordered pools run their parts in row order on the first worker's run. SPLITS_IN_FLIGHT_PER_WORKER only fed the old pool, so it goes. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-scan/src/pool.rs | 5 - vortex-scan/src/source/plan.rs | 12 +- vortex-scan/src/source/plan_pool.rs | 477 ++++++++++++++++------------ 3 files changed, 281 insertions(+), 213 deletions(-) diff --git a/vortex-scan/src/pool.rs b/vortex-scan/src/pool.rs index 004817d8c4f..147c8264c9a 100644 --- a/vortex-scan/src/pool.rs +++ b/vortex-scan/src/pool.rs @@ -64,11 +64,6 @@ pub trait ScanPool: 'static + Send + Sync { } } -/// The most units each worker of a pool keeps in flight when the request's -/// [`split_concurrency`](crate::ScanRequest::split_concurrency) does not say. Stands in for the -/// scan engine's memory budget. -pub const SPLITS_IN_FLIGHT_PER_WORKER: usize = 4; - /// A cloneable row budget shared by all work that can contribute rows to one scan. /// /// Filterless scans can reserve each unit's selected rows before decoding it, so rows past the diff --git a/vortex-scan/src/source/plan.rs b/vortex-scan/src/source/plan.rs index 7c613ef3748..5bd7cb5a691 100644 --- a/vortex-scan/src/source/plan.rs +++ b/vortex-scan/src/source/plan.rs @@ -203,11 +203,13 @@ pub enum PlanSourceChild { /// each a list of children and row ranges of them, on the 8,192-row block grid that every chunk /// boundary of the executor lies on. It reads nothing; a deferred child is one indivisible unit. /// -/// [`open`](DataSourceScan::open) prepares each ready child of the scan once and hands its parts, -/// the chunks of its plan, or the child's [splits](PlanChild::with_splits) when it has them, to -/// workers, which keep several in flight on the session's runtime. Expanding a deferred child is a unit -/// of work too: the worker that takes it expands it and puts the work of its children back for -/// any worker to take. See the pool's documentation in `plan_pool.rs`. +/// [`open`](DataSourceScan::open) runs the scan on V2's own driver, as develop's V2 DuckDB scan +/// does: it prepares each ready child of the scan once and queues its parts, the chunks of its +/// plan, or the rows between the child's [splits](PlanChild::with_splits) when it has them. Each +/// worker drives a planning run of its own on the task that polls it, fed with parts from that +/// queue. Expanding a deferred child is queued work too: the worker that takes it expands it and +/// queues the work of its children for any worker to take. See the pool's documentation in +/// `plan_pool.rs`. /// /// # Partitions /// diff --git a/vortex-scan/src/source/plan_pool.rs b/vortex-scan/src/source/plan_pool.rs index 0f789325a59..063a278a4a0 100644 --- a/vortex-scan/src/source/plan_pool.rs +++ b/vortex-scan/src/source/plan_pool.rs @@ -3,32 +3,29 @@ //! The work that the workers of an opened [`PlanDataSource`](super::PlanDataSource) scan share. //! -//! This is the V1 layout pool's pattern (`vortex-layout/src/scan/pool.rs`) over the V2 executor, -//! with plan work for units. A pool's units are parts, rows of a prepared child's plan, and -//! deferred children not yet expanded. Opening the scan prepares each ready child once, which -//! plans without reading, and runs its root up front, which spawns its parts, as develop's V2 -//! DuckDB scan does: a part is the rows between two of the child's splits for the fields the scan -//! reads, such as a file's layout splits, else one of the scan's chunks. A root whose filter -//! changes while the scan runs, as a top-N's bound does, prunes the child as a whole before it -//! spawns parts; it reads zone maps to do so, so it runs as a unit of work instead. A worker takes parts and keeps up to `split_concurrency` of them -//! in flight, each spawned onto the session's runtime when the worker takes it, as the V1 pool's -//! splits are, and driven there on a planning run of its own that awaits only its reads: with a -//! filter, the part's pruning plans first, continuing into the chunks of the rows pruning kept; -//! without, the chunks directly. +//! An opened scan runs V2's own driver, the planners, morsels and [`Run`] that develop's V2 DuckDB +//! and DataFusion scans run, behind [`ScanPool`]. Nothing here is a general work pool. //! -//! Work creates work: expanding a deferred child, whether a file to open, a manifest entry or a -//! table partition, is a unit like any other, and queues the work of the children it expands -//! into, which may be deferred in turn. -//! -//! - An unordered pool hands units out through a channel. The worker that expands a deferred -//! child sends its children's units back into the channel, where any worker can take them. The -//! channel closes once every expansion has finished, which ends the workers. -//! - An ordered pool gives all of its units, in row order, to its first worker, which expands -//! each deferred child in its place; later workers get nothing. Parallel ordered reads cut the -//! scan with `split` first. +//! - An unordered pool runs as develop's V2 DuckDB scan (`vortex-duckdb/src/scan_v2.rs`) does. +//! Opening it prepares each ready child once, which plans without reading, and runs its root up +//! front, which spawns its parts: a part is the rows between two of the child's splits for the +//! fields the scan reads, such as a file's layout splits, else one of the scan's chunks. A root +//! whose filter changes while the scan runs, as a top-N's bound does, prunes the child as a +//! whole before it spawns parts; it reads zone maps to do so, so the worker that takes it runs +//! it instead. Each worker owns a [`Run`], driven on the task that polls the worker, as a DuckDB +//! thread drives its own run: it takes parts from a queue every worker shares, runs a part's +//! chunks on its run beside each other, so one chunk's reads overlap another's compute, yields +//! batches as they are produced, and awaits reads with [`Run::poll_completion`]. Nothing is +//! spawned per part. Expanding a deferred child, whether a file to open, a manifest entry or a +//! table partition, is queued work too: the worker that takes it expands it and queues the work +//! of its children, which may be deferred in turn. +//! - An ordered pool gives every child, in row order, to its first worker, which expands each +//! deferred child in its place and runs the parts in row order on a run of its own, a part's +//! chunks beside each other, returning each part's batches in row order. Later workers get +//! nothing. Parallel ordered reads cut the scan with `split` first. //! //! A limit is a [`RowLimit`] the workers take rows from as they yield them; workers stop taking -//! units once it is spent. +//! work once it is spent. use std::future; use std::ops::Range; @@ -52,8 +49,6 @@ use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_error::vortex_bail; use vortex_io::request::IoService; -use vortex_io::session::RuntimeSessionExt; -use vortex_utils::parallelism::get_available_parallelism; use super::plan::DeferredPlanChild; use super::plan::PlanChild; @@ -65,21 +60,26 @@ use crate::execution::planning::driver::Run; use crate::execution::planning::planner::Planner; use crate::execution::planning::planner::WorkScope; use crate::pool::RowLimit; -use crate::pool::SPLITS_IN_FLIGHT_PER_WORKER; use crate::pool::ScanPool; use crate::pool::ScanPoolRef; use crate::pool::trim_to_limit; use crate::prepare::PreparedScan; use crate::prepare::part_root; +/// The parts a worker runs on its run at once when the request's +/// [`split_concurrency`](crate::ScanRequest::split_concurrency) does not say: one, as a DuckDB +/// thread runs one chunk of develop's V2 scan at a time. A part's chunks still run beside each +/// other on the run. +const PARTS_PER_WORKER: usize = 1; + /// One child's prepared scan, shared by the workers running its parts. struct PreparedChild { scan: Arc, io: Arc, } -/// A part of a child: the planner its root spawned for some of its rows, which one worker runs on -/// a planning run of its own. +/// A part of a child: the planner its root spawned for some of its rows, which a worker runs on +/// its run. struct Part { child: Arc, scope: WorkScope, @@ -106,9 +106,6 @@ impl Taken { } } -/// A part's batches, in row order. -type PartFuture = BoxFuture<'static, VortexResult>>; - /// The parts a child's root spawns, in row order. type PartsFuture = BoxFuture<'static, VortexResult>>; @@ -133,40 +130,33 @@ impl PoolChild { } } -/// Opens a pool over the scan's `units`, preparing each of its ready children. +/// Opens a pool over the scan's `units`. pub(super) fn open(state: Arc, units: Vec) -> VortexResult { let taken = Arc::new(Taken::default()); let share = 1.0 / units.len().max(1) as f64; + let dtype = state.dtype.clone(); + let shared = Arc::new(Shared { + limit: state.limit.map(RowLimit::new), + parts_per_worker: state + .split_concurrency + .map_or(PARTS_PER_WORKER, |parts| parts.get()), + state, + taken, + }); let mut children = Vec::with_capacity(units.len()); for unit in units { - children.push(match state.child(unit.child) { - PlanSourceChild::Ready(child) => prepare(&state, child, unit.rows, share, &taken)?, + children.push(match shared.state.child(unit.child) { + PlanSourceChild::Ready(child) => shared.prepare(child, unit.rows, share)?, PlanSourceChild::Deferred { child, .. } => { PoolChild::Deferred(Arc::clone(child), share) } }); } - let dtype = state.dtype.clone(); - // A worker takes the place of a partition that one host thread drains, so, like the layout - // pool's, it keeps as many parts in flight as a partition's stream does by default: four per - // core, at most the request's `split_concurrency`. - let scaled = - SPLITS_IN_FLIGHT_PER_WORKER.saturating_mul(get_available_parallelism().unwrap_or(1)); - let parts_in_flight = state - .split_concurrency - .map_or(scaled, |max| scaled.min(max.get())) - .max(1); - let shared = Arc::new(Shared { - limit: state.limit.map(RowLimit::new), - state, - taken, - }); if shared.state.ordered { return Ok(Arc::new(OrderedPool { dtype, shared, children: Mutex::new(Some(children)), - parts_in_flight, })); } @@ -178,50 +168,9 @@ pub(super) fn open(state: Arc, units: Vec) -> VortexResult>, - share: f64, - taken: &Arc, -) -> VortexResult { - let rows = match rows { - Some(rows) => rows, - None => state.child_rows(child)?, - }; - if rows.is_empty() { - taken.add(share); - return Ok(PoolChild::Parts(Vec::new())); - } - let splits = child.splits(&state.projection, state.filter.as_ref())?; - let scan = Arc::new(state.builder(child, rows).prepare()?); - let dynamic = state - .filter - .as_ref() - .is_some_and(|filter| DynamicExprUpdates::new(filter).is_some()); - let root = part_root(&scan, splits.as_deref(), dynamic); - let io = scan.io(); - let child = Arc::new(PreparedChild { scan, io }); - let parts = run_root(child, root, share, Arc::clone(taken)); - if dynamic { - return Ok(PoolChild::Root(parts)); - } - let parts = parts - .now_or_never() - .vortex_expect("a root that only cuts parts reads nothing")?; - Ok(PoolChild::Parts(parts)) -} - /// Runs a child's root on a planning run of its own, awaiting only its reads, and returns the /// parts it spawns, in row order, dividing the child's `share` among them by their rows. The share /// of the rows they leave out counts as taken. @@ -272,35 +221,32 @@ fn run_root( .boxed() } -/// Runs a part on a planning run of its own, awaiting only its reads, and returns its batches in -/// row order. -fn run_part(part: Part) -> PartFuture { - async move { - let Part { - child, - scope, - planner, - .. - } = part; - let mut run = Run::new(); - run.admit(planner, scope, child.io.session()); - let mut batches = Vec::new(); - loop { - match run.advance()? { - Progress::Batch(batch) => batches.push((batch.scope.rows.start, batch.array)), - Progress::Spawn(scope, planner) => { - run.admit(planner, scope, child.io.session()); - } - Progress::RootDone(_) if run.live_roots() > 0 => {} - Progress::RootDone(_) | Progress::Idle => break, - Progress::Waiting => future::poll_fn(|cx| run.poll_completion(cx)).await?, +/// Runs a part alone on a planning run of its own, awaiting only its reads, and returns its +/// batches in row order. +async fn run_part(part: Part) -> VortexResult> { + let Part { + child, + scope, + planner, + .. + } = part; + let mut run = Run::new(); + run.admit(planner, scope, child.io.session()); + let mut batches = Vec::new(); + loop { + match run.advance()? { + Progress::Batch(batch) => batches.push((batch.scope.rows.start, batch.array)), + Progress::Spawn(scope, planner) => { + run.admit(planner, scope, child.io.session()); } + Progress::RootDone(_) if run.live_roots() > 0 => {} + Progress::RootDone(_) | Progress::Idle => break, + Progress::Waiting => future::poll_fn(|cx| run.poll_completion(cx)).await?, } - // A part's chunks finish in whatever order their reads arrive. - batches.sort_by_key(|(start, _)| *start); - Ok(batches.into_iter().map(|(_, array)| array).collect()) } - .boxed() + // A part's chunks finish in whatever order their reads arrive. + batches.sort_by_key(|(start, _)| *start); + Ok(batches.into_iter().map(|(_, array)| array).collect()) } /// What every worker of a pool shares. @@ -308,18 +254,50 @@ struct Shared { state: Arc, limit: Option, taken: Arc, + /// The parts a worker runs on its run at once. + parts_per_worker: usize, } impl Shared { - /// Spawns a part onto the session's runtime: another runtime thread may run it while this - /// worker drives its other parts, and its reads start right away. - fn spawn_part(&self, part: Part) -> PartFuture { - self.taken.add(part.share); - self.state.session.handle().spawn(run_part(part)).boxed() - } - - fn prepare(&self, child: &PlanChild, share: f64) -> VortexResult { - prepare(&self.state, child, None, share, &self.taken) + /// Prepares the scan of `rows` of `child`, or of the request's rows when `None`, once, and runs + /// its root up front, like the splits of a V1 scan, unless the root reads before it spawns + /// parts. + /// + /// Parts are cut on the child's splits for the fields the scan reads, when it has them, else + /// on the scan's chunks. A filter whose value changes while the scan runs, as a top-N's bound + /// does, prunes the child as a whole first, so a child it rules out takes no worker. + fn prepare( + &self, + child: &PlanChild, + rows: Option>, + share: f64, + ) -> VortexResult { + let state = &self.state; + let rows = match rows { + Some(rows) => rows, + None => state.child_rows(child)?, + }; + if rows.is_empty() { + self.taken.add(share); + return Ok(PoolChild::Parts(Vec::new())); + } + let splits = child.splits(&state.projection, state.filter.as_ref())?; + let scan = Arc::new(state.builder(child, rows).prepare()?); + let dynamic = state + .filter + .as_ref() + .is_some_and(|filter| DynamicExprUpdates::new(filter).is_some()); + let root = part_root(&scan, splits.as_deref(), dynamic); + let io = scan.io(); + let child = Arc::new(PreparedChild { scan, io }); + let parts = run_root(child, root, share, Arc::clone(&self.taken)); + if dynamic { + return Ok(PoolChild::Root(parts)); + } + let parts = parts + .now_or_never() + .vortex_expect("a root that only cuts parts reads nothing")?; + Ok(PoolChild::Parts(parts)) } fn is_limit_spent(&self) -> bool { @@ -337,7 +315,7 @@ impl Shared { self.state .expand_in_order(children, Arc::new(move |share| taken.add(share))) .then(move |child| { - match child.and_then(|(child, share)| shared.prepare(&child, share)) { + match child.and_then(|(child, share)| shared.prepare(&child, None, share)) { Ok(child) => child.into_parts(), Err(err) => future::ready(Err(err)).boxed(), } @@ -345,25 +323,34 @@ impl Shared { .boxed() } - /// A worker's output: the batches of its parts, trimmed to the limit, ending after the first - /// error. - fn output( + /// Expands a deferred child and queues the work of the children it expands into. + async fn expand( &self, - outputs: BoxStream<'static, VortexResult>>, - ) -> SendableArrayStream { - let arrays = outputs - .scan(false, |failed, output| { - if *failed { - return future::ready(None); + child: Arc, + share: f64, + sender: &Sender, + ) -> VortexResult<()> { + let children = child.expand().await?; + if children.is_empty() { + self.taken.add(share); + } + let share = share / children.len().max(1) as f64; + for child in children { + match child { + PlanSourceChild::Ready(child) => match self.state.admit(child)? { + Some(child) => queue(sender, self.prepare(&child, None, share)?), + None => self.taken.add(share), + }, + PlanSourceChild::Deferred { child, .. } => { + send(sender, Work::Expand(child, share, sender.clone())); } - *failed = output.is_err(); - future::ready(Some(output)) - }) - .flat_map(|arrays| match arrays { - Ok(arrays) => stream::iter(arrays.into_iter().map(Ok)).left_stream(), - Err(err) => stream::once(future::ready(Err(err))).right_stream(), - }) - .boxed(); + } + } + Ok(()) + } + + /// A worker's output: `arrays`, trimmed to the limit. + fn output(&self, arrays: BoxStream<'static, VortexResult>) -> SendableArrayStream { let arrays = match &self.limit { Some(limit) => trim_to_limit(arrays, limit.clone()), None => arrays, @@ -408,45 +395,6 @@ struct UnorderedPool { dtype: DType, shared: Arc, receiver: Receiver, - parts_in_flight: usize, -} - -impl UnorderedPool { - fn run(shared: &Arc, work: Work) -> PartFuture { - match work { - Work::Part(part) => shared.spawn_part(part), - Work::Root(parts, sender) => async move { - for part in parts.await? { - send(&sender, Work::Part(part)); - } - Ok(Vec::new()) - } - .boxed(), - Work::Expand(child, share, sender) => { - let shared = Arc::clone(shared); - async move { - let children = child.expand().await?; - if children.is_empty() { - shared.taken.add(share); - } - let share = share / children.len().max(1) as f64; - for child in children { - match child { - PlanSourceChild::Ready(child) => match shared.state.admit(child)? { - Some(child) => queue(&sender, shared.prepare(&child, share)?), - None => shared.taken.add(share), - }, - PlanSourceChild::Deferred { child, .. } => { - send(&sender, Work::Expand(child, share, sender.clone())); - } - } - } - Ok(Vec::new()) - } - .boxed() - } - } - } } impl ScanPool for UnorderedPool { @@ -456,16 +404,24 @@ impl ScanPool for UnorderedPool { fn worker(self: Arc) -> SendableArrayStream { let shared = Arc::clone(&self.shared); - let runner = Arc::clone(&shared); - let receiver = self.receiver.clone(); - let parts_in_flight = self.parts_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.is_limit_spent())) - .map(move |work| UnorderedPool::run(&runner, work)) - .buffer_unordered(parts_in_flight) - .boxed(); - shared.output(outputs) + let worker = Worker { + receiver: self.receiver.clone(), + shared: Arc::clone(&shared), + run: Run::new(), + child: None, + held: None, + _pool: self, + }; + let arrays = stream::unfold(Some(worker), |worker| async move { + let mut worker = worker?; + match worker.next_array().await { + Ok(Some(array)) => Some((Ok(array), Some(worker))), + Ok(None) => None, + Err(err) => Some((Err(err), None)), + } + }) + .boxed(); + shared.output(arrays) } fn progress(&self) -> f64 { @@ -483,19 +439,127 @@ impl ScanPool for UnorderedPool { impl Drop for UnorderedPool { fn drop(&mut self) { - // Pending opens hold senders of the channel itself; drain them so it can be freed. + // Pending roots and expansions 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. +/// One worker of an unordered pool: a run of its own, fed with parts from the pool's queue, and +/// driven on the task that polls the worker. +struct Worker { + receiver: Receiver, + shared: Arc, + run: Run, + /// The child whose parts are live on the run. A run reads each root through the child's IO, + /// and a planner a part spawns does not say which part it came from, so a worker runs one + /// child's parts at a time. + child: Option>, + /// A part of another child, taken while the run still held parts of `child`. + held: Option, + /// Holds the pool, so the pool is dropped only after its last worker. + _pool: Arc, +} + +impl Worker { + /// The worker's next array, or `None` once the pool has no more work for it. Keeps the run fed + /// with parts, and awaits reads when every live part waits for them. + async fn next_array(&mut self) -> VortexResult> { + loop { + while self.run.live_roots() < self.shared.parts_per_worker + && !self.shared.is_limit_spent() + { + let part = match self.held.take() { + Some(part) => part, + // A worker with nothing live waits for work; one with parts live only takes + // work that is already queued. + None => match self.take(self.run.live_roots() == 0).await? { + Some(part) => part, + None => break, + }, + }; + if self.run.live_roots() > 0 + && !self + .child + .as_ref() + .is_some_and(|child| Arc::ptr_eq(child, &part.child)) + { + self.held = Some(part); + break; + } + self.admit(part); + } + if self.run.live_roots() == 0 { + return Ok(None); + } + match self.run.advance()? { + Progress::Batch(batch) => return Ok(Some(batch.array)), + Progress::Spawn(scope, planner) => { + let child = self + .child + .as_ref() + .vortex_expect("a planner is spawned by a live part"); + self.run.admit(planner, scope, child.io.session()); + } + Progress::RootDone(_) | Progress::Idle => {} + Progress::Waiting => { + future::poll_fn(|cx| self.run.poll_completion(cx)).await?; + } + } + } + } + + /// Admits `part` to the run. + fn admit(&mut self, part: Part) { + let Part { + child, + scope, + planner, + share, + } = part; + self.shared.taken.add(share); + self.run.admit(planner, scope, child.io.session()); + self.child = Some(child); + } + + /// Takes the next part from the pool's queue, running the roots and expansions it finds there + /// first, which queue parts of their own. With `wait`, waits for work until the queue closes; + /// otherwise takes only what is queued already. + async fn take(&mut self, wait: bool) -> VortexResult> { + loop { + let work = if wait { + match self.receiver.recv().await { + Ok(work) => work, + Err(_) => return Ok(None), + } + } else { + match self.receiver.try_recv() { + Ok(work) => work, + Err(_) => return Ok(None), + } + }; + match work { + Work::Part(part) => return Ok(Some(part)), + Work::Root(parts, sender) => { + for part in parts.await? { + send(&sender, Work::Part(part)); + } + } + Work::Expand(child, share, sender) => { + self.shared.expand(child, share, &sender).await?; + } + } + } + } +} + +/// A pool that gives all of its children, in row order, to its first worker. struct OrderedPool { dtype: DType, shared: Arc, /// The children, until the first worker takes them. children: Mutex>>, - parts_in_flight: usize, } impl ScanPool for OrderedPool { @@ -511,9 +575,9 @@ impl ScanPool for OrderedPool { )); }; let expander = Arc::clone(&self.shared); - let spawner = Arc::clone(&self.shared); let shared = Arc::clone(&self.shared); - let outputs = stream::iter(children) + let runner = Arc::clone(&self.shared); + let arrays = stream::iter(children) .flat_map(move |child| match child { PoolChild::Deferred(child, share) => expander.parts_in_order(vec![( PlanSourceChild::Deferred { @@ -529,13 +593,20 @@ impl ScanPool for OrderedPool { Err(err) => stream::once(future::ready(Err(err))).right_stream(), }) .take_while(move |_| future::ready(!shared.is_limit_spent())) - .map(move |part| match part { - Ok(part) => spawner.spawn_part(part), - Err(err) => future::ready(Err(err)).boxed(), + .then(move |part| { + let runner = Arc::clone(&runner); + async move { + let part = part?; + runner.taken.add(part.share); + run_part(part).await + } + }) + .flat_map(|arrays| match arrays { + Ok(arrays) => stream::iter(arrays.into_iter().map(Ok)).left_stream(), + Err(err) => stream::once(future::ready(Err(err))).right_stream(), }) - .buffered(self.parts_in_flight) .boxed(); - self.shared.output(outputs) + self.shared.output(arrays) } fn progress(&self) -> f64 {