From 8626a3ffde7562efbfb84886ef73894c71b28d8d Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Thu, 19 Nov 2026 15:54:11 -0500 Subject: [PATCH 01/25] Give layout scans a native split and open Layout scans now split on their layout splits and open into a pool whose workers share those splits through a channel. Multi-file scans queue an open for each deferred file; the worker that opens one sends the file's splits back into the channel for any worker to take. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-layout/src/scan/layout.rs | 553 ++++++++++++++++++- vortex-layout/src/scan/mod.rs | 1 + vortex-layout/src/scan/multi.rs | 681 +++++++++++++++++++++++- vortex-layout/src/scan/pool.rs | 480 +++++++++++++++++ vortex-layout/src/scan/repeated_scan.rs | 37 +- vortex-layout/src/scan/test.rs | 36 ++ 6 files changed, 1781 insertions(+), 7 deletions(-) create mode 100644 vortex-layout/src/scan/pool.rs diff --git a/vortex-layout/src/scan/layout.rs b/vortex-layout/src/scan/layout.rs index a0ab69310f8..926ea7cc8e8 100644 --- a/vortex-layout/src/scan/layout.rs +++ b/vortex-layout/src/scan/layout.rs @@ -37,6 +37,7 @@ use vortex_scan::Partition; use vortex_scan::PartitionRef; use vortex_scan::PartitionStream; use vortex_scan::ScanRequest; +use vortex_scan::pool::ScanPoolRef; use vortex_scan::selection::Selection; use vortex_session::VortexSession; @@ -44,9 +45,19 @@ use crate::LayoutReaderRef; use crate::scan::limit::RowLimit; use crate::scan::metrics::ScanMetrics; use crate::scan::metrics::ScanRecorder; +use crate::scan::pool::FileWork; +use crate::scan::pool::PiecePartition; +use crate::scan::pool::PoolFile; +use crate::scan::pool::PoolOptions; +use crate::scan::pool::PreparedScan; +use crate::scan::pool::open_pool; use crate::scan::scan_builder::ScanBuilder; /// An implementation of a [`DataSource`] that reads data from a [`LayoutReaderRef`]. +/// +/// When a scan is [split](DataSourceScan::split) or [opened](DataSourceScan::open), its units are +/// the layout's splits. Workers of an opened scan share them, each keeping several in flight on +/// its own thread. pub struct LayoutReaderDataSource { reader: LayoutReaderRef, session: VortexSession, @@ -201,6 +212,7 @@ impl DataSource for LayoutReaderDataSource { dtype, projection, filter, + limit: scan_request.limit, remaining_limit: scan_request.limit, row_limit, selection: scan_request.selection, @@ -224,6 +236,8 @@ struct LayoutReaderScan { dtype: DType, projection: BoundExpression, filter: Option, + /// The request's limit. + limit: Option, /// Limit rows not yet covered by the splits produced so far; production stops at zero. /// Decremented only for filterless scans, where each split's output is exactly its /// selected row count. @@ -239,6 +253,36 @@ struct LayoutReaderScan { split_size: u64, } +impl LayoutReaderScan { + /// Prepares the scan once, for splitting or opening. + fn into_split_scan(self) -> VortexResult { + let row_count = DataSourceScan::row_count(&self); + let options = LayoutScanOptions { + dtype: self.dtype, + ordered: self.ordered, + limit: self.limit, + has_filter: self.filter.is_some(), + splits_in_flight: self.split_concurrency, + }; + let row_range = clamp_row_range(self.next_row..self.end_row, self.reader.row_count()); + let scan = ScanBuilder::new(self.session, self.reader) + .with_row_range(row_range) + .with_selection(self.selection) + .with_projection(self.projection) + .with_some_filter(self.filter) + .with_some_scan_metrics(self.metrics) + .with_ordered(self.ordered) + .prepare()?; + let ranges = scan.split_ranges(None); + Ok(LayoutSplitScan { + options, + row_count, + scan: Arc::new(scan), + ranges, + }) + } +} + impl DataSourceScan for LayoutReaderScan { fn dtype(&self) -> &DType { &self.dtype @@ -256,6 +300,165 @@ impl DataSourceScan for LayoutReaderScan { fn partitions(self: Box) -> PartitionStream { (*self).boxed() } + + fn row_count(&self) -> Precision { + let selected = self + .selection + .row_count_in_range(&(self.next_row..self.end_row)); + let rows = self.limit.map_or(selected, |limit| selected.min(limit)); + if self.filter.is_some() { + Precision::inexact(rows) + } else { + Precision::exact(rows) + } + } + + fn split(self: Box, n: NonZeroUsize) -> VortexResult> { + Box::new(self.into_split_scan()?).split(n) + } + + fn open(self: Box) -> VortexResult { + Box::new(self.into_split_scan()?).open() + } +} + +/// Clamps a requested row range to the rows of the source. +fn clamp_row_range(row_range: Range, total_rows: u64) -> Range { + let end = row_range.end.min(total_rows); + row_range.start.min(end)..end +} + +/// What a [`LayoutSplitScan`] and every piece cut from it share. +#[derive(Clone)] +struct LayoutScanOptions { + dtype: DType, + ordered: bool, + limit: Option, + has_filter: bool, + splits_in_flight: Option, +} + +/// A prepared scan of one layout reader over some of its splits: a [`LayoutReaderScan`] that was +/// split or opened, or a piece cut from one. +struct LayoutSplitScan { + options: LayoutScanOptions, + row_count: Precision, + scan: Arc, + /// The scan's units: its layout splits, in row order. + ranges: Vec>, +} + +impl LayoutSplitScan { + /// A piece over some of the prepared scan's split `ranges`. + fn piece( + options: &LayoutScanOptions, + scan: Arc, + ranges: Vec>, + ) -> Self { + let selected = ranges + .iter() + .map(|range| scan.selected_row_count(range)) + .sum::(); + Self { + options: options.clone(), + row_count: if options.has_filter { + Precision::inexact(selected) + } else { + Precision::exact(selected) + }, + scan, + ranges, + } + } +} + +impl DataSourceScan for LayoutSplitScan { + fn dtype(&self) -> &DType { + &self.options.dtype + } + + fn partition_count(&self) -> Precision { + Precision::exact(1usize) + } + + fn partitions(self: Box) -> PartitionStream { + let index = self.ranges.first().map_or(0, |range| { + usize::try_from(range.start).unwrap_or(usize::MAX) + }); + PiecePartition::stream(self, index) + } + + fn row_count(&self) -> Precision { + self.row_count + } + + fn split(self: Box, n: NonZeroUsize) -> VortexResult> { + if self.options.limit.is_some() || self.ranges.len() <= 1 || n.get() == 1 { + return Ok(vec![self]); + } + let LayoutSplitScan { + options, + scan, + ranges, + .. + } = *self; + Ok(group_contiguous(ranges, n) + .into_iter() + .map(|ranges| { + Box::new(LayoutSplitScan::piece(&options, Arc::clone(&scan), ranges)) + as DataSourceScanRef + }) + .collect()) + } + + fn open(self: Box) -> VortexResult { + let LayoutScanOptions { + dtype, + ordered, + limit, + has_filter, + splits_in_flight, + } = self.options; + if limit == Some(0) { + return Box::new(Empty::new(dtype, 0)).open(); + } + let work = FileWork::start(self.scan, self.ranges)?; + let options = PoolOptions { + dtype, + ordered, + limit, + has_filter, + splits_in_flight, + }; + Ok(open_pool(options, vec![PoolFile::Opened(work)], None)) + } +} + +/// Groups consecutive `ranges` into at most `n` contiguous groups of about equal row counts. +/// +/// Never cuts a range: each range lands whole in one group. +pub(crate) fn group_contiguous(ranges: Vec>, n: NonZeroUsize) -> Vec>> { + let total = ranges + .iter() + .map(|range| u128::from(range.end - range.start)) + .sum::() + .max(1); + let n_groups = n.get() as u128; + let mut groups: Vec>> = Vec::new(); + let mut current_group = None; + let mut before = 0u128; + for range in ranges { + let group = (before * n_groups / total).min(n_groups - 1); + before += u128::from(range.end - range.start); + if current_group != Some(group) { + current_group = Some(group); + groups.push(Vec::new()); + } + if let Some(last) = groups.last_mut() { + last.push(range); + } + } + groups } impl Stream for LayoutReaderScan { @@ -393,11 +596,17 @@ impl Partition for LayoutReaderSplit { } /// A scan that produces no data, only empty arrays with the correct row count. -struct Empty { +pub(crate) struct Empty { dtype: DType, row_count: u64, } +impl Empty { + pub(crate) fn new(dtype: DType, row_count: u64) -> Self { + Self { dtype, row_count } + } +} + impl DataSourceScan for Empty { fn dtype(&self) -> &DType { &self.dtype @@ -410,6 +619,10 @@ impl DataSourceScan for Empty { fn partitions(self: Box) -> PartitionStream { stream::iter([Ok(self as _)]).boxed() } + + fn row_count(&self) -> Precision { + Precision::exact(self.row_count) + } } impl Partition for Empty { @@ -620,3 +833,341 @@ mod tests { Ok(()) } } + +#[cfg(test)] +mod pool_tests { + use std::num::NonZeroUsize; + use std::sync::Arc; + + use rstest::rstest; + use vortex_array::dtype::DType; + use vortex_array::dtype::Nullability; + use vortex_array::dtype::StructFields; + use vortex_array::expr::Expression; + use vortex_array::expr::root; + use vortex_buffer::Buffer; + use vortex_error::VortexResult; + use vortex_metrics::DefaultMetricsRegistry; + use vortex_metrics::MetricValue; + use vortex_metrics::MetricsRegistry; + use vortex_scan::DataSource; + use vortex_scan::DataSourceScanRef; + use vortex_scan::ScanRequest; + use vortex_scan::selection::Selection; + use vortex_scan::strict_sorted_buffer::StrictSortedBuffer; + + use super::LayoutReaderDataSource; + use super::group_contiguous; + use crate::scan::test::TestLayoutReader; + use crate::scan::test::collect_scan_values; + use crate::scan::test::keep_odd; + use crate::scan::test::new_session; + use crate::scan::test::read_with_one_worker; + use crate::scan::test::read_with_workers; + + fn counter_values(registry: &DefaultMetricsRegistry) -> Vec { + registry + .snapshot() + .iter() + .map(|metric| match metric.value() { + MetricValue::Counter(counter) => counter.value(), + _ => panic!("expected a scan counter"), + }) + .collect() + } + + fn plan( + source: &LayoutReaderDataSource, + request: ScanRequest, + ) -> VortexResult { + futures::executor::block_on(source.scan(request)) + } + + /// Earlier splits finish last, so completion order is the reverse of row order. + fn slow_start(row: u64) -> usize { + usize::try_from(32u64.saturating_sub(row)).unwrap_or(0) + } + + fn source(reader: TestLayoutReader) -> LayoutReaderDataSource { + LayoutReaderDataSource::new(Arc::new(reader), new_session()) + } + + /// Each opened scan is one execution: it counts one file scan, and one attempt per split. + #[test] + fn opened_executions_share_aggregate_handles() -> VortexResult<()> { + let registry = Arc::new(DefaultMetricsRegistry::default()); + let source = source(TestLayoutReader::new(8).with_split_size(2)) + .with_metrics_registry(Arc::::clone(®istry)); + for execution in 1..=2 { + let pool = plan(&source, ScanRequest::default())?.open()?; + let values = read_with_workers(&pool, 2)?.concat(); + assert_eq!(values.len(), 8); + assert_eq!( + counter_values(®istry), + [4 * execution, 0, 0, execution, 0] + ); + } + Ok(()) + } + + /// N workers on one pool read every split exactly once. + #[rstest] + #[case::ordered(true)] + #[case::unordered(false)] + fn workers_read_every_split_once(#[case] ordered: bool) -> VortexResult<()> { + let source = source(TestLayoutReader::new(64).with_split_size(1)); + let pool = plan( + &source, + ScanRequest { + ordered, + ..Default::default() + }, + )? + .open()?; + let per_worker = read_with_workers(&pool, 4)?; + + let mut values = per_worker.concat(); + values.sort_unstable(); + assert_eq!(values, (0..64).collect::>()); + Ok(()) + } + + /// A worker of an ordered pool yields rows in row order, even when later splits finish + /// first, and later workers of the pool get nothing. + #[test] + fn ordered_worker_yields_row_order() -> VortexResult<()> { + let read = |ordered| { + let source = source( + TestLayoutReader::new(32) + .with_split_size(1) + .with_yields(slow_start), + ); + let pool = plan( + &source, + ScanRequest { + ordered, + ..Default::default() + }, + )? + .open()?; + let first = read_with_one_worker(Arc::clone(&pool))?; + let second = read_with_one_worker(pool)?; + assert!(second.is_empty()); + Ok::<_, vortex_error::VortexError>(first) + }; + + assert_eq!(read(true)?, (0..32).collect::>()); + // The same splits complete out of order, so an unordered worker does not keep row order. + assert_ne!(read(false)?, (0..32).collect::>()); + Ok(()) + } + + /// A limit holds across several workers of an unordered pool, whether splits reserve their + /// rows up front (no filter) or trim their output (filter). + #[rstest] + #[case::reserved(None)] + #[case::trimmed(Some(root()))] + fn unordered_limit_holds_across_workers( + #[case] filter: Option, + ) -> VortexResult<()> { + let source = source(TestLayoutReader::new(64).with_split_size(2)); + let pool = plan( + &source, + ScanRequest { + filter, + limit: Some(7), + ..Default::default() + }, + )? + .open()?; + let mut values = read_with_workers(&pool, 4)?.concat(); + values.sort_unstable(); + values.dedup(); + assert_eq!(values.len(), 7); + Ok(()) + } + + /// An ordered pool with a limit returns exactly the first `limit` rows. + #[rstest] + #[case::reserved(false, &[0, 1, 2, 3, 4])] + #[case::trimmed(true, &[1, 3, 5, 7, 9])] + fn ordered_limit_returns_the_first_rows( + #[case] filtered: bool, + #[case] expected: &[i32], + ) -> VortexResult<()> { + let source = source( + TestLayoutReader::new(32) + .with_split_size(2) + .with_keep_row(keep_odd) + .with_yields(slow_start), + ); + let pool = plan( + &source, + ScanRequest { + filter: filtered.then(root), + ordered: true, + limit: Some(5), + ..Default::default() + }, + )? + .open()?; + assert_eq!(read_with_one_worker(pool)?, expected); + Ok(()) + } + + /// With a sparse selection and no filter, each split contributes only its selected rows, so + /// the workers keep taking splits until the limit is actually filled. + #[rstest] + #[case::ordered(true)] + #[case::unordered(false)] + fn opened_sparse_selection_with_limit_fills_the_limit( + #[case] ordered: bool, + ) -> VortexResult<()> { + let source = source(TestLayoutReader::new(12).with_split_size(2)); + + // Every two-row split contains exactly one selected row (the even ones). + let selection = + Selection::IncludeByIndex(StrictSortedBuffer::try_new(Buffer::from_iter([ + 0u64, 2, 4, 6, 8, 10, + ]))?); + let pool = plan( + &source, + ScanRequest { + selection, + limit: Some(3), + ordered, + ..Default::default() + }, + )? + .open()?; + let mut values = read_with_one_worker(pool)?; + if !ordered { + values.sort_unstable(); + } + assert_eq!(values, [0, 2, 4]); + Ok(()) + } + + /// `split(n)` pieces cover the scan exactly, are in row order, and never cut a layout split. + #[rstest] + #[case::fewer_pieces_than_splits(3, 3)] + #[case::more_pieces_than_splits(16, 7)] + fn split_pieces_cover_the_scan_on_split_boundaries( + #[case] n: usize, + #[case] expected_pieces: usize, + ) -> VortexResult<()> { + // Splits of three rows: [0, 3), [3, 6), ..., [18, 20). + let source = source(TestLayoutReader::new(20).with_split_size(3)); + let scan = plan(&source, ScanRequest::default())?; + let pieces = scan.split(NonZeroUsize::new(n).expect("non-zero"))?; + assert_eq!(pieces.len(), expected_pieces); + assert_eq!( + pieces + .iter() + .map(|piece| piece.row_count().as_exact()) + .sum::>(), + Some(20) + ); + + let mut values = Vec::new(); + for piece in pieces { + let piece_values = read_with_one_worker(piece.open()?)?; + let first = *piece_values.first().expect("pieces are not empty"); + let last = *piece_values.last().expect("pieces are not empty"); + assert_eq!(first % 3, 0, "piece starts on a split boundary"); + assert!( + (last + 1) % 3 == 0 || last == 19, + "piece ends on a split boundary" + ); + values.extend(piece_values); + } + assert_eq!(values, (0..20).collect::>()); + Ok(()) + } + + /// A piece read through the partitions API returns the same rows as its pool. + #[test] + fn split_pieces_read_through_partitions() -> VortexResult<()> { + let source = source(TestLayoutReader::new(20).with_split_size(3)); + let scan = plan( + &source, + ScanRequest { + ordered: true, + ..Default::default() + }, + )?; + let mut values = Vec::new(); + for piece in scan.split(NonZeroUsize::new(3).expect("non-zero"))? { + let partitions = + futures::executor::block_on_stream(piece.partitions()).collect::>(); + assert_eq!(partitions.len(), 1); + for partition in partitions { + values.extend(collect_scan_values(futures::executor::block_on_stream( + partition?.execute()?, + ))?); + } + } + assert_eq!(values, (0..20).collect::>()); + Ok(()) + } + + #[test] + fn split_keeps_a_limited_scan_whole() -> VortexResult<()> { + let source = source(TestLayoutReader::new(20).with_split_size(3)); + let scan = plan( + &source, + ScanRequest { + limit: Some(4), + ..Default::default() + }, + )?; + let pieces = scan.split(NonZeroUsize::new(4).expect("non-zero"))?; + assert_eq!(pieces.len(), 1); + Ok(()) + } + + #[test] + fn grouping_never_returns_more_groups_than_requested() { + let ranges = (0..10u64) + .map(|start| start * 10..start * 10 + 10) + .collect(); + let groups = group_contiguous(ranges, NonZeroUsize::new(3).expect("non-zero")); + assert_eq!(groups.len(), 3); + assert_eq!(groups.concat().len(), 10); + } + + /// A length-only scan opens into one pool whose workers together return its rows once. + #[test] + fn length_only_scan_returns_its_rows_once_across_workers() -> VortexResult<()> { + let source = source(TestLayoutReader::new(10).with_dtype(DType::Struct( + StructFields::empty(), + Nullability::NonNullable, + ))); + let pool = plan( + &source, + ScanRequest { + limit: Some(7), + ..Default::default() + }, + )? + .open()?; + let rows: usize = std::thread::scope(|scope| { + let handles = (0..3) + .map(|_| { + let worker = Arc::clone(&pool).worker(); + scope.spawn(move || { + futures::executor::block_on_stream(worker) + .map(|array| array.map(|array| array.len())) + .sum::>() + }) + }) + .collect::>(); + handles + .into_iter() + .map(|handle| handle.join().expect("worker thread panicked")) + .sum::>() + })?; + assert_eq!(rows, 7); + Ok(()) + } +} diff --git a/vortex-layout/src/scan/mod.rs b/vortex-layout/src/scan/mod.rs index ea8e8843773..ea8ea2d8e0f 100644 --- a/vortex-layout/src/scan/mod.rs +++ b/vortex-layout/src/scan/mod.rs @@ -7,6 +7,7 @@ pub mod layout; mod limit; pub mod metrics; pub mod multi; +mod pool; pub mod repeated_scan; pub mod scan_builder; pub mod split_by; diff --git a/vortex-layout/src/scan/multi.rs b/vortex-layout/src/scan/multi.rs index 1f1ee275688..be41497e0ad 100644 --- a/vortex-layout/src/scan/multi.rs +++ b/vortex-layout/src/scan/multi.rs @@ -57,12 +57,24 @@ use vortex_scan::Partition; use vortex_scan::PartitionRef; use vortex_scan::PartitionStream; use vortex_scan::ScanRequest; +use vortex_scan::pool::PartitionPool; +use vortex_scan::pool::ScanPoolRef; use vortex_scan::selection::Selection; use vortex_session::VortexSession; use vortex_utils::parallelism::get_available_parallelism; use crate::LayoutReaderRef; +use crate::scan::layout::Empty; +use crate::scan::layout::group_contiguous; use crate::scan::limit::RowLimit; +use crate::scan::pool::FileWork; +use crate::scan::pool::PiecePartition; +use crate::scan::pool::PlannedSplits; +use crate::scan::pool::PoolFile; +use crate::scan::pool::PoolOptions; +use crate::scan::pool::PrepareFile; +use crate::scan::pool::PreparedScan; +use crate::scan::pool::open_pool; use crate::scan::scan_builder::ScanBuilder; /// Default concurrency for opening deferred readers. @@ -322,7 +334,6 @@ impl DataSource for MultiLayoutDataSource { row_limit, ready, deferred, - handle: self.session.handle(), concurrency: self.concurrency, })) } @@ -374,6 +385,17 @@ impl BoundScanRequest { split_concurrency, }) } + + /// Whether the scan filters rows, so its output row count is unknown up front. A filter + /// that failed to bind counts as one. + fn has_filter(&self) -> bool { + !matches!(self.filter, Ok(None)) + } + + /// Whether the request selects partitions, which only the partitions path applies. + fn selects_partitions(&self) -> bool { + self.partition_range.is_some() || !matches!(self.partition_selection, Selection::All) + } } struct MultiLayoutScan { @@ -384,10 +406,31 @@ struct MultiLayoutScan { row_limit: Option, ready: VecDeque, deferred: VecDeque>, - handle: vortex_io::runtime::Handle, concurrency: usize, } +impl MultiLayoutScan { + /// The scan as files to split or open. Files keep their partition order. + fn into_split_scan(self) -> MultiLayoutSplitScan { + let children = self + .ready + .into_iter() + .map(ScanChild::Opened) + .chain(self.deferred.into_iter().map(ScanChild::Deferred)) + .collect(); + MultiLayoutSplitScan { + context: Arc::new(ScanContext { + session: self.session, + source_dtype: self.source_dtype, + dtype: self.dtype, + request: self.request, + }), + children, + index: 0, + } + } +} + impl DataSourceScan for MultiLayoutScan { fn dtype(&self) -> &DType { &self.dtype @@ -402,6 +445,35 @@ impl DataSourceScan for MultiLayoutScan { } } + fn row_count(&self) -> Precision { + let estimate = estimate_row_count( + &self.request, + self.ready + .iter() + .map(|reader| file_row_count(&self.request, reader)), + self.ready.len() + self.deferred.len(), + ); + if self.request.selects_partitions() { + estimate.into_inexact() + } else { + estimate + } + } + + fn split(self: Box, n: NonZeroUsize) -> VortexResult> { + if self.request.selects_partitions() { + return Ok(vec![self]); + } + Box::new(self.into_split_scan()).split(n) + } + + fn open(self: Box) -> VortexResult { + if self.request.selects_partitions() { + return Ok(Arc::new(PartitionPool::new(self))); + } + Box::new(self.into_split_scan()).open() + } + fn partitions(self: Box) -> PartitionStream { let Self { session, @@ -411,9 +483,9 @@ impl DataSourceScan for MultiLayoutScan { row_limit, ready, deferred, - handle, concurrency, } = *self; + let handle = session.handle(); let ordered = request.ordered; @@ -623,6 +695,279 @@ impl Partition for MultiLayoutPartition { } } +/// The rows `request` selects from an opened file, before any filter or limit. +fn file_row_count(request: &BoundScanRequest, reader: &LayoutReaderRef) -> u64 { + let row_range = request + .row_range + .clone() + .unwrap_or_else(|| 0..reader.row_count()); + request.selection.row_count_in_range(&row_range) +} + +/// Estimates the rows a scan of `files` files returns from the rows of the files whose rows are +/// known, extrapolating to the rest. +fn estimate_row_count( + request: &BoundScanRequest, + known: impl Iterator, + files: usize, +) -> Precision { + let (rows, known_files) = known.fold((0u64, 0u64), |(rows, count), file_rows| { + (rows.saturating_add(file_rows), count + 1) + }); + let files = files as u64; + let (rows, is_exact) = if known_files == files { + (rows, !request.has_filter()) + } else if let Some(average) = rows.checked_div(known_files) { + (average.saturating_mul(files), false) + } else { + return Precision::Absent; + }; + let rows = request.limit.map_or(rows, |limit| rows.min(limit)); + if is_exact { + Precision::exact(rows) + } else { + Precision::inexact(rows) + } +} + +/// What every piece of a split or opened multi-layout scan shares. +struct ScanContext { + session: VortexSession, + source_dtype: DType, + dtype: DType, + request: BoundScanRequest, +} + +impl ScanContext { + /// Plans the scan of one opened file: checks its dtype, prunes it on statistics, and + /// prepares its splits. Returns `None` when statistics reject the file. Reads metadata only. + fn plan_file(&self, reader: LayoutReaderRef) -> VortexResult> { + if reader.dtype() != &self.source_dtype { + return Err(vortex_err!( + "Multi-layout reader dtype mismatch: expected {}, got {}", + self.source_dtype, + reader.dtype() + )); + } + let filter = self.request.filter.clone()?; + let row_range = self + .request + .row_range + .clone() + .unwrap_or_else(|| 0..reader.row_count()); + + if let Some(filter) = &filter { + let mask_len = usize::try_from(row_range.end - row_range.start).unwrap_or(usize::MAX); + if let Ok(pruning) = + reader.pruning_evaluation(&row_range, filter, Mask::new_true(mask_len)) + && let Some(Ok(mask)) = pruning.now_or_never() + && mask.all_false() + { + return Ok(None); + } + } + + let scan = ScanBuilder::new(self.session.clone(), reader) + .with_row_range(row_range) + .with_selection(self.request.selection.clone()) + .with_projection(self.request.projection.clone()) + .with_some_filter(filter) + .with_ordered(self.request.ordered) + .prepare()?; + let ranges = scan.split_ranges(None); + Ok(Some((Arc::new(scan), ranges))) + } + + /// Starts reading an opened file for one execution. + fn start_file(&self, reader: LayoutReaderRef) -> VortexResult { + match self.plan_file(reader)? { + Some((scan, ranges)) => FileWork::start(scan, ranges), + None => Ok(FileWork::empty()), + } + } +} + +/// One file of a split or opened multi-layout scan. +enum ScanChild { + Opened(LayoutReaderRef), + /// An opened file whose splits are known: all of them, or the share of one piece. + Planned { + scan: Arc, + ranges: Vec>, + }, + Deferred(Arc), +} + +/// A multi-layout scan that was split or opened, or a piece cut from one. Its units are files, +/// then each file's splits. +struct MultiLayoutSplitScan { + context: Arc, + children: Vec, + /// The index of the piece's single partition. + index: usize, +} + +impl MultiLayoutSplitScan { + /// Splits a planned file's ranges into `pieces` contiguous groups. + fn split_child(child: ScanChild, pieces: usize) -> Vec { + match child { + ScanChild::Planned { scan, ranges } if pieces > 1 => group_contiguous( + ranges, + NonZeroUsize::new(pieces).unwrap_or(NonZeroUsize::MIN), + ) + .into_iter() + .map(|ranges| ScanChild::Planned { + scan: Arc::clone(&scan), + ranges, + }) + .collect(), + child => vec![child], + } + } +} + +impl DataSourceScan for MultiLayoutSplitScan { + fn dtype(&self) -> &DType { + &self.context.dtype + } + + fn partition_count(&self) -> Precision { + Precision::exact(1usize) + } + + fn partitions(self: Box) -> PartitionStream { + let index = self.index; + PiecePartition::stream(self, index) + } + + fn row_count(&self) -> Precision { + let request = &self.context.request; + let known = self.children.iter().filter_map(|child| match child { + ScanChild::Opened(reader) => Some(file_row_count(request, reader)), + ScanChild::Planned { scan, ranges } => Some( + ranges + .iter() + .map(|range| scan.selected_row_count(range)) + .sum(), + ), + ScanChild::Deferred(_) => None, + }); + estimate_row_count(request, known, self.children.len()) + } + + fn split(self: Box, n: NonZeroUsize) -> VortexResult> { + if self.context.request.limit.is_some() || n.get() == 1 || self.children.is_empty() { + return Ok(vec![self]); + } + let MultiLayoutSplitScan { + context, children, .. + } = *self; + + // Plan the opened files so they can be cut on their splits. Deferred files stay whole: + // splitting never opens a file. + let mut planned = Vec::with_capacity(children.len()); + for child in children { + match child { + ScanChild::Opened(reader) => { + if let Some((scan, ranges)) = context.plan_file(reader)? { + planned.push(ScanChild::Planned { scan, ranges }); + } + } + child => planned.push(child), + } + } + if planned.is_empty() { + return Ok(vec![Box::new(MultiLayoutSplitScan { + context, + children: planned, + index: 0, + })]); + } + + let n = n.get(); + let pieces: Vec> = if n <= planned.len() { + // Group whole files into contiguous pieces. + let files = planned.len(); + let mut pieces: Vec> = Vec::new(); + let mut current = None; + for (index, child) in planned.into_iter().enumerate() { + let piece = index * n / files; + if current != Some(piece) { + current = Some(piece); + pieces.push(Vec::new()); + } + if let Some(last) = pieces.last_mut() { + last.push(child); + } + } + pieces + } else { + // One piece per file, and the pieces left over cut planned files on their splits, in + // proportion to their rows. + let extra = (n - planned.len()) as u128; + let rows = |child: &ScanChild| match child { + ScanChild::Planned { ranges, .. } => ranges + .iter() + .map(|range| u128::from(range.end - range.start)) + .sum::(), + _ => 0, + }; + let total = planned.iter().map(rows).sum::().max(1); + planned + .into_iter() + .flat_map(|child| { + let pieces = 1 + usize::try_from(extra * rows(&child) / total).unwrap_or(0); + Self::split_child(child, pieces) + }) + .map(|child| vec![child]) + .collect() + }; + + Ok(pieces + .into_iter() + .enumerate() + .map(|(index, children)| { + Box::new(MultiLayoutSplitScan { + context: Arc::clone(&context), + children, + index, + }) as DataSourceScanRef + }) + .collect()) + } + + fn open(self: Box) -> VortexResult { + let MultiLayoutSplitScan { + context, children, .. + } = *self; + let request = &context.request; + if request.limit == Some(0) { + return Box::new(Empty::new(context.dtype.clone(), 0)).open(); + } + + let mut files = Vec::with_capacity(children.len()); + for child in children { + files.push(match child { + ScanChild::Opened(reader) => PoolFile::Opened(context.start_file(reader)?), + ScanChild::Planned { scan, ranges } => { + PoolFile::Opened(FileWork::start(scan, ranges)?) + } + ScanChild::Deferred(factory) => PoolFile::Deferred(factory), + }); + } + + let options = PoolOptions { + dtype: context.dtype.clone(), + ordered: request.ordered, + limit: request.limit, + has_filter: request.has_filter(), + splits_in_flight: request.split_concurrency, + }; + let prepare: PrepareFile = Arc::new(move |reader| context.start_file(reader)); + Ok(open_pool(options, files, Some(prepare))) + } +} + #[cfg(test)] mod tests { use std::sync::Arc; @@ -799,3 +1144,333 @@ mod tests { Ok(()) } } + +#[cfg(test)] +mod pool_tests { + use std::sync::Arc; + use std::sync::atomic::AtomicBool; + use std::sync::atomic::AtomicUsize; + use std::sync::atomic::Ordering; + use std::task::Context; + use std::task::Poll; + + use async_trait::async_trait; + use futures::StreamExt; + use futures::future::poll_fn; + use futures::task::ArcWake; + use futures::task::AtomicWaker; + use futures::task::noop_waker_ref; + use futures::task::waker; + use rstest::rstest; + use vortex_array::ArrayRef; + use vortex_array::dtype::Nullability; + use vortex_array::dtype::PType; + use vortex_array::expr::root; + use vortex_array::stream::SendableArrayStream; + use vortex_buffer::Buffer; + use vortex_error::VortexResult; + use vortex_io::runtime::BlockingRuntime; + use vortex_io::runtime::single::SingleThreadRuntime; + use vortex_scan::DataSource; + use vortex_scan::ScanRequest; + use vortex_scan::strict_sorted_buffer::StrictSortedBuffer; + + use super::*; + use crate::scan::test::InFlight; + use crate::scan::test::TestLayoutReader; + use crate::scan::test::collect_scan_values; + use crate::scan::test::new_session; + use crate::scan::test::read_with_one_worker; + use crate::scan::test::read_with_workers; + use crate::scan::test::session_with_handle; + + fn plan( + source: &MultiLayoutDataSource, + request: ScanRequest, + ) -> VortexResult { + futures::executor::block_on(source.scan(request)) + } + + fn i32_dtype() -> DType { + DType::Primitive(PType::I32, Nullability::NonNullable) + } + + /// A factory whose open completes only once its gate is released. + #[derive(Default)] + struct Gate { + is_open: AtomicBool, + waker: AtomicWaker, + } + + impl Gate { + fn release(&self) { + self.is_open.store(true, Ordering::SeqCst); + self.waker.wake(); + } + } + + struct GatedFactory { + reader: LayoutReaderRef, + gate: Arc, + opens: Arc, + } + + #[async_trait] + impl LayoutReaderFactory for GatedFactory { + async fn open(&self) -> VortexResult> { + self.opens.fetch_add(1, Ordering::SeqCst); + poll_fn(|cx| { + self.gate.waker.register(cx.waker()); + if self.gate.is_open.load(Ordering::SeqCst) { + Poll::Ready(()) + } else { + Poll::Pending + } + }) + .await; + Ok(Some(Arc::clone(&self.reader))) + } + } + + fn gated_factory(reader: TestLayoutReader, gate: &Arc) -> Arc { + Arc::new(GatedFactory { + reader: Arc::new(reader), + gate: Arc::clone(gate), + opens: Arc::default(), + }) + } + + /// Deferred files of `rows` one-row splits, the `i`th producing `100 * i + row`. + fn gated_source(files: usize, rows: u64) -> (MultiLayoutDataSource, Vec>) { + let gates: Vec<_> = (0..files).map(|_| Arc::new(Gate::default())).collect(); + let factories = gates + .iter() + .enumerate() + .map(|(index, gate)| { + let base = 100 * i32::try_from(index).expect("few files"); + gated_factory( + TestLayoutReader::new(rows) + .with_split_size(1) + .with_base(base), + gate, + ) + }) + .collect(); + let source = + MultiLayoutDataSource::new_deferred(i32_dtype(), factories, vec![], &new_session()); + (source, gates) + } + + #[derive(Default)] + struct WakeFlag(AtomicBool); + + impl ArcWake for WakeFlag { + fn wake_by_ref(arc_self: &Arc) { + arc_self.0.store(true, Ordering::SeqCst); + } + } + + fn poll_worker( + worker: &mut SendableArrayStream, + cx: &mut Context<'_>, + ) -> Poll>> { + worker.poll_next_unpin(cx) + } + + /// A deferred file is opened by a worker, and its splits are shared with other workers. A + /// worker that finds only an open in progress waits, and is woken when the open adds splits. + #[test] + fn deferred_file_splits_are_shared_with_waiting_workers() -> VortexResult<()> { + let (source, gates) = gated_source(1, 16); + let pool = plan(&source, ScanRequest::default())?.open()?; + let mut opener = Arc::clone(&pool).worker(); + let mut waiter = Arc::clone(&pool).worker(); + let mut noop = Context::from_waker(noop_waker_ref()); + let flag = Arc::new(WakeFlag::default()); + let flag_waker = waker(Arc::clone(&flag)); + let mut flagged = Context::from_waker(&flag_waker); + + // The opener takes the only file and blocks on its open; the waiter finds nothing to take + // but an open in progress, so it waits. + assert!(poll_worker(&mut opener, &mut noop).is_pending()); + assert!(poll_worker(&mut waiter, &mut flagged).is_pending()); + + gates[0].release(); + let Poll::Ready(Some(first)) = poll_worker(&mut opener, &mut noop) else { + panic!("the opener reads a split of the file it opened"); + }; + assert!(flag.0.load(Ordering::SeqCst), "the waiter is woken"); + + let waiter_values = collect_scan_values(futures::executor::block_on_stream(waiter))?; + let opener_values = collect_scan_values( + std::iter::once(first).chain(futures::executor::block_on_stream(opener)), + )?; + assert!( + !waiter_values.is_empty(), + "the waiter reads the opened file's splits" + ); + let mut values = [opener_values, waiter_values].concat(); + values.sort_unstable(); + assert_eq!(values, (0..16).collect::>()); + Ok(()) + } + + /// An ordered worker emits files in file order, even when a later file opens first. + #[test] + fn ordered_worker_emits_files_in_order() -> VortexResult<()> { + let (source, gates) = gated_source(3, 3); + let pool = plan( + &source, + ScanRequest { + ordered: true, + ..Default::default() + }, + )? + .open()?; + let mut worker = pool.worker(); + let mut noop = Context::from_waker(noop_waker_ref()); + assert!(poll_worker(&mut worker, &mut noop).is_pending()); + for gate in gates.iter().rev() { + gate.release(); + if !Arc::ptr_eq(gate, &gates[0]) { + assert!(poll_worker(&mut worker, &mut noop).is_pending()); + } + } + let values = collect_scan_values(futures::executor::block_on_stream(worker))?; + assert_eq!(values, [0, 1, 2, 100, 101, 102, 200, 201, 202]); + Ok(()) + } + + /// A limit is shared by every worker and file of an unordered pool. + #[test] + fn pool_limit_is_shared_across_readers() -> VortexResult<()> { + let first: LayoutReaderRef = Arc::new(TestLayoutReader::new(4).with_split_size(1)); + let gate = Arc::new(Gate::default()); + gate.release(); + let source = MultiLayoutDataSource::new_with_first( + first, + vec![gated_factory( + TestLayoutReader::new(4).with_split_size(1).with_base(10), + &gate, + )], + vec![], + &new_session(), + ); + + let pool = plan( + &source, + ScanRequest { + filter: Some(root()), + limit: Some(3), + ..Default::default() + }, + )? + .open()?; + let values = read_with_workers(&pool, 3)?.concat(); + + assert_eq!(values.len(), 3); + Ok(()) + } + + /// Splitting cuts opened files on their splits and keeps deferred files whole, in order. + #[test] + fn split_cuts_opened_files_and_keeps_deferred_files_whole() -> VortexResult<()> { + let first: LayoutReaderRef = Arc::new(TestLayoutReader::new(6).with_split_size(2)); + let opens = Arc::new(AtomicUsize::new(0)); + let gate = Arc::new(Gate::default()); + gate.release(); + let source = MultiLayoutDataSource::new_with_first( + first, + vec![Arc::new(GatedFactory { + reader: Arc::new(TestLayoutReader::new(4).with_split_size(2).with_base(100)), + gate, + opens: Arc::clone(&opens), + })], + vec![], + &new_session(), + ); + let scan = plan( + &source, + ScanRequest { + ordered: true, + ..Default::default() + }, + )?; + let pieces = scan.split(NonZeroUsize::new(4).expect("non-zero"))?; + assert_eq!(opens.load(Ordering::SeqCst), 0, "splitting opens no file"); + // The opened file's three splits take three pieces; the deferred file stays whole. + assert_eq!(pieces.len(), 4); + + let mut values = Vec::new(); + for piece in pieces { + values.extend(read_with_one_worker(piece.open()?)?); + } + assert_eq!(values, [0, 1, 2, 3, 4, 5, 100, 101, 102, 103]); + Ok(()) + } + + /// A request that selects partitions is split and opened by its partitions, so both paths + /// read the same files. + #[rstest] + #[case::range(Some(1..2), None)] + #[case::selection(None, Some(1))] + fn selected_partitions_open_by_partition( + #[case] partition_range: Option>, + #[case] selected_partition: Option, + ) -> VortexResult<()> { + let partition_selection = match selected_partition { + Some(index) => { + Selection::IncludeByIndex(StrictSortedBuffer::try_new(Buffer::from_iter([index]))?) + } + None => Selection::All, + }; + // The partitions path spawns file opens onto the session's runtime. + let runtime = SingleThreadRuntime::default(); + let gate = Arc::new(Gate::default()); + gate.release(); + let source = MultiLayoutDataSource::new_with_first( + Arc::new(TestLayoutReader::new(3)), + vec![gated_factory(TestLayoutReader::new(3).with_base(10), &gate)], + vec![], + &session_with_handle(runtime.handle()), + ); + let request = ScanRequest { + partition_range, + partition_selection, + ordered: true, + ..Default::default() + }; + let pieces = plan(&source, request.clone())?.split(NonZeroUsize::new(4).expect("4"))?; + assert_eq!(pieces.len(), 1); + let pool = plan(&source, request)?.open()?; + let values = collect_scan_values(runtime.block_on_stream(pool.worker()))?; + assert_eq!(values, [10, 11, 12]); + Ok(()) + } + + /// A worker reads at most `split_concurrency` splits at once. + #[rstest] + #[case(1)] + #[case(2)] + fn split_concurrency_bounds_each_worker(#[case] max: usize) -> VortexResult<()> { + let in_flight = Arc::new(InFlight::default()); + let reader: LayoutReaderRef = Arc::new( + TestLayoutReader::new(64) + .with_split_size(1) + .with_in_flight(Arc::clone(&in_flight)), + ); + let source = MultiLayoutDataSource::new_with_first(reader, vec![], vec![], &new_session()); + let pool = plan( + &source, + ScanRequest { + ordered: true, + split_concurrency: NonZeroUsize::new(max), + ..Default::default() + }, + )? + .open()?; + assert_eq!(read_with_one_worker(pool)?, (0..64).collect::>()); + assert!(in_flight.peak() <= max, "peak {}", in_flight.peak()); + Ok(()) + } +} diff --git a/vortex-layout/src/scan/pool.rs b/vortex-layout/src/scan/pool.rs new file mode 100644 index 00000000000..fcfea905b7a --- /dev/null +++ b/vortex-layout/src/scan/pool.rs @@ -0,0 +1,480 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! The work that the workers of an opened layout scan share. +//! +//! A pool's units are the splits of one or more files, and the files not yet opened. A worker +//! takes units and keeps up to `splits_in_flight` of them running on its own thread: it +//! builds a split's task only when it takes the split, and never spawns. Opening a deferred file +//! is a unit like any other. +//! +//! - An unordered pool hands units out through a channel. The worker that opens a deferred file +//! sends the file's splits back into the channel, where any worker can take them. The channel +//! closes once every open has finished, which ends the workers. +//! - An ordered pool gives all of its units, in row order, to its first worker; later workers +//! get nothing. Parallel ordered reads cut the scan with `split` first. + +use std::any::Any; +use std::num::NonZeroUsize; +use std::ops::Range; +use std::sync::Arc; + +use async_channel::Receiver; +use async_channel::Sender; +use futures::FutureExt; +use futures::StreamExt; +use futures::future; +use futures::future::BoxFuture; +use futures::stream; +use futures::stream::BoxStream; +use parking_lot::Mutex; +use tracing::Instrument; +use vortex_array::ArrayRef; +use vortex_array::dtype::DType; +use vortex_array::expr::stats::Precision; +use vortex_array::stream::ArrayStreamAdapter; +use vortex_array::stream::ArrayStreamExt; +use vortex_array::stream::SendableArrayStream; +use vortex_error::VortexResult; +use vortex_scan::DataSourceScanRef; +use vortex_scan::Partition; +use vortex_scan::PartitionRef; +use vortex_scan::PartitionStream; +use vortex_scan::pool::ScanPool; +use vortex_scan::pool::ScanPoolRef; +use vortex_scan::row_mask::RowMask; + +use crate::LayoutReaderRef; +use crate::scan::limit::RowLimit; +use crate::scan::multi::LayoutReaderFactory; +use crate::scan::repeated_scan::RepeatedScan; +use crate::scan::repeated_scan::can_prune_file; +use crate::scan::tasks::TaskContext; + +/// A scan prepared once and shared by every piece and execution of it. +pub(crate) type PreparedScan = RepeatedScan; + +/// A prepared scan and the row ranges of its splits, in row order. +pub(crate) type PlannedSplits = (Arc, Vec>); + +/// The most splits each worker keeps in flight when the request does not say; stands in for the +/// scan engine's memory budget. +const SPLITS_IN_FLIGHT_PER_WORKER: usize = 4; + +/// One execution of one file's prepared scan. +pub(crate) struct FileScan { + scan: Arc, + /// Records this execution's events, so file events count once for each execution. + ctx: Arc, +} + +/// One file's splits for one execution, ready to be handed to workers. +pub(crate) struct FileWork { + scan: Option>, + ranges: Vec>, +} + +impl FileWork { + /// A file with nothing to read, for example one that statistics pruned. + pub(crate) fn empty() -> Self { + Self { + scan: None, + ranges: Vec::new(), + } + } + + /// Starts an execution of `scan` over its split `ranges`. + /// + /// Counts a file scan attempt when the ranges select any row, and returns no work when + /// whole-file statistics reject the filter. + pub(crate) fn start(scan: Arc, ranges: Vec>) -> VortexResult { + if !ranges.iter().any(|range| scan.selects_rows(range)) { + return Ok(Self::empty()); + } + let ctx = scan.task_context(); + if can_prune_file(&ctx)? { + return Ok(Self::empty()); + } + Ok(Self { + scan: Some(Arc::new(FileScan { scan, ctx })), + ranges, + }) + } +} + +/// Opens a deferred file's reader into its work for this execution. +pub(crate) type PrepareFile = Arc VortexResult + Send + Sync>; + +/// A file of a pool, in file order. +pub(crate) enum PoolFile { + Opened(FileWork), + Deferred(Arc), +} + +/// How a pool reads its splits. +pub(crate) struct PoolOptions { + pub(crate) dtype: DType, + pub(crate) ordered: bool, + pub(crate) limit: Option, + /// Whether the scan filters rows, so a split's output row count is unknown up front. + pub(crate) has_filter: bool, + /// The most splits each worker keeps in flight, or the default when `None`. + pub(crate) splits_in_flight: Option, +} + +/// Opens a pool over `files`, in file order. `prepare` turns an opened deferred file into work. +pub(crate) fn open_pool( + options: PoolOptions, + files: Vec, + prepare: Option, +) -> ScanPoolRef { + let limit = match options.limit { + None => PoolLimit::Unlimited, + Some(limit) if options.has_filter => PoolLimit::Trim(RowLimit::new(limit)), + Some(limit) => PoolLimit::Reserve(RowLimit::new(limit)), + }; + let splits_in_flight = options + .splits_in_flight + .map_or(SPLITS_IN_FLIGHT_PER_WORKER, NonZeroUsize::get); + let shared = Arc::new(Shared { + limit, + prepare, + file_share: 1.0 / files.len().max(1) as f64, + progress: Mutex::new(0.0), + }); + if options.ordered { + return Arc::new(OrderedPool { + dtype: options.dtype, + shared, + files: Mutex::new(Some(files)), + splits_in_flight, + }); + } + + let (sender, receiver) = async_channel::unbounded(); + for file in files { + match file { + PoolFile::Opened(work) => { + for (file, range, progress) in shared.file_splits(work) { + send(&sender, Work::Split(file, range, progress)); + } + } + PoolFile::Deferred(factory) => send(&sender, Work::Open(factory, sender.clone())), + } + } + Arc::new(UnorderedPool { + dtype: options.dtype, + shared, + receiver, + splits_in_flight, + }) +} + +/// How a pool's row limit is applied. +enum PoolLimit { + Unlimited, + /// A split's selected rows are its output rows, so each split reserves them from the budget + /// when a worker takes it, and rows past the limit are never decoded. Admission order is + /// row order for an ordered pool, so it returns exactly the first rows. + Reserve(RowLimit), + /// A split's output rows are unknown until its filter has run, so workers take rows from the + /// budget as they yield them and discard the excess. + Trim(RowLimit), +} + +impl PoolLimit { + fn is_exhausted(&self) -> bool { + match self { + PoolLimit::Unlimited => false, + PoolLimit::Reserve(limit) | PoolLimit::Trim(limit) => limit.is_exhausted(), + } + } +} + +/// A split's output: `None` when it has no rows to return. +type SplitFuture = BoxFuture<'static, VortexResult>>; + +/// A split of a file, with the progress that taking it adds. +type FileSplit = (Arc, Range, f64); + +/// What every worker of a pool shares. +struct Shared { + limit: PoolLimit, + prepare: Option, + /// The progress that one file adds. + file_share: f64, + progress: Mutex, +} + +impl Shared { + /// The splits of an opened file, in row order. + fn file_splits(&self, work: FileWork) -> Vec { + let rows: u64 = work + .ranges + .iter() + .map(|range| range.end - range.start) + .sum(); + match work.scan { + Some(scan) if rows > 0 => { + let per_row = self.file_share / rows as f64; + work.ranges + .into_iter() + .map(|range| { + let progress = per_row * (range.end - range.start) as f64; + (Arc::clone(&scan), range, progress) + }) + .collect() + } + _ => { + *self.progress.lock() += self.file_share; + Vec::new() + } + } + } + + /// Opens a deferred file into its work. + fn open_file( + self: &Arc, + factory: Arc, + ) -> BoxFuture<'static, VortexResult> { + let shared = Arc::clone(self); + async move { + let reader = factory + .open() + .instrument(tracing::info_span!("LayoutReaderFactory::open")) + .await?; + match (reader, &shared.prepare) { + (Some(reader), Some(prepare)) => prepare(reader), + _ => Ok(FileWork::empty()), + } + } + .boxed() + } + + /// Takes a split: reserves its rows from a reserved limit and builds its task. + fn admit(&self, (file, range, progress): FileSplit) -> SplitFuture { + *self.progress.lock() += progress; + let Some(mask) = file.scan.split_mask(&range) else { + return future::ready(Ok(None)).boxed(); + }; + let mask = match &self.limit { + PoolLimit::Reserve(limit) => { + let reserved = limit.limit(mask.mask().clone()); + if reserved.all_false() { + return future::ready(Ok(None)).boxed(); + } + RowMask::new(range.start, reserved) + } + PoolLimit::Unlimited | PoolLimit::Trim(_) => mask, + }; + match file.scan.split_task(&file.ctx, mask) { + Ok(task) => task, + Err(err) => future::ready(Err(err)).boxed(), + } + } + + #[expect( + dead_code, + reason = "read by ScanPool::progress, which arrives with its first host" + )] + fn progress(&self) -> f64 { + if self.limit.is_exhausted() { + return 1.0; + } + self.progress.lock().clamp(0.0, 1.0) + } +} + +/// A worker's output: skips splits with no rows, trims to a trimmed limit, and ends after the +/// first error or once a trimmed limit is spent. +fn limit_output( + outputs: BoxStream<'static, VortexResult>>, + shared: Arc, +) -> BoxStream<'static, VortexResult> { + stream::unfold(Some(outputs), move |outputs| { + let shared = Arc::clone(&shared); + async move { + let mut outputs = outputs?; + loop { + if let PoolLimit::Trim(limit) = &shared.limit + && limit.is_exhausted() + { + return None; + } + let array = match outputs.next().await? { + Ok(Some(array)) => array, + Ok(None) => continue, + Err(err) => return Some((Err(err), None)), + }; + let PoolLimit::Trim(limit) = &shared.limit else { + return Some((Ok(array), Some(outputs))); + }; + let granted = limit.take(array.len()); + if granted == 0 { + return None; + } + if granted == array.len() { + return Some((Ok(array), Some(outputs))); + } + return Some((array.slice(0..granted), None)); + } + } + }) + .boxed() +} + +/// A unit of an unordered pool. +enum Work { + Split(Arc, Range, f64), + /// A deferred file, and where to send its splits once it is open. The sender keeps the + /// channel open until the file's splits are in it. + Open(Arc, Sender), +} + +fn send(sender: &Sender, work: Work) { + // The channel is unbounded and closes only once the pool is dropped, when the work is moot. + drop(sender.try_send(work)); +} + +/// A pool whose workers share its units through a channel. +struct UnorderedPool { + dtype: DType, + shared: Arc, + receiver: Receiver, + splits_in_flight: usize, +} + +impl UnorderedPool { + fn run(shared: &Arc, work: Work) -> SplitFuture { + match work { + Work::Split(file, range, progress) => shared.admit((file, range, progress)), + Work::Open(factory, sender) => { + let shared = Arc::clone(shared); + async move { + let work = shared.open_file(factory).await?; + for (file, range, progress) in shared.file_splits(work) { + send(&sender, Work::Split(file, range, progress)); + } + Ok(None) + } + .boxed() + } + } + } +} + +impl ScanPool for UnorderedPool { + fn dtype(&self) -> &DType { + &self.dtype + } + + fn worker(self: Arc) -> SendableArrayStream { + let dtype = self.dtype.clone(); + let shared = Arc::clone(&self.shared); + let runner = Arc::clone(&shared); + let receiver = self.receiver.clone(); + let splits_in_flight = self.splits_in_flight; + // The worker holds the pool, so the pool is dropped only after its last worker. + let outputs = receiver + .take_while(move |_| future::ready(!self.shared.limit.is_exhausted())) + .map(move |work| UnorderedPool::run(&runner, work)) + .buffer_unordered(splits_in_flight) + .boxed(); + ArrayStreamExt::boxed(ArrayStreamAdapter::new( + dtype, + limit_output(outputs, shared), + )) + } +} + +impl Drop for UnorderedPool { + fn drop(&mut self) { + // Pending opens hold senders of the channel itself; drain them so it can be freed. + self.receiver.close(); + while self.receiver.try_recv().is_ok() {} + } +} + +/// A pool that gives all of its units, in row order, to its first worker. +struct OrderedPool { + dtype: DType, + shared: Arc, + /// The files, until the first worker takes them. + files: Mutex>>, + splits_in_flight: usize, +} + +impl ScanPool for OrderedPool { + fn dtype(&self) -> &DType { + &self.dtype + } + + fn worker(self: Arc) -> SendableArrayStream { + let dtype = self.dtype.clone(); + let Some(files) = self.files.lock().take() else { + return ArrayStreamExt::boxed(ArrayStreamAdapter::new(dtype, stream::empty())); + }; + let shared = Arc::clone(&self.shared); + let opener = Arc::clone(&shared); + let splitter = Arc::clone(&shared); + let admitter = Arc::clone(&shared); + let outputs = stream::iter(files) + .then(move |file| match file { + PoolFile::Opened(work) => future::ready(Ok(work)).boxed(), + PoolFile::Deferred(factory) => opener.open_file(factory), + }) + .flat_map(move |work| match work { + Ok(work) => { + stream::iter(splitter.file_splits(work).into_iter().map(Ok)).left_stream() + } + Err(err) => stream::once(future::ready(Err(err))).right_stream(), + }) + .take_while(move |_| future::ready(!shared.limit.is_exhausted())) + .map(move |split| match split { + Ok(split) => admitter.admit(split), + Err(err) => future::ready(Err(err)).boxed(), + }) + .buffered(self.splits_in_flight) + .boxed(); + ArrayStreamExt::boxed(ArrayStreamAdapter::new( + dtype, + limit_output(outputs, Arc::clone(&self.shared)), + )) + } +} + +/// The single partition of a scan piece that is read through the partitions API: it opens the +/// piece and reads it with one worker. +pub(crate) struct PiecePartition { + piece: DataSourceScanRef, + index: usize, +} + +impl PiecePartition { + /// The partitions of `piece`: one, whose index is `index`. + pub(crate) fn stream(piece: DataSourceScanRef, index: usize) -> PartitionStream { + stream::iter([Ok(Box::new(PiecePartition { piece, index }) as PartitionRef)]).boxed() + } +} + +impl Partition for PiecePartition { + fn as_any(&self) -> &dyn Any { + self + } + + fn index(&self) -> usize { + self.index + } + + fn row_count(&self) -> Precision { + self.piece.row_count() + } + + fn byte_size(&self) -> Precision { + self.piece.byte_size() + } + + fn execute(self: Box) -> VortexResult { + Ok(self.piece.open()?.worker()) + } +} diff --git a/vortex-layout/src/scan/repeated_scan.rs b/vortex-layout/src/scan/repeated_scan.rs index 2a1c7026923..dcd4cba58c8 100644 --- a/vortex-layout/src/scan/repeated_scan.rs +++ b/vortex-layout/src/scan/repeated_scan.rs @@ -175,7 +175,7 @@ impl RepeatedScan { } /// Each execution gets its own recorder, so file events count once for each execution. - fn task_context(&self) -> Arc { + pub(crate) fn task_context(&self) -> Arc { Arc::new(TaskContext { filter: self .filter @@ -188,7 +188,10 @@ impl RepeatedScan { }) } - fn split_ranges(&self, row_range: Option>) -> Vec> { + /// The row ranges of the scan's splits within `row_range`, in row order. + /// + /// Ranges whose rows the selection excludes are included; [`Self::split_mask`] skips them. + pub(crate) fn split_ranges(&self, row_range: Option>) -> Vec> { let selection_range: Option> = match &self.selection { Selection::IncludeByIndex(buf) if !buf.is_empty() => { Some(buf[0]..buf[buf.len() - 1] + 1) @@ -244,6 +247,33 @@ impl RepeatedScan { } } + /// Whether the selection includes any row of `range`. + pub(crate) fn selects_rows(&self, range: &Range) -> bool { + self.selection.row_count_in_range(range) != 0 + } + + /// The number of rows of `range` that the selection includes. + pub(crate) fn selected_row_count(&self, range: &Range) -> u64 { + self.selection.row_count_in_range(range) + } + + /// The selected rows of the split over `range`, or `None` if the selection excludes them all. + pub(crate) fn split_mask(&self, range: &Range) -> Option { + selected_mask(&self.selection, range) + } + + /// Builds the task of one split. The task does no work until it is polled, but building it + /// may register the split's reads with the reader, so build it only when it is about to run. + /// + /// `mask` must select at least one row. + pub(crate) fn split_task( + &self, + ctx: &Arc, + mask: RowMask, + ) -> VortexResult>>> { + Ok(map_split(split_exec(ctx, mask)?, &self.map_fn)) + } + /// The non-empty row masks of the splits within `row_range`, in split order. fn split_masks(&self, row_range: Option>) -> impl Iterator + '_ { self.split_ranges(row_range) @@ -362,7 +392,8 @@ fn selected_mask(selection: &Selection, range: &Range) -> Option { (!mask.mask().all_false()).then_some(mask) } -fn can_prune_file(ctx: &TaskContext) -> VortexResult { +/// Counts a file scan attempt and returns whether whole-file statistics reject the filter. +pub(crate) fn can_prune_file(ctx: &TaskContext) -> VortexResult { ctx.count::(ScanRecorder::attempt_file_scan); if let Some(filter) = &ctx.filter && can_prune_conjuncts(filter, ctx.reader.as_ref())? diff --git a/vortex-layout/src/scan/test.rs b/vortex-layout/src/scan/test.rs index 85c4b25d8b1..41c9ce19e1e 100644 --- a/vortex-layout/src/scan/test.rs +++ b/vortex-layout/src/scan/test.rs @@ -27,6 +27,7 @@ use vortex_io::runtime::single::SingleThreadRuntime; use vortex_io::session::RuntimeSession; use vortex_io::session::RuntimeSessionExt; use vortex_mask::Mask; +use vortex_scan::pool::ScanPoolRef; use vortex_session::VortexSession; use crate::ArrayFuture; @@ -70,6 +71,7 @@ pub struct TestLayoutReader { projection_masks: Option>>>, filter_exprs: Option>>>, in_flight: Option>, + yields: fn(u64) -> usize, } /// Counts projections running at once, and the most that ever were. @@ -101,6 +103,7 @@ impl TestLayoutReader { projection_masks: None, filter_exprs: None, in_flight: None, + yields: |_| 0, } } @@ -137,6 +140,13 @@ impl TestLayoutReader { self } + /// Makes the projection of the split starting at row `start` yield `yields(start)` times + /// before it finishes, so tests can make splits complete out of row order. + pub fn with_yields(mut self, yields: fn(u64) -> usize) -> Self { + self.yields = yields; + self + } + pub fn with_filter_exprs(mut self, filter_exprs: Arc>>) -> Self { self.filter_exprs = Some(filter_exprs); self @@ -261,8 +271,12 @@ impl LayoutReader for TestLayoutReader { let projection_masks = self.projection_masks.clone(); let fail = self.fail_projection || (self.fail_first_projection && row_range.start == 0); let in_flight = self.in_flight.clone(); + let yields = (self.yields)(row_range.start); Ok(Box::pin(async move { + for _ in 0..yields { + tokio::task::yield_now().await; + } if let Some(in_flight) = &in_flight { let now = in_flight.now.fetch_add(1, Ordering::SeqCst) + 1; in_flight.peak.fetch_max(now, Ordering::SeqCst); @@ -313,6 +327,28 @@ where Ok(values) } +/// Reads `pool` with `workers` workers, each polled on its own thread, returning each worker's +/// values in the order it yielded them. +pub fn read_with_workers(pool: &ScanPoolRef, workers: usize) -> VortexResult>> { + std::thread::scope(|scope| { + let handles = (0..workers) + .map(|_| { + let worker = Arc::clone(pool).worker(); + scope.spawn(move || collect_scan_values(futures::executor::block_on_stream(worker))) + }) + .collect::>(); + handles + .into_iter() + .map(|handle| handle.join().expect("worker thread panicked")) + .collect() + }) +} + +/// Reads `pool` with a single worker polled on the calling thread. +pub fn read_with_one_worker(pool: ScanPoolRef) -> VortexResult> { + collect_scan_values(futures::executor::block_on_stream(pool.worker())) +} + /// Let already-spawned scan tasks run to completion after the stream has been dropped. pub fn drain_runtime(runtime: &SingleThreadRuntime) { for _ in 0..4 { From d300a84cd3ad7416f0cb111c5a16e5586046a7a2 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Thu, 19 Nov 2026 18:30:06 -0500 Subject: [PATCH 02/25] Spawn pool splits onto the session runtime Decoding a split inline kept each worker's splits on its own thread. Spawning them onto the session's runtime, as V1 scans do, lets idle runtime threads decode them and starts their I/O at once. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-layout/src/scan/pool.rs | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/vortex-layout/src/scan/pool.rs b/vortex-layout/src/scan/pool.rs index fcfea905b7a..c5f09310d45 100644 --- a/vortex-layout/src/scan/pool.rs +++ b/vortex-layout/src/scan/pool.rs @@ -4,9 +4,8 @@ //! The work that the workers of an opened layout scan share. //! //! A pool's units are the splits of one or more files, and the files not yet opened. A worker -//! takes units and keeps up to `splits_in_flight` of them running on its own thread: it -//! builds a split's task only when it takes the split, and never spawns. Opening a deferred file -//! is a unit like any other. +//! takes units and keeps up to `splits_in_flight` of them in flight, each spawned onto the +//! session's runtime when the worker takes it. Opening a deferred file is a unit like any other. //! //! - An unordered pool hands units out through a channel. The worker that opens a deferred file //! sends the file's splits back into the channel, where any worker can take them. The channel @@ -36,6 +35,7 @@ use vortex_array::stream::ArrayStreamAdapter; use vortex_array::stream::ArrayStreamExt; use vortex_array::stream::SendableArrayStream; use vortex_error::VortexResult; +use vortex_io::session::RuntimeSessionExt; use vortex_scan::DataSourceScanRef; use vortex_scan::Partition; use vortex_scan::PartitionRef; @@ -251,7 +251,7 @@ impl Shared { .boxed() } - /// Takes a split: reserves its rows from a reserved limit and builds its task. + /// Takes a split: reserves its rows from a reserved limit and spawns its task. fn admit(&self, (file, range, progress): FileSplit) -> SplitFuture { *self.progress.lock() += progress; let Some(mask) = file.scan.split_mask(&range) else { @@ -267,10 +267,12 @@ impl Shared { } PoolLimit::Unlimited | PoolLimit::Trim(_) => mask, }; - match file.scan.split_task(&file.ctx, mask) { - Ok(task) => task, - Err(err) => future::ready(Err(err)).boxed(), - } + // Spawned onto the session's runtime, as V1 scans do: another runtime thread may decode + // it while this worker drives its other splits, and its I/O starts right away. + let handle = file.ctx.session.handle(); + handle + .spawn(async move { file.scan.split_task(&file.ctx, mask)?.await }) + .boxed() } #[expect( From f1bf5cfd552566d0a0d63c0d9b619e7b3d48cffb Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Thu, 19 Nov 2026 18:58:00 -0500 Subject: [PATCH 03/25] Drive layout pool tests with a background runtime Pool splits are spawned onto the session runtime, so the test session needs a runtime that runs them while test workers block on their streams. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-layout/src/scan/layout.rs | 4 +++- vortex-layout/src/scan/multi.rs | 3 ++- vortex-layout/src/scan/test.rs | 12 ++++++++++++ 3 files changed, 17 insertions(+), 2 deletions(-) diff --git a/vortex-layout/src/scan/layout.rs b/vortex-layout/src/scan/layout.rs index 926ea7cc8e8..0413edff9c6 100644 --- a/vortex-layout/src/scan/layout.rs +++ b/vortex-layout/src/scan/layout.rs @@ -1071,7 +1071,9 @@ mod pool_tests { let mut values = Vec::new(); for piece in pieces { - let piece_values = read_with_one_worker(piece.open()?)?; + // The scan is unordered, so a piece's splits may finish in any order. + let mut piece_values = read_with_one_worker(piece.open()?)?; + piece_values.sort_unstable(); let first = *piece_values.first().expect("pieces are not empty"); let last = *piece_values.last().expect("pieces are not empty"); assert_eq!(first % 3, 0, "piece starts on a split boundary"); diff --git a/vortex-layout/src/scan/multi.rs b/vortex-layout/src/scan/multi.rs index be41497e0ad..5acaa3a9063 100644 --- a/vortex-layout/src/scan/multi.rs +++ b/vortex-layout/src/scan/multi.rs @@ -1296,7 +1296,8 @@ mod pool_tests { assert!(poll_worker(&mut waiter, &mut flagged).is_pending()); gates[0].release(); - let Poll::Ready(Some(first)) = poll_worker(&mut opener, &mut noop) else { + // The opener's split runs on the session runtime, so wait for it rather than polling once. + let Some(first) = futures::executor::block_on(opener.next()) else { panic!("the opener reads a split of the file it opened"); }; assert!(flag.0.load(Ordering::SeqCst), "the waiter is woken"); diff --git a/vortex-layout/src/scan/test.rs b/vortex-layout/src/scan/test.rs index 41c9ce19e1e..3e0b70465e6 100644 --- a/vortex-layout/src/scan/test.rs +++ b/vortex-layout/src/scan/test.rs @@ -23,6 +23,8 @@ use vortex_error::VortexResult; use vortex_error::vortex_err; use vortex_io::runtime::BlockingRuntime; use vortex_io::runtime::Handle; +use vortex_io::runtime::current::CurrentThreadRuntime; +use vortex_io::runtime::current::CurrentThreadWorkerPool; use vortex_io::runtime::single::SingleThreadRuntime; use vortex_io::session::RuntimeSession; use vortex_io::session::RuntimeSessionExt; @@ -38,10 +40,20 @@ use crate::session::LayoutSession; static SESSION: LazyLock = LazyLock::new(VortexSession::empty); +/// A runtime driven by background threads, so splits the pools spawn make progress while test +/// workers block on their streams with `futures::executor`. +static RUNTIME: LazyLock<(CurrentThreadRuntime, CurrentThreadWorkerPool)> = LazyLock::new(|| { + let runtime = CurrentThreadRuntime::new(); + let pool = runtime.new_pool(); + pool.set_workers(4); + (runtime, pool) +}); + pub fn new_session() -> VortexSession { VortexSession::empty() .with::() .with::() + .with_handle(RUNTIME.0.handle()) } pub fn session_with_handle(handle: Handle) -> VortexSession { From d10623da315dd2f044c978c357bc53b115fb8143 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Thu, 19 Nov 2026 19:09:33 -0500 Subject: [PATCH 04/25] Run pool splits the way execute_stream runs them A benchmark of the pool should measure the pool, not a different way of running splits. Pools now build a file's split tasks all at once when a worker first takes one, so the file's reads register together and coalesce, as execute_stream builds a partition's tasks up front. Scans with a filter and a limit build each split lazily on a CPU task and optimize the trimmed output on a second one, through the same helpers execute_stream now uses. A worker keeps as many splits in flight as one partition stream does by default (four per core, capped by split_concurrency), so a host with a worker per core matches the partitions path's in-flight total. Deferred files open on the session runtime, at most the source's open concurrency at once, in both pool kinds. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-layout/src/scan/layout.rs | 92 +++++- vortex-layout/src/scan/multi.rs | 82 +++++- vortex-layout/src/scan/pool.rs | 358 +++++++++++++++++------- vortex-layout/src/scan/repeated_scan.rs | 68 +++-- vortex-layout/src/scan/scan_builder.rs | 5 +- vortex-layout/src/scan/test.rs | 11 + 6 files changed, 481 insertions(+), 135 deletions(-) diff --git a/vortex-layout/src/scan/layout.rs b/vortex-layout/src/scan/layout.rs index 0413edff9c6..38f801fd9a9 100644 --- a/vortex-layout/src/scan/layout.rs +++ b/vortex-layout/src/scan/layout.rs @@ -57,7 +57,7 @@ use crate::scan::scan_builder::ScanBuilder; /// /// When a scan is [split](DataSourceScan::split) or [opened](DataSourceScan::open), its units are /// the layout's splits. Workers of an opened scan share them, each keeping several in flight on -/// its own thread. +/// the session's runtime. pub struct LayoutReaderDataSource { reader: LayoutReaderRef, session: VortexSession, @@ -258,11 +258,12 @@ impl LayoutReaderScan { fn into_split_scan(self) -> VortexResult { let row_count = DataSourceScan::row_count(&self); let options = LayoutScanOptions { + session: self.session.clone(), dtype: self.dtype, ordered: self.ordered, limit: self.limit, has_filter: self.filter.is_some(), - splits_in_flight: self.split_concurrency, + split_concurrency: self.split_concurrency, }; let row_range = clamp_row_range(self.next_row..self.end_row, self.reader.row_count()); let scan = ScanBuilder::new(self.session, self.reader) @@ -331,11 +332,12 @@ fn clamp_row_range(row_range: Range, total_rows: u64) -> Range { /// What a [`LayoutSplitScan`] and every piece cut from it share. #[derive(Clone)] struct LayoutScanOptions { + session: VortexSession, dtype: DType, ordered: bool, limit: Option, has_filter: bool, - splits_in_flight: Option, + split_concurrency: Option, } /// A prepared scan of one layout reader over some of its splits: a [`LayoutReaderScan`] that was @@ -413,22 +415,26 @@ impl DataSourceScan for LayoutSplitScan { fn open(self: Box) -> VortexResult { let LayoutScanOptions { + session, dtype, ordered, limit, has_filter, - splits_in_flight, + split_concurrency, } = self.options; if limit == Some(0) { return Box::new(Empty::new(dtype, 0)).open(); } let work = FileWork::start(self.scan, self.ranges)?; let options = PoolOptions { + session, dtype, ordered, limit, has_filter, - splits_in_flight, + split_concurrency, + // A single opened file has nothing to open. + open_concurrency: 1, }; Ok(open_pool(options, vec![PoolFile::Opened(work)], None)) } @@ -838,7 +844,10 @@ mod tests { mod pool_tests { use std::num::NonZeroUsize; use std::sync::Arc; + use std::sync::atomic::AtomicUsize; + use std::sync::atomic::Ordering; + use futures::StreamExt; use rstest::rstest; use vortex_array::dtype::DType; use vortex_array::dtype::Nullability; @@ -987,6 +996,79 @@ mod pool_tests { Ok(()) } + /// Split tasks are built as `execute_stream` builds them: all of a file's at once, so their + /// reads are registered together, when a worker takes its first split; but one at a time, as + /// workers take them, when the scan has both a filter and a limit. + #[rstest] + #[case::unfiltered(None, None, true)] + #[case::filtered(Some(root()), None, true)] + #[case::limited(None, Some(1000), true)] + #[case::filtered_and_limited(Some(root()), Some(1000), false)] + fn split_tasks_build_like_execute_stream( + #[case] filter: Option, + #[case] limit: Option, + #[case] up_front: bool, + ) -> VortexResult<()> { + let built = Arc::new(AtomicUsize::new(0)); + let source = source( + TestLayoutReader::new(16) + .with_split_size(1) + .with_built_projections(Arc::clone(&built)), + ); + let pool = plan( + &source, + ScanRequest { + filter, + limit, + split_concurrency: NonZeroUsize::new(1), + ..Default::default() + }, + )? + .open()?; + let mut worker = Arc::clone(&pool).worker(); + assert!(futures::executor::block_on(worker.next()).is_some()); + let built_after_first = built.load(Ordering::SeqCst); + if up_front { + assert_eq!(built_after_first, 16); + } else { + assert!( + built_after_first < 16, + "built {built_after_first} splits up front" + ); + } + + let rest = collect_scan_values(futures::executor::block_on_stream(worker))?; + assert_eq!(rest.len(), 15); + assert_eq!(built.load(Ordering::SeqCst), 16); + Ok(()) + } + + /// A pool reports the share of its splits that workers have taken, and is exhausted once + /// none are left to take. + #[rstest] + #[case::ordered(true)] + #[case::unordered(false)] + fn pools_report_progress_and_exhaustion(#[case] ordered: bool) -> VortexResult<()> { + let source = source(TestLayoutReader::new(8).with_split_size(2)); + let pool = plan( + &source, + ScanRequest { + ordered, + ..Default::default() + }, + )? + .open()?; + assert_eq!(pool.progress(), 0.0); + assert!(!pool.is_exhausted()); + + let values = read_with_one_worker(Arc::clone(&pool))?; + assert_eq!(values.len(), 8); + assert_eq!(pool.progress(), 1.0); + assert!(pool.is_exhausted()); + assert!(read_with_one_worker(pool)?.is_empty()); + Ok(()) + } + /// An ordered pool with a limit returns exactly the first `limit` rows. #[rstest] #[case::reserved(false, &[0, 1, 2, 3, 4])] diff --git a/vortex-layout/src/scan/multi.rs b/vortex-layout/src/scan/multi.rs index 5acaa3a9063..0ae1db43e65 100644 --- a/vortex-layout/src/scan/multi.rs +++ b/vortex-layout/src/scan/multi.rs @@ -221,8 +221,8 @@ impl MultiLayoutDataSource { /// Sets the concurrency for opening deferred readers. /// - /// Controls how many file opens run in parallel via `buffer_unordered`. - /// Defaults to the number of available CPU cores. + /// Controls how many file opens run in parallel, on the partitions path and in an opened + /// scan's pool alike. Defaults to the number of available CPU cores. pub fn with_concurrency(mut self, concurrency: usize) -> Self { self.concurrency = concurrency; self @@ -424,6 +424,7 @@ impl MultiLayoutScan { source_dtype: self.source_dtype, dtype: self.dtype, request: self.request, + open_concurrency: self.concurrency, }), children, index: 0, @@ -736,6 +737,8 @@ struct ScanContext { source_dtype: DType, dtype: DType, request: BoundScanRequest, + /// The most deferred files that are opened at once. + open_concurrency: usize, } impl ScanContext { @@ -957,11 +960,13 @@ impl DataSourceScan for MultiLayoutSplitScan { } let options = PoolOptions { + session: context.session.clone(), dtype: context.dtype.clone(), ordered: request.ordered, limit: request.limit, has_filter: request.has_filter(), - splits_in_flight: request.split_concurrency, + split_concurrency: request.split_concurrency, + open_concurrency: context.open_concurrency, }; let prepare: PrepareFile = Arc::new(move |reader| context.start_file(reader)); Ok(open_pool(options, files, Some(prepare))) @@ -1277,12 +1282,81 @@ mod pool_tests { worker.poll_next_unpin(cx) } + /// An unordered pool opens at most the source's open concurrency of deferred files at once, + /// however many workers are waiting for splits. + #[test] + fn deferred_opens_are_bounded() -> VortexResult<()> { + let opens = Arc::new(AtomicUsize::new(0)); + let gates: Vec<_> = (0..6).map(|_| Arc::new(Gate::default())).collect(); + let factories = gates + .iter() + .enumerate() + .map(|(index, gate)| { + let base = 100 * i32::try_from(index).expect("few files"); + Arc::new(GatedFactory { + reader: Arc::new(TestLayoutReader::new(4).with_split_size(1).with_base(base)), + gate: Arc::clone(gate), + opens: Arc::clone(&opens), + }) as Arc + }) + .collect(); + let source = + MultiLayoutDataSource::new_deferred(i32_dtype(), factories, vec![], &new_session()) + .with_concurrency(2); + let pool = plan(&source, ScanRequest::default())?.open()?; + let mut workers: Vec<_> = (0..4).map(|_| Arc::clone(&pool).worker()).collect(); + let mut noop = Context::from_waker(noop_waker_ref()); + for worker in &mut workers { + assert!(poll_worker(worker, &mut noop).is_pending()); + } + // Opens run on the session's runtime; give them time to start. + for _ in 0..200 { + if opens.load(Ordering::SeqCst) >= 2 { + break; + } + std::thread::sleep(std::time::Duration::from_millis(1)); + } + std::thread::sleep(std::time::Duration::from_millis(20)); + assert_eq!(opens.load(Ordering::SeqCst), 2); + + for gate in &gates { + gate.release(); + } + let mut values = std::thread::scope(|scope| { + let handles: Vec<_> = workers + .into_iter() + .map(|worker| { + scope.spawn(move || { + collect_scan_values(futures::executor::block_on_stream(worker)) + }) + }) + .collect(); + handles + .into_iter() + .map(|handle| handle.join().expect("worker thread panicked")) + .collect::>>() + })? + .concat(); + values.sort_unstable(); + let expected: Vec = (0..6) + .flat_map(|file| (0..4).map(move |row| 100 * file + row)) + .collect(); + assert_eq!(values, expected); + assert_eq!(opens.load(Ordering::SeqCst), 6); + Ok(()) + } + /// A deferred file is opened by a worker, and its splits are shared with other workers. A /// worker that finds only an open in progress waits, and is woken when the open adds splits. #[test] fn deferred_file_splits_are_shared_with_waiting_workers() -> VortexResult<()> { let (source, gates) = gated_source(1, 16); - let pool = plan(&source, ScanRequest::default())?.open()?; + // Each worker holds at most two splits, so the opener leaves splits for the waiter. + let request = ScanRequest { + split_concurrency: NonZeroUsize::new(2), + ..Default::default() + }; + let pool = plan(&source, request)?.open()?; let mut opener = Arc::clone(&pool).worker(); let mut waiter = Arc::clone(&pool).worker(); let mut noop = Context::from_waker(noop_waker_ref()); diff --git a/vortex-layout/src/scan/pool.rs b/vortex-layout/src/scan/pool.rs index c5f09310d45..f0094a6e16a 100644 --- a/vortex-layout/src/scan/pool.rs +++ b/vortex-layout/src/scan/pool.rs @@ -4,22 +4,37 @@ //! The work that the workers of an opened layout scan share. //! //! A pool's units are the splits of one or more files, and the files not yet opened. A worker -//! takes units and keeps up to `splits_in_flight` of them in flight, each spawned onto the -//! session's runtime when the worker takes it. Opening a deferred file is a unit like any other. +//! takes units and keeps several splits in flight, each spawned onto the session's runtime; it +//! never starts threads of its own. Opening a deferred file is a unit like any other, and at most +//! `open_concurrency` opens are queued or running at once. +//! +//! Splits run as [`RepeatedScan::execute_stream`] runs them: +//! +//! - A scan with a filter and a limit builds each split on a CPU thread only once a worker takes +//! it ([`spawn_lazy_split`]), so no new split starts once the limit is spent, and optimizes the +//! rows the limit keeps on a second CPU task ([`spawn_map_trimmed`]). +//! - Every other scan builds all of a file's split tasks together, when a worker first takes one +//! of them, so the file's reads are registered at once and can coalesce. A limit is reserved +//! then, in split order. +//! +//! The pools differ in how workers share units: //! //! - An unordered pool hands units out through a channel. The worker that opens a deferred file -//! sends the file's splits back into the channel, where any worker can take them. The channel -//! closes once every open has finished, which ends the workers. +//! sends the file's splits back into the channel, where any worker can take them, followed by +//! the next deferred file. The channel closes once every open has finished, which ends the +//! workers. //! - An ordered pool gives all of its units, in row order, to its first worker; later workers //! get nothing. Parallel ordered reads cut the scan with `split` first. use std::any::Any; +use std::collections::VecDeque; use std::num::NonZeroUsize; use std::ops::Range; use std::sync::Arc; use async_channel::Receiver; use async_channel::Sender; +use async_lock::OnceCell; use futures::FutureExt; use futures::StreamExt; use futures::future; @@ -43,13 +58,22 @@ use vortex_scan::PartitionStream; use vortex_scan::pool::ScanPool; use vortex_scan::pool::ScanPoolRef; use vortex_scan::row_mask::RowMask; +use vortex_session::VortexSession; use crate::LayoutReaderRef; use crate::scan::limit::RowLimit; use crate::scan::multi::LayoutReaderFactory; +use crate::scan::repeated_scan::DEFAULT_SPLITS_PER_THREAD; +use crate::scan::repeated_scan::MapFn; use crate::scan::repeated_scan::RepeatedScan; +use crate::scan::repeated_scan::SplitConcurrency; use crate::scan::repeated_scan::can_prune_file; +use crate::scan::repeated_scan::spawn_lazy_split; +use crate::scan::repeated_scan::spawn_map_trimmed; +use crate::scan::repeated_scan::stop_on_error; +use crate::scan::tasks::SplitFuture; use crate::scan::tasks::TaskContext; +use crate::scan::tasks::split_exec; /// A scan prepared once and shared by every piece and execution of it. pub(crate) type PreparedScan = RepeatedScan; @@ -57,30 +81,60 @@ pub(crate) type PreparedScan = RepeatedScan; /// A prepared scan and the row ranges of its splits, in row order. pub(crate) type PlannedSplits = (Arc, Vec>); -/// The most splits each worker keeps in flight when the request does not say; stands in for the -/// scan engine's memory budget. -const SPLITS_IN_FLIGHT_PER_WORKER: usize = 4; - -/// One execution of one file's prepared scan. +/// One execution of one file's prepared scan over some of its splits. pub(crate) struct FileScan { scan: Arc, /// Records this execution's events, so file events count once for each execution. ctx: Arc, + /// The row ranges of the splits, in row order. + ranges: Vec>, + /// The task of each split, built together when a worker first takes one of them. `None` + /// where the split has no rows to read, or a worker has taken it. + tasks: OnceCell>>>, +} + +impl FileScan { + /// The tasks of the file's splits, built on first use. A file whose tasks are built once a + /// reserved limit is spent builds none. + async fn tasks(&self, limit: &PoolLimit) -> VortexResult<&[Mutex>]> { + let tasks = self + .tasks + .get_or_try_init(|| future::ready(self.build_tasks(limit))) + .await?; + Ok(tasks) + } + + /// Builds every split's task, which registers its reads, reserving a reserved limit in split + /// order. + fn build_tasks(&self, limit: &PoolLimit) -> VortexResult>>> { + self.ranges + .iter() + .map(|range| { + let mask = self.scan.split_mask(range).and_then(|mask| match limit { + PoolLimit::Reserve(limit) => { + let reserved = limit.limit(mask.mask().clone()); + (!reserved.all_false()).then(|| RowMask::new(range.start, reserved)) + } + PoolLimit::Unlimited | PoolLimit::Trim(_) => Some(mask), + }); + let task = mask + .map(|mask| self.scan.split_task(&self.ctx, mask)) + .transpose()?; + Ok(Mutex::new(task)) + }) + .collect() + } } /// One file's splits for one execution, ready to be handed to workers. pub(crate) struct FileWork { - scan: Option>, - ranges: Vec>, + file: Option>, } impl FileWork { /// A file with nothing to read, for example one that statistics pruned. pub(crate) fn empty() -> Self { - Self { - scan: None, - ranges: Vec::new(), - } + Self { file: None } } /// Starts an execution of `scan` over its split `ranges`. @@ -96,8 +150,12 @@ impl FileWork { return Ok(Self::empty()); } Ok(Self { - scan: Some(Arc::new(FileScan { scan, ctx })), - ranges, + file: Some(Arc::new(FileScan { + scan, + ctx, + ranges, + tasks: OnceCell::new(), + })), }) } } @@ -113,13 +171,16 @@ pub(crate) enum PoolFile { /// How a pool reads its splits. pub(crate) struct PoolOptions { + pub(crate) session: VortexSession, pub(crate) dtype: DType, pub(crate) ordered: bool, pub(crate) limit: Option, /// Whether the scan filters rows, so a split's output row count is unknown up front. pub(crate) has_filter: bool, - /// The most splits each worker keeps in flight, or the default when `None`. - pub(crate) splits_in_flight: Option, + /// The request's bound on the splits each worker keeps in flight. + pub(crate) split_concurrency: Option, + /// The most deferred files that are queued or being opened at once. + pub(crate) open_concurrency: usize, } /// Opens a pool over `files`, in file order. `prepare` turns an opened deferred file into work. @@ -133,14 +194,26 @@ pub(crate) fn open_pool( Some(limit) if options.has_filter => PoolLimit::Trim(RowLimit::new(limit)), Some(limit) => PoolLimit::Reserve(RowLimit::new(limit)), }; - let splits_in_flight = options - .splits_in_flight - .map_or(SPLITS_IN_FLIGHT_PER_WORKER, NonZeroUsize::get); + // A worker takes the place of a partition that one host thread drains, so it keeps as many + // splits in flight as a partition's stream does by default: four per core, at most the + // request's `split_concurrency`. A host with a worker per core therefore has the in-flight + // total of the partitions path, where each of DuckDB's threads drained one file's partition + // and each of DataFusion's `target_partitions` streams drained one partition, each with up to + // `4 × cores` splits in flight. + let splits_in_flight = SplitConcurrency { + per_worker: DEFAULT_SPLITS_PER_THREAD, + max: options.split_concurrency, + } + .splits_in_flight() + .max(1); + let open_concurrency = options.open_concurrency.max(1); let shared = Arc::new(Shared { limit, prepare, + session: options.session, file_share: 1.0 / files.len().max(1) as f64, progress: Mutex::new(0.0), + deferred: Mutex::new(VecDeque::new()), }); if options.ordered { return Arc::new(OrderedPool { @@ -148,18 +221,24 @@ pub(crate) fn open_pool( shared, files: Mutex::new(Some(files)), splits_in_flight, + open_concurrency, }); } let (sender, receiver) = async_channel::unbounded(); + let mut opens = 0; for file in files { match file { PoolFile::Opened(work) => { - for (file, range, progress) in shared.file_splits(work) { - send(&sender, Work::Split(file, range, progress)); + for split in shared.file_splits(work) { + send(&sender, Work::Split(split)); } } - PoolFile::Deferred(factory) => send(&sender, Work::Open(factory, sender.clone())), + PoolFile::Deferred(factory) if opens < open_concurrency => { + opens += 1; + send(&sender, Work::Open(factory, sender.clone())); + } + PoolFile::Deferred(factory) => shared.deferred.lock().push_back(factory), } } Arc::new(UnorderedPool { @@ -173,9 +252,9 @@ pub(crate) fn open_pool( /// How a pool's row limit is applied. enum PoolLimit { Unlimited, - /// A split's selected rows are its output rows, so each split reserves them from the budget - /// when a worker takes it, and rows past the limit are never decoded. Admission order is - /// row order for an ordered pool, so it returns exactly the first rows. + /// A split's selected rows are its output rows, so a file reserves its splits' rows from the + /// budget in split order when it builds their tasks, and rows past the limit are never + /// decoded. Files build in row order in an ordered pool, so it returns exactly the first rows. Reserve(RowLimit), /// A split's output rows are unknown until its filter has run, so workers take rows from the /// budget as they yield them and discard the excess. @@ -183,112 +262,160 @@ enum PoolLimit { } impl PoolLimit { - fn is_exhausted(&self) -> bool { + /// Whether the budget is spent, so no file that has not started has rows to return. + fn is_spent(&self) -> bool { match self { PoolLimit::Unlimited => false, PoolLimit::Reserve(limit) | PoolLimit::Trim(limit) => limit.is_exhausted(), } } + + /// Whether a trimmed budget is spent, so workers end without returning any more rows. + fn is_trimmed_out(&self) -> bool { + matches!(self, PoolLimit::Trim(limit) if limit.is_exhausted()) + } } /// A split's output: `None` when it has no rows to return. -type SplitFuture = BoxFuture<'static, VortexResult>>; +type SplitOutput = BoxFuture<'static, VortexResult>>; -/// A split of a file, with the progress that taking it adds. -type FileSplit = (Arc, Range, f64); +/// A split of a file by its index, with the progress that taking it adds. +type FileSplit = (Arc, usize, f64); /// What every worker of a pool shares. struct Shared { limit: PoolLimit, prepare: Option, + /// The session whose runtime runs the pool's splits and opens. + session: VortexSession, /// The progress that one file adds. file_share: f64, progress: Mutex, + /// An unordered pool's deferred files that are not yet queued for opening, in file order. + deferred: Mutex>>, } impl Shared { /// The splits of an opened file, in row order. fn file_splits(&self, work: FileWork) -> Vec { - let rows: u64 = work + let Some(file) = work.file else { + *self.progress.lock() += self.file_share; + return Vec::new(); + }; + let rows: u64 = file .ranges .iter() .map(|range| range.end - range.start) .sum(); - match work.scan { - Some(scan) if rows > 0 => { - let per_row = self.file_share / rows as f64; - work.ranges - .into_iter() - .map(|range| { - let progress = per_row * (range.end - range.start) as f64; - (Arc::clone(&scan), range, progress) - }) - .collect() - } - _ => { - *self.progress.lock() += self.file_share; - Vec::new() - } + if rows == 0 { + *self.progress.lock() += self.file_share; + return Vec::new(); } + let per_row = self.file_share / rows as f64; + (0..file.ranges.len()) + .map(|index| { + let range = &file.ranges[index]; + let progress = per_row * (range.end - range.start) as f64; + (Arc::clone(&file), index, progress) + }) + .collect() } - /// Opens a deferred file into its work. + /// Opens a deferred file into its work on the session's runtime. A file that starts after + /// the limit is spent is not opened. fn open_file( self: &Arc, factory: Arc, ) -> BoxFuture<'static, VortexResult> { + if self.limit.is_spent() { + return future::ready(Ok(FileWork::empty())).boxed(); + } let shared = Arc::clone(self); - async move { - let reader = factory - .open() - .instrument(tracing::info_span!("LayoutReaderFactory::open")) - .await?; - match (reader, &shared.prepare) { - (Some(reader), Some(prepare)) => prepare(reader), - _ => Ok(FileWork::empty()), - } + self.session + .handle() + .spawn(async move { + let reader = factory + .open() + .instrument(tracing::info_span!("LayoutReaderFactory::open")) + .await?; + match (reader, &shared.prepare) { + (Some(reader), Some(prepare)) => prepare(reader), + _ => Ok(FileWork::empty()), + } + }) + .boxed() + } + + /// The next deferred file of an unordered pool to open, if any is left and the limit is not + /// spent. + fn next_deferred(&self) -> Option> { + let mut deferred = self.deferred.lock(); + if self.limit.is_spent() { + deferred.clear(); } - .boxed() + deferred.pop_front() } - /// Takes a split: reserves its rows from a reserved limit and spawns its task. - fn admit(&self, (file, range, progress): FileSplit) -> SplitFuture { + /// Takes a split and runs it on the session's runtime. + fn admit(self: &Arc, (file, index, progress): FileSplit) -> SplitOutput { *self.progress.lock() += progress; - let Some(mask) = file.scan.split_mask(&range) else { - return future::ready(Ok(None)).boxed(); - }; - let mask = match &self.limit { - PoolLimit::Reserve(limit) => { - let reserved = limit.limit(mask.mask().clone()); - if reserved.all_false() { - return future::ready(Ok(None)).boxed(); - } - RowMask::new(range.start, reserved) + let handle = self.session.handle(); + if let PoolLimit::Trim(_) = &self.limit { + let Some(mask) = file.scan.split_mask(&file.ranges[index]) else { + return future::ready(Ok(None)).boxed(); + }; + return spawn_lazy_split(&handle, move || split_exec(&file.ctx, mask).map(Some)) + .boxed(); + } + let shared = Arc::clone(self); + async move { + let task = file.tasks(&shared.limit).await?[index].lock().take(); + match task { + Some(task) => handle.spawn(task).await, + None => Ok(None), } - PoolLimit::Unlimited | PoolLimit::Trim(_) => mask, - }; - // Spawned onto the session's runtime, as V1 scans do: another runtime thread may decode - // it while this worker drives its other splits, and its I/O starts right away. - let handle = file.ctx.session.handle(); - handle - .spawn(async move { file.scan.split_task(&file.ctx, mask)?.await }) - .boxed() + } + .boxed() } - #[expect( - dead_code, - reason = "read by ScanPool::progress, which arrives with its first host" - )] fn progress(&self) -> f64 { - if self.limit.is_exhausted() { + if self.limit.is_trimmed_out() { return 1.0; } self.progress.lock().clamp(0.0, 1.0) } + + /// A worker's output: skips splits with no rows, trims to a trimmed limit, and ends after the + /// first error or once a trimmed limit is spent. A trimmed array is optimized again, on a CPU + /// task, `splits_in_flight` at a time. + fn output( + self: Arc, + outputs: BoxStream<'static, VortexResult>>, + ordered: bool, + splits_in_flight: usize, + ) -> BoxStream<'static, VortexResult> { + let trimmed = matches!(self.limit, PoolLimit::Trim(_)); + let handle = self.session.handle(); + let session = self.session.clone(); + let arrays = limit_output(outputs, self); + if !trimmed { + return arrays; + } + let identity: MapFn = Arc::new(Ok); + let mapped = arrays.map(move |array| { + spawn_map_trimmed(&handle, session.clone(), Arc::clone(&identity), array) + }); + let mapped = if ordered { + mapped.buffered(splits_in_flight).boxed() + } else { + mapped.buffer_unordered(splits_in_flight).boxed() + }; + stop_on_error(mapped) + } } -/// A worker's output: skips splits with no rows, trims to a trimmed limit, and ends after the -/// first error or once a trimmed limit is spent. +/// Skips splits with no rows, trims to a trimmed limit, and ends after the first error or once +/// a trimmed limit is spent. fn limit_output( outputs: BoxStream<'static, VortexResult>>, shared: Arc, @@ -298,9 +425,7 @@ fn limit_output( async move { let mut outputs = outputs?; loop { - if let PoolLimit::Trim(limit) = &shared.limit - && limit.is_exhausted() - { + if shared.limit.is_trimmed_out() { return None; } let array = match outputs.next().await? { @@ -327,9 +452,9 @@ fn limit_output( /// A unit of an unordered pool. enum Work { - Split(Arc, Range, f64), + Split(FileSplit), /// A deferred file, and where to send its splits once it is open. The sender keeps the - /// channel open until the file's splits are in it. + /// channel open until the file's splits, and the next deferred file, are in it. Open(Arc, Sender), } @@ -347,17 +472,24 @@ struct UnorderedPool { } impl UnorderedPool { - fn run(shared: &Arc, work: Work) -> SplitFuture { + fn run(shared: &Arc, work: Work) -> SplitOutput { match work { - Work::Split(file, range, progress) => shared.admit((file, range, progress)), + Work::Split(split) => shared.admit(split), Work::Open(factory, sender) => { let shared = Arc::clone(shared); async move { - let work = shared.open_file(factory).await?; - for (file, range, progress) in shared.file_splits(work) { - send(&sender, Work::Split(file, range, progress)); + let opened = shared.open_file(factory).await.map(|work| { + for split in shared.file_splits(work) { + send(&sender, Work::Split(split)); + } + None + }); + // Queue the next file behind this one's splits, so opens keep pace with the + // workers and at most `open_concurrency` are queued or running at once. + if let Some(next) = shared.next_deferred() { + send(&sender, Work::Open(next, sender.clone())); } - Ok(None) + opened } .boxed() } @@ -378,15 +510,25 @@ impl ScanPool for UnorderedPool { let splits_in_flight = self.splits_in_flight; // The worker holds the pool, so the pool is dropped only after its last worker. let outputs = receiver - .take_while(move |_| future::ready(!self.shared.limit.is_exhausted())) + .take_while(move |_| future::ready(!self.shared.limit.is_trimmed_out())) .map(move |work| UnorderedPool::run(&runner, work)) .buffer_unordered(splits_in_flight) .boxed(); ArrayStreamExt::boxed(ArrayStreamAdapter::new( dtype, - limit_output(outputs, shared), + shared.output(outputs, false, splits_in_flight), )) } + + fn progress(&self) -> f64 { + self.shared.progress() + } + + fn is_exhausted(&self) -> bool { + // Pending opens hold senders, so the channel closes only once every unit is in it. + self.shared.limit.is_trimmed_out() + || (self.receiver.is_closed() && self.receiver.is_empty()) + } } impl Drop for UnorderedPool { @@ -404,6 +546,7 @@ struct OrderedPool { /// The files, until the first worker takes them. files: Mutex>>, splits_in_flight: usize, + open_concurrency: usize, } impl ScanPool for OrderedPool { @@ -420,18 +563,21 @@ impl ScanPool for OrderedPool { let opener = Arc::clone(&shared); let splitter = Arc::clone(&shared); let admitter = Arc::clone(&shared); + let gate = Arc::clone(&shared); + // Deferred files open `open_concurrency` at a time, ahead of the splits being read. let outputs = stream::iter(files) - .then(move |file| match file { + .map(move |file| match file { PoolFile::Opened(work) => future::ready(Ok(work)).boxed(), PoolFile::Deferred(factory) => opener.open_file(factory), }) + .buffered(self.open_concurrency) .flat_map(move |work| match work { Ok(work) => { stream::iter(splitter.file_splits(work).into_iter().map(Ok)).left_stream() } Err(err) => stream::once(future::ready(Err(err))).right_stream(), }) - .take_while(move |_| future::ready(!shared.limit.is_exhausted())) + .take_while(move |_| future::ready(!gate.limit.is_trimmed_out())) .map(move |split| match split { Ok(split) => admitter.admit(split), Err(err) => future::ready(Err(err)).boxed(), @@ -440,9 +586,17 @@ impl ScanPool for OrderedPool { .boxed(); ArrayStreamExt::boxed(ArrayStreamAdapter::new( dtype, - limit_output(outputs, Arc::clone(&self.shared)), + shared.output(outputs, true, self.splits_in_flight), )) } + + fn progress(&self) -> f64 { + self.shared.progress() + } + + fn is_exhausted(&self) -> bool { + self.shared.limit.is_trimmed_out() || self.files.lock().is_none() + } } /// The single partition of a scan piece that is read through the partitions API: it opens the diff --git a/vortex-layout/src/scan/repeated_scan.rs b/vortex-layout/src/scan/repeated_scan.rs index dcd4cba58c8..4431e452ce9 100644 --- a/vortex-layout/src/scan/repeated_scan.rs +++ b/vortex-layout/src/scan/repeated_scan.rs @@ -31,6 +31,8 @@ use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_error::vortex_bail; use vortex_io::runtime::BlockingRuntime; +use vortex_io::runtime::Handle; +use vortex_io::runtime::Task; use vortex_io::session::RuntimeSessionExt; use vortex_scan::row_mask::RowMask; use vortex_scan::selection::Selection; @@ -84,7 +86,7 @@ pub struct RepeatedScan { pub type ScanTasks = Vec>>>; /// A function applied to each projected split array. -type MapFn = Arc VortexResult + Send + Sync>; +pub(crate) type MapFn = Arc VortexResult + Send + Sync>; impl RepeatedScan { pub fn execute_array_iter( @@ -326,21 +328,13 @@ impl RepeatedScan { .map(move |split| { let ctx = Arc::clone(&ctx); let selection = selection.clone(); - split_handle.spawn_nested(move |handle| async move { - let task = handle - .spawn_cpu(move || { - let Some(row_mask) = - split.either(Some, |range| selected_mask(&selection, &range)) - else { - return Ok(None); - }; - split_exec(&ctx, row_mask).map(Some) - }) - .await?; - match task { - Some(task) => task.await, - None => Ok(None), - } + spawn_lazy_split(&split_handle, move || { + let Some(row_mask) = + split.either(Some, |range| selected_mask(&selection, &range)) + else { + return Ok(None); + }; + split_exec(&ctx, row_mask).map(Some) }) }); let map_fn = Arc::clone(map_fn); @@ -349,9 +343,7 @@ impl RepeatedScan { .boxed(); let session = self.session.clone(); let mapped = limit_rows(arrays, limit).map(move |array| { - let map_fn = Arc::clone(&map_fn); - let session = session.clone(); - handle.spawn_cpu(move || map_fn(array?.optimize_ctx(&session)?)) + spawn_map_trimmed(&handle, session.clone(), Arc::clone(&map_fn), array) }); buffer(mapped, ordered, concurrency) } @@ -386,6 +378,36 @@ impl RepeatedScan { } } +/// Builds a split's task on a CPU thread and runs it, both on the session's runtime. +/// +/// This is how scans with a filter and a limit run their splits: a split's output row count is +/// unknown until its filter has run, so each split is built only once it is about to run, and none +/// start once the limit is spent. `build` returns `None` when the split has nothing to read. Every +/// other scan builds all of its split tasks up front with [`RepeatedScan::split_task`], so that +/// their reads are registered together and can coalesce, and runs each with [`Handle::spawn`]. +pub(crate) fn spawn_lazy_split( + handle: &Handle, + build: impl FnOnce() -> VortexResult> + Send + 'static, +) -> Task>> { + handle.spawn_nested(move |handle| async move { + match handle.spawn_cpu(build).await? { + Some(task) => task.await, + None => Ok(None), + } + }) +} + +/// Optimizes an array that a limit may have trimmed and maps it, on a CPU thread: the second +/// stage of a scan with a filter and a limit, after [`spawn_lazy_split`]. +pub(crate) fn spawn_map_trimmed( + handle: &Handle, + session: VortexSession, + map_fn: MapFn, + array: VortexResult, +) -> Task> { + handle.spawn_cpu(move || map_fn(array?.optimize_ctx(&session)?)) +} + /// This function returns `None` if the selection excludes every row in `range`. fn selected_mask(selection: &Selection, range: &Range) -> Option { let mask = selection.row_mask(range); @@ -452,7 +474,7 @@ fn limit_rows( } /// Yield the first error and drop upstream without polling it again. -fn stop_on_error( +pub(crate) fn stop_on_error( stream: BoxStream<'static, VortexResult>, ) -> BoxStream<'static, VortexResult> { let mut stream = Some(stream); @@ -469,6 +491,10 @@ fn stop_on_error( .boxed() } +/// The splits a scan keeps in flight for each worker thread by default, which allows for some I/O +/// lookahead without too much impact on work-stealing. +pub(crate) const DEFAULT_SPLITS_PER_THREAD: usize = 4; + /// How many splits a scan makes progress on at once: `per_worker` for each worker thread, as /// [`get_available_parallelism`] counts them, and at most `max` in all when that is set. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -478,7 +504,7 @@ pub(crate) struct SplitConcurrency { } impl SplitConcurrency { - fn splits_in_flight(self) -> usize { + pub(crate) fn splits_in_flight(self) -> usize { let scaled = self .per_worker .saturating_mul(get_available_parallelism().unwrap_or(1)); diff --git a/vortex-layout/src/scan/scan_builder.rs b/vortex-layout/src/scan/scan_builder.rs index 3785489d710..96373ae3e72 100644 --- a/vortex-layout/src/scan/scan_builder.rs +++ b/vortex-layout/src/scan/scan_builder.rs @@ -40,6 +40,7 @@ use crate::scan::limit::RowLimit; use crate::scan::limit::ScanLimit; use crate::scan::metrics::ScanMetrics; use crate::scan::metrics::ScanUsage; +use crate::scan::repeated_scan::DEFAULT_SPLITS_PER_THREAD; use crate::scan::repeated_scan::RepeatedScan; use crate::scan::repeated_scan::ScanTasks; use crate::scan::repeated_scan::SplitConcurrency; @@ -103,10 +104,8 @@ impl ScanBuilder { selection: Default::default(), split_by: SplitBy::default(), natural_splits: None, - // We default to four tasks per worker thread, which allows for some I/O lookahead - // without too much impact on work-stealing. concurrency: SplitConcurrency { - per_worker: 4, + per_worker: DEFAULT_SPLITS_PER_THREAD, max: None, }, map_fn: Arc::new(Ok), diff --git a/vortex-layout/src/scan/test.rs b/vortex-layout/src/scan/test.rs index 3e0b70465e6..0e15bcced80 100644 --- a/vortex-layout/src/scan/test.rs +++ b/vortex-layout/src/scan/test.rs @@ -84,6 +84,7 @@ pub struct TestLayoutReader { filter_exprs: Option>>>, in_flight: Option>, yields: fn(u64) -> usize, + built_projections: Option>, } /// Counts projections running at once, and the most that ever were. @@ -116,6 +117,7 @@ impl TestLayoutReader { filter_exprs: None, in_flight: None, yields: |_| 0, + built_projections: None, } } @@ -159,6 +161,12 @@ impl TestLayoutReader { self } + /// Counts the projections built, which is when a split registers its reads. + pub fn with_built_projections(mut self, built: Arc) -> Self { + self.built_projections = Some(built); + self + } + pub fn with_filter_exprs(mut self, filter_exprs: Arc>>) -> Self { self.filter_exprs = Some(filter_exprs); self @@ -284,6 +292,9 @@ impl LayoutReader for TestLayoutReader { let fail = self.fail_projection || (self.fail_first_projection && row_range.start == 0); let in_flight = self.in_flight.clone(); let yields = (self.yields)(row_range.start); + if let Some(built) = &self.built_projections { + built.fetch_add(1, Ordering::SeqCst); + } Ok(Box::pin(async move { for _ in 0..yields { From c638db423a70e230720a626aed1cc37b96e33be8 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Thu, 19 Nov 2026 19:15:57 -0500 Subject: [PATCH 05/25] Pass a pool's open slot on when its worker drops An open slot now passes to the next deferred file whether the open finished or its worker gave it up, so a dropped worker strands only the file it was opening. A spent limit counts the unopened files as read, so progress ends at 1.0. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-layout/src/scan/multi.rs | 114 +++++++++++++++++++++++++++----- vortex-layout/src/scan/pool.rs | 72 +++++++++++++------- 2 files changed, 147 insertions(+), 39 deletions(-) diff --git a/vortex-layout/src/scan/multi.rs b/vortex-layout/src/scan/multi.rs index 0ae1db43e65..b71bc2eace7 100644 --- a/vortex-layout/src/scan/multi.rs +++ b/vortex-layout/src/scan/multi.rs @@ -1287,22 +1287,8 @@ mod pool_tests { #[test] fn deferred_opens_are_bounded() -> VortexResult<()> { let opens = Arc::new(AtomicUsize::new(0)); - let gates: Vec<_> = (0..6).map(|_| Arc::new(Gate::default())).collect(); - let factories = gates - .iter() - .enumerate() - .map(|(index, gate)| { - let base = 100 * i32::try_from(index).expect("few files"); - Arc::new(GatedFactory { - reader: Arc::new(TestLayoutReader::new(4).with_split_size(1).with_base(base)), - gate: Arc::clone(gate), - opens: Arc::clone(&opens), - }) as Arc - }) - .collect(); - let source = - MultiLayoutDataSource::new_deferred(i32_dtype(), factories, vec![], &new_session()) - .with_concurrency(2); + let (source, gates) = counted_source(6, 4, &opens); + let source = source.with_concurrency(2); let pool = plan(&source, ScanRequest::default())?.open()?; let mut workers: Vec<_> = (0..4).map(|_| Arc::clone(&pool).worker()).collect(); let mut noop = Context::from_waker(noop_waker_ref()); @@ -1416,6 +1402,102 @@ mod pool_tests { Ok(()) } + /// Deferred files of `rows` one-row splits whose opens are released, counted by `opens`; the + /// `i`th produces `100 * i + row`. + fn counted_source( + files: usize, + rows: u64, + opens: &Arc, + ) -> (MultiLayoutDataSource, Vec>) { + let gates: Vec<_> = (0..files).map(|_| Arc::new(Gate::default())).collect(); + let factories = gates + .iter() + .enumerate() + .map(|(index, gate)| { + let base = 100 * i32::try_from(index).expect("few files"); + Arc::new(GatedFactory { + reader: Arc::new( + TestLayoutReader::new(rows) + .with_split_size(1) + .with_base(base), + ), + gate: Arc::clone(gate), + opens: Arc::clone(opens), + }) as Arc + }) + .collect(); + let source = + MultiLayoutDataSource::new_deferred(i32_dtype(), factories, vec![], &new_session()); + (source, gates) + } + + /// An ordered pool reserves an unfiltered limit in row order across files, so it returns + /// exactly the first rows even when the limit ends inside a later file. + #[test] + fn ordered_reserved_limit_crosses_files() -> VortexResult<()> { + let (source, gates) = counted_source(3, 4, &Arc::default()); + for gate in &gates { + gate.release(); + } + let pool = plan( + &source, + ScanRequest { + ordered: true, + limit: Some(6), + ..Default::default() + }, + )? + .open()?; + assert_eq!(read_with_one_worker(pool)?, [0, 1, 2, 3, 100, 101]); + Ok(()) + } + + /// Once an unordered pool's reserved limit is spent, it opens no more files, and reports + /// that it is done. + #[test] + fn spent_limit_stops_opening_files() -> VortexResult<()> { + let opens = Arc::new(AtomicUsize::new(0)); + let (source, gates) = counted_source(6, 4, &opens); + for gate in &gates { + gate.release(); + } + let source = source.with_concurrency(1); + let pool = plan( + &source, + ScanRequest { + limit: Some(2), + ..Default::default() + }, + )? + .open()?; + let values = read_with_one_worker(Arc::clone(&pool))?; + assert_eq!(values.len(), 2); + assert!(opens.load(Ordering::SeqCst) < 6, "opened every file"); + assert!(pool.is_exhausted()); + assert_eq!(pool.progress(), 1.0); + Ok(()) + } + + /// A worker dropped while it opens a file gives up only that file: the next deferred file + /// still opens, and other workers read it. + #[test] + fn dropped_opener_strands_only_its_file() -> VortexResult<()> { + let (source, gates) = counted_source(3, 2, &Arc::default()); + let source = source.with_concurrency(1); + let pool = plan(&source, ScanRequest::default())?.open()?; + let mut dropped = Arc::clone(&pool).worker(); + let mut noop = Context::from_waker(noop_waker_ref()); + assert!(poll_worker(&mut dropped, &mut noop).is_pending()); + drop(dropped); + + gates[1].release(); + gates[2].release(); + let mut values = read_with_one_worker(pool)?; + values.sort_unstable(); + assert_eq!(values, [100, 101, 200, 201]); + Ok(()) + } + /// A limit is shared by every worker and file of an unordered pool. #[test] fn pool_limit_is_shared_across_readers() -> VortexResult<()> { diff --git a/vortex-layout/src/scan/pool.rs b/vortex-layout/src/scan/pool.rs index f0094a6e16a..973623e8eba 100644 --- a/vortex-layout/src/scan/pool.rs +++ b/vortex-layout/src/scan/pool.rs @@ -236,7 +236,11 @@ pub(crate) fn open_pool( } PoolFile::Deferred(factory) if opens < open_concurrency => { opens += 1; - send(&sender, Work::Open(factory, sender.clone())); + let slot = OpenSlot { + shared: Arc::clone(&shared), + sender: sender.clone(), + }; + send(&sender, Work::Open(factory, slot)); } PoolFile::Deferred(factory) => shared.deferred.lock().push_back(factory), } @@ -347,10 +351,11 @@ impl Shared { } /// The next deferred file of an unordered pool to open, if any is left and the limit is not - /// spent. + /// spent. Once it is spent, the files left count as read. fn next_deferred(&self) -> Option> { let mut deferred = self.deferred.lock(); - if self.limit.is_spent() { + if self.limit.is_spent() && !deferred.is_empty() { + *self.progress.lock() += self.file_share * deferred.len() as f64; deferred.clear(); } deferred.pop_front() @@ -453,9 +458,33 @@ fn limit_output( /// A unit of an unordered pool. enum Work { Split(FileSplit), - /// A deferred file, and where to send its splits once it is open. The sender keeps the - /// channel open until the file's splits, and the next deferred file, are in it. - Open(Arc, Sender), + /// A deferred file, and the open slot it holds until its splits are in the channel. + Open(Arc, OpenSlot), +} + +/// One of an unordered pool's `open_concurrency` open slots. Its sender keeps the channel open +/// while the file that holds it is queued or opening. +struct OpenSlot { + shared: Arc, + sender: Sender, +} + +impl Drop for OpenSlot { + /// Passes the slot to the next deferred file, queued behind the splits of the file that held + /// it, so opens keep pace with the workers. The slot passes on whether the open finished or a + /// dropped worker gave it up, so that worker strands only the file it was opening. + fn drop(&mut self) { + if self.sender.is_closed() { + return; + } + if let Some(next) = self.shared.next_deferred() { + let slot = OpenSlot { + shared: Arc::clone(&self.shared), + sender: self.sender.clone(), + }; + send(&self.sender, Work::Open(next, slot)); + } + } } fn send(sender: &Sender, work: Work) { @@ -475,24 +504,17 @@ impl UnorderedPool { fn run(shared: &Arc, work: Work) -> SplitOutput { match work { Work::Split(split) => shared.admit(split), - Work::Open(factory, sender) => { - let shared = Arc::clone(shared); - async move { - let opened = shared.open_file(factory).await.map(|work| { - for split in shared.file_splits(work) { - send(&sender, Work::Split(split)); - } - None - }); - // Queue the next file behind this one's splits, so opens keep pace with the - // workers and at most `open_concurrency` are queued or running at once. - if let Some(next) = shared.next_deferred() { - send(&sender, Work::Open(next, sender.clone())); + Work::Open(factory, slot) => async move { + let opened = slot.shared.open_file(factory).await.map(|work| { + for split in slot.shared.file_splits(work) { + send(&slot.sender, Work::Split(split)); } - opened - } - .boxed() + None + }); + drop(slot); + opened } + .boxed(), } } } @@ -521,11 +543,14 @@ impl ScanPool for UnorderedPool { } fn progress(&self) -> f64 { + if self.is_exhausted() { + return 1.0; + } self.shared.progress() } fn is_exhausted(&self) -> bool { - // Pending opens hold senders, so the channel closes only once every unit is in it. + // Open slots hold senders, so the channel closes only once every unit is in it. self.shared.limit.is_trimmed_out() || (self.receiver.is_closed() && self.receiver.is_empty()) } @@ -595,6 +620,7 @@ impl ScanPool for OrderedPool { } fn is_exhausted(&self) -> bool { + // The first worker takes every file. self.shared.limit.is_trimmed_out() || self.files.lock().is_none() } } From 0cd40e45df61e85ca78440a3469f70ea3af12dcb Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Thu, 19 Nov 2026 19:25:53 -0500 Subject: [PATCH 06/25] Request shared segments without an exclusive lock When pool workers share one file's splits, many threads request segments from one SharedSegmentSource. Each request took an exclusive shard lock and held it across the inner request. Requests now look up an in-flight request under a read lock, make the inner request outside any lock, and lock exclusively only to record it, with the shard count scaled to the cores. A requester that loses a race for the same segment drops its own request, which reads the same bytes, so coalescing is unchanged. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-io/src/segments/shared.rs | 128 ++++++++++++++++++++++++++----- 1 file changed, 109 insertions(+), 19 deletions(-) diff --git a/vortex-io/src/segments/shared.rs b/vortex-io/src/segments/shared.rs index dbaf553264a..bed9394a9d2 100644 --- a/vortex-io/src/segments/shared.rs +++ b/vortex-io/src/segments/shared.rs @@ -6,6 +6,7 @@ use std::sync::Arc; use futures::FutureExt; use futures::TryFutureExt; use futures::future::BoxFuture; +use futures::future::Shared; use futures::future::WeakShared; use vortex_array::buffer::BufferHandle; use vortex_error::SharedVortexResult; @@ -20,6 +21,11 @@ use super::SegmentSource; /// A [`SegmentSource`] that allows multiple requesters to await the same underlying segment /// request. +/// +/// Many threads may request segments of one source at once, for example the workers of a scan +/// pool sharing one file's splits. Requests therefore look for a request in flight under a shared +/// lock, call the inner source outside any lock, and take an exclusive lock only to record a new +/// request. pub struct SharedSegmentSource { inner: S, in_flight: DashMap>, @@ -32,33 +38,117 @@ impl SharedSegmentSource { pub fn new(inner: S) -> Self { Self { inner, - in_flight: DashMap::with_hasher_and_shard_amount(Default::default(), 64), + // The default shard count scales with the machine's cores, as the requesters do. + in_flight: DashMap::default(), } } + + /// The request in flight for `id`, if any. + fn in_flight(&self, id: SegmentId) -> Option> { + self.in_flight.get(&id)?.upgrade() + } } impl SegmentSource for SharedSegmentSource { fn request(&self, id: SegmentId) -> SegmentFuture { - loop { - match self.in_flight.entry(id) { - Entry::Occupied(e) => { - if let Some(shared_future) = e.get().upgrade() { - return shared_future.map_err(VortexError::from).boxed(); - } else { - // The future has been dropped, remove the entry and try again. - e.remove(); - } - } - Entry::Vacant(e) => { - let future = self.inner.request(id).map_err(Arc::new).boxed().shared(); - e.insert( - future - .downgrade() - .vortex_expect("just created, cannot be polled to completion"), - ); - return future.map_err(VortexError::from).boxed(); + if let Some(future) = self.in_flight(id) { + return future.map_err(VortexError::from).boxed(); + } + + let future = self.inner.request(id).map_err(Arc::new).boxed().shared(); + let weak = future + .downgrade() + .vortex_expect("just created, cannot be polled to completion"); + match self.in_flight.entry(id) { + Entry::Occupied(mut entry) => { + if let Some(existing) = entry.get().upgrade() { + // Another requester recorded the same segment first. Its request reads the + // same bytes, so dropping this one changes nothing that is read or coalesced. + return existing.map_err(VortexError::from).boxed(); } + entry.insert(weak); } + Entry::Vacant(entry) => { + entry.insert(weak); + } + } + future.map_err(VortexError::from).boxed() + } +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + use std::sync::atomic::AtomicUsize; + use std::sync::atomic::Ordering; + + use futures::FutureExt; + use futures::executor::block_on; + use vortex_array::buffer::BufferHandle; + use vortex_buffer::ByteBuffer; + use vortex_error::VortexResult; + + use super::*; + + /// Counts its requests, and answers each with the segment's id as one byte. + #[derive(Default)] + struct Counting(AtomicUsize); + + impl SegmentSource for Counting { + fn request(&self, id: SegmentId) -> SegmentFuture { + self.0.fetch_add(1, Ordering::SeqCst); + let byte = u8::try_from(*id).unwrap_or(u8::MAX); + async move { Ok(BufferHandle::new_host(ByteBuffer::from(vec![byte]))) }.boxed() + } + } + + #[test] + fn concurrent_requests_share_one_inner_request() -> VortexResult<()> { + let source = SharedSegmentSource::new(Counting::default()); + let first = source.request(SegmentId::from(7)); + let second = source.request(SegmentId::from(7)); + assert_eq!(source.inner.0.load(Ordering::SeqCst), 1); + assert_eq!(block_on(first)?.to_host_sync().as_slice(), [7]); + assert_eq!(block_on(second)?.to_host_sync().as_slice(), [7]); + Ok(()) + } + + #[test] + fn a_finished_request_is_made_again() -> VortexResult<()> { + let source = SharedSegmentSource::new(Counting::default()); + drop(block_on(source.request(SegmentId::from(3)))?); + drop(block_on(source.request(SegmentId::from(3)))?); + assert_eq!(source.inner.0.load(Ordering::SeqCst), 2); + Ok(()) + } + + /// Threads requesting the same segments at once each get their segment. + #[test] + fn racing_requesters_get_their_segments() -> VortexResult<()> { + let source = Arc::new(SharedSegmentSource::new(Counting::default())); + let futures = std::thread::scope(|scope| { + let handles: Vec<_> = (0..8) + .map(|_| { + let source = Arc::clone(&source); + scope.spawn(move || { + (0..64u32) + .map(|id| source.request(SegmentId::from(id))) + .collect::>() + }) + }) + .collect(); + handles + .into_iter() + .flat_map(|handle| handle.join().expect("requester panicked")) + .collect::>() + }); + // A requester that loses a race drops its own inner request, so there may be more than + // one per segment, but never fewer. + assert!(source.inner.0.load(Ordering::SeqCst) >= 64); + for (index, future) in futures.into_iter().enumerate() { + let id = u8::try_from(index % 64).unwrap_or(u8::MAX); + assert_eq!(block_on(future)?.to_host_sync().as_slice(), [id]); } + Ok(()) } } From 7843fbcc1197b64ec09aeef6b54c07852ab4d69d Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Thu, 19 Nov 2026 20:14:00 -0500 Subject: [PATCH 07/25] Share an unordered pool's output instead of its work MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Workers of an unordered pool each kept their own window of splits, so with fewer splits than workers × window the first workers took most of a scan and the rest idled. The pool now runs its splits in lanes on the session runtime, splits_in_flight of them across the whole pool, and every worker takes rows from one bounded output channel. A worker is just one host thread's share of the output, so the number of workers is only the host's parallelism. Trimming to a filtered limit happens once, in the lanes, and dropping a worker gives up nothing. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-layout/src/scan/multi.rs | 91 ++++++--------- vortex-layout/src/scan/pool.rs | 190 +++++++++++++++++++++++--------- 2 files changed, 169 insertions(+), 112 deletions(-) diff --git a/vortex-layout/src/scan/multi.rs b/vortex-layout/src/scan/multi.rs index b71bc2eace7..9ccbe87712d 100644 --- a/vortex-layout/src/scan/multi.rs +++ b/vortex-layout/src/scan/multi.rs @@ -1162,10 +1162,8 @@ mod pool_tests { use async_trait::async_trait; use futures::StreamExt; use futures::future::poll_fn; - use futures::task::ArcWake; use futures::task::AtomicWaker; use futures::task::noop_waker_ref; - use futures::task::waker; use rstest::rstest; use vortex_array::ArrayRef; use vortex_array::dtype::Nullability; @@ -1266,15 +1264,6 @@ mod pool_tests { (source, gates) } - #[derive(Default)] - struct WakeFlag(AtomicBool); - - impl ArcWake for WakeFlag { - fn wake_by_ref(arc_self: &Arc) { - arc_self.0.store(true, Ordering::SeqCst); - } - } - fn poll_worker( worker: &mut SendableArrayStream, cx: &mut Context<'_>, @@ -1332,47 +1321,27 @@ mod pool_tests { Ok(()) } - /// A deferred file is opened by a worker, and its splits are shared with other workers. A - /// worker that finds only an open in progress waits, and is woken when the open adds splits. + /// Rows go to whichever worker asks for them: a worker that stops asking holds none back, + /// so another worker that waited while the file opened reads all of it. #[test] - fn deferred_file_splits_are_shared_with_waiting_workers() -> VortexResult<()> { + fn rows_go_to_whichever_worker_asks() -> VortexResult<()> { let (source, gates) = gated_source(1, 16); - // Each worker holds at most two splits, so the opener leaves splits for the waiter. - let request = ScanRequest { - split_concurrency: NonZeroUsize::new(2), - ..Default::default() - }; - let pool = plan(&source, request)?.open()?; - let mut opener = Arc::clone(&pool).worker(); + let pool = plan(&source, ScanRequest::default())?.open()?; + let mut idle = Arc::clone(&pool).worker(); let mut waiter = Arc::clone(&pool).worker(); let mut noop = Context::from_waker(noop_waker_ref()); - let flag = Arc::new(WakeFlag::default()); - let flag_waker = waker(Arc::clone(&flag)); - let mut flagged = Context::from_waker(&flag_waker); - // The opener takes the only file and blocks on its open; the waiter finds nothing to take - // but an open in progress, so it waits. - assert!(poll_worker(&mut opener, &mut noop).is_pending()); - assert!(poll_worker(&mut waiter, &mut flagged).is_pending()); + // Both workers find only an open in progress, so both wait. + assert!(poll_worker(&mut idle, &mut noop).is_pending()); + assert!(poll_worker(&mut waiter, &mut noop).is_pending()); gates[0].release(); - // The opener's split runs on the session runtime, so wait for it rather than polling once. - let Some(first) = futures::executor::block_on(opener.next()) else { - panic!("the opener reads a split of the file it opened"); - }; - assert!(flag.0.load(Ordering::SeqCst), "the waiter is woken"); - - let waiter_values = collect_scan_values(futures::executor::block_on_stream(waiter))?; - let opener_values = collect_scan_values( - std::iter::once(first).chain(futures::executor::block_on_stream(opener)), - )?; - assert!( - !waiter_values.is_empty(), - "the waiter reads the opened file's splits" - ); - let mut values = [opener_values, waiter_values].concat(); - values.sort_unstable(); - assert_eq!(values, (0..16).collect::>()); + let values = collect_scan_values(futures::executor::block_on_stream(waiter))?; + assert_eq!(values.len(), 16); + let mut sorted = values; + sorted.sort_unstable(); + assert_eq!(sorted, (0..16).collect::>()); + assert!(futures::executor::block_on(idle.next()).is_none()); Ok(()) } @@ -1478,10 +1447,10 @@ mod pool_tests { Ok(()) } - /// A worker dropped while it opens a file gives up only that file: the next deferred file - /// still opens, and other workers read it. + /// Opens run in the pool's lanes, not in its workers, so dropping a worker that is waiting + /// on an open gives up nothing: the other workers still read every file. #[test] - fn dropped_opener_strands_only_its_file() -> VortexResult<()> { + fn dropped_worker_gives_up_nothing() -> VortexResult<()> { let (source, gates) = counted_source(3, 2, &Arc::default()); let source = source.with_concurrency(1); let pool = plan(&source, ScanRequest::default())?.open()?; @@ -1490,11 +1459,12 @@ mod pool_tests { assert!(poll_worker(&mut dropped, &mut noop).is_pending()); drop(dropped); - gates[1].release(); - gates[2].release(); + for gate in &gates { + gate.release(); + } let mut values = read_with_one_worker(pool)?; values.sort_unstable(); - assert_eq!(values, [100, 101, 200, 201]); + assert_eq!(values, [0, 1, 100, 101, 200, 201]); Ok(()) } @@ -1605,11 +1575,16 @@ mod pool_tests { Ok(()) } - /// A worker reads at most `split_concurrency` splits at once. + /// A pool reads at most `split_concurrency` splits at once, however many workers read it. #[rstest] - #[case(1)] - #[case(2)] - fn split_concurrency_bounds_each_worker(#[case] max: usize) -> VortexResult<()> { + #[case::ordered(true, 1)] + #[case::ordered(true, 2)] + #[case::unordered(false, 1)] + #[case::unordered(false, 2)] + fn split_concurrency_bounds_the_pool( + #[case] ordered: bool, + #[case] max: usize, + ) -> VortexResult<()> { let in_flight = Arc::new(InFlight::default()); let reader: LayoutReaderRef = Arc::new( TestLayoutReader::new(64) @@ -1620,13 +1595,15 @@ mod pool_tests { let pool = plan( &source, ScanRequest { - ordered: true, + ordered, split_concurrency: NonZeroUsize::new(max), ..Default::default() }, )? .open()?; - assert_eq!(read_with_one_worker(pool)?, (0..64).collect::>()); + let mut values = read_with_workers(&pool, 4)?.concat(); + values.sort_unstable(); + assert_eq!(values, (0..64).collect::>()); assert!(in_flight.peak() <= max, "peak {}", in_flight.peak()); Ok(()) } diff --git a/vortex-layout/src/scan/pool.rs b/vortex-layout/src/scan/pool.rs index 973623e8eba..fa58016a7dd 100644 --- a/vortex-layout/src/scan/pool.rs +++ b/vortex-layout/src/scan/pool.rs @@ -3,34 +3,40 @@ //! The work that the workers of an opened layout scan share. //! -//! A pool's units are the splits of one or more files, and the files not yet opened. A worker -//! takes units and keeps several splits in flight, each spawned onto the session's runtime; it -//! never starts threads of its own. Opening a deferred file is a unit like any other, and at most -//! `open_concurrency` opens are queued or running at once. +//! A pool's units are the splits of one or more files, and the files not yet opened. Its splits +//! run as tasks on the session's runtime, at most `splits_in_flight` at once across the whole +//! pool; it never starts threads of its own. Opening a deferred file is a unit like any other, and +//! at most `open_concurrency` opens are queued or running at once. //! //! Splits run as [`RepeatedScan::execute_stream`] runs them: //! -//! - A scan with a filter and a limit builds each split on a CPU thread only once a worker takes -//! it ([`spawn_lazy_split`]), so no new split starts once the limit is spent, and optimizes the +//! - A scan with a filter and a limit builds each split on a CPU thread only once it is taken +//! to run ([`spawn_lazy_split`]), so no new split starts once the limit is spent, and optimizes the //! rows the limit keeps on a second CPU task ([`spawn_map_trimmed`]). -//! - Every other scan builds all of a file's split tasks together, when a worker first takes one -//! of them, so the file's reads are registered at once and can coalesce. A limit is reserved +//! - Every other scan builds all of a file's split tasks together, when the first of them is +//! taken, so the file's reads are registered at once and can coalesce. A limit is reserved //! then, in split order. //! -//! The pools differ in how workers share units: +//! The pools differ in how workers share the work: //! -//! - An unordered pool hands units out through a channel. The worker that opens a deferred file -//! sends the file's splits back into the channel, where any worker can take them, followed by -//! the next deferred file. The channel closes once every open has finished, which ends the -//! workers. -//! - An ordered pool gives all of its units, in row order, to its first worker; later workers -//! get nothing. Parallel ordered reads cut the scan with `split` first. +//! - An unordered pool runs `splits_in_flight` lanes on the runtime once its first worker starts. +//! Each lane takes the next unit from a channel of units, runs it, and sends its rows into one +//! bounded output channel; a lane that opens a deferred file sends the file's splits back into +//! the channel of units, followed by the next deferred file. Workers only take rows from the +//! output channel, so whichever worker asks next gets the next rows, however many workers there +//! are, and the number of workers is only the host's parallelism. The output channel closes +//! once every lane has finished, which ends the workers. +//! - An ordered pool gives all of its units, in row order, to its first worker, which keeps +//! `splits_in_flight` of them running at once; later workers get nothing. Parallel ordered reads +//! cut the scan with `split` first. use std::any::Any; use std::collections::VecDeque; use std::num::NonZeroUsize; use std::ops::Range; use std::sync::Arc; +use std::sync::atomic::AtomicBool; +use std::sync::atomic::Ordering; use async_channel::Receiver; use async_channel::Sender; @@ -50,6 +56,7 @@ use vortex_array::stream::ArrayStreamAdapter; use vortex_array::stream::ArrayStreamExt; use vortex_array::stream::SendableArrayStream; use vortex_error::VortexResult; +use vortex_io::runtime::Task; use vortex_io::session::RuntimeSessionExt; use vortex_scan::DataSourceScanRef; use vortex_scan::Partition; @@ -194,12 +201,10 @@ pub(crate) fn open_pool( Some(limit) if options.has_filter => PoolLimit::Trim(RowLimit::new(limit)), Some(limit) => PoolLimit::Reserve(RowLimit::new(limit)), }; - // A worker takes the place of a partition that one host thread drains, so it keeps as many - // splits in flight as a partition's stream does by default: four per core, at most the - // request's `split_concurrency`. A host with a worker per core therefore has the in-flight - // total of the partitions path, where each of DuckDB's threads drained one file's partition - // and each of DataFusion's `target_partitions` streams drained one partition, each with up to - // `4 × cores` splits in flight. + // The pool keeps as many splits in flight as one scan stream does by default: four per core, + // at most the request's `split_concurrency`, however many workers read it. The runtime's + // threads decode them, so more in flight would only read further ahead, and the file's + // registered reads already let I/O coalesce ahead of the splits being decoded. let splits_in_flight = SplitConcurrency { per_worker: DEFAULT_SPLITS_PER_THREAD, max: options.split_concurrency, @@ -214,6 +219,7 @@ pub(crate) fn open_pool( file_share: 1.0 / files.len().max(1) as f64, progress: Mutex::new(0.0), deferred: Mutex::new(VecDeque::new()), + failed: AtomicBool::new(false), }); if options.ordered { return Arc::new(OrderedPool { @@ -245,10 +251,13 @@ pub(crate) fn open_pool( PoolFile::Deferred(factory) => shared.deferred.lock().push_back(factory), } } + let (output, outputs) = async_channel::bounded(splits_in_flight); Arc::new(UnorderedPool { dtype: options.dtype, shared, - receiver, + units: receiver, + outputs, + lanes: Mutex::new(Lanes::Idle(output)), splits_in_flight, }) } @@ -297,6 +306,8 @@ struct Shared { progress: Mutex, /// An unordered pool's deferred files that are not yet queued for opening, in file order. deferred: Mutex>>, + /// Whether a unit of an unordered pool failed, which stops its lanes. + failed: AtomicBool, } impl Shared { @@ -390,13 +401,12 @@ impl Shared { self.progress.lock().clamp(0.0, 1.0) } - /// A worker's output: skips splits with no rows, trims to a trimmed limit, and ends after the - /// first error or once a trimmed limit is spent. A trimmed array is optimized again, on a CPU - /// task, `splits_in_flight` at a time. + /// An ordered worker's output: skips splits with no rows, trims to a trimmed limit, and ends + /// after the first error or once a trimmed limit is spent. A trimmed array is optimized again, + /// on a CPU task, `splits_in_flight` at a time. fn output( self: Arc, outputs: BoxStream<'static, VortexResult>>, - ordered: bool, splits_in_flight: usize, ) -> BoxStream<'static, VortexResult> { let trimmed = matches!(self.limit, PoolLimit::Trim(_)); @@ -410,12 +420,7 @@ impl Shared { let mapped = arrays.map(move |array| { spawn_map_trimmed(&handle, session.clone(), Arc::clone(&identity), array) }); - let mapped = if ordered { - mapped.buffered(splits_in_flight).boxed() - } else { - mapped.buffer_unordered(splits_in_flight).boxed() - }; - stop_on_error(mapped) + stop_on_error(mapped.buffered(splits_in_flight).boxed()) } } @@ -492,11 +497,24 @@ fn send(sender: &Sender, work: Work) { drop(sender.try_send(work)); } -/// A pool whose workers share its units through a channel. +/// The lanes of an unordered pool. +enum Lanes { + /// Not started: the sender of the output channel, for the lanes to hold once they start. + Idle(Sender>), + /// Running, until the pool is dropped, which aborts them. + Running( + #[expect(dead_code, reason = "held so that dropping the pool aborts the lanes")] + Vec>, + ), +} + +/// A pool whose lanes run its units on the runtime, and whose workers share their output. struct UnorderedPool { dtype: DType, shared: Arc, - receiver: Receiver, + units: Receiver, + outputs: Receiver>, + lanes: Mutex, splits_in_flight: usize, } @@ -517,6 +535,73 @@ impl UnorderedPool { .boxed(), } } + + /// Starts the lanes, once. + fn start_lanes(&self) { + let mut lanes = self.lanes.lock(); + let Lanes::Idle(output) = &*lanes else { + return; + }; + let output = output.clone(); + let handle = self.shared.session.handle(); + let running = (0..self.splits_in_flight) + .map(|_| { + handle.spawn(lane( + Arc::clone(&self.shared), + self.units.clone(), + output.clone(), + )) + }) + .collect(); + // Dropping the pool's own sender leaves the lanes holding the output channel open. + *lanes = Lanes::Running(running); + } +} + +/// A lane: runs units one at a time and sends their rows to the workers, trimming them to a +/// trimmed limit. Ends once the units run out, a limit is spent, a unit fails, or every worker +/// is gone. +async fn lane(shared: Arc, units: Receiver, output: Sender>) { + let handle = shared.session.handle(); + let identity: MapFn = Arc::new(Ok); + while !shared.limit.is_trimmed_out() && !shared.failed.load(Ordering::Acquire) { + let Ok(work) = units.recv().await else { + return; + }; + let array = match UnorderedPool::run(&shared, work).await { + Ok(Some(array)) => Ok(array), + Ok(None) => continue, + Err(err) => Err(err), + }; + let array = match (&shared.limit, array) { + (PoolLimit::Trim(limit), Ok(array)) => { + let granted = limit.take(array.len()); + if granted == 0 { + return; + } + let array = if granted < array.len() { + array.slice(0..granted) + } else { + Ok(array) + }; + spawn_map_trimmed( + &handle, + shared.session.clone(), + Arc::clone(&identity), + array, + ) + .await + } + (_, array) => array, + }; + let failed = array.is_err(); + if failed { + shared.failed.store(true, Ordering::Release); + } + if output.send(array).await.is_err() || failed { + return; + } + } } impl ScanPool for UnorderedPool { @@ -525,21 +610,15 @@ impl ScanPool for UnorderedPool { } fn worker(self: Arc) -> SendableArrayStream { + self.start_lanes(); let dtype = self.dtype.clone(); - let shared = Arc::clone(&self.shared); - let runner = Arc::clone(&shared); - let receiver = self.receiver.clone(); - let splits_in_flight = self.splits_in_flight; - // The worker holds the pool, so the pool is dropped only after its last worker. - let outputs = receiver - .take_while(move |_| future::ready(!self.shared.limit.is_trimmed_out())) - .map(move |work| UnorderedPool::run(&runner, work)) - .buffer_unordered(splits_in_flight) - .boxed(); - ArrayStreamExt::boxed(ArrayStreamAdapter::new( - dtype, - shared.output(outputs, false, splits_in_flight), - )) + // The worker holds the pool, so the lanes run until the pool's last worker is dropped. + let arrays = stream::unfold(self, |pool| async move { + let array = pool.outputs.recv().await.ok()?; + Some((array, pool)) + }) + .boxed(); + ArrayStreamExt::boxed(ArrayStreamAdapter::new(dtype, stop_on_error(arrays))) } fn progress(&self) -> f64 { @@ -550,17 +629,18 @@ impl ScanPool for UnorderedPool { } fn is_exhausted(&self) -> bool { - // Open slots hold senders, so the channel closes only once every unit is in it. - self.shared.limit.is_trimmed_out() - || (self.receiver.is_closed() && self.receiver.is_empty()) + // The lanes hold the output channel's senders, so it closes once every lane has ended. + self.outputs.is_closed() && self.outputs.is_empty() } } impl Drop for UnorderedPool { fn drop(&mut self) { - // Pending opens hold senders of the channel itself; drain them so it can be freed. - self.receiver.close(); - while self.receiver.try_recv().is_ok() {} + // Pending opens hold senders of the channel of units itself; drain them so it can be + // freed. The lanes are aborted when they are dropped. + self.units.close(); + while self.units.try_recv().is_ok() {} + self.outputs.close(); } } @@ -611,7 +691,7 @@ impl ScanPool for OrderedPool { .boxed(); ArrayStreamExt::boxed(ArrayStreamAdapter::new( dtype, - shared.output(outputs, true, self.splits_in_flight), + shared.output(outputs, self.splits_in_flight), )) } From 52a122f0f410f42128c26b61d66044fe93fa500b Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Thu, 19 Nov 2026 22:06:23 -0500 Subject: [PATCH 08/25] Run an unordered pool's units on the lane that takes them A lane is already a task on the session's runtime, so spawning each split and each deferred-file open as a second task and awaiting it only added a spawn and a cross-thread wake per unit. The ordered pool, whose units are polled by its worker on the host thread, still spawns them. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-layout/src/scan/pool.rs | 61 +++++++++++++++++++++++----------- 1 file changed, 42 insertions(+), 19 deletions(-) diff --git a/vortex-layout/src/scan/pool.rs b/vortex-layout/src/scan/pool.rs index fa58016a7dd..cd7fdfd9111 100644 --- a/vortex-layout/src/scan/pool.rs +++ b/vortex-layout/src/scan/pool.rs @@ -336,7 +336,7 @@ impl Shared { .collect() } - /// Opens a deferred file into its work on the session's runtime. A file that starts after + /// Opens a deferred file into its work, on the task that polls it. A file that starts after /// the limit is spent is not opened. fn open_file( self: &Arc, @@ -346,19 +346,28 @@ impl Shared { return future::ready(Ok(FileWork::empty())).boxed(); } let shared = Arc::clone(self); - self.session - .handle() - .spawn(async move { - let reader = factory - .open() - .instrument(tracing::info_span!("LayoutReaderFactory::open")) - .await?; - match (reader, &shared.prepare) { - (Some(reader), Some(prepare)) => prepare(reader), - _ => Ok(FileWork::empty()), - } - }) - .boxed() + async move { + let reader = factory + .open() + .instrument(tracing::info_span!("LayoutReaderFactory::open")) + .await?; + match (reader, &shared.prepare) { + (Some(reader), Some(prepare)) => prepare(reader), + _ => Ok(FileWork::empty()), + } + } + .boxed() + } + + /// Opens a deferred file into its work as a task on the session's runtime. + fn spawn_open_file( + self: &Arc, + factory: Arc, + ) -> BoxFuture<'static, VortexResult> { + if self.limit.is_spent() { + return future::ready(Ok(FileWork::empty())).boxed(); + } + self.session.handle().spawn(self.open_file(factory)).boxed() } /// The next deferred file of an unordered pool to open, if any is left and the limit is not @@ -372,8 +381,19 @@ impl Shared { deferred.pop_front() } - /// Takes a split and runs it on the session's runtime. - fn admit(self: &Arc, (file, index, progress): FileSplit) -> SplitOutput { + /// Takes a split and runs it as a task on the session's runtime. + fn admit(self: &Arc, split: FileSplit) -> SplitOutput { + self.take_split(split, true) + } + + /// Takes a split. A split of a scan with a filter and a limit is built and run as + /// [`spawn_lazy_split`] runs it; any other split runs as a task on the session's runtime when + /// `spawn` is set, or else on the task that polls it, such as a lane, which is already one. + fn take_split( + self: &Arc, + (file, index, progress): FileSplit, + spawn: bool, + ) -> SplitOutput { *self.progress.lock() += progress; let handle = self.session.handle(); if let PoolLimit::Trim(_) = &self.limit { @@ -387,7 +407,8 @@ impl Shared { async move { let task = file.tasks(&shared.limit).await?[index].lock().take(); match task { - Some(task) => handle.spawn(task).await, + Some(task) if spawn => handle.spawn(task).await, + Some(task) => task.await, None => Ok(None), } } @@ -519,9 +540,11 @@ struct UnorderedPool { } impl UnorderedPool { + /// Runs a unit on the lane that took it. The lane is already a task on the runtime, so + /// spawning the unit as another task would only add a hop. fn run(shared: &Arc, work: Work) -> SplitOutput { match work { - Work::Split(split) => shared.admit(split), + Work::Split(split) => shared.take_split(split, false), Work::Open(factory, slot) => async move { let opened = slot.shared.open_file(factory).await.map(|work| { for split in slot.shared.file_splits(work) { @@ -673,7 +696,7 @@ impl ScanPool for OrderedPool { let outputs = stream::iter(files) .map(move |file| match file { PoolFile::Opened(work) => future::ready(Ok(work)).boxed(), - PoolFile::Deferred(factory) => opener.open_file(factory), + PoolFile::Deferred(factory) => opener.spawn_open_file(factory), }) .buffered(self.open_concurrency) .flat_map(move |work| match work { From 530b9434c6cabeda141b6f35c9f494de2553edcf Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Thu, 19 Nov 2026 22:07:19 -0500 Subject: [PATCH 09/25] Recheck whole-file pruning when a pooled file's first split is taken A pool checks a file's statistics against the filter when the file starts, which for an opened scan is when the pool opens. A filter with dynamic parts, such as a join's, may reject the file by the time its splits run, and execute_stream checks when it starts reading. Check again, once per file, when the first split is taken. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-layout/src/scan/pool.rs | 39 +++++++++++++++++++++---- vortex-layout/src/scan/repeated_scan.rs | 7 +++++ 2 files changed, 41 insertions(+), 5 deletions(-) diff --git a/vortex-layout/src/scan/pool.rs b/vortex-layout/src/scan/pool.rs index cd7fdfd9111..01248d86547 100644 --- a/vortex-layout/src/scan/pool.rs +++ b/vortex-layout/src/scan/pool.rs @@ -75,6 +75,7 @@ use crate::scan::repeated_scan::MapFn; use crate::scan::repeated_scan::RepeatedScan; use crate::scan::repeated_scan::SplitConcurrency; use crate::scan::repeated_scan::can_prune_file; +use crate::scan::repeated_scan::recheck_prune_file; use crate::scan::repeated_scan::spawn_lazy_split; use crate::scan::repeated_scan::spawn_map_trimmed; use crate::scan::repeated_scan::stop_on_error; @@ -98,15 +99,33 @@ pub(crate) struct FileScan { /// The task of each split, built together when a worker first takes one of them. `None` /// where the split has no rows to read, or a worker has taken it. tasks: OnceCell>>>, + /// Whether whole-file statistics reject the filter when the file's first split is taken. + pruned: OnceCell, } impl FileScan { + /// Whether whole-file statistics reject the filter, checked again when the first split is + /// taken, as [`RepeatedScan::execute_stream`] checks when it starts: a filter with dynamic + /// parts may reject the file by then though it did not when the pool was opened. + async fn is_pruned(&self) -> VortexResult { + let pruned = self + .pruned + .get_or_try_init(|| future::ready(recheck_prune_file(&self.ctx))) + .await?; + Ok(*pruned) + } + /// The tasks of the file's splits, built on first use. A file whose tasks are built once a - /// reserved limit is spent builds none. + /// reserved limit is spent, or that statistics now reject, builds none. async fn tasks(&self, limit: &PoolLimit) -> VortexResult<&[Mutex>]> { let tasks = self .tasks - .get_or_try_init(|| future::ready(self.build_tasks(limit))) + .get_or_try_init(|| async { + if self.is_pruned().await? { + return Ok(Vec::new()); + } + self.build_tasks(limit) + }) .await?; Ok(tasks) } @@ -162,6 +181,7 @@ impl FileWork { ctx, ranges, tasks: OnceCell::new(), + pruned: OnceCell::new(), })), }) } @@ -400,12 +420,21 @@ impl Shared { let Some(mask) = file.scan.split_mask(&file.ranges[index]) else { return future::ready(Ok(None)).boxed(); }; - return spawn_lazy_split(&handle, move || split_exec(&file.ctx, mask).map(Some)) - .boxed(); + return async move { + if file.is_pruned().await? { + return Ok(None); + } + spawn_lazy_split(&handle, move || split_exec(&file.ctx, mask).map(Some)).await + } + .boxed(); } let shared = Arc::clone(self); async move { - let task = file.tasks(&shared.limit).await?[index].lock().take(); + let task = file + .tasks(&shared.limit) + .await? + .get(index) + .and_then(|task| task.lock().take()); match task { Some(task) if spawn => handle.spawn(task).await, Some(task) => task.await, diff --git a/vortex-layout/src/scan/repeated_scan.rs b/vortex-layout/src/scan/repeated_scan.rs index 4431e452ce9..e1654b05e98 100644 --- a/vortex-layout/src/scan/repeated_scan.rs +++ b/vortex-layout/src/scan/repeated_scan.rs @@ -417,6 +417,13 @@ fn selected_mask(selection: &Selection, range: &Range) -> Option { /// Counts a file scan attempt and returns whether whole-file statistics reject the filter. pub(crate) fn can_prune_file(ctx: &TaskContext) -> VortexResult { ctx.count::(ScanRecorder::attempt_file_scan); + recheck_prune_file(ctx) +} + +/// Returns whether whole-file statistics reject the filter, for a file whose scan attempt +/// [`can_prune_file`] has already counted. A filter with dynamic parts, such as a join's, may +/// reject a file later that it did not reject when the scan started. +pub(crate) fn recheck_prune_file(ctx: &TaskContext) -> VortexResult { if let Some(filter) = &ctx.filter && can_prune_conjuncts(filter, ctx.reader.as_ref())? { From 99967430e21b2cfebcb4dcc7f25057b423c6085a Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Thu, 19 Nov 2026 22:10:32 -0500 Subject: [PATCH 10/25] Start an unordered pool's lanes only as units are ready A pool started splits_in_flight lanes, four per core, when its first worker started, and woke every one of them to end, however few units the scan had. A TPC-H query scans several small single-file tables, so it paid that spawn and teardown once per table. Lanes now start one for each unit that no waiting lane will take, when the first worker starts and whenever a lane takes a unit with more queued behind it, up to splits_in_flight. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-layout/src/scan/pool.rs | 113 ++++++++++++++++++++++----------- 1 file changed, 77 insertions(+), 36 deletions(-) diff --git a/vortex-layout/src/scan/pool.rs b/vortex-layout/src/scan/pool.rs index 01248d86547..5f367d2883f 100644 --- a/vortex-layout/src/scan/pool.rs +++ b/vortex-layout/src/scan/pool.rs @@ -19,10 +19,11 @@ //! //! The pools differ in how workers share the work: //! -//! - An unordered pool runs `splits_in_flight` lanes on the runtime once its first worker starts. -//! Each lane takes the next unit from a channel of units, runs it, and sends its rows into one -//! bounded output channel; a lane that opens a deferred file sends the file's splits back into -//! the channel of units, followed by the next deferred file. Workers only take rows from the +//! - An unordered pool runs lanes on the runtime once its first worker starts: one for each unit +//! that is ready, more as units queue, and at most `splits_in_flight`. Each lane takes the next +//! unit from a channel of units, runs it, and sends its rows into one bounded output channel; a +//! lane that opens a deferred file sends the file's splits back into the channel of units, +//! followed by the next deferred file. Workers only take rows from the //! output channel, so whichever worker asks next gets the next rows, however many workers there //! are, and the number of workers is only the host's parallelism. The output channel closes //! once every lane has finished, which ends the workers. @@ -36,6 +37,7 @@ use std::num::NonZeroUsize; use std::ops::Range; use std::sync::Arc; use std::sync::atomic::AtomicBool; +use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering; use async_channel::Receiver; @@ -272,13 +274,21 @@ pub(crate) fn open_pool( } } let (output, outputs) = async_channel::bounded(splits_in_flight); + let lanes = Arc::new(Lanes { + shared: Arc::clone(&shared), + units: receiver.clone(), + max: splits_in_flight, + waiting: AtomicUsize::new(0), + started: AtomicUsize::new(0), + tasks: Mutex::new(Some(Vec::new())), + }); Arc::new(UnorderedPool { dtype: options.dtype, shared, units: receiver, outputs, - lanes: Mutex::new(Lanes::Idle(output)), - splits_in_flight, + lanes, + output: Mutex::new(Some(output)), }) } @@ -547,15 +557,49 @@ fn send(sender: &Sender, work: Work) { drop(sender.try_send(work)); } -/// The lanes of an unordered pool. -enum Lanes { - /// Not started: the sender of the output channel, for the lanes to hold once they start. - Idle(Sender>), - /// Running, until the pool is dropped, which aborts them. - Running( - #[expect(dead_code, reason = "held so that dropping the pool aborts the lanes")] - Vec>, - ), +/// The lanes of an unordered pool. They start when its first worker does, as many as there are +/// units ready, and grow while units wait for a lane, up to `splits_in_flight`, so a scan with +/// few units spawns and wakes few tasks. +struct Lanes { + shared: Arc, + units: Receiver, + /// The most lanes that run at once. + max: usize, + /// Lanes waiting for a unit. + waiting: AtomicUsize, + /// Lanes started, so a lane can see without a lock that no more may start. + started: AtomicUsize, + /// The lanes started, until the pool is dropped, which aborts them. `None` once it is. + tasks: Mutex>>>, +} + +impl Lanes { + /// Starts lanes for the units that no waiting lane will take, up to the most that run at + /// once. Each lane holds a sender of the output channel. + fn grow(self: &Arc, output: &Sender>) { + // Every lane calls this for every unit it takes, so it locks only to start lanes. + if self.started.load(Ordering::Acquire) >= self.max || self.unserved() == 0 { + return; + } + let mut tasks = self.tasks.lock(); + let Some(tasks) = tasks.as_mut() else { + return; + }; + let new = self.unserved().min(self.max.saturating_sub(tasks.len())); + if new == 0 { + return; + } + let handle = self.shared.session.handle(); + tasks.extend((0..new).map(|_| handle.spawn(lane(Arc::clone(self), output.clone())))); + self.started.store(tasks.len(), Ordering::Release); + } + + /// The units that the lanes waiting for one will not take. + fn unserved(&self) -> usize { + self.units + .len() + .saturating_sub(self.waiting.load(Ordering::Acquire)) + } } /// A pool whose lanes run its units on the runtime, and whose workers share their output. @@ -564,8 +608,10 @@ struct UnorderedPool { shared: Arc, units: Receiver, outputs: Receiver>, - lanes: Mutex, - splits_in_flight: usize, + lanes: Arc, + /// The sender of the output channel until the first worker starts the lanes, which hold it + /// from then on. + output: Mutex>>>, } impl UnorderedPool { @@ -588,38 +634,32 @@ impl UnorderedPool { } } - /// Starts the lanes, once. + /// Starts the lanes, once. With no units, it starts none, and the output channel closes. fn start_lanes(&self) { - let mut lanes = self.lanes.lock(); - let Lanes::Idle(output) = &*lanes else { - return; - }; - let output = output.clone(); - let handle = self.shared.session.handle(); - let running = (0..self.splits_in_flight) - .map(|_| { - handle.spawn(lane( - Arc::clone(&self.shared), - self.units.clone(), - output.clone(), - )) - }) - .collect(); // Dropping the pool's own sender leaves the lanes holding the output channel open. - *lanes = Lanes::Running(running); + if let Some(output) = self.output.lock().take() { + self.lanes.grow(&output); + } } } /// A lane: runs units one at a time and sends their rows to the workers, trimming them to a /// trimmed limit. Ends once the units run out, a limit is spent, a unit fails, or every worker /// is gone. -async fn lane(shared: Arc, units: Receiver, output: Sender>) { +async fn lane(lanes: Arc, output: Sender>) { + let shared = Arc::clone(&lanes.shared); let handle = shared.session.handle(); let identity: MapFn = Arc::new(Ok); while !shared.limit.is_trimmed_out() && !shared.failed.load(Ordering::Acquire) { - let Ok(work) = units.recv().await else { + lanes.waiting.fetch_add(1, Ordering::AcqRel); + let work = lanes.units.recv().await; + lanes.waiting.fetch_sub(1, Ordering::AcqRel); + let Ok(work) = work else { return; }; + // Units the waiting lanes will not take get lanes of their own, such as the splits an + // open has just queued. + lanes.grow(&output); let array = match UnorderedPool::run(&shared, work).await { Ok(Some(array)) => Ok(array), Ok(None) => continue, @@ -693,6 +733,7 @@ impl Drop for UnorderedPool { self.units.close(); while self.units.try_recv().is_ok() {} self.outputs.close(); + drop(self.lanes.tasks.lock().take()); } } From 235d5396e95e31d43a97ca08ff2088611e41b02e Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Thu, 19 Nov 2026 22:36:46 -0500 Subject: [PATCH 11/25] Read an unordered pool's opened files in turn An unordered pool queued each opened file's splits one after another, so its lanes read about one file at a time. A wide scan then waited on that file's read latency, and every split of the file was started before the first rows could tighten a dynamic filter. Each opened file is now one turn in the channel: a lane takes the file's next split and queues the turn again behind the other files', so the lanes read the open files' splits in turn. On ClickBench q23 through DataFusion this cut wall time from 169 to 114 ms (develop: 139 ms) and scan output rows from 886 to 400 (develop: 2,425); q22 returned to parity. Lanes now grow with the splits and opens pending rather than the units in the channel, since a file is a single unit. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-layout/src/scan/multi.rs | 18 ++++++ vortex-layout/src/scan/pool.rs | 107 +++++++++++++++++++++++--------- 2 files changed, 96 insertions(+), 29 deletions(-) diff --git a/vortex-layout/src/scan/multi.rs b/vortex-layout/src/scan/multi.rs index 9ccbe87712d..b2960e702bd 100644 --- a/vortex-layout/src/scan/multi.rs +++ b/vortex-layout/src/scan/multi.rs @@ -1345,6 +1345,24 @@ mod pool_tests { Ok(()) } + /// An unordered pool takes the opened files' splits in turn. With one lane, rows come out in + /// the order the lane takes splits. + #[test] + fn unordered_splits_interleave_across_files() -> VortexResult<()> { + let (source, gates) = gated_source(2, 3); + for gate in &gates { + gate.release(); + } + let request = ScanRequest { + split_concurrency: NonZeroUsize::new(1), + ..Default::default() + }; + let pool = plan(&source.with_concurrency(2), request)?.open()?; + let values = collect_scan_values(futures::executor::block_on_stream(pool.worker()))?; + assert_eq!(values, [0, 100, 1, 101, 2, 102]); + Ok(()) + } + /// An ordered worker emits files in file order, even when a later file opens first. #[test] fn ordered_worker_emits_files_in_order() -> VortexResult<()> { diff --git a/vortex-layout/src/scan/pool.rs b/vortex-layout/src/scan/pool.rs index 5f367d2883f..5abc7825de4 100644 --- a/vortex-layout/src/scan/pool.rs +++ b/vortex-layout/src/scan/pool.rs @@ -19,11 +19,12 @@ //! //! The pools differ in how workers share the work: //! -//! - An unordered pool runs lanes on the runtime once its first worker starts: one for each unit -//! that is ready, more as units queue, and at most `splits_in_flight`. Each lane takes the next -//! unit from a channel of units, runs it, and sends its rows into one bounded output channel; a -//! lane that opens a deferred file sends the file's splits back into the channel of units, -//! followed by the next deferred file. Workers only take rows from the +//! - An unordered pool runs lanes on the runtime once its first worker starts: one for each split +//! or open that is ready, more as they queue, and at most `splits_in_flight`. Each lane takes the +//! next unit from a channel of units, runs it, and sends its rows into one bounded output +//! channel. An opened file is one unit, its turn, which a lane queues again after taking the +//! file's next split, so the lanes read the opened files' splits in turn. A lane that opens a +//! deferred file queues the file's turn, followed by the next deferred file. Workers only take rows from the //! output channel, so whichever worker asks next gets the next rows, however many workers there //! are, and the number of workers is only the host's parallelism. The output channel closes //! once every lane has finished, which ends the workers. @@ -242,6 +243,7 @@ pub(crate) fn open_pool( progress: Mutex::new(0.0), deferred: Mutex::new(VecDeque::new()), failed: AtomicBool::new(false), + pending: AtomicUsize::new(0), }); if options.ordered { return Arc::new(OrderedPool { @@ -257,18 +259,14 @@ pub(crate) fn open_pool( let mut opens = 0; for file in files { match file { - PoolFile::Opened(work) => { - for split in shared.file_splits(work) { - send(&sender, Work::Split(split)); - } - } + PoolFile::Opened(work) => shared.queue_file(&sender, work), PoolFile::Deferred(factory) if opens < open_concurrency => { opens += 1; let slot = OpenSlot { shared: Arc::clone(&shared), sender: sender.clone(), }; - send(&sender, Work::Open(factory, slot)); + shared.queue(&sender, Work::Open(factory, slot)); } PoolFile::Deferred(factory) => shared.deferred.lock().push_back(factory), } @@ -338,6 +336,8 @@ struct Shared { deferred: Mutex>>, /// Whether a unit of an unordered pool failed, which stops its lanes. failed: AtomicBool, + /// The splits and opens of an unordered pool that are queued and not yet taken by a lane. + pending: AtomicUsize, } impl Shared { @@ -454,6 +454,24 @@ impl Shared { .boxed() } + /// Queues a unit of an unordered pool, counting the splits or open it holds as pending. + fn queue(&self, sender: &Sender, work: Work) { + let units = match &work { + Work::File(splits, _) => splits.len(), + Work::Open(..) => 1, + }; + self.pending.fetch_add(units, Ordering::AcqRel); + send(sender, work); + } + + /// Queues an opened file of an unordered pool as one turn among the files. + fn queue_file(&self, sender: &Sender, work: FileWork) { + let splits: VecDeque = self.file_splits(work).into(); + if !splits.is_empty() { + self.queue(sender, Work::File(splits, sender.clone())); + } + } + fn progress(&self) -> f64 { if self.limit.is_trimmed_out() { return 1.0; @@ -520,13 +538,41 @@ fn limit_output( .boxed() } -/// A unit of an unordered pool. +/// A unit of an unordered pool's channel. enum Work { + /// An opened file's turn: the splits not yet taken, in row order. The lane that takes the + /// turn takes the file's next split and queues the turn again behind the other files' turns, + /// so the lanes take splits from every opened file in turn rather than from one file after + /// another. Each file then has only a few splits in flight, which keeps its first rows, and + /// any dynamic filter they tighten, ahead of its later splits. + File(VecDeque, Sender), + /// A deferred file, and the open slot it holds until its turn is in the channel. + Open(Arc, OpenSlot), +} + +/// What a lane takes from a unit. +enum Taken { Split(FileSplit), - /// A deferred file, and the open slot it holds until its splits are in the channel. Open(Arc, OpenSlot), } +impl Work { + /// Takes the unit's split or open, queueing a file's turn again while it has splits left. + fn take(self) -> Option { + match self { + Work::File(mut splits, sender) => { + let split = splits.pop_front()?; + if !splits.is_empty() { + let requeue = sender.clone(); + send(&requeue, Work::File(splits, sender)); + } + Some(Taken::Split(split)) + } + Work::Open(factory, slot) => Some(Taken::Open(factory, slot)), + } + } +} + /// One of an unordered pool's `open_concurrency` open slots. Its sender keeps the channel open /// while the file that holds it is queued or opening. struct OpenSlot { @@ -535,8 +581,8 @@ struct OpenSlot { } impl Drop for OpenSlot { - /// Passes the slot to the next deferred file, queued behind the splits of the file that held - /// it, so opens keep pace with the workers. The slot passes on whether the open finished or a + /// Passes the slot to the next deferred file, queued behind the turns already in the channel, + /// so opens keep pace with the workers. The slot passes on whether the open finished or a /// dropped worker gave it up, so that worker strands only the file it was opening. fn drop(&mut self) { if self.sender.is_closed() { @@ -547,7 +593,7 @@ impl Drop for OpenSlot { shared: Arc::clone(&self.shared), sender: self.sender.clone(), }; - send(&self.sender, Work::Open(next, slot)); + self.shared.queue(&self.sender, Work::Open(next, slot)); } } } @@ -558,8 +604,8 @@ fn send(sender: &Sender, work: Work) { } /// The lanes of an unordered pool. They start when its first worker does, as many as there are -/// units ready, and grow while units wait for a lane, up to `splits_in_flight`, so a scan with -/// few units spawns and wakes few tasks. +/// splits and opens ready, and grow while those wait for a lane, up to `splits_in_flight`, so a +/// scan with few units spawns and wakes few tasks. struct Lanes { shared: Arc, units: Receiver, @@ -594,10 +640,11 @@ impl Lanes { self.started.store(tasks.len(), Ordering::Release); } - /// The units that the lanes waiting for one will not take. + /// The pending splits and opens that the lanes waiting for one will not take. fn unserved(&self) -> usize { - self.units - .len() + self.shared + .pending + .load(Ordering::Acquire) .saturating_sub(self.waiting.load(Ordering::Acquire)) } } @@ -617,14 +664,12 @@ struct UnorderedPool { impl UnorderedPool { /// Runs a unit on the lane that took it. The lane is already a task on the runtime, so /// spawning the unit as another task would only add a hop. - fn run(shared: &Arc, work: Work) -> SplitOutput { - match work { - Work::Split(split) => shared.take_split(split, false), - Work::Open(factory, slot) => async move { + fn run(shared: &Arc, taken: Taken) -> SplitOutput { + match taken { + Taken::Split(split) => shared.take_split(split, false), + Taken::Open(factory, slot) => async move { let opened = slot.shared.open_file(factory).await.map(|work| { - for split in slot.shared.file_splits(work) { - send(&slot.sender, Work::Split(split)); - } + slot.shared.queue_file(&slot.sender, work); None }); drop(slot); @@ -657,10 +702,14 @@ async fn lane(lanes: Arc, output: Sender>) { let Ok(work) = work else { return; }; + let Some(taken) = work.take() else { + continue; + }; + shared.pending.fetch_sub(1, Ordering::AcqRel); // Units the waiting lanes will not take get lanes of their own, such as the splits an // open has just queued. lanes.grow(&output); - let array = match UnorderedPool::run(&shared, work).await { + let array = match UnorderedPool::run(&shared, taken).await { Ok(Some(array)) => Ok(array), Ok(None) => continue, Err(err) => Err(err), From 3cd041935340438883ba4fc73f4e6884a9aa7cf8 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Thu, 19 Nov 2026 23:36:33 -0500 Subject: [PATCH 12/25] Hand out an unordered pool's files in runs of adjacent splits Reading opened files in turn handed each file's read driver one polled split at a time, so adjacent splits no longer coalesced into shared reads, and short filtered scans such as ClickBench q01 and q06 paid for many more object-store reads. A file's turn now gives a lane a run of adjacent splits, its share of the splits in flight (splits_in_flight / open_concurrency, four with the defaults), which the lane polls together. The files still rotate, a run at a time, and the lanes still hold splits_in_flight splits in all. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-layout/src/scan/pool.rs | 173 +++++++++++++++++++++------------ 1 file changed, 109 insertions(+), 64 deletions(-) diff --git a/vortex-layout/src/scan/pool.rs b/vortex-layout/src/scan/pool.rs index 5abc7825de4..2f37745a922 100644 --- a/vortex-layout/src/scan/pool.rs +++ b/vortex-layout/src/scan/pool.rs @@ -19,21 +19,24 @@ //! //! The pools differ in how workers share the work: //! -//! - An unordered pool runs lanes on the runtime once its first worker starts: one for each split -//! or open that is ready, more as they queue, and at most `splits_in_flight`. Each lane takes the -//! next unit from a channel of units, runs it, and sends its rows into one bounded output -//! channel. An opened file is one unit, its turn, which a lane queues again after taking the -//! file's next split, so the lanes read the opened files' splits in turn. A lane that opens a -//! deferred file queues the file's turn, followed by the next deferred file. Workers only take rows from the -//! output channel, so whichever worker asks next gets the next rows, however many workers there -//! are, and the number of workers is only the host's parallelism. The output channel closes -//! once every lane has finished, which ends the workers. +//! - An unordered pool runs lanes on the runtime once its first worker starts: one for each run +//! of splits or open that is ready, more as they queue, and at most enough to keep +//! `splits_in_flight` splits running. Each lane takes the next unit from a channel of units, +//! runs it, and sends its rows into one bounded output channel. An opened file is one unit, its +//! turn, which a lane queues again after taking the file's next run of adjacent splits, so the +//! lanes read the opened files in turn, a run at a time, and poll each run's splits together so +//! that their reads coalesce. A lane that opens a deferred file queues the file's turn, followed +//! by the next deferred file. Workers only take rows from the output channel, so whichever +//! worker asks next gets the next rows, however many workers there are, and the number of +//! workers is only the host's parallelism. The output channel closes once every lane has +//! finished, which ends the workers. //! - An ordered pool gives all of its units, in row order, to its first worker, which keeps //! `splits_in_flight` of them running at once; later workers get nothing. Parallel ordered reads //! cut the scan with `split` first. use std::any::Any; use std::collections::VecDeque; +use std::iter; use std::num::NonZeroUsize; use std::ops::Range; use std::sync::Arc; @@ -50,6 +53,7 @@ use futures::future; use futures::future::BoxFuture; use futures::stream; use futures::stream::BoxStream; +use futures::stream::FuturesUnordered; use parking_lot::Mutex; use tracing::Instrument; use vortex_array::ArrayRef; @@ -59,6 +63,7 @@ use vortex_array::stream::ArrayStreamAdapter; use vortex_array::stream::ArrayStreamExt; use vortex_array::stream::SendableArrayStream; use vortex_error::VortexResult; +use vortex_io::runtime::Handle; use vortex_io::runtime::Task; use vortex_io::session::RuntimeSessionExt; use vortex_scan::DataSourceScanRef; @@ -271,11 +276,18 @@ pub(crate) fn open_pool( PoolFile::Deferred(factory) => shared.deferred.lock().push_back(factory), } } + // Each open file gets an equal share of the splits in flight, and a lane takes a file's share + // as one run of adjacent splits that it polls together. The run's reads then reach the + // file's read driver together and coalesce, as they do when one scan stream polls its + // file's splits; a run of one would hand the driver one read at a time. The rotation moves + // between files after each run, and the lanes hold `splits_in_flight` splits in all. + let run = (splits_in_flight / open_concurrency).max(1); let (output, outputs) = async_channel::bounded(splits_in_flight); let lanes = Arc::new(Lanes { shared: Arc::clone(&shared), units: receiver.clone(), - max: splits_in_flight, + run, + max: (splits_in_flight / run).max(1), waiting: AtomicUsize::new(0), started: AtomicUsize::new(0), tasks: Mutex::new(Some(Vec::new())), @@ -541,9 +553,9 @@ fn limit_output( /// A unit of an unordered pool's channel. enum Work { /// An opened file's turn: the splits not yet taken, in row order. The lane that takes the - /// turn takes the file's next split and queues the turn again behind the other files' turns, - /// so the lanes take splits from every opened file in turn rather than from one file after - /// another. Each file then has only a few splits in flight, which keeps its first rows, and + /// turn takes the file's next run of splits and queues the turn again behind the other + /// files' turns, so the lanes take runs from every opened file in turn rather than from one + /// file after another. Each file then has only a few splits in flight, which keeps its first rows, and /// any dynamic filter they tighten, ahead of its later splits. File(VecDeque, Sender), /// A deferred file, and the open slot it holds until its turn is in the channel. @@ -552,21 +564,33 @@ enum Work { /// What a lane takes from a unit. enum Taken { - Split(FileSplit), + /// A run of a file's adjacent splits, in row order. + Splits(Vec), Open(Arc, OpenSlot), } +impl Taken { + /// The pending splits or open that this takes. + fn units(&self) -> usize { + match self { + Taken::Splits(splits) => splits.len(), + Taken::Open(..) => 1, + } + } +} + impl Work { - /// Takes the unit's split or open, queueing a file's turn again while it has splits left. - fn take(self) -> Option { + /// Takes the unit's next `run` splits, or its open, queueing a file's turn again while it + /// has splits left. + fn take(self, run: usize) -> Option { match self { Work::File(mut splits, sender) => { - let split = splits.pop_front()?; + let taken: Vec<_> = splits.drain(..run.min(splits.len())).collect(); if !splits.is_empty() { let requeue = sender.clone(); send(&requeue, Work::File(splits, sender)); } - Some(Taken::Split(split)) + (!taken.is_empty()).then_some(Taken::Splits(taken)) } Work::Open(factory, slot) => Some(Taken::Open(factory, slot)), } @@ -609,6 +633,8 @@ fn send(sender: &Sender, work: Work) { struct Lanes { shared: Arc, units: Receiver, + /// The most adjacent splits of a file that a lane takes and polls together. + run: usize, /// The most lanes that run at once. max: usize, /// Lanes waiting for a unit. @@ -631,7 +657,10 @@ impl Lanes { let Some(tasks) = tasks.as_mut() else { return; }; - let new = self.unserved().min(self.max.saturating_sub(tasks.len())); + let new = self + .unserved() + .div_ceil(self.run) + .min(self.max.saturating_sub(tasks.len())); if new == 0 { return; } @@ -640,12 +669,13 @@ impl Lanes { self.started.store(tasks.len(), Ordering::Release); } - /// The pending splits and opens that the lanes waiting for one will not take. + /// The pending splits and opens that the lanes waiting for a unit will not take, each of + /// which takes up to a run. fn unserved(&self) -> usize { self.shared .pending .load(Ordering::Acquire) - .saturating_sub(self.waiting.load(Ordering::Acquire)) + .saturating_sub(self.waiting.load(Ordering::Acquire) * self.run) } } @@ -664,18 +694,24 @@ struct UnorderedPool { impl UnorderedPool { /// Runs a unit on the lane that took it. The lane is already a task on the runtime, so /// spawning the unit as another task would only add a hop. - fn run(shared: &Arc, taken: Taken) -> SplitOutput { + fn run(shared: &Arc, taken: Taken) -> FuturesUnordered { match taken { - Taken::Split(split) => shared.take_split(split, false), - Taken::Open(factory, slot) => async move { - let opened = slot.shared.open_file(factory).await.map(|work| { - slot.shared.queue_file(&slot.sender, work); - None - }); - drop(slot); - opened - } - .boxed(), + Taken::Splits(splits) => splits + .into_iter() + .map(|split| shared.take_split(split, false)) + .collect(), + Taken::Open(factory, slot) => iter::once( + async move { + let opened = slot.shared.open_file(factory).await.map(|work| { + slot.shared.queue_file(&slot.sender, work); + None + }); + drop(slot); + opened + } + .boxed(), + ) + .collect(), } } @@ -702,47 +738,56 @@ async fn lane(lanes: Arc, output: Sender>) { let Ok(work) = work else { return; }; - let Some(taken) = work.take() else { + let Some(taken) = work.take(lanes.run) else { continue; }; - shared.pending.fetch_sub(1, Ordering::AcqRel); + shared.pending.fetch_sub(taken.units(), Ordering::AcqRel); // Units the waiting lanes will not take get lanes of their own, such as the splits an // open has just queued. lanes.grow(&output); - let array = match UnorderedPool::run(&shared, taken).await { - Ok(Some(array)) => Ok(array), - Ok(None) => continue, - Err(err) => Err(err), - }; - let array = match (&shared.limit, array) { - (PoolLimit::Trim(limit), Ok(array)) => { - let granted = limit.take(array.len()); - if granted == 0 { - return; - } - let array = if granted < array.len() { - array.slice(0..granted) - } else { - Ok(array) - }; - spawn_map_trimmed( - &handle, - shared.session.clone(), - Arc::clone(&identity), - array, - ) - .await + let mut running = UnorderedPool::run(&shared, taken); + while let Some(array) = running.next().await { + let array = match array { + Ok(Some(array)) => Ok(array), + Ok(None) => continue, + Err(err) => Err(err), + }; + if !emit(&shared, &handle, &identity, &output, array).await { + return; } - (_, array) => array, - }; - let failed = array.is_err(); - if failed { - shared.failed.store(true, Ordering::Release); } - if output.send(array).await.is_err() || failed { - return; + } +} + +/// Sends a lane's rows to the workers, trimmed to a trimmed limit. Returns whether the lane +/// should go on: not once the limit is spent, a unit failed, or every worker is gone. +async fn emit( + shared: &Shared, + handle: &Handle, + identity: &MapFn, + output: &Sender>, + array: VortexResult, +) -> bool { + let array = match (&shared.limit, array) { + (PoolLimit::Trim(limit), Ok(array)) => { + let granted = limit.take(array.len()); + if granted == 0 { + return false; + } + let array = if granted < array.len() { + array.slice(0..granted) + } else { + Ok(array) + }; + spawn_map_trimmed(handle, shared.session.clone(), Arc::clone(identity), array).await } + (_, array) => array, + }; + let failed = array.is_err(); + if failed { + shared.failed.store(true, Ordering::Release); } + output.send(array).await.is_ok() && !failed } impl ScanPool for UnorderedPool { From 03bc34a0188d7e1cfc53790429d486b4e9eefd8e Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Thu, 19 Nov 2026 23:55:47 -0500 Subject: [PATCH 13/25] Decode a single-file pool's splits on every core A single-file scan opens one file at a time, so its run was every split in flight and the pool started one lane, which polled the run's splits inline and decoded them on one thread. A run is now at most one core's share of the splits in flight, and each split of a run is spawned as `execute_stream` spawns it: the run still starts its splits together, so their reads coalesce, but they decode in parallel. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-layout/src/scan/pool.rs | 38 ++++++++++++++++------------------ 1 file changed, 18 insertions(+), 20 deletions(-) diff --git a/vortex-layout/src/scan/pool.rs b/vortex-layout/src/scan/pool.rs index 2f37745a922..f345e908c0a 100644 --- a/vortex-layout/src/scan/pool.rs +++ b/vortex-layout/src/scan/pool.rs @@ -74,6 +74,7 @@ use vortex_scan::pool::ScanPool; use vortex_scan::pool::ScanPoolRef; use vortex_scan::row_mask::RowMask; use vortex_session::VortexSession; +use vortex_utils::parallelism::get_available_parallelism; use crate::LayoutReaderRef; use crate::scan::limit::RowLimit; @@ -277,11 +278,16 @@ pub(crate) fn open_pool( } } // Each open file gets an equal share of the splits in flight, and a lane takes a file's share - // as one run of adjacent splits that it polls together. The run's reads then reach the + // as one run of adjacent splits that it starts together. The run's reads then reach the // file's read driver together and coalesce, as they do when one scan stream polls its // file's splits; a run of one would hand the driver one read at a time. The rotation moves - // between files after each run, and the lanes hold `splits_in_flight` splits in all. - let run = (splits_in_flight / open_concurrency).max(1); + // between files after each run, and the lanes hold `splits_in_flight` splits in all. A run is + // at most one core's share, so that a scan of few files, such as a single-file scan whose + // share is every split in flight, still has a lane per core. + let cores = get_available_parallelism().unwrap_or(1).max(1); + let run = (splits_in_flight / open_concurrency) + .min(splits_in_flight / cores) + .max(1); let (output, outputs) = async_channel::bounded(splits_in_flight); let lanes = Arc::new(Lanes { shared: Arc::clone(&shared), @@ -423,19 +429,10 @@ impl Shared { deferred.pop_front() } - /// Takes a split and runs it as a task on the session's runtime. - fn admit(self: &Arc, split: FileSplit) -> SplitOutput { - self.take_split(split, true) - } - /// Takes a split. A split of a scan with a filter and a limit is built and run as - /// [`spawn_lazy_split`] runs it; any other split runs as a task on the session's runtime when - /// `spawn` is set, or else on the task that polls it, such as a lane, which is already one. - fn take_split( - self: &Arc, - (file, index, progress): FileSplit, - spawn: bool, - ) -> SplitOutput { + /// [`spawn_lazy_split`] runs it; any other split runs as a task on the session's runtime, since + /// a split decodes inside its future. + fn admit(self: &Arc, (file, index, progress): FileSplit) -> SplitOutput { *self.progress.lock() += progress; let handle = self.session.handle(); if let PoolLimit::Trim(_) = &self.limit { @@ -458,8 +455,7 @@ impl Shared { .get(index) .and_then(|task| task.lock().take()); match task { - Some(task) if spawn => handle.spawn(task).await, - Some(task) => task.await, + Some(task) => handle.spawn(task).await, None => Ok(None), } } @@ -692,13 +688,15 @@ struct UnorderedPool { } impl UnorderedPool { - /// Runs a unit on the lane that took it. The lane is already a task on the runtime, so - /// spawning the unit as another task would only add a hop. + /// Runs a unit for the lane that took it. Each split of a run runs as a task of its own, as + /// [`RepeatedScan::execute_stream`] runs it, since a split decodes inside its future: the run's + /// splits start together, so their reads coalesce, and decode on as many threads as there + /// are splits. An open runs on the lane itself. fn run(shared: &Arc, taken: Taken) -> FuturesUnordered { match taken { Taken::Splits(splits) => splits .into_iter() - .map(|split| shared.take_split(split, false)) + .map(|split| shared.admit(split)) .collect(), Taken::Open(factory, slot) => iter::once( async move { From 5d18c27db09862c09ad7a78b3c8d2ccfc3b37186 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 13:21:32 -0500 Subject: [PATCH 14/25] Read V1 layout scans through split and open on develop's pipeline Each host should get develop's execution unchanged, so this replaces the shared layout pool with develop's own paths. A single-file scan opens into a queue of its split futures from RepeatedScan::execute: a worker claims the next split and runs it outside the lock, one at a time, which is how DuckDB's threads read a file's splits on develop. A limited or ordered scan, and a multi-file scan, open into a PartitionPool over their unchanged partition pipeline. split cuts a file at its layout split boundaries, and a multi-file scan into groups of whole files, reading metadata only. The I/O and execute_stream changes that served the old pool are reverted. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-io/src/segments/shared.rs | 128 +--- vortex-layout/src/scan/layout.rs | 687 ++++-------------- vortex-layout/src/scan/multi.rs | 926 +++--------------------- vortex-layout/src/scan/pool.rs | 922 ++--------------------- vortex-layout/src/scan/repeated_scan.rs | 111 +-- vortex-layout/src/scan/scan_builder.rs | 5 +- vortex-layout/src/scan/test.rs | 59 -- 7 files changed, 320 insertions(+), 2518 deletions(-) diff --git a/vortex-io/src/segments/shared.rs b/vortex-io/src/segments/shared.rs index bed9394a9d2..dbaf553264a 100644 --- a/vortex-io/src/segments/shared.rs +++ b/vortex-io/src/segments/shared.rs @@ -6,7 +6,6 @@ use std::sync::Arc; use futures::FutureExt; use futures::TryFutureExt; use futures::future::BoxFuture; -use futures::future::Shared; use futures::future::WeakShared; use vortex_array::buffer::BufferHandle; use vortex_error::SharedVortexResult; @@ -21,11 +20,6 @@ use super::SegmentSource; /// A [`SegmentSource`] that allows multiple requesters to await the same underlying segment /// request. -/// -/// Many threads may request segments of one source at once, for example the workers of a scan -/// pool sharing one file's splits. Requests therefore look for a request in flight under a shared -/// lock, call the inner source outside any lock, and take an exclusive lock only to record a new -/// request. pub struct SharedSegmentSource { inner: S, in_flight: DashMap>, @@ -38,117 +32,33 @@ impl SharedSegmentSource { pub fn new(inner: S) -> Self { Self { inner, - // The default shard count scales with the machine's cores, as the requesters do. - in_flight: DashMap::default(), + in_flight: DashMap::with_hasher_and_shard_amount(Default::default(), 64), } } - - /// The request in flight for `id`, if any. - fn in_flight(&self, id: SegmentId) -> Option> { - self.in_flight.get(&id)?.upgrade() - } } impl SegmentSource for SharedSegmentSource { fn request(&self, id: SegmentId) -> SegmentFuture { - if let Some(future) = self.in_flight(id) { - return future.map_err(VortexError::from).boxed(); - } - - let future = self.inner.request(id).map_err(Arc::new).boxed().shared(); - let weak = future - .downgrade() - .vortex_expect("just created, cannot be polled to completion"); - match self.in_flight.entry(id) { - Entry::Occupied(mut entry) => { - if let Some(existing) = entry.get().upgrade() { - // Another requester recorded the same segment first. Its request reads the - // same bytes, so dropping this one changes nothing that is read or coalesced. - return existing.map_err(VortexError::from).boxed(); + loop { + match self.in_flight.entry(id) { + Entry::Occupied(e) => { + if let Some(shared_future) = e.get().upgrade() { + return shared_future.map_err(VortexError::from).boxed(); + } else { + // The future has been dropped, remove the entry and try again. + e.remove(); + } + } + Entry::Vacant(e) => { + let future = self.inner.request(id).map_err(Arc::new).boxed().shared(); + e.insert( + future + .downgrade() + .vortex_expect("just created, cannot be polled to completion"), + ); + return future.map_err(VortexError::from).boxed(); } - entry.insert(weak); - } - Entry::Vacant(entry) => { - entry.insert(weak); } } - future.map_err(VortexError::from).boxed() - } -} - -#[cfg(test)] -mod tests { - use std::sync::Arc; - use std::sync::atomic::AtomicUsize; - use std::sync::atomic::Ordering; - - use futures::FutureExt; - use futures::executor::block_on; - use vortex_array::buffer::BufferHandle; - use vortex_buffer::ByteBuffer; - use vortex_error::VortexResult; - - use super::*; - - /// Counts its requests, and answers each with the segment's id as one byte. - #[derive(Default)] - struct Counting(AtomicUsize); - - impl SegmentSource for Counting { - fn request(&self, id: SegmentId) -> SegmentFuture { - self.0.fetch_add(1, Ordering::SeqCst); - let byte = u8::try_from(*id).unwrap_or(u8::MAX); - async move { Ok(BufferHandle::new_host(ByteBuffer::from(vec![byte]))) }.boxed() - } - } - - #[test] - fn concurrent_requests_share_one_inner_request() -> VortexResult<()> { - let source = SharedSegmentSource::new(Counting::default()); - let first = source.request(SegmentId::from(7)); - let second = source.request(SegmentId::from(7)); - assert_eq!(source.inner.0.load(Ordering::SeqCst), 1); - assert_eq!(block_on(first)?.to_host_sync().as_slice(), [7]); - assert_eq!(block_on(second)?.to_host_sync().as_slice(), [7]); - Ok(()) - } - - #[test] - fn a_finished_request_is_made_again() -> VortexResult<()> { - let source = SharedSegmentSource::new(Counting::default()); - drop(block_on(source.request(SegmentId::from(3)))?); - drop(block_on(source.request(SegmentId::from(3)))?); - assert_eq!(source.inner.0.load(Ordering::SeqCst), 2); - Ok(()) - } - - /// Threads requesting the same segments at once each get their segment. - #[test] - fn racing_requesters_get_their_segments() -> VortexResult<()> { - let source = Arc::new(SharedSegmentSource::new(Counting::default())); - let futures = std::thread::scope(|scope| { - let handles: Vec<_> = (0..8) - .map(|_| { - let source = Arc::clone(&source); - scope.spawn(move || { - (0..64u32) - .map(|id| source.request(SegmentId::from(id))) - .collect::>() - }) - }) - .collect(); - handles - .into_iter() - .flat_map(|handle| handle.join().expect("requester panicked")) - .collect::>() - }); - // A requester that loses a race drops its own inner request, so there may be more than - // one per segment, but never fewer. - assert!(source.inner.0.load(Ordering::SeqCst) >= 64); - for (index, future) in futures.into_iter().enumerate() { - let id = u8::try_from(index % 64).unwrap_or(u8::MAX); - assert_eq!(block_on(future)?.to_host_sync().as_slice(), [id]); - } - Ok(()) } } diff --git a/vortex-layout/src/scan/layout.rs b/vortex-layout/src/scan/layout.rs index 38f801fd9a9..2b4ab2d1d5a 100644 --- a/vortex-layout/src/scan/layout.rs +++ b/vortex-layout/src/scan/layout.rs @@ -14,6 +14,7 @@ use futures::FutureExt; use futures::Stream; use futures::stream; use futures::stream::StreamExt; +use vortex_array::ArrayRef; use vortex_array::IntoArray; use vortex_array::arrays::ConstantArray; use vortex_array::dtype::DType; @@ -37,6 +38,7 @@ use vortex_scan::Partition; use vortex_scan::PartitionRef; use vortex_scan::PartitionStream; use vortex_scan::ScanRequest; +use vortex_scan::pool::PartitionPool; use vortex_scan::pool::ScanPoolRef; use vortex_scan::selection::Selection; use vortex_session::VortexSession; @@ -45,19 +47,10 @@ use crate::LayoutReaderRef; use crate::scan::limit::RowLimit; use crate::scan::metrics::ScanMetrics; use crate::scan::metrics::ScanRecorder; -use crate::scan::pool::FileWork; -use crate::scan::pool::PiecePartition; -use crate::scan::pool::PoolFile; -use crate::scan::pool::PoolOptions; -use crate::scan::pool::PreparedScan; -use crate::scan::pool::open_pool; +use crate::scan::pool::SplitPool; use crate::scan::scan_builder::ScanBuilder; /// An implementation of a [`DataSource`] that reads data from a [`LayoutReaderRef`]. -/// -/// When a scan is [split](DataSourceScan::split) or [opened](DataSourceScan::open), its units are -/// the layout's splits. Workers of an opened scan share them, each keeping several in flight on -/// the session's runtime. pub struct LayoutReaderDataSource { reader: LayoutReaderRef, session: VortexSession, @@ -212,7 +205,6 @@ impl DataSource for LayoutReaderDataSource { dtype, projection, filter, - limit: scan_request.limit, remaining_limit: scan_request.limit, row_limit, selection: scan_request.selection, @@ -236,8 +228,6 @@ struct LayoutReaderScan { dtype: DType, projection: BoundExpression, filter: Option, - /// The request's limit. - limit: Option, /// Limit rows not yet covered by the splits produced so far; production stops at zero. /// Decremented only for filterless scans, where each split's output is exactly its /// selected row count. @@ -254,33 +244,35 @@ struct LayoutReaderScan { } impl LayoutReaderScan { - /// Prepares the scan once, for splitting or opening. - fn into_split_scan(self) -> VortexResult { - let row_count = DataSourceScan::row_count(&self); - let options = LayoutScanOptions { + /// The scan over the rows that remain, as develop's DuckDB scan builds it for a file. + fn builder(&self) -> ScanBuilder { + ScanBuilder::new(self.session.clone(), Arc::clone(&self.reader)) + .with_selection(self.selection.clone()) + .with_projection(self.projection.clone()) + .with_some_filter(self.filter.clone()) + .with_some_scan_metrics(self.metrics.clone()) + .with_some_max_splits_in_flight(self.split_concurrency) + } + + /// This scan over `rows` only. Only a scan without a limit is cut into pieces, so a piece + /// has no limit to share. + fn piece(&self, rows: Range) -> Self { + Self { + reader: Arc::clone(&self.reader), session: self.session.clone(), - dtype: self.dtype, + dtype: self.dtype.clone(), + projection: self.projection.clone(), + filter: self.filter.clone(), + remaining_limit: None, + row_limit: None, ordered: self.ordered, - limit: self.limit, - has_filter: self.filter.is_some(), split_concurrency: self.split_concurrency, - }; - let row_range = clamp_row_range(self.next_row..self.end_row, self.reader.row_count()); - let scan = ScanBuilder::new(self.session, self.reader) - .with_row_range(row_range) - .with_selection(self.selection) - .with_projection(self.projection) - .with_some_filter(self.filter) - .with_some_scan_metrics(self.metrics) - .with_ordered(self.ordered) - .prepare()?; - let ranges = scan.split_ranges(None); - Ok(LayoutSplitScan { - options, - row_count, - scan: Arc::new(scan), - ranges, - }) + selection: self.selection.clone(), + metrics: self.metrics.clone(), + next_row: rows.start, + end_row: rows.end, + split_size: self.split_size, + } } } @@ -289,24 +281,54 @@ impl DataSourceScan for LayoutReaderScan { &self.dtype } - fn partition_count(&self) -> Precision { - let (lower, upper) = self.size_hint(); - match upper { - Some(u) if u == lower => Precision::exact(lower), - Some(u) => Precision::inexact(u), - None => Precision::inexact(lower), + /// Cuts the scan at the layout's natural split boundaries, into pieces of about equal rows. + /// + /// A scan with a limit stays whole, because the limit is one budget across all its rows. + fn split(self: Box, n: NonZeroUsize) -> VortexResult> { + if n.get() == 1 || self.remaining_limit.is_some() || self.next_row >= self.end_row { + return Ok(vec![self]); + } + let ranges = self + .builder() + .prepare()? + .split_ranges(Some(self.next_row..self.end_row)); + let pieces: Vec> = group_contiguous(ranges, n) + .into_iter() + .filter_map(|group| Some(group.first()?.start..group.last()?.end)) + .collect(); + if pieces.len() <= 1 { + return Ok(vec![self]); } + Ok(pieces + .into_iter() + .map(|rows| Box::new(self.piece(rows)) as DataSourceScanRef) + .collect()) } - fn partitions(self: Box) -> PartitionStream { - (*self).boxed() + /// Opens the scan into a queue of its split futures, which workers claim one at a time and + /// run themselves: develop's DuckDB scan of a file. + /// + /// Split futures cannot share a limit, and workers of a queue finish splits out of row + /// order. So a scan with a limit, or an ordered one, keeps its partition pipeline and hands + /// its partitions to workers instead. + fn open(self: Box) -> VortexResult { + if self.remaining_limit.is_some() || self.ordered { + return Ok(Arc::new(PartitionPool::new(self))); + } + let splits = self + .builder() + .prepare()? + .execute(Some(self.next_row..self.end_row))?; + Ok(Arc::new(SplitPool::new(self.dtype, splits))) } fn row_count(&self) -> Precision { let selected = self .selection .row_count_in_range(&(self.next_row..self.end_row)); - let rows = self.limit.map_or(selected, |limit| selected.min(limit)); + let rows = self + .remaining_limit + .map_or(selected, |limit| selected.min(limit)); if self.filter.is_some() { Precision::inexact(rows) } else { @@ -314,129 +336,17 @@ impl DataSourceScan for LayoutReaderScan { } } - fn split(self: Box, n: NonZeroUsize) -> VortexResult> { - Box::new(self.into_split_scan()?).split(n) - } - - fn open(self: Box) -> VortexResult { - Box::new(self.into_split_scan()?).open() - } -} - -/// Clamps a requested row range to the rows of the source. -fn clamp_row_range(row_range: Range, total_rows: u64) -> Range { - let end = row_range.end.min(total_rows); - row_range.start.min(end)..end -} - -/// What a [`LayoutSplitScan`] and every piece cut from it share. -#[derive(Clone)] -struct LayoutScanOptions { - session: VortexSession, - dtype: DType, - ordered: bool, - limit: Option, - has_filter: bool, - split_concurrency: Option, -} - -/// A prepared scan of one layout reader over some of its splits: a [`LayoutReaderScan`] that was -/// split or opened, or a piece cut from one. -struct LayoutSplitScan { - options: LayoutScanOptions, - row_count: Precision, - scan: Arc, - /// The scan's units: its layout splits, in row order. - ranges: Vec>, -} - -impl LayoutSplitScan { - /// A piece over some of the prepared scan's split `ranges`. - fn piece( - options: &LayoutScanOptions, - scan: Arc, - ranges: Vec>, - ) -> Self { - let selected = ranges - .iter() - .map(|range| scan.selected_row_count(range)) - .sum::(); - Self { - options: options.clone(), - row_count: if options.has_filter { - Precision::inexact(selected) - } else { - Precision::exact(selected) - }, - scan, - ranges, - } - } -} - -impl DataSourceScan for LayoutSplitScan { - fn dtype(&self) -> &DType { - &self.options.dtype - } - fn partition_count(&self) -> Precision { - Precision::exact(1usize) - } - - fn partitions(self: Box) -> PartitionStream { - let index = self.ranges.first().map_or(0, |range| { - usize::try_from(range.start).unwrap_or(usize::MAX) - }); - PiecePartition::stream(self, index) - } - - fn row_count(&self) -> Precision { - self.row_count - } - - fn split(self: Box, n: NonZeroUsize) -> VortexResult> { - if self.options.limit.is_some() || self.ranges.len() <= 1 || n.get() == 1 { - return Ok(vec![self]); + let (lower, upper) = self.size_hint(); + match upper { + Some(u) if u == lower => Precision::exact(lower), + Some(u) => Precision::inexact(u), + None => Precision::inexact(lower), } - let LayoutSplitScan { - options, - scan, - ranges, - .. - } = *self; - Ok(group_contiguous(ranges, n) - .into_iter() - .map(|ranges| { - Box::new(LayoutSplitScan::piece(&options, Arc::clone(&scan), ranges)) - as DataSourceScanRef - }) - .collect()) } - fn open(self: Box) -> VortexResult { - let LayoutScanOptions { - session, - dtype, - ordered, - limit, - has_filter, - split_concurrency, - } = self.options; - if limit == Some(0) { - return Box::new(Empty::new(dtype, 0)).open(); - } - let work = FileWork::start(self.scan, self.ranges)?; - let options = PoolOptions { - session, - dtype, - ordered, - limit, - has_filter, - split_concurrency, - // A single opened file has nothing to open. - open_concurrency: 1, - }; - Ok(open_pool(options, vec![PoolFile::Opened(work)], None)) + fn partitions(self: Box) -> PartitionStream { + (*self).boxed() } } @@ -602,22 +512,24 @@ impl Partition for LayoutReaderSplit { } /// A scan that produces no data, only empty arrays with the correct row count. -pub(crate) struct Empty { +struct Empty { dtype: DType, row_count: u64, } -impl Empty { - pub(crate) fn new(dtype: DType, row_count: u64) -> Self { - Self { dtype, row_count } - } -} - impl DataSourceScan for Empty { fn dtype(&self) -> &DType { &self.dtype } + fn split(self: Box, _n: NonZeroUsize) -> VortexResult> { + Ok(vec![self]) + } + + fn open(self: Box) -> VortexResult { + Ok(Arc::new(PartitionPool::new(self))) + } + fn partition_count(&self) -> Precision { Precision::exact(1usize) } @@ -841,417 +753,94 @@ mod tests { } #[cfg(test)] -mod pool_tests { +mod split_open_tests { use std::num::NonZeroUsize; use std::sync::Arc; - use std::sync::atomic::AtomicUsize; - use std::sync::atomic::Ordering; - use futures::StreamExt; - use rstest::rstest; - use vortex_array::dtype::DType; - use vortex_array::dtype::Nullability; - use vortex_array::dtype::StructFields; - use vortex_array::expr::Expression; - use vortex_array::expr::root; - use vortex_buffer::Buffer; + use futures::TryStreamExt; + use futures::executor::block_on; + use futures::executor::block_on_stream; + use futures::future::try_join_all; + use vortex_array::expr::stats::Precision; use vortex_error::VortexResult; - use vortex_metrics::DefaultMetricsRegistry; - use vortex_metrics::MetricValue; - use vortex_metrics::MetricsRegistry; + use vortex_io::runtime::BlockingRuntime; + use vortex_io::runtime::single::SingleThreadRuntime; use vortex_scan::DataSource; - use vortex_scan::DataSourceScanRef; use vortex_scan::ScanRequest; - use vortex_scan::selection::Selection; - use vortex_scan::strict_sorted_buffer::StrictSortedBuffer; use super::LayoutReaderDataSource; use super::group_contiguous; use crate::scan::test::TestLayoutReader; use crate::scan::test::collect_scan_values; - use crate::scan::test::keep_odd; use crate::scan::test::new_session; - use crate::scan::test::read_with_one_worker; - use crate::scan::test::read_with_workers; - - fn counter_values(registry: &DefaultMetricsRegistry) -> Vec { - registry - .snapshot() - .iter() - .map(|metric| match metric.value() { - MetricValue::Counter(counter) => counter.value(), - _ => panic!("expected a scan counter"), - }) - .collect() - } - - fn plan( - source: &LayoutReaderDataSource, - request: ScanRequest, - ) -> VortexResult { - futures::executor::block_on(source.scan(request)) - } - - /// Earlier splits finish last, so completion order is the reverse of row order. - fn slow_start(row: u64) -> usize { - usize::try_from(32u64.saturating_sub(row)).unwrap_or(0) - } + use crate::scan::test::session_with_handle; - fn source(reader: TestLayoutReader) -> LayoutReaderDataSource { - LayoutReaderDataSource::new(Arc::new(reader), new_session()) + fn source() -> LayoutReaderDataSource { + LayoutReaderDataSource::new( + Arc::new(TestLayoutReader::new(64).with_split_size(4)), + new_session(), + ) } - /// Each opened scan is one execution: it counts one file scan, and one attempt per split. + /// Workers of an opened scan each claim splits until none is left, so together they read + /// every row once. #[test] - fn opened_executions_share_aggregate_handles() -> VortexResult<()> { - let registry = Arc::new(DefaultMetricsRegistry::default()); - let source = source(TestLayoutReader::new(8).with_split_size(2)) - .with_metrics_registry(Arc::::clone(®istry)); - for execution in 1..=2 { - let pool = plan(&source, ScanRequest::default())?.open()?; - let values = read_with_workers(&pool, 2)?.concat(); - assert_eq!(values.len(), 8); - assert_eq!( - counter_values(®istry), - [4 * execution, 0, 0, execution, 0] - ); - } - Ok(()) - } - - /// N workers on one pool read every split exactly once. - #[rstest] - #[case::ordered(true)] - #[case::unordered(false)] - fn workers_read_every_split_once(#[case] ordered: bool) -> VortexResult<()> { - let source = source(TestLayoutReader::new(64).with_split_size(1)); - let pool = plan( - &source, - ScanRequest { - ordered, - ..Default::default() - }, - )? - .open()?; - let per_worker = read_with_workers(&pool, 4)?; - - let mut values = per_worker.concat(); + fn opened_workers_read_every_row_once() -> VortexResult<()> { + let pool = block_on(source().scan(ScanRequest::default()))?.open()?; + let workers = (0..3).map(|_| Arc::clone(&pool).worker().try_collect::>()); + let arrays = block_on(try_join_all(workers))?; + let mut values = collect_scan_values(arrays.into_iter().flatten().map(Ok))?; values.sort_unstable(); assert_eq!(values, (0..64).collect::>()); - Ok(()) - } - - /// A worker of an ordered pool yields rows in row order, even when later splits finish - /// first, and later workers of the pool get nothing. - #[test] - fn ordered_worker_yields_row_order() -> VortexResult<()> { - let read = |ordered| { - let source = source( - TestLayoutReader::new(32) - .with_split_size(1) - .with_yields(slow_start), - ); - let pool = plan( - &source, - ScanRequest { - ordered, - ..Default::default() - }, - )? - .open()?; - let first = read_with_one_worker(Arc::clone(&pool))?; - let second = read_with_one_worker(pool)?; - assert!(second.is_empty()); - Ok::<_, vortex_error::VortexError>(first) - }; - - assert_eq!(read(true)?, (0..32).collect::>()); - // The same splits complete out of order, so an unordered worker does not keep row order. - assert_ne!(read(false)?, (0..32).collect::>()); - Ok(()) - } - - /// A limit holds across several workers of an unordered pool, whether splits reserve their - /// rows up front (no filter) or trim their output (filter). - #[rstest] - #[case::reserved(None)] - #[case::trimmed(Some(root()))] - fn unordered_limit_holds_across_workers( - #[case] filter: Option, - ) -> VortexResult<()> { - let source = source(TestLayoutReader::new(64).with_split_size(2)); - let pool = plan( - &source, - ScanRequest { - filter, - limit: Some(7), - ..Default::default() - }, - )? - .open()?; - let mut values = read_with_workers(&pool, 4)?.concat(); - values.sort_unstable(); - values.dedup(); - assert_eq!(values.len(), 7); - Ok(()) - } - - /// Split tasks are built as `execute_stream` builds them: all of a file's at once, so their - /// reads are registered together, when a worker takes its first split; but one at a time, as - /// workers take them, when the scan has both a filter and a limit. - #[rstest] - #[case::unfiltered(None, None, true)] - #[case::filtered(Some(root()), None, true)] - #[case::limited(None, Some(1000), true)] - #[case::filtered_and_limited(Some(root()), Some(1000), false)] - fn split_tasks_build_like_execute_stream( - #[case] filter: Option, - #[case] limit: Option, - #[case] up_front: bool, - ) -> VortexResult<()> { - let built = Arc::new(AtomicUsize::new(0)); - let source = source( - TestLayoutReader::new(16) - .with_split_size(1) - .with_built_projections(Arc::clone(&built)), - ); - let pool = plan( - &source, - ScanRequest { - filter, - limit, - split_concurrency: NonZeroUsize::new(1), - ..Default::default() - }, - )? - .open()?; - let mut worker = Arc::clone(&pool).worker(); - assert!(futures::executor::block_on(worker.next()).is_some()); - let built_after_first = built.load(Ordering::SeqCst); - if up_front { - assert_eq!(built_after_first, 16); - } else { - assert!( - built_after_first < 16, - "built {built_after_first} splits up front" - ); - } - - let rest = collect_scan_values(futures::executor::block_on_stream(worker))?; - assert_eq!(rest.len(), 15); - assert_eq!(built.load(Ordering::SeqCst), 16); - Ok(()) - } - - /// A pool reports the share of its splits that workers have taken, and is exhausted once - /// none are left to take. - #[rstest] - #[case::ordered(true)] - #[case::unordered(false)] - fn pools_report_progress_and_exhaustion(#[case] ordered: bool) -> VortexResult<()> { - let source = source(TestLayoutReader::new(8).with_split_size(2)); - let pool = plan( - &source, - ScanRequest { - ordered, - ..Default::default() - }, - )? - .open()?; - assert_eq!(pool.progress(), 0.0); - assert!(!pool.is_exhausted()); - - let values = read_with_one_worker(Arc::clone(&pool))?; - assert_eq!(values.len(), 8); - assert_eq!(pool.progress(), 1.0); assert!(pool.is_exhausted()); - assert!(read_with_one_worker(pool)?.is_empty()); - Ok(()) - } - - /// An ordered pool with a limit returns exactly the first `limit` rows. - #[rstest] - #[case::reserved(false, &[0, 1, 2, 3, 4])] - #[case::trimmed(true, &[1, 3, 5, 7, 9])] - fn ordered_limit_returns_the_first_rows( - #[case] filtered: bool, - #[case] expected: &[i32], - ) -> VortexResult<()> { - let source = source( - TestLayoutReader::new(32) - .with_split_size(2) - .with_keep_row(keep_odd) - .with_yields(slow_start), - ); - let pool = plan( - &source, - ScanRequest { - filter: filtered.then(root), - ordered: true, - limit: Some(5), - ..Default::default() - }, - )? - .open()?; - assert_eq!(read_with_one_worker(pool)?, expected); - Ok(()) - } - - /// With a sparse selection and no filter, each split contributes only its selected rows, so - /// the workers keep taking splits until the limit is actually filled. - #[rstest] - #[case::ordered(true)] - #[case::unordered(false)] - fn opened_sparse_selection_with_limit_fills_the_limit( - #[case] ordered: bool, - ) -> VortexResult<()> { - let source = source(TestLayoutReader::new(12).with_split_size(2)); - - // Every two-row split contains exactly one selected row (the even ones). - let selection = - Selection::IncludeByIndex(StrictSortedBuffer::try_new(Buffer::from_iter([ - 0u64, 2, 4, 6, 8, 10, - ]))?); - let pool = plan( - &source, - ScanRequest { - selection, - limit: Some(3), - ordered, - ..Default::default() - }, - )? - .open()?; - let mut values = read_with_one_worker(pool)?; - if !ordered { - values.sort_unstable(); - } - assert_eq!(values, [0, 2, 4]); + assert_eq!(pool.progress(), 1.0); Ok(()) } - /// `split(n)` pieces cover the scan exactly, are in row order, and never cut a layout split. - #[rstest] - #[case::fewer_pieces_than_splits(3, 3)] - #[case::more_pieces_than_splits(16, 7)] - fn split_pieces_cover_the_scan_on_split_boundaries( - #[case] n: usize, - #[case] expected_pieces: usize, - ) -> VortexResult<()> { - // Splits of three rows: [0, 3), [3, 6), ..., [18, 20). - let source = source(TestLayoutReader::new(20).with_split_size(3)); - let scan = plan(&source, ScanRequest::default())?; - let pieces = scan.split(NonZeroUsize::new(n).expect("non-zero"))?; - assert_eq!(pieces.len(), expected_pieces); - assert_eq!( - pieces - .iter() - .map(|piece| piece.row_count().as_exact()) - .sum::>(), - Some(20) - ); - + /// Splitting cuts at the layout's split boundaries, and the pieces read the rows in order. + #[test] + fn split_cuts_at_split_boundaries() -> VortexResult<()> { + let scan = block_on(source().scan(ScanRequest::default()))?; + let pieces = scan.split(NonZeroUsize::try_from(4)?)?; + assert_eq!(pieces.len(), 4); let mut values = Vec::new(); for piece in pieces { - // The scan is unordered, so a piece's splits may finish in any order. - let mut piece_values = read_with_one_worker(piece.open()?)?; - piece_values.sort_unstable(); - let first = *piece_values.first().expect("pieces are not empty"); - let last = *piece_values.last().expect("pieces are not empty"); - assert_eq!(first % 3, 0, "piece starts on a split boundary"); - assert!( - (last + 1) % 3 == 0 || last == 19, - "piece ends on a split boundary" - ); - values.extend(piece_values); + assert_eq!(piece.row_count(), Precision::exact(16u64)); + values.extend(collect_scan_values(block_on_stream( + piece.open()?.worker(), + ))?); } - assert_eq!(values, (0..20).collect::>()); + assert_eq!(values, (0..64).collect::>()); Ok(()) } - /// A piece read through the partitions API returns the same rows as its pool. + /// A limit is one budget across the scan, so a limited scan stays whole and opens into its + /// partitions, which apply the limit. #[test] - fn split_pieces_read_through_partitions() -> VortexResult<()> { - let source = source(TestLayoutReader::new(20).with_split_size(3)); - let scan = plan( - &source, - ScanRequest { - ordered: true, - ..Default::default() - }, - )?; - let mut values = Vec::new(); - for piece in scan.split(NonZeroUsize::new(3).expect("non-zero"))? { - let partitions = - futures::executor::block_on_stream(piece.partitions()).collect::>(); - assert_eq!(partitions.len(), 1); - for partition in partitions { - values.extend(collect_scan_values(futures::executor::block_on_stream( - partition?.execute()?, - ))?); - } - } - assert_eq!(values, (0..20).collect::>()); - Ok(()) - } + fn limited_scan_stays_whole() -> VortexResult<()> { + let runtime = SingleThreadRuntime::default(); + let source = LayoutReaderDataSource::new( + Arc::new(TestLayoutReader::new(64).with_split_size(4)), + session_with_handle(runtime.handle()), + ); + let request = || ScanRequest { + limit: Some(10), + ..Default::default() + }; + let scan = runtime.block_on(source.scan(request()))?; + assert_eq!(scan.split(NonZeroUsize::try_from(4)?)?.len(), 1); - #[test] - fn split_keeps_a_limited_scan_whole() -> VortexResult<()> { - let source = source(TestLayoutReader::new(20).with_split_size(3)); - let scan = plan( - &source, - ScanRequest { - limit: Some(4), - ..Default::default() - }, - )?; - let pieces = scan.split(NonZeroUsize::new(4).expect("non-zero"))?; - assert_eq!(pieces.len(), 1); + let pool = runtime.block_on(source.scan(request()))?.open()?; + let values = collect_scan_values(runtime.block_on_stream(pool.worker()))?; + assert_eq!(values.len(), 10); Ok(()) } #[test] - fn grouping_never_returns_more_groups_than_requested() { - let ranges = (0..10u64) - .map(|start| start * 10..start * 10 + 10) - .collect(); - let groups = group_contiguous(ranges, NonZeroUsize::new(3).expect("non-zero")); - assert_eq!(groups.len(), 3); - assert_eq!(groups.concat().len(), 10); - } - - /// A length-only scan opens into one pool whose workers together return its rows once. - #[test] - fn length_only_scan_returns_its_rows_once_across_workers() -> VortexResult<()> { - let source = source(TestLayoutReader::new(10).with_dtype(DType::Struct( - StructFields::empty(), - Nullability::NonNullable, - ))); - let pool = plan( - &source, - ScanRequest { - limit: Some(7), - ..Default::default() - }, - )? - .open()?; - let rows: usize = std::thread::scope(|scope| { - let handles = (0..3) - .map(|_| { - let worker = Arc::clone(&pool).worker(); - scope.spawn(move || { - futures::executor::block_on_stream(worker) - .map(|array| array.map(|array| array.len())) - .sum::>() - }) - }) - .collect::>(); - handles - .into_iter() - .map(|handle| handle.join().expect("worker thread panicked")) - .sum::>() - })?; - assert_eq!(rows, 7); + fn group_contiguous_keeps_ranges_whole() -> VortexResult<()> { + let ranges = vec![0..10, 10..12, 12..30, 30..31]; + let groups = group_contiguous(ranges, NonZeroUsize::try_from(2)?); + assert_eq!(groups, vec![vec![0..10, 10..12], vec![12..30, 30..31]]); Ok(()) } } diff --git a/vortex-layout/src/scan/multi.rs b/vortex-layout/src/scan/multi.rs index 87152745cc0..5d5b605bbe6 100644 --- a/vortex-layout/src/scan/multi.rs +++ b/vortex-layout/src/scan/multi.rs @@ -64,17 +64,7 @@ use vortex_session::VortexSession; use vortex_utils::parallelism::get_available_parallelism; use crate::LayoutReaderRef; -use crate::scan::layout::Empty; -use crate::scan::layout::group_contiguous; use crate::scan::limit::RowLimit; -use crate::scan::pool::FileWork; -use crate::scan::pool::PiecePartition; -use crate::scan::pool::PlannedSplits; -use crate::scan::pool::PoolFile; -use crate::scan::pool::PoolOptions; -use crate::scan::pool::PrepareFile; -use crate::scan::pool::PreparedScan; -use crate::scan::pool::open_pool; use crate::scan::scan_builder::ScanBuilder; /// Default concurrency for opening deferred readers. @@ -221,8 +211,8 @@ impl MultiLayoutDataSource { /// Sets the concurrency for opening deferred readers. /// - /// Controls how many file opens run in parallel, on the partitions path and in an opened - /// scan's pool alike. Defaults to the number of available CPU cores. + /// Controls how many file opens run in parallel via `buffer_unordered`. + /// Defaults to the number of available CPU cores. pub fn with_concurrency(mut self, concurrency: usize) -> Self { self.concurrency = concurrency; self @@ -334,6 +324,7 @@ impl DataSource for MultiLayoutDataSource { row_limit, ready, deferred, + handle: self.session.handle(), concurrency: self.concurrency, })) } @@ -385,17 +376,6 @@ impl BoundScanRequest { split_concurrency, }) } - - /// Whether the scan filters rows, so its output row count is unknown up front. A filter - /// that failed to bind counts as one. - fn has_filter(&self) -> bool { - !matches!(self.filter, Ok(None)) - } - - /// Whether the request selects partitions, which only the partitions path applies. - fn selects_partitions(&self) -> bool { - self.partition_range.is_some() || !matches!(self.partition_selection, Selection::All) - } } struct MultiLayoutScan { @@ -406,41 +386,64 @@ struct MultiLayoutScan { row_limit: Option, ready: VecDeque, deferred: VecDeque>, + handle: vortex_io::runtime::Handle, concurrency: usize, } -impl MultiLayoutScan { - /// The scan as files to split or open. Files keep their partition order. - fn into_split_scan(self) -> MultiLayoutSplitScan { - let children = self - .ready - .into_iter() - .map(ScanChild::Opened) - .chain(self.deferred.into_iter().map(ScanChild::Deferred)) - .collect(); - MultiLayoutSplitScan { - context: Arc::new(ScanContext { - session: self.session, - source_dtype: self.source_dtype, - dtype: self.dtype, - request: self.request, - open_concurrency: self.concurrency, - }), - children, - index: 0, - } - } -} - impl DataSourceScan for MultiLayoutScan { fn dtype(&self) -> &DType { &self.dtype } - fn split(self: Box, _n: NonZeroUsize) -> VortexResult> { - Ok(vec![self]) + /// Cuts the scan into pieces of whole files, in file order, without opening any. + /// + /// A scan with a limit stays whole, because the limit is one budget across all its files, + /// and so does one that selects partitions, because partition indices count from its first + /// file. + fn split(self: Box, n: NonZeroUsize) -> VortexResult> { + let files = self.ready.len() + self.deferred.len(); + if n.get() == 1 + || files <= 1 + || self.request.limit.is_some() + || self.request.partition_range.is_some() + || !matches!(self.request.partition_selection, Selection::All) + { + return Ok(vec![self]); + } + let Self { + session, + source_dtype, + dtype, + request, + row_limit, + mut ready, + mut deferred, + handle, + concurrency, + } = *self; + let pieces = n.get().min(files); + Ok((0..pieces) + .map(|piece| { + // Piece `piece` takes files `piece * files / pieces` up to the next piece's start. + let take = (piece + 1) * files / pieces - piece * files / pieces; + let from_ready = take.min(ready.len()); + Box::new(MultiLayoutScan { + session: session.clone(), + source_dtype: source_dtype.clone(), + dtype: dtype.clone(), + request: request.clone(), + row_limit: row_limit.clone(), + ready: ready.drain(..from_ready).collect(), + deferred: deferred.drain(..take - from_ready).collect(), + handle: handle.clone(), + concurrency, + }) as DataSourceScanRef + }) + .collect()) } + /// Opens the scan into its partition pipeline, which opens up to `concurrency` files ahead + /// and reads each file as one partition, handing the partitions to workers. fn open(self: Box) -> VortexResult { Ok(Arc::new(PartitionPool::new(self))) } @@ -454,35 +457,6 @@ impl DataSourceScan for MultiLayoutScan { } } - fn row_count(&self) -> Precision { - let estimate = estimate_row_count( - &self.request, - self.ready - .iter() - .map(|reader| file_row_count(&self.request, reader)), - self.ready.len() + self.deferred.len(), - ); - if self.request.selects_partitions() { - estimate.into_inexact() - } else { - estimate - } - } - - fn split(self: Box, n: NonZeroUsize) -> VortexResult> { - if self.request.selects_partitions() { - return Ok(vec![self]); - } - Box::new(self.into_split_scan()).split(n) - } - - fn open(self: Box) -> VortexResult { - if self.request.selects_partitions() { - return Ok(Arc::new(PartitionPool::new(self))); - } - Box::new(self.into_split_scan()).open() - } - fn partitions(self: Box) -> PartitionStream { let Self { session, @@ -492,9 +466,9 @@ impl DataSourceScan for MultiLayoutScan { row_limit, ready, deferred, + handle, concurrency, } = *self; - let handle = session.handle(); let ordered = request.ordered; @@ -704,283 +678,6 @@ impl Partition for MultiLayoutPartition { } } -/// The rows `request` selects from an opened file, before any filter or limit. -fn file_row_count(request: &BoundScanRequest, reader: &LayoutReaderRef) -> u64 { - let row_range = request - .row_range - .clone() - .unwrap_or_else(|| 0..reader.row_count()); - request.selection.row_count_in_range(&row_range) -} - -/// Estimates the rows a scan of `files` files returns from the rows of the files whose rows are -/// known, extrapolating to the rest. -fn estimate_row_count( - request: &BoundScanRequest, - known: impl Iterator, - files: usize, -) -> Precision { - let (rows, known_files) = known.fold((0u64, 0u64), |(rows, count), file_rows| { - (rows.saturating_add(file_rows), count + 1) - }); - let files = files as u64; - let (rows, is_exact) = if known_files == files { - (rows, !request.has_filter()) - } else if let Some(average) = rows.checked_div(known_files) { - (average.saturating_mul(files), false) - } else { - return Precision::Absent; - }; - let rows = request.limit.map_or(rows, |limit| rows.min(limit)); - if is_exact { - Precision::exact(rows) - } else { - Precision::inexact(rows) - } -} - -/// What every piece of a split or opened multi-layout scan shares. -struct ScanContext { - session: VortexSession, - source_dtype: DType, - dtype: DType, - request: BoundScanRequest, - /// The most deferred files that are opened at once. - open_concurrency: usize, -} - -impl ScanContext { - /// Plans the scan of one opened file: checks its dtype, prunes it on statistics, and - /// prepares its splits. Returns `None` when statistics reject the file. Reads metadata only. - fn plan_file(&self, reader: LayoutReaderRef) -> VortexResult> { - if reader.dtype() != &self.source_dtype { - return Err(vortex_err!( - "Multi-layout reader dtype mismatch: expected {}, got {}", - self.source_dtype, - reader.dtype() - )); - } - let filter = self.request.filter.clone()?; - let row_range = self - .request - .row_range - .clone() - .unwrap_or_else(|| 0..reader.row_count()); - - if let Some(filter) = &filter { - let mask_len = usize::try_from(row_range.end - row_range.start).unwrap_or(usize::MAX); - if let Ok(pruning) = - reader.pruning_evaluation(&row_range, filter, Mask::new_true(mask_len)) - && let Some(Ok(mask)) = pruning.now_or_never() - && mask.all_false() - { - return Ok(None); - } - } - - let scan = ScanBuilder::new(self.session.clone(), reader) - .with_row_range(row_range) - .with_selection(self.request.selection.clone()) - .with_projection(self.request.projection.clone()) - .with_some_filter(filter) - .with_ordered(self.request.ordered) - .prepare()?; - let ranges = scan.split_ranges(None); - Ok(Some((Arc::new(scan), ranges))) - } - - /// Starts reading an opened file for one execution. - fn start_file(&self, reader: LayoutReaderRef) -> VortexResult { - match self.plan_file(reader)? { - Some((scan, ranges)) => FileWork::start(scan, ranges), - None => Ok(FileWork::empty()), - } - } -} - -/// One file of a split or opened multi-layout scan. -enum ScanChild { - Opened(LayoutReaderRef), - /// An opened file whose splits are known: all of them, or the share of one piece. - Planned { - scan: Arc, - ranges: Vec>, - }, - Deferred(Arc), -} - -/// A multi-layout scan that was split or opened, or a piece cut from one. Its units are files, -/// then each file's splits. -struct MultiLayoutSplitScan { - context: Arc, - children: Vec, - /// The index of the piece's single partition. - index: usize, -} - -impl MultiLayoutSplitScan { - /// Splits a planned file's ranges into `pieces` contiguous groups. - fn split_child(child: ScanChild, pieces: usize) -> Vec { - match child { - ScanChild::Planned { scan, ranges } if pieces > 1 => group_contiguous( - ranges, - NonZeroUsize::new(pieces).unwrap_or(NonZeroUsize::MIN), - ) - .into_iter() - .map(|ranges| ScanChild::Planned { - scan: Arc::clone(&scan), - ranges, - }) - .collect(), - child => vec![child], - } - } -} - -impl DataSourceScan for MultiLayoutSplitScan { - fn dtype(&self) -> &DType { - &self.context.dtype - } - - fn partition_count(&self) -> Precision { - Precision::exact(1usize) - } - - fn partitions(self: Box) -> PartitionStream { - let index = self.index; - PiecePartition::stream(self, index) - } - - fn row_count(&self) -> Precision { - let request = &self.context.request; - let known = self.children.iter().filter_map(|child| match child { - ScanChild::Opened(reader) => Some(file_row_count(request, reader)), - ScanChild::Planned { scan, ranges } => Some( - ranges - .iter() - .map(|range| scan.selected_row_count(range)) - .sum(), - ), - ScanChild::Deferred(_) => None, - }); - estimate_row_count(request, known, self.children.len()) - } - - fn split(self: Box, n: NonZeroUsize) -> VortexResult> { - if self.context.request.limit.is_some() || n.get() == 1 || self.children.is_empty() { - return Ok(vec![self]); - } - let MultiLayoutSplitScan { - context, children, .. - } = *self; - - // Plan the opened files so they can be cut on their splits. Deferred files stay whole: - // splitting never opens a file. - let mut planned = Vec::with_capacity(children.len()); - for child in children { - match child { - ScanChild::Opened(reader) => { - if let Some((scan, ranges)) = context.plan_file(reader)? { - planned.push(ScanChild::Planned { scan, ranges }); - } - } - child => planned.push(child), - } - } - if planned.is_empty() { - return Ok(vec![Box::new(MultiLayoutSplitScan { - context, - children: planned, - index: 0, - })]); - } - - let n = n.get(); - let pieces: Vec> = if n <= planned.len() { - // Group whole files into contiguous pieces. - let files = planned.len(); - let mut pieces: Vec> = Vec::new(); - let mut current = None; - for (index, child) in planned.into_iter().enumerate() { - let piece = index * n / files; - if current != Some(piece) { - current = Some(piece); - pieces.push(Vec::new()); - } - if let Some(last) = pieces.last_mut() { - last.push(child); - } - } - pieces - } else { - // One piece per file, and the pieces left over cut planned files on their splits, in - // proportion to their rows. - let extra = (n - planned.len()) as u128; - let rows = |child: &ScanChild| match child { - ScanChild::Planned { ranges, .. } => ranges - .iter() - .map(|range| u128::from(range.end - range.start)) - .sum::(), - _ => 0, - }; - let total = planned.iter().map(rows).sum::().max(1); - planned - .into_iter() - .flat_map(|child| { - let pieces = 1 + usize::try_from(extra * rows(&child) / total).unwrap_or(0); - Self::split_child(child, pieces) - }) - .map(|child| vec![child]) - .collect() - }; - - Ok(pieces - .into_iter() - .enumerate() - .map(|(index, children)| { - Box::new(MultiLayoutSplitScan { - context: Arc::clone(&context), - children, - index, - }) as DataSourceScanRef - }) - .collect()) - } - - fn open(self: Box) -> VortexResult { - let MultiLayoutSplitScan { - context, children, .. - } = *self; - let request = &context.request; - if request.limit == Some(0) { - return Box::new(Empty::new(context.dtype.clone(), 0)).open(); - } - - let mut files = Vec::with_capacity(children.len()); - for child in children { - files.push(match child { - ScanChild::Opened(reader) => PoolFile::Opened(context.start_file(reader)?), - ScanChild::Planned { scan, ranges } => { - PoolFile::Opened(FileWork::start(scan, ranges)?) - } - ScanChild::Deferred(factory) => PoolFile::Deferred(factory), - }); - } - - let options = PoolOptions { - session: context.session.clone(), - dtype: context.dtype.clone(), - ordered: request.ordered, - limit: request.limit, - has_filter: request.has_filter(), - split_concurrency: request.split_concurrency, - open_concurrency: context.open_concurrency, - }; - let prepare: PrepareFile = Arc::new(move |reader| context.start_file(reader)); - Ok(open_pool(options, files, Some(prepare))) - } -} - #[cfg(test)] mod tests { use std::sync::Arc; @@ -1099,6 +796,48 @@ mod tests { Ok(()) } + /// Splitting hands out whole files in file order, without opening any. + #[test] + fn split_groups_whole_files() -> VortexResult<()> { + let runtime = SingleThreadRuntime::default(); + let session = session_with_handle(runtime.handle()); + let first: LayoutReaderRef = Arc::new(TestLayoutReader::new(2)); + let rest = (1..5) + .map(|file| { + Arc::new(StaticReaderFactory { + reader: Arc::new(TestLayoutReader::new(2).with_base(10 * file)), + }) as Arc + }) + .collect(); + let source = MultiLayoutDataSource::new_with_first(first, rest, vec![], &session); + + let scan = runtime.block_on(source.scan(ScanRequest { + ordered: true, + ..Default::default() + }))?; + let pieces = scan.split(NonZeroUsize::try_from(3)?)?; + let files: Vec<_> = pieces.iter().map(|piece| piece.partition_count()).collect(); + assert_eq!( + files, + [ + Precision::exact(1usize), + Precision::inexact(2usize), + Precision::inexact(2usize) + ] + ); + + let mut values = Vec::new(); + for piece in pieces { + for partition in runtime.block_on(piece.partitions().try_collect::>())? { + values.extend(collect_scan_values( + runtime.block_on_stream(partition.execute()?), + )?); + } + } + assert_eq!(values, [0, 1, 10, 11, 20, 21, 30, 31, 40, 41]); + Ok(()) + } + /// Scans 64 one-row splits, returning the rows and the most splits read at once. fn scan_with_split_concurrency( split_concurrency: Option, @@ -1157,480 +896,3 @@ mod tests { Ok(()) } } - -#[cfg(test)] -mod pool_tests { - use std::sync::Arc; - use std::sync::atomic::AtomicBool; - use std::sync::atomic::AtomicUsize; - use std::sync::atomic::Ordering; - use std::task::Context; - use std::task::Poll; - - use async_trait::async_trait; - use futures::StreamExt; - use futures::future::poll_fn; - use futures::task::AtomicWaker; - use futures::task::noop_waker_ref; - use rstest::rstest; - use vortex_array::ArrayRef; - use vortex_array::dtype::Nullability; - use vortex_array::dtype::PType; - use vortex_array::expr::root; - use vortex_array::stream::SendableArrayStream; - use vortex_buffer::Buffer; - use vortex_error::VortexResult; - use vortex_io::runtime::BlockingRuntime; - use vortex_io::runtime::single::SingleThreadRuntime; - use vortex_scan::DataSource; - use vortex_scan::ScanRequest; - use vortex_scan::strict_sorted_buffer::StrictSortedBuffer; - - use super::*; - use crate::scan::test::InFlight; - use crate::scan::test::TestLayoutReader; - use crate::scan::test::collect_scan_values; - use crate::scan::test::new_session; - use crate::scan::test::read_with_one_worker; - use crate::scan::test::read_with_workers; - use crate::scan::test::session_with_handle; - - fn plan( - source: &MultiLayoutDataSource, - request: ScanRequest, - ) -> VortexResult { - futures::executor::block_on(source.scan(request)) - } - - fn i32_dtype() -> DType { - DType::Primitive(PType::I32, Nullability::NonNullable) - } - - /// A factory whose open completes only once its gate is released. - #[derive(Default)] - struct Gate { - is_open: AtomicBool, - waker: AtomicWaker, - } - - impl Gate { - fn release(&self) { - self.is_open.store(true, Ordering::SeqCst); - self.waker.wake(); - } - } - - struct GatedFactory { - reader: LayoutReaderRef, - gate: Arc, - opens: Arc, - } - - #[async_trait] - impl LayoutReaderFactory for GatedFactory { - async fn open(&self) -> VortexResult> { - self.opens.fetch_add(1, Ordering::SeqCst); - poll_fn(|cx| { - self.gate.waker.register(cx.waker()); - if self.gate.is_open.load(Ordering::SeqCst) { - Poll::Ready(()) - } else { - Poll::Pending - } - }) - .await; - Ok(Some(Arc::clone(&self.reader))) - } - } - - fn gated_factory(reader: TestLayoutReader, gate: &Arc) -> Arc { - Arc::new(GatedFactory { - reader: Arc::new(reader), - gate: Arc::clone(gate), - opens: Arc::default(), - }) - } - - /// Deferred files of `rows` one-row splits, the `i`th producing `100 * i + row`. - fn gated_source(files: usize, rows: u64) -> (MultiLayoutDataSource, Vec>) { - let gates: Vec<_> = (0..files).map(|_| Arc::new(Gate::default())).collect(); - let factories = gates - .iter() - .enumerate() - .map(|(index, gate)| { - let base = 100 * i32::try_from(index).expect("few files"); - gated_factory( - TestLayoutReader::new(rows) - .with_split_size(1) - .with_base(base), - gate, - ) - }) - .collect(); - let source = - MultiLayoutDataSource::new_deferred(i32_dtype(), factories, vec![], &new_session()); - (source, gates) - } - - fn poll_worker( - worker: &mut SendableArrayStream, - cx: &mut Context<'_>, - ) -> Poll>> { - worker.poll_next_unpin(cx) - } - - /// An unordered pool opens at most the source's open concurrency of deferred files at once, - /// however many workers are waiting for splits. - #[test] - fn deferred_opens_are_bounded() -> VortexResult<()> { - let opens = Arc::new(AtomicUsize::new(0)); - let (source, gates) = counted_source(6, 4, &opens); - let source = source.with_concurrency(2); - let pool = plan(&source, ScanRequest::default())?.open()?; - let mut workers: Vec<_> = (0..4).map(|_| Arc::clone(&pool).worker()).collect(); - let mut noop = Context::from_waker(noop_waker_ref()); - for worker in &mut workers { - assert!(poll_worker(worker, &mut noop).is_pending()); - } - // Opens run on the session's runtime; give them time to start. - for _ in 0..200 { - if opens.load(Ordering::SeqCst) >= 2 { - break; - } - std::thread::sleep(std::time::Duration::from_millis(1)); - } - std::thread::sleep(std::time::Duration::from_millis(20)); - assert_eq!(opens.load(Ordering::SeqCst), 2); - - for gate in &gates { - gate.release(); - } - let mut values = std::thread::scope(|scope| { - let handles: Vec<_> = workers - .into_iter() - .map(|worker| { - scope.spawn(move || { - collect_scan_values(futures::executor::block_on_stream(worker)) - }) - }) - .collect(); - handles - .into_iter() - .map(|handle| handle.join().expect("worker thread panicked")) - .collect::>>() - })? - .concat(); - values.sort_unstable(); - let expected: Vec = (0..6) - .flat_map(|file| (0..4).map(move |row| 100 * file + row)) - .collect(); - assert_eq!(values, expected); - assert_eq!(opens.load(Ordering::SeqCst), 6); - Ok(()) - } - - /// Rows go to whichever worker asks for them: a worker that stops asking holds none back, - /// so another worker that waited while the file opened reads all of it. - #[test] - fn rows_go_to_whichever_worker_asks() -> VortexResult<()> { - let (source, gates) = gated_source(1, 16); - let pool = plan(&source, ScanRequest::default())?.open()?; - let mut idle = Arc::clone(&pool).worker(); - let mut waiter = Arc::clone(&pool).worker(); - let mut noop = Context::from_waker(noop_waker_ref()); - - // Both workers find only an open in progress, so both wait. - assert!(poll_worker(&mut idle, &mut noop).is_pending()); - assert!(poll_worker(&mut waiter, &mut noop).is_pending()); - - gates[0].release(); - let values = collect_scan_values(futures::executor::block_on_stream(waiter))?; - assert_eq!(values.len(), 16); - let mut sorted = values; - sorted.sort_unstable(); - assert_eq!(sorted, (0..16).collect::>()); - assert!(futures::executor::block_on(idle.next()).is_none()); - Ok(()) - } - - /// An unordered pool takes the opened files' splits in turn. With one lane, rows come out in - /// the order the lane takes splits. - #[test] - fn unordered_splits_interleave_across_files() -> VortexResult<()> { - let (source, gates) = gated_source(2, 3); - for gate in &gates { - gate.release(); - } - let request = ScanRequest { - split_concurrency: NonZeroUsize::new(1), - ..Default::default() - }; - let pool = plan(&source.with_concurrency(2), request)?.open()?; - let values = collect_scan_values(futures::executor::block_on_stream(pool.worker()))?; - assert_eq!(values, [0, 100, 1, 101, 2, 102]); - Ok(()) - } - - /// An ordered worker emits files in file order, even when a later file opens first. - #[test] - fn ordered_worker_emits_files_in_order() -> VortexResult<()> { - let (source, gates) = gated_source(3, 3); - let pool = plan( - &source, - ScanRequest { - ordered: true, - ..Default::default() - }, - )? - .open()?; - let mut worker = pool.worker(); - let mut noop = Context::from_waker(noop_waker_ref()); - assert!(poll_worker(&mut worker, &mut noop).is_pending()); - for gate in gates.iter().rev() { - gate.release(); - if !Arc::ptr_eq(gate, &gates[0]) { - assert!(poll_worker(&mut worker, &mut noop).is_pending()); - } - } - let values = collect_scan_values(futures::executor::block_on_stream(worker))?; - assert_eq!(values, [0, 1, 2, 100, 101, 102, 200, 201, 202]); - Ok(()) - } - - /// Deferred files of `rows` one-row splits whose opens are released, counted by `opens`; the - /// `i`th produces `100 * i + row`. - fn counted_source( - files: usize, - rows: u64, - opens: &Arc, - ) -> (MultiLayoutDataSource, Vec>) { - let gates: Vec<_> = (0..files).map(|_| Arc::new(Gate::default())).collect(); - let factories = gates - .iter() - .enumerate() - .map(|(index, gate)| { - let base = 100 * i32::try_from(index).expect("few files"); - Arc::new(GatedFactory { - reader: Arc::new( - TestLayoutReader::new(rows) - .with_split_size(1) - .with_base(base), - ), - gate: Arc::clone(gate), - opens: Arc::clone(opens), - }) as Arc - }) - .collect(); - let source = - MultiLayoutDataSource::new_deferred(i32_dtype(), factories, vec![], &new_session()); - (source, gates) - } - - /// An ordered pool reserves an unfiltered limit in row order across files, so it returns - /// exactly the first rows even when the limit ends inside a later file. - #[test] - fn ordered_reserved_limit_crosses_files() -> VortexResult<()> { - let (source, gates) = counted_source(3, 4, &Arc::default()); - for gate in &gates { - gate.release(); - } - let pool = plan( - &source, - ScanRequest { - ordered: true, - limit: Some(6), - ..Default::default() - }, - )? - .open()?; - assert_eq!(read_with_one_worker(pool)?, [0, 1, 2, 3, 100, 101]); - Ok(()) - } - - /// Once an unordered pool's reserved limit is spent, it opens no more files, and reports - /// that it is done. - #[test] - fn spent_limit_stops_opening_files() -> VortexResult<()> { - let opens = Arc::new(AtomicUsize::new(0)); - let (source, gates) = counted_source(6, 4, &opens); - for gate in &gates { - gate.release(); - } - let source = source.with_concurrency(1); - let pool = plan( - &source, - ScanRequest { - limit: Some(2), - ..Default::default() - }, - )? - .open()?; - let values = read_with_one_worker(Arc::clone(&pool))?; - assert_eq!(values.len(), 2); - assert!(opens.load(Ordering::SeqCst) < 6, "opened every file"); - assert!(pool.is_exhausted()); - assert_eq!(pool.progress(), 1.0); - Ok(()) - } - - /// Opens run in the pool's lanes, not in its workers, so dropping a worker that is waiting - /// on an open gives up nothing: the other workers still read every file. - #[test] - fn dropped_worker_gives_up_nothing() -> VortexResult<()> { - let (source, gates) = counted_source(3, 2, &Arc::default()); - let source = source.with_concurrency(1); - let pool = plan(&source, ScanRequest::default())?.open()?; - let mut dropped = Arc::clone(&pool).worker(); - let mut noop = Context::from_waker(noop_waker_ref()); - assert!(poll_worker(&mut dropped, &mut noop).is_pending()); - drop(dropped); - - for gate in &gates { - gate.release(); - } - let mut values = read_with_one_worker(pool)?; - values.sort_unstable(); - assert_eq!(values, [0, 1, 100, 101, 200, 201]); - Ok(()) - } - - /// A limit is shared by every worker and file of an unordered pool. - #[test] - fn pool_limit_is_shared_across_readers() -> VortexResult<()> { - let first: LayoutReaderRef = Arc::new(TestLayoutReader::new(4).with_split_size(1)); - let gate = Arc::new(Gate::default()); - gate.release(); - let source = MultiLayoutDataSource::new_with_first( - first, - vec![gated_factory( - TestLayoutReader::new(4).with_split_size(1).with_base(10), - &gate, - )], - vec![], - &new_session(), - ); - - let pool = plan( - &source, - ScanRequest { - filter: Some(root()), - limit: Some(3), - ..Default::default() - }, - )? - .open()?; - let values = read_with_workers(&pool, 3)?.concat(); - - assert_eq!(values.len(), 3); - Ok(()) - } - - /// Splitting cuts opened files on their splits and keeps deferred files whole, in order. - #[test] - fn split_cuts_opened_files_and_keeps_deferred_files_whole() -> VortexResult<()> { - let first: LayoutReaderRef = Arc::new(TestLayoutReader::new(6).with_split_size(2)); - let opens = Arc::new(AtomicUsize::new(0)); - let gate = Arc::new(Gate::default()); - gate.release(); - let source = MultiLayoutDataSource::new_with_first( - first, - vec![Arc::new(GatedFactory { - reader: Arc::new(TestLayoutReader::new(4).with_split_size(2).with_base(100)), - gate, - opens: Arc::clone(&opens), - })], - vec![], - &new_session(), - ); - let scan = plan( - &source, - ScanRequest { - ordered: true, - ..Default::default() - }, - )?; - let pieces = scan.split(NonZeroUsize::new(4).expect("non-zero"))?; - assert_eq!(opens.load(Ordering::SeqCst), 0, "splitting opens no file"); - // The opened file's three splits take three pieces; the deferred file stays whole. - assert_eq!(pieces.len(), 4); - - let mut values = Vec::new(); - for piece in pieces { - values.extend(read_with_one_worker(piece.open()?)?); - } - assert_eq!(values, [0, 1, 2, 3, 4, 5, 100, 101, 102, 103]); - Ok(()) - } - - /// A request that selects partitions is split and opened by its partitions, so both paths - /// read the same files. - #[rstest] - #[case::range(Some(1..2), None)] - #[case::selection(None, Some(1))] - fn selected_partitions_open_by_partition( - #[case] partition_range: Option>, - #[case] selected_partition: Option, - ) -> VortexResult<()> { - let partition_selection = match selected_partition { - Some(index) => { - Selection::IncludeByIndex(StrictSortedBuffer::try_new(Buffer::from_iter([index]))?) - } - None => Selection::All, - }; - // The partitions path spawns file opens onto the session's runtime. - let runtime = SingleThreadRuntime::default(); - let gate = Arc::new(Gate::default()); - gate.release(); - let source = MultiLayoutDataSource::new_with_first( - Arc::new(TestLayoutReader::new(3)), - vec![gated_factory(TestLayoutReader::new(3).with_base(10), &gate)], - vec![], - &session_with_handle(runtime.handle()), - ); - let request = ScanRequest { - partition_range, - partition_selection, - ordered: true, - ..Default::default() - }; - let pieces = plan(&source, request.clone())?.split(NonZeroUsize::new(4).expect("4"))?; - assert_eq!(pieces.len(), 1); - let pool = plan(&source, request)?.open()?; - let values = collect_scan_values(runtime.block_on_stream(pool.worker()))?; - assert_eq!(values, [10, 11, 12]); - Ok(()) - } - - /// A pool reads at most `split_concurrency` splits at once, however many workers read it. - #[rstest] - #[case::ordered(true, 1)] - #[case::ordered(true, 2)] - #[case::unordered(false, 1)] - #[case::unordered(false, 2)] - fn split_concurrency_bounds_the_pool( - #[case] ordered: bool, - #[case] max: usize, - ) -> VortexResult<()> { - let in_flight = Arc::new(InFlight::default()); - let reader: LayoutReaderRef = Arc::new( - TestLayoutReader::new(64) - .with_split_size(1) - .with_in_flight(Arc::clone(&in_flight)), - ); - let source = MultiLayoutDataSource::new_with_first(reader, vec![], vec![], &new_session()); - let pool = plan( - &source, - ScanRequest { - ordered, - split_concurrency: NonZeroUsize::new(max), - ..Default::default() - }, - )? - .open()?; - let mut values = read_with_workers(&pool, 4)?.concat(); - values.sort_unstable(); - assert_eq!(values, (0..64).collect::>()); - assert!(in_flight.peak() <= max, "peak {}", in_flight.peak()); - Ok(()) - } -} diff --git a/vortex-layout/src/scan/pool.rs b/vortex-layout/src/scan/pool.rs index f345e908c0a..002372a3d23 100644 --- a/vortex-layout/src/scan/pool.rs +++ b/vortex-layout/src/scan/pool.rs @@ -1,927 +1,89 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors -//! The work that the workers of an opened layout scan share. -//! -//! A pool's units are the splits of one or more files, and the files not yet opened. Its splits -//! run as tasks on the session's runtime, at most `splits_in_flight` at once across the whole -//! pool; it never starts threads of its own. Opening a deferred file is a unit like any other, and -//! at most `open_concurrency` opens are queued or running at once. -//! -//! Splits run as [`RepeatedScan::execute_stream`] runs them: -//! -//! - A scan with a filter and a limit builds each split on a CPU thread only once it is taken -//! to run ([`spawn_lazy_split`]), so no new split starts once the limit is spent, and optimizes the -//! rows the limit keeps on a second CPU task ([`spawn_map_trimmed`]). -//! - Every other scan builds all of a file's split tasks together, when the first of them is -//! taken, so the file's reads are registered at once and can coalesce. A limit is reserved -//! then, in split order. -//! -//! The pools differ in how workers share the work: -//! -//! - An unordered pool runs lanes on the runtime once its first worker starts: one for each run -//! of splits or open that is ready, more as they queue, and at most enough to keep -//! `splits_in_flight` splits running. Each lane takes the next unit from a channel of units, -//! runs it, and sends its rows into one bounded output channel. An opened file is one unit, its -//! turn, which a lane queues again after taking the file's next run of adjacent splits, so the -//! lanes read the opened files in turn, a run at a time, and poll each run's splits together so -//! that their reads coalesce. A lane that opens a deferred file queues the file's turn, followed -//! by the next deferred file. Workers only take rows from the output channel, so whichever -//! worker asks next gets the next rows, however many workers there are, and the number of -//! workers is only the host's parallelism. The output channel closes once every lane has -//! finished, which ends the workers. -//! - An ordered pool gives all of its units, in row order, to its first worker, which keeps -//! `splits_in_flight` of them running at once; later workers get nothing. Parallel ordered reads -//! cut the scan with `split` first. +//! The pool an opened layout scan shares among host threads. -use std::any::Any; -use std::collections::VecDeque; -use std::iter; -use std::num::NonZeroUsize; -use std::ops::Range; use std::sync::Arc; -use std::sync::atomic::AtomicBool; use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering; +use std::vec; -use async_channel::Receiver; -use async_channel::Sender; -use async_lock::OnceCell; -use futures::FutureExt; -use futures::StreamExt; -use futures::future; use futures::future::BoxFuture; use futures::stream; -use futures::stream::BoxStream; -use futures::stream::FuturesUnordered; use parking_lot::Mutex; -use tracing::Instrument; use vortex_array::ArrayRef; use vortex_array::dtype::DType; -use vortex_array::expr::stats::Precision; use vortex_array::stream::ArrayStreamAdapter; use vortex_array::stream::ArrayStreamExt; use vortex_array::stream::SendableArrayStream; use vortex_error::VortexResult; -use vortex_io::runtime::Handle; -use vortex_io::runtime::Task; -use vortex_io::session::RuntimeSessionExt; -use vortex_scan::DataSourceScanRef; -use vortex_scan::Partition; -use vortex_scan::PartitionRef; -use vortex_scan::PartitionStream; use vortex_scan::pool::ScanPool; -use vortex_scan::pool::ScanPoolRef; -use vortex_scan::row_mask::RowMask; -use vortex_session::VortexSession; -use vortex_utils::parallelism::get_available_parallelism; -use crate::LayoutReaderRef; -use crate::scan::limit::RowLimit; -use crate::scan::multi::LayoutReaderFactory; -use crate::scan::repeated_scan::DEFAULT_SPLITS_PER_THREAD; -use crate::scan::repeated_scan::MapFn; -use crate::scan::repeated_scan::RepeatedScan; -use crate::scan::repeated_scan::SplitConcurrency; -use crate::scan::repeated_scan::can_prune_file; -use crate::scan::repeated_scan::recheck_prune_file; -use crate::scan::repeated_scan::spawn_lazy_split; -use crate::scan::repeated_scan::spawn_map_trimmed; -use crate::scan::repeated_scan::stop_on_error; -use crate::scan::tasks::SplitFuture; -use crate::scan::tasks::TaskContext; -use crate::scan::tasks::split_exec; +use crate::scan::repeated_scan::ScanTasks; -/// A scan prepared once and shared by every piece and execution of it. -pub(crate) type PreparedScan = RepeatedScan; +/// One split of a scan, which returns the split's array, or `None` when the filter removes all +/// of its rows. +type SplitTask = BoxFuture<'static, VortexResult>>; -/// A prepared scan and the row ranges of its splits, in row order. -pub(crate) type PlannedSplits = (Arc, Vec>); - -/// One execution of one file's prepared scan over some of its splits. -pub(crate) struct FileScan { - scan: Arc, - /// Records this execution's events, so file events count once for each execution. - ctx: Arc, - /// The row ranges of the splits, in row order. - ranges: Vec>, - /// The task of each split, built together when a worker first takes one of them. `None` - /// where the split has no rows to read, or a worker has taken it. - tasks: OnceCell>>>, - /// Whether whole-file statistics reject the filter when the file's first split is taken. - pruned: OnceCell, -} - -impl FileScan { - /// Whether whole-file statistics reject the filter, checked again when the first split is - /// taken, as [`RepeatedScan::execute_stream`] checks when it starts: a filter with dynamic - /// parts may reject the file by then though it did not when the pool was opened. - async fn is_pruned(&self) -> VortexResult { - let pruned = self - .pruned - .get_or_try_init(|| future::ready(recheck_prune_file(&self.ctx))) - .await?; - Ok(*pruned) - } - - /// The tasks of the file's splits, built on first use. A file whose tasks are built once a - /// reserved limit is spent, or that statistics now reject, builds none. - async fn tasks(&self, limit: &PoolLimit) -> VortexResult<&[Mutex>]> { - let tasks = self - .tasks - .get_or_try_init(|| async { - if self.is_pruned().await? { - return Ok(Vec::new()); - } - self.build_tasks(limit) - }) - .await?; - Ok(tasks) - } - - /// Builds every split's task, which registers its reads, reserving a reserved limit in split - /// order. - fn build_tasks(&self, limit: &PoolLimit) -> VortexResult>>> { - self.ranges - .iter() - .map(|range| { - let mask = self.scan.split_mask(range).and_then(|mask| match limit { - PoolLimit::Reserve(limit) => { - let reserved = limit.limit(mask.mask().clone()); - (!reserved.all_false()).then(|| RowMask::new(range.start, reserved)) - } - PoolLimit::Unlimited | PoolLimit::Trim(_) => Some(mask), - }); - let task = mask - .map(|mask| self.scan.split_task(&self.ctx, mask)) - .transpose()?; - Ok(Mutex::new(task)) - }) - .collect() - } -} - -/// One file's splits for one execution, ready to be handed to workers. -pub(crate) struct FileWork { - file: Option>, -} - -impl FileWork { - /// A file with nothing to read, for example one that statistics pruned. - pub(crate) fn empty() -> Self { - Self { file: None } - } - - /// Starts an execution of `scan` over its split `ranges`. - /// - /// Counts a file scan attempt when the ranges select any row, and returns no work when - /// whole-file statistics reject the filter. - pub(crate) fn start(scan: Arc, ranges: Vec>) -> VortexResult { - if !ranges.iter().any(|range| scan.selects_rows(range)) { - return Ok(Self::empty()); - } - let ctx = scan.task_context(); - if can_prune_file(&ctx)? { - return Ok(Self::empty()); - } - Ok(Self { - file: Some(Arc::new(FileScan { - scan, - ctx, - ranges, - tasks: OnceCell::new(), - pruned: OnceCell::new(), - })), - }) - } -} - -/// Opens a deferred file's reader into its work for this execution. -pub(crate) type PrepareFile = Arc VortexResult + Send + Sync>; - -/// A file of a pool, in file order. -pub(crate) enum PoolFile { - Opened(FileWork), - Deferred(Arc), -} - -/// How a pool reads its splits. -pub(crate) struct PoolOptions { - pub(crate) session: VortexSession, - pub(crate) dtype: DType, - pub(crate) ordered: bool, - pub(crate) limit: Option, - /// Whether the scan filters rows, so a split's output row count is unknown up front. - pub(crate) has_filter: bool, - /// The request's bound on the splits each worker keeps in flight. - pub(crate) split_concurrency: Option, - /// The most deferred files that are queued or being opened at once. - pub(crate) open_concurrency: usize, -} - -/// Opens a pool over `files`, in file order. `prepare` turns an opened deferred file into work. -pub(crate) fn open_pool( - options: PoolOptions, - files: Vec, - prepare: Option, -) -> ScanPoolRef { - let limit = match options.limit { - None => PoolLimit::Unlimited, - Some(limit) if options.has_filter => PoolLimit::Trim(RowLimit::new(limit)), - Some(limit) => PoolLimit::Reserve(RowLimit::new(limit)), - }; - // The pool keeps as many splits in flight as one scan stream does by default: four per core, - // at most the request's `split_concurrency`, however many workers read it. The runtime's - // threads decode them, so more in flight would only read further ahead, and the file's - // registered reads already let I/O coalesce ahead of the splits being decoded. - let splits_in_flight = SplitConcurrency { - per_worker: DEFAULT_SPLITS_PER_THREAD, - max: options.split_concurrency, - } - .splits_in_flight() - .max(1); - let open_concurrency = options.open_concurrency.max(1); - let shared = Arc::new(Shared { - limit, - prepare, - session: options.session, - file_share: 1.0 / files.len().max(1) as f64, - progress: Mutex::new(0.0), - deferred: Mutex::new(VecDeque::new()), - failed: AtomicBool::new(false), - pending: AtomicUsize::new(0), - }); - if options.ordered { - return Arc::new(OrderedPool { - dtype: options.dtype, - shared, - files: Mutex::new(Some(files)), - splits_in_flight, - open_concurrency, - }); - } - - let (sender, receiver) = async_channel::unbounded(); - let mut opens = 0; - for file in files { - match file { - PoolFile::Opened(work) => shared.queue_file(&sender, work), - PoolFile::Deferred(factory) if opens < open_concurrency => { - opens += 1; - let slot = OpenSlot { - shared: Arc::clone(&shared), - sender: sender.clone(), - }; - shared.queue(&sender, Work::Open(factory, slot)); - } - PoolFile::Deferred(factory) => shared.deferred.lock().push_back(factory), - } - } - // Each open file gets an equal share of the splits in flight, and a lane takes a file's share - // as one run of adjacent splits that it starts together. The run's reads then reach the - // file's read driver together and coalesce, as they do when one scan stream polls its - // file's splits; a run of one would hand the driver one read at a time. The rotation moves - // between files after each run, and the lanes hold `splits_in_flight` splits in all. A run is - // at most one core's share, so that a scan of few files, such as a single-file scan whose - // share is every split in flight, still has a lane per core. - let cores = get_available_parallelism().unwrap_or(1).max(1); - let run = (splits_in_flight / open_concurrency) - .min(splits_in_flight / cores) - .max(1); - let (output, outputs) = async_channel::bounded(splits_in_flight); - let lanes = Arc::new(Lanes { - shared: Arc::clone(&shared), - units: receiver.clone(), - run, - max: (splits_in_flight / run).max(1), - waiting: AtomicUsize::new(0), - started: AtomicUsize::new(0), - tasks: Mutex::new(Some(Vec::new())), - }); - Arc::new(UnorderedPool { - dtype: options.dtype, - shared, - units: receiver, - outputs, - lanes, - output: Mutex::new(Some(output)), - }) -} - -/// How a pool's row limit is applied. -enum PoolLimit { - Unlimited, - /// A split's selected rows are its output rows, so a file reserves its splits' rows from the - /// budget in split order when it builds their tasks, and rows past the limit are never - /// decoded. Files build in row order in an ordered pool, so it returns exactly the first rows. - Reserve(RowLimit), - /// A split's output rows are unknown until its filter has run, so workers take rows from the - /// budget as they yield them and discard the excess. - Trim(RowLimit), -} - -impl PoolLimit { - /// Whether the budget is spent, so no file that has not started has rows to return. - fn is_spent(&self) -> bool { - match self { - PoolLimit::Unlimited => false, - PoolLimit::Reserve(limit) | PoolLimit::Trim(limit) => limit.is_exhausted(), - } - } - - /// Whether a trimmed budget is spent, so workers end without returning any more rows. - fn is_trimmed_out(&self) -> bool { - matches!(self, PoolLimit::Trim(limit) if limit.is_exhausted()) - } -} - -/// A split's output: `None` when it has no rows to return. -type SplitOutput = BoxFuture<'static, VortexResult>>; - -/// A split of a file by its index, with the progress that taking it adds. -type FileSplit = (Arc, usize, f64); - -/// What every worker of a pool shares. -struct Shared { - limit: PoolLimit, - prepare: Option, - /// The session whose runtime runs the pool's splits and opens. - session: VortexSession, - /// The progress that one file adds. - file_share: f64, - progress: Mutex, - /// An unordered pool's deferred files that are not yet queued for opening, in file order. - deferred: Mutex>>, - /// Whether a unit of an unordered pool failed, which stops its lanes. - failed: AtomicBool, - /// The splits and opens of an unordered pool that are queued and not yet taken by a lane. - pending: AtomicUsize, -} - -impl Shared { - /// The splits of an opened file, in row order. - fn file_splits(&self, work: FileWork) -> Vec { - let Some(file) = work.file else { - *self.progress.lock() += self.file_share; - return Vec::new(); - }; - let rows: u64 = file - .ranges - .iter() - .map(|range| range.end - range.start) - .sum(); - if rows == 0 { - *self.progress.lock() += self.file_share; - return Vec::new(); - } - let per_row = self.file_share / rows as f64; - (0..file.ranges.len()) - .map(|index| { - let range = &file.ranges[index]; - let progress = per_row * (range.end - range.start) as f64; - (Arc::clone(&file), index, progress) - }) - .collect() - } - - /// Opens a deferred file into its work, on the task that polls it. A file that starts after - /// the limit is spent is not opened. - fn open_file( - self: &Arc, - factory: Arc, - ) -> BoxFuture<'static, VortexResult> { - if self.limit.is_spent() { - return future::ready(Ok(FileWork::empty())).boxed(); - } - let shared = Arc::clone(self); - async move { - let reader = factory - .open() - .instrument(tracing::info_span!("LayoutReaderFactory::open")) - .await?; - match (reader, &shared.prepare) { - (Some(reader), Some(prepare)) => prepare(reader), - _ => Ok(FileWork::empty()), - } - } - .boxed() - } - - /// Opens a deferred file into its work as a task on the session's runtime. - fn spawn_open_file( - self: &Arc, - factory: Arc, - ) -> BoxFuture<'static, VortexResult> { - if self.limit.is_spent() { - return future::ready(Ok(FileWork::empty())).boxed(); - } - self.session.handle().spawn(self.open_file(factory)).boxed() - } - - /// The next deferred file of an unordered pool to open, if any is left and the limit is not - /// spent. Once it is spent, the files left count as read. - fn next_deferred(&self) -> Option> { - let mut deferred = self.deferred.lock(); - if self.limit.is_spent() && !deferred.is_empty() { - *self.progress.lock() += self.file_share * deferred.len() as f64; - deferred.clear(); - } - deferred.pop_front() - } - - /// Takes a split. A split of a scan with a filter and a limit is built and run as - /// [`spawn_lazy_split`] runs it; any other split runs as a task on the session's runtime, since - /// a split decodes inside its future. - fn admit(self: &Arc, (file, index, progress): FileSplit) -> SplitOutput { - *self.progress.lock() += progress; - let handle = self.session.handle(); - if let PoolLimit::Trim(_) = &self.limit { - let Some(mask) = file.scan.split_mask(&file.ranges[index]) else { - return future::ready(Ok(None)).boxed(); - }; - return async move { - if file.is_pruned().await? { - return Ok(None); - } - spawn_lazy_split(&handle, move || split_exec(&file.ctx, mask).map(Some)).await - } - .boxed(); - } - let shared = Arc::clone(self); - async move { - let task = file - .tasks(&shared.limit) - .await? - .get(index) - .and_then(|task| task.lock().take()); - match task { - Some(task) => handle.spawn(task).await, - None => Ok(None), - } - } - .boxed() - } - - /// Queues a unit of an unordered pool, counting the splits or open it holds as pending. - fn queue(&self, sender: &Sender, work: Work) { - let units = match &work { - Work::File(splits, _) => splits.len(), - Work::Open(..) => 1, - }; - self.pending.fetch_add(units, Ordering::AcqRel); - send(sender, work); - } - - /// Queues an opened file of an unordered pool as one turn among the files. - fn queue_file(&self, sender: &Sender, work: FileWork) { - let splits: VecDeque = self.file_splits(work).into(); - if !splits.is_empty() { - self.queue(sender, Work::File(splits, sender.clone())); - } - } - - fn progress(&self) -> f64 { - if self.limit.is_trimmed_out() { - return 1.0; - } - self.progress.lock().clamp(0.0, 1.0) - } - - /// An ordered worker's output: skips splits with no rows, trims to a trimmed limit, and ends - /// after the first error or once a trimmed limit is spent. A trimmed array is optimized again, - /// on a CPU task, `splits_in_flight` at a time. - fn output( - self: Arc, - outputs: BoxStream<'static, VortexResult>>, - splits_in_flight: usize, - ) -> BoxStream<'static, VortexResult> { - let trimmed = matches!(self.limit, PoolLimit::Trim(_)); - let handle = self.session.handle(); - let session = self.session.clone(); - let arrays = limit_output(outputs, self); - if !trimmed { - return arrays; - } - let identity: MapFn = Arc::new(Ok); - let mapped = arrays.map(move |array| { - spawn_map_trimmed(&handle, session.clone(), Arc::clone(&identity), array) - }); - stop_on_error(mapped.buffered(splits_in_flight).boxed()) - } -} - -/// Skips splits with no rows, trims to a trimmed limit, and ends after the first error or once -/// a trimmed limit is spent. -fn limit_output( - outputs: BoxStream<'static, VortexResult>>, - shared: Arc, -) -> BoxStream<'static, VortexResult> { - stream::unfold(Some(outputs), move |outputs| { - let shared = Arc::clone(&shared); - async move { - let mut outputs = outputs?; - loop { - if shared.limit.is_trimmed_out() { - return None; - } - let array = match outputs.next().await? { - Ok(Some(array)) => array, - Ok(None) => continue, - Err(err) => return Some((Err(err), None)), - }; - let PoolLimit::Trim(limit) = &shared.limit else { - return Some((Ok(array), Some(outputs))); - }; - let granted = limit.take(array.len()); - if granted == 0 { - return None; - } - if granted == array.len() { - return Some((Ok(array), Some(outputs))); - } - return Some((array.slice(0..granted), None)); - } - } - }) - .boxed() -} - -/// A unit of an unordered pool's channel. -enum Work { - /// An opened file's turn: the splits not yet taken, in row order. The lane that takes the - /// turn takes the file's next run of splits and queues the turn again behind the other - /// files' turns, so the lanes take runs from every opened file in turn rather than from one - /// file after another. Each file then has only a few splits in flight, which keeps its first rows, and - /// any dynamic filter they tighten, ahead of its later splits. - File(VecDeque, Sender), - /// A deferred file, and the open slot it holds until its turn is in the channel. - Open(Arc, OpenSlot), -} - -/// What a lane takes from a unit. -enum Taken { - /// A run of a file's adjacent splits, in row order. - Splits(Vec), - Open(Arc, OpenSlot), -} - -impl Taken { - /// The pending splits or open that this takes. - fn units(&self) -> usize { - match self { - Taken::Splits(splits) => splits.len(), - Taken::Open(..) => 1, - } - } -} - -impl Work { - /// Takes the unit's next `run` splits, or its open, queueing a file's turn again while it - /// has splits left. - fn take(self, run: usize) -> Option { - match self { - Work::File(mut splits, sender) => { - let taken: Vec<_> = splits.drain(..run.min(splits.len())).collect(); - if !splits.is_empty() { - let requeue = sender.clone(); - send(&requeue, Work::File(splits, sender)); - } - (!taken.is_empty()).then_some(Taken::Splits(taken)) - } - Work::Open(factory, slot) => Some(Taken::Open(factory, slot)), - } - } -} - -/// One of an unordered pool's `open_concurrency` open slots. Its sender keeps the channel open -/// while the file that holds it is queued or opening. -struct OpenSlot { - shared: Arc, - sender: Sender, -} - -impl Drop for OpenSlot { - /// Passes the slot to the next deferred file, queued behind the turns already in the channel, - /// so opens keep pace with the workers. The slot passes on whether the open finished or a - /// dropped worker gave it up, so that worker strands only the file it was opening. - fn drop(&mut self) { - if self.sender.is_closed() { - return; - } - if let Some(next) = self.shared.next_deferred() { - let slot = OpenSlot { - shared: Arc::clone(&self.shared), - sender: self.sender.clone(), - }; - self.shared.queue(&self.sender, Work::Open(next, slot)); - } - } -} - -fn send(sender: &Sender, work: Work) { - // The channel is unbounded and closes only once the pool is dropped, when the work is moot. - drop(sender.try_send(work)); -} - -/// The lanes of an unordered pool. They start when its first worker does, as many as there are -/// splits and opens ready, and grow while those wait for a lane, up to `splits_in_flight`, so a -/// scan with few units spawns and wakes few tasks. -struct Lanes { - shared: Arc, - units: Receiver, - /// The most adjacent splits of a file that a lane takes and polls together. - run: usize, - /// The most lanes that run at once. - max: usize, - /// Lanes waiting for a unit. - waiting: AtomicUsize, - /// Lanes started, so a lane can see without a lock that no more may start. - started: AtomicUsize, - /// The lanes started, until the pool is dropped, which aborts them. `None` once it is. - tasks: Mutex>>>, -} - -impl Lanes { - /// Starts lanes for the units that no waiting lane will take, up to the most that run at - /// once. Each lane holds a sender of the output channel. - fn grow(self: &Arc, output: &Sender>) { - // Every lane calls this for every unit it takes, so it locks only to start lanes. - if self.started.load(Ordering::Acquire) >= self.max || self.unserved() == 0 { - return; - } - let mut tasks = self.tasks.lock(); - let Some(tasks) = tasks.as_mut() else { - return; - }; - let new = self - .unserved() - .div_ceil(self.run) - .min(self.max.saturating_sub(tasks.len())); - if new == 0 { - return; - } - let handle = self.shared.session.handle(); - tasks.extend((0..new).map(|_| handle.spawn(lane(Arc::clone(self), output.clone())))); - self.started.store(tasks.len(), Ordering::Release); - } - - /// The pending splits and opens that the lanes waiting for a unit will not take, each of - /// which takes up to a run. - fn unserved(&self) -> usize { - self.shared - .pending - .load(Ordering::Acquire) - .saturating_sub(self.waiting.load(Ordering::Acquire) * self.run) - } -} - -/// A pool whose lanes run its units on the runtime, and whose workers share their output. -struct UnorderedPool { +/// A pool over the split futures of [`RepeatedScan::execute`], in row order. +/// +/// A worker claims the next split and then runs it itself, outside the lock, one split at a +/// time. This is how DuckDB's threads read a file's splits on develop, so a host that runs one +/// worker per thread reads as many splits at once as it has threads, with no read-ahead. +/// +/// [`RepeatedScan::execute`]: crate::scan::repeated_scan::RepeatedScan::execute +pub(crate) struct SplitPool { dtype: DType, - shared: Arc, - units: Receiver, - outputs: Receiver>, - lanes: Arc, - /// The sender of the output channel until the first worker starts the lanes, which hold it - /// from then on. - output: Mutex>>>, + splits: Mutex>, + total: usize, + claimed: AtomicUsize, } -impl UnorderedPool { - /// Runs a unit for the lane that took it. Each split of a run runs as a task of its own, as - /// [`RepeatedScan::execute_stream`] runs it, since a split decodes inside its future: the run's - /// splits start together, so their reads coalesce, and decode on as many threads as there - /// are splits. An open runs on the lane itself. - fn run(shared: &Arc, taken: Taken) -> FuturesUnordered { - match taken { - Taken::Splits(splits) => splits - .into_iter() - .map(|split| shared.admit(split)) - .collect(), - Taken::Open(factory, slot) => iter::once( - async move { - let opened = slot.shared.open_file(factory).await.map(|work| { - slot.shared.queue_file(&slot.sender, work); - None - }); - drop(slot); - opened - } - .boxed(), - ) - .collect(), - } - } - - /// Starts the lanes, once. With no units, it starts none, and the output channel closes. - fn start_lanes(&self) { - // Dropping the pool's own sender leaves the lanes holding the output channel open. - if let Some(output) = self.output.lock().take() { - self.lanes.grow(&output); +impl SplitPool { + pub(crate) fn new(dtype: DType, splits: ScanTasks) -> Self { + Self { + dtype, + total: splits.len(), + splits: Mutex::new(splits.into_iter()), + claimed: AtomicUsize::new(0), } } -} -/// A lane: runs units one at a time and sends their rows to the workers, trimming them to a -/// trimmed limit. Ends once the units run out, a limit is spent, a unit fails, or every worker -/// is gone. -async fn lane(lanes: Arc, output: Sender>) { - let shared = Arc::clone(&lanes.shared); - let handle = shared.session.handle(); - let identity: MapFn = Arc::new(Ok); - while !shared.limit.is_trimmed_out() && !shared.failed.load(Ordering::Acquire) { - lanes.waiting.fetch_add(1, Ordering::AcqRel); - let work = lanes.units.recv().await; - lanes.waiting.fetch_sub(1, Ordering::AcqRel); - let Ok(work) = work else { - return; - }; - let Some(taken) = work.take(lanes.run) else { - continue; - }; - shared.pending.fetch_sub(taken.units(), Ordering::AcqRel); - // Units the waiting lanes will not take get lanes of their own, such as the splits an - // open has just queued. - lanes.grow(&output); - let mut running = UnorderedPool::run(&shared, taken); - while let Some(array) = running.next().await { - let array = match array { - Ok(Some(array)) => Ok(array), - Ok(None) => continue, - Err(err) => Err(err), - }; - if !emit(&shared, &handle, &identity, &output, array).await { - return; - } - } + /// Claims the next split, if any is left. + fn claim(&self) -> Option { + let split = self.splits.lock().next()?; + self.claimed.fetch_add(1, Ordering::Release); + Some(split) } } -/// Sends a lane's rows to the workers, trimmed to a trimmed limit. Returns whether the lane -/// should go on: not once the limit is spent, a unit failed, or every worker is gone. -async fn emit( - shared: &Shared, - handle: &Handle, - identity: &MapFn, - output: &Sender>, - array: VortexResult, -) -> bool { - let array = match (&shared.limit, array) { - (PoolLimit::Trim(limit), Ok(array)) => { - let granted = limit.take(array.len()); - if granted == 0 { - return false; - } - let array = if granted < array.len() { - array.slice(0..granted) - } else { - Ok(array) - }; - spawn_map_trimmed(handle, shared.session.clone(), Arc::clone(identity), array).await - } - (_, array) => array, - }; - let failed = array.is_err(); - if failed { - shared.failed.store(true, Ordering::Release); - } - output.send(array).await.is_ok() && !failed -} - -impl ScanPool for UnorderedPool { +impl ScanPool for SplitPool { fn dtype(&self) -> &DType { &self.dtype } fn worker(self: Arc) -> SendableArrayStream { - self.start_lanes(); let dtype = self.dtype.clone(); - // The worker holds the pool, so the lanes run until the pool's last worker is dropped. let arrays = stream::unfold(self, |pool| async move { - let array = pool.outputs.recv().await.ok()?; - Some((array, pool)) - }) - .boxed(); - ArrayStreamExt::boxed(ArrayStreamAdapter::new(dtype, stop_on_error(arrays))) + loop { + match pool.claim()?.await { + Ok(Some(array)) => return Some((Ok(array), pool)), + Ok(None) => {} + Err(err) => return Some((Err(err), pool)), + } + } + }); + ArrayStreamExt::boxed(ArrayStreamAdapter::new(dtype, arrays)) } fn progress(&self) -> f64 { - if self.is_exhausted() { + if self.total == 0 { return 1.0; } - self.shared.progress() - } - - fn is_exhausted(&self) -> bool { - // The lanes hold the output channel's senders, so it closes once every lane has ended. - self.outputs.is_closed() && self.outputs.is_empty() - } -} - -impl Drop for UnorderedPool { - fn drop(&mut self) { - // Pending opens hold senders of the channel of units itself; drain them so it can be - // freed. The lanes are aborted when they are dropped. - self.units.close(); - while self.units.try_recv().is_ok() {} - self.outputs.close(); - drop(self.lanes.tasks.lock().take()); - } -} - -/// A pool that gives all of its units, in row order, to its first worker. -struct OrderedPool { - dtype: DType, - shared: Arc, - /// The files, until the first worker takes them. - files: Mutex>>, - splits_in_flight: usize, - open_concurrency: usize, -} - -impl ScanPool for OrderedPool { - fn dtype(&self) -> &DType { - &self.dtype - } - - fn worker(self: Arc) -> SendableArrayStream { - let dtype = self.dtype.clone(); - let Some(files) = self.files.lock().take() else { - return ArrayStreamExt::boxed(ArrayStreamAdapter::new(dtype, stream::empty())); - }; - let shared = Arc::clone(&self.shared); - let opener = Arc::clone(&shared); - let splitter = Arc::clone(&shared); - let admitter = Arc::clone(&shared); - let gate = Arc::clone(&shared); - // Deferred files open `open_concurrency` at a time, ahead of the splits being read. - let outputs = stream::iter(files) - .map(move |file| match file { - PoolFile::Opened(work) => future::ready(Ok(work)).boxed(), - PoolFile::Deferred(factory) => opener.spawn_open_file(factory), - }) - .buffered(self.open_concurrency) - .flat_map(move |work| match work { - Ok(work) => { - stream::iter(splitter.file_splits(work).into_iter().map(Ok)).left_stream() - } - Err(err) => stream::once(future::ready(Err(err))).right_stream(), - }) - .take_while(move |_| future::ready(!gate.limit.is_trimmed_out())) - .map(move |split| match split { - Ok(split) => admitter.admit(split), - Err(err) => future::ready(Err(err)).boxed(), - }) - .buffered(self.splits_in_flight) - .boxed(); - ArrayStreamExt::boxed(ArrayStreamAdapter::new( - dtype, - shared.output(outputs, self.splits_in_flight), - )) - } - - fn progress(&self) -> f64 { - self.shared.progress() + (self.claimed.load(Ordering::Acquire) as f64 / self.total as f64).clamp(0.0, 1.0) } fn is_exhausted(&self) -> bool { - // The first worker takes every file. - self.shared.limit.is_trimmed_out() || self.files.lock().is_none() - } -} - -/// The single partition of a scan piece that is read through the partitions API: it opens the -/// piece and reads it with one worker. -pub(crate) struct PiecePartition { - piece: DataSourceScanRef, - index: usize, -} - -impl PiecePartition { - /// The partitions of `piece`: one, whose index is `index`. - pub(crate) fn stream(piece: DataSourceScanRef, index: usize) -> PartitionStream { - stream::iter([Ok(Box::new(PiecePartition { piece, index }) as PartitionRef)]).boxed() - } -} - -impl Partition for PiecePartition { - fn as_any(&self) -> &dyn Any { - self - } - - fn index(&self) -> usize { - self.index - } - - fn row_count(&self) -> Precision { - self.piece.row_count() - } - - fn byte_size(&self) -> Precision { - self.piece.byte_size() - } - - fn execute(self: Box) -> VortexResult { - Ok(self.piece.open()?.worker()) + self.claimed.load(Ordering::Acquire) >= self.total } } diff --git a/vortex-layout/src/scan/repeated_scan.rs b/vortex-layout/src/scan/repeated_scan.rs index e1654b05e98..f13b4bc752d 100644 --- a/vortex-layout/src/scan/repeated_scan.rs +++ b/vortex-layout/src/scan/repeated_scan.rs @@ -31,8 +31,6 @@ use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_error::vortex_bail; use vortex_io::runtime::BlockingRuntime; -use vortex_io::runtime::Handle; -use vortex_io::runtime::Task; use vortex_io::session::RuntimeSessionExt; use vortex_scan::row_mask::RowMask; use vortex_scan::selection::Selection; @@ -86,7 +84,7 @@ pub struct RepeatedScan { pub type ScanTasks = Vec>>>; /// A function applied to each projected split array. -pub(crate) type MapFn = Arc VortexResult + Send + Sync>; +type MapFn = Arc VortexResult + Send + Sync>; impl RepeatedScan { pub fn execute_array_iter( @@ -177,7 +175,7 @@ impl RepeatedScan { } /// Each execution gets its own recorder, so file events count once for each execution. - pub(crate) fn task_context(&self) -> Arc { + fn task_context(&self) -> Arc { Arc::new(TaskContext { filter: self .filter @@ -190,9 +188,7 @@ impl RepeatedScan { }) } - /// The row ranges of the scan's splits within `row_range`, in row order. - /// - /// Ranges whose rows the selection excludes are included; [`Self::split_mask`] skips them. + /// The row ranges of the scan's natural splits within `row_range`, in row order. pub(crate) fn split_ranges(&self, row_range: Option>) -> Vec> { let selection_range: Option> = match &self.selection { Selection::IncludeByIndex(buf) if !buf.is_empty() => { @@ -249,33 +245,6 @@ impl RepeatedScan { } } - /// Whether the selection includes any row of `range`. - pub(crate) fn selects_rows(&self, range: &Range) -> bool { - self.selection.row_count_in_range(range) != 0 - } - - /// The number of rows of `range` that the selection includes. - pub(crate) fn selected_row_count(&self, range: &Range) -> u64 { - self.selection.row_count_in_range(range) - } - - /// The selected rows of the split over `range`, or `None` if the selection excludes them all. - pub(crate) fn split_mask(&self, range: &Range) -> Option { - selected_mask(&self.selection, range) - } - - /// Builds the task of one split. The task does no work until it is polled, but building it - /// may register the split's reads with the reader, so build it only when it is about to run. - /// - /// `mask` must select at least one row. - pub(crate) fn split_task( - &self, - ctx: &Arc, - mask: RowMask, - ) -> VortexResult>>> { - Ok(map_split(split_exec(ctx, mask)?, &self.map_fn)) - } - /// The non-empty row masks of the splits within `row_range`, in split order. fn split_masks(&self, row_range: Option>) -> impl Iterator + '_ { self.split_ranges(row_range) @@ -328,13 +297,21 @@ impl RepeatedScan { .map(move |split| { let ctx = Arc::clone(&ctx); let selection = selection.clone(); - spawn_lazy_split(&split_handle, move || { - let Some(row_mask) = - split.either(Some, |range| selected_mask(&selection, &range)) - else { - return Ok(None); - }; - split_exec(&ctx, row_mask).map(Some) + split_handle.spawn_nested(move |handle| async move { + let task = handle + .spawn_cpu(move || { + let Some(row_mask) = + split.either(Some, |range| selected_mask(&selection, &range)) + else { + return Ok(None); + }; + split_exec(&ctx, row_mask).map(Some) + }) + .await?; + match task { + Some(task) => task.await, + None => Ok(None), + } }) }); let map_fn = Arc::clone(map_fn); @@ -343,7 +320,9 @@ impl RepeatedScan { .boxed(); let session = self.session.clone(); let mapped = limit_rows(arrays, limit).map(move |array| { - spawn_map_trimmed(&handle, session.clone(), Arc::clone(&map_fn), array) + let map_fn = Arc::clone(&map_fn); + let session = session.clone(); + handle.spawn_cpu(move || map_fn(array?.optimize_ctx(&session)?)) }); buffer(mapped, ordered, concurrency) } @@ -378,52 +357,14 @@ impl RepeatedScan { } } -/// Builds a split's task on a CPU thread and runs it, both on the session's runtime. -/// -/// This is how scans with a filter and a limit run their splits: a split's output row count is -/// unknown until its filter has run, so each split is built only once it is about to run, and none -/// start once the limit is spent. `build` returns `None` when the split has nothing to read. Every -/// other scan builds all of its split tasks up front with [`RepeatedScan::split_task`], so that -/// their reads are registered together and can coalesce, and runs each with [`Handle::spawn`]. -pub(crate) fn spawn_lazy_split( - handle: &Handle, - build: impl FnOnce() -> VortexResult> + Send + 'static, -) -> Task>> { - handle.spawn_nested(move |handle| async move { - match handle.spawn_cpu(build).await? { - Some(task) => task.await, - None => Ok(None), - } - }) -} - -/// Optimizes an array that a limit may have trimmed and maps it, on a CPU thread: the second -/// stage of a scan with a filter and a limit, after [`spawn_lazy_split`]. -pub(crate) fn spawn_map_trimmed( - handle: &Handle, - session: VortexSession, - map_fn: MapFn, - array: VortexResult, -) -> Task> { - handle.spawn_cpu(move || map_fn(array?.optimize_ctx(&session)?)) -} - /// This function returns `None` if the selection excludes every row in `range`. fn selected_mask(selection: &Selection, range: &Range) -> Option { let mask = selection.row_mask(range); (!mask.mask().all_false()).then_some(mask) } -/// Counts a file scan attempt and returns whether whole-file statistics reject the filter. -pub(crate) fn can_prune_file(ctx: &TaskContext) -> VortexResult { +fn can_prune_file(ctx: &TaskContext) -> VortexResult { ctx.count::(ScanRecorder::attempt_file_scan); - recheck_prune_file(ctx) -} - -/// Returns whether whole-file statistics reject the filter, for a file whose scan attempt -/// [`can_prune_file`] has already counted. A filter with dynamic parts, such as a join's, may -/// reject a file later that it did not reject when the scan started. -pub(crate) fn recheck_prune_file(ctx: &TaskContext) -> VortexResult { if let Some(filter) = &ctx.filter && can_prune_conjuncts(filter, ctx.reader.as_ref())? { @@ -481,7 +422,7 @@ fn limit_rows( } /// Yield the first error and drop upstream without polling it again. -pub(crate) fn stop_on_error( +fn stop_on_error( stream: BoxStream<'static, VortexResult>, ) -> BoxStream<'static, VortexResult> { let mut stream = Some(stream); @@ -498,10 +439,6 @@ pub(crate) fn stop_on_error( .boxed() } -/// The splits a scan keeps in flight for each worker thread by default, which allows for some I/O -/// lookahead without too much impact on work-stealing. -pub(crate) const DEFAULT_SPLITS_PER_THREAD: usize = 4; - /// How many splits a scan makes progress on at once: `per_worker` for each worker thread, as /// [`get_available_parallelism`] counts them, and at most `max` in all when that is set. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -511,7 +448,7 @@ pub(crate) struct SplitConcurrency { } impl SplitConcurrency { - pub(crate) fn splits_in_flight(self) -> usize { + fn splits_in_flight(self) -> usize { let scaled = self .per_worker .saturating_mul(get_available_parallelism().unwrap_or(1)); diff --git a/vortex-layout/src/scan/scan_builder.rs b/vortex-layout/src/scan/scan_builder.rs index 96373ae3e72..3785489d710 100644 --- a/vortex-layout/src/scan/scan_builder.rs +++ b/vortex-layout/src/scan/scan_builder.rs @@ -40,7 +40,6 @@ use crate::scan::limit::RowLimit; use crate::scan::limit::ScanLimit; use crate::scan::metrics::ScanMetrics; use crate::scan::metrics::ScanUsage; -use crate::scan::repeated_scan::DEFAULT_SPLITS_PER_THREAD; use crate::scan::repeated_scan::RepeatedScan; use crate::scan::repeated_scan::ScanTasks; use crate::scan::repeated_scan::SplitConcurrency; @@ -104,8 +103,10 @@ impl ScanBuilder { selection: Default::default(), split_by: SplitBy::default(), natural_splits: None, + // We default to four tasks per worker thread, which allows for some I/O lookahead + // without too much impact on work-stealing. concurrency: SplitConcurrency { - per_worker: DEFAULT_SPLITS_PER_THREAD, + per_worker: 4, max: None, }, map_fn: Arc::new(Ok), diff --git a/vortex-layout/src/scan/test.rs b/vortex-layout/src/scan/test.rs index 0e15bcced80..85c4b25d8b1 100644 --- a/vortex-layout/src/scan/test.rs +++ b/vortex-layout/src/scan/test.rs @@ -23,13 +23,10 @@ use vortex_error::VortexResult; use vortex_error::vortex_err; use vortex_io::runtime::BlockingRuntime; use vortex_io::runtime::Handle; -use vortex_io::runtime::current::CurrentThreadRuntime; -use vortex_io::runtime::current::CurrentThreadWorkerPool; use vortex_io::runtime::single::SingleThreadRuntime; use vortex_io::session::RuntimeSession; use vortex_io::session::RuntimeSessionExt; use vortex_mask::Mask; -use vortex_scan::pool::ScanPoolRef; use vortex_session::VortexSession; use crate::ArrayFuture; @@ -40,20 +37,10 @@ use crate::session::LayoutSession; static SESSION: LazyLock = LazyLock::new(VortexSession::empty); -/// A runtime driven by background threads, so splits the pools spawn make progress while test -/// workers block on their streams with `futures::executor`. -static RUNTIME: LazyLock<(CurrentThreadRuntime, CurrentThreadWorkerPool)> = LazyLock::new(|| { - let runtime = CurrentThreadRuntime::new(); - let pool = runtime.new_pool(); - pool.set_workers(4); - (runtime, pool) -}); - pub fn new_session() -> VortexSession { VortexSession::empty() .with::() .with::() - .with_handle(RUNTIME.0.handle()) } pub fn session_with_handle(handle: Handle) -> VortexSession { @@ -83,8 +70,6 @@ pub struct TestLayoutReader { projection_masks: Option>>>, filter_exprs: Option>>>, in_flight: Option>, - yields: fn(u64) -> usize, - built_projections: Option>, } /// Counts projections running at once, and the most that ever were. @@ -116,8 +101,6 @@ impl TestLayoutReader { projection_masks: None, filter_exprs: None, in_flight: None, - yields: |_| 0, - built_projections: None, } } @@ -154,19 +137,6 @@ impl TestLayoutReader { self } - /// Makes the projection of the split starting at row `start` yield `yields(start)` times - /// before it finishes, so tests can make splits complete out of row order. - pub fn with_yields(mut self, yields: fn(u64) -> usize) -> Self { - self.yields = yields; - self - } - - /// Counts the projections built, which is when a split registers its reads. - pub fn with_built_projections(mut self, built: Arc) -> Self { - self.built_projections = Some(built); - self - } - pub fn with_filter_exprs(mut self, filter_exprs: Arc>>) -> Self { self.filter_exprs = Some(filter_exprs); self @@ -291,15 +261,8 @@ impl LayoutReader for TestLayoutReader { let projection_masks = self.projection_masks.clone(); let fail = self.fail_projection || (self.fail_first_projection && row_range.start == 0); let in_flight = self.in_flight.clone(); - let yields = (self.yields)(row_range.start); - if let Some(built) = &self.built_projections { - built.fetch_add(1, Ordering::SeqCst); - } Ok(Box::pin(async move { - for _ in 0..yields { - tokio::task::yield_now().await; - } if let Some(in_flight) = &in_flight { let now = in_flight.now.fetch_add(1, Ordering::SeqCst) + 1; in_flight.peak.fetch_max(now, Ordering::SeqCst); @@ -350,28 +313,6 @@ where Ok(values) } -/// Reads `pool` with `workers` workers, each polled on its own thread, returning each worker's -/// values in the order it yielded them. -pub fn read_with_workers(pool: &ScanPoolRef, workers: usize) -> VortexResult>> { - std::thread::scope(|scope| { - let handles = (0..workers) - .map(|_| { - let worker = Arc::clone(pool).worker(); - scope.spawn(move || collect_scan_values(futures::executor::block_on_stream(worker))) - }) - .collect::>(); - handles - .into_iter() - .map(|handle| handle.join().expect("worker thread panicked")) - .collect() - }) -} - -/// Reads `pool` with a single worker polled on the calling thread. -pub fn read_with_one_worker(pool: ScanPoolRef) -> VortexResult> { - collect_scan_values(futures::executor::block_on_stream(pool.worker())) -} - /// Let already-spawned scan tasks run to completion after the stream has been dropped. pub fn drain_runtime(runtime: &SingleThreadRuntime) { for _ in 0..4 { From a68063c45e636de7b07532089742d1ab08e774da Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 13:33:58 -0500 Subject: [PATCH 15/25] Test group_contiguous against ranges grouped by their first row Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-layout/src/scan/layout.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/vortex-layout/src/scan/layout.rs b/vortex-layout/src/scan/layout.rs index 2b4ab2d1d5a..52464361851 100644 --- a/vortex-layout/src/scan/layout.rs +++ b/vortex-layout/src/scan/layout.rs @@ -838,9 +838,10 @@ mod split_open_tests { #[test] fn group_contiguous_keeps_ranges_whole() -> VortexResult<()> { - let ranges = vec![0..10, 10..12, 12..30, 30..31]; + // Each range joins the group its first row falls in. + let ranges = vec![0..10, 10..16, 16..26, 26..32]; let groups = group_contiguous(ranges, NonZeroUsize::try_from(2)?); - assert_eq!(groups, vec![vec![0..10, 10..12], vec![12..30, 30..31]]); + assert_eq!(groups, vec![vec![0..10, 10..16], vec![16..26, 26..32]]); Ok(()) } } From b414761130cc32f6e26da001c2ff1f336c4a5f11 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 13:41:19 -0500 Subject: [PATCH 16/25] Keep develop's splits in flight when opening a file, and split inside files An opened single-file scan's workers each keep the stream pipeline's per-thread count of splits in flight, spawned on the session runtime, so a host polling one worker per core keeps as many in flight as the stream does. A worker yields only the splits it claimed, so no worker waits on another's. A multi-file scan split into more pieces than it has files cuts its open files at their layout split boundaries, sharing the pieces by row count. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-layout/src/scan/layout.rs | 50 ++++-- vortex-layout/src/scan/multi.rs | 198 ++++++++++++++++++++---- vortex-layout/src/scan/pool.rs | 44 ++++-- vortex-layout/src/scan/repeated_scan.rs | 4 + vortex-layout/src/scan/scan_builder.rs | 5 +- 5 files changed, 236 insertions(+), 65 deletions(-) diff --git a/vortex-layout/src/scan/layout.rs b/vortex-layout/src/scan/layout.rs index 52464361851..5833a9001bb 100644 --- a/vortex-layout/src/scan/layout.rs +++ b/vortex-layout/src/scan/layout.rs @@ -29,6 +29,7 @@ use vortex_array::stream::ArrayStreamExt; use vortex_array::stream::SendableArrayStream; use vortex_error::VortexResult; use vortex_error::vortex_bail; +use vortex_io::session::RuntimeSessionExt; use vortex_mask::Mask; use vortex_metrics::MetricsRegistry; use vortex_scan::DataSource; @@ -48,6 +49,7 @@ use crate::scan::limit::RowLimit; use crate::scan::metrics::ScanMetrics; use crate::scan::metrics::ScanRecorder; use crate::scan::pool::SplitPool; +use crate::scan::repeated_scan::DEFAULT_SPLITS_PER_THREAD; use crate::scan::scan_builder::ScanBuilder; /// An implementation of a [`DataSource`] that reads data from a [`LayoutReaderRef`]. @@ -305,21 +307,32 @@ impl DataSourceScan for LayoutReaderScan { .collect()) } - /// Opens the scan into a queue of its split futures, which workers claim one at a time and - /// run themselves: develop's DuckDB scan of a file. + /// Opens the scan into a [`SplitPool`] over its split futures, each worker keeping the + /// stream pipeline's per-thread count of them in flight. /// - /// Split futures cannot share a limit, and workers of a queue finish splits out of row - /// order. So a scan with a limit, or an ordered one, keeps its partition pipeline and hands - /// its partitions to workers instead. + /// Split futures cannot share a limit, and the workers of a queue finish splits out of row + /// order. So a scan with a limit, or an ordered one, opens into its partition pipeline and + /// hands its partitions to workers. fn open(self: Box) -> VortexResult { if self.remaining_limit.is_some() || self.ordered { return Ok(Arc::new(PartitionPool::new(self))); } + // A cap on the scan's splits in flight also caps each worker's. + let per_worker = self + .split_concurrency + .map_or(DEFAULT_SPLITS_PER_THREAD, |max| { + max.get().min(DEFAULT_SPLITS_PER_THREAD) + }); let splits = self .builder() .prepare()? .execute(Some(self.next_row..self.end_row))?; - Ok(Arc::new(SplitPool::new(self.dtype, splits))) + Ok(Arc::new(SplitPool::new( + self.dtype, + self.session.handle(), + per_worker, + splits, + ))) } fn row_count(&self) -> Precision { @@ -758,8 +771,6 @@ mod split_open_tests { use std::sync::Arc; use futures::TryStreamExt; - use futures::executor::block_on; - use futures::executor::block_on_stream; use futures::future::try_join_all; use vortex_array::expr::stats::Precision; use vortex_error::VortexResult; @@ -772,13 +783,12 @@ mod split_open_tests { use super::group_contiguous; use crate::scan::test::TestLayoutReader; use crate::scan::test::collect_scan_values; - use crate::scan::test::new_session; use crate::scan::test::session_with_handle; - fn source() -> LayoutReaderDataSource { + fn source(runtime: &SingleThreadRuntime) -> LayoutReaderDataSource { LayoutReaderDataSource::new( Arc::new(TestLayoutReader::new(64).with_split_size(4)), - new_session(), + session_with_handle(runtime.handle()), ) } @@ -786,9 +796,12 @@ mod split_open_tests { /// every row once. #[test] fn opened_workers_read_every_row_once() -> VortexResult<()> { - let pool = block_on(source().scan(ScanRequest::default()))?.open()?; + let runtime = SingleThreadRuntime::default(); + let pool = runtime + .block_on(source(&runtime).scan(ScanRequest::default()))? + .open()?; let workers = (0..3).map(|_| Arc::clone(&pool).worker().try_collect::>()); - let arrays = block_on(try_join_all(workers))?; + let arrays = runtime.block_on(try_join_all(workers))?; let mut values = collect_scan_values(arrays.into_iter().flatten().map(Ok))?; values.sort_unstable(); assert_eq!(values, (0..64).collect::>()); @@ -800,15 +813,18 @@ mod split_open_tests { /// Splitting cuts at the layout's split boundaries, and the pieces read the rows in order. #[test] fn split_cuts_at_split_boundaries() -> VortexResult<()> { - let scan = block_on(source().scan(ScanRequest::default()))?; + let runtime = SingleThreadRuntime::default(); + let scan = runtime.block_on(source(&runtime).scan(ScanRequest::default()))?; let pieces = scan.split(NonZeroUsize::try_from(4)?)?; assert_eq!(pieces.len(), 4); let mut values = Vec::new(); for piece in pieces { assert_eq!(piece.row_count(), Precision::exact(16u64)); - values.extend(collect_scan_values(block_on_stream( - piece.open()?.worker(), - ))?); + let mut piece_values = + collect_scan_values(runtime.block_on_stream(piece.open()?.worker()))?; + // A worker yields its splits as they finish. + piece_values.sort_unstable(); + values.extend(piece_values); } assert_eq!(values, (0..64).collect::>()); Ok(()) diff --git a/vortex-layout/src/scan/multi.rs b/vortex-layout/src/scan/multi.rs index 5d5b605bbe6..576528c87de 100644 --- a/vortex-layout/src/scan/multi.rs +++ b/vortex-layout/src/scan/multi.rs @@ -26,6 +26,7 @@ use std::any::Any; use std::collections::VecDeque; +use std::mem; use std::num::NonZeroUsize; use std::ops::Range; use std::sync::Arc; @@ -64,6 +65,7 @@ use vortex_session::VortexSession; use vortex_utils::parallelism::get_available_parallelism; use crate::LayoutReaderRef; +use crate::scan::layout::group_contiguous; use crate::scan::limit::RowLimit; use crate::scan::scan_builder::ScanBuilder; @@ -390,12 +392,139 @@ struct MultiLayoutScan { concurrency: usize, } +impl MultiLayoutScan { + /// This scan over `ready` and `deferred` files only, reading `row_range` of each. + fn piece( + &self, + ready: VecDeque, + deferred: VecDeque>, + row_range: Option>, + ) -> DataSourceScanRef { + Box::new(MultiLayoutScan { + session: self.session.clone(), + source_dtype: self.source_dtype.clone(), + dtype: self.dtype.clone(), + request: BoundScanRequest { + row_range, + ..self.request.clone() + }, + row_limit: self.row_limit.clone(), + ready, + deferred, + handle: self.handle.clone(), + concurrency: self.concurrency, + }) + } + + /// Cuts the scan into `pieces` runs of whole files, in file order. `pieces` is at most the + /// number of files. + fn split_files(mut self: Box, pieces: usize) -> Vec { + let files = self.ready.len() + self.deferred.len(); + let mut ready = mem::take(&mut self.ready); + let mut deferred = mem::take(&mut self.deferred); + let row_range = self.request.row_range.clone(); + (0..pieces) + .map(|piece| { + // Piece `piece` takes files `piece * files / pieces` up to the next piece's start. + let take = (piece + 1) * files / pieces - piece * files / pieces; + let from_ready = take.min(ready.len()); + self.piece( + ready.drain(..from_ready).collect(), + deferred.drain(..take - from_ready).collect(), + row_range.clone(), + ) + }) + .collect() + } + + /// Cuts every open file at its layout's split boundaries into `extra` more pieces than it has + /// files in all, shared among the open files by row count. Each unopened file is one piece. + fn split_within_files(self: Box, extra: usize) -> Vec { + fn rows(ranges: &[Range]) -> u64 { + ranges.iter().map(|range| range.end - range.start).sum() + } + + let file_ranges: Vec>>> = self + .ready + .iter() + .map(|reader| self.file_split_ranges(reader)) + .collect(); + let total_rows = file_ranges + .iter() + .flatten() + .map(|ranges| u128::from(rows(ranges))) + .sum::() + .max(1); + let budget = (self.ready.len() + extra) as u128; + + let mut pieces = Vec::new(); + for (reader, ranges) in self.ready.iter().zip(file_ranges) { + let Some(ranges) = ranges else { + // The file's splits could not be planned, so its partition reports why when read. + pieces.push(self.piece( + [Arc::clone(reader)].into(), + VecDeque::new(), + self.request.row_range.clone(), + )); + continue; + }; + let share = u128::from(rows(&ranges)) * budget / total_rows; + let share = NonZeroUsize::new(usize::try_from(share).unwrap_or(usize::MAX)) + .unwrap_or(NonZeroUsize::MIN); + for group in group_contiguous(ranges, share) { + if let (Some(first), Some(last)) = (group.first(), group.last()) { + pieces.push(self.piece( + [Arc::clone(reader)].into(), + VecDeque::new(), + Some(first.start..last.end), + )); + } + } + } + for factory in &self.deferred { + pieces.push(self.piece( + VecDeque::new(), + [Arc::clone(factory)].into(), + self.request.row_range.clone(), + )); + } + if pieces.is_empty() { + // Every open file's selection is empty and no file is unopened. + return vec![self]; + } + pieces + } + + /// The row ranges of `reader`'s natural splits that the scan reads, or `None` if they cannot + /// be planned, such as when the request does not bind to the file. + fn file_split_ranges(&self, reader: &LayoutReaderRef) -> Option>> { + let row_range = self + .request + .row_range + .clone() + .unwrap_or(0..reader.row_count()); + let filter = self.request.filter.clone().ok()?; + let scan = ScanBuilder::new(self.session.clone(), Arc::clone(reader)) + .with_selection(self.request.selection.clone()) + .with_projection(self.request.projection.clone()) + .with_some_filter(filter) + .prepare() + .ok()?; + Some(scan.split_ranges(Some(row_range))) + } +} + impl DataSourceScan for MultiLayoutScan { fn dtype(&self) -> &DType { &self.dtype } - /// Cuts the scan into pieces of whole files, in file order, without opening any. + /// Cuts the scan into up to `n` contiguous pieces in file order, reading metadata only. + /// + /// With no more pieces than files, each piece is a run of whole files. With more, each file + /// whose reader is open is cut further at its layout's split boundaries, with pieces shared + /// among the open files by row count. A file not yet opened is one piece, since cutting it + /// would mean opening it. /// /// A scan with a limit stays whole, because the limit is one budget across all its files, /// and so does one that selects partitions, because partition indices count from its first @@ -403,43 +532,17 @@ impl DataSourceScan for MultiLayoutScan { fn split(self: Box, n: NonZeroUsize) -> VortexResult> { let files = self.ready.len() + self.deferred.len(); if n.get() == 1 - || files <= 1 + || files == 0 || self.request.limit.is_some() || self.request.partition_range.is_some() || !matches!(self.request.partition_selection, Selection::All) { return Ok(vec![self]); } - let Self { - session, - source_dtype, - dtype, - request, - row_limit, - mut ready, - mut deferred, - handle, - concurrency, - } = *self; - let pieces = n.get().min(files); - Ok((0..pieces) - .map(|piece| { - // Piece `piece` takes files `piece * files / pieces` up to the next piece's start. - let take = (piece + 1) * files / pieces - piece * files / pieces; - let from_ready = take.min(ready.len()); - Box::new(MultiLayoutScan { - session: session.clone(), - source_dtype: source_dtype.clone(), - dtype: dtype.clone(), - request: request.clone(), - row_limit: row_limit.clone(), - ready: ready.drain(..from_ready).collect(), - deferred: deferred.drain(..take - from_ready).collect(), - handle: handle.clone(), - concurrency, - }) as DataSourceScanRef - }) - .collect()) + if n.get() <= files { + return Ok(self.split_files(n.get())); + } + Ok(self.split_within_files(n.get() - files)) } /// Opens the scan into its partition pipeline, which opens up to `concurrency` files ahead @@ -838,6 +941,37 @@ mod tests { Ok(()) } + /// With more pieces than files, an open file is cut at its split boundaries, and an + /// unopened file stays one piece. + #[test] + fn split_cuts_open_files_at_split_boundaries() -> VortexResult<()> { + let runtime = SingleThreadRuntime::default(); + let session = session_with_handle(runtime.handle()); + let first: LayoutReaderRef = Arc::new(TestLayoutReader::new(8).with_split_size(2)); + let rest: Vec> = vec![Arc::new(StaticReaderFactory { + reader: Arc::new(TestLayoutReader::new(2).with_base(10)), + })]; + let source = MultiLayoutDataSource::new_with_first(first, rest, vec![], &session); + + let scan = runtime.block_on(source.scan(ScanRequest { + ordered: true, + ..Default::default() + }))?; + let pieces = scan.split(NonZeroUsize::try_from(4)?)?; + assert_eq!(pieces.len(), 4); + + let mut values = Vec::new(); + for piece in pieces { + for partition in runtime.block_on(piece.partitions().try_collect::>())? { + values.extend(collect_scan_values( + runtime.block_on_stream(partition.execute()?), + )?); + } + } + assert_eq!(values, [0, 1, 2, 3, 4, 5, 6, 7, 10, 11]); + Ok(()) + } + /// Scans 64 one-row splits, returning the rows and the most splits read at once. fn scan_with_split_concurrency( split_concurrency: Option, diff --git a/vortex-layout/src/scan/pool.rs b/vortex-layout/src/scan/pool.rs index 002372a3d23..207c55c41bf 100644 --- a/vortex-layout/src/scan/pool.rs +++ b/vortex-layout/src/scan/pool.rs @@ -3,11 +3,14 @@ //! The pool an opened layout scan shares among host threads. +use std::iter; use std::sync::Arc; use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering; use std::vec; +use futures::StreamExt; +use futures::future; use futures::future::BoxFuture; use futures::stream; use parking_lot::Mutex; @@ -17,6 +20,7 @@ use vortex_array::stream::ArrayStreamAdapter; use vortex_array::stream::ArrayStreamExt; use vortex_array::stream::SendableArrayStream; use vortex_error::VortexResult; +use vortex_io::runtime::Handle; use vortex_scan::pool::ScanPool; use crate::scan::repeated_scan::ScanTasks; @@ -27,22 +31,37 @@ type SplitTask = BoxFuture<'static, VortexResult>>; /// A pool over the split futures of [`RepeatedScan::execute`], in row order. /// -/// A worker claims the next split and then runs it itself, outside the lock, one split at a -/// time. This is how DuckDB's threads read a file's splits on develop, so a host that runs one -/// worker per thread reads as many splits at once as it has threads, with no read-ahead. +/// Each worker claims splits from the shared queue and keeps up to `per_worker` of its own in +/// flight, spawned on the session's runtime, yielding them as they finish. This is the scan's +/// stream pipeline with its in-flight bound split across workers: `per_worker` is the per-thread +/// count that the stream multiplies by the cores, so a host polling one worker per core keeps as +/// many splits in flight as the stream does. +/// +/// A worker yields only the splits it claimed, and claims a split only when it has room for one. +/// So [`is_exhausted`](ScanPool::is_exhausted) turns true once every split has been claimed, and +/// a host can move a thread to other work then: no worker waits on a split another one claimed. /// /// [`RepeatedScan::execute`]: crate::scan::repeated_scan::RepeatedScan::execute pub(crate) struct SplitPool { dtype: DType, + handle: Handle, + per_worker: usize, splits: Mutex>, total: usize, claimed: AtomicUsize, } impl SplitPool { - pub(crate) fn new(dtype: DType, splits: ScanTasks) -> Self { + pub(crate) fn new( + dtype: DType, + handle: Handle, + per_worker: usize, + splits: ScanTasks, + ) -> Self { Self { dtype, + handle, + per_worker: per_worker.max(1), total: splits.len(), splits: Mutex::new(splits.into_iter()), claimed: AtomicUsize::new(0), @@ -64,15 +83,14 @@ impl ScanPool for SplitPool { fn worker(self: Arc) -> SendableArrayStream { let dtype = self.dtype.clone(); - let arrays = stream::unfold(self, |pool| async move { - loop { - match pool.claim()?.await { - Ok(Some(array)) => return Some((Ok(array), pool)), - Ok(None) => {} - Err(err) => return Some((Err(err), pool)), - } - } - }); + let handle = self.handle.clone(); + let per_worker = self.per_worker; + // `buffer_unordered` pulls a split only when it has room, so a worker claims no more + // than it runs. + let arrays = stream::iter(iter::from_fn(move || self.claim())) + .map(move |split| handle.spawn(split)) + .buffer_unordered(per_worker) + .filter_map(|array| future::ready(array.transpose())); ArrayStreamExt::boxed(ArrayStreamAdapter::new(dtype, arrays)) } diff --git a/vortex-layout/src/scan/repeated_scan.rs b/vortex-layout/src/scan/repeated_scan.rs index f13b4bc752d..1a950fec418 100644 --- a/vortex-layout/src/scan/repeated_scan.rs +++ b/vortex-layout/src/scan/repeated_scan.rs @@ -439,6 +439,10 @@ fn stop_on_error( .boxed() } +/// The splits a scan keeps in flight for each worker thread by default, which allows for some I/O +/// lookahead without too much impact on work-stealing. +pub(crate) const DEFAULT_SPLITS_PER_THREAD: usize = 4; + /// How many splits a scan makes progress on at once: `per_worker` for each worker thread, as /// [`get_available_parallelism`] counts them, and at most `max` in all when that is set. #[derive(Clone, Copy, Debug, PartialEq, Eq)] diff --git a/vortex-layout/src/scan/scan_builder.rs b/vortex-layout/src/scan/scan_builder.rs index 3785489d710..96373ae3e72 100644 --- a/vortex-layout/src/scan/scan_builder.rs +++ b/vortex-layout/src/scan/scan_builder.rs @@ -40,6 +40,7 @@ use crate::scan::limit::RowLimit; use crate::scan::limit::ScanLimit; use crate::scan::metrics::ScanMetrics; use crate::scan::metrics::ScanUsage; +use crate::scan::repeated_scan::DEFAULT_SPLITS_PER_THREAD; use crate::scan::repeated_scan::RepeatedScan; use crate::scan::repeated_scan::ScanTasks; use crate::scan::repeated_scan::SplitConcurrency; @@ -103,10 +104,8 @@ impl ScanBuilder { selection: Default::default(), split_by: SplitBy::default(), natural_splits: None, - // We default to four tasks per worker thread, which allows for some I/O lookahead - // without too much impact on work-stealing. concurrency: SplitConcurrency { - per_worker: 4, + per_worker: DEFAULT_SPLITS_PER_THREAD, max: None, }, map_fn: Arc::new(Ok), From 168533026beffd121fb3ade15b1d1bce2b85ccb5 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 13:47:43 -0500 Subject: [PATCH 17/25] Keep multi-file split to runs of whole files A multi-file scan splits into runs of whole files only, so the path stays small until multi-file reading moves to a composite over child sources. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-layout/src/scan/multi.rs | 198 ++++++-------------------------- 1 file changed, 32 insertions(+), 166 deletions(-) diff --git a/vortex-layout/src/scan/multi.rs b/vortex-layout/src/scan/multi.rs index 576528c87de..5d5b605bbe6 100644 --- a/vortex-layout/src/scan/multi.rs +++ b/vortex-layout/src/scan/multi.rs @@ -26,7 +26,6 @@ use std::any::Any; use std::collections::VecDeque; -use std::mem; use std::num::NonZeroUsize; use std::ops::Range; use std::sync::Arc; @@ -65,7 +64,6 @@ use vortex_session::VortexSession; use vortex_utils::parallelism::get_available_parallelism; use crate::LayoutReaderRef; -use crate::scan::layout::group_contiguous; use crate::scan::limit::RowLimit; use crate::scan::scan_builder::ScanBuilder; @@ -392,139 +390,12 @@ struct MultiLayoutScan { concurrency: usize, } -impl MultiLayoutScan { - /// This scan over `ready` and `deferred` files only, reading `row_range` of each. - fn piece( - &self, - ready: VecDeque, - deferred: VecDeque>, - row_range: Option>, - ) -> DataSourceScanRef { - Box::new(MultiLayoutScan { - session: self.session.clone(), - source_dtype: self.source_dtype.clone(), - dtype: self.dtype.clone(), - request: BoundScanRequest { - row_range, - ..self.request.clone() - }, - row_limit: self.row_limit.clone(), - ready, - deferred, - handle: self.handle.clone(), - concurrency: self.concurrency, - }) - } - - /// Cuts the scan into `pieces` runs of whole files, in file order. `pieces` is at most the - /// number of files. - fn split_files(mut self: Box, pieces: usize) -> Vec { - let files = self.ready.len() + self.deferred.len(); - let mut ready = mem::take(&mut self.ready); - let mut deferred = mem::take(&mut self.deferred); - let row_range = self.request.row_range.clone(); - (0..pieces) - .map(|piece| { - // Piece `piece` takes files `piece * files / pieces` up to the next piece's start. - let take = (piece + 1) * files / pieces - piece * files / pieces; - let from_ready = take.min(ready.len()); - self.piece( - ready.drain(..from_ready).collect(), - deferred.drain(..take - from_ready).collect(), - row_range.clone(), - ) - }) - .collect() - } - - /// Cuts every open file at its layout's split boundaries into `extra` more pieces than it has - /// files in all, shared among the open files by row count. Each unopened file is one piece. - fn split_within_files(self: Box, extra: usize) -> Vec { - fn rows(ranges: &[Range]) -> u64 { - ranges.iter().map(|range| range.end - range.start).sum() - } - - let file_ranges: Vec>>> = self - .ready - .iter() - .map(|reader| self.file_split_ranges(reader)) - .collect(); - let total_rows = file_ranges - .iter() - .flatten() - .map(|ranges| u128::from(rows(ranges))) - .sum::() - .max(1); - let budget = (self.ready.len() + extra) as u128; - - let mut pieces = Vec::new(); - for (reader, ranges) in self.ready.iter().zip(file_ranges) { - let Some(ranges) = ranges else { - // The file's splits could not be planned, so its partition reports why when read. - pieces.push(self.piece( - [Arc::clone(reader)].into(), - VecDeque::new(), - self.request.row_range.clone(), - )); - continue; - }; - let share = u128::from(rows(&ranges)) * budget / total_rows; - let share = NonZeroUsize::new(usize::try_from(share).unwrap_or(usize::MAX)) - .unwrap_or(NonZeroUsize::MIN); - for group in group_contiguous(ranges, share) { - if let (Some(first), Some(last)) = (group.first(), group.last()) { - pieces.push(self.piece( - [Arc::clone(reader)].into(), - VecDeque::new(), - Some(first.start..last.end), - )); - } - } - } - for factory in &self.deferred { - pieces.push(self.piece( - VecDeque::new(), - [Arc::clone(factory)].into(), - self.request.row_range.clone(), - )); - } - if pieces.is_empty() { - // Every open file's selection is empty and no file is unopened. - return vec![self]; - } - pieces - } - - /// The row ranges of `reader`'s natural splits that the scan reads, or `None` if they cannot - /// be planned, such as when the request does not bind to the file. - fn file_split_ranges(&self, reader: &LayoutReaderRef) -> Option>> { - let row_range = self - .request - .row_range - .clone() - .unwrap_or(0..reader.row_count()); - let filter = self.request.filter.clone().ok()?; - let scan = ScanBuilder::new(self.session.clone(), Arc::clone(reader)) - .with_selection(self.request.selection.clone()) - .with_projection(self.request.projection.clone()) - .with_some_filter(filter) - .prepare() - .ok()?; - Some(scan.split_ranges(Some(row_range))) - } -} - impl DataSourceScan for MultiLayoutScan { fn dtype(&self) -> &DType { &self.dtype } - /// Cuts the scan into up to `n` contiguous pieces in file order, reading metadata only. - /// - /// With no more pieces than files, each piece is a run of whole files. With more, each file - /// whose reader is open is cut further at its layout's split boundaries, with pieces shared - /// among the open files by row count. A file not yet opened is one piece, since cutting it - /// would mean opening it. + /// Cuts the scan into pieces of whole files, in file order, without opening any. /// /// A scan with a limit stays whole, because the limit is one budget across all its files, /// and so does one that selects partitions, because partition indices count from its first @@ -532,17 +403,43 @@ impl DataSourceScan for MultiLayoutScan { fn split(self: Box, n: NonZeroUsize) -> VortexResult> { let files = self.ready.len() + self.deferred.len(); if n.get() == 1 - || files == 0 + || files <= 1 || self.request.limit.is_some() || self.request.partition_range.is_some() || !matches!(self.request.partition_selection, Selection::All) { return Ok(vec![self]); } - if n.get() <= files { - return Ok(self.split_files(n.get())); - } - Ok(self.split_within_files(n.get() - files)) + let Self { + session, + source_dtype, + dtype, + request, + row_limit, + mut ready, + mut deferred, + handle, + concurrency, + } = *self; + let pieces = n.get().min(files); + Ok((0..pieces) + .map(|piece| { + // Piece `piece` takes files `piece * files / pieces` up to the next piece's start. + let take = (piece + 1) * files / pieces - piece * files / pieces; + let from_ready = take.min(ready.len()); + Box::new(MultiLayoutScan { + session: session.clone(), + source_dtype: source_dtype.clone(), + dtype: dtype.clone(), + request: request.clone(), + row_limit: row_limit.clone(), + ready: ready.drain(..from_ready).collect(), + deferred: deferred.drain(..take - from_ready).collect(), + handle: handle.clone(), + concurrency, + }) as DataSourceScanRef + }) + .collect()) } /// Opens the scan into its partition pipeline, which opens up to `concurrency` files ahead @@ -941,37 +838,6 @@ mod tests { Ok(()) } - /// With more pieces than files, an open file is cut at its split boundaries, and an - /// unopened file stays one piece. - #[test] - fn split_cuts_open_files_at_split_boundaries() -> VortexResult<()> { - let runtime = SingleThreadRuntime::default(); - let session = session_with_handle(runtime.handle()); - let first: LayoutReaderRef = Arc::new(TestLayoutReader::new(8).with_split_size(2)); - let rest: Vec> = vec![Arc::new(StaticReaderFactory { - reader: Arc::new(TestLayoutReader::new(2).with_base(10)), - })]; - let source = MultiLayoutDataSource::new_with_first(first, rest, vec![], &session); - - let scan = runtime.block_on(source.scan(ScanRequest { - ordered: true, - ..Default::default() - }))?; - let pieces = scan.split(NonZeroUsize::try_from(4)?)?; - assert_eq!(pieces.len(), 4); - - let mut values = Vec::new(); - for piece in pieces { - for partition in runtime.block_on(piece.partitions().try_collect::>())? { - values.extend(collect_scan_values( - runtime.block_on_stream(partition.execute()?), - )?); - } - } - assert_eq!(values, [0, 1, 2, 3, 4, 5, 6, 7, 10, 11]); - Ok(()) - } - /// Scans 64 one-row splits, returning the rows and the most splits read at once. fn scan_with_split_concurrency( split_concurrency: Option, From 570b1c334208b7ca1804b985dc55cb3823d4d202 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 13:54:08 -0500 Subject: [PATCH 18/25] Drop the layout pools' unused size and progress methods Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-layout/src/scan/layout.rs | 22 ---------------------- vortex-layout/src/scan/pool.rs | 26 +++----------------------- 2 files changed, 3 insertions(+), 45 deletions(-) diff --git a/vortex-layout/src/scan/layout.rs b/vortex-layout/src/scan/layout.rs index 5833a9001bb..f8505c8fb98 100644 --- a/vortex-layout/src/scan/layout.rs +++ b/vortex-layout/src/scan/layout.rs @@ -335,20 +335,6 @@ impl DataSourceScan for LayoutReaderScan { ))) } - fn row_count(&self) -> Precision { - let selected = self - .selection - .row_count_in_range(&(self.next_row..self.end_row)); - let rows = self - .remaining_limit - .map_or(selected, |limit| selected.min(limit)); - if self.filter.is_some() { - Precision::inexact(rows) - } else { - Precision::exact(rows) - } - } - fn partition_count(&self) -> Precision { let (lower, upper) = self.size_hint(); match upper { @@ -550,10 +536,6 @@ impl DataSourceScan for Empty { fn partitions(self: Box) -> PartitionStream { stream::iter([Ok(self as _)]).boxed() } - - fn row_count(&self) -> Precision { - Precision::exact(self.row_count) - } } impl Partition for Empty { @@ -772,7 +754,6 @@ mod split_open_tests { use futures::TryStreamExt; use futures::future::try_join_all; - use vortex_array::expr::stats::Precision; use vortex_error::VortexResult; use vortex_io::runtime::BlockingRuntime; use vortex_io::runtime::single::SingleThreadRuntime; @@ -805,8 +786,6 @@ mod split_open_tests { let mut values = collect_scan_values(arrays.into_iter().flatten().map(Ok))?; values.sort_unstable(); assert_eq!(values, (0..64).collect::>()); - assert!(pool.is_exhausted()); - assert_eq!(pool.progress(), 1.0); Ok(()) } @@ -819,7 +798,6 @@ mod split_open_tests { assert_eq!(pieces.len(), 4); let mut values = Vec::new(); for piece in pieces { - assert_eq!(piece.row_count(), Precision::exact(16u64)); let mut piece_values = collect_scan_values(runtime.block_on_stream(piece.open()?.worker()))?; // A worker yields its splits as they finish. diff --git a/vortex-layout/src/scan/pool.rs b/vortex-layout/src/scan/pool.rs index 207c55c41bf..dd0ba0e9fed 100644 --- a/vortex-layout/src/scan/pool.rs +++ b/vortex-layout/src/scan/pool.rs @@ -5,8 +5,6 @@ use std::iter; use std::sync::Arc; -use std::sync::atomic::AtomicUsize; -use std::sync::atomic::Ordering; use std::vec; use futures::StreamExt; @@ -37,9 +35,8 @@ type SplitTask = BoxFuture<'static, VortexResult>>; /// count that the stream multiplies by the cores, so a host polling one worker per core keeps as /// many splits in flight as the stream does. /// -/// A worker yields only the splits it claimed, and claims a split only when it has room for one. -/// So [`is_exhausted`](ScanPool::is_exhausted) turns true once every split has been claimed, and -/// a host can move a thread to other work then: no worker waits on a split another one claimed. +/// A worker yields only the splits it claimed, and claims a split only when it has room for one, +/// so no worker waits on a split another one claimed. /// /// [`RepeatedScan::execute`]: crate::scan::repeated_scan::RepeatedScan::execute pub(crate) struct SplitPool { @@ -47,8 +44,6 @@ pub(crate) struct SplitPool { handle: Handle, per_worker: usize, splits: Mutex>, - total: usize, - claimed: AtomicUsize, } impl SplitPool { @@ -62,17 +57,13 @@ impl SplitPool { dtype, handle, per_worker: per_worker.max(1), - total: splits.len(), splits: Mutex::new(splits.into_iter()), - claimed: AtomicUsize::new(0), } } /// Claims the next split, if any is left. fn claim(&self) -> Option { - let split = self.splits.lock().next()?; - self.claimed.fetch_add(1, Ordering::Release); - Some(split) + self.splits.lock().next() } } @@ -93,15 +84,4 @@ impl ScanPool for SplitPool { .filter_map(|array| future::ready(array.transpose())); ArrayStreamExt::boxed(ArrayStreamAdapter::new(dtype, arrays)) } - - fn progress(&self) -> f64 { - if self.total == 0 { - return 1.0; - } - (self.claimed.load(Ordering::Acquire) as f64 / self.total as f64).clamp(0.0, 1.0) - } - - fn is_exhausted(&self) -> bool { - self.claimed.load(Ordering::Acquire) >= self.total - } } From 40d7b336aa58403b989d9d08223ad310c198ac95 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 14:05:31 -0500 Subject: [PATCH 19/25] Drop dtype from the split pool Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-layout/src/scan/pool.rs | 4 ---- 1 file changed, 4 deletions(-) diff --git a/vortex-layout/src/scan/pool.rs b/vortex-layout/src/scan/pool.rs index dd0ba0e9fed..64e09524dba 100644 --- a/vortex-layout/src/scan/pool.rs +++ b/vortex-layout/src/scan/pool.rs @@ -68,10 +68,6 @@ impl SplitPool { } impl ScanPool for SplitPool { - fn dtype(&self) -> &DType { - &self.dtype - } - fn worker(self: Arc) -> SendableArrayStream { let dtype = self.dtype.clone(); let handle = self.handle.clone(); From 17ddf3427570b5ea7a0983fc965459ad396e513f Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 14:13:36 -0500 Subject: [PATCH 20/25] Cut multi-file scans inside files when there are fewer files than pieces Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-layout/src/scan/multi.rs | 440 +++++++++++++++++++++++++++++--- 1 file changed, 406 insertions(+), 34 deletions(-) diff --git a/vortex-layout/src/scan/multi.rs b/vortex-layout/src/scan/multi.rs index 5d5b605bbe6..6c87fa662ba 100644 --- a/vortex-layout/src/scan/multi.rs +++ b/vortex-layout/src/scan/multi.rs @@ -64,6 +64,7 @@ use vortex_session::VortexSession; use vortex_utils::parallelism::get_available_parallelism; use crate::LayoutReaderRef; +use crate::scan::layout::group_contiguous; use crate::scan::limit::RowLimit; use crate::scan::scan_builder::ScanBuilder; @@ -296,15 +297,23 @@ impl DataSource for MultiLayoutDataSource { async fn scan(&self, scan_request: ScanRequest) -> VortexResult { let mut ready = VecDeque::new(); let mut deferred = VecDeque::new(); + let mut ready_sizes = VecDeque::new(); + let mut deferred_sizes = VecDeque::new(); for child in self.children.iter() { match child { - MultiLayoutChild::Opened { reader, .. } => ready.push_back(Arc::clone(reader)), - MultiLayoutChild::Deferred { factory, .. } => { - deferred.push_back(Arc::clone(factory)) + MultiLayoutChild::Opened { reader, byte_size } => { + ready.push_back(Arc::clone(reader)); + ready_sizes.push_back(*byte_size); + } + MultiLayoutChild::Deferred { factory, byte_size } => { + deferred.push_back(Arc::clone(factory)); + deferred_sizes.push_back(*byte_size); } } } + // The scan reads its opened files first, so its sizes follow that order too. + let byte_sizes = ready_sizes.into_iter().chain(deferred_sizes).collect(); let request = BoundScanRequest::try_new(scan_request, &self.dtype)?; let dtype = request.projection.dtype().clone(); @@ -324,6 +333,8 @@ impl DataSource for MultiLayoutDataSource { row_limit, ready, deferred, + byte_sizes, + fraction: None, handle: self.session.handle(), concurrency: self.concurrency, })) @@ -386,16 +397,63 @@ struct MultiLayoutScan { row_limit: Option, ready: VecDeque, deferred: VecDeque>, + /// The on-storage size of each file, if known: the `ready` files, then the `deferred` ones. + byte_sizes: VecDeque>, + /// The part of its one unopened file that a piece of a split reads; `None` reads every file + /// whole. See [`FileFraction`]. + fraction: Option, handle: vortex_io::runtime::Handle, concurrency: usize, } +/// Piece `index` of `count` equal parts of a file's rows, for a piece cut from a file that was +/// not opened when the scan was split. +/// +/// The rows are resolved once the file is opened. The part's row range is computed from the +/// file's row count, and then each of the file's splits goes to the part whose range holds the +/// split's first row. So the parts of a file read each of its splits exactly once, whole. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct FileFraction { + index: u64, + count: u64, +} + +impl FileFraction { + /// The rows of `rows` that this part reads, given the start rows of the file's splits within + /// `rows`, in order. + fn resolve(self, rows: Range, split_starts: impl IntoIterator) -> Range { + let len = u128::from(rows.end - rows.start); + let at = |part: u64| { + rows.start + + u64::try_from(len * u128::from(part) / u128::from(self.count)).unwrap_or(u64::MAX) + }; + let (from, to) = (at(self.index), at(self.index + 1)); + let mut start = None; + for split in split_starts { + if split >= to { + return start.map_or(to..to, |start| start..split); + } + if split >= from && start.is_none() { + start = Some(split); + } + } + start.map_or(rows.end..rows.end, |start| start..rows.end) + } +} + impl DataSourceScan for MultiLayoutScan { fn dtype(&self) -> &DType { &self.dtype } - /// Cuts the scan into pieces of whole files, in file order, without opening any. + /// Cuts the scan into at most `n` pieces, in file order, reading metadata only. + /// + /// With at least `n` files, each piece is a run of whole files. The runs balance the files' + /// byte sizes when every size is known, and their counts otherwise. With fewer files, each + /// file gets a share of the `n` pieces in proportion to its size, at least one, and no piece + /// holds parts of two files. An opened file is cut at its natural split boundaries. A file + /// that is not opened is cut into equal fractions of its rows, which are resolved to whole + /// splits when the piece opens it; see [`FileFraction`]. /// /// A scan with a limit stays whole, because the limit is one budget across all its files, /// and so does one that selects partitions, because partition indices count from its first @@ -403,7 +461,8 @@ impl DataSourceScan for MultiLayoutScan { fn split(self: Box, n: NonZeroUsize) -> VortexResult> { let files = self.ready.len() + self.deferred.len(); if n.get() == 1 - || files <= 1 + || files == 0 + || self.fraction.is_some() || self.request.limit.is_some() || self.request.partition_range.is_some() || !matches!(self.request.partition_selection, Selection::All) @@ -418,28 +477,127 @@ impl DataSourceScan for MultiLayoutScan { row_limit, mut ready, mut deferred, + mut byte_sizes, + fraction: _, handle, concurrency, } = *self; - let pieces = n.get().min(files); - Ok((0..pieces) - .map(|piece| { - // Piece `piece` takes files `piece * files / pieces` up to the next piece's start. - let take = (piece + 1) * files / pieces - piece * files / pieces; - let from_ready = take.min(ready.len()); - Box::new(MultiLayoutScan { - session: session.clone(), - source_dtype: source_dtype.clone(), - dtype: dtype.clone(), - request: request.clone(), - row_limit: row_limit.clone(), - ready: ready.drain(..from_ready).collect(), - deferred: deferred.drain(..take - from_ready).collect(), - handle: handle.clone(), - concurrency, - }) as DataSourceScanRef - }) - .collect()) + + let weights: Vec = byte_sizes + .iter() + .map(|size| size.map(|size| u128::from(size.max(1)))) + .collect::>() + .unwrap_or_else(|| vec![1; files]); + let total = weights.iter().sum::(); + let n = n.get(); + + let piece = |ready: VecDeque, + deferred: VecDeque>, + byte_sizes: VecDeque>, + fraction: Option, + request: BoundScanRequest| { + Box::new(MultiLayoutScan { + session: session.clone(), + source_dtype: source_dtype.clone(), + dtype: dtype.clone(), + request, + row_limit: row_limit.clone(), + ready, + deferred, + byte_sizes, + fraction, + handle: handle.clone(), + concurrency, + }) as DataSourceScanRef + }; + + if files >= n { + // Each file joins the piece in which its first byte falls. + let mut runs: Vec = Vec::with_capacity(n); + let mut last_group = None; + let mut before = 0u128; + for weight in &weights { + let group = before * n as u128 / total; + before += weight; + match runs.last_mut() { + Some(run) if last_group == Some(group) => *run += 1, + _ => runs.push(1), + } + last_group = Some(group); + } + return Ok(runs + .into_iter() + .map(|take| { + let from_ready = take.min(ready.len()); + piece( + ready.drain(..from_ready).collect(), + deferred.drain(..take - from_ready).collect(), + byte_sizes.drain(..take).collect(), + None, + request.clone(), + ) + }) + .collect()); + } + + let spare = (n - files) as u128; + let shares = weights + .iter() + .map(|weight| 1 + u64::try_from(weight * spare / total).unwrap_or(0)); + let mut pieces = Vec::with_capacity(n); + let mut sizes = byte_sizes.into_iter(); + let ready_len = ready.len(); + for (file, share) in shares.enumerate() { + let size = sizes.next().flatten(); + if file < ready_len { + let Some(reader) = ready.pop_front() else { + break; + }; + let cuts = (share > 1) + .then(|| opened_file_cuts(&session, &reader, &request, share)) + .flatten(); + match cuts { + Some(cuts) => { + for rows in cuts { + let mut request = request.clone(); + request.row_range = Some(rows); + pieces.push(piece( + VecDeque::from([Arc::clone(&reader)]), + VecDeque::new(), + VecDeque::from([size]), + None, + request, + )); + } + } + None => pieces.push(piece( + VecDeque::from([reader]), + VecDeque::new(), + VecDeque::from([size]), + None, + request.clone(), + )), + } + } else { + let Some(factory) = deferred.pop_front() else { + break; + }; + for index in 0..share { + let fraction = (share > 1).then_some(FileFraction { + index, + count: share, + }); + pieces.push(piece( + VecDeque::new(), + VecDeque::from([Arc::clone(&factory)]), + VecDeque::from([size]), + fraction, + request.clone(), + )); + } + } + } + Ok(pieces) } /// Opens the scan into its partition pipeline, which opens up to `concurrency` files ahead @@ -466,6 +624,8 @@ impl DataSourceScan for MultiLayoutScan { row_limit, ready, deferred, + byte_sizes: _, + fraction, handle, concurrency, } = *self; @@ -525,6 +685,7 @@ impl DataSourceScan for MultiLayoutScan { &source_dtype, request.clone(), row_limit.clone(), + fraction, ), Err(e) => stream::once(async move { Err(e) }).boxed(), }) @@ -532,6 +693,66 @@ impl DataSourceScan for MultiLayoutScan { } } +/// The row ranges of `reader`'s natural splits within `rows` that `request` reads, or `None` if +/// they cannot be planned, such as when the request does not bind to the file. Reads metadata +/// only. +fn file_split_ranges( + session: &VortexSession, + reader: &LayoutReaderRef, + request: &BoundScanRequest, + rows: Range, +) -> Option>> { + let filter = request.filter.clone().ok()?; + let scan = ScanBuilder::new(session.clone(), Arc::clone(reader)) + .with_selection(request.selection.clone()) + .with_projection(request.projection.clone()) + .with_some_filter(filter) + .prepare() + .ok()?; + Some(scan.split_ranges(Some(rows))) +} + +/// Cuts the rows of an opened file that `request` reads into at most `share` ranges that cover +/// them in order, at the file's natural split boundaries. `None` if the file cannot be cut. +fn opened_file_cuts( + session: &VortexSession, + reader: &LayoutReaderRef, + request: &BoundScanRequest, + share: u64, +) -> Option>> { + let row_count = reader.row_count(); + let rows = request.row_range.clone().map_or(0..row_count, |rows| { + rows.start.min(row_count)..rows.end.min(row_count) + }); + let share = NonZeroUsize::new(usize::try_from(share).ok()?)?; + let splits = file_split_ranges(session, reader, request, rows.clone())?; + let groups = group_contiguous(splits, share); + if groups.len() <= 1 { + return None; + } + let last = groups.len() - 1; + Some( + groups + .iter() + .enumerate() + .filter_map(|(i, group)| { + // The cuts start and end where `rows` does, so no row is lost at either edge. + let start = if i == 0 { + rows.start + } else { + group.first()?.start + }; + let end = if i == last { + rows.end + } else { + group.last()?.end + }; + Some(start..end) + }) + .collect(), + ) +} + /// Generates a partition stream for a single layout reader. /// /// Checks file-level pruning first (via `pruning_evaluation`). If the filter proves no rows @@ -544,6 +765,7 @@ fn reader_partition( source_dtype: &DType, request: BoundScanRequest, row_limit: Option, + fraction: Option, ) -> PartitionStream { if reader.dtype() != source_dtype { let error = vortex_err!( @@ -555,7 +777,20 @@ fn reader_partition( } let row_count = reader.row_count(); - let row_range = request.row_range.clone().unwrap_or(0..row_count); + let mut row_range = request.row_range.clone().unwrap_or(0..row_count); + if let Some(fraction) = fraction { + let rows = row_range.start.min(row_count)..row_range.end.min(row_count); + // A file whose splits cannot be planned is one split, which the first part reads. + let split_starts = file_split_ranges(&session, &reader, &request, rows.clone()) + .map_or_else( + || vec![rows.start], + |splits| splits.into_iter().map(|s| s.start).collect(), + ); + row_range = fraction.resolve(rows, split_starts); + if row_range.is_empty() { + return stream::empty().boxed(); + } + } let partition_idx_u64: u64 = partition_idx as u64; if let Some(range) = &request.partition_range @@ -708,7 +943,7 @@ mod tests { #[async_trait] impl LayoutReaderFactory for NeverOpened { async fn open(&self) -> VortexResult> { - unreachable!("byte_size must not open readers") + unreachable!("byte_size and split must not open readers") } } @@ -796,7 +1031,39 @@ mod tests { Ok(()) } - /// Splitting hands out whole files in file order, without opening any. + /// Reads every partition of `piece`, in order. + fn piece_values( + runtime: &SingleThreadRuntime, + piece: DataSourceScanRef, + ) -> VortexResult> { + let mut values = Vec::new(); + for partition in runtime.block_on(piece.partitions().try_collect::>())? { + values.extend(collect_scan_values( + runtime.block_on_stream(partition.execute()?), + )?); + } + Ok(values) + } + + /// A source of files that are never opened, whose scans run on `runtime`. + fn unopened_files( + runtime: &SingleThreadRuntime, + byte_sizes: Vec>, + ) -> MultiLayoutDataSource { + let factories = byte_sizes + .iter() + .map(|_| Arc::new(NeverOpened) as Arc) + .collect(); + MultiLayoutDataSource::new_deferred( + DType::Bool(Nullability::NonNullable), + factories, + byte_sizes, + &session_with_handle(runtime.handle()), + ) + } + + /// With at least `n` files, splitting hands out runs of whole files in file order, without + /// opening any. #[test] fn split_groups_whole_files() -> VortexResult<()> { let runtime = SingleThreadRuntime::default(); @@ -820,24 +1087,129 @@ mod tests { assert_eq!( files, [ - Precision::exact(1usize), Precision::inexact(2usize), - Precision::inexact(2usize) + Precision::inexact(2usize), + Precision::inexact(1usize) ] ); let mut values = Vec::new(); for piece in pieces { - for partition in runtime.block_on(piece.partitions().try_collect::>())? { - values.extend(collect_scan_values( - runtime.block_on_stream(partition.execute()?), - )?); - } + values.extend(piece_values(&runtime, piece)?); } assert_eq!(values, [0, 1, 10, 11, 20, 21, 30, 31, 40, 41]); Ok(()) } + /// Known file sizes balance the runs by bytes rather than by file count. `NeverOpened` + /// panics if splitting opens a file. + #[test] + fn split_balances_whole_files_by_size() -> VortexResult<()> { + let runtime = SingleThreadRuntime::default(); + let scan = runtime.block_on( + unopened_files(&runtime, vec![Some(80), Some(10), Some(10)]) + .scan(ScanRequest::default()), + )?; + let files: Vec<_> = scan + .split(NonZeroUsize::try_from(2)?)? + .iter() + .map(|piece| piece.partition_count()) + .collect(); + assert_eq!( + files, + [Precision::inexact(1usize), Precision::inexact(2usize)] + ); + Ok(()) + } + + /// With fewer files than `n`, each file gets a share of the pieces by size, still without + /// opening any. + #[test] + fn split_shares_pieces_among_unopened_files_by_size() -> VortexResult<()> { + let runtime = SingleThreadRuntime::default(); + let scan = runtime.block_on( + unopened_files(&runtime, vec![Some(30), Some(10)]).scan(ScanRequest::default()), + )?; + // Two spare pieces: the larger file takes one of them, the smaller none. + assert_eq!(scan.split(NonZeroUsize::try_from(4)?)?.len(), 3); + Ok(()) + } + + /// An opened file is cut at its split boundaries. + #[test] + fn split_cuts_an_opened_file_at_splits() -> VortexResult<()> { + let runtime = SingleThreadRuntime::default(); + let session = session_with_handle(runtime.handle()); + let reader: LayoutReaderRef = Arc::new(TestLayoutReader::new(8).with_split_size(2)); + let source = MultiLayoutDataSource::new_with_first(reader, vec![], vec![], &session); + + let scan = runtime.block_on(source.scan(ScanRequest { + ordered: true, + ..Default::default() + }))?; + let pieces = scan + .split(NonZeroUsize::try_from(4)?)? + .into_iter() + .map(|piece| piece_values(&runtime, piece)) + .collect::>>()?; + assert_eq!(pieces, [vec![0, 1], vec![2, 3], vec![4, 5], vec![6, 7]]); + Ok(()) + } + + /// An unopened file is cut into fractions of its rows, resolved to whole splits once it is + /// opened. The fractions of this file meet at row 4, inside the split of rows 3..6, which + /// the first fraction reads whole because the split starts in it. + #[test] + fn split_reads_each_split_of_an_unopened_file_once() -> VortexResult<()> { + let runtime = SingleThreadRuntime::default(); + let session = session_with_handle(runtime.handle()); + let first: LayoutReaderRef = Arc::new(TestLayoutReader::new(2)); + let deferred = Arc::new(StaticReaderFactory { + reader: Arc::new(TestLayoutReader::new(9).with_split_size(3).with_base(100)), + }) as Arc; + let source = MultiLayoutDataSource::new_with_first(first, vec![deferred], vec![], &session); + + let scan = runtime.block_on(source.scan(ScanRequest { + ordered: true, + ..Default::default() + }))?; + let pieces = scan + .split(NonZeroUsize::try_from(4)?)? + .into_iter() + .map(|piece| piece_values(&runtime, piece)) + .collect::>>()?; + // The opened file has one split, so it stays one piece of the two it was given. + assert_eq!( + pieces, + [ + vec![0, 1], + vec![100, 101, 102, 103, 104, 105], + vec![106, 107, 108] + ] + ); + Ok(()) + } + + /// Each split goes to the fraction whose rows hold the split's first row, and a fraction in + /// which no split starts reads nothing. + #[rstest] + #[case::boundary_inside_a_split(0..9, vec![0, 3, 6], 2, vec![0..6, 6..9])] + #[case::fraction_without_a_split(0..9, vec![0, 6], 3, vec![0..6, 6..6, 6..9])] + #[case::one_split(10..20, vec![10], 2, vec![10..20, 20..20])] + fn file_fraction_resolves_to_whole_splits( + #[case] rows: Range, + #[case] split_starts: Vec, + #[case] count: u64, + #[case] expected: Vec>, + ) { + let resolved: Vec<_> = (0..count) + .map(|index| { + FileFraction { index, count }.resolve(rows.clone(), split_starts.iter().copied()) + }) + .collect(); + assert_eq!(resolved, expected); + } + /// Scans 64 one-row splits, returning the rows and the most splits read at once. fn scan_with_split_concurrency( split_concurrency: Option, From 426cb196aca229e417ac9227c9308386d6534f44 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 14:44:41 -0500 Subject: [PATCH 21/25] Say what LayoutReaderScan::builder builds Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-layout/src/scan/layout.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/vortex-layout/src/scan/layout.rs b/vortex-layout/src/scan/layout.rs index b3d930d06ff..24755112d6f 100644 --- a/vortex-layout/src/scan/layout.rs +++ b/vortex-layout/src/scan/layout.rs @@ -246,7 +246,8 @@ struct LayoutReaderScan { } impl LayoutReaderScan { - /// The scan over the rows that remain, as develop's DuckDB scan builds it for a file. + /// A scan builder over this scan's reader, with its selection, projection, filter, metrics + /// and split concurrency. Callers give it the row range to read. fn builder(&self) -> ScanBuilder { ScanBuilder::new(self.session.clone(), Arc::clone(&self.reader)) .with_selection(self.selection.clone()) From 00011de85945e4adf14000b2cdadbbc129fc307d Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 14:47:34 -0500 Subject: [PATCH 22/25] Read two files at once per clone of an unordered multi-file scan Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-layout/src/scan/multi.rs | 77 ++++++++++++++++++++++++++++++++- vortex-scan/src/lib.rs | 9 ++-- 2 files changed, 81 insertions(+), 5 deletions(-) diff --git a/vortex-layout/src/scan/multi.rs b/vortex-layout/src/scan/multi.rs index dc2e7094e65..00d35271434 100644 --- a/vortex-layout/src/scan/multi.rs +++ b/vortex-layout/src/scan/multi.rs @@ -33,6 +33,7 @@ use std::sync::Arc; use async_trait::async_trait; use futures::FutureExt; use futures::StreamExt; +use futures::TryStreamExt; use futures::stream; use itertools::Itertools; use tracing::Instrument; @@ -68,6 +69,13 @@ use crate::scan::layout::group_contiguous; use crate::scan::limit::RowLimit; use crate::scan::scan_builder::ScanBuilder; +/// How many files each clone of an unordered scan's opened stream reads at once. +/// +/// This matches the read-ahead of the DataFusion `VortexTable` path on develop +/// (`SCAN_PARTITION_READ_AHEAD`), so that reading a scan through `open` and through `split` +/// behaves the same. +const PARTITION_READ_AHEAD: usize = 2; + /// Default concurrency for opening deferred readers. const DEFAULT_CONCURRENCY: usize = 8; @@ -554,8 +562,28 @@ impl DataSourceScan for MultiLayoutScan { /// Opens the scan into its partition pipeline, which opens up to `concurrency` files ahead /// and reads each file as one partition, handing the partitions to the stream's clones. + /// + /// Each clone of an unordered scan without a limit reads [`PARTITION_READ_AHEAD`] files at + /// once, each with its own split concurrency, so that one file's last splits overlap the + /// next file's first. An ordered scan must finish a file before it starts the next, and a + /// limited one would read files the limit may never need, so both read one at a time. fn open(self: Box) -> VortexResult { - Ok(ScanStream::from_partitions(self)) + if self.request.ordered || self.request.limit.is_some() { + return Ok(ScanStream::from_partitions(self)); + } + let dtype = self.dtype.clone(); + let partitions = Arc::new(futures::lock::Mutex::new(self.partitions())); + Ok(ScanStream::new(dtype, move || { + stream::unfold(Arc::clone(&partitions), |shared| async move { + let next = shared.lock().await.next().await?; + Some((next, shared)) + }) + .map(|partition| partition.and_then(|partition| partition.execute())) + // Matches the DataFusion `VortexTable` path's read-ahead on develop, so a scan read + // through `open` behaves as one read through `split`. + .try_flatten_unordered(Some(PARTITION_READ_AHEAD)) + .boxed() + })) } fn partition_count(&self) -> Precision { @@ -1122,6 +1150,53 @@ mod tests { Ok(()) } + /// A clone of an unordered scan's opened stream reads two files at once, each with its own + /// split concurrency. An ordered scan reads one file at a time. + #[rstest] + #[case::unordered(false, 2)] + #[case::ordered(true, 1)] + fn opened_stream_reads_files_ahead( + #[case] ordered: bool, + #[case] expected_peak: usize, + ) -> VortexResult<()> { + let runtime = SingleThreadRuntime::default(); + let session = session_with_handle(runtime.handle()); + let in_flight = Arc::new(InFlight::default()); + let file = |base: i32| { + Arc::new( + TestLayoutReader::new(8) + .with_split_size(1) + .with_base(base) + .with_in_flight(Arc::clone(&in_flight)), + ) as LayoutReaderRef + }; + let rest = (1..3) + .map(|i| { + Arc::new(StaticReaderFactory { + reader: file(10 * i), + }) as Arc + }) + .collect(); + let source = MultiLayoutDataSource::new_with_first(file(0), rest, vec![], &session); + + let stream = runtime + .block_on(source.scan(ScanRequest { + ordered, + split_concurrency: NonZeroUsize::new(1), + ..Default::default() + }))? + .open()?; + let mut values = collect_scan_values(runtime.block_on_stream(stream))?; + values.sort_unstable(); + let expected: Vec = [0, 10, 20] + .into_iter() + .flat_map(|base| base..base + 8) + .collect(); + assert_eq!(values, expected); + assert_eq!(in_flight.peak(), expected_peak, "splits read at once"); + Ok(()) + } + /// Scans 64 one-row splits, returning the rows and the most splits read at once. fn scan_with_split_concurrency( split_concurrency: Option, diff --git a/vortex-scan/src/lib.rs b/vortex-scan/src/lib.rs index 1838ff10157..369f2edfb79 100644 --- a/vortex-scan/src/lib.rs +++ b/vortex-scan/src/lib.rs @@ -178,11 +178,12 @@ pub struct ScanRequest { /// order is completion order, so each partition applies the limit locally and the caller must /// trim the concatenated result. pub limit: Option, - /// The most splits that each worker decodes at once, where a worker is a partition or a - /// clone of an opened scan's stream. + /// The most splits decoded at once for each partition being read, or for each clone of an + /// opened scan's stream that reads a single queue of splits. /// - /// It bounds each worker on its own, not the whole scan: a scan read by several workers - /// decodes up to this many splits in each. `None` keeps the source's default. Each + /// It does not bound the whole scan: a scan read by several workers decodes up to this many + /// splits for each partition each worker is reading, and a worker may read more than one + /// partition at once. `None` keeps the source's default. Each /// split being decoded holds the decoded chunks of every column it overlaps, so a scan that /// runs alongside others, such as one task of several on a machine, can set this to bound its /// memory. It does not bound I/O: segment reads for later splits may still be coalesced ahead From db19654ba524ea507a1648dfb15312996077f7c6 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 15:26:23 -0500 Subject: [PATCH 23/25] Poll a worker's only split on the thread that reads it Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-layout/src/scan/split_queue.rs | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/vortex-layout/src/scan/split_queue.rs b/vortex-layout/src/scan/split_queue.rs index ba46fe3a263..c92071300fd 100644 --- a/vortex-layout/src/scan/split_queue.rs +++ b/vortex-layout/src/scan/split_queue.rs @@ -35,6 +35,10 @@ type SplitTask = BoxFuture<'static, VortexResult>>; /// A worker yields only the splits it claimed, and claims a split only when it has room for one, /// so no worker waits on a split another one claimed. /// +/// A worker with room for one split has nothing to overlap it with, so it polls the split itself +/// rather than spawning it. The split then runs on the thread that polls the worker, which also +/// consumes its array, and no other thread driving the runtime picks it up. +/// /// [`RepeatedScan::execute`]: crate::scan::repeated_scan::RepeatedScan::execute pub(crate) struct SplitQueue { handle: Handle, @@ -60,9 +64,16 @@ impl SplitQueue { pub(crate) fn worker(self: Arc) -> BoxStream<'static, VortexResult> { let handle = self.handle.clone(); let per_worker = self.per_worker; + let splits = stream::iter(iter::from_fn(move || self.claim())); + if per_worker == 1 { + return splits + .then(|split| split) + .filter_map(|array| future::ready(array.transpose())) + .boxed(); + } // `buffer_unordered` pulls a split only when it has room, so a worker claims no more // than it runs. - stream::iter(iter::from_fn(move || self.claim())) + splits .map(move |split| handle.spawn(split)) .buffer_unordered(per_worker) .filter_map(|array| future::ready(array.transpose())) From 1c91d119b4366a5dc76e2dd107cd86224e1ae7ad Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 16:26:56 -0500 Subject: [PATCH 24/25] Cut layout scans into fixed pieces for every request Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-layout/src/scan/layout.rs | 31 ++++++++--------------- vortex-layout/src/scan/multi.rs | 43 +++++++++++++++----------------- 2 files changed, 30 insertions(+), 44 deletions(-) diff --git a/vortex-layout/src/scan/layout.rs b/vortex-layout/src/scan/layout.rs index 24755112d6f..ce883a459a5 100644 --- a/vortex-layout/src/scan/layout.rs +++ b/vortex-layout/src/scan/layout.rs @@ -41,7 +41,6 @@ use vortex_scan::PartitionStream; use vortex_scan::ScanRequest; use vortex_scan::selection::Selection; use vortex_scan::stream::ScanStream; -use vortex_scan::stream::split_shared; use vortex_session::VortexSession; use crate::LayoutReaderRef; @@ -284,18 +283,14 @@ impl DataSourceScan for LayoutReaderScan { &self.dtype } - /// Splits an unordered scan into `n` pieces that share its opened stream, and so its - /// splits. Cuts an ordered scan at the layout's natural split boundaries, into contiguous - /// pieces of about equal rows. + /// Cuts the scan at the layout's natural split boundaries, into contiguous pieces of about + /// equal rows. /// /// A scan with a limit stays whole, because the limit is one budget across all its rows. fn split(self: Box, n: NonZeroUsize) -> VortexResult> { if n.get() == 1 || self.remaining_limit.is_some() || self.next_row >= self.end_row { return Ok(vec![self]); } - if !self.ordered { - return split_shared(self, n); - } let ranges = self .builder() .prepare()? @@ -793,25 +788,19 @@ mod split_open_tests { Ok(()) } - /// The pieces of an unordered scan share its splits, so together they read every row once. + /// The pieces of an unordered scan are fixed too: each owns a contiguous run of splits, + /// which it may return in any order. #[test] - fn unordered_pieces_share_the_splits() -> VortexResult<()> { + fn unordered_pieces_own_their_rows() -> VortexResult<()> { let runtime = SingleThreadRuntime::default(); let scan = runtime.block_on(source(&runtime).scan(ScanRequest::default()))?; let pieces = scan.split(NonZeroUsize::try_from(4)?)?; assert_eq!(pieces.len(), 4); - let streams = pieces - .into_iter() - .map(|piece| piece.open()) - .collect::>>()?; - let arrays = runtime.block_on(try_join_all( - streams - .into_iter() - .map(|stream| stream.try_collect::>()), - ))?; - let mut values = collect_scan_values(arrays.into_iter().flatten().map(Ok))?; - values.sort_unstable(); - assert_eq!(values, (0..64).collect::>()); + for (i, piece) in (0i32..).zip(pieces) { + let mut values = collect_scan_values(runtime.block_on_stream(piece.open()?))?; + values.sort_unstable(); + assert_eq!(values, (16 * i..16 * (i + 1)).collect::>()); + } Ok(()) } diff --git a/vortex-layout/src/scan/multi.rs b/vortex-layout/src/scan/multi.rs index 00d35271434..9e9ad36264b 100644 --- a/vortex-layout/src/scan/multi.rs +++ b/vortex-layout/src/scan/multi.rs @@ -60,7 +60,6 @@ use vortex_scan::PartitionStream; use vortex_scan::ScanRequest; use vortex_scan::selection::Selection; use vortex_scan::stream::ScanStream; -use vortex_scan::stream::split_shared; use vortex_session::VortexSession; use vortex_utils::parallelism::get_available_parallelism; @@ -415,11 +414,9 @@ impl DataSourceScan for MultiLayoutScan { &self.dtype } - /// Splits an unordered scan into `n` clones of its opened partition stream, which share its - /// files. Cuts an ordered scan into at most `n` contiguous pieces in file order, reading - /// metadata only. + /// Cuts the scan into at most `n` contiguous pieces in file order, reading metadata only. /// - /// With at least `n` files, each ordered piece is a run of whole files. The runs balance the + /// With at least `n` files, each piece is a run of whole files. The runs balance the /// files' byte sizes when every size is known, and their counts otherwise. With fewer files, /// each file gets a share of the `n` pieces in proportion to its size, at least one, and no /// piece holds parts of two files. A file that is open is cut at its natural split @@ -427,17 +424,14 @@ impl DataSourceScan for MultiLayoutScan { /// opening it, so the scan may return fewer than `n` pieces. /// /// A scan with a limit stays whole, because the limit is one budget across all its files. - /// So does an ordered one that selects partitions, because partition indices count from its - /// first file. + /// So does one that selects partitions, because partition indices count from its first + /// file. fn split(self: Box, n: NonZeroUsize) -> VortexResult> { let files = self.ready.len() + self.deferred.len(); - if n.get() == 1 || files == 0 || self.request.limit.is_some() { - return Ok(vec![self]); - } - if !self.request.ordered { - return split_shared(self, n); - } - if self.request.partition_range.is_some() + if n.get() == 1 + || files == 0 + || self.request.limit.is_some() + || self.request.partition_range.is_some() || !matches!(self.request.partition_selection, Selection::All) { return Ok(vec![self]); @@ -1123,9 +1117,10 @@ mod tests { Ok(()) } - /// The pieces of an unordered scan share its files, so together they read every row once. + /// The pieces of an unordered scan are fixed: each owns its files' rows. Files that cannot + /// be cut stay whole, so there may be fewer pieces than asked for. #[test] - fn unordered_pieces_share_the_files() -> VortexResult<()> { + fn unordered_pieces_own_their_files() -> VortexResult<()> { let runtime = SingleThreadRuntime::default(); let session = session_with_handle(runtime.handle()); let first: LayoutReaderRef = Arc::new(TestLayoutReader::new(2)); @@ -1140,13 +1135,15 @@ mod tests { let scan = runtime.block_on(source.scan(ScanRequest::default()))?; let pieces = scan.split(NonZeroUsize::try_from(5)?)?; - assert_eq!(pieces.len(), 5); - let mut values = Vec::new(); - for piece in pieces { - values.extend(piece_values(&runtime, piece)?); - } - values.sort_unstable(); - assert_eq!(values, [0, 1, 10, 11, 20, 21]); + let pieces = pieces + .into_iter() + .map(|piece| { + let mut values = piece_values(&runtime, piece)?; + values.sort_unstable(); + Ok(values) + }) + .collect::>>()?; + assert_eq!(pieces, [vec![0, 1], vec![10, 11], vec![20, 21]]); Ok(()) } From 4fa814171a2d24e7111bc5089e6c4eba3318f790 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 16:27:48 -0500 Subject: [PATCH 25/25] Describe the read-ahead without reference to split Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-layout/src/scan/multi.rs | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/vortex-layout/src/scan/multi.rs b/vortex-layout/src/scan/multi.rs index 9e9ad36264b..c092f37eca7 100644 --- a/vortex-layout/src/scan/multi.rs +++ b/vortex-layout/src/scan/multi.rs @@ -71,8 +71,7 @@ use crate::scan::scan_builder::ScanBuilder; /// How many files each clone of an unordered scan's opened stream reads at once. /// /// This matches the read-ahead of the DataFusion `VortexTable` path on develop -/// (`SCAN_PARTITION_READ_AHEAD`), so that reading a scan through `open` and through `split` -/// behaves the same. +/// (`SCAN_PARTITION_READ_AHEAD`), whose partitions share one stream of files as the clones do. const PARTITION_READ_AHEAD: usize = 2; /// Default concurrency for opening deferred readers. @@ -573,8 +572,7 @@ impl DataSourceScan for MultiLayoutScan { Some((next, shared)) }) .map(|partition| partition.and_then(|partition| partition.execute())) - // Matches the DataFusion `VortexTable` path's read-ahead on develop, so a scan read - // through `open` behaves as one read through `split`. + // Matches the read-ahead of the DataFusion `VortexTable` path on develop. .try_flatten_unordered(Some(PARTITION_READ_AHEAD)) .boxed() }))