diff --git a/vortex-duckdb/src/file_reader.rs b/vortex-duckdb/src/file_reader.rs index 0959cf5023e..c0fbbfd16b2 100644 --- a/vortex-duckdb/src/file_reader.rs +++ b/vortex-duckdb/src/file_reader.rs @@ -27,7 +27,6 @@ use vortex::file::multi::MultiFileSession; use vortex::file::multi::open_cached; use vortex::file::multi::parse_uri_or_path; use vortex::file::v2::FileStatsLayoutReader; -use vortex::functions::dynamic::DynamicExprUpdates; use vortex::io::compat::Compat; use vortex::io::filesystem::FileSystemRef; use vortex::io::object_store::ObjectStoreFileSystem; @@ -35,11 +34,9 @@ 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::DataSourceRef; use vortex::scan::ScanRequest; use vortex::scan::stream::Claims; use vortex::scan::stream::ScanExec; @@ -56,7 +53,6 @@ use crate::exporter::ArrayExporter; use crate::exporter::ConversionCache; use crate::projection::Filter; use crate::projection::extract_schema_from_dtype; -use crate::scan_v2::FileScan; use crate::table_function::BindState; use crate::table_function::GlobalState; use crate::table_function::LocalState; @@ -132,29 +128,30 @@ pub struct OpenFileReader { /// The state of an open file that the threads scanning it share. pub struct FileScanState { reader: LayoutReaderRef, - /// The file as the V2 executor reads it. - scan_file: ScanFile, - /// 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, + /// The file as a source whose scans run on the V2 executor. + plan_source: DataSourceRef, + /// The opened scan of the file, which each thread scanning the file reads a stream of. Set + /// when the file is initialized. + scan: OnceLock, cache: ConversionCache, } +/// The opened scan of a file. +struct FileExec { + exec: ScanExec, + /// Whether a batch can join chunks of several layout chunks, as a V2 batch can. + joins_chunks: bool, +} + 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)) + // A thread joins the file until its last unit of work, a V1 split or a V2 part, is taken, + // then moves on to the next file while the threads holding the last work finish it: 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 scan = self.scan.get()?; + (!scan.exec.is_exhausted()).then_some(Split(None)) } } @@ -162,15 +159,16 @@ impl OpenFileReader { async fn open(path: String) -> VortexResult { let (fs, fs_path) = resolve_filesystem(&parse_uri_or_path(&path)?)?; let source = fs.open_read(&fs_path).await?; - let file = open_cached(&SESSION, Some(&path), source, None, &|options| options).await?; - let mut scan_file = file.scan_file(); - scan_file.cache.get_or_insert_default(); + // Caching lets the V2 source cut its parts on the layout reader built here, and gives + // every V2 scan of the file one plan cache. + let file = open_cached(&SESSION, Some(&path), source, None, &|options| options) + .await? + .with_caching(); Ok(OpenFileReader { scan_state: Some(Arc::new(FileScanState { reader: file.layout_reader()?, - scan_file, - v2: OnceLock::new(), - exec: OnceLock::new(), + plan_source: file.plan_data_source(), + scan: OnceLock::new(), cache: ConversionCache::default(), })), }) @@ -241,27 +239,8 @@ pub fn reader_initialize(file: &mut OpenFileReader, global: &GlobalState) -> Vor return Ok(true); } - // 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 { - let state = file.scan_state(); - let splits = ScanBuilder::new(SESSION.clone(), Arc::clone(&state.reader)) - .with_projection(global.projection.clone()) - .with_some_filter(global.filter.filter.clone()) - .full_file_splits()?; - let dynamic = global - .filter - .filter - .as_ref() - .is_some_and(|filter| DynamicExprUpdates::new(filter).is_some()); - let scan = FileScan::try_new(v2_builder(state, global), &splits, dynamic)?; - if state.v2.set(scan).is_err() { - vortex_panic!("file initialized twice"); - } - return Ok(false); - } - + // Opening the file's scan is non-trivial work so we prefer doing it here under file lock and + // not in reader_try_initialize_scan under global lock. let state = file.scan_state(); let filter = &global.filter; let request = ScanRequest { @@ -271,16 +250,25 @@ 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, 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. + // one split at a time, polling it itself. A stream with room for more would claim splits + // other threads could have run, leaving them nothing on a file with few splits. A V2 + // stream always runs one part at a time. 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() { + // An unordered scan without a limit opens onto a queue of the file's work, V1 splits or V2 + // parts, whose streams each take the next once they have finished their last. + let exec = if global.scan_v2 { + RUNTIME.block_on(state.plan_source.scan(request))?.open()? + } else { + let source = LayoutReaderDataSource::new(Arc::clone(&state.reader), SESSION.clone()); + RUNTIME.block_on(source.scan(request))?.open()? + }; + let scan = FileExec { + exec, + joins_chunks: global.scan_v2, + }; + if state.scan.set(scan).is_err() { vortex_panic!("file initialized twice"); } Ok(false) @@ -296,17 +284,6 @@ fn file_rows(state: &FileScanState, filter: &Filter) -> Range { }) } -/// 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 rows = file_rows(state, filter); - V2ScanBuilder::new(SESSION.clone(), state.scan_file.clone()) - .with_projection(global.projection.clone()) - .with_some_filter(filter.filter.clone()) - .with_selection(filter.row_selection.clone()) - .with_row_range(rows) -} - /// What a thread's split yields next. enum SplitItem { /// The split has no more rows. @@ -318,65 +295,42 @@ enum SplitItem { /// Takes the next array of the thread's split, keeping the split while it has more to yield. fn next_split_item(local: &mut LocalState) -> VortexResult { - match local.split.take() { - None => Ok(SplitItem::Done), - 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))); + let array = match local.pending.pop() { + Some(array) => array, + None => { + let Some(Split(stream)) = local.split.take() else { 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 - .v2 + .scan .get() - .vortex_expect("V2 split of a file without a V2 scan"); - let array = match local.pending.pop() { - Some(array) => array, - None => { - 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, - } - } + .vortex_expect("split of a file without an opened scan"); + let mut stream = stream.unwrap_or_else(|| scan.exec.stream()); + let Some(array) = RUNTIME.block_on(stream.next()).transpose()? else { + // Dropping the last stream drops the file's queue of work; do that outside + // DuckDB's locks. + local.retired_splits.push(Split(Some(stream))); + return Ok(SplitItem::Done); }; - local.split = Some(Split::V2); - Ok(if array.is_empty() { - SplitItem::Empty - } else { - SplitItem::Array(array) - }) + local.split = Some(Split(Some(stream))); + let joins_chunks = scan.joins_chunks; + // 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::().filter(|_| joins_chunks) { + Some(chunked) => { + local.pending.extend(chunked.chunks().into_iter().rev()); + local.pending.pop().unwrap_or(array) + } + None => array, + } } - } + }; + Ok(if array.is_empty() { + SplitItem::Empty + } else { + SplitItem::Array(array) + }) } /// Called by all threads under global lock. If this function returns true, @@ -388,9 +342,9 @@ 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 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. + // A thread joins a file while its scan has work left to take. The 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() @@ -513,13 +467,10 @@ pub fn reader_get_progress_in_file(file: &OpenFileReader) -> f64 { let Some(state) = file.scan_state.as_ref() else { return 100.0; }; - if let Some(scan) = state.v2.get() { - return scan.progress(); - } state - .exec + .scan .get() - .and_then(ScanExec::progress) + .and_then(|scan| scan.exec.progress()) .map_or(0.0, |Claims { claimed, total }| { if total == 0 { 100.0 diff --git a/vortex-duckdb/src/lib.rs b/vortex-duckdb/src/lib.rs index 57712698666..73eba2133f0 100644 --- a/vortex-duckdb/src/lib.rs +++ b/vortex-duckdb/src/lib.rs @@ -31,7 +31,6 @@ mod exporter; mod ffi; mod file_reader; mod projection; -mod scan_v2; mod table_function; #[rustfmt::skip] diff --git a/vortex-duckdb/src/scan_v2.rs b/vortex-duckdb/src/scan_v2.rs deleted file mode 100644 index cc8fc4305d5..00000000000 --- a/vortex-duckdb/src/scan_v2.rs +++ /dev/null @@ -1,166 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// SPDX-FileCopyrightText: Copyright the Vortex contributors - -//! Drives a V2 scan for DuckDB. -//! -//! A planner says what it needs: compute, or reads. This driver decides where each runs, and -//! DuckDB's own threads run all of it. Each file is prepared once, and the thread that initializes -//! it cuts the scanned rows into parts on the file's layout splits, the units a V1 scan hands its -//! threads, after pruning the scan as a whole when its filter is dynamic. A thread takes the next -//! part and runs it on a run of its own, inline, waiting only for its reads: with a filter, the -//! part's pruning plans first, continuing into the chunks of the rows pruning kept; without, the -//! chunks directly. Threads join the file only while parts are left, so the threads a file -//! cannot use move on to the next file. - -use std::collections::VecDeque; -use std::future; -use std::sync::Arc; -use std::sync::atomic::AtomicBool; -use std::sync::atomic::AtomicU64; -use std::sync::atomic::Ordering; - -use parking_lot::Mutex; -use vortex::array::ArrayRef; -use vortex::error::VortexResult; -use vortex::io::request::IoService; -use vortex::io::runtime::BlockingRuntime as _; -use vortex::layout::scan::v2::ScanBuilder; -use vortex::scan::planning::driver::Progress; -use vortex::scan::planning::driver::Run; -use vortex::scan::planning::planner::Planner; -use vortex::scan::planning::planner::WorkScope; -use vortex::scan::prepare::PreparedScan; -use vortex::scan::prepare::part_root; - -use crate::RUNTIME; - -/// The chunks a thread runs beside each other on its run, so one chunk's reads overlap another's -/// compute. -const CHUNKS_PER_THREAD: usize = 1; - -/// One file's V2 scan, shared by the threads scanning it. -pub(crate) struct FileScan { - scan: Arc, - io: Arc, - /// The work the root spawned, in row order, that no thread has taken yet. - queue: Mutex>, - /// Set once a thread has taken the last of `queue`. - exhausted: AtomicBool, - /// The rows of the chunks taken so far, for DuckDB's progress bar. - rows_taken: AtomicU64, -} - -/// What a thread takes from the file next. -enum Work { - /// A chunk to run on the thread's run. - Chunk(WorkScope, Box), - /// A batch the root produced itself. - Batch(ArrayRef), -} - -impl FileScan { - /// Prepares `builder`, composes its planners, and runs the root until it has spawned the - /// planner of every part. The root only prunes the scan, for a dynamic filter, and cuts parts, - /// so this reads zone maps at most. - /// - /// Running the root up front leaves the file with a known list of parts, like the splits of a - /// V1 scan: a thread joins the file only while a part is left, and the threads DuckDB has to - /// spare move on to the next file instead of waiting for this file's root. - /// - /// `splits` are the file's layout split boundaries, as a V1 scan of the same fields cuts it. - /// `dynamic` says the filter's value changes while the scan runs, as a top-N's bound does. - pub(crate) fn try_new( - builder: ScanBuilder, - splits: &[u64], - dynamic: bool, - ) -> VortexResult { - let scan = Arc::new(builder.prepare()?); - let io = scan.io(); - let rows = scan.rows().clone(); - let mut root = Run::new(); - root.admit( - part_root(&scan, splits, dynamic), - WorkScope { - file_ordinal: 0, - rows, - }, - io.session(), - ); - let mut queue = VecDeque::new(); - loop { - match root.advance()? { - Progress::Batch(batch) => queue.push_back(Work::Batch(batch.array)), - Progress::Spawn(scope, chunk) => queue.push_back(Work::Chunk(scope, chunk)), - Progress::RootDone(_) if root.live_roots() > 0 => {} - Progress::RootDone(_) | Progress::Idle => break, - Progress::Waiting => { - RUNTIME.block_on(future::poll_fn(|cx| root.poll_completion(cx)))?; - } - } - } - Ok(Self { - scan, - io, - exhausted: AtomicBool::new(queue.is_empty()), - queue: Mutex::new(queue), - rows_taken: AtomicU64::new(0), - }) - } - - /// Whether every chunk has been taken, so a thread joining the scan finds no work. - pub(crate) fn is_exhausted(&self) -> bool { - self.exhausted.load(Ordering::Acquire) - } - - /// The percentage of the scanned rows whose chunks threads have taken. - pub(crate) fn progress(&self) -> f64 { - let rows = self.scan.rows(); - let total = rows.end - rows.start; - if total == 0 || self.exhausted.load(Ordering::Relaxed) { - return 100.0; - } - 100.0 * self.rows_taken.load(Ordering::Relaxed) as f64 / total as f64 - } - - /// The next array of this file for the thread whose run is `run`, or `None` once the file has - /// no more work for the thread. Keeps the thread's run fed with chunks from the file, and - /// waits for reads on the calling thread. - pub(crate) fn next_array(&self, run: &mut Run) -> VortexResult> { - loop { - while run.live_roots() < CHUNKS_PER_THREAD { - match self.next_work() { - Some(Work::Chunk(scope, chunk)) => { - run.admit(chunk, scope, self.io.session()); - } - Some(Work::Batch(array)) => return Ok(Some(array)), - None => break, - } - } - match run.advance()? { - Progress::Batch(batch) => return Ok(Some(batch.array)), - Progress::Spawn(scope, child) => { - run.admit(child, scope, self.io.session()); - } - Progress::RootDone(_) => {} - Progress::Idle => return Ok(None), - Progress::Waiting => { - RUNTIME.block_on(future::poll_fn(|cx| run.poll_completion(cx)))?; - } - } - } - } - - /// Takes the next chunk or batch of the file, or `None` once every one has been taken. - fn next_work(&self) -> Option { - let mut queue = self.queue.lock(); - let work = queue.pop_front()?; - if queue.is_empty() { - self.exhausted.store(true, Ordering::Release); - } - if let Work::Chunk(scope, _) = &work { - self.rows_taken - .fetch_add(scope.rows.end - scope.rows.start, Ordering::Relaxed); - } - Some(work) - } -} diff --git a/vortex-duckdb/src/table_function.rs b/vortex-duckdb/src/table_function.rs index 401a8753963..da22e5c9db7 100644 --- a/vortex-duckdb/src/table_function.rs +++ b/vortex-duckdb/src/table_function.rs @@ -33,7 +33,6 @@ use vortex::error::VortexResult; use vortex::error::vortex_bail; use vortex::error::vortex_ensure; use vortex::error::vortex_err; -use vortex::expr::BoundExpression; use vortex::expr::Expression; use vortex::expr::col; use vortex::expr::proto::ExprSerializeProtoExt; @@ -41,7 +40,6 @@ use vortex::expr::proto::ExprSerializeProtoExt; 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; @@ -182,8 +180,7 @@ impl<'a> TableInitInput<'a> { } pub struct GlobalState { - pub projection: BoundExpression, - /// The projection before binding, for scans that bind it against each file. + /// The projection before binding, which each file's scan binds against the file. pub projection_expr: Expression, pub filter: Filter, pub file_row_number_column_pos: Option, @@ -205,15 +202,11 @@ pub struct AggregateState { } assert_impl_all!(GlobalState: Send, Sync); -/// The scan work that one thread does on a file. -pub enum Split { - /// 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, -} +/// The scan work that one thread does on a file: a stream of the file's opened scan, which the +/// thread polls inline. It takes the file's work as it has room for it until none is left, and +/// yields only the work it took. `None` until the thread's first scan call creates it, outside +/// DuckDB's lock. +pub struct Split(pub Option); /// field position, accumulator pub type Partials = Vec<(usize, Box)>; @@ -228,8 +221,6 @@ pub struct LocalState { /// 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 an array that this thread has yet to export, in reverse order. pub(crate) pending: Vec, @@ -357,11 +348,8 @@ 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, + projection_expr: projection, filter, aggregates: bind_data.aggregates.clone(), has_count_star, @@ -438,16 +426,11 @@ pub fn init_local(bind_data: &BindState, global: &GlobalState) -> LocalState { file: None, retired_files: Vec::new(), retired_splits: Vec::new(), - run: Run::new(), pending: Vec::new(), finished: false, } } -pub(crate) fn optimize_and_bind(expr: Expression, dtype: &DType) -> VortexResult { - expr.bind(dtype)?.optimize_recursive() -} - pub(crate) fn convert_result(array: ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult { // By the time we got here, array is fully optimized, don't call // optimize_recursive or similar functions here.