diff --git a/vortex-layout/src/scan/layout.rs b/vortex-layout/src/scan/layout.rs index c240daddb36..2b1551bb7de 100644 --- a/vortex-layout/src/scan/layout.rs +++ b/vortex-layout/src/scan/layout.rs @@ -15,6 +15,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; @@ -30,6 +31,7 @@ use vortex_array::stream::SendableArrayStream; use vortex_error::VortexResult; use vortex_error::vortex_bail; use vortex_error::vortex_err; +use vortex_io::session::RuntimeSessionExt; use vortex_mask::Mask; use vortex_metrics::MetricsRegistry; use vortex_scan::DataSource; @@ -40,6 +42,7 @@ use vortex_scan::PartitionRef; use vortex_scan::PartitionStream; use vortex_scan::ScanRequest; use vortex_scan::selection::Selection; +use vortex_scan::stream::ExhaustedFlag; use vortex_scan::stream::ScanExec; use vortex_session::VortexSession; @@ -47,7 +50,9 @@ use crate::LayoutReaderRef; use crate::scan::limit::RowLimit; use crate::scan::metrics::ScanMetrics; use crate::scan::metrics::ScanRecorder; +use crate::scan::repeated_scan::DEFAULT_SPLITS_PER_THREAD; use crate::scan::scan_builder::ScanBuilder; +use crate::scan::split_queue::SplitQueue; /// Cursor over absolute split-grid partition indices for a [`LayoutReaderDataSource`]. /// @@ -128,6 +133,20 @@ impl PartitionCursor { Some((partition_idx, split_start..split_end)) } + /// The rows the cursor has left, when they are a whole run of the grid: no partition range + /// or selection trims them. A scan cut into pieces or opened into a queue reads its rows + /// without the grid, so only such a scan can be. + fn whole_rows(&self) -> Option> { + if !matches!(self.partition_selection, Selection::All) { + return None; + } + let split_size = self.split_size.get(); + let start = self.next_partition.saturating_mul(split_size); + let end = self.end_partition.saturating_mul(split_size); + let covers_end = end >= self.row_range.end || self.row_range.start >= self.row_range.end; + (start <= self.row_range.start && covers_end).then(|| self.row_range.clone()) + } + fn remaining_count(&self) -> u64 { if self.next_partition >= self.end_partition { return 0; @@ -338,17 +357,96 @@ struct LayoutReaderScan { cursor: PartitionCursor, } +impl LayoutReaderScan { + /// 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()) + .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.clone(), + projection: self.projection.clone(), + filter: self.filter.clone(), + remaining_limit: None, + row_limit: None, + ordered: self.ordered, + split_concurrency: self.split_concurrency, + selection: self.selection.clone(), + metrics: self.metrics.clone(), + cursor: PartitionCursor::new(rows, self.cursor.split_size, None, Selection::All), + } + } +} + impl DataSourceScan for LayoutReaderScan { fn dtype(&self) -> &DType { &self.dtype } - fn split(self: Box, _n: NonZeroUsize) -> VortexResult> { - Ok(vec![self]) + /// 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. So + /// does one that selects partitions, because its pieces would read rows outside them. + fn split(self: Box, n: NonZeroUsize) -> VortexResult> { + let rows = match self.cursor.whole_rows() { + Some(rows) if n.get() > 1 && self.remaining_limit.is_none() && !rows.is_empty() => rows, + _ => return Ok(vec![self]), + }; + let ranges = self.builder().prepare()?.split_ranges(Some(rows)); + 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()) } + /// Opens the scan into a [`SplitQueue`] of its split futures, each stream of it keeping the + /// stream pipeline's per-thread count of them in flight. + /// + /// Split futures cannot share a limit, and the streams 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 the streams. So does one that selects partitions, which the queue + /// does not know. fn open(self: Box) -> VortexResult { - Ok(ScanExec::from_partitions(self)) + let rows = match self.cursor.whole_rows() { + Some(rows) if self.remaining_limit.is_none() && !self.ordered => rows, + _ => return Ok(ScanExec::from_partitions(self)), + }; + // A cap on the scan's splits in flight also caps each stream'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(rows))?; + let exhausted = ExhaustedFlag::new(); + let queue = Arc::new(SplitQueue::new( + self.session.handle(), + per_worker, + splits, + exhausted.clone(), + )); + Ok(ScanExec::new(self.dtype, exhausted, move || { + Arc::clone(&queue).worker() + })) } fn partition_count(&self) -> Precision { @@ -365,6 +463,33 @@ impl DataSourceScan for LayoutReaderScan { } } +/// 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 { type Item = VortexResult; @@ -1081,3 +1206,116 @@ mod tests { Ok(()) } } + +#[cfg(test)] +mod split_open_tests { + use std::num::NonZeroUsize; + use std::sync::Arc; + + use futures::TryStreamExt; + use futures::future::try_join_all; + use vortex_error::VortexResult; + use vortex_io::runtime::BlockingRuntime; + use vortex_io::runtime::single::SingleThreadRuntime; + use vortex_scan::DataSource; + use vortex_scan::ScanRequest; + + use super::LayoutReaderDataSource; + use super::group_contiguous; + use crate::scan::test::TestLayoutReader; + use crate::scan::test::collect_scan_values; + use crate::scan::test::session_with_handle; + + fn source(runtime: &SingleThreadRuntime) -> LayoutReaderDataSource { + LayoutReaderDataSource::new( + Arc::new(TestLayoutReader::new(64).with_split_size(4)), + session_with_handle(runtime.handle()), + ) + } + + /// The streams of an opened scan each claim splits until none is left, so together they read + /// every row once, and the scan is exhausted once the last split is claimed. + #[test] + fn opened_streams_read_every_row_once() -> VortexResult<()> { + let runtime = SingleThreadRuntime::default(); + let exec = runtime + .block_on(source(&runtime).scan(ScanRequest::default()))? + .open()?; + assert!(!exec.is_exhausted()); + let workers = (0..3).map(|_| exec.stream().try_collect::>()); + let arrays = runtime.block_on(try_join_all(workers))?; + let mut values = collect_scan_values(arrays.into_iter().flatten().map(Ok))?; + values.sort_unstable(); + assert_eq!(values, (0..64).collect::>()); + assert!(exec.is_exhausted()); + Ok(()) + } + + /// 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_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); + for (i, piece) in (0i32..).zip(pieces) { + let mut values = collect_scan_values(runtime.block_on_stream(piece.open()?.stream()))?; + values.sort_unstable(); + assert_eq!(values, (16 * i..16 * (i + 1)).collect::>()); + } + Ok(()) + } + + /// An ordered scan is cut at the layout's split boundaries, and the pieces read the rows in + /// order. + #[test] + fn ordered_split_cuts_at_split_boundaries() -> VortexResult<()> { + let runtime = SingleThreadRuntime::default(); + let scan = runtime.block_on(source(&runtime).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 { + values.extend(collect_scan_values( + runtime.block_on_stream(piece.open()?.stream()), + )?); + } + assert_eq!(values, (0..64).collect::>()); + Ok(()) + } + + /// 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 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); + + let stream = runtime.block_on(source.scan(request()))?.open()?.stream(); + let values = collect_scan_values(runtime.block_on_stream(stream))?; + assert_eq!(values.len(), 10); + Ok(()) + } + + #[test] + fn group_contiguous_keeps_ranges_whole() -> VortexResult<()> { + // 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..16], vec![16..26, 26..32]]); + Ok(()) + } +} diff --git a/vortex-layout/src/scan/mod.rs b/vortex-layout/src/scan/mod.rs index ea8e8843773..bda570ee1e7 100644 --- a/vortex-layout/src/scan/mod.rs +++ b/vortex-layout/src/scan/mod.rs @@ -10,6 +10,7 @@ pub mod multi; pub mod repeated_scan; pub mod scan_builder; pub mod split_by; +mod split_queue; mod splits; mod tasks; #[cfg(test)] diff --git a/vortex-layout/src/scan/multi.rs b/vortex-layout/src/scan/multi.rs index b085753f08b..819e9dff5d7 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; @@ -58,14 +59,22 @@ use vortex_scan::PartitionRef; use vortex_scan::PartitionStream; use vortex_scan::ScanRequest; use vortex_scan::selection::Selection; +use vortex_scan::stream::ExhaustedFlag; use vortex_scan::stream::ScanExec; 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; +/// How many files each stream of an opened unordered scan reads at once. +/// +/// This matches the read-ahead of the DataFusion `VortexTable` path on develop +/// (`SCAN_PARTITION_READ_AHEAD`), whose partitions share one stream of files as the scan's streams do. +const PARTITION_READ_AHEAD: usize = 2; + /// Default concurrency for opening deferred readers. const DEFAULT_CONCURRENCY: usize = 8; @@ -301,20 +310,26 @@ impl DataSource for MultiLayoutDataSource { let mut ready = VecDeque::new(); let mut deferred = VecDeque::new(); + let mut ready_sizes = VecDeque::new(); + let mut deferred_sizes = VecDeque::new(); for (partition_idx, child) in self.children.iter().enumerate() { if !request.includes_partition(partition_idx as u64) { continue; } match child { - MultiLayoutChild::Opened { reader, .. } => { - ready.push_back((partition_idx, Arc::clone(reader))) + MultiLayoutChild::Opened { reader, byte_size } => { + ready.push_back((partition_idx, Arc::clone(reader))); + ready_sizes.push_back(*byte_size); } - MultiLayoutChild::Deferred { factory, .. } => { - deferred.push_back((partition_idx, Arc::clone(factory))) + MultiLayoutChild::Deferred { factory, byte_size } => { + deferred.push_back((partition_idx, 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(); // Only unordered scans share a limit across external partitions: reservation order is // completion order, which an ordered scan cannot accept. Ordered partitions each apply the @@ -331,6 +346,7 @@ impl DataSource for MultiLayoutDataSource { row_limit, ready, deferred, + byte_sizes, handle: self.session.handle(), concurrency: self.concurrency, })) @@ -399,8 +415,12 @@ struct MultiLayoutScan { dtype: DType, request: BoundScanRequest, row_limit: Option, + /// The opened files, each with its partition index among the source's children. ready: VecDeque<(usize, LayoutReaderRef)>, + /// The files still to open, each with its partition index among the source's children. deferred: VecDeque<(usize, Arc)>, + /// The on-storage size of each file, if known: the `ready` files, then the `deferred` ones. + byte_sizes: VecDeque>, handle: vortex_io::runtime::Handle, concurrency: usize, } @@ -410,12 +430,178 @@ impl DataSourceScan for MultiLayoutScan { &self.dtype } - fn split(self: Box, _n: NonZeroUsize) -> VortexResult> { - Ok(vec![self]) + /// Cuts the scan into at most `n` contiguous 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. A file that is open is cut at its natural split + /// boundaries. A file that is not open stays one piece, because cutting it would mean + /// 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 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() + || 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, + mut byte_sizes, + handle, + concurrency, + } = *self; + + 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<(usize, LayoutReaderRef)>, + deferred: VecDeque<(usize, Arc)>, + byte_sizes: VecDeque>, + 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, + 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(), + 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((partition_idx, 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([(partition_idx, Arc::clone(&reader))]), + VecDeque::new(), + VecDeque::from([size]), + request, + )); + } + } + None => pieces.push(piece( + VecDeque::from([(partition_idx, reader)]), + VecDeque::new(), + VecDeque::from([size]), + request.clone(), + )), + } + } else { + let Some(factory) = deferred.pop_front() else { + break; + }; + pieces.push(piece( + VecDeque::new(), + VecDeque::from([factory]), + VecDeque::from([size]), + request.clone(), + )); + } + } + Ok(pieces) } + /// 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 scan's streams. + /// + /// Each stream 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(ScanExec::from_partitions(self)) + if self.request.ordered || self.request.limit.is_some() { + return Ok(ScanExec::from_partitions(self)); + } + let dtype = self.dtype.clone(); + let exhausted = ExhaustedFlag::new(); + let flag = exhausted.clone(); + let partitions = Arc::new(futures::lock::Mutex::new(self.partitions())); + Ok(ScanExec::new(dtype, exhausted, move || { + let flag = flag.clone(); + stream::unfold(Arc::clone(&partitions), move |shared| { + let flag = flag.clone(); + async move { + let Some(next) = shared.lock().await.next().await else { + flag.set(); + return None; + }; + Some((next, shared)) + } + }) + .map(|partition| partition.and_then(|partition| partition.execute())) + // Matches the read-ahead of the DataFusion `VortexTable` path on develop. + .try_flatten_unordered(Some(PARTITION_READ_AHEAD)) + .boxed() + })) } fn partition_count(&self) -> Precision { @@ -436,6 +622,7 @@ impl DataSourceScan for MultiLayoutScan { row_limit, ready, deferred, + byte_sizes: _, handle, concurrency, } = *self; @@ -504,6 +691,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 @@ -663,7 +910,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") } } @@ -751,6 +998,212 @@ mod tests { Ok(()) } + /// 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(); + 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::inexact(2usize), + Precision::inexact(2usize), + Precision::inexact(1usize) + ] + ); + + let mut values = Vec::new(); + for piece in pieces { + 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 { + ordered: true, + ..Default::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(()) + } + + /// An ordered split never opens a file to cut it, so an unopened file stays one piece. + #[test] + fn ordered_split_keeps_unopened_files_whole() -> VortexResult<()> { + let runtime = SingleThreadRuntime::default(); + let scan = runtime.block_on(unopened_files(&runtime, vec![Some(30), Some(10)]).scan( + ScanRequest { + ordered: true, + ..Default::default() + }, + ))?; + assert_eq!(scan.split(NonZeroUsize::try_from(4)?)?.len(), 2); + 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(()) + } + + /// 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_own_their_files() -> VortexResult<()> { + let runtime = SingleThreadRuntime::default(); + let session = session_with_handle(runtime.handle()); + let first: LayoutReaderRef = Arc::new(TestLayoutReader::new(2)); + let rest = (1..3) + .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::default()))?; + let pieces = scan.split(NonZeroUsize::try_from(5)?)?; + 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(()) + } + + /// A stream of an opened unordered scan 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()? + .stream(); + 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-layout/src/scan/repeated_scan.rs b/vortex-layout/src/scan/repeated_scan.rs index 2a1c7026923..1a950fec418 100644 --- a/vortex-layout/src/scan/repeated_scan.rs +++ b/vortex-layout/src/scan/repeated_scan.rs @@ -188,7 +188,8 @@ impl RepeatedScan { }) } - fn split_ranges(&self, row_range: Option>) -> Vec> { + /// 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() => { Some(buf[0]..buf[buf.len() - 1] + 1) @@ -438,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 b57162dde0b..6d74559550c 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/split_queue.rs b/vortex-layout/src/scan/split_queue.rs new file mode 100644 index 00000000000..1f25fde5d1b --- /dev/null +++ b/vortex-layout/src/scan/split_queue.rs @@ -0,0 +1,100 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! The queue of splits behind an opened layout scan. + +use std::iter; +use std::sync::Arc; +use std::vec; + +use futures::StreamExt; +use futures::future; +use futures::future::BoxFuture; +use futures::stream; +use futures::stream::BoxStream; +use parking_lot::Mutex; +use vortex_array::ArrayRef; +use vortex_error::VortexResult; +use vortex_io::runtime::Handle; +use vortex_scan::stream::ExhaustedFlag; + +use crate::scan::repeated_scan::ScanTasks; + +/// 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 queue of the split futures of [`RepeatedScan::execute`], in row order, which the streams of +/// an opened scan share. Each stream polls one worker over the queue. +/// +/// Each worker claims splits from the 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 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, + per_worker: usize, + splits: Mutex>, + /// Set once the last split is claimed. + exhausted: ExhaustedFlag, +} + +impl SplitQueue { + pub(crate) fn new( + handle: Handle, + per_worker: usize, + splits: ScanTasks, + exhausted: ExhaustedFlag, + ) -> Self { + if splits.is_empty() { + exhausted.set(); + } + Self { + handle, + per_worker: per_worker.max(1), + splits: Mutex::new(splits.into_iter()), + exhausted, + } + } + + /// Claims the next split, if any is left, and marks the queue exhausted when it claims the + /// last. + fn claim(&self) -> Option { + let mut splits = self.splits.lock(); + let split = splits.next()?; + if splits.len() == 0 { + self.exhausted.set(); + } + Some(split) + } + + /// A new worker over the shared queue, which one stream of the scan polls. + 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. + splits + .map(move |split| handle.spawn(split)) + .buffer_unordered(per_worker) + .filter_map(|array| future::ready(array.transpose())) + .boxed() + } +} diff --git a/vortex-scan/src/lib.rs b/vortex-scan/src/lib.rs index 4a625b9c421..fe00d0480fe 100644 --- a/vortex-scan/src/lib.rs +++ b/vortex-scan/src/lib.rs @@ -182,11 +182,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 - /// stream of an opened scan. + /// The most splits decoded at once for each partition being read, or for each stream of an + /// opened scan 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