Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions vortex-scan/src/pool.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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<T>(
items: Vec<T>,
n: NonZeroUsize,
weight: impl Fn(&T) -> u64,
) -> Vec<Vec<T>> {
let total = items
.iter()
.map(|item| u128::from(weight(item)))
.sum::<u128>()
.max(1);
let n_groups = n.get() as u128;
let mut groups: Vec<Vec<T>> = 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
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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]]);
}
}
127 changes: 124 additions & 3 deletions vortex-scan/src/source/plan.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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.
///
Expand Down Expand Up @@ -575,15 +582,89 @@ impl DataSourceScan for PlanScan {
.map_or(Precision::Absent, Precision::inexact)
}

fn split(self: Box<Self>, _n: NonZeroUsize) -> VortexResult<Vec<DataSourceScanRef>> {
Ok(vec![self])
fn split(self: Box<Self>, n: NonZeroUsize) -> VortexResult<Vec<DataSourceScanRef>> {
// 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<u64> = 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::<u64>() / 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<Self>) -> VortexResult<ScanPoolRef> {
Ok(Arc::new(PartitionPool::new(self)))
}
}

/// 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<Unit> {
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<Unit>) -> Vec<Unit> {
let mut units: Vec<Unit> = 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<ScanState>,
Expand Down Expand Up @@ -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<u64>) -> 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<Unit>,
#[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::<Vec<_>>(),
units.iter().map(|u| u.rows.clone()).collect::<Vec<_>>()
);
}
}
Loading