diff --git a/vortex-scan/src/pool.rs b/vortex-scan/src/pool.rs index f5a39f1ab2e..949f016281d 100644 --- a/vortex-scan/src/pool.rs +++ b/vortex-scan/src/pool.rs @@ -4,6 +4,7 @@ //! Pools of work that host threads share by each polling a worker. use std::any::Any; +use std::num::NonZeroUsize; use std::sync::Arc; use std::sync::atomic::AtomicBool; use std::sync::atomic::AtomicU64; @@ -140,6 +141,37 @@ pub fn trim_to_limit( .boxed() } +/// Groups consecutive `items` into at most `n` contiguous groups of about equal total `weight`. +/// +/// Never cuts an item: each lands whole in one group. Every group is non-empty. +pub fn group_contiguous( + items: Vec, + n: NonZeroUsize, + weight: impl Fn(&T) -> u64, +) -> Vec> { + let total = items + .iter() + .map(|item| u128::from(weight(item))) + .sum::() + .max(1); + let n_groups = n.get() as u128; + let mut groups: Vec> = Vec::new(); + let mut current_group = None; + let mut before = 0u128; + for item in items { + let group = (before * n_groups / total).min(n_groups - 1); + before += u128::from(weight(&item)); + if current_group != Some(group) { + current_group = Some(group); + groups.push(Vec::new()); + } + if let Some(last) = groups.last_mut() { + last.push(item); + } + } + groups +} + /// A pool whose workers take partitions one at a time from a scan's shared partition stream. /// /// A source without a pool of its own can open into this one, as long as it implements @@ -281,6 +313,7 @@ mod tests { use super::RowLimit; use super::ScanPool; use super::ScanPoolRef; + use super::group_contiguous; use super::trim_to_limit; use crate::DataSourceScan; use crate::DataSourceScanRef; @@ -536,4 +569,14 @@ mod tests { ); Ok(()) } + + #[test] + fn group_contiguous_balances_weights() { + let groups = group_contiguous( + vec![4u64, 4, 4, 4, 1, 1], + NonZeroUsize::new(3).unwrap_or(NonZeroUsize::MIN), + |w| *w, + ); + assert_eq!(groups, vec![vec![4, 4], vec![4], vec![4, 1, 1]]); + } } diff --git a/vortex-scan/src/source/plan.rs b/vortex-scan/src/source/plan.rs index 8488a524965..ebf457b5a49 100644 --- a/vortex-scan/src/source/plan.rs +++ b/vortex-scan/src/source/plan.rs @@ -44,10 +44,12 @@ use crate::Partition; use crate::PartitionRef; use crate::PartitionStream; use crate::ScanRequest; +use crate::execution::ROW_BLOCK_SIZE; use crate::execution::driver::ScanDriver; use crate::pool::PartitionPool; use crate::pool::RowLimit; use crate::pool::ScanPoolRef; +use crate::pool::group_contiguous; use crate::pool::trim_to_limit; use crate::prepare::ScanBuilder; use crate::selection::Selection; @@ -160,7 +162,12 @@ pub enum PlanSourceChild { /// # Splitting and opening /// /// The work of a scan is plan work: chunks of a prepared plan, and the expansion of deferred -/// children. [`split`](DataSourceScan::split) does not cut a scan yet: it returns the scan whole. +/// children. +/// +/// [`split`](DataSourceScan::split) cuts a scan into contiguous pieces of about equal row counts, +/// each a list of children and row ranges of them, on the 8,192-row block grid that every chunk +/// boundary of the executor lies on. It reads nothing; a deferred child is one indivisible unit. +/// /// [`open`](DataSourceScan::open) reads the scan's partitions through a [`PartitionPool`], each /// worker taking one partition at a time. /// @@ -575,8 +582,36 @@ impl DataSourceScan for PlanScan { .map_or(Precision::Absent, Precision::inexact) } - fn split(self: Box, _n: NonZeroUsize) -> VortexResult> { - Ok(vec![self]) + fn split(self: Box, n: NonZeroUsize) -> VortexResult> { + // A limit holds across the whole scan, which pieces read independently cannot share. + if self.state.limit.is_some() || n.get() == 1 { + return Ok(vec![self]); + } + let atoms = split_atoms(&self.units, n); + if atoms.len() <= 1 { + return Ok(vec![self]); + } + let known: Vec = atoms + .iter() + .filter_map(|unit| unit.rows.as_ref().map(|rows| rows.end - rows.start)) + .collect(); + // A deferred child weighs as much as the average ready unit. + let unknown = (known.iter().sum::() / known.len().max(1) as u64).max(1); + let weight = |unit: &Unit| { + unit.rows + .as_ref() + .map_or(unknown, |rows| rows.end - rows.start) + }; + let state = self.state; + Ok(group_contiguous(atoms, n, weight) + .into_iter() + .map(|atoms| { + Box::new(PlanScan { + state: Arc::clone(&state), + units: join_atoms(atoms), + }) as DataSourceScanRef + }) + .collect()) } fn open(self: Box) -> VortexResult { @@ -584,6 +619,52 @@ impl DataSourceScan for PlanScan { } } +/// The pieces a split may not cut further: the scan's known rows on a grid of whole 8,192-row +/// blocks, coarse enough that each of `n` pieces gets about 64 of them, and each unit whose rows +/// are not known yet whole. +fn split_atoms(units: &[Unit], n: NonZeroUsize) -> Vec { + let block = ROW_BLOCK_SIZE as u64; + let known: u64 = units + .iter() + .filter_map(|unit| unit.rows.as_ref().map(|rows| rows.end - rows.start)) + .sum(); + let per_atom = known.div_ceil(n.get() as u64 * 64).div_ceil(block).max(1) * block; + let mut atoms = Vec::new(); + for unit in units { + let Some(rows) = &unit.rows else { + atoms.push(unit.clone()); + continue; + }; + let mut start = rows.start; + while start < rows.end { + let end = ((start / per_atom + 1) * per_atom).min(rows.end); + atoms.push(Unit { + child: unit.child, + rows: Some(start..end), + }); + start = end; + } + } + atoms +} + +/// Joins adjacent atoms of the same child back into one unit. +fn join_atoms(atoms: Vec) -> Vec { + let mut units: Vec = Vec::new(); + for atom in atoms { + if let Some(last) = units.last_mut() + && last.child == atom.child + && let (Some(rows), Some(next)) = (&mut last.rows, &atom.rows) + && rows.end == next.start + { + rows.end = next.end; + continue; + } + units.push(atom); + } + units +} + /// One child's rows of a scan of a [`PlanDataSource`]. struct PlanPartition { state: Arc, @@ -650,3 +731,43 @@ impl Partition for PlanPartition { ))) } } + +#[cfg(test)] +mod tests { + use std::num::NonZeroUsize; + + use rstest::rstest; + + use super::Unit; + use super::join_atoms; + use super::split_atoms; + + fn unit(child: usize, rows: std::ops::Range) -> Unit { + Unit { + child, + rows: Some(rows), + } + } + + #[rstest] + #[case::one_block(vec![unit(0, 0..100)], 4, 1)] + #[case::grid_aligned(vec![unit(0, 10..40_000)], 1, 5)] + fn atoms_lie_on_the_block_grid( + #[case] units: Vec, + #[case] n: usize, + #[case] expected: usize, + ) { + let n = NonZeroUsize::new(n).unwrap_or(NonZeroUsize::MIN); + let atoms = split_atoms(&units, n); + assert_eq!(atoms.len(), expected); + for atom in &atoms[1..] { + let start = atom.rows.as_ref().map_or(0, |rows| rows.start); + assert_eq!(start % 8192, 0); + } + let joined = join_atoms(atoms); + assert_eq!( + joined.iter().map(|u| u.rows.clone()).collect::>(), + units.iter().map(|u| u.rows.clone()).collect::>() + ); + } +}