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 f345e908c0a..01e52627c9f 100644 --- a/vortex-layout/src/scan/pool.rs +++ b/vortex-layout/src/scan/pool.rs @@ -1,93 +1,71 @@ // 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. Its splits -//! run as tasks on the session's runtime, at most `splits_in_flight` at once across the whole -//! pool; 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. An opened +//! 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, 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 +//! [pool](vortex_scan::pool::open_work_pool) 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: //! -//! - A scan with a filter and a limit builds each split on a CPU thread only once it is taken -//! to run ([`spawn_lazy_split`]), so no new split starts once the limit is spent, and optimizes the +//! - A scan with a filter and a limit builds each split on a CPU thread only once a worker takes +//! it ([`spawn_lazy_split`]), so no new split starts once the limit is spent, and optimizes the //! rows the limit keeps on a second CPU task ([`spawn_map_trimmed`]). -//! - Every other scan builds all of a file's split tasks together, when the first of them is -//! taken, so the file's reads are registered at once and can coalesce. A limit is reserved +//! - 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 the work: -//! -//! - An unordered pool runs lanes on the runtime once its first worker starts: one for each run -//! of splits or open that is ready, more as they queue, and at most enough to keep -//! `splits_in_flight` splits running. Each lane takes the next unit from a channel of units, -//! runs it, and sends its rows into one bounded output channel. An opened file is one unit, its -//! turn, which a lane queues again after taking the file's next run of adjacent splits, so the -//! lanes read the opened files in turn, a run at a time, and poll each run's splits together so -//! that their reads coalesce. A lane that opens a deferred file queues the file's turn, followed -//! by the next deferred file. Workers only take rows from the output channel, so whichever -//! worker asks next gets the next rows, however many workers there are, and the number of -//! workers is only the host's parallelism. The output channel closes once every lane has -//! finished, which ends the workers. -//! - An ordered pool gives all of its units, in row order, to its first worker, which keeps -//! `splits_in_flight` of them running at once; later workers get nothing. Parallel ordered reads -//! cut the scan with `split` first. use std::any::Any; -use std::collections::VecDeque; -use std::iter; use std::num::NonZeroUsize; use std::ops::Range; use std::sync::Arc; -use std::sync::atomic::AtomicBool; -use std::sync::atomic::AtomicUsize; -use std::sync::atomic::Ordering; -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 futures::stream::FuturesUnordered; 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::runtime::Handle; -use vortex_io::runtime::Task; use vortex_io::session::RuntimeSessionExt; 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 vortex_utils::parallelism::get_available_parallelism; 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::recheck_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; @@ -213,7 +191,7 @@ pub(crate) struct PoolOptions { pub(crate) limit: Option, /// Whether the scan filters rows, so a split's output row count is unknown up front. pub(crate) has_filter: bool, - /// The request's bound on the splits each worker keeps in flight. + /// The request's bound on the splits the pool keeps in flight. pub(crate) split_concurrency: Option, /// The most deferred files that are queued or being opened at once. pub(crate) open_concurrency: usize, @@ -230,140 +208,74 @@ pub(crate) fn open_pool( Some(limit) if options.has_filter => PoolLimit::Trim(RowLimit::new(limit)), Some(limit) => PoolLimit::Reserve(RowLimit::new(limit)), }; - // The pool keeps as many splits in flight as one scan stream does by default: four per core, - // at most the request's `split_concurrency`, however many workers read it. The runtime's - // threads decode them, so more in flight would only read further ahead, and the file's - // registered reads already let I/O coalesce ahead of the splits being decoded. - 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()), - failed: AtomicBool::new(false), - pending: AtomicUsize::new(0), + session: options.session.clone(), + spawn: options.ordered, }); - 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) => shared.queue_file(&sender, work), - PoolFile::Deferred(factory) if opens < open_concurrency => { - opens += 1; - let slot = OpenSlot { - shared: Arc::clone(&shared), - sender: sender.clone(), - }; - shared.queue(&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), } } - // Each open file gets an equal share of the splits in flight, and a lane takes a file's share - // as one run of adjacent splits that it starts together. The run's reads then reach the - // file'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 files after each run, and the lanes hold `splits_in_flight` splits in all. A run is - // at most one core's share, so that a scan of few files, such as a single-file scan whose - // share is every split in flight, still has a lane per core. - let cores = get_available_parallelism().unwrap_or(1).max(1); - let run = (splits_in_flight / open_concurrency) - .min(splits_in_flight / cores) - .max(1); - let (output, outputs) = async_channel::bounded(splits_in_flight); - let lanes = Arc::new(Lanes { - shared: Arc::clone(&shared), - units: receiver.clone(), - run, - max: (splits_in_flight / run).max(1), - waiting: AtomicUsize::new(0), - started: AtomicUsize::new(0), - tasks: Mutex::new(Some(Vec::new())), + // A limit's trimmed arrays are optimized again, on a CPU task, as `execute_stream` does. + let handle = options.session.handle(); + let map_handle = handle.clone(); + let session = options.session; + let identity: MapFn = Arc::new(Ok); + let map_trimmed: MapOutput = Arc::new(move |array| { + spawn_map_trimmed( + &map_handle, + session.clone(), + Arc::clone(&identity), + Ok(array), + ) + .boxed() }); - Arc::new(UnorderedPool { - dtype: options.dtype, - shared, - units: receiver, - outputs, - lanes, - output: Mutex::new(Some(output)), - }) -} - -/// 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 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 { + open_work_pool( + WorkPoolOptions { + dtype: options.dtype, + ordered: options.ordered, + limit, + // The pool keeps as many splits in flight as one scan stream does: four per core, at + // most the request's `split_concurrency`. + split_concurrency: options.split_concurrency, + handle, + expand_concurrency: NonZeroUsize::new(options.open_concurrency) + .unwrap_or(NonZeroUsize::MIN), + map_trimmed: Some(map_trimmed), + }, + units, + ) +} + +/// 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>>, - /// Whether a unit of an unordered pool failed, which stops its lanes. - failed: AtomicBool, - /// The splits and opens of an unordered pool that are queued and not yet taken by a lane. - pending: AtomicUsize, + /// Whether splits and opens are spawned onto the runtime: an ordered pool's worker runs on the + /// host's thread, while an unordered pool's lane is already a task on the runtime, where + /// spawning would only add a hop. + spawn: bool, } -impl Shared { - /// The splits of an opened file, in row order. - fn file_splits(&self, work: FileWork) -> Vec { +impl Files { + /// The turn 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 @@ -371,69 +283,55 @@ 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; - (0..file.ranges.len()) + let per_row = share / rows as f64; + let splits = (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() + .collect(); + vec![WorkUnit::turn(splits)] } - /// Opens a deferred file into its work, on the task that polls it. 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); - async move { + /// Opens a deferred file into the turn of its splits. + fn open(self: &Arc, factory: Arc, share: f64) -> Expansion { + let files = Arc::clone(self); + let opened = async move { let reader = factory .open() .instrument(tracing::info_span!("LayoutReaderFactory::open")) .await?; - match (reader, &shared.prepare) { + match (reader, &files.prepare) { (Some(reader), Some(prepare)) => prepare(reader), _ => Ok(FileWork::empty()), } - } - .boxed() + }; + let opened = if self.spawn { + self.session.handle().spawn(opened).boxed() + } else { + opened.boxed() + }; + let files = Arc::clone(self); + async move { Ok(files.units(opened.await?, share)) }.boxed() } - /// Opens a deferred file into its work as a task on the session's runtime. - fn spawn_open_file( + /// Runs a split. A split of a scan with a filter and a limit is built and run as + /// [`spawn_lazy_split`] runs it; any other split runs on the session's runtime when splits are + /// spawned, or else on the task that polls it. + fn admit( self: &Arc, - factory: Arc, - ) -> BoxFuture<'static, VortexResult> { - if self.limit.is_spent() { - return future::ready(Ok(FileWork::empty())).boxed(); - } - self.session.handle().spawn(self.open_file(factory)).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() - } - - /// Takes a split. A split of a scan with a filter and a limit is built and run as - /// [`spawn_lazy_split`] runs it; any other split runs as a task on the session's runtime, since - /// a split decodes inside its future. - fn admit(self: &Arc, (file, index, progress): FileSplit) -> SplitOutput { - *self.progress.lock() += progress; + 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 { @@ -447,447 +345,21 @@ impl Shared { } .boxed(); } - let shared = Arc::clone(self); + let files = Arc::clone(self); async move { let task = file - .tasks(&shared.limit) + .tasks(&files.limit) .await? .get(index) .and_then(|task| task.lock().take()); match task { - Some(task) => handle.spawn(task).await, + Some(task) if files.spawn => handle.spawn(task).await, + Some(task) => task.await, None => Ok(None), } } .boxed() } - - /// Queues a unit of an unordered pool, counting the splits or open it holds as pending. - fn queue(&self, sender: &Sender, work: Work) { - let units = match &work { - Work::File(splits, _) => splits.len(), - Work::Open(..) => 1, - }; - self.pending.fetch_add(units, Ordering::AcqRel); - send(sender, work); - } - - /// Queues an opened file of an unordered pool as one turn among the files. - fn queue_file(&self, sender: &Sender, work: FileWork) { - let splits: VecDeque = self.file_splits(work).into(); - if !splits.is_empty() { - self.queue(sender, Work::File(splits, sender.clone())); - } - } - - fn progress(&self) -> f64 { - if self.limit.is_trimmed_out() { - return 1.0; - } - self.progress.lock().clamp(0.0, 1.0) - } - - /// An ordered 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>>, - 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) - }); - stop_on_error(mapped.buffered(splits_in_flight).boxed()) - } -} - -/// 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's channel. -enum Work { - /// An opened file's turn: the splits not yet taken, in row order. The lane that takes the - /// turn takes the file's next run of splits and queues the turn again behind the other - /// files' turns, so the lanes take runs from every opened file in turn rather than from one - /// file after another. Each file then has only a few splits in flight, which keeps its first rows, and - /// any dynamic filter they tighten, ahead of its later splits. - File(VecDeque, Sender), - /// A deferred file, and the open slot it holds until its turn is in the channel. - Open(Arc, OpenSlot), -} - -/// What a lane takes from a unit. -enum Taken { - /// A run of a file's adjacent splits, in row order. - Splits(Vec), - Open(Arc, OpenSlot), -} - -impl Taken { - /// The pending splits or open that this takes. - fn units(&self) -> usize { - match self { - Taken::Splits(splits) => splits.len(), - Taken::Open(..) => 1, - } - } -} - -impl Work { - /// Takes the unit's next `run` splits, or its open, queueing a file's turn again while it - /// has splits left. - fn take(self, run: usize) -> Option { - match self { - Work::File(mut splits, sender) => { - let taken: Vec<_> = splits.drain(..run.min(splits.len())).collect(); - if !splits.is_empty() { - let requeue = sender.clone(); - send(&requeue, Work::File(splits, sender)); - } - (!taken.is_empty()).then_some(Taken::Splits(taken)) - } - Work::Open(factory, slot) => Some(Taken::Open(factory, slot)), - } - } -} - -/// 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 turns already in the channel, - /// 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(), - }; - self.shared.queue(&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)); -} - -/// The lanes of an unordered pool. They start when its first worker does, as many as there are -/// splits and opens ready, and grow while those wait for a lane, up to `splits_in_flight`, so a -/// scan with few units spawns and wakes few tasks. -struct Lanes { - shared: Arc, - units: Receiver, - /// The most adjacent splits of a file that a lane takes and polls together. - run: usize, - /// The most lanes that run at once. - max: 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, - /// 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 the most that run at - /// once. 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. - if self.started.load(Ordering::Acquire) >= self.max || self.unserved() == 0 { - return; - } - let mut tasks = self.tasks.lock(); - let Some(tasks) = tasks.as_mut() else { - return; - }; - let new = self - .unserved() - .div_ceil(self.run) - .min(self.max.saturating_sub(tasks.len())); - if new == 0 { - return; - } - let handle = self.shared.session.handle(); - tasks.extend((0..new).map(|_| handle.spawn(lane(Arc::clone(self), output.clone())))); - self.started.store(tasks.len(), Ordering::Release); - } - - /// The pending splits and opens that the lanes waiting for a unit will not take, each of - /// which takes up to a run. - fn unserved(&self) -> usize { - self.shared - .pending - .load(Ordering::Acquire) - .saturating_sub(self.waiting.load(Ordering::Acquire) * self.run) - } -} - -/// A pool whose lanes run its units on the runtime, and whose workers share their output. -struct UnorderedPool { - dtype: DType, - shared: Arc, - units: Receiver, - outputs: Receiver>, - lanes: Arc, - /// The sender of the output channel until the first worker starts the lanes, which hold it - /// from then on. - output: Mutex>>>, -} - -impl UnorderedPool { - /// Runs a unit for the lane that took it. Each split of a run runs as a task of its own, as - /// [`RepeatedScan::execute_stream`] runs it, since a split decodes inside its future: the run's - /// splits start together, so their reads coalesce, and decode on as many threads as there - /// are splits. An open runs on the lane itself. - fn run(shared: &Arc, taken: Taken) -> FuturesUnordered { - match taken { - Taken::Splits(splits) => splits - .into_iter() - .map(|split| shared.admit(split)) - .collect(), - Taken::Open(factory, slot) => iter::once( - async move { - let opened = slot.shared.open_file(factory).await.map(|work| { - slot.shared.queue_file(&slot.sender, work); - None - }); - drop(slot); - opened - } - .boxed(), - ) - .collect(), - } - } - - /// Starts the lanes, once. With no units, it starts none, and the output channel closes. - fn start_lanes(&self) { - // Dropping the pool's own sender leaves the lanes holding the output channel open. - if let Some(output) = self.output.lock().take() { - self.lanes.grow(&output); - } - } -} - -/// A lane: runs units one at a time and sends their rows to the workers, trimming them to a -/// trimmed limit. Ends once the units run out, a limit is spent, a unit fails, or every worker -/// is gone. -async fn lane(lanes: Arc, output: Sender>) { - let shared = Arc::clone(&lanes.shared); - let handle = shared.session.handle(); - let identity: MapFn = Arc::new(Ok); - while !shared.limit.is_trimmed_out() && !shared.failed.load(Ordering::Acquire) { - 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; - }; - let Some(taken) = work.take(lanes.run) else { - continue; - }; - shared.pending.fetch_sub(taken.units(), Ordering::AcqRel); - // Units the waiting lanes will not take get lanes of their own, such as the splits an - // open has just queued. - lanes.grow(&output); - let mut running = UnorderedPool::run(&shared, taken); - while let Some(array) = running.next().await { - let array = match array { - Ok(Some(array)) => Ok(array), - Ok(None) => continue, - Err(err) => Err(err), - }; - if !emit(&shared, &handle, &identity, &output, array).await { - return; - } - } - } -} - -/// Sends a lane's rows to the workers, trimmed to a trimmed limit. Returns whether the lane -/// should go on: not once the limit is spent, a unit failed, or every worker is gone. -async fn emit( - shared: &Shared, - handle: &Handle, - identity: &MapFn, - output: &Sender>, - array: VortexResult, -) -> bool { - let array = match (&shared.limit, array) { - (PoolLimit::Trim(limit), Ok(array)) => { - let granted = limit.take(array.len()); - if granted == 0 { - return false; - } - let array = if granted < array.len() { - array.slice(0..granted) - } else { - Ok(array) - }; - spawn_map_trimmed(handle, shared.session.clone(), Arc::clone(identity), array).await - } - (_, 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 { - fn dtype(&self) -> &DType { - &self.dtype - } - - fn worker(self: Arc) -> SendableArrayStream { - self.start_lanes(); - let dtype = self.dtype.clone(); - // The worker holds the pool, so the lanes run until the pool's last worker is dropped. - let arrays = stream::unfold(self, |pool| async move { - let array = pool.outputs.recv().await.ok()?; - Some((array, pool)) - }) - .boxed(); - ArrayStreamExt::boxed(ArrayStreamAdapter::new(dtype, stop_on_error(arrays))) - } - - fn progress(&self) -> f64 { - if self.is_exhausted() { - return 1.0; - } - self.shared.progress() - } - - fn is_exhausted(&self) -> bool { - // The lanes hold the output channel's senders, so it closes once every lane has ended. - self.outputs.is_closed() && self.outputs.is_empty() - } -} - -impl Drop for UnorderedPool { - fn drop(&mut self) { - // Pending opens hold senders of the channel of units itself; drain them so it can be - // freed. The lanes are aborted when they are dropped. - self.units.close(); - while self.units.try_recv().is_ok() {} - self.outputs.close(); - drop(self.lanes.tasks.lock().take()); - } -} - -/// 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.spawn_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, 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 004817d8c4f..b3a929293e9 100644 --- a/vortex-scan/src/pool.rs +++ b/vortex-scan/src/pool/mod.rs @@ -29,6 +29,18 @@ 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::UnitStream; +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..d5bf264098d --- /dev/null +++ b/vortex-scan/src/pool/work.rs @@ -0,0 +1,1126 @@ +// 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. +//! +//! Workers share the output, not the work. A pool keeps up to `in_flight` units running at once, +//! however many workers read it: four per core, at most the request's `split_concurrency`, as one +//! scan stream does. The number of workers is only the host's parallelism. +//! +//! - An unordered pool runs lanes on the session's runtime once its first worker starts: one for +//! each run of units that is ready, more as units queue, and at most enough to keep `in_flight` +//! units running; a pool with no units +//! starts none. Each lane takes the next unit from a channel of units, runs it on the lane +//! itself, and sends its rows, trimmed to a trimmed limit, into one bounded output channel. A +//! [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 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 +//! channel, so whichever worker asks next gets the next rows. The output channel closes once +//! every lane has ended, which ends the workers. An error stops every lane, dropping a worker +//! gives up nothing, and dropping the pool aborts the lanes. +//! - An ordered pool gives all of its units, in row order, to its first worker, which keeps +//! `in_flight` of them running at once and 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. + +use std::collections::VecDeque; +use std::num::NonZeroUsize; +use std::sync::Arc; +use std::sync::atomic::AtomicBool; +use std::sync::atomic::AtomicUsize; +use std::sync::atomic::Ordering; +use std::task::Poll; + +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; +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::VortexExpect; +use vortex_error::VortexResult; +use vortex_io::runtime::Handle; +use vortex_io::runtime::Task; +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 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>>; + +/// Maps each array of a trimmed limit's pool once it is trimmed. +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 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>), + /// Units taken in turn with the other turns of an unordered pool, in row order. + Turn(Vec), +} + +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 `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 { + kind: UnitKind::Expand(Box::new(expand)), + share, + } + } + + /// Units, in row order, that an unordered pool's lanes take one at a time, in turn with its + /// other turns, rather than all at once: a file's splits, or a child's parts. An ordered pool + /// reads them in their place. Expansions among them are queued on their own. + pub fn turn(units: Vec) -> Self { + Self { + share: units.iter().map(|unit| unit.share).sum(), + kind: UnitKind::Turn(units), + } + } + + /// A unit with nothing to read, whose share is taken once a worker reaches it. + pub fn skipped(share: f64) -> Self { + // 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. + fn in_place(self) -> Vec { + match self.kind { + UnitKind::Turn(units) => units.into_iter().flat_map(WorkUnit::in_place).collect(), + kind => vec![Self { + kind, + share: self.share, + }], + } + } + + 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. +#[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 the pool keeps in flight. + pub split_concurrency: Option, + /// The runtime that an unordered pool's lanes run on. + pub handle: Handle, + /// 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, + 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, + 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); + let (output, outputs) = async_channel::bounded(in_flight); + // Each turn being expanded or read gets an equal share of the units in flight, and a lane + // takes a turn's share as one run of adjacent units that it runs together. The run's reads + // 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. + // + // 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 = (in_flight / expand_concurrency) + .min(in_flight / cores) + .max(1); + let lanes = Arc::new(Lanes { + shared: Arc::clone(&shared), + units: receiver.clone(), + run, + max_runs: (in_flight / run).max(1), + max_units: in_flight, + waiting: AtomicUsize::new(0), + live: AtomicUsize::new(0), + tasks: Mutex::new(Some(Vec::new())), + }); + Arc::new(UnorderedPool { + dtype: options.dtype, + shared, + units: receiver, + outputs, + lanes, + output: Mutex::new(Some(output)), + }) +} + +/// What every worker of a pool shares. +struct Shared { + limit: PoolLimit, + map_trimmed: Option, + /// The units the pool keeps in flight. + in_flight: usize, + /// The runtime that an unordered pool's lanes run on. + handle: Handle, + /// Whether a unit of an unordered pool failed, which stops its lanes. + 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. + 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, 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(_) | UnitKind::Turn(_) => unreachable!("only units that run are run"), + } + } + + /// 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() + .boxed(), + UnitKind::Stream(stream) => stream(), + UnitKind::Expand(_) | UnitKind::Turn(_) => unreachable!("only units that run are 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(_) | UnitKind::Stream(_) | UnitKind::Turn(_) => { + 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 { + match unit.kind { + UnitKind::Turn(units) => { + let (expansions, units): (Vec<_>, Vec<_>) = + units.into_iter().partition(WorkUnit::is_expand); + if !units.is_empty() { + self.send(sender, Work::Turn(units.into(), sender.clone())); + } + self.queue(sender, expansions); + } + UnitKind::Expand(_) => { + let mut slots = self.slots.lock(); + if slots.free > 0 { + slots.free -= 1; + drop(slots); + self.send(sender, Work::Expand(unit, Slot::new(self, sender))); + } else { + slots.waiting.push_back(unit); + } + } + UnitKind::Run(_) | UnitKind::Stream(_) => self.send(sender, Work::Unit(unit)), + } + } + } + + /// 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, 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); + } + + /// 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) + } + + /// An ordered 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>>, + ) -> 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(), + }); + stop_on_error(mapped.buffered(self.in_flight).boxed()) + } + _ => 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() +} + +/// What a lane takes from an entry of an unordered pool's channel. +enum Taken { + /// Units that run together: a run of a turn's adjacent units, or one unit. + Run(Vec), + /// An expansion, and its slot. + Expand(WorkUnit, Slot), +} + +/// An entry of an unordered pool's channel. +enum Work { + Unit(WorkUnit), + /// A turn's units not yet taken, in row order, and the channel to queue the rest into once a + /// lane takes the next of them. + Turn(VecDeque, Sender), + /// 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); + self.shared.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)); +} + +/// 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` 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, when they return + /// their arrays at once. + run: 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 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 { + /// 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, per_lane) = self.cap(); + if self.live.load(Ordering::Acquire) >= max || self.unserved(per_lane) == 0 { + return; + } + let mut tasks = self.tasks.lock(); + let Some(tasks) = tasks.as_mut() else { + return; + }; + let new = self + .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())) + })); + } + + /// 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 `per_lane` units. + fn unserved(&self, per_lane: usize) -> usize { + self.shared + .pending + .load(Ordering::Acquire) + .saturating_sub(self.waiting.load(Ordering::Acquire) * per_lane) + } +} + +/// A pool whose lanes run its units on the runtime, and whose workers share their output. +struct UnorderedPool { + dtype: DType, + shared: Arc, + units: Receiver, + outputs: Receiver>, + lanes: Arc, + /// The sender of the output channel until the first worker starts the lanes, which hold it + /// from then on. + output: Mutex>>>, +} + +impl UnorderedPool { + /// Starts the lanes, once. With no units, it starts none, and the output channel closes. + fn start_lanes(&self) { + // Dropping the pool's own sender leaves the lanes holding the output channel open. + if let Some(output) = self.output.lock().take() { + self.lanes.grow(&output); + } + } +} + +/// 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, 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: &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() { + 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 false; + }; + let taken = match work { + Work::Turn(mut units, sender) => { + // 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; + } + if !units.is_empty() { + let requeue = sender.clone(); + send(&requeue, Work::Turn(units, sender)); + } + Taken::Run(run) + } + Work::Unit(unit) => Taken::Run(vec![unit]), + Work::Expand(unit, slot) => Taken::Expand(unit, slot), + }; + let units = match &taken { + Taken::Run(units) => units.len(), + Taken::Expand(..) => 1, + }; + shared.pending.fetch_sub(units, Ordering::AcqRel); + // Units the waiting lanes will not take get lanes of their own, such as the units an + // expansion has just queued. + 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"), false) + } + // 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() + } + Taken::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(), + } + } + }; + while let Some(array) = arrays.next().await { + if !emit(&shared, &output, array).await { + return false; + } + } + } + false +} + +/// 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; + } + 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 { + fn dtype(&self) -> &DType { + &self.dtype + } + + fn worker(self: Arc) -> SendableArrayStream { + self.start_lanes(); + let dtype = self.dtype.clone(); + // The worker holds the pool, so the lanes run until the pool's last worker is dropped. + let arrays = stream::unfold(self, |pool| async move { + let array = pool.outputs.recv().await.ok()?; + Some((array, pool)) + }) + .boxed(); + ArrayStreamExt::boxed(ArrayStreamAdapter::new(dtype, stop_on_error(arrays))) + } + + fn progress(&self) -> f64 { + if self.is_exhausted() { + return 1.0; + } + self.shared.progress() + } + + fn is_exhausted(&self) -> bool { + // The lanes hold the output channel's senders, so it closes once every lane has ended. + self.outputs.is_closed() && self.outputs.is_empty() + } +} + +impl Drop for UnorderedPool { + fn drop(&mut self) { + // Queued expansions hold senders of the channel of units itself; drain them so it can be + // freed. The lanes are aborted when they are dropped. + self.units.close(); + while self.units.try_recv().is_ok() {} + self.outputs.close(); + drop(self.lanes.tasks.lock().take()); + } +} + +/// 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.into_iter().flat_map(WorkUnit::in_place) { + 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) + } + + 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::LazyLock; + 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 vortex_io::runtime::BlockingRuntime; + use vortex_io::runtime::current::CurrentThreadRuntime; + use vortex_io::runtime::current::CurrentThreadWorkerPool; + + 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; + + /// A runtime driven by background threads, so the lanes the pools spawn make progress while + /// test workers block on their streams with `futures::executor`. + static RUNTIME: LazyLock<(CurrentThreadRuntime, CurrentThreadWorkerPool)> = + LazyLock::new(|| { + let runtime = CurrentThreadRuntime::new(); + let pool = runtime.new_pool(); + pool.set_workers(4); + (runtime, pool) + }); + + 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), + handle: RUNTIME.0.handle(), + 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 7c613ef3748..d4050ee0a92 100644 --- a/vortex-scan/src/source/plan.rs +++ b/vortex-scan/src/source/plan.rs @@ -205,9 +205,9 @@ pub enum PlanSourceChild { /// /// [`open`](DataSourceScan::open) prepares each ready child of the scan once and hands its parts, /// the chunks of its plan, or the child's [splits](PlanChild::with_splits) when it has them, to -/// workers, which keep several in flight on the session's runtime. Expanding a deferred child is a unit -/// of work too: the worker that takes it expands it and puts the work of its children back for -/// any worker to take. See the pool's documentation in `plan_pool.rs`. +/// the pool, which keeps several in flight on the session's runtime. Expanding a deferred child is a +/// unit of work too: expanding it puts the work of its children back in the pool. See the pool's +/// documentation in `plan_pool.rs`. /// /// # Partitions /// @@ -452,34 +452,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); } } } @@ -748,11 +738,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..94713a1abdb 100644 --- a/vortex-scan/src/source/plan_pool.rs +++ b/vortex-scan/src/source/plan_pool.rs @@ -1,58 +1,44 @@ // 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 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, 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) runs the units on its lanes and shares their output 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_session::VortexSession; use vortex_utils::parallelism::get_available_parallelism; use super::plan::DeferredPlanChild; @@ -64,11 +50,15 @@ 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::UnitStream; +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 +68,68 @@ 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, + handle: state.session.handle(), + // An ordered pool expands each deferred child only once the units before it are taken; + // an unordered one opens as many children at once as V1 opens files, one per core, so the + // parts of the first children run before every footer is read. + expand_concurrency: if state.ordered { + NonZeroUsize::MIN + } else { + get_available_parallelism() + .and_then(NonZeroUsize::new) + .unwrap_or(NonZeroUsize::MIN) + }, + 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 +143,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 +160,25 @@ 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.ordered, 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, as one turn, 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 { + ordered: bool, + session: VortexSession, +) -> Expansion { async move { let rows = child.scan.rows(); let per_row = share / (rows.end - rows.start).max(1) as f64; @@ -240,22 +188,30 @@ 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 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"), @@ -265,23 +221,52 @@ fn run_root( } } if unassigned > 0 { - taken.add(per_row * unassigned as f64); + units.push(WorkUnit::skipped(per_row * unassigned as f64)); } - Ok(parts) + // An unordered pool's lanes take the child's parts in turn with other children's. + Ok(vec![WorkUnit::turn(units)]) } .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(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 +287,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() - } -}