From af7a003b80a6de66693b0f22f0e3bd73d755531b Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 21:01:50 -0500 Subject: [PATCH 1/2] Stop DuckDB threads joining a file once its V1 splits or V2 parts are covered Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-duckdb/src/file_reader.rs | 30 ++++++++++++--- vortex-layout/src/scan/layout.rs | 20 ++++++++-- vortex-layout/src/scan/split_queue.rs | 11 +++--- vortex-scan/src/source/plan_stream.rs | 53 +++++++++------------------ vortex-scan/src/source/tests.rs | 6 ++- vortex-scan/src/stream.rs | 46 ++++++++++++++++------- 6 files changed, 104 insertions(+), 62 deletions(-) diff --git a/vortex-duckdb/src/file_reader.rs b/vortex-duckdb/src/file_reader.rs index ac7c83b63b3..a11e9a6a25a 100644 --- a/vortex-duckdb/src/file_reader.rs +++ b/vortex-duckdb/src/file_reader.rs @@ -6,6 +6,7 @@ use std::ops::Range; use std::sync::Arc; use std::sync::OnceLock; use std::sync::atomic::AtomicBool; +use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering; use futures::FutureExt; @@ -39,6 +40,7 @@ use vortex::mask::Mask; use vortex::scan::DataSource as _; use vortex::scan::DataSourceRef; use vortex::scan::ScanRequest; +use vortex::scan::stream::Claims; use vortex::scan::stream::ScanStream; use vortex::session::SessionExt as _; @@ -135,6 +137,8 @@ pub struct FileScanState { stream: OnceLock, /// Whether a clone of `stream` has ended, so no work of the file is left to take. finished: AtomicBool, + /// How many threads have joined the file, each with its own clone of `stream`. + joined: AtomicUsize, cache: ConversionCache, } @@ -156,9 +160,18 @@ impl FileScanState { if self.finished.load(Ordering::Acquire) { return None; } - self.stream - .get() - .map(|stream| Split(stream.stream.lock().clone())) + let stream = self.stream.get()?.stream.lock(); + // A clone claims its first unit of work, a V1 split or a V2 part, only when its thread + // first polls it, outside DuckDB's lock, so without a bound every thread would join before + // any had claimed. As many clones as units drain the file, so a later thread moves on + // instead. + if let Some(Claims { claimed, total }) = stream.claims() + && (claimed >= total || self.joined.load(Ordering::Relaxed) >= total) + { + return None; + } + self.joined.fetch_add(1, Ordering::Relaxed); + Some(Split(stream.clone())) } } @@ -177,6 +190,7 @@ impl OpenFileReader { plan_source: file.plan_data_source(), stream: OnceLock::new(), finished: AtomicBool::new(false), + joined: AtomicUsize::new(0), cache: ConversionCache::default(), })), }) @@ -473,8 +487,14 @@ pub fn reader_get_progress_in_file(file: &OpenFileReader) -> f64 { state .stream .get() - .and_then(|stream| stream.stream.lock().progress()) - .map_or(0.0, |progress| 100.0 * progress) + .and_then(|stream| stream.stream.lock().claims()) + .map_or(0.0, |Claims { claimed, total }| { + if total == 0 { + 100.0 + } else { + 100.0 * claimed as f64 / total as f64 + } + }) } /// Called by one thread in planning phase diff --git a/vortex-layout/src/scan/layout.rs b/vortex-layout/src/scan/layout.rs index 9f555b7a1bc..a05e8519f1f 100644 --- a/vortex-layout/src/scan/layout.rs +++ b/vortex-layout/src/scan/layout.rs @@ -329,10 +329,10 @@ impl DataSourceScan for LayoutReaderScan { .prepare()? .execute(Some(self.next_row..self.end_row))?; let queue = Arc::new(SplitQueue::new(self.session.handle(), per_worker, splits)); - let progress = Arc::clone(&queue); + let claims = Arc::clone(&queue); Ok( ScanStream::new(self.dtype, move || Arc::clone(&queue).worker()) - .with_progress(move || progress.progress()), + .with_claims(move || claims.claims()), ) } @@ -760,6 +760,7 @@ mod split_open_tests { use vortex_io::runtime::single::SingleThreadRuntime; use vortex_scan::DataSource; use vortex_scan::ScanRequest; + use vortex_scan::stream::Claims; use super::LayoutReaderDataSource; use super::group_contiguous; @@ -782,12 +783,25 @@ mod split_open_tests { let stream = runtime .block_on(source(&runtime).scan(ScanRequest::default()))? .open()?; + assert_eq!( + stream.claims(), + Some(Claims { + claimed: 0, + total: 16 + }) + ); let workers = (0..3).map(|_| stream.clone().try_collect::>()); let arrays = runtime.block_on(try_join_all(workers))?; let mut values = collect_scan_values(arrays.into_iter().flatten().map(Ok))?; values.sort_unstable(); assert_eq!(values, (0..64).collect::>()); - assert_eq!(stream.progress(), Some(1.0)); + assert_eq!( + stream.claims(), + Some(Claims { + claimed: 16, + total: 16 + }) + ); Ok(()) } diff --git a/vortex-layout/src/scan/split_queue.rs b/vortex-layout/src/scan/split_queue.rs index 463eeb72828..ab1c0a977e2 100644 --- a/vortex-layout/src/scan/split_queue.rs +++ b/vortex-layout/src/scan/split_queue.rs @@ -18,6 +18,7 @@ use parking_lot::Mutex; use vortex_array::ArrayRef; use vortex_error::VortexResult; use vortex_io::runtime::Handle; +use vortex_scan::stream::Claims; use crate::scan::repeated_scan::ScanTasks; @@ -68,12 +69,12 @@ impl SplitQueue { Some(split) } - /// The fraction of the splits that the stream's clones have claimed. - pub(crate) fn progress(&self) -> f64 { - if self.total == 0 { - return 1.0; + /// How many of the splits the stream's clones have claimed, out of how many in all. + pub(crate) fn claims(&self) -> Claims { + Claims { + claimed: self.claimed.load(Ordering::Relaxed).min(self.total), + total: self.total, } - (self.claimed.load(Ordering::Relaxed) as f64 / self.total as f64).min(1.0) } /// A new worker over the shared queue, which one clone of the scan's stream polls. diff --git a/vortex-scan/src/source/plan_stream.rs b/vortex-scan/src/source/plan_stream.rs index ef2b3e7f996..ba2013921e1 100644 --- a/vortex-scan/src/source/plan_stream.rs +++ b/vortex-scan/src/source/plan_stream.rs @@ -33,8 +33,7 @@ use std::future; use std::iter; use std::ops::Range; use std::sync::Arc; -use std::sync::atomic::AtomicBool; -use std::sync::atomic::AtomicU64; +use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering; use futures::StreamExt; @@ -60,30 +59,27 @@ use crate::planning::planner::Planner; use crate::planning::planner::WorkScope; use crate::prepare::PreparedScan; use crate::prepare::part_root; +use crate::stream::Claims; use crate::stream::ScanStream; /// The parts of an unordered scan, cut when the scan is made. pub(super) struct Planned { work: Vec, - /// The rows of the scan's units. - total_rows: u64, } /// Prepares each of the scan's `units` once and runs its root, awaiting the zone maps a dynamic /// filter's root reads, and returns the work the roots produce, in unit and row order. pub(super) async fn plan(state: &ScanState, units: &[Unit]) -> VortexResult { let mut work = Vec::new(); - let mut total_rows = 0; for unit in units { let rows = state.unit_rows(unit)?; if rows.is_empty() { continue; } - total_rows += rows.end - rows.start; let (child, root) = prepare(state, unit, rows)?; work.extend(run_root(child, root).await?); } - Ok(Planned { work, total_rows }) + Ok(Planned { work }) } /// Opens the stream of a scan of `units`. An unordered scan reads the parts it `planned`. @@ -107,12 +103,11 @@ pub(super) fn open( let planned = planned.vortex_expect("an unordered scan cuts its parts when it is made"); let queue = Arc::new(Queue { - exhausted: AtomicBool::new(planned.work.is_empty()), + total: planned.work.len(), work: Mutex::new(planned.work.into()), - total_rows: planned.total_rows, - rows_taken: AtomicU64::new(0), + taken: AtomicUsize::new(0), }); - let progress = Arc::clone(&queue); + let claims = Arc::clone(&queue); Ok(ScanStream::new(dtype, move || { let worker = Worker { queue: Arc::clone(&queue), @@ -131,7 +126,7 @@ pub(super) fn open( .boxed(); limited(arrays, limit.clone()) }) - .with_progress(move || progress.progress())) + .with_claims(move || claims.claims())) } /// One child's prepared scan, shared by the parts of it that clones run. @@ -215,38 +210,26 @@ enum Work { struct Queue { /// The work no clone has taken yet, in unit and row order. work: Mutex>, - /// Set once a clone has taken the last of `work`. - exhausted: AtomicBool, - /// The rows of the scan's units. - total_rows: u64, - /// The rows of the parts clones have taken. - rows_taken: AtomicU64, + /// The work the queue started with. + total: usize, + /// The work clones have taken. + taken: AtomicUsize, } impl Queue { /// Takes the next work, or `None` once every one has been taken. fn take(&self) -> Option { - let mut queue = self.work.lock(); - let work = queue.pop_front()?; - if queue.is_empty() { - self.exhausted.store(true, Ordering::Release); - } - if let Work::Part(part) = &work { - self.rows_taken.fetch_add( - part.scope.rows.end - part.scope.rows.start, - Ordering::Relaxed, - ); - } + let work = self.work.lock().pop_front()?; + self.taken.fetch_add(1, Ordering::Relaxed); Some(work) } - /// The fraction of the scan's rows whose parts clones have taken. Pruning can leave rows that - /// no part covers, so a queue with nothing left to take has made all of its progress. - fn progress(&self) -> f64 { - if self.total_rows == 0 || self.exhausted.load(Ordering::Relaxed) { - return 1.0; + /// How much of the queue's work clones have taken, out of how much in all. + fn claims(&self) -> Claims { + Claims { + claimed: self.taken.load(Ordering::Relaxed).min(self.total), + total: self.total, } - (self.rows_taken.load(Ordering::Relaxed) as f64 / self.total_rows as f64).min(1.0) } } diff --git a/vortex-scan/src/source/tests.rs b/vortex-scan/src/source/tests.rs index daeb32082b5..3f5793abdaa 100644 --- a/vortex-scan/src/source/tests.rs +++ b/vortex-scan/src/source/tests.rs @@ -192,7 +192,11 @@ async fn clones_share_the_scan() -> VortexResult<()> { .map(|clone| clone.try_collect::>()), ) .await?; - assert_eq!(stream.progress(), Some(1.0)); + assert!( + stream + .claims() + .is_some_and(|claims| claims.total > 0 && claims.claimed == claims.total) + ); let mut ctx = VortexSession::empty().create_execution_ctx(); let mut values = Vec::new(); for batch in batches.into_iter().flatten() { diff --git a/vortex-scan/src/stream.rs b/vortex-scan/src/stream.rs index 27dfc53ebdf..cadc8fcc3e3 100644 --- a/vortex-scan/src/stream.rs +++ b/vortex-scan/src/stream.rs @@ -21,8 +21,20 @@ use crate::DataSourceScanRef; /// Starts a new worker over the shared work of an opened scan. type NewWorker = dyn Fn() -> BoxStream<'static, VortexResult> + Send + Sync; -/// Reads the fraction of an opened scan's work that its clones have taken. -type Progress = dyn Fn() -> f64 + Send + Sync; +/// Reads how many units of an opened scan's work its clones have claimed. +type ReadClaims = dyn Fn() -> Claims + Send + Sync; + +/// How many units of an opened scan's work its clones have claimed, out of how many in all. +/// +/// A unit is what one clone claims at a time, such as a split of a layout scan. Claims only grow, +/// and `claimed` never exceeds `total`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Claims { + /// The units that clones have claimed so far. + pub claimed: usize, + /// The units of the scan in all. + pub total: usize, +} /// The arrays of an opened scan, which host threads read by each polling a clone. /// @@ -37,7 +49,7 @@ type Progress = dyn Fn() -> f64 + Send + Sync; pub struct ScanStream { dtype: DType, new_worker: Arc, - progress: Option>, + claims: Option>, worker: Option>>, } @@ -53,22 +65,30 @@ impl ScanStream { Self { dtype, new_worker: Arc::new(new_worker), - progress: None, + claims: None, worker: None, } } - /// This stream, reporting its progress through `progress`, which returns the fraction of the - /// scan's work that its clones have taken, from 0.0 to 1.0, and must never block. - pub fn with_progress(mut self, progress: impl Fn() -> f64 + Send + Sync + 'static) -> Self { - self.progress = Some(Arc::new(progress)); + /// This stream, reporting through `claims` how many units of its work its clones have + /// claimed, out of how many in all. `claims` must never block. + pub fn with_claims(mut self, claims: impl Fn() -> Claims + Send + Sync + 'static) -> Self { + self.claims = Some(Arc::new(claims)); self } - /// The fraction of the scan's work that its clones have taken, from 0.0 to 1.0, for a host's - /// progress bar, or `None` when the scan does not track it. Never blocks. - pub fn progress(&self) -> Option { - self.progress.as_ref().map(|progress| progress()) + /// How many units of the scan's work its clones have claimed, out of how many in all, or + /// `None` when the source does not know its total up front, as for a stream from + /// [`Self::from_partitions`]. Never blocks. + /// + /// A host derives its progress from this. It also bounds how many clones a host needs: a + /// host that hands out clones under its own lock may stop once it has handed out `total` + /// clones, or once `claimed` reaches `total`, because the clones already handed out keep + /// claiming units until none is left and so drain the rest. A clone handed out after that + /// would find nothing to claim. When this is `None` the host cannot bound its clones this + /// way, and learns that no work is left only when a clone ends. + pub fn claims(&self) -> Option { + self.claims.as_ref().map(|claims| claims()) } /// A stream whose clones take the partitions of `scan` one at a time. @@ -99,7 +119,7 @@ impl Clone for ScanStream { Self { dtype: self.dtype.clone(), new_worker: Arc::clone(&self.new_worker), - progress: self.progress.clone(), + claims: self.claims.clone(), worker: None, } } From dc1559f057c55f1a2c6e93675eebb86d1d5501de Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Mon, 23 Nov 2026 17:48:03 -0500 Subject: [PATCH 2/2] Return from the current-thread runtime's block_on without entering the executor when the future is ready Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-io/src/runtime/current.rs | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/vortex-io/src/runtime/current.rs b/vortex-io/src/runtime/current.rs index 203d7858359..825f8bf19a0 100644 --- a/vortex-io/src/runtime/current.rs +++ b/vortex-io/src/runtime/current.rs @@ -2,9 +2,11 @@ // SPDX-FileCopyrightText: Copyright the Vortex contributors use std::future::Future; +use std::pin::pin; use std::sync::Arc; use async_channel::TryRecvError; +use futures::FutureExt; use futures::SinkExt; use futures::Stream; use futures::StreamExt; @@ -136,7 +138,7 @@ impl BlockingRuntime for CurrentThreadRuntime { where Fut: Future, { - block_on(self.executor.run(fut)) + drive(&self.executor, fut) } fn block_on_stream<'a, S, R>(&self, stream: S) -> Self::BlockingIterator<'a, R> @@ -151,6 +153,22 @@ impl BlockingRuntime for CurrentThreadRuntime { } } +/// Drives `fut` to completion on the calling thread. +/// +/// The future is polled once before entering the executor and returned from directly if it is +/// ready. Each entry into [`smol::Executor::run`] registers the thread with the executor's shared +/// state, under a write lock that every thread entering the runtime contends on, and a caller that +/// blocks on many futures which are mostly ready already, such as one batch of a scan after +/// another, would otherwise pay that for each of them. A future that is not ready is polled again +/// inside the executor, which runs the runtime's tasks while the thread waits for it. +fn drive(executor: &SmolExecutor, fut: Fut) -> Fut::Output { + let mut fut = pin!(fut); + if let Some(output) = fut.as_mut().now_or_never() { + return output; + } + block_on(executor.run(fut)) +} + /// An iterator that wraps up a stream to drive it using the current thread execution. pub struct CurrentThreadIterator<'a, T> { executor: Arc, @@ -161,7 +179,7 @@ impl Iterator for CurrentThreadIterator<'_, T> { type Item = T; fn next(&mut self) -> Option { - block_on(self.executor.run(self.stream.next())) + drive(&self.executor, self.stream.next()) } }