From 9d5c2fad216f4f33785b02743a03fa14bc6443cb Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 14:37:53 -0500 Subject: [PATCH 1/7] Report an opened scan's progress on its stream A host reading an opened scan, such as DuckDB showing a progress bar per file, asks its stream how much of the work its clones have taken. A layout scan's stream reports the fraction of its splits claimed; a stream over partitions reports none. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-layout/src/scan/layout.rs | 9 ++++++--- vortex-layout/src/scan/split_queue.rs | 18 +++++++++++++++++- vortex-scan/src/stream.rs | 19 +++++++++++++++++++ 3 files changed, 42 insertions(+), 4 deletions(-) diff --git a/vortex-layout/src/scan/layout.rs b/vortex-layout/src/scan/layout.rs index 24755112d6f..07cf1e5860a 100644 --- a/vortex-layout/src/scan/layout.rs +++ b/vortex-layout/src/scan/layout.rs @@ -334,9 +334,11 @@ 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)); - Ok(ScanStream::new(self.dtype, move || { - Arc::clone(&queue).worker() - })) + let progress = Arc::clone(&queue); + Ok( + ScanStream::new(self.dtype, move || Arc::clone(&queue).worker()) + .with_progress(move || progress.progress()), + ) } fn partition_count(&self) -> Precision { @@ -790,6 +792,7 @@ mod split_open_tests { 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)); Ok(()) } diff --git a/vortex-layout/src/scan/split_queue.rs b/vortex-layout/src/scan/split_queue.rs index ba46fe3a263..49afc813c56 100644 --- a/vortex-layout/src/scan/split_queue.rs +++ b/vortex-layout/src/scan/split_queue.rs @@ -5,6 +5,8 @@ use std::iter; use std::sync::Arc; +use std::sync::atomic::AtomicUsize; +use std::sync::atomic::Ordering; use std::vec; use futures::StreamExt; @@ -40,6 +42,8 @@ pub(crate) struct SplitQueue { handle: Handle, per_worker: usize, splits: Mutex>, + total: usize, + claimed: AtomicUsize, } impl SplitQueue { @@ -47,13 +51,25 @@ impl SplitQueue { Self { handle, per_worker: per_worker.max(1), + total: splits.len(), splits: Mutex::new(splits.into_iter()), + claimed: AtomicUsize::new(0), } } /// Claims the next split, if any is left. fn claim(&self) -> Option { - self.splits.lock().next() + let split = self.splits.lock().next()?; + self.claimed.fetch_add(1, Ordering::Relaxed); + 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; + } + (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/stream.rs b/vortex-scan/src/stream.rs index 957b01407df..7c2ec623c5d 100644 --- a/vortex-scan/src/stream.rs +++ b/vortex-scan/src/stream.rs @@ -30,6 +30,9 @@ use crate::PartitionStream; /// 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; + /// The arrays of an opened scan, which host threads read by each polling a clone. /// /// A clone is another worker over the same remaining work, like a clone of a channel's receiver: @@ -43,6 +46,7 @@ type NewWorker = dyn Fn() -> BoxStream<'static, VortexResult> + Send + pub struct ScanStream { dtype: DType, new_worker: Arc, + progress: Option>, worker: Option>>, } @@ -58,10 +62,24 @@ impl ScanStream { Self { dtype, new_worker: Arc::new(new_worker), + progress: 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)); + 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()) + } + /// A stream whose clones take the partitions of `scan` one at a time. /// /// A source that has no queue of work of its own can open into this one. @@ -90,6 +108,7 @@ impl Clone for ScanStream { Self { dtype: self.dtype.clone(), new_worker: Arc::clone(&self.new_worker), + progress: self.progress.clone(), worker: None, } } From cdb5fadd2c0869dd140dca4af3715529b24e08f2 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 14:37:53 -0500 Subject: [PATCH 2/7] Read DuckDB's V1 scans through open Each file DuckDB's MultiFileReader opens is opened once as a V1 layout scan, and every DuckDB thread that joins the file polls a clone of its stream. A thread joins a file until the first clone ends, which happens only once no split is left to claim, so threads move on to the next file without waiting for the last splits to finish. DuckDB's private per-file split list is removed. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-duckdb/src/file_reader.rs | 176 +++++++++++++++++++--------- vortex-duckdb/src/projection.rs | 7 +- vortex-duckdb/src/table_function.rs | 19 ++- 3 files changed, 141 insertions(+), 61 deletions(-) diff --git a/vortex-duckdb/src/file_reader.rs b/vortex-duckdb/src/file_reader.rs index 70d8d30c6cb..24d609e7217 100644 --- a/vortex-duckdb/src/file_reader.rs +++ b/vortex-duckdb/src/file_reader.rs @@ -1,12 +1,14 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +use std::ops::Range; use std::sync::Arc; use std::sync::OnceLock; use std::sync::atomic::AtomicBool; use std::sync::atomic::Ordering; use futures::FutureExt; +use futures::StreamExt; use object_store::registry::ObjectStoreRegistry; use url::Url; use vortex::array::ArrayRef; @@ -31,10 +33,14 @@ use vortex::io::object_store::ObjectStoreFileSystem; use vortex::io::runtime::BlockingRuntime as _; use vortex::io::std_file::StdFileSystem; use vortex::layout::LayoutReaderRef; +use vortex::layout::scan::layout::LayoutReaderDataSource; use vortex::layout::scan::scan_builder::ScanBuilder; use vortex::layout::scan::v2::ScanBuilder as V2ScanBuilder; use vortex::layout::scan::v2::ScanFile; use vortex::mask::Mask; +use vortex::scan::DataSource as _; +use vortex::scan::ScanRequest; +use vortex::scan::stream::ScanStream; use vortex::session::SessionExt as _; use crate::REGISTRY; @@ -111,17 +117,14 @@ fn resolve_filesystem(url: &Url) -> VortexResult<(FileSystemRef, String)> { } pub struct OpenFileReader { - /// The layout reader and conversion cache of the file. `None` after the file is skipped or - /// all its splits are taken. + /// The layout reader, scan and conversion cache of the file. `None` after the file is skipped + /// or no thread can join it any more. /// /// DuckDB releases its last reference to a file while it holds the global lock of the /// multi-file scan, and dropping this state takes long. So every local state that scans the /// file holds a reference too, and the file gives its own reference to a local state before /// DuckDB releases the file. The last local state drops the state outside the lock. scan_state: Option>, - /// File splits stored in inverse order - pub splits: Vec, - total_splits: usize, } /// The state of an open file that the threads scanning it share. @@ -132,9 +135,31 @@ pub struct FileScanState { /// The file's V2 scan, which every thread scanning the file drives. Set when the file is /// initialized for a V2 scan. v2: OnceLock, + /// The opened stream of the file's V1 scan, which each thread scanning the file polls a clone + /// of. Set when the file is initialized for a V1 scan. + stream: OnceLock, + /// Whether a clone of `stream` has ended, so no split of the file is left to claim. + finished: AtomicBool, cache: ConversionCache, } +impl FileScanState { + /// The scan work a thread joining the file would take, or `None` once the file has none. + fn next_split(&self) -> Option { + if let Some(scan) = self.v2.get() { + return (!scan.is_exhausted()).then_some(Split::V2); + } + // A clone of the file's stream ends only once no split is left to claim and its own + // splits are done. So a thread joins the file until the first clone ends, and threads + // then move on to the next file while the clones holding the last splits finish them: + // no thread waits for the rest of a file to drain. + if self.finished.load(Ordering::Acquire) { + return None; + } + self.stream.get().cloned().map(Split::V1) + } +} + impl OpenFileReader { async fn open(path: String) -> VortexResult { let (fs, fs_path) = resolve_filesystem(&parse_uri_or_path(&path)?)?; @@ -147,10 +172,10 @@ impl OpenFileReader { reader: file.layout_reader()?, scan_file, v2: OnceLock::new(), + stream: OnceLock::new(), + finished: AtomicBool::new(false), cache: ConversionCache::default(), })), - splits: vec![], - total_splits: 0, }) } @@ -219,7 +244,7 @@ pub fn reader_initialize(file: &mut OpenFileReader, global: &GlobalState) -> Vor return Ok(true); } - // Getting splits, or planning a V2 scan, is non-trivial work so we prefer + // Opening the file's scan, or planning a V2 scan, is non-trivial work so we prefer // doing it here under file lock and not in reader_try_initialize_scan under // global lock. if global.scan_v2 { @@ -240,33 +265,42 @@ pub fn reader_initialize(file: &mut OpenFileReader, global: &GlobalState) -> Vor return Ok(false); } - let reader = Arc::clone(file.reader()); + let state = file.scan_state(); let filter = &global.filter; - let builder = ScanBuilder::new(SESSION.clone(), reader) - .with_projection(global.projection.clone()) - .with_some_filter(filter.filter.clone()) - .with_selection(filter.row_selection.clone()); - let scan = builder.prepare()?; - let mut splits: Vec = scan - .execute(filter.row_range.clone())? - .into_iter() - .map(Split::V1) - .collect(); - - // threads take last element of file.splits so we need to reverse - splits.reverse(); - file.total_splits = splits.len(); - file.splits = splits; + let request = ScanRequest { + projection: global.projection_expr.clone(), + filter: filter.expr.clone(), + row_range: Some(file_rows(state, filter)), + selection: filter.row_selection.clone(), + ordered: false, + ..ScanRequest::default() + }; + // An unordered scan without a limit opens into a stream over a queue of the file's splits. + // Each clone claims splits as it has room for them, keeps a few in flight on the runtime, + // and yields each as it finishes, so the threads polling clones decode while their reads are + // pending. + let source = LayoutReaderDataSource::new(Arc::clone(&state.reader), SESSION.clone()); + let stream = RUNTIME.block_on(source.scan(request))?.open()?; + if state.stream.set(stream).is_err() { + vortex_panic!("file initialized twice"); + } Ok(false) } +/// The rows of the file that the scan's row range keeps. A `file_row_number` filter can bound +/// the range past the end of the file, up to `u64::MAX`. +fn file_rows(state: &FileScanState, filter: &Filter) -> Range { + let row_count = state.reader.row_count(); + filter.row_range.as_ref().map_or(0..row_count, |range| { + let end = range.end.min(row_count); + range.start.min(end)..end + }) +} + /// The V2 scan of the file's rows that the scan's row range and selection keep. fn v2_builder(state: &FileScanState, global: &GlobalState) -> V2ScanBuilder { let filter = &global.filter; - let row_count = state.reader.row_count(); - let rows = filter.row_range.as_ref().map_or(0..row_count, |range| { - range.start.min(row_count)..range.end.min(row_count) - }); + let rows = file_rows(state, filter); V2ScanBuilder::new(SESSION.clone(), state.scan_file.clone()) .with_projection(global.projection.clone()) .with_some_filter(filter.filter.clone()) @@ -287,9 +321,32 @@ enum SplitItem { fn next_split_item(local: &mut LocalState) -> VortexResult { match local.split.take() { None => Ok(SplitItem::Done), - Some(Split::V1(task)) => Ok(RUNTIME - .block_on(task)? - .map_or(SplitItem::Empty, SplitItem::Array)), + Some(Split::V1(mut stream)) => { + let array = match local.pending.pop() { + Some(array) => array, + None => { + let Some(array) = RUNTIME.block_on(stream.next()).transpose()? else { + local + .file + .as_ref() + .vortex_expect("split without a file") + .finished + .store(true, Ordering::Release); + // Dropping the last clone drops the file's split queue; do that outside + // DuckDB's locks. + local.retired_splits.push(Split::V1(stream)); + return Ok(SplitItem::Done); + }; + split_chunks(&mut local.pending, array) + } + }; + local.split = Some(Split::V1(stream)); + Ok(if array.is_empty() { + SplitItem::Empty + } else { + SplitItem::Array(array) + }) + } Some(Split::V2) => { let file = local.file.as_ref().vortex_expect("split without a file"); let scan = file @@ -302,16 +359,7 @@ fn next_split_item(local: &mut LocalState) -> VortexResult { let Some(array) = scan.next_array(&mut local.run)? else { return Ok(SplitItem::Done); }; - // A V2 batch can join chunks of several layout chunks. Canonicalizing it - // would decode their dictionaries, so export each chunk on its own, as a V1 - // scan yields them. - match array.as_opt::() { - Some(chunked) => { - local.pending.extend(chunked.chunks().into_iter().rev()); - local.pending.pop().unwrap_or(array) - } - None => array, - } + split_chunks(&mut local.pending, array) } }; local.split = Some(Split::V2); @@ -324,6 +372,20 @@ fn next_split_item(local: &mut LocalState) -> VortexResult { } } +/// The first chunk of `array`, leaving the rest in `pending` in reverse order. +/// +/// An array can join chunks of several layout chunks. Canonicalizing it would decode their +/// dictionaries, so export each chunk on its own. +fn split_chunks(pending: &mut Vec, array: ArrayRef) -> ArrayRef { + match array.as_opt::() { + Some(chunked) => { + pending.extend(chunked.chunks().into_iter().rev()); + pending.pop().unwrap_or(array) + } + None => array, + } +} + /// Called by all threads under global lock. If this function returns true, /// thread calls reader_scan on this file. If this function returns false, /// duckdb thinks file is exhausted, closes the file, and the first thread to @@ -333,14 +395,14 @@ fn next_split_item(local: &mut LocalState) -> VortexResult { /// the global lock. It only moves references between the file and the local /// state, and reader_scan drops the retired ones. pub fn reader_try_initialize_scan(file: &mut OpenFileReader, local: &mut LocalState) -> bool { - // A V2 scan's threads take chunks from the file's scan until it has spawned - // them all, so the file has work for another thread until then. - let v2 = file + // A thread joins a file while its V2 scan has chunks left to spawn or its V1 + // stream has a split left to claim. Cloning the stream only clones its handles, + // so it is cheap under the global lock. + let split = file .scan_state .as_ref() - .and_then(|state| state.v2.get()) - .map(|scan| (!scan.is_exhausted()).then_some(Split::V2)); - let Some(split) = v2.unwrap_or_else(|| file.splits.pop()) else { + .and_then(|state| state.next_split()); + let Some(split) = split else { // DuckDB releases the file after this call, under the global lock. // Give the reference of the file to this thread so it drops outside. local.retired_files.extend(file.scan_state.take()); @@ -360,7 +422,7 @@ pub fn reader_try_initialize_scan(file: &mut OpenFileReader, local: &mut LocalSt local.retired_files.extend(previous); } - local.split = Some(split); + local.retired_splits.extend(local.split.replace(split)); true } @@ -372,7 +434,8 @@ pub fn reader_scan( local: &mut LocalState, chunk: &mut DataChunkRef, ) -> VortexResult { - // No lock is held here, so drop the scan states of files this thread left. + // No lock is held here, so drop the splits and scan states this thread left. + local.retired_splits.clear(); local.retired_files.clear(); if !global.aggregates.is_empty() { @@ -453,13 +516,18 @@ pub fn reader_get_statistics( /// Called from a separate thread (not related to threads for Vortex /// table function) under global lock. pub fn reader_get_progress_in_file(file: &OpenFileReader) -> f64 { - if let Some(scan) = file.scan_state.as_ref().and_then(|state| state.v2.get()) { + // A file without a scan state was skipped or has every split taken. + let Some(state) = file.scan_state.as_ref() else { + return 100.0; + }; + if let Some(scan) = state.v2.get() { return scan.progress(); } - let total = file.total_splits; - let left = file.splits.len(); - let denom = total + (total == 0) as usize; - 100.0 * (total - left) as f64 / denom as f64 + state + .stream + .get() + .and_then(ScanStream::progress) + .map_or(0.0, |progress| 100.0 * progress) } /// Called by one thread in planning phase diff --git a/vortex-duckdb/src/projection.rs b/vortex-duckdb/src/projection.rs index 68a7c8cd454..afa76f59635 100644 --- a/vortex-duckdb/src/projection.rs +++ b/vortex-duckdb/src/projection.rs @@ -191,6 +191,8 @@ impl Projection { pub struct Filter { pub filter: Option, + /// `filter` before binding, for scans that bind it against each file. + pub expr: Option, pub row_selection: Selection, pub row_range: Option>, pub has_non_optional_filter: bool, @@ -257,12 +259,15 @@ impl Filter { } }; - let filter = and_collect(table_filter_exprs) + let expr = and_collect(table_filter_exprs); + let filter = expr + .as_ref() .map(|expr| expr.bind(dtype)?.optimize_recursive()) .transpose()?; let out = Self { filter, + expr, row_selection, row_range, has_non_optional_filter, diff --git a/vortex-duckdb/src/table_function.rs b/vortex-duckdb/src/table_function.rs index e96dd83d12c..02e9446bfbf 100644 --- a/vortex-duckdb/src/table_function.rs +++ b/vortex-duckdb/src/table_function.rs @@ -11,7 +11,6 @@ use std::sync::atomic::Ordering; #[cfg(unix)] use custom_labels::CURRENT_LABELSET; -use futures::future::BoxFuture; use itertools::Itertools; use num_traits::AsPrimitive; use parking_lot::Mutex; @@ -43,6 +42,7 @@ use vortex::metrics::tracing::get_global_labels; use vortex::proto::expr as expr_pb; use vortex::scalar::Scalar; use vortex::scan::planning::driver::Run; +use vortex::scan::stream::ScanStream; use vortex_utils::aliases::hash_map::HashMap; use crate::SESSION; @@ -183,6 +183,8 @@ impl<'a> TableInitInput<'a> { pub struct GlobalState { pub projection: BoundExpression, + /// The projection before binding, for scans that bind it against each file. + pub projection_expr: Expression, pub filter: Filter, pub file_row_number_column_pos: Option, /// Whether the scan runs on the planner-driven V2 executor. @@ -203,10 +205,11 @@ pub struct AggregateState { } assert_impl_all!(GlobalState: Send, Sync); -/// A unit of scan work that one thread takes at a time. +/// The scan work that one thread does on a file. pub enum Split { - /// A V1 scan task yielding one array, or `None` if the filter removed every row. - V1(BoxFuture<'static, VortexResult>>), + /// A clone of the file's V1 scan stream, which the thread polls inline. It claims the file's + /// splits as it has room for them until none is left, and yields only the splits it claimed. + V1(ScanStream), /// Chunks of the file's V2 scan, taken by the thread until the scan has none left. V2, } @@ -220,12 +223,13 @@ pub struct LocalState { pub split: Option, /// The scan state of the file that this thread scans. pub(crate) file: Option>, - /// Scan states that this thread no longer uses. They are dropped outside + /// Scan states and splits that this thread no longer uses. They are dropped outside /// DuckDB's global multi-file lock; see `OpenFileReader`. pub(crate) retired_files: Vec>, + pub(crate) retired_splits: Vec, /// The planning run on which this thread runs the chunks of V2 scans. pub(crate) run: Run, - /// Chunks of a V2 batch that this thread has yet to export, in reverse order. + /// Chunks of an array that this thread has yet to export, in reverse order. pub(crate) pending: Vec, /// Empty for non-aggregate scan @@ -352,9 +356,11 @@ pub fn init_global(init_input: &TableInitInput) -> VortexResult { "table function scan input" ); + let projection_expr = projection.clone(); let projection = optimize_and_bind(projection, &bind_data.dtype)?; Ok(GlobalState { projection, + projection_expr, filter, aggregates: bind_data.aggregates.clone(), has_count_star, @@ -430,6 +436,7 @@ pub fn init_local(bind_data: &BindState, global: &GlobalState) -> LocalState { split: None, file: None, retired_files: Vec::new(), + retired_splits: Vec::new(), run: Run::new(), pending: Vec::new(), finished: false, From c7656fcd872abc44d1aa8e0b5d3ee96742c770f0 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 14:59:48 -0500 Subject: [PATCH 3/7] Clone a DuckDB file's scan stream under a lock A ScanStream is Send but not Sync, so the file state that every thread scanning the file shares holds it behind a mutex, and each thread clones it there. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-duckdb/src/file_reader.rs | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/vortex-duckdb/src/file_reader.rs b/vortex-duckdb/src/file_reader.rs index 24d609e7217..f080714a07a 100644 --- a/vortex-duckdb/src/file_reader.rs +++ b/vortex-duckdb/src/file_reader.rs @@ -10,6 +10,7 @@ use std::sync::atomic::Ordering; use futures::FutureExt; use futures::StreamExt; use object_store::registry::ObjectStoreRegistry; +use parking_lot::Mutex; use url::Url; use vortex::array::ArrayRef; use vortex::array::VortexSessionExecute as _; @@ -136,8 +137,9 @@ pub struct FileScanState { /// initialized for a V2 scan. v2: OnceLock, /// The opened stream of the file's V1 scan, which each thread scanning the file polls a clone - /// of. Set when the file is initialized for a V1 scan. - stream: OnceLock, + /// of. Set when the file is initialized for a V1 scan. A stream is `Send` but not `Sync`, so + /// threads clone it under the lock. + stream: OnceLock>, /// Whether a clone of `stream` has ended, so no split of the file is left to claim. finished: AtomicBool, cache: ConversionCache, @@ -156,7 +158,9 @@ impl FileScanState { if self.finished.load(Ordering::Acquire) { return None; } - self.stream.get().cloned().map(Split::V1) + self.stream + .get() + .map(|stream| Split::V1(stream.lock().clone())) } } @@ -281,7 +285,7 @@ pub fn reader_initialize(file: &mut OpenFileReader, global: &GlobalState) -> Vor // pending. let source = LayoutReaderDataSource::new(Arc::clone(&state.reader), SESSION.clone()); let stream = RUNTIME.block_on(source.scan(request))?.open()?; - if state.stream.set(stream).is_err() { + if state.stream.set(Mutex::new(stream)).is_err() { vortex_panic!("file initialized twice"); } Ok(false) @@ -526,7 +530,7 @@ pub fn reader_get_progress_in_file(file: &OpenFileReader) -> f64 { state .stream .get() - .and_then(ScanStream::progress) + .and_then(|stream| stream.lock().progress()) .map_or(0.0, |progress| 100.0 * progress) } From f869fdbd4d8373757e261fb0ae4fb64268205922 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 15:05:01 -0500 Subject: [PATCH 4/7] Run one split at a time on each DuckDB thread DuckDB runs one thread per core, and each polls its own clone of a file's scan stream. A clone that keeps several splits in flight claims splits that other threads could have run, so on a file with few splits, such as TPC-H's smaller tables, most threads find the queue empty. Capping each clone at one split matches DuckDB's own parallelism. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-duckdb/src/file_reader.rs | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/vortex-duckdb/src/file_reader.rs b/vortex-duckdb/src/file_reader.rs index f080714a07a..1ce1c813478 100644 --- a/vortex-duckdb/src/file_reader.rs +++ b/vortex-duckdb/src/file_reader.rs @@ -1,6 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +use std::num::NonZeroUsize; use std::ops::Range; use std::sync::Arc; use std::sync::OnceLock; @@ -277,12 +278,14 @@ pub fn reader_initialize(file: &mut OpenFileReader, global: &GlobalState) -> Vor row_range: Some(file_rows(state, filter)), selection: filter.row_selection.clone(), ordered: false, + // DuckDB runs one thread per core, so its threads are the scan's parallelism: each runs + // one split at a time. A clone with room for more would claim splits other threads could + // have run, leaving them nothing on a file with few splits. + split_concurrency: Some(NonZeroUsize::MIN), ..ScanRequest::default() }; - // An unordered scan without a limit opens into a stream over a queue of the file's splits. - // Each clone claims splits as it has room for them, keeps a few in flight on the runtime, - // and yields each as it finishes, so the threads polling clones decode while their reads are - // pending. + // An unordered scan without a limit opens into a stream over a queue of the file's splits, + // whose clones each claim the next split once they have finished their last. let source = LayoutReaderDataSource::new(Arc::clone(&state.reader), SESSION.clone()); let stream = RUNTIME.block_on(source.scan(request))?.open()?; if state.stream.set(Mutex::new(stream)).is_err() { From 28c6b76c34d7fa3e553c6986c3101e0360af1e85 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 15:14:47 -0500 Subject: [PATCH 5/7] Poll a DuckDB thread's split on that thread Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-duckdb/src/file_reader.rs | 57 +++++++++++---------------- vortex-layout/src/scan/split_queue.rs | 13 +++++- 2 files changed, 35 insertions(+), 35 deletions(-) diff --git a/vortex-duckdb/src/file_reader.rs b/vortex-duckdb/src/file_reader.rs index 1ce1c813478..c6c1969fcda 100644 --- a/vortex-duckdb/src/file_reader.rs +++ b/vortex-duckdb/src/file_reader.rs @@ -279,8 +279,8 @@ pub fn reader_initialize(file: &mut OpenFileReader, global: &GlobalState) -> Vor selection: filter.row_selection.clone(), ordered: false, // DuckDB runs one thread per core, so its threads are the scan's parallelism: each runs - // one split at a time. A clone with room for more would claim splits other threads could - // have run, leaving them nothing on a file with few splits. + // one split at a time, polling it itself. A clone with room for more would claim splits + // other threads could have run, leaving them nothing on a file with few splits. split_concurrency: Some(NonZeroUsize::MIN), ..ScanRequest::default() }; @@ -329,23 +329,17 @@ fn next_split_item(local: &mut LocalState) -> VortexResult { match local.split.take() { None => Ok(SplitItem::Done), Some(Split::V1(mut stream)) => { - let array = match local.pending.pop() { - Some(array) => array, - None => { - let Some(array) = RUNTIME.block_on(stream.next()).transpose()? else { - local - .file - .as_ref() - .vortex_expect("split without a file") - .finished - .store(true, Ordering::Release); - // Dropping the last clone drops the file's split queue; do that outside - // DuckDB's locks. - local.retired_splits.push(Split::V1(stream)); - return Ok(SplitItem::Done); - }; - split_chunks(&mut local.pending, array) - } + let Some(array) = RUNTIME.block_on(stream.next()).transpose()? else { + local + .file + .as_ref() + .vortex_expect("split without a file") + .finished + .store(true, Ordering::Release); + // Dropping the last clone drops the file's split queue; do that outside DuckDB's + // locks. + local.retired_splits.push(Split::V1(stream)); + return Ok(SplitItem::Done); }; local.split = Some(Split::V1(stream)); Ok(if array.is_empty() { @@ -366,7 +360,16 @@ fn next_split_item(local: &mut LocalState) -> VortexResult { let Some(array) = scan.next_array(&mut local.run)? else { return Ok(SplitItem::Done); }; - split_chunks(&mut local.pending, array) + // A V2 batch can join chunks of several layout chunks. Canonicalizing it + // would decode their dictionaries, so export each chunk on its own, as a V1 + // scan yields them. + match array.as_opt::() { + Some(chunked) => { + local.pending.extend(chunked.chunks().into_iter().rev()); + local.pending.pop().unwrap_or(array) + } + None => array, + } } }; local.split = Some(Split::V2); @@ -379,20 +382,6 @@ fn next_split_item(local: &mut LocalState) -> VortexResult { } } -/// The first chunk of `array`, leaving the rest in `pending` in reverse order. -/// -/// An array can join chunks of several layout chunks. Canonicalizing it would decode their -/// dictionaries, so export each chunk on its own. -fn split_chunks(pending: &mut Vec, array: ArrayRef) -> ArrayRef { - match array.as_opt::() { - Some(chunked) => { - pending.extend(chunked.chunks().into_iter().rev()); - pending.pop().unwrap_or(array) - } - None => array, - } -} - /// Called by all threads under global lock. If this function returns true, /// thread calls reader_scan on this file. If this function returns false, /// duckdb thinks file is exhausted, closes the file, and the first thread to diff --git a/vortex-layout/src/scan/split_queue.rs b/vortex-layout/src/scan/split_queue.rs index 49afc813c56..463eeb72828 100644 --- a/vortex-layout/src/scan/split_queue.rs +++ b/vortex-layout/src/scan/split_queue.rs @@ -37,6 +37,10 @@ type SplitTask = BoxFuture<'static, VortexResult>>; /// A worker yields only the splits it claimed, and claims a split only when it has room for one, /// so no worker waits on a split another one claimed. /// +/// A worker with room for one split has nothing to overlap it with, so it polls the split itself +/// rather than spawning it. The split then runs on the thread that polls the worker, which also +/// consumes its array, and no other thread driving the runtime picks it up. +/// /// [`RepeatedScan::execute`]: crate::scan::repeated_scan::RepeatedScan::execute pub(crate) struct SplitQueue { handle: Handle, @@ -76,9 +80,16 @@ impl SplitQueue { pub(crate) fn worker(self: Arc) -> BoxStream<'static, VortexResult> { let handle = self.handle.clone(); let per_worker = self.per_worker; + let splits = stream::iter(iter::from_fn(move || self.claim())); + if per_worker == 1 { + return splits + .then(|split| split) + .filter_map(|array| future::ready(array.transpose())) + .boxed(); + } // `buffer_unordered` pulls a split only when it has room, so a worker claims no more // than it runs. - stream::iter(iter::from_fn(move || self.claim())) + splits .map(move |split| handle.spawn(split)) .buffer_unordered(per_worker) .filter_map(|array| future::ready(array.transpose())) From 7fb994d718cc86047bfb33a02300cb2db1a6a764 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 21:01:50 -0500 Subject: [PATCH 6/7] Stop DuckDB threads joining a file once its splits are covered Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-duckdb/src/file_reader.rs | 29 ++++++++++++++--- vortex-layout/src/scan/layout.rs | 20 ++++++++++-- vortex-layout/src/scan/split_queue.rs | 11 ++++--- vortex-scan/src/stream.rs | 46 +++++++++++++++++++-------- 4 files changed, 80 insertions(+), 26 deletions(-) diff --git a/vortex-duckdb/src/file_reader.rs b/vortex-duckdb/src/file_reader.rs index c6c1969fcda..07f0c4b3c38 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; @@ -42,6 +43,7 @@ use vortex::layout::scan::v2::ScanFile; use vortex::mask::Mask; use vortex::scan::DataSource as _; use vortex::scan::ScanRequest; +use vortex::scan::stream::Claims; use vortex::scan::stream::ScanStream; use vortex::session::SessionExt as _; @@ -143,6 +145,8 @@ pub struct FileScanState { stream: OnceLock>, /// Whether a clone of `stream` has ended, so no split of the file is left to claim. finished: AtomicBool, + /// How many threads have joined the file, each with its own clone of `stream`. + joined: AtomicUsize, cache: ConversionCache, } @@ -159,9 +163,17 @@ impl FileScanState { if self.finished.load(Ordering::Acquire) { return None; } - self.stream - .get() - .map(|stream| Split::V1(stream.lock().clone())) + let stream = self.stream.get()?.lock(); + // A clone claims its first split 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 splits 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::V1(stream.clone())) } } @@ -179,6 +191,7 @@ impl OpenFileReader { v2: OnceLock::new(), stream: OnceLock::new(), finished: AtomicBool::new(false), + joined: AtomicUsize::new(0), cache: ConversionCache::default(), })), }) @@ -522,8 +535,14 @@ pub fn reader_get_progress_in_file(file: &OpenFileReader) -> f64 { state .stream .get() - .and_then(|stream| stream.lock().progress()) - .map_or(0.0, |progress| 100.0 * progress) + .and_then(|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/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 ae8d4bb31edd02e5e8984a81a73eb8422b193381 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Mon, 23 Nov 2026 19:48:54 -0500 Subject: [PATCH 7/7] Re-run pull request checks GitHub did not rebuild this pull request's merge ref after the previous push. Signed-off-by: Nicholas Gates Co-Authored-By: Claude Opus 5.5