From 334df7d2c4774edf4048bc61660ff394bce4bfed Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Thu, 19 Nov 2026 19:39:14 -0500 Subject: [PATCH 1/8] Run layout and plan scans through one work pool Both scan engines had their own channel pool with the same shape. Move the channel, expansion slots, ordered first-worker handoff, in-flight bound, row limit, progress and exhaustion into one pool in vortex_scan::pool, which V1 layout splits and V2 plan units feed as work units. Expanding a unit yields more units in its place, so opening a deferred file, expanding a manifest entry and pruning before cutting parts are all expansions. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-layout/src/scan/layout.rs | 22 +- vortex-layout/src/scan/limit.rs | 123 +--- vortex-layout/src/scan/pool.rs | 490 +++------------ vortex-scan/src/{pool.rs => pool/mod.rs} | 11 + vortex-scan/src/pool/work.rs | 740 +++++++++++++++++++++++ vortex-scan/src/source/plan.rs | 37 +- vortex-scan/src/source/plan_pool.rs | 510 +++------------- 7 files changed, 950 insertions(+), 983 deletions(-) rename vortex-scan/src/{pool.rs => pool/mod.rs} (98%) create mode 100644 vortex-scan/src/pool/work.rs diff --git a/vortex-layout/src/scan/layout.rs b/vortex-layout/src/scan/layout.rs index 38f801fd9a9..822e7909db3 100644 --- a/vortex-layout/src/scan/layout.rs +++ b/vortex-layout/src/scan/layout.rs @@ -444,27 +444,7 @@ impl DataSourceScan for LayoutSplitScan { /// /// 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 + vortex_scan::pool::group_contiguous(ranges, n, |range| range.end - range.start) } impl Stream for LayoutReaderScan { diff --git a/vortex-layout/src/scan/limit.rs b/vortex-layout/src/scan/limit.rs index e7791e5961f..2fa6a25e638 100644 --- a/vortex-layout/src/scan/limit.rs +++ b/vortex-layout/src/scan/limit.rs @@ -1,22 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors -use std::sync::Arc; -use std::sync::atomic::AtomicU64; -use std::sync::atomic::Ordering; - -use vortex_error::VortexExpect; -use vortex_mask::Mask; - -/// A cloneable row budget shared by all work that can contribute rows to one scan. -/// -/// Filterless scans reserve each split's selected rows before constructing its projection, so -/// rows past the limit are never decoded. Filtered scans cannot know a split'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 split order, an unordered one in completion order. -#[derive(Clone)] -pub(crate) struct RowLimit(Arc); +pub(crate) use vortex_scan::pool::RowLimit; /// The row limit of a scan. #[derive(Clone)] @@ -36,109 +21,3 @@ impl ScanLimit { } } } - -impl RowLimit { - pub(crate) fn new(limit: u64) -> Self { - Self(Arc::new(AtomicU64::new(limit))) - } - - /// Reserve rows selected by `mask` and retain only the earliest granted rows in that mask. - pub(crate) fn limit(&self, mask: Mask) -> Mask { - let granted = self.take(mask.true_count()); - mask.limit(granted) - } - - /// Reserve up to `rows` rows, returning how many the remaining budget granted. - pub(crate) 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) - } - - pub(crate) 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) - } -} - -#[cfg(test)] -mod tests { - use std::sync::Arc; - use std::sync::Barrier; - use std::sync::atomic::AtomicU64; - use std::sync::atomic::Ordering; - use std::thread; - - use vortex_mask::Mask; - - use super::RowLimit; - - #[test] - fn reserve_grants_up_to_the_remaining_budget() { - let limit = RowLimit::new(5); - assert_eq!(limit.reserve(3), 3); - assert!(!limit.is_exhausted()); - // Only two rows remain, so a larger request saturates at what is left. - assert_eq!(limit.reserve(10), 2); - assert!(limit.is_exhausted()); - // Once exhausted, further requests grant nothing. - assert_eq!(limit.reserve(1), 0); - } - - #[test] - fn limit_keeps_the_earliest_granted_rows() { - let limit = RowLimit::new(2); - // Rows 0, 2, 3, 5 are selected; only the first two survive the budget of 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 || { - // Start all threads together to maximize contention on the atomic. - barrier.wait(); - let mut local = 0; - for _ in 0..PER_THREAD { - local += limit.reserve(1); - } - granted_total.fetch_add(local, Ordering::Relaxed); - }); - } - }); - - // Total requested (THREADS * PER_THREAD = 80_000) exceeds the budget, so exactly the - // budget is granted across all threads — no double-grant, over-grant, or lost reservation. - assert_eq!(granted_total.load(Ordering::Relaxed), LIMIT); - assert!(limit.is_exhausted()); - } -} diff --git a/vortex-layout/src/scan/pool.rs b/vortex-layout/src/scan/pool.rs index 973623e8eba..c0ab039b864 100644 --- a/vortex-layout/src/scan/pool.rs +++ b/vortex-layout/src/scan/pool.rs @@ -1,12 +1,14 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors -//! The work that the workers of an opened layout scan share. +//! The work of an opened layout scan, for the scan pool. //! -//! A pool's units are the splits of one or more files, and the files not yet opened. A worker -//! takes units and keeps several splits in flight, each spawned onto the session's runtime; it -//! never starts threads of its own. Opening a deferred file is a unit like any other, and at most -//! `open_concurrency` opens are queued or running at once. +//! A pool's units are the splits of one or more files, and the files not yet opened. Opening a +//! deferred file is an expansion that yields the file's splits, and at most `open_concurrency` +//! opens are queued or running at once. Each split is spawned onto the session's runtime when a +//! worker takes it; the [pool](vortex_scan::pool::open_work_pool) shares the units among the +//! workers and never starts threads of its own. Each file has an equal share of the pool's +//! progress, divided among its splits by their rows. //! //! Splits run as [`RepeatedScan::execute_stream`] runs them: //! @@ -16,38 +18,23 @@ //! - Every other scan builds all of a file's split tasks together, when a worker first takes one //! of them, so the file's reads are registered at once and can coalesce. A limit is reserved //! then, in split order. -//! -//! The pools differ in how workers share units: -//! -//! - An unordered pool hands units out through a channel. The worker that opens a deferred file -//! sends the file's splits back into the channel, where any worker can take them, followed by -//! the next deferred file. The channel closes once every open has finished, which ends the -//! workers. -//! - An ordered pool gives all of its units, in row order, to its first worker; later workers -//! get nothing. Parallel ordered reads cut the scan with `split` first. use std::any::Any; -use std::collections::VecDeque; use std::num::NonZeroUsize; use std::ops::Range; use std::sync::Arc; -use async_channel::Receiver; -use async_channel::Sender; use async_lock::OnceCell; use futures::FutureExt; use futures::StreamExt; use futures::future; use futures::future::BoxFuture; use futures::stream; -use futures::stream::BoxStream; use parking_lot::Mutex; use tracing::Instrument; 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::VortexResult; use vortex_io::session::RuntimeSessionExt; @@ -55,22 +42,24 @@ use vortex_scan::DataSourceScanRef; use vortex_scan::Partition; use vortex_scan::PartitionRef; use vortex_scan::PartitionStream; -use vortex_scan::pool::ScanPool; +use vortex_scan::pool::Expansion; +use vortex_scan::pool::MapOutput; +use vortex_scan::pool::PoolLimit; use vortex_scan::pool::ScanPoolRef; +use vortex_scan::pool::WorkPoolOptions; +use vortex_scan::pool::WorkUnit; +use vortex_scan::pool::open_work_pool; use vortex_scan::row_mask::RowMask; use vortex_session::VortexSession; use crate::LayoutReaderRef; use crate::scan::limit::RowLimit; use crate::scan::multi::LayoutReaderFactory; -use crate::scan::repeated_scan::DEFAULT_SPLITS_PER_THREAD; use crate::scan::repeated_scan::MapFn; use crate::scan::repeated_scan::RepeatedScan; -use crate::scan::repeated_scan::SplitConcurrency; use crate::scan::repeated_scan::can_prune_file; use crate::scan::repeated_scan::spawn_lazy_split; use crate::scan::repeated_scan::spawn_map_trimmed; -use crate::scan::repeated_scan::stop_on_error; use crate::scan::tasks::SplitFuture; use crate::scan::tasks::TaskContext; use crate::scan::tasks::split_exec; @@ -194,117 +183,62 @@ pub(crate) fn open_pool( Some(limit) if options.has_filter => PoolLimit::Trim(RowLimit::new(limit)), Some(limit) => PoolLimit::Reserve(RowLimit::new(limit)), }; - // A worker takes the place of a partition that one host thread drains, so it keeps as many - // splits in flight as a partition's stream does by default: four per core, at most the - // request's `split_concurrency`. A host with a worker per core therefore has the in-flight - // total of the partitions path, where each of DuckDB's threads drained one file's partition - // and each of DataFusion's `target_partitions` streams drained one partition, each with up to - // `4 × cores` splits in flight. - let splits_in_flight = SplitConcurrency { - per_worker: DEFAULT_SPLITS_PER_THREAD, - max: options.split_concurrency, - } - .splits_in_flight() - .max(1); - let open_concurrency = options.open_concurrency.max(1); - let shared = Arc::new(Shared { - limit, + let files_work = Arc::new(Files { + limit: limit.clone(), prepare, - session: options.session, - file_share: 1.0 / files.len().max(1) as f64, - progress: Mutex::new(0.0), - deferred: Mutex::new(VecDeque::new()), + session: options.session.clone(), }); - if options.ordered { - return Arc::new(OrderedPool { - dtype: options.dtype, - shared, - files: Mutex::new(Some(files)), - splits_in_flight, - open_concurrency, - }); - } - - let (sender, receiver) = async_channel::unbounded(); - let mut opens = 0; + let file_share = 1.0 / files.len().max(1) as f64; + let mut units = Vec::new(); for file in files { match file { - PoolFile::Opened(work) => { - for split in shared.file_splits(work) { - send(&sender, Work::Split(split)); - } - } - PoolFile::Deferred(factory) if opens < open_concurrency => { - opens += 1; - let slot = OpenSlot { - shared: Arc::clone(&shared), - sender: sender.clone(), - }; - send(&sender, Work::Open(factory, slot)); + PoolFile::Opened(work) => units.extend(files_work.units(work, file_share)), + PoolFile::Deferred(factory) => { + let files_work = Arc::clone(&files_work); + units.push(WorkUnit::expand(file_share, move || { + files_work.open(factory, file_share) + })); } - PoolFile::Deferred(factory) => shared.deferred.lock().push_back(factory), } } - Arc::new(UnorderedPool { - dtype: options.dtype, - shared, - receiver, - splits_in_flight, - }) -} - -/// How a pool's row limit is applied. -enum PoolLimit { - Unlimited, - /// A split's selected rows are its output rows, so a file reserves its splits' rows from the - /// budget in split order when it builds their tasks, and rows past the limit are never - /// decoded. Files build in row order in an ordered pool, so it returns exactly the first rows. - Reserve(RowLimit), - /// A split's output rows are unknown until its filter has run, so workers take rows from the - /// budget as they yield them and discard the excess. - Trim(RowLimit), -} - -impl PoolLimit { - /// Whether the budget is spent, so no file that has not started has rows to return. - fn is_spent(&self) -> bool { - match self { - PoolLimit::Unlimited => false, - PoolLimit::Reserve(limit) | PoolLimit::Trim(limit) => limit.is_exhausted(), - } - } - - /// Whether a trimmed budget is spent, so workers end without returning any more rows. - fn is_trimmed_out(&self) -> bool { - matches!(self, PoolLimit::Trim(limit) if limit.is_exhausted()) - } + // A limit's trimmed arrays are optimized again, on a CPU task, as `execute_stream` does. + let handle = options.session.handle(); + let session = options.session; + let identity: MapFn = Arc::new(Ok); + let map_trimmed: MapOutput = Arc::new(move |array| { + spawn_map_trimmed(&handle, session.clone(), Arc::clone(&identity), Ok(array)).boxed() + }); + open_work_pool( + WorkPoolOptions { + dtype: options.dtype, + ordered: options.ordered, + limit, + // A worker takes the place of a partition that one host thread drains, so it keeps as + // many splits in flight as a partition's stream does by default: four per core, at most + // the request's `split_concurrency`. + split_concurrency: options.split_concurrency, + expand_concurrency: NonZeroUsize::new(options.open_concurrency) + .unwrap_or(NonZeroUsize::MIN), + map_trimmed: Some(map_trimmed), + }, + units, + ) } -/// A split's output: `None` when it has no rows to return. -type SplitOutput = BoxFuture<'static, VortexResult>>; - -/// A split of a file by its index, with the progress that taking it adds. -type FileSplit = (Arc, usize, f64); - -/// What every worker of a pool shares. -struct Shared { +/// What the units of a pool's files share. +struct Files { limit: PoolLimit, prepare: Option, /// The session whose runtime runs the pool's splits and opens. session: VortexSession, - /// The progress that one file adds. - file_share: f64, - progress: Mutex, - /// An unordered pool's deferred files that are not yet queued for opening, in file order. - deferred: Mutex>>, } -impl Shared { - /// The splits of an opened file, in row order. - fn file_splits(&self, work: FileWork) -> Vec { +impl Files { + /// The units of an opened file's splits, in row order, dividing the file's `share` among them + /// by their rows. + fn units(self: &Arc, work: FileWork, share: f64) -> Vec { let Some(file) = work.file else { - *self.progress.lock() += self.file_share; - return Vec::new(); + return vec![WorkUnit::skipped(share)]; }; let rows: u64 = file .ranges @@ -312,58 +246,47 @@ impl Shared { .map(|range| range.end - range.start) .sum(); if rows == 0 { - *self.progress.lock() += self.file_share; - return Vec::new(); + return vec![WorkUnit::skipped(share)]; } - let per_row = self.file_share / rows as f64; + let per_row = share / rows as f64; (0..file.ranges.len()) .map(|index| { let range = &file.ranges[index]; - let progress = per_row * (range.end - range.start) as f64; - (Arc::clone(&file), index, progress) + let files = Arc::clone(self); + let file = Arc::clone(&file); + WorkUnit::run(per_row * (range.end - range.start) as f64, move || { + files + .admit(file, index) + .map(|array| array.map(|array| array.into_iter().collect())) + .boxed() + }) }) .collect() } - /// Opens a deferred file into its work on the session's runtime. A file that starts after - /// the limit is spent is not opened. - fn open_file( - self: &Arc, - factory: Arc, - ) -> BoxFuture<'static, VortexResult> { - if self.limit.is_spent() { - return future::ready(Ok(FileWork::empty())).boxed(); - } - let shared = Arc::clone(self); - self.session - .handle() - .spawn(async move { - let reader = factory - .open() - .instrument(tracing::info_span!("LayoutReaderFactory::open")) - .await?; - match (reader, &shared.prepare) { - (Some(reader), Some(prepare)) => prepare(reader), - _ => Ok(FileWork::empty()), - } - }) - .boxed() - } - - /// The next deferred file of an unordered pool to open, if any is left and the limit is not - /// spent. Once it is spent, the files left count as read. - fn next_deferred(&self) -> Option> { - let mut deferred = self.deferred.lock(); - if self.limit.is_spent() && !deferred.is_empty() { - *self.progress.lock() += self.file_share * deferred.len() as f64; - deferred.clear(); - } - deferred.pop_front() + /// Opens a deferred file on the session's runtime into the units of its splits. + fn open(self: &Arc, factory: Arc, share: f64) -> Expansion { + let files = Arc::clone(self); + let opened = self.session.handle().spawn(async move { + let reader = factory + .open() + .instrument(tracing::info_span!("LayoutReaderFactory::open")) + .await?; + match (reader, &files.prepare) { + (Some(reader), Some(prepare)) => prepare(reader), + _ => Ok(FileWork::empty()), + } + }); + let files = Arc::clone(self); + async move { Ok(files.units(opened.await?, share)) }.boxed() } - /// Takes a split and runs it on the session's runtime. - fn admit(self: &Arc, (file, index, progress): FileSplit) -> SplitOutput { - *self.progress.lock() += progress; + /// Runs a split on the session's runtime. + fn admit( + self: &Arc, + file: Arc, + index: usize, + ) -> BoxFuture<'static, VortexResult>> { let handle = self.session.handle(); if let PoolLimit::Trim(_) = &self.limit { let Some(mask) = file.scan.split_mask(&file.ranges[index]) else { @@ -372,9 +295,9 @@ impl Shared { return spawn_lazy_split(&handle, move || split_exec(&file.ctx, mask).map(Some)) .boxed(); } - let shared = Arc::clone(self); + let files = Arc::clone(self); async move { - let task = file.tasks(&shared.limit).await?[index].lock().take(); + let task = file.tasks(&files.limit).await?[index].lock().take(); match task { Some(task) => handle.spawn(task).await, None => Ok(None), @@ -382,247 +305,6 @@ impl Shared { } .boxed() } - - fn progress(&self) -> f64 { - if self.limit.is_trimmed_out() { - return 1.0; - } - self.progress.lock().clamp(0.0, 1.0) - } - - /// A worker's output: skips splits with no rows, trims to a trimmed limit, and ends after the - /// first error or once a trimmed limit is spent. A trimmed array is optimized again, on a CPU - /// task, `splits_in_flight` at a time. - fn output( - self: Arc, - outputs: BoxStream<'static, VortexResult>>, - ordered: bool, - splits_in_flight: usize, - ) -> BoxStream<'static, VortexResult> { - let trimmed = matches!(self.limit, PoolLimit::Trim(_)); - let handle = self.session.handle(); - let session = self.session.clone(); - let arrays = limit_output(outputs, self); - if !trimmed { - return arrays; - } - let identity: MapFn = Arc::new(Ok); - let mapped = arrays.map(move |array| { - spawn_map_trimmed(&handle, session.clone(), Arc::clone(&identity), array) - }); - let mapped = if ordered { - mapped.buffered(splits_in_flight).boxed() - } else { - mapped.buffer_unordered(splits_in_flight).boxed() - }; - stop_on_error(mapped) - } -} - -/// Skips splits with no rows, trims to a trimmed limit, and ends after the first error or once -/// a trimmed limit is spent. -fn limit_output( - outputs: BoxStream<'static, VortexResult>>, - shared: Arc, -) -> BoxStream<'static, VortexResult> { - stream::unfold(Some(outputs), move |outputs| { - let shared = Arc::clone(&shared); - async move { - let mut outputs = outputs?; - loop { - if shared.limit.is_trimmed_out() { - return None; - } - let array = match outputs.next().await? { - Ok(Some(array)) => array, - Ok(None) => continue, - Err(err) => return Some((Err(err), None)), - }; - let PoolLimit::Trim(limit) = &shared.limit else { - return Some((Ok(array), Some(outputs))); - }; - let granted = limit.take(array.len()); - if granted == 0 { - return None; - } - if granted == array.len() { - return Some((Ok(array), Some(outputs))); - } - return Some((array.slice(0..granted), None)); - } - } - }) - .boxed() -} - -/// A unit of an unordered pool. -enum Work { - Split(FileSplit), - /// A deferred file, and the open slot it holds until its splits are in the channel. - Open(Arc, OpenSlot), -} - -/// One of an unordered pool's `open_concurrency` open slots. Its sender keeps the channel open -/// while the file that holds it is queued or opening. -struct OpenSlot { - shared: Arc, - sender: Sender, -} - -impl Drop for OpenSlot { - /// Passes the slot to the next deferred file, queued behind the splits of the file that held - /// it, so opens keep pace with the workers. The slot passes on whether the open finished or a - /// dropped worker gave it up, so that worker strands only the file it was opening. - fn drop(&mut self) { - if self.sender.is_closed() { - return; - } - if let Some(next) = self.shared.next_deferred() { - let slot = OpenSlot { - shared: Arc::clone(&self.shared), - sender: self.sender.clone(), - }; - send(&self.sender, Work::Open(next, slot)); - } - } -} - -fn send(sender: &Sender, work: Work) { - // The channel is unbounded and closes only once the pool is dropped, when the work is moot. - drop(sender.try_send(work)); -} - -/// A pool whose workers share its units through a channel. -struct UnorderedPool { - dtype: DType, - shared: Arc, - receiver: Receiver, - splits_in_flight: usize, -} - -impl UnorderedPool { - fn run(shared: &Arc, work: Work) -> SplitOutput { - match work { - Work::Split(split) => shared.admit(split), - Work::Open(factory, slot) => async move { - let opened = slot.shared.open_file(factory).await.map(|work| { - for split in slot.shared.file_splits(work) { - send(&slot.sender, Work::Split(split)); - } - None - }); - drop(slot); - opened - } - .boxed(), - } - } -} - -impl ScanPool for UnorderedPool { - fn dtype(&self) -> &DType { - &self.dtype - } - - fn worker(self: Arc) -> SendableArrayStream { - let dtype = self.dtype.clone(); - let shared = Arc::clone(&self.shared); - let runner = Arc::clone(&shared); - let receiver = self.receiver.clone(); - let splits_in_flight = self.splits_in_flight; - // The worker holds the pool, so the pool is dropped only after its last worker. - let outputs = receiver - .take_while(move |_| future::ready(!self.shared.limit.is_trimmed_out())) - .map(move |work| UnorderedPool::run(&runner, work)) - .buffer_unordered(splits_in_flight) - .boxed(); - ArrayStreamExt::boxed(ArrayStreamAdapter::new( - dtype, - shared.output(outputs, false, splits_in_flight), - )) - } - - fn progress(&self) -> f64 { - if self.is_exhausted() { - return 1.0; - } - self.shared.progress() - } - - fn is_exhausted(&self) -> bool { - // Open slots hold senders, so the channel closes only once every unit is in it. - self.shared.limit.is_trimmed_out() - || (self.receiver.is_closed() && self.receiver.is_empty()) - } -} - -impl Drop for UnorderedPool { - fn drop(&mut self) { - // Pending opens hold senders of the channel itself; drain them so it can be freed. - self.receiver.close(); - while self.receiver.try_recv().is_ok() {} - } -} - -/// A pool that gives all of its units, in row order, to its first worker. -struct OrderedPool { - dtype: DType, - shared: Arc, - /// The files, until the first worker takes them. - files: Mutex>>, - splits_in_flight: usize, - open_concurrency: usize, -} - -impl ScanPool for OrderedPool { - fn dtype(&self) -> &DType { - &self.dtype - } - - fn worker(self: Arc) -> SendableArrayStream { - let dtype = self.dtype.clone(); - let Some(files) = self.files.lock().take() else { - return ArrayStreamExt::boxed(ArrayStreamAdapter::new(dtype, stream::empty())); - }; - let shared = Arc::clone(&self.shared); - let opener = Arc::clone(&shared); - let splitter = Arc::clone(&shared); - let admitter = Arc::clone(&shared); - let gate = Arc::clone(&shared); - // Deferred files open `open_concurrency` at a time, ahead of the splits being read. - let outputs = stream::iter(files) - .map(move |file| match file { - PoolFile::Opened(work) => future::ready(Ok(work)).boxed(), - PoolFile::Deferred(factory) => opener.open_file(factory), - }) - .buffered(self.open_concurrency) - .flat_map(move |work| match work { - Ok(work) => { - stream::iter(splitter.file_splits(work).into_iter().map(Ok)).left_stream() - } - Err(err) => stream::once(future::ready(Err(err))).right_stream(), - }) - .take_while(move |_| future::ready(!gate.limit.is_trimmed_out())) - .map(move |split| match split { - Ok(split) => admitter.admit(split), - Err(err) => future::ready(Err(err)).boxed(), - }) - .buffered(self.splits_in_flight) - .boxed(); - ArrayStreamExt::boxed(ArrayStreamAdapter::new( - dtype, - shared.output(outputs, true, self.splits_in_flight), - )) - } - - fn progress(&self) -> f64 { - self.shared.progress() - } - - fn is_exhausted(&self) -> bool { - // The first worker takes every file. - self.shared.limit.is_trimmed_out() || self.files.lock().is_none() - } } /// The single partition of a scan piece that is read through the partitions API: it opens the diff --git a/vortex-scan/src/pool.rs b/vortex-scan/src/pool/mod.rs similarity index 98% rename from vortex-scan/src/pool.rs rename to vortex-scan/src/pool/mod.rs index 8b25959f816..d3820a4d77a 100644 --- a/vortex-scan/src/pool.rs +++ b/vortex-scan/src/pool/mod.rs @@ -29,6 +29,17 @@ use vortex_mask::Mask; use crate::DataSourceScanRef; use crate::PartitionStream; +mod work; + +pub use work::Expansion; +pub use work::MapOutput; +pub use work::MappedArray; +pub use work::PoolLimit; +pub use work::UnitOutput; +pub use work::WorkPoolOptions; +pub use work::WorkUnit; +pub use work::open_work_pool; + /// A shared reference to a [`ScanPool`]. pub type ScanPoolRef = Arc; diff --git a/vortex-scan/src/pool/work.rs b/vortex-scan/src/pool/work.rs new file mode 100644 index 00000000000..aa664545143 --- /dev/null +++ b/vortex-scan/src/pool/work.rs @@ -0,0 +1,740 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! The one pool that every scan engine's work runs through. +//! +//! A source opens a pool over [`WorkUnit`]s, in row order. A unit either runs, returning arrays, +//! or expands into further units in its place, which may expand in turn: work creates work. A +//! deferred file to open, a table format's manifest entry, and a scan root that prunes before it +//! cuts parts are all expansions. The source decides what a unit does and where it runs, spawning +//! it onto the session's runtime if it likes; the pool decides who takes which unit, how many run +//! at once, and when the scan's row limit stops the workers. +//! +//! - An unordered pool hands units out through a channel. The worker that expands a unit sends +//! the units it yields back into the channel, where any worker can take them. At most +//! `expand_concurrency` expansions are queued or running at once; each holds a slot that it +//! passes on to the next waiting expansion when it is done, or when its worker drops it. The +//! channel closes once every expansion has finished, which ends the workers. +//! - An ordered pool gives all of its units, in row order, to its first worker, which expands each +//! unit in its place, `expand_concurrency` top-level expansions ahead; later workers get +//! nothing. Parallel ordered reads cut the scan with `split` first. +//! +//! Each worker keeps up to its in-flight bound of units running at once: four per core, at most +//! the request's `split_concurrency`, the in-flight total of a partition's stream. + +use std::collections::VecDeque; +use std::num::NonZeroUsize; +use std::sync::Arc; +use std::task::Poll; + +use async_channel::Receiver; +use async_channel::Sender; +use futures::FutureExt; +use futures::StreamExt; +use futures::future; +use futures::future::BoxFuture; +use futures::ready; +use futures::stream; +use futures::stream::BoxStream; +use parking_lot::Mutex; +use vortex_array::ArrayRef; +use vortex_array::dtype::DType; +use vortex_array::stream::ArrayStreamAdapter; +use vortex_array::stream::ArrayStreamExt; +use vortex_array::stream::SendableArrayStream; +use vortex_error::VortexResult; +use vortex_utils::parallelism::get_available_parallelism; + +use super::RowLimit; +use super::SPLITS_IN_FLIGHT_PER_WORKER; +use super::ScanPool; +use super::ScanPoolRef; + +/// The arrays a unit returns, in row order. +pub type UnitOutput = BoxFuture<'static, VortexResult>>; + +/// The units an expansion yields, in row order, in its place. +pub type Expansion = BoxFuture<'static, VortexResult>>; + +/// Maps each array a worker returns, as a future that the worker runs `in flight` at a time. +pub type MapOutput = Arc MappedArray + Send + Sync>; + +/// One mapped array. +pub type MappedArray = BoxFuture<'static, VortexResult>; + +/// A unit of a pool's work, and its share of the pool's work for progress. +/// +/// Shares are the source's to give: the shares of a pool's units, and of the units an expansion +/// yields, sum to the share of what they stand for. A unit's share counts as taken when a worker +/// takes it. A part of the work that the source learns has nothing to read is a +/// [`skipped`](Self::skipped) unit, so its share is still taken. +pub struct WorkUnit { + kind: UnitKind, + share: f64, +} + +enum UnitKind { + /// Called once a worker takes the unit. + Run(Box UnitOutput + Send>), + /// Called once the unit is expanded. + Expand(Box Expansion + Send>), +} + +impl WorkUnit { + /// A unit that `run` starts once a worker takes it. + pub fn run(share: f64, run: impl FnOnce() -> UnitOutput + Send + 'static) -> Self { + Self { + kind: UnitKind::Run(Box::new(run)), + share, + } + } + + /// A unit that `expand` turns into further units, in its place, once it is reached. + pub fn expand(share: f64, expand: impl FnOnce() -> Expansion + Send + 'static) -> Self { + Self { + kind: UnitKind::Expand(Box::new(expand)), + share, + } + } + + /// A unit with nothing to read, whose share is taken once a worker reaches it. + pub fn skipped(share: f64) -> Self { + Self::run(share, || future::ready(Ok(Vec::new())).boxed()) + } + + fn is_expand(&self) -> bool { + matches!(self.kind, UnitKind::Expand(_)) + } +} + +/// How a pool applies the scan's row limit. +#[derive(Clone)] +pub enum PoolLimit { + /// The scan has no limit. + Unlimited, + /// The units reserve their rows from the budget before they read them, so their output needs + /// no trimming. Workers keep taking units once it is spent, which then return nothing, but + /// expansions not yet started are skipped. + Reserve(RowLimit), + /// A unit's output rows are unknown until it has run, so workers take rows from the budget as + /// they return them, discard the excess, and end once it is spent. + Trim(RowLimit), +} + +impl PoolLimit { + /// Whether the budget is spent, so no expansion that has not started has rows to return. + fn is_spent(&self) -> bool { + match self { + PoolLimit::Unlimited => false, + PoolLimit::Reserve(limit) | PoolLimit::Trim(limit) => limit.is_exhausted(), + } + } + + /// Whether a trimmed budget is spent, so workers end without returning any more rows. + fn is_trimmed_out(&self) -> bool { + matches!(self, PoolLimit::Trim(limit) if limit.is_exhausted()) + } +} + +/// How a pool shares its units among its workers. +pub struct WorkPoolOptions { + /// The dtype of every array the workers return. + pub dtype: DType, + /// Whether the scan returns rows in order, so the first worker takes every unit. + pub ordered: bool, + /// The scan's row limit, and how it is applied. + pub limit: PoolLimit, + /// The request's bound on the units each worker keeps in flight. + pub split_concurrency: Option, + /// The most expansions that are queued or running at once. + pub expand_concurrency: NonZeroUsize, + /// Maps every array the workers return under a [trimmed](PoolLimit::Trim) limit, such as to + /// optimize the array that the limit sliced. + pub map_trimmed: Option, +} + +/// Opens a pool over `units`, in row order. +pub fn open_work_pool(options: WorkPoolOptions, units: Vec) -> ScanPoolRef { + let scaled = + SPLITS_IN_FLIGHT_PER_WORKER.saturating_mul(get_available_parallelism().unwrap_or(1)); + let in_flight = options + .split_concurrency + .map_or(scaled, |max| scaled.min(max.get())) + .max(1); + let expand_concurrency = options.expand_concurrency.get(); + let shared = Arc::new(Shared { + limit: options.limit, + map_trimmed: options.map_trimmed, + in_flight, + taken: Mutex::new(0.0), + slots: Mutex::new(Slots { + free: expand_concurrency, + waiting: VecDeque::new(), + }), + }); + if options.ordered { + return Arc::new(OrderedPool { + dtype: options.dtype, + shared, + units: Mutex::new(Some(units)), + expand_concurrency, + }); + } + + let (sender, receiver) = async_channel::unbounded(); + shared.queue(&sender, units); + Arc::new(UnorderedPool { + dtype: options.dtype, + shared, + receiver, + }) +} + +/// What every worker of a pool shares. +struct Shared { + limit: PoolLimit, + map_trimmed: Option, + /// The units each worker keeps in flight. + in_flight: usize, + /// The share of the pool's work that workers have taken. + taken: Mutex, + /// An unordered pool's expansion slots. + slots: Mutex, +} + +/// An unordered pool's expansion slots: how many are free, and the expansions that wait for one, +/// in row order. +struct Slots { + free: usize, + waiting: VecDeque, +} + +impl Shared { + fn take(&self, share: f64) { + *self.taken.lock() += share; + } + + /// Takes a unit that runs, and starts it. + fn run(&self, unit: WorkUnit) -> UnitOutput { + self.take(unit.share); + match unit.kind { + UnitKind::Run(run) => run(), + UnitKind::Expand(_) => unreachable!("expansions are not run"), + } + } + + /// Expands a unit, or skips it once the limit is spent. + fn expand(&self, unit: WorkUnit) -> Expansion { + if self.limit.is_spent() { + self.take(unit.share); + return future::ready(Ok(Vec::new())).boxed(); + } + match unit.kind { + UnitKind::Expand(expand) => expand(), + UnitKind::Run(_) => unreachable!("only expansions expand"), + } + } + + /// Queues `units` into an unordered pool's channel, in order. An expansion takes a free slot, + /// or waits for one behind the expansions already waiting. + fn queue(self: &Arc, sender: &Sender, units: Vec) { + for unit in units { + if !unit.is_expand() { + send(sender, Work::Unit(unit)); + continue; + } + let mut slots = self.slots.lock(); + if slots.free > 0 { + slots.free -= 1; + drop(slots); + send(sender, Work::Expand(unit, Slot::new(self, sender))); + } else { + slots.waiting.push_back(unit); + } + } + } + + /// The expansion that a freed slot passes to, if any waits and the limit is not spent. Once it + /// is spent, the expansions left count as taken. Without one, the slot is free again. + fn pass_slot(&self) -> Option { + let mut slots = self.slots.lock(); + if self.limit.is_spent() && !slots.waiting.is_empty() { + let share: f64 = slots.waiting.iter().map(|unit| unit.share).sum(); + self.take(share); + slots.waiting.clear(); + } + let next = slots.waiting.pop_front(); + if next.is_none() { + slots.free += 1; + } + next + } + + fn progress(&self) -> f64 { + if self.limit.is_trimmed_out() { + return 1.0; + } + self.taken.lock().clamp(0.0, 1.0) + } + + /// A worker's output: the arrays of its units, trimmed to a trimmed limit and mapped, ending + /// after the first error or once a trimmed limit is spent. + fn output( + self: Arc, + dtype: DType, + outputs: BoxStream<'static, VortexResult>>, + ordered: bool, + ) -> SendableArrayStream { + let arrays = stop_on_error(outputs) + .flat_map(|arrays| match arrays { + Ok(arrays) => stream::iter(arrays.into_iter().map(Ok)).left_stream(), + Err(err) => stream::once(future::ready(Err(err))).right_stream(), + }) + .boxed(); + let arrays = match &self.limit { + PoolLimit::Trim(limit) => trim(arrays, limit.clone()), + PoolLimit::Unlimited | PoolLimit::Reserve(_) => arrays, + }; + let arrays = match (&self.limit, &self.map_trimmed) { + (PoolLimit::Trim(_), Some(map)) => { + let map = Arc::clone(map); + let mapped = arrays.map(move |array| match array { + Ok(array) => map(array), + Err(err) => future::ready(Err(err)).boxed(), + }); + let mapped = if ordered { + mapped.buffered(self.in_flight).boxed() + } else { + mapped.buffer_unordered(self.in_flight).boxed() + }; + stop_on_error(mapped) + } + _ => arrays, + }; + ArrayStreamExt::boxed(ArrayStreamAdapter::new(dtype, arrays)) + } +} + +/// 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. Leaves out empty arrays, and ends after the first error. +fn trim( + arrays: BoxStream<'static, VortexResult>, + limit: RowLimit, +) -> BoxStream<'static, VortexResult> { + super::trim_to_limit(arrays, limit) +} + +/// Ends `stream` after its first error. +fn stop_on_error( + stream: BoxStream<'static, VortexResult>, +) -> BoxStream<'static, VortexResult> { + let mut stream = Some(stream); + stream::poll_fn(move |cx| { + let Some(input) = stream.as_mut() else { + return Poll::Ready(None); + }; + let item = ready!(input.poll_next_unpin(cx)); + if !matches!(item, Some(Ok(_))) { + stream = None; + } + Poll::Ready(item) + }) + .boxed() +} + +/// A unit of an unordered pool's channel. +enum Work { + Unit(WorkUnit), + /// An expansion, and the slot it holds until its units are in the channel. + Expand(WorkUnit, Slot), +} + +/// One of an unordered pool's `expand_concurrency` expansion slots. Its sender keeps the channel +/// open while the expansion that holds it is queued or running. +struct Slot { + shared: Arc, + sender: Sender, +} + +impl Slot { + fn new(shared: &Arc, sender: &Sender) -> Self { + Self { + shared: Arc::clone(shared), + sender: sender.clone(), + } + } +} + +impl Drop for Slot { + /// Passes the slot to the next waiting expansion, queued behind the units of the expansion + /// that held it, so expansions keep pace with the workers. The slot passes on whether the + /// expansion finished or a dropped worker gave it up, so that worker strands only the + /// expansion it held. + fn drop(&mut self) { + if self.sender.is_closed() { + return; + } + if let Some(next) = self.shared.pass_slot() { + let slot = Slot::new(&self.shared, &self.sender); + send(&self.sender, Work::Expand(next, slot)); + } + } +} + +fn send(sender: &Sender, work: Work) { + // The channel is unbounded and closes only once the pool is dropped, when the work is moot. + drop(sender.try_send(work)); +} + +/// A pool whose workers share its units through a channel. +struct UnorderedPool { + dtype: DType, + shared: Arc, + receiver: Receiver, +} + +impl UnorderedPool { + fn run(shared: &Arc, work: Work) -> UnitOutput { + match work { + Work::Unit(unit) => shared.run(unit), + Work::Expand(unit, slot) => { + let expansion = shared.expand(unit); + async move { + let expanded = expansion.await.map(|units| { + slot.shared.queue(&slot.sender, units); + Vec::new() + }); + drop(slot); + expanded + } + .boxed() + } + } + } +} + +impl ScanPool for UnorderedPool { + fn dtype(&self) -> &DType { + &self.dtype + } + + fn worker(self: Arc) -> SendableArrayStream { + let dtype = self.dtype.clone(); + let shared = Arc::clone(&self.shared); + let runner = Arc::clone(&shared); + let receiver = self.receiver.clone(); + let in_flight = shared.in_flight; + // The worker holds the pool, so the pool is dropped only after its last worker. + let outputs = receiver + .take_while(move |_| future::ready(!self.shared.limit.is_trimmed_out())) + .map(move |work| UnorderedPool::run(&runner, work)) + .buffer_unordered(in_flight) + .boxed(); + shared.output(dtype, outputs, false) + } + + fn progress(&self) -> f64 { + if self.is_exhausted() { + return 1.0; + } + self.shared.progress() + } + + fn is_exhausted(&self) -> bool { + // Slots hold senders, so the channel closes only once every unit is in it. + self.shared.limit.is_trimmed_out() + || (self.receiver.is_closed() && self.receiver.is_empty()) + } +} + +impl Drop for UnorderedPool { + fn drop(&mut self) { + // Queued expansions hold senders of the channel itself; drain them so it can be freed. + self.receiver.close(); + while self.receiver.try_recv().is_ok() {} + } +} + +/// A pool that gives all of its units, in row order, to its first worker. +struct OrderedPool { + dtype: DType, + shared: Arc, + /// The units, until the first worker takes them. + units: Mutex>>, + expand_concurrency: usize, +} + +impl OrderedPool { + /// The units that `units` stand for, in row order, with each expansion's units in its place. + /// Expansions run up to `expand_concurrency` ahead of the units being taken, counting each + /// run of consecutive units that need no expansion as one step, as a file's splits are. + fn in_order( + shared: Arc, + units: Vec, + expand_concurrency: usize, + ) -> BoxStream<'static, VortexResult> { + let mut segments: Vec = Vec::new(); + for unit in units { + match (unit.is_expand(), segments.last_mut()) { + (true, _) => segments.push(Segment::Expand(unit)), + (false, Some(Segment::Units(run))) => run.push(unit), + (false, _) => segments.push(Segment::Units(vec![unit])), + } + } + let expander = Arc::clone(&shared); + stream::iter(segments) + .map(move |segment| match segment { + Segment::Units(units) => future::ready(Ok((units, false))).boxed(), + Segment::Expand(unit) => expander + .expand(unit) + .map(|units| units.map(|units| (units, true))) + .boxed(), + }) + .buffered(expand_concurrency) + .flat_map(move |segment| match segment { + Ok((units, false)) => stream::iter(units.into_iter().map(Ok)).boxed(), + Ok((units, true)) => { + OrderedPool::in_order(Arc::clone(&shared), units, expand_concurrency) + } + Err(err) => stream::once(future::ready(Err(err))).boxed(), + }) + .boxed() + } +} + +/// A step of an ordered pool's units: consecutive units that need no expansion, or one expansion. +enum Segment { + Units(Vec), + Expand(WorkUnit), +} + +impl ScanPool for OrderedPool { + fn dtype(&self) -> &DType { + &self.dtype + } + + fn worker(self: Arc) -> SendableArrayStream { + let dtype = self.dtype.clone(); + let Some(units) = self.units.lock().take() else { + return ArrayStreamExt::boxed(ArrayStreamAdapter::new(dtype, stream::empty())); + }; + let shared = Arc::clone(&self.shared); + let runner = Arc::clone(&shared); + let gate = Arc::clone(&shared); + let outputs = OrderedPool::in_order(Arc::clone(&shared), units, self.expand_concurrency) + .take_while(move |_| future::ready(!gate.limit.is_trimmed_out())) + .map(move |unit| match unit { + Ok(unit) => runner.run(unit), + Err(err) => future::ready(Err(err)).boxed(), + }) + .buffered(shared.in_flight) + .boxed(); + shared.output(dtype, outputs, true) + } + + fn progress(&self) -> f64 { + self.shared.progress() + } + + fn is_exhausted(&self) -> bool { + // The first worker takes every unit. + self.shared.limit.is_trimmed_out() || self.units.lock().is_none() + } +} + +#[cfg(test)] +mod tests { + use std::num::NonZeroUsize; + use std::ops::Range; + use std::sync::Arc; + use std::sync::atomic::AtomicUsize; + use std::sync::atomic::Ordering; + + use futures::FutureExt; + use futures::TryStreamExt; + use futures::executor::block_on; + use futures::future::try_join_all; + use rstest::rstest; + use vortex_array::ArrayRef; + use vortex_array::IntoArray; + use vortex_array::VortexSessionExecute; + use vortex_array::arrays::PrimitiveArray; + use vortex_array::dtype::DType; + use vortex_array::dtype::Nullability; + use vortex_array::dtype::PType; + use vortex_buffer::Buffer; + use vortex_error::VortexResult; + + use super::PoolLimit; + use super::WorkPoolOptions; + use super::WorkUnit; + use super::open_work_pool; + use crate::pool::RowLimit; + use crate::pool::ScanPoolRef; + use crate::test::SESSION; + + fn dtype() -> DType { + DType::Primitive(PType::I32, Nullability::NonNullable) + } + + /// A unit returning the values of `rows`. + fn rows(rows: Range, share: f64) -> WorkUnit { + WorkUnit::run(share, move || { + futures::future::ready(Ok(vec![Buffer::from_iter(rows).into_array()])).boxed() + }) + } + + /// An expansion of `rows` into `parts` units, or into nested expansions `depth` levels deep, + /// counting how many expansions run at once in `running` and the most in `peak`. + fn expansion( + rows_: Range, + parts: i32, + depth: usize, + share: f64, + running: Arc, + peak: Arc, + ) -> WorkUnit { + WorkUnit::expand(share, move || { + async move { + let now = running.fetch_add(1, Ordering::SeqCst) + 1; + peak.fetch_max(now, Ordering::SeqCst); + yield_once().await; + let step = (rows_.end - rows_.start) / parts; + let share = share / f64::from(parts); + let units = (0..parts) + .map(|i| { + let start = rows_.start + i * step; + let part = start..start + step; + if depth == 0 { + rows(part, share) + } else { + let (running, peak) = (Arc::clone(&running), Arc::clone(&peak)); + expansion(part, parts, depth - 1, share, running, peak) + } + }) + .collect(); + running.fetch_sub(1, Ordering::SeqCst); + Ok(units) + } + .boxed() + }) + } + + /// Pends once, waking itself, so that other work runs in between. + async fn yield_once() { + let mut yielded = false; + futures::future::poll_fn(|cx| { + if yielded { + return std::task::Poll::Ready(()); + } + yielded = true; + cx.waker().wake_by_ref(); + std::task::Poll::Pending + }) + .await; + } + + fn options(ordered: bool, limit: PoolLimit, expand_concurrency: usize) -> WorkPoolOptions { + WorkPoolOptions { + dtype: dtype(), + ordered, + limit, + split_concurrency: NonZeroUsize::new(2), + expand_concurrency: NonZeroUsize::new(expand_concurrency).unwrap_or(NonZeroUsize::MIN), + map_trimmed: None, + } + } + + fn values(arrays: Vec) -> VortexResult> { + let mut ctx = SESSION.create_execution_ctx(); + let mut values = Vec::new(); + for array in arrays { + values.extend_from_slice(array.execute::(&mut ctx)?.as_slice::()); + } + Ok(values) + } + + /// Reads `pool` with `workers` workers, returning each worker's values. + fn read(pool: &ScanPoolRef, workers: usize) -> VortexResult>> { + let workers = (0..workers).map(|_| Arc::clone(pool).worker().try_collect::>()); + block_on(try_join_all(workers))? + .into_iter() + .map(values) + .collect() + } + + /// Three top-level units: rows, a two-level expansion, and rows again. + fn units(running: &Arc, peak: &Arc) -> Vec { + let share = 1.0 / 3.0; + vec![ + rows(0..10, share), + expansion(10..90, 2, 2, share, Arc::clone(running), Arc::clone(peak)), + rows(90..100, share), + ] + } + + /// An ordered pool's first worker reads every unit in row order, with each expansion's units + /// in its place however deep it nests; an unordered pool's workers read each unit once. + #[rstest] + #[case::ordered(true)] + #[case::unordered(false)] + fn pool_reads_expansions_in_place(#[case] ordered: bool) -> VortexResult<()> { + let (running, peak) = Default::default(); + let pool = open_work_pool( + options(ordered, PoolLimit::Unlimited, 4), + units(&running, &peak), + ); + assert_eq!(pool.progress(), 0.0); + let workers = read(&pool, 3)?; + if ordered { + assert_eq!(workers[0], (0..100).collect::>()); + assert!(workers[1..].iter().all(Vec::is_empty)); + } else { + let mut all: Vec = workers.into_iter().flatten().collect(); + all.sort_unstable(); + assert_eq!(all, (0..100).collect::>()); + } + assert!(pool.is_exhausted()); + assert!((pool.progress() - 1.0).abs() < 1e-9, "{}", pool.progress()); + Ok(()) + } + + /// An unordered pool runs at most `expand_concurrency` expansions at once. + #[test] + fn unordered_pool_bounds_expansions() -> VortexResult<()> { + let running = Arc::new(AtomicUsize::new(0)); + let peak = Arc::new(AtomicUsize::new(0)); + let units = (0..8) + .map(|i| { + let (running, peak) = (Arc::clone(&running), Arc::clone(&peak)); + expansion(i * 20..i * 20 + 20, 2, 1, 1.0 / 8.0, running, peak) + }) + .collect(); + let pool = open_work_pool(options(false, PoolLimit::Unlimited, 1), units); + let mut all: Vec = read(&pool, 4)?.into_iter().flatten().collect(); + all.sort_unstable(); + assert_eq!(all, (0..160).collect::>()); + assert_eq!(peak.load(Ordering::SeqCst), 1); + Ok(()) + } + + /// A trimmed limit ends the workers once spent, slicing the array that spends it, and leaves + /// the pool exhausted. + #[rstest] + #[case::ordered(true)] + #[case::unordered(false)] + fn trimmed_limit_ends_the_workers(#[case] ordered: bool) -> VortexResult<()> { + let (running, peak) = Default::default(); + let limit = PoolLimit::Trim(RowLimit::new(25)); + let pool = open_work_pool(options(ordered, limit, 4), units(&running, &peak)); + let workers = read(&pool, 2)?; + let rows: usize = workers.iter().map(Vec::len).sum(); + assert_eq!(rows, 25); + if ordered { + assert_eq!(workers[0], (0..25).collect::>()); + } + assert!(pool.is_exhausted()); + assert_eq!(pool.progress(), 1.0); + Ok(()) + } +} diff --git a/vortex-scan/src/source/plan.rs b/vortex-scan/src/source/plan.rs index f9039a388ae..335cba3f455 100644 --- a/vortex-scan/src/source/plan.rs +++ b/vortex-scan/src/source/plan.rs @@ -451,34 +451,24 @@ impl ScanState { /// Expands `children` depth-first, in order, into the admitted ready children they stand for, /// expanding each deferred child only once the children before it are taken. - /// - /// Each child comes with its share of the scan's work, which a deferred child divides evenly - /// among the children it expands into. The share of a child that is pruned, or that expands - /// into nothing, goes to `skipped`. pub(super) fn expand_in_order( self: &Arc, - children: Vec<(PlanSourceChild, f64)>, - skipped: Arc, - ) -> BoxStream<'static, VortexResult<(PlanChild, f64)>> { + children: Vec, + ) -> BoxStream<'static, VortexResult> { let state = Arc::clone(self); stream::try_unfold(VecDeque::from(children), move |mut queue| { let state = Arc::clone(&state); - let skipped = Arc::clone(&skipped); async move { - while let Some((child, share)) = queue.pop_front() { + while let Some(child) = queue.pop_front() { match child { - PlanSourceChild::Ready(child) => match state.admit(child)? { - Some(child) => return Ok(Some(((child, share), queue))), - None => skipped(share), - }, - PlanSourceChild::Deferred { child, .. } => { - let children = child.expand().await?; - if children.is_empty() { - skipped(share); + PlanSourceChild::Ready(child) => { + if let Some(child) = state.admit(child)? { + return Ok(Some((child, queue))); } - let share = share / children.len().max(1) as f64; - for child in children.into_iter().rev() { - queue.push_front((child, share)); + } + PlanSourceChild::Deferred { child, .. } => { + for child in child.expand().await?.into_iter().rev() { + queue.push_front(child); } } } @@ -747,11 +737,8 @@ impl Partition for PlanPartition { let children = match state.ready(unit.child) { Some(child) => stream::iter([Ok((child.clone(), unit.rows))]).boxed(), None => state - .expand_in_order( - vec![(state.child(unit.child).clone(), 0.0)], - Arc::new(|_| {}), - ) - .map_ok(|(child, _)| (child, None)) + .expand_in_order(vec![state.child(unit.child).clone()]) + .map_ok(|child| (child, None)) .boxed(), }; let driver = Arc::clone(&state); diff --git a/vortex-scan/src/source/plan_pool.rs b/vortex-scan/src/source/plan_pool.rs index 0f789325a59..fee2bfd3918 100644 --- a/vortex-scan/src/source/plan_pool.rs +++ b/vortex-scan/src/source/plan_pool.rs @@ -1,59 +1,39 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors -//! The work that the workers of an opened [`PlanDataSource`](super::PlanDataSource) scan share. +//! The work of an opened [`PlanDataSource`](super::PlanDataSource) scan, for the scan pool. //! -//! This is the V1 layout pool's pattern (`vortex-layout/src/scan/pool.rs`) over the V2 executor, -//! with plan work for units. A pool's units are parts, rows of a prepared child's plan, and -//! deferred children not yet expanded. Opening the scan prepares each ready child once, which -//! plans without reading, and runs its root up front, which spawns its parts, as develop's V2 -//! DuckDB scan does: a part is the rows between two of the child's splits for the fields the scan -//! reads, such as a file's layout splits, else one of the scan's chunks. A root whose filter -//! changes while the scan runs, as a top-N's bound does, prunes the child as a whole before it -//! spawns parts; it reads zone maps to do so, so it runs as a unit of work instead. A worker takes parts and keeps up to `split_concurrency` of them -//! in flight, each spawned onto the session's runtime when the worker takes it, as the V1 pool's -//! splits are, and driven there on a planning run of its own that awaits only its reads: with a -//! filter, the part's pruning plans first, continuing into the chunks of the rows pruning kept; -//! without, the chunks directly. +//! The units are plan work. Opening the scan prepares each ready child once, which plans without +//! reading, and runs its root up front, which spawns its parts, as develop's V2 DuckDB scan does: +//! a part is the rows between two of the child's splits for the fields the scan reads, such as a +//! file's layout splits, else one of the scan's chunks. A root whose filter changes while the scan +//! runs, as a top-N's bound does, prunes the child as a whole before it spawns parts; it reads +//! zone maps to do so, so it is an expansion instead. A worker spawns each part it takes onto the +//! session's runtime, where it is driven on a planning run of its own that awaits only its reads: +//! with a filter, the part's pruning plans first, continuing into the chunks of the rows pruning +//! kept; without, the chunks directly. //! //! Work creates work: expanding a deferred child, whether a file to open, a manifest entry or a -//! table partition, is a unit like any other, and queues the work of the children it expands -//! into, which may be deferred in turn. +//! table partition, yields the units of the children it expands into, which may be deferred in +//! turn. The [pool](crate::pool::open_work_pool) shares the units among the workers. //! -//! - An unordered pool hands units out through a channel. The worker that expands a deferred -//! child sends its children's units back into the channel, where any worker can take them. The -//! channel closes once every expansion has finished, which ends the workers. -//! - An ordered pool gives all of its units, in row order, to its first worker, which expands -//! each deferred child in its place; later workers get nothing. Parallel ordered reads cut the -//! scan with `split` first. -//! -//! A limit is a [`RowLimit`] the workers take rows from as they yield them; workers stop taking -//! units once it is spent. +//! Each top-level child has an equal share of the pool's progress. A deferred child divides its +//! share evenly among the children it expands into, and a prepared child divides its share among +//! its parts by their rows. use std::future; +use std::num::NonZeroUsize; use std::ops::Range; use std::sync::Arc; -use async_channel::Receiver; -use async_channel::Sender; use futures::FutureExt; -use futures::StreamExt; -use futures::future::BoxFuture; -use futures::stream; -use futures::stream::BoxStream; -use parking_lot::Mutex; -use vortex_array::ArrayRef; -use vortex_array::dtype::DType; use vortex_array::scalar_fn::fns::dynamic::DynamicExprUpdates; -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_error::vortex_bail; use vortex_io::request::IoService; use vortex_io::session::RuntimeSessionExt; -use vortex_utils::parallelism::get_available_parallelism; +use vortex_session::VortexSession; use super::plan::DeferredPlanChild; use super::plan::PlanChild; @@ -64,11 +44,14 @@ use crate::execution::planning::driver::Progress; use crate::execution::planning::driver::Run; use crate::execution::planning::planner::Planner; use crate::execution::planning::planner::WorkScope; +use crate::pool::Expansion; +use crate::pool::PoolLimit; use crate::pool::RowLimit; -use crate::pool::SPLITS_IN_FLIGHT_PER_WORKER; -use crate::pool::ScanPool; use crate::pool::ScanPoolRef; -use crate::pool::trim_to_limit; +use crate::pool::UnitOutput; +use crate::pool::WorkPoolOptions; +use crate::pool::WorkUnit; +use crate::pool::open_work_pool; use crate::prepare::PreparedScan; use crate::prepare::part_root; @@ -78,108 +61,64 @@ struct PreparedChild { io: Arc, } -/// A part of a child: the planner its root spawned for some of its rows, which one worker runs on -/// a planning run of its own. -struct Part { - child: Arc, - scope: WorkScope, - planner: Box, - /// The part's share of the pool's work, for its progress. - share: f64, -} - -/// The share of a pool's work that workers have taken, from 0.0 to 1.0. -/// -/// Each top-level child of the pool has an equal share. A deferred child divides its share evenly -/// among the children it expands into, and a prepared child divides its share among its parts by -/// their rows. The share of rows that pruning skips counts as taken once they are skipped. -#[derive(Default)] -struct Taken(Mutex); - -impl Taken { - fn add(&self, share: f64) { - *self.0.lock() += share; - } - - fn get(&self) -> f64 { - self.0.lock().clamp(0.0, 1.0) - } -} - -/// A part's batches, in row order. -type PartFuture = BoxFuture<'static, VortexResult>>; - -/// The parts a child's root spawns, in row order. -type PartsFuture = BoxFuture<'static, VortexResult>>; - -/// A child of a pool, in row order. -enum PoolChild { - /// A child whose root has run, with the parts it spawned. - Parts(Vec), - /// A child whose root reads before it spawns parts: it prunes the child as a whole first. - Root(PartsFuture), - /// A deferred child, and its share of the pool's work. - Deferred(Arc, f64), -} - -impl PoolChild { - /// The child's parts once its root has run. - fn into_parts(self) -> PartsFuture { - match self { - Self::Parts(parts) => future::ready(Ok(parts)).boxed(), - Self::Root(parts) => parts, - Self::Deferred(..) => unreachable!("a deferred child has no root"), - } - } -} - /// Opens a pool over the scan's `units`, preparing each of its ready children. pub(super) fn open(state: Arc, units: Vec) -> VortexResult { - let taken = Arc::new(Taken::default()); let share = 1.0 / units.len().max(1) as f64; - let mut children = Vec::with_capacity(units.len()); + let mut work = Vec::with_capacity(units.len()); for unit in units { - children.push(match state.child(unit.child) { - PlanSourceChild::Ready(child) => prepare(&state, child, unit.rows, share, &taken)?, + match state.child(unit.child) { + PlanSourceChild::Ready(child) => { + work.extend(prepare(&state, child, unit.rows, share)?); + } PlanSourceChild::Deferred { child, .. } => { - PoolChild::Deferred(Arc::clone(child), share) + work.push(expand(Arc::clone(&state), Arc::clone(child), share)); } - }); - } - let dtype = state.dtype.clone(); - // A worker takes the place of a partition that one host thread drains, so, like the layout - // pool's, it keeps as many parts in flight as a partition's stream does by default: four per - // core, at most the request's `split_concurrency`. - let scaled = - SPLITS_IN_FLIGHT_PER_WORKER.saturating_mul(get_available_parallelism().unwrap_or(1)); - let parts_in_flight = state - .split_concurrency - .map_or(scaled, |max| scaled.min(max.get())) - .max(1); - let shared = Arc::new(Shared { - limit: state.limit.map(RowLimit::new), - state, - taken, - }); - if shared.state.ordered { - return Ok(Arc::new(OrderedPool { - dtype, - shared, - children: Mutex::new(Some(children)), - parts_in_flight, - })); + } } + let options = WorkPoolOptions { + dtype: state.dtype.clone(), + ordered: state.ordered, + limit: state.limit.map_or(PoolLimit::Unlimited, |limit| { + PoolLimit::Trim(RowLimit::new(limit)) + }), + split_concurrency: state.split_concurrency, + // An ordered pool expands each deferred child only once the units before it are taken; + // an unordered one expands every child as soon as a worker takes it. + expand_concurrency: if state.ordered { + NonZeroUsize::MIN + } else { + NonZeroUsize::MAX + }, + map_trimmed: None, + }; + Ok(open_work_pool(options, work)) +} - let (sender, receiver) = async_channel::unbounded(); - for child in children { - queue(&sender, child); - } - Ok(Arc::new(UnorderedPool { - dtype, - shared, - receiver, - parts_in_flight, - })) +/// The unit that expands a deferred child into the units of the children it stands for. +fn expand(state: Arc, child: Arc, share: f64) -> WorkUnit { + WorkUnit::expand(share, move || { + async move { + let children = child.expand().await?; + if children.is_empty() { + return Ok(vec![WorkUnit::skipped(share)]); + } + let share = share / children.len() as f64; + let mut units = Vec::new(); + for child in children { + match child { + PlanSourceChild::Ready(child) => match state.admit(child)? { + Some(child) => units.extend(prepare(&state, &child, None, share)?), + None => units.push(WorkUnit::skipped(share)), + }, + PlanSourceChild::Deferred { child, .. } => { + units.push(expand(Arc::clone(&state), child, share)); + } + } + } + Ok(units) + } + .boxed() + }) } /// Prepares the scan of `rows` of `child`, or of the request's rows when `None`, once, and runs its @@ -193,15 +132,13 @@ fn prepare( child: &PlanChild, rows: Option>, share: f64, - taken: &Arc, -) -> VortexResult { +) -> VortexResult> { let rows = match rows { Some(rows) => rows, None => state.child_rows(child)?, }; if rows.is_empty() { - taken.add(share); - return Ok(PoolChild::Parts(Vec::new())); + return Ok(vec![WorkUnit::skipped(share)]); } let splits = child.splits(&state.projection, state.filter.as_ref())?; let scan = Arc::new(state.builder(child, rows).prepare()?); @@ -212,25 +149,24 @@ fn prepare( let root = part_root(&scan, splits.as_deref(), dynamic); let io = scan.io(); let child = Arc::new(PreparedChild { scan, io }); - let parts = run_root(child, root, share, Arc::clone(taken)); + let parts = run_root(child, root, share, state.session.clone()); if dynamic { - return Ok(PoolChild::Root(parts)); + return Ok(vec![WorkUnit::expand(share, move || parts)]); } - let parts = parts + parts .now_or_never() - .vortex_expect("a root that only cuts parts reads nothing")?; - Ok(PoolChild::Parts(parts)) + .vortex_expect("a root that only cuts parts reads nothing") } -/// Runs a child's root on a planning run of its own, awaiting only its reads, and returns the -/// parts it spawns, in row order, dividing the child's `share` among them by their rows. The share -/// of the rows they leave out counts as taken. +/// Runs a child's root on a planning run of its own, awaiting only its reads, and returns a unit +/// for each part it spawns, in row order, dividing the child's `share` among them by their rows. +/// The rows the parts leave out are a skipped unit. fn run_root( child: Arc, root: Box, share: f64, - taken: Arc, -) -> PartsFuture { + session: VortexSession, +) -> Expansion { async move { let rows = child.scan.rows(); let per_row = share / (rows.end - rows.start).max(1) as f64; @@ -240,23 +176,26 @@ fn run_root( root, WorkScope { file_ordinal: 0, - rows: child.scan.rows().clone(), + rows: rows.clone(), }, child.io.session(), ); - let mut parts = Vec::new(); + let mut units = Vec::new(); loop { match run.advance()? { Progress::Spawn(scope, planner) => { let part_rows = scope.rows.end - scope.rows.start; unassigned = unassigned.saturating_sub(part_rows); - let share = per_row * part_rows as f64; - parts.push(Part { - child: Arc::clone(&child), - scope, - planner, - share, - }); + let child = Arc::clone(&child); + let session = session.clone(); + units.push(WorkUnit::run(per_row * part_rows as f64, move || { + // Another runtime thread may run the part while this worker drives its + // other parts, and its reads start right away. + session + .handle() + .spawn(run_part(child, scope, planner)) + .boxed() + })); } Progress::Batch(_) => vortex_bail!("a scan's root produced a batch"), Progress::RootDone(_) if run.live_roots() > 0 => {} @@ -265,23 +204,17 @@ fn run_root( } } if unassigned > 0 { - taken.add(per_row * unassigned as f64); + units.push(WorkUnit::skipped(per_row * unassigned as f64)); } - Ok(parts) + Ok(units) } .boxed() } /// Runs a part on a planning run of its own, awaiting only its reads, and returns its batches in /// row order. -fn run_part(part: Part) -> PartFuture { +fn run_part(child: Arc, scope: WorkScope, planner: Box) -> UnitOutput { async move { - let Part { - child, - scope, - planner, - .. - } = part; let mut run = Run::new(); run.admit(planner, scope, child.io.session()); let mut batches = Vec::new(); @@ -302,248 +235,3 @@ fn run_part(part: Part) -> PartFuture { } .boxed() } - -/// What every worker of a pool shares. -struct Shared { - state: Arc, - limit: Option, - taken: Arc, -} - -impl Shared { - /// Spawns a part onto the session's runtime: another runtime thread may run it while this - /// worker drives its other parts, and its reads start right away. - fn spawn_part(&self, part: Part) -> PartFuture { - self.taken.add(part.share); - self.state.session.handle().spawn(run_part(part)).boxed() - } - - fn prepare(&self, child: &PlanChild, share: f64) -> VortexResult { - prepare(&self.state, child, None, share, &self.taken) - } - - fn is_limit_spent(&self) -> bool { - self.limit.as_ref().is_some_and(RowLimit::is_exhausted) - } - - /// The parts of the children that `children` expand into, in row order, expanding each - /// deferred child only once the parts before it are taken. - fn parts_in_order( - self: &Arc, - children: Vec<(PlanSourceChild, f64)>, - ) -> BoxStream<'static, VortexResult>> { - let shared = Arc::clone(self); - let taken = Arc::clone(&self.taken); - self.state - .expand_in_order(children, Arc::new(move |share| taken.add(share))) - .then(move |child| { - match child.and_then(|(child, share)| shared.prepare(&child, share)) { - Ok(child) => child.into_parts(), - Err(err) => future::ready(Err(err)).boxed(), - } - }) - .boxed() - } - - /// A worker's output: the batches of its parts, trimmed to the limit, ending after the first - /// error. - fn output( - &self, - outputs: BoxStream<'static, VortexResult>>, - ) -> SendableArrayStream { - let arrays = outputs - .scan(false, |failed, output| { - if *failed { - return future::ready(None); - } - *failed = output.is_err(); - future::ready(Some(output)) - }) - .flat_map(|arrays| match arrays { - Ok(arrays) => stream::iter(arrays.into_iter().map(Ok)).left_stream(), - Err(err) => stream::once(future::ready(Err(err))).right_stream(), - }) - .boxed(); - let arrays = match &self.limit { - Some(limit) => trim_to_limit(arrays, limit.clone()), - None => arrays, - }; - ArrayStreamExt::boxed(ArrayStreamAdapter::new(self.state.dtype.clone(), arrays)) - } -} - -/// A unit of an unordered pool. -enum Work { - Part(Part), - /// A child's root that reads before it spawns parts, and where to send the parts. The sender - /// keeps the channel open until they are in it. - Root(PartsFuture, Sender), - /// A deferred child, its share of the pool's work, and where to send the units of its children - /// once it is expanded. - Expand(Arc, f64, Sender), -} - -fn send(sender: &Sender, work: Work) { - // The channel is unbounded and closes only once the pool is dropped, when the work is moot. - drop(sender.try_send(work)); -} - -/// Queues the units of `child`. -fn queue(sender: &Sender, child: PoolChild) { - match child { - PoolChild::Parts(parts) => { - for part in parts { - send(sender, Work::Part(part)); - } - } - PoolChild::Root(parts) => send(sender, Work::Root(parts, sender.clone())), - PoolChild::Deferred(child, share) => { - send(sender, Work::Expand(child, share, sender.clone())); - } - } -} - -/// A pool whose workers share its units through a channel. -struct UnorderedPool { - dtype: DType, - shared: Arc, - receiver: Receiver, - parts_in_flight: usize, -} - -impl UnorderedPool { - fn run(shared: &Arc, work: Work) -> PartFuture { - match work { - Work::Part(part) => shared.spawn_part(part), - Work::Root(parts, sender) => async move { - for part in parts.await? { - send(&sender, Work::Part(part)); - } - Ok(Vec::new()) - } - .boxed(), - Work::Expand(child, share, sender) => { - let shared = Arc::clone(shared); - async move { - let children = child.expand().await?; - if children.is_empty() { - shared.taken.add(share); - } - let share = share / children.len().max(1) as f64; - for child in children { - match child { - PlanSourceChild::Ready(child) => match shared.state.admit(child)? { - Some(child) => queue(&sender, shared.prepare(&child, share)?), - None => shared.taken.add(share), - }, - PlanSourceChild::Deferred { child, .. } => { - send(&sender, Work::Expand(child, share, sender.clone())); - } - } - } - Ok(Vec::new()) - } - .boxed() - } - } - } -} - -impl ScanPool for UnorderedPool { - fn dtype(&self) -> &DType { - &self.dtype - } - - fn worker(self: Arc) -> SendableArrayStream { - let shared = Arc::clone(&self.shared); - let runner = Arc::clone(&shared); - let receiver = self.receiver.clone(); - let parts_in_flight = self.parts_in_flight; - // The worker holds the pool, so the pool is dropped only after its last worker. - let outputs = receiver - .take_while(move |_| future::ready(!self.shared.is_limit_spent())) - .map(move |work| UnorderedPool::run(&runner, work)) - .buffer_unordered(parts_in_flight) - .boxed(); - shared.output(outputs) - } - - fn progress(&self) -> f64 { - if self.is_exhausted() { - return 1.0; - } - self.shared.taken.get() - } - - fn is_exhausted(&self) -> bool { - // Roots and expansions hold senders, so the channel closes only once every unit is in it. - self.shared.is_limit_spent() || (self.receiver.is_closed() && self.receiver.is_empty()) - } -} - -impl Drop for UnorderedPool { - fn drop(&mut self) { - // Pending opens hold senders of the channel itself; drain them so it can be freed. - self.receiver.close(); - while self.receiver.try_recv().is_ok() {} - } -} - -/// A pool that gives all of its units, in row order, to its first worker. -struct OrderedPool { - dtype: DType, - shared: Arc, - /// The children, until the first worker takes them. - children: Mutex>>, - parts_in_flight: usize, -} - -impl ScanPool for OrderedPool { - fn dtype(&self) -> &DType { - &self.dtype - } - - fn worker(self: Arc) -> SendableArrayStream { - let Some(children) = self.children.lock().take() else { - return ArrayStreamExt::boxed(ArrayStreamAdapter::new( - self.dtype.clone(), - stream::empty(), - )); - }; - let expander = Arc::clone(&self.shared); - let spawner = Arc::clone(&self.shared); - let shared = Arc::clone(&self.shared); - let outputs = stream::iter(children) - .flat_map(move |child| match child { - PoolChild::Deferred(child, share) => expander.parts_in_order(vec![( - PlanSourceChild::Deferred { - child, - byte_size: None, - }, - share, - )]), - child => stream::once(child.into_parts()).boxed(), - }) - .flat_map(|parts| match parts { - Ok(parts) => stream::iter(parts.into_iter().map(Ok)).left_stream(), - Err(err) => stream::once(future::ready(Err(err))).right_stream(), - }) - .take_while(move |_| future::ready(!shared.is_limit_spent())) - .map(move |part| match part { - Ok(part) => spawner.spawn_part(part), - Err(err) => future::ready(Err(err)).boxed(), - }) - .buffered(self.parts_in_flight) - .boxed(); - self.shared.output(outputs) - } - - fn progress(&self) -> f64 { - self.shared.taken.get() - } - - fn is_exhausted(&self) -> bool { - // The first worker takes every child. - self.shared.is_limit_spent() || self.children.lock().is_none() - } -} From d6f9e17709a2ff254248fd0e54375b74bc12f9e1 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Thu, 19 Nov 2026 22:03:53 -0500 Subject: [PATCH 2/8] Stream V2 parts' chunks as they finish and bound V2 opens An unordered pool's lane now runs a V2 part itself and passes each chunk on as it finishes, as a DuckDB thread of develop's V2 scan does, instead of spawning the part and holding all its chunks until it is done. A top-N then tightens its bound after the first chunk, not the first part, and a part's chunks no longer sit in memory together. Ordered pools keep collecting parts in row order. An unordered V2 pool now opens one child per core at once, as V1 opens files, rather than every child at once. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-scan/src/pool/mod.rs | 1 + vortex-scan/src/pool/work.rs | 138 +++++++++++++++++----------- vortex-scan/src/source/plan_pool.rs | 81 ++++++++++++---- 3 files changed, 150 insertions(+), 70 deletions(-) diff --git a/vortex-scan/src/pool/mod.rs b/vortex-scan/src/pool/mod.rs index 055f679aea6..b3a929293e9 100644 --- a/vortex-scan/src/pool/mod.rs +++ b/vortex-scan/src/pool/mod.rs @@ -36,6 +36,7 @@ pub use work::MapOutput; pub use work::MappedArray; pub use work::PoolLimit; pub use work::UnitOutput; +pub use work::UnitStream; pub use work::WorkPoolOptions; pub use work::WorkUnit; pub use work::open_work_pool; diff --git a/vortex-scan/src/pool/work.rs b/vortex-scan/src/pool/work.rs index d7af37b2084..3cb55b61b64 100644 --- a/vortex-scan/src/pool/work.rs +++ b/vortex-scan/src/pool/work.rs @@ -39,6 +39,8 @@ use async_channel::Receiver; use async_channel::Sender; use futures::FutureExt; use futures::StreamExt; +use futures::TryFutureExt; +use futures::TryStreamExt; use futures::future; use futures::future::BoxFuture; use futures::ready; @@ -63,6 +65,9 @@ use super::ScanPoolRef; /// The arrays a unit returns, in row order. pub type UnitOutput = BoxFuture<'static, VortexResult>>; +/// The arrays a unit yields one at a time, as it produces them. +pub type UnitStream = BoxStream<'static, VortexResult>; + /// The units an expansion yields, in row order, in its place. pub type Expansion = BoxFuture<'static, VortexResult>>; @@ -86,6 +91,8 @@ pub struct WorkUnit { enum UnitKind { /// Called once a worker takes the unit. Run(Box UnitOutput + Send>), + /// Called once a worker takes the unit; yields its arrays as they are produced. + Stream(Box UnitStream + Send>), /// Called once the unit is expanded. Expand(Box Expansion + Send>), } @@ -99,6 +106,16 @@ impl WorkUnit { } } + /// A unit that `stream` starts once a worker takes it, whose arrays an unordered pool passes + /// on as they are produced rather than once the unit is done. An ordered pool collects them, so + /// they must be in row order there. + pub fn stream(share: f64, stream: impl FnOnce() -> UnitStream + Send + 'static) -> Self { + Self { + kind: UnitKind::Stream(Box::new(stream)), + share, + } + } + /// A unit that `expand` turns into further units, in its place, once it is reached. pub fn expand(share: f64, expand: impl FnOnce() -> Expansion + Send + 'static) -> Self { Self { @@ -235,11 +252,25 @@ impl Shared { *self.taken.lock() += share; } - /// Takes a unit that runs, and starts it. + /// Takes a unit that runs, and starts it, returning all of its arrays at once. fn run(&self, unit: WorkUnit) -> UnitOutput { self.take(unit.share); match unit.kind { UnitKind::Run(run) => run(), + UnitKind::Stream(stream) => stream().try_collect::>().boxed(), + UnitKind::Expand(_) => unreachable!("expansions are not run"), + } + } + + /// Takes a unit that runs, and starts it, returning its arrays as they are produced. + fn stream(&self, unit: WorkUnit) -> UnitStream { + self.take(unit.share); + match unit.kind { + UnitKind::Run(run) => run() + .map_ok(|arrays| stream::iter(arrays.into_iter().map(Ok))) + .try_flatten_stream() + .boxed(), + UnitKind::Stream(stream) => stream(), UnitKind::Expand(_) => unreachable!("expansions are not run"), } } @@ -422,24 +453,6 @@ struct UnorderedPool { } impl UnorderedPool { - fn run(shared: &Arc, work: Work) -> UnitOutput { - match work { - Work::Unit(unit) => shared.run(unit), - Work::Expand(unit, slot) => { - let expansion = shared.expand(unit); - async move { - let expanded = expansion.await.map(|units| { - slot.shared.queue(&slot.sender, units); - Vec::new() - }); - drop(slot); - expanded - } - .boxed() - } - } - } - /// Starts the lanes, once. fn start_lanes(&self) { let mut lanes = self.lanes.lock(); @@ -461,53 +474,70 @@ impl UnorderedPool { } } -/// A lane: runs units one at a time and sends their rows to the workers, trimmed to a trimmed -/// limit and mapped. Ends once the units run out, a trimmed limit is spent, a unit fails, or the -/// pool is gone. +/// A lane: runs units one at a time and sends their rows to the workers as they are produced, +/// trimmed to a trimmed limit and mapped. Ends once the units run out, a trimmed limit is spent, a +/// unit fails, or the pool is gone. async fn lane(shared: Arc, units: Receiver, output: Sender>) { while !shared.limit.is_trimmed_out() && !shared.failed.load(Ordering::Acquire) { let Ok(work) = units.recv().await else { return; }; - let arrays = match UnorderedPool::run(&shared, work).await { - Ok(arrays) => arrays, - Err(err) => { - shared.failed.store(true, Ordering::Release); - drop(output.send(Err(err)).await); - return; + let mut arrays = match work { + Work::Unit(unit) => shared.stream(unit), + Work::Expand(unit, slot) => { + let expanded = shared.expand(unit).await; + // The expansion's units go into the channel before its slot passes on. + let expanded = expanded.map(|units| slot.shared.queue(&slot.sender, units)); + drop(slot); + match expanded { + Ok(()) => continue, + Err(err) => stream::once(future::ready(Err(err))).boxed(), + } } }; - for array in arrays { - if array.is_empty() { - continue; + while let Some(array) = arrays.next().await { + if !emit(&shared, &output, array).await { + return; } - let array = match &shared.limit { - PoolLimit::Trim(limit) => { - let granted = limit.take(array.len()); - if granted == 0 { - return; - } - let array = if granted < array.len() { - array.slice(0..granted) - } else { - Ok(array) - }; - match (array, &shared.map_trimmed) { - (Ok(array), Some(map)) => map(array).await, - (array, _) => array, - } - } - PoolLimit::Unlimited | PoolLimit::Reserve(_) => Ok(array), - }; - let failed = array.is_err(); - if failed { - shared.failed.store(true, Ordering::Release); + } + } +} + +/// Sends one of a lane's arrays to the workers, trimmed to a trimmed limit and mapped. Returns +/// whether the lane goes on: not once a trimmed limit is spent, the array is an error, a unit +/// failed elsewhere, or the workers are gone. +async fn emit( + shared: &Shared, + output: &Sender>, + array: VortexResult, +) -> bool { + if shared.failed.load(Ordering::Acquire) { + return false; + } + let array = match (array, &shared.limit) { + (Ok(array), _) if array.is_empty() => return true, + (Ok(array), PoolLimit::Trim(limit)) => { + let granted = limit.take(array.len()); + if granted == 0 { + return false; } - if output.send(array).await.is_err() || failed { - return; + let array = if granted < array.len() { + array.slice(0..granted) + } else { + Ok(array) + }; + match (array, &shared.map_trimmed) { + (Ok(array), Some(map)) => map(array).await, + (array, _) => array, } } + (array, _) => array, + }; + let failed = array.is_err(); + if failed { + shared.failed.store(true, Ordering::Release); } + output.send(array).await.is_ok() && !failed } impl ScanPool for UnorderedPool { diff --git a/vortex-scan/src/source/plan_pool.rs b/vortex-scan/src/source/plan_pool.rs index 8b77607dbf6..33e8a44b33b 100644 --- a/vortex-scan/src/source/plan_pool.rs +++ b/vortex-scan/src/source/plan_pool.rs @@ -8,10 +8,12 @@ //! a part is the rows between two of the child's splits for the fields the scan reads, such as a //! file's layout splits, else one of the scan's chunks. A root whose filter changes while the scan //! runs, as a top-N's bound does, prunes the child as a whole before it spawns parts; it reads -//! zone maps to do so, so it is an expansion instead. The pool spawns each part it runs onto the -//! session's runtime, where it is driven on a planning run of its own that awaits only its reads: -//! with a filter, the part's pruning plans first, continuing into the chunks of the rows pruning -//! kept; without, the chunks directly. +//! zone maps to do so, so it is an expansion instead. A part is driven on a planning run of its own +//! that awaits only its reads: with a filter, the part's pruning plans first, continuing into the +//! chunks of the rows pruning kept; without, the chunks directly. An unordered pool's lane runs the +//! part itself and passes each chunk on as it finishes, as a DuckDB thread of develop's V2 scan +//! does, so a top-N sees rows, and tightens its bound, before the part is done. An ordered pool's +//! worker spawns each part onto the session's runtime and returns its chunks in row order. //! //! Work creates work: expanding a deferred child, whether a file to open, a manifest entry or a //! table partition, yields the units of the children it expands into, which may be deferred in @@ -28,6 +30,8 @@ use std::ops::Range; use std::sync::Arc; use futures::FutureExt; +use futures::StreamExt; +use futures::stream; use vortex_array::scalar_fn::fns::dynamic::DynamicExprUpdates; use vortex_error::VortexExpect; use vortex_error::VortexResult; @@ -35,6 +39,7 @@ use vortex_error::vortex_bail; use vortex_io::request::IoService; use vortex_io::session::RuntimeSessionExt; use vortex_session::VortexSession; +use vortex_utils::parallelism::get_available_parallelism; use super::plan::DeferredPlanChild; use super::plan::PlanChild; @@ -50,6 +55,7 @@ use crate::pool::PoolLimit; use crate::pool::RowLimit; use crate::pool::ScanPoolRef; use crate::pool::UnitOutput; +use crate::pool::UnitStream; use crate::pool::WorkPoolOptions; use crate::pool::WorkUnit; use crate::pool::open_work_pool; @@ -85,11 +91,14 @@ pub(super) fn open(state: Arc, units: Vec) -> VortexResult, root: Box, share: f64, + ordered: bool, session: VortexSession, ) -> Expansion { async move { @@ -189,15 +199,20 @@ fn run_root( let part_rows = scope.rows.end - scope.rows.start; unassigned = unassigned.saturating_sub(part_rows); let child = Arc::clone(&child); - let session = session.clone(); - units.push(WorkUnit::run(per_row * part_rows as f64, move || { - // Another runtime thread may run the part while its lane waits, and its - // reads start right away. - session - .handle() - .spawn(run_part(child, scope, planner)) - .boxed() - })); + let part_share = per_row * part_rows as f64; + units.push(if ordered { + let session = session.clone(); + WorkUnit::run(part_share, move || { + // Another runtime thread runs the part while the worker drives its + // other parts, and its reads start right away. + session + .handle() + .spawn(run_part(child, scope, planner)) + .boxed() + }) + } else { + WorkUnit::stream(part_share, move || stream_part(child, scope, planner)) + }); } Progress::Batch(_) => vortex_bail!("a scan's root produced a batch"), Progress::RootDone(_) if run.live_roots() > 0 => {} @@ -213,6 +228,40 @@ fn run_root( .boxed() } +/// Runs a part on a planning run of its own, awaiting only its reads, and yields each of its +/// batches as it finishes, in whatever order their reads arrive. +fn stream_part( + child: Arc, + scope: WorkScope, + planner: Box, +) -> UnitStream { + let mut run = Run::new(); + run.admit(planner, scope, child.io.session()); + stream::unfold(Some((run, child)), |state| async move { + let (mut run, child) = state?; + loop { + let progress = match run.advance() { + Ok(progress) => progress, + Err(err) => return Some((Err(err), None)), + }; + match progress { + Progress::Batch(batch) => return Some((Ok(batch.array), Some((run, child)))), + Progress::Spawn(scope, planner) => { + run.admit(planner, scope, child.io.session()); + } + Progress::RootDone(_) if run.live_roots() > 0 => {} + Progress::RootDone(_) | Progress::Idle => return None, + Progress::Waiting => { + if let Err(err) = future::poll_fn(|cx| run.poll_completion(cx)).await { + return Some((Err(err), None)); + } + } + } + } + }) + .boxed() +} + /// Runs a part on a planning run of its own, awaiting only its reads, and returns its batches in /// row order. fn run_part(child: Arc, scope: WorkScope, planner: Box) -> UnitOutput { From da1011173eceee905398b3c039a593567efaba08 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Thu, 19 Nov 2026 22:08:46 -0500 Subject: [PATCH 3/8] Cover stream units when expanding Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-scan/src/pool/work.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vortex-scan/src/pool/work.rs b/vortex-scan/src/pool/work.rs index 3cb55b61b64..85706eb0032 100644 --- a/vortex-scan/src/pool/work.rs +++ b/vortex-scan/src/pool/work.rs @@ -283,7 +283,7 @@ impl Shared { } match unit.kind { UnitKind::Expand(expand) => expand(), - UnitKind::Run(_) => unreachable!("only expansions expand"), + UnitKind::Run(_) | UnitKind::Stream(_) => unreachable!("only expansions expand"), } } From 1f3f62280bdda9220d13b5fd6197b9752c15ef7d Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Thu, 19 Nov 2026 23:52:03 -0500 Subject: [PATCH 4/8] Keep a lane per core when one turn fills the pool A lane decodes its run's units on its own task, so a single-file V1 scan, whose one turn took every unit in flight, ran on one lane. Cap a run at in_flight per core. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-layout/src/scan/pool.rs | 3 ++- vortex-scan/src/pool/work.rs | 9 ++++++++- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/vortex-layout/src/scan/pool.rs b/vortex-layout/src/scan/pool.rs index b30a5b15344..01e52627c9f 100644 --- a/vortex-layout/src/scan/pool.rs +++ b/vortex-layout/src/scan/pool.rs @@ -7,7 +7,8 @@ //! file's splits are one [turn](WorkUnit::turn), so an unordered pool's lanes take runs of //! adjacent splits from every opened file in turn, polling each run's splits together so that //! their reads coalesce. With `open_concurrency` files open, a run is `1 / open_concurrency` of -//! the splits in flight. Opening a deferred file is an expansion that yields the file's turn, +//! the splits in flight, and at most the splits in flight per core, since a lane decodes its +//! run's splits on its own task. Opening a deferred file is an expansion that yields the file's turn, //! and at most `open_concurrency` opens are queued or running at once. An unordered pool runs //! splits and opens on the lane that takes them, which is already a task on the session's runtime; //! an ordered pool's worker spawns each onto the runtime. The diff --git a/vortex-scan/src/pool/work.rs b/vortex-scan/src/pool/work.rs index 8874889b3ac..5836e079470 100644 --- a/vortex-scan/src/pool/work.rs +++ b/vortex-scan/src/pool/work.rs @@ -253,7 +253,14 @@ pub fn open_work_pool(options: WorkPoolOptions, units: Vec) -> ScanPoo // then reach the source's read driver together and coalesce, as they do when one scan stream // polls its file's splits; a run of one would hand the driver one read at a time. The rotation // moves between turns after each run, and the lanes hold `in_flight` units in all. - let run = (in_flight / expand_concurrency).max(1); + // + // A lane polls its run's units on its own task, and their decoding and filtering run there + // too, so a run is at most `in_flight` divided by the cores: there is then a lane for every + // core, even when one turn, such as a single file, would otherwise take every unit in flight. + let cores = get_available_parallelism().unwrap_or(1).clamp(1, in_flight); + let run = (in_flight / expand_concurrency) + .min(in_flight / cores) + .max(1); let lanes = Arc::new(Lanes { shared: Arc::clone(&shared), units: receiver.clone(), From ab507716497df812729b00c570839499aea51151 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Thu, 19 Nov 2026 23:56:27 -0500 Subject: [PATCH 5/8] Spawn each V1 split of a run, as the foundation does Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-scan/src/pool/work.rs | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/vortex-scan/src/pool/work.rs b/vortex-scan/src/pool/work.rs index 5836e079470..f497edbec12 100644 --- a/vortex-scan/src/pool/work.rs +++ b/vortex-scan/src/pool/work.rs @@ -320,10 +320,17 @@ impl Shared { } } - /// Takes a unit that runs, and starts it, returning its arrays as they are produced. - fn stream(&self, unit: WorkUnit) -> UnitStream { + /// Takes a unit that runs, and starts it, returning its arrays as they are produced. With + /// `spawn`, a unit that returns all of its arrays at once runs as its own task on the runtime. + fn stream(&self, unit: WorkUnit, spawn: bool) -> UnitStream { self.take(unit.share); match unit.kind { + UnitKind::Run(run) if spawn => self + .handle + .spawn(run()) + .map_ok(|arrays| stream::iter(arrays.into_iter().map(Ok))) + .try_flatten_stream() + .boxed(), UnitKind::Run(run) => run() .map_ok(|arrays| stream::iter(arrays.into_iter().map(Ok))) .try_flatten_stream() @@ -637,11 +644,14 @@ async fn lane(lanes: Arc, output: Sender>) { lanes.grow(&output); let mut arrays = match taken { Taken::Run(mut units) if units.len() == 1 => { - shared.stream(units.pop().vortex_expect("a run of one unit")) + shared.stream(units.pop().vortex_expect("a run of one unit"), false) } - // The run's units are polled together, so their reads are registered together. + // The run's units start together, so their reads are registered together. A unit that + // returns its arrays at once, such as a V1 split, decodes inside its future, so each + // runs as its own task, as a scan stream spawns its splits, rather than all on this + // lane. A streaming unit, such as a V2 part, stays on the lane to pass on its chunks. Taken::Run(units) => { - stream::select_all(units.into_iter().map(|unit| shared.stream(unit))).boxed() + stream::select_all(units.into_iter().map(|unit| shared.stream(unit, true))).boxed() } Taken::Expand(unit, slot) => { let expanded = shared.expand(unit).await; From 52c19a98cad9d9a746a06ab50c3f408a90e7399c Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 09:38:56 -0500 Subject: [PATCH 6/8] Take V2 parts one at a time again Runs of adjacent units put a run of V2 parts on one lane's task, since a part streams its chunks from its lane, and capped the lanes at in_flight over the run: a table with few parts got a quarter of the lanes, each decoding four parts on one task. V2 parts already coalesce their chunks' reads within the part, so lanes take one part at a time, as before the runs. V1 keeps its runs and its single-file fix. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-layout/src/scan/pool.rs | 1 + vortex-scan/src/pool/work.rs | 21 ++++++++++++++++----- vortex-scan/src/source/plan_pool.rs | 8 +++++--- 3 files changed, 22 insertions(+), 8 deletions(-) diff --git a/vortex-layout/src/scan/pool.rs b/vortex-layout/src/scan/pool.rs index 01e52627c9f..3fb88bd86a0 100644 --- a/vortex-layout/src/scan/pool.rs +++ b/vortex-layout/src/scan/pool.rs @@ -253,6 +253,7 @@ pub(crate) fn open_pool( expand_concurrency: NonZeroUsize::new(options.open_concurrency) .unwrap_or(NonZeroUsize::MIN), map_trimmed: Some(map_trimmed), + runs: true, }, units, ) diff --git a/vortex-scan/src/pool/work.rs b/vortex-scan/src/pool/work.rs index f497edbec12..6b5be32ad0d 100644 --- a/vortex-scan/src/pool/work.rs +++ b/vortex-scan/src/pool/work.rs @@ -22,8 +22,8 @@ //! [turn](WorkUnit::turn), such as an opened file's splits or a child's parts, is one entry of //! the channel: the lane that takes it takes its next run of adjacent units, which it runs //! together so that their reads coalesce, and queues the rest again behind the other entries, -//! so the lanes rotate over the open turns. A run is the turn's share of `in_flight`, divided -//! among `expand_concurrency` turns. Each turn then has only a few units in flight, which keeps +//! so the lanes rotate over the open turns. With [runs](WorkPoolOptions::runs), a run is the +//! turn's share of `in_flight`, divided among `expand_concurrency` turns; without, one unit. Each turn then has only a few units in flight, which keeps //! its first rows, and any dynamic filter they tighten, ahead of its later units. A lane that expands a unit sends the units it yields back into the channel of units. At most `expand_concurrency` expansions //! are queued or running at once; each holds a slot that it passes on to the next waiting //! expansion when it is done, or when it is dropped. Workers only take rows from the output @@ -209,6 +209,12 @@ pub struct WorkPoolOptions { pub handle: Handle, /// The most expansions that are queued or running at once. pub expand_concurrency: NonZeroUsize, + /// Whether an unordered pool's lanes take a turn's adjacent units in runs, starting them + /// together so that their reads coalesce, or one at a time. Runs suit units that read little + /// each and return their arrays at once, which run as tasks of their own, such as V1 splits. + /// A unit that streams its arrays runs on its lane, so a run of them would share one task's + /// CPU, and a scan with few units would get few lanes. + pub runs: bool, /// Maps every array the workers return under a [trimmed](PoolLimit::Trim) limit, such as to /// optimize the array that the limit sliced. pub map_trimmed: Option, @@ -258,9 +264,13 @@ pub fn open_work_pool(options: WorkPoolOptions, units: Vec) -> ScanPoo // too, so a run is at most `in_flight` divided by the cores: there is then a lane for every // core, even when one turn, such as a single file, would otherwise take every unit in flight. let cores = get_available_parallelism().unwrap_or(1).clamp(1, in_flight); - let run = (in_flight / expand_concurrency) - .min(in_flight / cores) - .max(1); + let run = if options.runs { + (in_flight / expand_concurrency) + .min(in_flight / cores) + .max(1) + } else { + 1 + }; let lanes = Arc::new(Lanes { shared: Arc::clone(&shared), units: receiver.clone(), @@ -952,6 +962,7 @@ mod tests { handle: RUNTIME.0.handle(), expand_concurrency: NonZeroUsize::new(expand_concurrency).unwrap_or(NonZeroUsize::MIN), map_trimmed: None, + runs: true, } } diff --git a/vortex-scan/src/source/plan_pool.rs b/vortex-scan/src/source/plan_pool.rs index 08751fd0e90..1ea964c9c36 100644 --- a/vortex-scan/src/source/plan_pool.rs +++ b/vortex-scan/src/source/plan_pool.rs @@ -101,6 +101,10 @@ pub(super) fn open(state: Arc, units: Vec) -> VortexResult 0 { units.push(WorkUnit::skipped(per_row * unassigned as f64)); } - // An unordered pool's lanes take the child's parts in runs of adjacent parts, in turn with - // other children's. A part is a layout split, as a V1 split is, so a run's parts read - // adjacent segments, and polling them together lets their reads coalesce. + // An unordered pool's lanes take the child's parts in turn with other children's. Ok(vec![WorkUnit::turn(units)]) } .boxed() From 2e73095cd6d84a0087a704a18a1a6b6dab47c706 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 10:48:52 -0500 Subject: [PATCH 7/8] Take units in runs by their kind rather than a pool option Units that return their arrays at once, such as V1 splits, are taken in runs of adjacent units; units that stream their arrays, such as V2 parts, are taken alone, one per lane. Once a pool queues units of the first kind, its lanes are capped at in_flight over a run, so a pool mixing both kinds still keeps in_flight units, and lanes above the cap end. A skipped unit is an empty stream, so it never caps a pool of streaming units. Pools of either kind alone behave as before. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-layout/src/scan/pool.rs | 1 - vortex-scan/src/pool/work.rs | 161 +++++++++++++++++++--------- vortex-scan/src/source/plan_pool.rs | 4 - 3 files changed, 113 insertions(+), 53 deletions(-) diff --git a/vortex-layout/src/scan/pool.rs b/vortex-layout/src/scan/pool.rs index 3fb88bd86a0..01e52627c9f 100644 --- a/vortex-layout/src/scan/pool.rs +++ b/vortex-layout/src/scan/pool.rs @@ -253,7 +253,6 @@ pub(crate) fn open_pool( expand_concurrency: NonZeroUsize::new(options.open_concurrency) .unwrap_or(NonZeroUsize::MIN), map_trimmed: Some(map_trimmed), - runs: true, }, units, ) diff --git a/vortex-scan/src/pool/work.rs b/vortex-scan/src/pool/work.rs index 6b5be32ad0d..5e242057b3c 100644 --- a/vortex-scan/src/pool/work.rs +++ b/vortex-scan/src/pool/work.rs @@ -22,8 +22,9 @@ //! [turn](WorkUnit::turn), such as an opened file's splits or a child's parts, is one entry of //! the channel: the lane that takes it takes its next run of adjacent units, which it runs //! together so that their reads coalesce, and queues the rest again behind the other entries, -//! so the lanes rotate over the open turns. With [runs](WorkPoolOptions::runs), a run is the -//! turn's share of `in_flight`, divided among `expand_concurrency` turns; without, one unit. Each turn then has only a few units in flight, which keeps +//! so the lanes rotate over the open turns. A run of [units that run](WorkUnit::run) is the +//! turn's share of `in_flight`, divided among `expand_concurrency` turns; a +//! [streaming unit](WorkUnit::stream) is a run of its own. Each turn then has only a few units in flight, which keeps //! its first rows, and any dynamic filter they tighten, ahead of its later units. A lane that expands a unit sends the units it yields back into the channel of units. At most `expand_concurrency` expansions //! are queued or running at once; each holds a slot that it passes on to the next waiting //! expansion when it is done, or when it is dropped. Workers only take rows from the output @@ -147,7 +148,8 @@ impl WorkUnit { /// A unit with nothing to read, whose share is taken once a worker reaches it. pub fn skipped(share: f64) -> Self { - Self::run(share, || future::ready(Ok(Vec::new())).boxed()) + // A stream, so that it never makes a pool take its units in runs. + Self::stream(share, || stream::empty().boxed()) } /// The unit, or a turn's units, in its place. @@ -164,6 +166,12 @@ impl WorkUnit { fn is_expand(&self) -> bool { matches!(self.kind, UnitKind::Expand(_)) } + + /// Whether the unit runs to return all of its arrays at once, so that an unordered pool's + /// lanes take it in a run with the adjacent units that do too. + fn runs_at_once(&self) -> bool { + matches!(self.kind, UnitKind::Run(_)) + } } /// How a pool applies the scan's row limit. @@ -209,12 +217,6 @@ pub struct WorkPoolOptions { pub handle: Handle, /// The most expansions that are queued or running at once. pub expand_concurrency: NonZeroUsize, - /// Whether an unordered pool's lanes take a turn's adjacent units in runs, starting them - /// together so that their reads coalesce, or one at a time. Runs suit units that read little - /// each and return their arrays at once, which run as tasks of their own, such as V1 splits. - /// A unit that streams its arrays runs on its lane, so a run of them would share one task's - /// CPU, and a scan with few units would get few lanes. - pub runs: bool, /// Maps every array the workers return under a [trimmed](PoolLimit::Trim) limit, such as to /// optimize the array that the limit sliced. pub map_trimmed: Option, @@ -236,6 +238,7 @@ pub fn open_work_pool(options: WorkPoolOptions, units: Vec) -> ScanPoo handle: options.handle, failed: AtomicBool::new(false), pending: AtomicUsize::new(0), + runs_queued: AtomicBool::new(false), taken: Mutex::new(0.0), slots: Mutex::new(Slots { free: expand_concurrency, @@ -263,21 +266,23 @@ pub fn open_work_pool(options: WorkPoolOptions, units: Vec) -> ScanPoo // A lane polls its run's units on its own task, and their decoding and filtering run there // too, so a run is at most `in_flight` divided by the cores: there is then a lane for every // core, even when one turn, such as a single file, would otherwise take every unit in flight. + // + // Only units that return their arrays at once, such as V1 splits, run in runs: each runs as a + // task of its own. A unit that streams its arrays, such as a V2 part, runs on its lane, so a + // run of them would share one task's CPU, and it already keeps many reads in flight itself, + // so a lane takes one at a time, and the lanes hold `in_flight` of them. let cores = get_available_parallelism().unwrap_or(1).clamp(1, in_flight); - let run = if options.runs { - (in_flight / expand_concurrency) - .min(in_flight / cores) - .max(1) - } else { - 1 - }; + let run = (in_flight / expand_concurrency) + .min(in_flight / cores) + .max(1); let lanes = Arc::new(Lanes { shared: Arc::clone(&shared), units: receiver.clone(), run, - max: (in_flight / run).max(1), + max_runs: (in_flight / run).max(1), + max_units: in_flight, waiting: AtomicUsize::new(0), - started: AtomicUsize::new(0), + live: AtomicUsize::new(0), tasks: Mutex::new(Some(Vec::new())), }); Arc::new(UnorderedPool { @@ -302,6 +307,9 @@ struct Shared { failed: AtomicBool, /// The units of an unordered pool that are queued and not yet taken by a lane. pending: AtomicUsize, + /// Whether an unordered pool has queued a unit that runs to return its arrays at once, which + /// lanes take in runs. Once it has, the lanes are capped so that runs keep `in_flight` units. + runs_queued: AtomicBool, /// The share of the pool's work that workers have taken. taken: Mutex, /// An unordered pool's expansion slots. @@ -394,10 +402,14 @@ impl Shared { /// Sends an entry into an unordered pool's channel, counting the units it holds as pending. fn send(&self, sender: &Sender, work: Work) { - let units = match &work { - Work::Turn(units, _) => units.len(), - Work::Unit(_) | Work::Expand(..) => 1, + let (units, runs) = match &work { + Work::Turn(units, _) => (units.len(), units.iter().any(WorkUnit::runs_at_once)), + Work::Unit(unit) => (1, unit.runs_at_once()), + Work::Expand(..) => (1, false), }; + if runs && !self.runs_queued.load(Ordering::Acquire) { + self.runs_queued.store(true, Ordering::Release); + } self.pending.fetch_add(units, Ordering::AcqRel); send(sender, work); } @@ -540,30 +552,49 @@ fn send(sender: &Sender, work: Work) { } /// The lanes of an unordered pool. They start when its first worker does, as many as there are -/// units ready, and grow while units wait for a lane, up to `in_flight`, so a scan with few units -/// spawns and wakes few tasks. +/// units ready, and grow while units wait for a lane, up to `in_flight` units, so a scan with few +/// units spawns and wakes few tasks. struct Lanes { shared: Arc, units: Receiver, - /// The most adjacent units of a turn that a lane takes and runs together. + /// The most adjacent units of a turn that a lane takes and runs together, when they return + /// their arrays at once. run: usize, - /// The most lanes that run at once, so that they run `in_flight` units in all. - max: usize, + /// The most lanes that run at once once the pool has queued units that run in runs, so that + /// they run `in_flight` units in all. + max_runs: usize, + /// The most lanes that run at once while every unit is taken alone: `in_flight`. + max_units: usize, /// Lanes waiting for a unit. waiting: AtomicUsize, - /// Lanes started, so a lane can see without a lock that no more may start. - started: AtomicUsize, + /// Lanes running, so a lane can see without a lock that no more may start, or that it is + /// beyond the cap. + live: AtomicUsize, /// The lanes started, until the pool is dropped, which aborts them. `None` once it is. tasks: Mutex>>>, } impl Lanes { - /// Starts lanes for the units that no waiting lane will take, up to `in_flight` in all. Each - /// lane holds a sender of the output channel. + /// The most lanes that run at once, so that they run at most `in_flight` units in all, and + /// the most units a lane takes at once. + /// + /// Each lane takes at most a run, so once the pool has queued units that run in runs, the + /// lanes are capped at `in_flight` divided by a run, even when other units are taken alone. + /// Until then, each lane takes one unit, and up to `in_flight` lanes run. + fn cap(&self) -> (usize, usize) { + if self.shared.runs_queued.load(Ordering::Acquire) { + (self.max_runs, self.run) + } else { + (self.max_units, 1) + } + } + + /// Starts lanes for the units that no waiting lane will take, up to the cap. Each lane holds a + /// sender of the output channel. fn grow(self: &Arc, output: &Sender>) { // Every lane calls this for every unit it takes, so it locks only to start lanes. - let max = self.max; - if self.started.load(Ordering::Acquire) >= max || self.unserved() == 0 { + let (max, per_lane) = self.cap(); + if self.live.load(Ordering::Acquire) >= max || self.unserved(per_lane) == 0 { return; } let mut tasks = self.tasks.lock(); @@ -571,27 +602,39 @@ impl Lanes { return; }; let new = self - .unserved() - .div_ceil(self.run) - .min(max.saturating_sub(tasks.len())); + .unserved(per_lane) + .div_ceil(per_lane) + .min(max.saturating_sub(self.live.load(Ordering::Acquire))); if new == 0 { return; } + self.live.fetch_add(new, Ordering::AcqRel); tasks.extend((0..new).map(|_| { self.shared .handle .spawn(lane(Arc::clone(self), output.clone())) })); - self.started.store(tasks.len(), Ordering::Release); + } + + /// Stops counting a lane that is beyond the cap, which a pool lowers once it queues units + /// that run in runs after its lanes started for units taken alone. Returns whether it did, in + /// which case the lane ends. The lanes left are never fewer than the cap. + fn leave_if_beyond_cap(&self) -> bool { + let (max, _) = self.cap(); + self.live + .try_update(Ordering::AcqRel, Ordering::Acquire, |live| { + live.checked_sub(1).filter(|_| live > max) + }) + .is_ok() } /// The pending units that the lanes waiting for one will not take, each of which takes up - /// to a run. - fn unserved(&self) -> usize { + /// to `per_lane` units. + fn unserved(&self, per_lane: usize) -> usize { self.shared .pending .load(Ordering::Acquire) - .saturating_sub(self.waiting.load(Ordering::Acquire) * self.run) + .saturating_sub(self.waiting.load(Ordering::Acquire) * per_lane) } } @@ -619,19 +662,41 @@ impl UnorderedPool { /// A lane: runs units one at a time and sends their rows to the workers as they are produced, /// trimmed to a trimmed limit and mapped. Ends once the units run out, a trimmed limit is spent, a -/// unit fails, or the pool is gone. +/// unit fails, the pool is gone, or it is beyond the lanes' cap. async fn lane(lanes: Arc, output: Sender>) { + if !run_lane(&lanes, output).await { + lanes.live.fetch_sub(1, Ordering::AcqRel); + } +} + +/// Runs a lane until it ends. Returns whether it ended beyond the cap, which already stopped +/// counting it. +async fn run_lane(lanes: &Lanes, output: Sender>) -> bool { let shared = Arc::clone(&lanes.shared); while !shared.limit.is_trimmed_out() && !shared.failed.load(Ordering::Acquire) { + if lanes.leave_if_beyond_cap() { + return true; + } lanes.waiting.fetch_add(1, Ordering::AcqRel); let work = lanes.units.recv().await; lanes.waiting.fetch_sub(1, Ordering::AcqRel); let Ok(work) = work else { - return; + return false; }; let taken = match work { Work::Turn(mut units, sender) => { - let run: Vec<_> = units.drain(..lanes.run.min(units.len())).collect(); + // Adjacent units that return their arrays at once are taken in a run; a unit that + // streams them is taken alone. + let len = if units.front().is_some_and(WorkUnit::runs_at_once) { + units + .iter() + .take(lanes.run) + .take_while(|unit| unit.runs_at_once()) + .count() + } else { + units.len().min(1) + }; + let run: Vec<_> = units.drain(..len).collect(); if run.is_empty() { continue; } @@ -656,10 +721,10 @@ async fn lane(lanes: Arc, output: Sender>) { Taken::Run(mut units) if units.len() == 1 => { shared.stream(units.pop().vortex_expect("a run of one unit"), false) } - // The run's units start together, so their reads are registered together. A unit that - // returns its arrays at once, such as a V1 split, decodes inside its future, so each - // runs as its own task, as a scan stream spawns its splits, rather than all on this - // lane. A streaming unit, such as a V2 part, stays on the lane to pass on its chunks. + // The run's units start together, so their reads are registered together. Each + // returns its arrays at once, such as a V1 split, and decodes inside its future, so + // each runs as its own task, as a scan stream spawns its splits, rather than all on + // this lane. Taken::Run(units) => { stream::select_all(units.into_iter().map(|unit| shared.stream(unit, true))).boxed() } @@ -676,10 +741,11 @@ async fn lane(lanes: Arc, output: Sender>) { }; while let Some(array) = arrays.next().await { if !emit(&shared, &output, array).await { - return; + return false; } } } + false } /// Sends one of a lane's arrays to the workers, trimmed to a trimmed limit and mapped. Returns @@ -962,7 +1028,6 @@ mod tests { handle: RUNTIME.0.handle(), expand_concurrency: NonZeroUsize::new(expand_concurrency).unwrap_or(NonZeroUsize::MIN), map_trimmed: None, - runs: true, } } diff --git a/vortex-scan/src/source/plan_pool.rs b/vortex-scan/src/source/plan_pool.rs index 1ea964c9c36..94713a1abdb 100644 --- a/vortex-scan/src/source/plan_pool.rs +++ b/vortex-scan/src/source/plan_pool.rs @@ -101,10 +101,6 @@ pub(super) fn open(state: Arc, units: Vec) -> VortexResult Date: Fri, 20 Nov 2026 10:56:04 -0500 Subject: [PATCH 8/8] Pass the lane's Arc to run_lane so it can grow lanes Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-scan/src/pool/work.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vortex-scan/src/pool/work.rs b/vortex-scan/src/pool/work.rs index 5e242057b3c..d5bf264098d 100644 --- a/vortex-scan/src/pool/work.rs +++ b/vortex-scan/src/pool/work.rs @@ -671,7 +671,7 @@ async fn lane(lanes: Arc, output: Sender>) { /// Runs a lane until it ends. Returns whether it ended beyond the cap, which already stopped /// counting it. -async fn run_lane(lanes: &Lanes, output: Sender>) -> bool { +async fn run_lane(lanes: &Arc, output: Sender>) -> bool { let shared = Arc::clone(&lanes.shared); while !shared.limit.is_trimmed_out() && !shared.failed.load(Ordering::Acquire) { if lanes.leave_if_beyond_cap() {