diff --git a/vortex-datafusion/src/v2/source.rs b/vortex-datafusion/src/v2/source.rs index cefefb0f696..a491b92cf94 100644 --- a/vortex-datafusion/src/v2/source.rs +++ b/vortex-datafusion/src/v2/source.rs @@ -70,6 +70,7 @@ use std::any::Any; use std::fmt; use std::fmt::Formatter; +use std::num::NonZeroUsize; use std::pin::Pin; use std::sync::Arc; use std::sync::atomic::AtomicBool; @@ -498,6 +499,7 @@ impl VortexDataSource { filter: self.filter.clone(), limit: self.limit.map(|l| u64::try_from(l).unwrap_or(u64::MAX)), ordered: self.ordered, + target_partitions: NonZeroUsize::new(self.target_parallelism), ..Default::default() }; let data_source = Arc::clone(&self.data_source); diff --git a/vortex-ffi/src/scan.rs b/vortex-ffi/src/scan.rs index 16f6803e23f..6eb4e83d830 100644 --- a/vortex-ffi/src/scan.rs +++ b/vortex-ffi/src/scan.rs @@ -210,6 +210,7 @@ fn scan_request(opts: *const vx_scan_options) -> VortexResult { partition_selection: Selection::All, partition_range: None, split_concurrency: None, + target_partitions: None, }) } diff --git a/vortex-file/src/file.rs b/vortex-file/src/file.rs index c5fbb61cb68..3f0eb6e5407 100644 --- a/vortex-file/src/file.rs +++ b/vortex-file/src/file.rs @@ -331,8 +331,7 @@ impl VortexFile { /// Create a [`DataSource`](vortex_scan::DataSource) from this file whose scans run on the /// planner-driven executor. /// - /// A scan has one partition covering the requested rows, which runs it with - /// [`ScanDriver`](crate::v2::ScanDriver) from + /// Each partition of a scan, a range of the file's rows, runs it with [`ScanDriver`](crate::v2::ScanDriver) from /// [`Partition::execute`](vortex_scan::Partition::execute). Every scan of the source shares /// one [`ScanCache`]: the file's, with [caching](Self::with_caching), or else one of its own. /// A scan whose filter the file-level statistics prove false has no partitions. Stored footer diff --git a/vortex-jni/src/scan.rs b/vortex-jni/src/scan.rs index 9f7287391f4..c9aad23f977 100644 --- a/vortex-jni/src/scan.rs +++ b/vortex-jni/src/scan.rs @@ -137,6 +137,7 @@ fn build_scan_request( partition_selection: Selection::All, partition_range: None, split_concurrency, + target_partitions: None, }) } diff --git a/vortex-layout/src/scan/multi.rs b/vortex-layout/src/scan/multi.rs index 1f1ee275688..99dc169ea0d 100644 --- a/vortex-layout/src/scan/multi.rs +++ b/vortex-layout/src/scan/multi.rs @@ -357,6 +357,7 @@ impl BoundScanRequest { ordered, limit, split_concurrency, + target_partitions: _, } = request; Ok(Self { diff --git a/vortex-scan/src/lib.rs b/vortex-scan/src/lib.rs index 891c202fe11..390019e621d 100644 --- a/vortex-scan/src/lib.rs +++ b/vortex-scan/src/lib.rs @@ -87,13 +87,16 @@ pub type DataSourceRef = Arc; /// The DataSource may be used multiple times to create multiple scans, whereas each scan and each /// partition of a scan can only be consumed once. /// -/// Partitions have indices. Partition index is stable throughout DataSource's -/// lifetime. For every scan requested on the DataSource, the index will stay -/// the same. -/// However, this means you should create another instance of a DataSource if -/// your environment changes e.g. you have a glob and another file is added to -/// the filesystem this glob references. -/// See MultiFileDataSource in vortex-file/src/multi/mod.rs +/// Every partition has an [`index`](Partition::index) naming the unit of the source it reads, +/// which is what [`ScanRequest::partition_range`] and [`ScanRequest::partition_selection`] +/// select. A [`PlanDataSource`](source::PlanDataSource) is one unit with index 0, and a source +/// with several units, such as one over several files, gives each its own index. The index is +/// stable for the lifetime of the DataSource, so every scan of it gives a unit the same index. It +/// is not unique within a scan: a unit may be split into several partitions that share its index. +/// +/// Because indices are stable, create another DataSource when the data it covers changes, for +/// example when a file is added to the directory that a glob names. See `MultiFileDataSource` in +/// `vortex-file`. #[async_trait] pub trait DataSource: 'static + Send + Sync { /// Returns the dtype of the source. @@ -156,15 +159,22 @@ pub struct ScanRequest { pub projection: Expression, /// Filter expression, `None` implies no filter. pub filter: Option, - /// The per-partition row range to read. Row range will be applied - /// over every partition you scan. + /// The range of rows to read from each selected unit, in that unit's own row numbering. + /// + /// Units are what [`Partition::index`] names: for a source over several files, each file is a + /// unit and the range applies to each file's rows. A unit that a scan splits into several + /// partitions applies the range once across them, so each row is read by one partition. pub row_range: Option>, - /// The per-partition row selection to read. Row selection will be applied - /// over every partition you scan. + /// The rows to read from each selected unit, by row index in that unit's own row numbering. + /// + /// The indices are not relative to [`row_range`](Self::row_range): a scan reads the rows that + /// are both in the row range and selected. Like the row range, the selection applies to every + /// selected unit, and once across the partitions of a unit that a scan splits. pub selection: Selection, - /// Partition selection to scan, which allows readers to skip unwanted partitions. + /// The units to scan, by [`Partition::index`], which allows readers to skip unwanted units. pub partition_selection: Selection, - /// Partition range to scan, which allows readers to skip unwanted partitions. + /// The range of units to scan, by [`Partition::index`], which allows readers to skip unwanted + /// units. pub partition_range: Option>, /// Whether the scan should preserve row order. If false, the scan may produce rows in any /// order, for example to enable parallel execution across partitions. @@ -183,6 +193,14 @@ pub struct ScanRequest { /// others, such as one task of several on a machine, can set this to bound its memory. It does /// not bound I/O: segment reads for later splits may still be coalesced ahead of them. pub split_concurrency: Option, + /// The number of partitions the caller would like the scan to produce, as a hint. + /// + /// A source may return more or fewer partitions than this, for example because it has more + /// units than the hint or because a unit is too small to be worth splitting. `None` lets the + /// source choose: a [`PlanDataSource`](source::PlanDataSource) then uses the machine's + /// available parallelism. The hint only affects scans that a source is free to split, which + /// are unordered and have no limit. Defaults to `None`. + pub target_partitions: Option, } impl Default for ScanRequest { @@ -197,6 +215,7 @@ impl Default for ScanRequest { limit: None, partition_range: None, split_concurrency: None, + target_partitions: None, } } } @@ -224,9 +243,13 @@ pub trait Partition: 'static + Send { /// Downcast the partition to a concrete type. fn as_any(&self) -> &dyn Any; - /// Some unique identifier for partition. - /// If you have an instance of a DataSource, the indices of emitted - /// partitions will stay stable for every scan in this DataSource. + /// The index of the unit of the source this partition reads, which + /// [`ScanRequest::partition_range`] and [`ScanRequest::partition_selection`] select. + /// + /// For a [`PlanDataSource`](source::PlanDataSource) it is 0, since the source is one unit; a + /// source with several units gives each its own index. The index is stable for the lifetime of + /// the [`DataSource`], but not unique within a scan: a unit may be split into several + /// partitions that share its index. fn index(&self) -> usize; /// Returns an estimate of the row count for this partition. diff --git a/vortex-scan/src/source.rs b/vortex-scan/src/source.rs index f4225bc9b6a..188a8b6549d 100644 --- a/vortex-scan/src/source.rs +++ b/vortex-scan/src/source.rs @@ -29,6 +29,7 @@ pub use vortex_io::segments::SegmentId; pub use vortex_io::segments::SegmentSource; use vortex_io::session::RuntimeSessionExt; use vortex_session::VortexSession; +use vortex_utils::parallelism::get_available_parallelism; use crate::DataSource; use crate::DataSourceScan; @@ -70,12 +71,18 @@ pub struct ScanInput { /// lower its data to plans. Every scan of the source shares the input's [`ScanCache`], so scans /// that overlap in time plan the input and register its reader once. /// -/// A scan of the source has one partition covering the request's row range, clamped to the -/// input's rows when the row count is known. The partition has [`index`](Partition::index) 0, so a -/// request's `partition_range` and `partition_selection` either select it or leave the scan with -/// no partitions. +/// An unordered scan without a limit over a known row range is split into contiguous row ranges +/// of near-equal length, one partition each, so engines that parallelise by partition spread a +/// single input across their workers. The split count is the request's +/// [`target_partitions`](ScanRequest::target_partitions), or else the available parallelism, +/// capped at one partition per 65,536 rows, rounded up. Ordered and limited scans, and scans +/// whose row range is unknown, have one partition covering the request's row range. /// -/// The partition's [`execute`](Partition::execute) runs the planner-driven scan of its rows with a +/// The source is one selectable unit: every partition has [`index`](Partition::index) 0, so a +/// request's `partition_range` and `partition_selection` either select all of a scan's partitions +/// or none of them. +/// +/// A partition's [`execute`](Partition::execute) runs the planner-driven scan of its rows with a /// [`ScanDriver`] on the session's runtime and applies the request's limit. #[derive(Clone)] pub struct PlanDataSource { @@ -85,6 +92,12 @@ pub struct PlanDataSource { byte_size: Precision, } +/// The fewest rows a split partition covers. +/// +/// Each partition prepares, plans and drives its own scan, so splitting a small range costs more +/// in per-partition setup than it gains in parallelism. +const MIN_PARTITION_ROWS: u64 = 65_536; + impl PlanDataSource { /// A source scanning `input` with `session`. Without a cache, the input gets a fresh one that /// all of the source's scans share. @@ -119,6 +132,38 @@ impl PlanDataSource { pub fn session(&self) -> &VortexSession { &self.session } + + /// The row ranges an unordered, unlimited scan of `row_range` splits into, aiming for + /// `target_partitions`, or `None` when the scan keeps one partition. + fn split_range( + &self, + row_range: Option<&Range>, + ordered: bool, + limit: Option, + target_partitions: Option, + ) -> Option>> { + if ordered || limit.is_some() { + return None; + } + let rows = row_range + .cloned() + .or_else(|| self.row_count.as_exact().map(|count| 0..count))?; + let target_partitions = target_partitions.map_or_else( + || get_available_parallelism().unwrap_or(1), + NonZeroUsize::get, + ); + let len = rows.end - rows.start; + let count = len + .div_ceil(MIN_PARTITION_ROWS) + .min(target_partitions as u64) + .max(1); + Some( + (0..count) + .map(|i| rows.start + len * i / count..rows.start + len * (i + 1) / count) + .filter(|range| !range.is_empty()) + .collect(), + ) + } } #[async_trait] @@ -162,22 +207,31 @@ impl DataSource for PlanDataSource { partitions: Vec::new(), })); } - let partition = PlanPartition { - session: self.session.clone(), - input: self.input.clone(), - row_count: self.row_count, - projection, - filter, - row_range, - selection: request.selection, - ordered: request.ordered, - limit: request.limit, - split_concurrency: request.split_concurrency, + let ranges = match self.split_range( + row_range.as_ref(), + request.ordered, + request.limit, + request.target_partitions, + ) { + Some(ranges) => ranges.into_iter().map(Some).collect(), + None => vec![row_range], }; - Ok(Box::new(PlanScan { - dtype, - partitions: vec![partition], - })) + let partitions = ranges + .into_iter() + .map(|row_range| PlanPartition { + session: self.session.clone(), + input: self.input.clone(), + row_count: self.row_count, + projection: projection.clone(), + filter: filter.clone(), + row_range, + selection: request.selection.clone(), + ordered: request.ordered, + limit: request.limit, + split_concurrency: request.split_concurrency, + }) + .collect(); + Ok(Box::new(PlanScan { dtype, partitions })) } async fn field_statistics(&self, _field_path: &FieldPath) -> VortexResult { diff --git a/vortex-scan/src/source/tests.rs b/vortex-scan/src/source/tests.rs index ad8c09f6aa9..561bf38b97f 100644 --- a/vortex-scan/src/source/tests.rs +++ b/vortex-scan/src/source/tests.rs @@ -1,10 +1,12 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +use std::num::NonZeroUsize; use std::ops::Range; use std::sync::Arc; use futures::TryStreamExt; +use itertools::Itertools; use roaring::RoaringTreemap; use rstest::rstest; use vortex_array::ArrayRef; @@ -21,10 +23,13 @@ use vortex_array::expr::stats::Precision; use vortex_buffer::Buffer; use vortex_error::VortexResult; use vortex_error::vortex_bail; +use vortex_error::vortex_err; use vortex_io::request::SegmentReader; use vortex_io::session::RuntimeSessionExt; use vortex_session::VortexSession; +use vortex_utils::parallelism::get_available_parallelism; +use super::MIN_PARTITION_ROWS; use super::PlanDataSource; use super::ScanInput; use super::SegmentFuture; @@ -36,6 +41,7 @@ use crate::ScanRequest; use crate::execution::pipeline::synthetic::RowSource; use crate::plan::LazyPlanRef; use crate::selection::Selection; +use crate::strict_sorted_buffer::StrictSortedBuffer; struct NoSegments; @@ -45,6 +51,9 @@ impl SegmentSource for NoSegments { } } +/// Rows of the source that unordered, unlimited scans split into four partitions. +const SPLIT_ROWS: u64 = 4 * MIN_PARTITION_ROWS; + fn source() -> PlanDataSource { source_of(20) } @@ -61,6 +70,20 @@ fn source_of(row_count: u64) -> PlanDataSource { PlanDataSource::new(VortexSession::empty().with_tokio(), input).with_row_count(row_count) } +fn split_source() -> PlanDataSource { + source_of(SPLIT_ROWS) +} + +/// A request for an unordered, unlimited scan aiming for `target` partitions. +fn split_request(target: usize) -> VortexResult { + Ok(ScanRequest { + target_partitions: Some( + NonZeroUsize::new(target).ok_or_else(|| vortex_err!("target must be positive"))?, + ), + ..Default::default() + }) +} + async fn partitions(request: ScanRequest) -> VortexResult> { partitions_of(&source(), request).await } @@ -164,27 +187,148 @@ async fn sorted_values(partitions: Vec) -> VortexResult> Ok(values) } -/// Selecting the source's unit, by range or by selection, returns its one partition. +fn include(indices: impl IntoIterator) -> VortexResult { + Ok(Selection::IncludeByIndex(StrictSortedBuffer::try_new( + Buffer::from_iter(indices), + )?)) +} + +/// The request's hint sets the split count, below or above the default, capped so that no +/// partition covers fewer than `MIN_PARTITION_ROWS` rows. Without a hint the source splits by the +/// available parallelism. +#[rstest] +#[case::fewer(Some(2), 2)] +#[case::target(Some(4), 4)] +#[case::row_floor(Some(8), 4)] +#[case::single(Some(1), 1)] +#[case::default(None, get_available_parallelism().unwrap_or(1).min(4))] +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn unordered_scans_split_into_row_ranges( + #[case] target: Option, + #[case] expected: usize, +) -> VortexResult<()> { + let source = split_source(); + let request = match target { + Some(target) => split_request(target)?, + None => ScanRequest::default(), + }; + let scan = source.scan(request).await?; + assert_eq!(scan.partition_count(), Precision::exact(expected)); + let partitions: Vec = scan.partitions().try_collect().await?; + assert_eq!(partitions.len(), expected); + // The source is one unit, so every split shares its index. + assert!(partitions.iter().all(|p| p.index() == 0)); + assert_near_equal_splits(&partitions, SPLIT_ROWS)?; + let single = partitions_of( + &source, + ScanRequest { + ordered: true, + ..Default::default() + }, + ) + .await?; + assert_eq!( + sorted_values(partitions).await?, + sorted_values(single).await? + ); + Ok(()) +} + +/// Asserts that `partitions` cover `rows` rows in splits whose lengths differ by at most one. +fn assert_near_equal_splits(partitions: &[PartitionRef], rows: u64) -> VortexResult<()> { + let lengths = partitions + .iter() + .map(|p| { + p.row_count() + .as_exact() + .ok_or_else(|| vortex_err!("split partitions know their rows")) + }) + .collect::>>()?; + assert_eq!(lengths.iter().sum::(), rows); + let (min, max) = lengths + .iter() + .copied() + .minmax() + .into_option() + .ok_or_else(|| vortex_err!("a split scan has partitions"))?; + assert!( + max - min <= 1, + "split lengths {lengths:?} are not near-equal" + ); + Ok(()) +} + +/// A hint above the available parallelism splits a large enough source further than the default. +#[tokio::test] +async fn hints_above_the_default_split_further() -> VortexResult<()> { + let target = get_available_parallelism().unwrap_or(1) + 2; + let rows = target as u64 * MIN_PARTITION_ROWS; + let partitions = partitions_of(&source_of(rows), split_request(target)?).await?; + assert_eq!(partitions.len(), target); + assert!(partitions.iter().all(|p| p.index() == 0)); + assert_near_equal_splits(&partitions, rows) +} + +/// Selecting the source's unit, by range or by selection, returns every split of it. #[rstest] #[case::range(Some(0..1), Selection::All)] #[case::wide_range(Some(0..5), Selection::All)] #[case::selection(None, Selection::IncludeRoaring(RoaringTreemap::from_iter([0_u64, 3])))] #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn selecting_the_unit_returns_its_partition( +async fn selecting_the_unit_returns_every_split( #[case] partition_range: Option>, #[case] partition_selection: Selection, ) -> VortexResult<()> { - let partitions = partitions(ScanRequest { + let request = ScanRequest { partition_selection, partition_range, - ..Default::default() - }) - .await?; - assert_eq!(partitions.len(), 1); - assert_eq!(partitions[0].index(), 0); + ..split_request(4)? + }; + let partitions = partitions_of(&split_source(), request).await?; + assert_eq!(partitions.len(), 4); + assert!(partitions.iter().all(|p| p.index() == 0)); assert_eq!( sorted_values(partitions).await?, - (0..20).collect::>() + (0..SPLIT_ROWS).collect::>() ); Ok(()) } + +#[rstest] +#[case::ordered(ScanRequest { ordered: true, ..Default::default() })] +#[case::limited(ScanRequest { limit: Some(10), ..Default::default() })] +#[tokio::test] +async fn ordered_and_limited_scans_keep_one_partition( + #[case] request: ScanRequest, +) -> VortexResult<()> { + let request = ScanRequest { + target_partitions: NonZeroUsize::new(4), + ..request + }; + let partitions = partitions_of(&split_source(), request).await?; + assert_eq!(partitions.len(), 1); + assert_eq!(partitions[0].index(), 0); + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn split_partitions_apply_the_request() -> VortexResult<()> { + let row_range = 1_000..SPLIT_ROWS - 1_000; + let selected = (0..SPLIT_ROWS).step_by(997); + let partitions = partitions_of( + &split_source(), + ScanRequest { + filter: Some(gt(root(), lit(100_000_u64))), + row_range: Some(row_range.clone()), + selection: include(selected.clone())?, + ..split_request(4)? + }, + ) + .await?; + assert_eq!(partitions.len(), 4); + let expected: Vec = selected + .filter(|row| row_range.contains(row) && *row > 100_000) + .collect(); + assert_eq!(sorted_values(partitions).await?, expected); + Ok(()) +}