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
13 changes: 13 additions & 0 deletions vortex-scan/src/execution/driver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
//! produced the batch, beside the scan's other chunks.

use std::future;
use std::num::NonZeroUsize;
use std::sync::Arc;
use std::task::Poll;

Expand Down Expand Up @@ -42,6 +43,7 @@ use crate::prepare::ScanBuilder;
pub struct ScanDriver {
handle: Handle,
concurrency: usize,
max_in_flight: Option<NonZeroUsize>,
ordered: bool,
}

Expand All @@ -54,10 +56,18 @@ impl ScanDriver {
Self {
handle,
concurrency,
max_in_flight: None,
ordered,
}
}

/// Caps the chunks the scan decodes at once, in all, below the per-worker limit. `None`
/// keeps the per-worker limit only.
pub fn with_max_in_flight(mut self, max_in_flight: Option<NonZeroUsize>) -> Self {
self.max_in_flight = max_in_flight;
self
}

/// Prepares `builder` where compute runs, composes its planners, and streams their batches.
/// Preparation errors are the stream's first item.
pub fn run(
Expand Down Expand Up @@ -101,6 +111,9 @@ impl ScanDriver {
let scan = Arc::new(scan);
let map_fn: MapFn<A> = Arc::new(map_fn);
let in_flight = self.concurrency * get_available_parallelism().unwrap_or(1);
let in_flight = self
.max_in_flight
.map_or(in_flight, |max| in_flight.min(max.get()));
let inline = in_flight <= 1;
let scope = WorkScope {
file_ordinal: 0,
Expand Down
152 changes: 152 additions & 0 deletions vortex-scan/src/pool.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,24 @@
use std::any::Any;
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::AtomicU64;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;

use async_lock::Mutex;
use futures::StreamExt;
use futures::future;
use futures::stream;
use futures::stream::BoxStream;
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::VortexExpect;
use vortex_error::VortexResult;
use vortex_mask::Mask;

use crate::DataSourceScanRef;
use crate::Partition;
Expand Down Expand Up @@ -58,6 +64,82 @@ pub trait ScanPool: 'static + Send + Sync {
}
}

/// A cloneable row budget shared by all work that can contribute rows to one scan.
///
/// Filterless scans can reserve each unit's selected rows before decoding it, so rows past the
/// limit are never decoded. Filtered scans cannot know a unit's row count up front, so they take
/// rows from the budget as arrays are emitted and discard the excess. Either way, the order in
/// which rows are taken decides which rows are returned: an ordered scan takes them in row order,
/// an unordered one in completion order.
#[derive(Clone, Debug)]
pub struct RowLimit(Arc<AtomicU64>);

impl RowLimit {
/// A budget of `limit` rows.
pub fn new(limit: u64) -> Self {
Self(Arc::new(AtomicU64::new(limit)))
}

/// Reserves the rows selected by `mask` and keeps only the earliest granted rows of it.
pub fn limit(&self, mask: Mask) -> Mask {
let granted = self.take(mask.true_count());
mask.limit(granted)
}

/// Reserves up to `rows` rows, returning how many the remaining budget granted.
pub fn take(&self, rows: usize) -> usize {
let requested = u64::try_from(rows).unwrap_or(u64::MAX);
usize::try_from(self.reserve(requested)).unwrap_or(usize::MAX)
}

/// Whether the budget is spent.
pub fn is_exhausted(&self) -> bool {
self.0.load(Ordering::Relaxed) == 0
}

fn reserve(&self, requested: u64) -> u64 {
let remaining = self
.0
.try_update(Ordering::Relaxed, Ordering::Relaxed, |remaining| {
Some(remaining.saturating_sub(requested))
})
.ok()
.vortex_expect("row reservation always updates the budget");
remaining.min(requested)
}
}

/// Ends `arrays` once `limit` is spent, taking each array's rows from it as the array is yielded
/// and slicing the array that spends it. Also ends after the first error.
pub fn trim_to_limit(
arrays: BoxStream<'static, VortexResult<ArrayRef>>,
limit: RowLimit,
) -> BoxStream<'static, VortexResult<ArrayRef>> {
stream::unfold(Some(arrays), move |arrays| {
let limit = limit.clone();
async move {
let mut arrays = arrays?;
if limit.is_exhausted() {
return None;
}
let array = match arrays.next().await? {
Ok(array) => array,
Err(err) => return Some((Err(err), None)),
};
let granted = limit.take(array.len());
if granted == array.len() {
return Some((Ok(array), Some(arrays)));
}
if granted == 0 {
return None;
}
Some((array.slice(0..granted), None))
}
})
.filter(|array| future::ready(array.as_ref().map_or(true, |array| !array.is_empty())))
.boxed()
}

/// 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 @@ -171,6 +253,10 @@ mod tests {
use std::collections::VecDeque;
use std::num::NonZeroUsize;
use std::sync::Arc;
use std::sync::Barrier;
use std::sync::atomic::AtomicU64;
use std::sync::atomic::Ordering;
use std::thread;

use futures::StreamExt;
use futures::TryStreamExt;
Expand All @@ -189,10 +275,13 @@ mod tests {
use vortex_array::stream::SendableArrayStream;
use vortex_buffer::Buffer;
use vortex_error::VortexResult;
use vortex_mask::Mask;

use super::PartitionPool;
use super::RowLimit;
use super::ScanPool;
use super::ScanPoolRef;
use super::trim_to_limit;
use crate::DataSourceScan;
use crate::DataSourceScanRef;
use crate::Partition;
Expand Down Expand Up @@ -384,4 +473,67 @@ mod tests {
assert_eq!(rows.into_iter().sum::<usize>(), 14);
Ok(())
}

#[test]
fn reserve_grants_up_to_the_remaining_budget() {
let limit = RowLimit::new(5);
assert_eq!(limit.reserve(3), 3);
assert!(!limit.is_exhausted());
assert_eq!(limit.reserve(10), 2);
assert!(limit.is_exhausted());
assert_eq!(limit.reserve(1), 0);
}

#[test]
fn limit_keeps_the_earliest_granted_rows() {
let limit = RowLimit::new(2);
let mask = Mask::from_iter([true, false, true, true, false, true]);
let limited = limit.limit(mask);
assert_eq!(limited.true_count(), 2);
assert!(limited.value(0));
assert!(limited.value(2));
assert!(!limited.value(3));
assert!(!limited.value(5));
assert!(limit.is_exhausted());
}

#[test]
fn concurrent_reservations_never_exceed_the_budget() {
const THREADS: usize = 8;
const PER_THREAD: u64 = 10_000;
const LIMIT: u64 = 25_000;

let limit = RowLimit::new(LIMIT);
let granted_total = Arc::new(AtomicU64::new(0));
let barrier = Arc::new(Barrier::new(THREADS));
thread::scope(|scope| {
for _ in 0..THREADS {
let limit = limit.clone();
let granted_total = Arc::clone(&granted_total);
let barrier = Arc::clone(&barrier);
scope.spawn(move || {
barrier.wait();
let mut local = 0;
for _ in 0..PER_THREAD {
local += limit.reserve(1);
}
granted_total.fetch_add(local, Ordering::Relaxed);
});
}
});
assert_eq!(granted_total.load(Ordering::Relaxed), LIMIT);
assert!(limit.is_exhausted());
}

#[test]
fn trim_to_limit_slices_the_array_that_spends_it() -> VortexResult<()> {
let arrays = stream::iter((0..4).map(|_| Ok(Buffer::from_iter(0..3i32).into_array())));
let trimmed: Vec<_> =
block_on(trim_to_limit(arrays.boxed(), RowLimit::new(7)).try_collect())?;
assert_eq!(
trimmed.iter().map(|a| a.len()).collect::<Vec<_>>(),
vec![3, 3, 1]
);
Ok(())
}
}
14 changes: 13 additions & 1 deletion vortex-scan/src/source.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright the Vortex contributors

//! Source inputs and byte access for scans.
//! Source inputs and byte access for scans, and the [`DataSource`](crate::DataSource) that scans
//! them.

use std::sync::Arc;

Expand Down Expand Up @@ -32,3 +33,14 @@ pub struct ScanInput {
/// State shared by repeated scans of this input.
pub cache: Option<ScanCache>,
}

mod plan;

pub use plan::DeferredPlanChild;
pub use plan::FilePruner;
pub use plan::PlanChild;
pub use plan::PlanDataSource;
pub use plan::PlanSourceChild;

#[cfg(test)]
mod tests;
Loading
Loading