diff --git a/vortex-duckdb/src/file_reader.rs b/vortex-duckdb/src/file_reader.rs index 54bdeba6856..0959cf5023e 100644 --- a/vortex-duckdb/src/file_reader.rs +++ b/vortex-duckdb/src/file_reader.rs @@ -1,12 +1,15 @@ // 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; 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 +34,15 @@ 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::Claims; +use vortex::scan::stream::ScanExec; use vortex::session::SessionExt as _; use crate::REGISTRY; @@ -111,17 +119,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 +137,27 @@ 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 V1 scan of the file, which each thread scanning the file reads a stream of. Set + /// when the file is initialized for a V1 scan. + exec: OnceLock, 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 thread joins the file until its last split is claimed, then moves on to the next file + // while the threads holding the last splits finish them: no thread waits for the rest of + // a file to drain. The thread creates its stream on its first scan call, outside DuckDB's + // lock. + let exec = self.exec.get()?; + (!exec.is_exhausted()).then_some(Split::V1(None)) + } +} + impl OpenFileReader { async fn open(path: String) -> VortexResult { let (fs, fs_path) = resolve_filesystem(&parse_uri_or_path(&path)?)?; @@ -147,10 +170,9 @@ impl OpenFileReader { reader: file.layout_reader()?, scan_file, v2: OnceLock::new(), + exec: OnceLock::new(), cache: ConversionCache::default(), })), - splits: vec![], - total_splits: 0, }) } @@ -219,7 +241,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 +262,44 @@ 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, + // DuckDB runs one thread per core, so its threads are the scan's parallelism: each runs + // 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() + }; + // An unordered scan without a limit opens onto a queue of the file's splits, whose streams + // each claim the next split once they have finished their last. + let source = LayoutReaderDataSource::new(Arc::clone(&state.reader), SESSION.clone()); + let exec = RUNTIME.block_on(source.scan(request))?.open()?; + if state.exec.set(exec).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 +320,31 @@ 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(stream)) => { + let mut stream = match stream { + Some(stream) => stream, + None => local + .file + .as_ref() + .vortex_expect("split without a file") + .exec + .get() + .vortex_expect("V1 split of a file without a V1 scan") + .stream(), + }; + let Some(array) = RUNTIME.block_on(stream.next()).transpose()? else { + // Dropping the last stream drops the file's split queue; do that outside DuckDB's + // locks. + local.retired_splits.push(Split::V1(Some(stream))); + return Ok(SplitItem::Done); + }; + local.split = Some(Split::V1(Some(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 @@ -333,14 +388,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 + // scan has a split left to claim. Either check is one load of a flag that is + // written once, 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 +415,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 +427,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 +509,24 @@ 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 + .exec + .get() + .and_then(ScanExec::progress) + .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-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..401a8753963 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,12 @@ 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 stream of the file's V1 scan, 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. `None` + /// until the thread's first scan call creates it, outside DuckDB's lock. + V1(Option), /// Chunks of the file's V2 scan, taken by the thread until the scan has none left. V2, } @@ -220,12 +224,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 +357,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 +437,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, diff --git a/vortex-layout/src/scan/layout.rs b/vortex-layout/src/scan/layout.rs index 2b1551bb7de..b4d40d57020 100644 --- a/vortex-layout/src/scan/layout.rs +++ b/vortex-layout/src/scan/layout.rs @@ -444,9 +444,11 @@ impl DataSourceScan for LayoutReaderScan { splits, exhausted.clone(), )); - Ok(ScanExec::new(self.dtype, exhausted, move || { - Arc::clone(&queue).worker() - })) + let progress = Arc::clone(&queue); + Ok( + ScanExec::new(self.dtype, exhausted, move || Arc::clone(&queue).worker()) + .with_progress(move || progress.claims()), + ) } fn partition_count(&self) -> Precision { @@ -1219,6 +1221,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; @@ -1242,12 +1245,26 @@ mod split_open_tests { .block_on(source(&runtime).scan(ScanRequest::default()))? .open()?; assert!(!exec.is_exhausted()); + assert_eq!( + exec.progress(), + Some(Claims { + claimed: 0, + total: 16 + }) + ); let workers = (0..3).map(|_| exec.stream().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!(exec.is_exhausted()); + assert_eq!( + exec.progress(), + 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 1f25fde5d1b..82cc721ac3b 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; @@ -16,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 vortex_scan::stream::ExhaustedFlag; use crate::scan::repeated_scan::ScanTasks; @@ -45,6 +48,8 @@ pub(crate) struct SplitQueue { handle: Handle, per_worker: usize, splits: Mutex>, + total: usize, + claimed: AtomicUsize, /// Set once the last split is claimed. exhausted: ExhaustedFlag, } @@ -62,7 +67,9 @@ impl SplitQueue { Self { handle, per_worker: per_worker.max(1), + total: splits.len(), splits: Mutex::new(splits.into_iter()), + claimed: AtomicUsize::new(0), exhausted, } } @@ -75,9 +82,19 @@ impl SplitQueue { if splits.len() == 0 { self.exhausted.set(); } + drop(splits); + self.claimed.fetch_add(1, Ordering::Relaxed); Some(split) } + /// How many of the splits the scan's streams 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, + } + } + /// A new worker over the shared queue, which one stream of the scan polls. pub(crate) fn worker(self: Arc) -> BoxStream<'static, VortexResult> { let handle = self.handle.clone(); diff --git a/vortex-scan/src/stream.rs b/vortex-scan/src/stream.rs index cd7a9154c04..2de6ce2cd3e 100644 --- a/vortex-scan/src/stream.rs +++ b/vortex-scan/src/stream.rs @@ -26,6 +26,21 @@ 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 how many units of an opened scan's work its streams have claimed. +type ReadProgress = dyn Fn() -> Claims + Send + Sync; + +/// How many units of an opened scan's work its streams have claimed, out of how many in all. +/// +/// A unit is what one stream 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 streams have claimed so far. + pub claimed: usize, + /// The units of the scan in all. + pub total: usize, +} + /// A flag that an opened scan sets once no stream created afterwards would find work. /// /// It is set at most once and never cleared, so hosts read it from a cache line that is almost @@ -70,6 +85,7 @@ pub struct ScanExec { dtype: DType, exhausted: ExhaustedFlag, new_worker: Arc, + progress: Option>, } impl ScanExec { @@ -88,9 +104,17 @@ impl ScanExec { dtype, exhausted, new_worker: Arc::new(new_worker), + progress: None, } } + /// This scan, reporting through `progress` how many units of its work its streams have + /// claimed, out of how many in all. `progress` must never block. + pub fn with_progress(mut self, progress: impl Fn() -> Claims + Send + Sync + 'static) -> Self { + self.progress = Some(Arc::new(progress)); + self + } + /// An opened scan whose streams 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. It does not know its @@ -136,6 +160,16 @@ impl ScanExec { self.exhausted.is_set() } + /// How many units of the scan's work its streams have claimed, out of how many in all, or + /// `None` when the source does not know its total up front, as for + /// [`Self::from_partitions`]. Never blocks. + /// + /// This is for reporting progress. A host decides whether to join the scan with + /// [`is_exhausted`](Self::is_exhausted). + pub fn progress(&self) -> Option { + self.progress.as_ref().map(|progress| progress()) + } + /// A new stream over the scan's remaining work, which one host thread or partition reads. pub fn stream(&self) -> ScanStream { ScanStream {