diff --git a/vortex-duckdb/src/file_reader.rs b/vortex-duckdb/src/file_reader.rs index 70d8d30c6cb..59505a4a229 100644 --- a/vortex-duckdb/src/file_reader.rs +++ b/vortex-duckdb/src/file_reader.rs @@ -7,6 +7,8 @@ use std::sync::atomic::AtomicBool; use std::sync::atomic::Ordering; use futures::FutureExt; +use futures::StreamExt as _; +use futures::TryStreamExt as _; use object_store::registry::ObjectStoreRegistry; use url::Url; use vortex::array::ArrayRef; @@ -20,6 +22,7 @@ use vortex::error::VortexExpect; use vortex::error::VortexResult; use vortex::error::vortex_err; use vortex::error::vortex_panic; +use vortex::expr::stats::Precision; use vortex::file::Footer; use vortex::file::multi::MultiFileSession; use vortex::file::multi::open_cached; @@ -31,10 +34,12 @@ 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::session::SessionExt as _; use crate::REGISTRY; @@ -209,49 +214,38 @@ pub fn reader_bind(file: &OpenFileReader, result: &mut BindResultRef) -> VortexR } /// Called once per file by one thread under file-local lock. Determines -/// whether the opened file should be skipped. If this function returns false, +/// whether the opened file should be skipped. If this function returns true, /// duckdb closes the file and doesn't call reader_try_initialize_scan on it. +/// +/// Planning 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. pub fn reader_initialize(file: &mut OpenFileReader, global: &GlobalState) -> VortexResult { - if file.can_skip(&global.filter)? { - // DuckDB releases a skipped file under the global lock. Here only the - // file-local lock is held, so drop the scan state now. - file.scan_state = None; - return Ok(true); - } - - // Getting splits, 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); + initialize_v2(file, global) + } else { + initialize_v1(file, global) } +} - let reader = Arc::clone(file.reader()); - 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())? +/// Plans the file's V1 scan through the Scan API. Each partition is one +/// layout split, which a thread claims whole. +fn initialize_v1(file: &mut OpenFileReader, global: &GlobalState) -> VortexResult { + let source = LayoutReaderDataSource::new(Arc::clone(file.reader()), SESSION.clone()) + .with_layout_split_partitions(); + let partitions = RUNTIME.block_on(async { + let scan = source.scan(global.scan_request.clone()).await?; + scan.partitions().try_collect::>().await + })?; + let mut splits = partitions .into_iter() - .map(Split::V1) - .collect(); + .filter(|partition| !matches!(partition.row_count(), Precision::Exact(0))) + .map(|partition| partition.execute().map(Split::V1)) + .collect::>>()?; + + if splits.is_empty() { + skip_file(file); + return Ok(true); + } // threads take last element of file.splits so we need to reverse splits.reverse(); @@ -260,6 +254,37 @@ pub fn reader_initialize(file: &mut OpenFileReader, global: &GlobalState) -> Vor Ok(false) } +fn initialize_v2(file: &mut OpenFileReader, global: &GlobalState) -> VortexResult { + if file.can_skip(&global.filter)? { + skip_file(file); + return Ok(true); + } + + 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"); + } + Ok(false) +} + +/// Releases the scan state of a file that DuckDB will skip. +/// +/// DuckDB releases a skipped file under the global lock. Here only the +/// file-local lock is held, so drop the scan state now. +fn skip_file(file: &mut OpenFileReader) { + file.scan_state = None; +} + /// 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; @@ -287,9 +312,18 @@ 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 Some(array) = RUNTIME.block_on(stream.next()) else { + return Ok(SplitItem::Done); + }; + let array = 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 diff --git a/vortex-duckdb/src/projection.rs b/vortex-duckdb/src/projection.rs index 68a7c8cd454..a0581181620 100644 --- a/vortex-duckdb/src/projection.rs +++ b/vortex-duckdb/src/projection.rs @@ -190,6 +190,9 @@ impl Projection { } pub struct Filter { + /// The conjunction of the pushed-down filters, as the Scan API takes it. + pub expression: Option, + /// `expression` bound to the scan's dtype. pub filter: Option, pub row_selection: Selection, pub row_range: Option>, @@ -257,11 +260,14 @@ impl Filter { } }; - let filter = and_collect(table_filter_exprs) + let expression = and_collect(table_filter_exprs); + let filter = expression + .as_ref() .map(|expr| expr.bind(dtype)?.optimize_recursive()) .transpose()?; let out = Self { + expression, filter, row_selection, row_range, diff --git a/vortex-duckdb/src/table_function.rs b/vortex-duckdb/src/table_function.rs index e96dd83d12c..dab6047c934 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; @@ -24,6 +23,7 @@ use vortex::array::Canonical; use vortex::array::ExecutionCtx; use vortex::array::arrays::Struct; use vortex::array::arrays::StructArray; +use vortex::array::stream::SendableArrayStream; use vortex::dtype::DType; use vortex::dtype::Nullability; use vortex::dtype::PType; @@ -42,6 +42,7 @@ 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::ScanRequest; use vortex::scan::planning::driver::Run; use vortex_utils::aliases::hash_map::HashMap; @@ -182,6 +183,8 @@ impl<'a> TableInitInput<'a> { } pub struct GlobalState { + /// The request the V1 scan sends to each file's Scan API source. + pub scan_request: ScanRequest, pub projection: BoundExpression, pub filter: Filter, pub file_row_number_column_pos: Option, @@ -205,8 +208,8 @@ assert_impl_all!(GlobalState: Send, Sync); /// A unit of scan work that one thread takes at a time. pub enum Split { - /// A V1 scan task yielding one array, or `None` if the filter removed every row. - V1(BoxFuture<'static, VortexResult>>), + /// The stream of a Scan API partition of the file: one layout split of a V1 scan. + V1(SendableArrayStream), /// Chunks of the file's V2 scan, taken by the thread until the scan has none left. V2, } @@ -352,8 +355,16 @@ pub fn init_global(init_input: &TableInitInput) -> VortexResult { "table function scan input" ); + let scan_request = ScanRequest { + projection: projection.clone(), + filter: filter.expression.clone(), + row_range: filter.row_range.clone(), + selection: filter.row_selection.clone(), + ..ScanRequest::default() + }; let projection = optimize_and_bind(projection, &bind_data.dtype)?; Ok(GlobalState { + scan_request, projection, filter, aggregates: bind_data.aggregates.clone(), diff --git a/vortex-layout/src/scan/layout.rs b/vortex-layout/src/scan/layout.rs index a0ab69310f8..aebad45dc22 100644 --- a/vortex-layout/src/scan/layout.rs +++ b/vortex-layout/src/scan/layout.rs @@ -12,8 +12,11 @@ use std::task::Poll; use async_trait::async_trait; use futures::FutureExt; use futures::Stream; +use futures::future; +use futures::future::BoxFuture; use futures::stream; use futures::stream::StreamExt; +use vortex_array::ArrayRef; use vortex_array::IntoArray; use vortex_array::arrays::ConstantArray; use vortex_array::dtype::DType; @@ -50,10 +53,20 @@ use crate::scan::scan_builder::ScanBuilder; pub struct LayoutReaderDataSource { reader: LayoutReaderRef, session: VortexSession, - split_max_row_count: u64, + partitioning: Partitioning, metrics: Option, } +/// How a [`LayoutReaderDataSource`] cuts a scan into partitions. +#[derive(Clone, Copy)] +enum Partitioning { + /// Partitions of at most this many rows. Each runs its own [`ScanBuilder`] stream, which + /// keeps several of its layout splits in flight on the session's runtime. + MaxRows(u64), + /// One partition per layout split, polled on the task that polls its stream. + LayoutSplits, +} + impl LayoutReaderDataSource { /// Creates a new [`LayoutReaderDataSource`]. /// @@ -65,7 +78,7 @@ impl LayoutReaderDataSource { Self { reader, session, - split_max_row_count: u64::MAX, + partitioning: Partitioning::MaxRows(u64::MAX), metrics: None, } } @@ -76,7 +89,21 @@ impl LayoutReaderDataSource { /// physical layout alignment and I/O pipelining. This controls the engine-level /// parallelism granularity, not the I/O granularity. pub fn with_split_max_row_count(mut self, row_count: u64) -> Self { - self.split_max_row_count = row_count; + self.partitioning = Partitioning::MaxRows(row_count); + self + } + + /// Makes each layout split of the scanned fields its own partition, for hosts that run one + /// partition per thread and want the splits a V1 scan would otherwise run internally. + /// + /// The scan is prepared once, in [`DataSource::scan`], and its partitions share that + /// preparation. A partition's stream does its split's work on the task that polls it and + /// spawns nothing, so the host gets parallelism by polling several partitions at once. + /// + /// A scan with a limit keeps one partition for the whole range: its splits must share the + /// limit, which a split polled on its own cannot do. + pub fn with_layout_split_partitions(mut self) -> Self { + self.partitioning = Partitioning::LayoutSplits; self } @@ -117,7 +144,9 @@ impl DataSource for LayoutReaderDataSource { async fn scan(&self, scan_request: ScanRequest) -> VortexResult { let total_rows = self.reader.row_count(); - let row_range = scan_request.row_range.unwrap_or(0..total_rows); + let row_range = scan_request.row_range.map_or(0..total_rows, |range| { + range.start.min(total_rows)..range.end.min(total_rows) + }); let projection = scan_request .projection @@ -188,6 +217,21 @@ impl DataSource for LayoutReaderDataSource { } } + let split_size = match self.partitioning { + Partitioning::LayoutSplits if scan_request.limit.is_none() => { + return self.layout_split_scan( + dtype, + projection, + filter, + row_range, + scan_request.selection, + scan_request.ordered, + ); + } + Partitioning::LayoutSplits => u64::MAX, + Partitioning::MaxRows(row_count) => row_count, + }; + // Only unordered scans share a limit across external partitions: reservation order is // completion order, which an ordered scan cannot accept. Ordered partitions each apply // the limit locally and the engine trims the concatenated result. @@ -209,7 +253,7 @@ impl DataSource for LayoutReaderDataSource { metrics: self.metrics.clone(), next_row: row_range.start, end_row: row_range.end, - split_size: self.split_max_row_count, + split_size, })) } @@ -218,6 +262,109 @@ impl DataSource for LayoutReaderDataSource { } } +impl LayoutReaderDataSource { + /// Prepares one V1 scan over `row_range` and makes each of its layout splits a partition. + fn layout_split_scan( + &self, + dtype: DType, + projection: BoundExpression, + filter: Option, + row_range: Range, + selection: Selection, + ordered: bool, + ) -> VortexResult { + let is_filtered = filter.is_some(); + let scan = ScanBuilder::new(self.session.clone(), Arc::clone(&self.reader)) + .with_projection(projection) + .with_some_filter(filter) + .with_row_range(row_range) + .with_selection(selection.clone()) + .with_ordered(ordered) + .with_some_scan_metrics(self.metrics.clone()) + .prepare()?; + let partitions = scan + .execute_splits(None)? + .into_iter() + .map(|split| { + let rows = selection.row_count_in_range(&split.row_range); + LayoutSplitPartition { + dtype: dtype.clone(), + row_count: if is_filtered { + Precision::inexact(rows) + } else { + Precision::exact(rows) + }, + row_range: split.row_range, + task: split.task, + } + }) + .collect(); + Ok(Box::new(LayoutSplitScan { dtype, partitions })) + } +} + +/// The partitions of a scan prepared once, one per layout split. +struct LayoutSplitScan { + dtype: DType, + partitions: Vec, +} + +impl DataSourceScan for LayoutSplitScan { + fn dtype(&self) -> &DType { + &self.dtype + } + + fn partition_count(&self) -> Precision { + Precision::exact(self.partitions.len()) + } + + fn partitions(self: Box) -> PartitionStream { + stream::iter( + self.partitions + .into_iter() + .map(|partition| Ok(Box::new(partition) as PartitionRef)), + ) + .boxed() + } +} + +/// One layout split of a prepared V1 scan. +struct LayoutSplitPartition { + dtype: DType, + row_range: Range, + row_count: Precision, + /// The split's work: it yields the split's array, or `None` when the filter removes every + /// row. It spawns nothing. + task: BoxFuture<'static, VortexResult>>, +} + +impl Partition for LayoutSplitPartition { + fn as_any(&self) -> &dyn Any { + self + } + + #[expect(clippy::cast_possible_truncation)] + fn index(&self) -> usize { + // Row range is unique per split + self.row_range.start as usize + } + + fn row_count(&self) -> Precision { + self.row_count + } + + fn byte_size(&self) -> Precision { + Precision::Absent + } + + fn execute(self: Box) -> VortexResult { + let arrays = stream::once(self.task).filter_map(|array| future::ready(array.transpose())); + Ok(ArrayStreamExt::boxed(ArrayStreamAdapter::new( + self.dtype, arrays, + ))) + } +} + struct LayoutReaderScan { reader: LayoutReaderRef, session: VortexSession, @@ -460,6 +607,7 @@ mod tests { use futures::TryStreamExt; use rstest::rstest; use vortex_array::expr::root; + use vortex_array::expr::stats::Precision; use vortex_buffer::Buffer; use vortex_error::VortexResult; use vortex_io::runtime::BlockingRuntime; @@ -555,6 +703,44 @@ mod tests { Ok(()) } + /// Layout-split partitions follow the reader's splits, and a row range past the end of the + /// source is clamped to it. + #[test] + fn layout_split_partitions_follow_splits() -> VortexResult<()> { + let runtime = SingleThreadRuntime::default(); + let session = session_with_handle(runtime.handle()); + let reader = TestLayoutReader::new(10).with_split_size(4); + let source = + LayoutReaderDataSource::new(Arc::new(reader), session).with_layout_split_partitions(); + + let scan = runtime.block_on(source.scan(ScanRequest { + row_range: Some(0..20), + ..Default::default() + }))?; + let partitions = runtime.block_on(scan.partitions().try_collect::>())?; + let row_counts = partitions + .iter() + .map(|partition| partition.row_count()) + .collect::>(); + assert_eq!( + row_counts, + [ + Precision::exact(4u64), + Precision::exact(4u64), + Precision::exact(2u64) + ] + ); + + let mut values = Vec::new(); + for partition in partitions { + values.extend(collect_scan_values( + runtime.block_on_stream(partition.execute()?), + )?); + } + assert_eq!(values, (0..10).collect::>()); + Ok(()) + } + /// An unordered limit is shared by every partition of the scan, so the partitions together /// return no more rows than the limit. #[test] diff --git a/vortex-layout/src/scan/repeated_scan.rs b/vortex-layout/src/scan/repeated_scan.rs index 2a1c7026923..1d6f8fff915 100644 --- a/vortex-layout/src/scan/repeated_scan.rs +++ b/vortex-layout/src/scan/repeated_scan.rs @@ -83,6 +83,12 @@ pub struct RepeatedScan { /// Split tasks for one scan execution. pub type ScanTasks = Vec>>>; +/// One split's future and the rows it covers. +pub(crate) struct SplitTask { + pub(crate) row_range: Range, + pub(crate) task: BoxFuture<'static, VortexResult>>, +} + /// A function applied to each projected split array. type MapFn = Arc VortexResult + Send + Sync>; @@ -117,6 +123,18 @@ impl RepeatedScan { /// Scans with row limits must use [`Self::execute_stream`] so the scan can coordinate the /// limit across splits. pub fn execute(&self, row_range: Option>) -> VortexResult> { + Ok(self + .execute_splits(row_range)? + .into_iter() + .map(|split| split.task) + .collect()) + } + + /// Like [`Self::execute`], but pairs each split future with the rows it covers. + pub(crate) fn execute_splits( + &self, + row_range: Option>, + ) -> VortexResult>> { if self.limit.is_some() { vortex_bail!("Split futures do not support row limits; use a scan stream or iterator"); } @@ -127,7 +145,11 @@ impl RepeatedScan { return Ok(Vec::new()); } masks - .map(|mask| Ok(map_split(split_exec(&ctx, mask)?, &self.map_fn))) + .map(|mask| { + let row_range = mask.row_range(); + let task = map_split(split_exec(&ctx, mask)?, &self.map_fn); + Ok(SplitTask { row_range, task }) + }) .collect() } diff --git a/vortex-scan/src/lib.rs b/vortex-scan/src/lib.rs index 891c202fe11..65e6924bf18 100644 --- a/vortex-scan/src/lib.rs +++ b/vortex-scan/src/lib.rs @@ -243,9 +243,11 @@ pub trait Partition: 'static + Send { /// Executes the partition, returning an array stream. /// /// This method must be fast. The returned stream should be lazy — all non-trivial work - /// (I/O, decoding, filtering) must be deferred to when the stream is polled. Expensive - /// operations should be spawned onto the runtime to enable parallel execution across - /// threads. + /// (I/O, decoding, filtering) must be deferred to when the stream is polled. A partition + /// that holds several units of work should spawn them onto the runtime so they run in + /// parallel. A partition that is a single unit, such as one layout split, may do its work + /// on the task that polls the stream; the host then gets parallelism by polling several + /// partitions at once. fn execute(self: Box) -> VortexResult; }