diff --git a/Cargo.lock b/Cargo.lock index f3939e4f95c..9e924c82e80 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -11164,6 +11164,7 @@ dependencies = [ "vortex-error", "vortex-fsst", "vortex-functions", + "vortex-io", "vortex-mask", "vortex-onpair", "vortex-scan", diff --git a/vortex-arrow/Cargo.toml b/vortex-arrow/Cargo.toml index cbb3e8d6f39..48868dd074f 100644 --- a/vortex-arrow/Cargo.toml +++ b/vortex-arrow/Cargo.toml @@ -41,6 +41,7 @@ vortex-array = { workspace = true } vortex-buffer = { workspace = true, features = ["arrow"] } vortex-error = { workspace = true } vortex-functions = { workspace = true } +vortex-io = { workspace = true } vortex-mask = { workspace = true } vortex-scan = { workspace = true } vortex-session = { workspace = true } diff --git a/vortex-arrow/src/lib.rs b/vortex-arrow/src/lib.rs index dea929599ff..8970cc6c1fa 100644 --- a/vortex-arrow/src/lib.rs +++ b/vortex-arrow/src/lib.rs @@ -39,6 +39,7 @@ mod run_end_import; mod scalar; mod scan; mod session; +mod stream; #[cfg(feature = "_test-harness")] pub mod test_harness; #[cfg(test)] @@ -55,3 +56,4 @@ pub use options::*; pub use scalar::ToArrowDatum; pub use scan::ArrowScanExt; pub use session::*; +pub use stream::ArrowArrayStreamExt; diff --git a/vortex-arrow/src/stream.rs b/vortex-arrow/src/stream.rs new file mode 100644 index 00000000000..84a6331d943 --- /dev/null +++ b/vortex-arrow/src/stream.rs @@ -0,0 +1,116 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Arrow output for array streams. + +use std::future; +use std::num::NonZeroUsize; +use std::sync::Arc; + +use arrow_array::RecordBatch; +use arrow_array::cast::AsArray; +use arrow_schema::Field; +use arrow_schema::SchemaRef; +use futures::StreamExt; +use futures::stream; +use futures::stream::BoxStream; +use vortex_array::VortexSessionExecute; +use vortex_array::stream::ArrayStream; +use vortex_error::VortexResult; +use vortex_io::session::RuntimeSessionExt; +use vortex_session::VortexSession; + +use crate::ArrowSessionExt; +use crate::ExecuteArrowExt; + +/// Arrow record-batch output for an [`ArrayStream`], such as a piece of a split scan. +pub trait ArrowArrayStreamExt: ArrayStream + Send + Sized + 'static { + /// Converts each array of the stream to an Arrow [`RecordBatch`] with `schema`. + /// + /// Each conversion runs as a CPU task on the session's runtime, with at most `concurrency` + /// in flight, and the batches keep the stream's order. When `schema` is `None`, the session + /// derives it from the stream's dtype. + fn to_arrow( + self, + session: &VortexSession, + schema: Option, + concurrency: NonZeroUsize, + ) -> BoxStream<'static, VortexResult> { + let schema = match schema { + Some(schema) => schema, + None => match session.arrow().to_arrow_schema(self.dtype()) { + Ok(schema) => Arc::new(schema), + Err(error) => return stream::once(future::ready(Err(error))).boxed(), + }, + }; + let field = Arc::new(Field::new_struct("", schema.fields().clone(), false)); + let session = session.clone(); + let handle = session.handle(); + self.map(move |array| { + let session = session.clone(); + let field = Arc::clone(&field); + handle.spawn_cpu(move || { + let arrow = + array?.execute_arrow(Some(&field), &mut session.create_execution_ctx())?; + Ok(RecordBatch::from(arrow.as_struct().clone())) + }) + }) + .buffered(concurrency.get()) + .boxed() + } +} + +impl ArrowArrayStreamExt for S {} + +#[cfg(test)] +mod tests { + use std::num::NonZeroUsize; + + use arrow_array::cast::AsArray; + use arrow_array::types::Int32Type; + use futures::TryStreamExt; + use futures::stream; + use vortex_array::IntoArray; + use vortex_array::arrays::StructArray; + use vortex_array::stream::ArrayStreamAdapter; + use vortex_buffer::buffer; + use vortex_error::VortexResult; + use vortex_io::runtime::single::block_on; + use vortex_io::session::RuntimeSessionExt; + use vortex_session::VortexSession; + + use super::ArrowArrayStreamExt; + + #[test] + fn converts_each_array_in_order() -> VortexResult<()> { + let arrays = [buffer![0i32, 1], buffer![2i32], buffer![3i32, 4, 5]] + .into_iter() + .map(|values| { + StructArray::from_fields(&[("a", values.into_array())]).map(IntoArray::into_array) + }) + .collect::>>()?; + let dtype = arrays[0].dtype().clone(); + let batches: Vec<_> = block_on(|handle| { + let session = VortexSession::empty().with_handle(handle); + ArrayStreamAdapter::new(dtype, stream::iter(arrays.into_iter().map(Ok))) + .to_arrow( + &session, + None, + NonZeroUsize::new(2).unwrap_or(NonZeroUsize::MIN), + ) + .try_collect() + })?; + let values: Vec = batches + .iter() + .flat_map(|batch| { + batch + .column(0) + .as_primitive::() + .values() + .to_vec() + }) + .collect(); + assert_eq!(values, [0, 1, 2, 3, 4, 5]); + Ok(()) + } +} diff --git a/vortex-datafusion/src/v2/mod.rs b/vortex-datafusion/src/v2/mod.rs index 7f16da3ed84..3d1822f7d0d 100644 --- a/vortex-datafusion/src/v2/mod.rs +++ b/vortex-datafusion/src/v2/mod.rs @@ -40,5 +40,6 @@ mod table; #[cfg(test)] mod tests; +pub use source::SCAN_POOL_ENV; pub use source::VortexDataSource; pub use table::VortexTable; diff --git a/vortex-datafusion/src/v2/source.rs b/vortex-datafusion/src/v2/source.rs index 098e1218228..a36f6557fe8 100644 --- a/vortex-datafusion/src/v2/source.rs +++ b/vortex-datafusion/src/v2/source.rs @@ -70,6 +70,7 @@ use std::any::Any; use std::fmt; use std::fmt::Formatter; +use std::num::NonZeroUsize; use std::pin::Pin; use std::sync::Arc; use std::sync::atomic::AtomicBool; @@ -77,7 +78,6 @@ use std::sync::atomic::Ordering; use std::task::Context; use std::task::Poll; -use arrow_schema::Field; use arrow_schema::Schema; use arrow_schema::SchemaRef; use datafusion_common::ColumnStatistics; @@ -113,10 +113,14 @@ use futures::Stream; use futures::StreamExt; use futures::TryStreamExt; use futures::future::try_join_all; -use futures::lock::Mutex; +use futures::lock::Mutex as AsyncMutex; use futures::stream; +use futures::stream::BoxStream; use futures::task::AtomicWaker; use tokio::sync::OnceCell; +use vortex::array::stream::ArrayStreamAdapter; +use vortex::array::stream::ArrayStreamExt; +use vortex::array::stream::SendableArrayStream; use vortex::dtype::DType; use vortex::dtype::FieldPath; use vortex::dtype::Nullability; @@ -130,11 +134,14 @@ use vortex::expr::pack; use vortex::expr::root; use vortex::expr::stats::Precision; use vortex::expr::transform::replace; -use vortex::io::session::RuntimeSessionExt; use vortex::scan::DataSourceRef; +use vortex::scan::DataSourceScanRef; +use vortex::scan::PartitionRef; use vortex::scan::PartitionStream; use vortex::scan::ScanRequest; +use vortex::scan::stream::ScanExec; use vortex::session::VortexSession; +use vortex_arrow::ArrowArrayStreamExt; use vortex_arrow::ArrowSessionExt; use vortex_utils::parallelism::get_available_parallelism; @@ -144,10 +151,6 @@ use crate::convert::exprs::ExpressionConverter; use crate::convert::exprs::ProcessedProjection; use crate::convert::schema::calculate_physical_schema; use crate::convert::stats::stats_set_to_df; -use crate::convert::to_record_batch; - -// Bound active Scan API partition streams independently of the DataFusion output count. -const SCAN_PARTITION_READ_AHEAD: usize = 2; /// Builder for [`VortexDataSource`]. /// @@ -196,6 +199,19 @@ pub struct VortexDataSourceBuilder { projection: Option>, expression_converter: Arc, output_ordering: Option, + split_scan: bool, +} + +/// The environment variable that selects how [`VortexDataSource`] reads its scan: `0` reads the +/// scan's shared partition stream, anything else (the default) reads it through +/// [`DataSourceScan::open`](vortex::scan::DataSourceScan::open) and +/// [`DataSourceScan::split`](vortex::scan::DataSourceScan::split). +/// +/// It exists to compare the two in one binary, and goes away with the partition stream. +pub const SCAN_POOL_ENV: &str = "VORTEX_SCAN_POOL"; + +fn split_scan_from_env() -> bool { + std::env::var(SCAN_POOL_ENV).map_or(true, |value| value != "0") } impl VortexDataSourceBuilder { @@ -253,6 +269,14 @@ impl VortexDataSourceBuilder { self } + /// Selects whether output partitions read the scan through its `open` and `split` (`true`) or + /// take partitions from the scan's shared partition stream (`false`). Defaults to + /// [`SCAN_POOL_ENV`], read when the builder is created. + pub fn with_split_scan(mut self, split_scan: bool) -> Self { + self.split_scan = split_scan; + self + } + /// Builds the [`VortexDataSource`]. /// /// The builder eagerly resolves statistics for the initial projection @@ -350,7 +374,9 @@ impl VortexDataSourceBuilder { dynamic_filters: Vec::new(), limit: None, ordered: self.output_ordering.is_some(), + preserve_order: false, target_parallelism: get_available_parallelism().unwrap_or(1), + split_scan: self.split_scan, }) } } @@ -365,6 +391,7 @@ impl VortexDataSource { arrow_schema: None, projection: None, output_ordering: None, + split_scan: split_scan_from_env(), } } } @@ -379,16 +406,31 @@ impl VortexDataSource { /// During execution, it builds the final Vortex [`ScanRequest`] from the /// current projection, pushed filters, ordering hints, and row limit. /// -/// Unordered scans expose the requested DataFusion output partitions, sharing one lazy scan -/// per execution through [`DataSource::create_sibling_state`]. Ordered and fetch-limited scans -/// use one output partition to preserve partition sequence and a global fetch limit. Direct -/// [`DataSource::open`] calls support only a single output partition; multiple output partitions -/// must be opened through [`DataSourceExec`] or shared [`OpenArgs`]. Dropping an output partition -/// before completion cancels its execution; other output partitions report an error. -/// Scan initialization attempts are serialized; cancellation may drop a pending attempt, -/// allowing another output partition to retry it. +/// A scan exposes the requested DataFusion output partitions. With a declared ordering, each output +/// partition keeps that ordering, as a sorted file group does in DataFusion's own file scans, and +/// DataFusion merges the partitions where it needs one global order. /// -/// [`DataSourceExec`]: datafusion_datasource::source::DataSourceExec +/// Each execution scans once, through [`DataSource::create_sibling_state`], and the first output +/// partition polled starts the scan. Like DataFusion's own file scans, the output partitions share +/// the work unless each must keep its rows in order: +/// +/// - An unordered scan is [opened] once, and every output partition reads its own stream of it, +/// so partitions that finish early keep taking work. +/// - A scan with a declared ordering, or whose output partitions DataFusion asks to keep their +/// order, is [split] into one fixed piece per output partition, and output partition `i` reads +/// piece `i` in order. The pieces are contiguous, so each partition keeps the ordering. Partitions beyond the +/// piece count return no rows. +/// +/// Setting [`SCAN_POOL_ENV`] to `0` instead has the output partitions take partitions from one +/// shared partition stream, for comparison. +/// +/// In every mode an output partition holds work that no other partition reads: the work its stream +/// has taken, its piece, or the partitions it has taken. Dropping an output partition before it finishes therefore cancels its +/// execution, and the other output partitions report an error rather than finish without those +/// rows. +/// +/// [opened]: vortex::scan::DataSourceScan::open +/// [split]: vortex::scan::DataSourceScan::split /// /// Use [`crate::VortexSource`] instead when DataFusion should discover and plan /// `.vortex` files on its own. @@ -439,12 +481,18 @@ pub struct VortexDataSource { dynamic_filters: Vec>, /// An optional row limit populated by [`DataSource::with_fetch`]. limit: Option, - /// Whether to preserve the order of the output rows. + /// Whether to preserve a declared ordering in each output partition. ordered: bool, + /// Whether each output partition must return its rows in order, as DataFusion requests + /// through [`DataSource::with_preserve_order`]. + preserve_order: bool, /// Target Arrow conversion concurrency when only one output partition is exposed. - /// Each unordered output partition opens at most two Scan API partitions concurrently. target_parallelism: usize, + /// Whether output partitions read the scan through its `open` and `split` rather than taking + /// partitions from the scan's shared partition stream, which keeps one output partition for a + /// limited scan. + split_scan: bool, } impl fmt::Debug for VortexDataSource { @@ -460,32 +508,87 @@ impl fmt::Debug for VortexDataSource { impl VortexDataSource { fn output_partition_count(&self) -> usize { - if self.ordered || self.limit.is_some() { + // The shared partition stream keeps an ordering only in one output partition. + if !self.split_scan && (self.ordered || self.limit.is_some()) { 1 } else { self.output_partitions } } + fn scan_request(&self) -> ScanRequest { + ScanRequest { + projection: self.projected_projection.clone(), + filter: self.filter.clone(), + limit: self.limit.map(|l| u64::try_from(l).unwrap_or(u64::MAX)), + ordered: self.ordered || self.preserve_order, + ..Default::default() + } + } + + /// Output partition `partition` of the execution `execution`. fn open_partition( &self, partition: usize, execution: Arc, ) -> DFResult { if execution.cancelled.load(Ordering::Acquire) { - return Err(DataFusionError::Execution( - "scan execution cancelled".into(), - )); + return Err(cancelled()); } - let output = execution.output_partitions.get(partition).ok_or_else(|| { - DataFusionError::Execution(format!("invalid scan output partition {partition}")) - })?; + let output = execution + .output_partitions + .get(partition) + .ok_or_else(|| invalid_partition(partition))?; if output.claimed.swap(true, Ordering::AcqRel) { return Err(DataFusionError::Execution( "scan output partition already opened; reset the execution plan before replay" .into(), )); } + let data_source = Arc::clone(&self.data_source); + let request = self.scan_request(); + let session = self.session.clone(); + let schema = Arc::clone(&self.projected_schema); + let concurrency = self.conversion_concurrency(); + let ordered = self.ordered; + let shared = Arc::clone(&execution); + let batches = stream::once(async move { + let work = execution + .work + .get_or_init(|| execution.start(data_source, request)) + .await + .as_ref() + .map_err(Clone::clone)?; + let arrays = match work { + ScanWork::Partitions(partitions) => Arc::clone(partitions).arrays(ordered), + ScanWork::Stream(exec) => ArrayStreamExt::boxed(exec.stream()), + ScanWork::Pieces(pieces) => { + let piece = match pieces.get(partition) { + Some(piece) => piece.lock().await.take(), + None => None, + }; + // Output partitions beyond the scan's pieces have nothing to read. + let Some(piece) = piece else { + return VortexResult::Ok(stream::empty().boxed()); + }; + ArrayStreamExt::boxed(piece.open()?.stream()) + } + }; + Ok(arrays.to_arrow(&session, Some(schema), concurrency)) + }) + .try_flatten() + .boxed(); + self.output_stream(batches, partition, shared) + } + + /// Applies the limit and leftover projection to an output partition's batches and records its + /// metrics. A zero limit reads nothing. + fn output_stream( + &self, + batches: BoxStream<'static, VortexResult>, + partition: usize, + execution: Arc, + ) -> DFResult { let metrics = BaselineMetrics::new(&self.metrics, partition); let stream = if self.limit == Some(0) { Box::pin(RecordBatchStreamAdapter::new( @@ -493,46 +596,7 @@ impl VortexDataSource { stream::empty(), )) as SendableRecordBatchStream } else { - let scan_request = ScanRequest { - projection: self.projected_projection.clone(), - filter: self.filter.clone(), - limit: self.limit.map(|l| u64::try_from(l).unwrap_or(u64::MAX)), - ordered: self.ordered, - ..Default::default() - }; - let data_source = Arc::clone(&self.data_source); - let partitions = stream::try_unfold(Arc::clone(&execution), move |execution| { - let data_source = Arc::clone(&data_source); - let request = scan_request.clone(); - async move { - // Cancellation may retry initialization, but never runs attempts concurrently. - let partitions = execution - .scan_partitions - .get_or_init(|| async { - data_source - .scan(request) - .await - .map(|scan| Mutex::new(Some(scan.partitions()))) - }) - .await - .as_ref() - .map_err(Clone::clone)?; - let partition = { - let mut partitions = partitions.lock().await; - let next = match partitions.as_mut() { - Some(partitions) => partitions.try_next().await?, - None => None, - }; - if next.is_none() { - drop(partitions.take()); - } - next - }; - Ok(partition.map(|partition| (partition, execution))) - } - }) - .boxed(); - self.batch_stream(partitions, partition, metrics.clone())? + self.batch_stream(batches, partition)? }; Ok(Box::pin(OutputPartitionStream { partition, @@ -543,25 +607,23 @@ impl VortexDataSource { })) } + /// How many arrays each output partition converts to Arrow at once: one when several + /// partitions already convert in parallel, or the target parallelism for a single one. + fn conversion_concurrency(&self) -> NonZeroUsize { + let concurrency = if self.output_partition_count() == 1 { + self.target_parallelism + } else { + 1 + }; + NonZeroUsize::new(concurrency).unwrap_or(NonZeroUsize::MIN) + } + fn batch_stream( &self, - scan_partitions: PartitionStream, + batches: BoxStream<'static, VortexResult>, partition: usize, - metrics: BaselineMetrics, ) -> DFResult { let projected_schema = Arc::clone(&self.projected_schema); - let projected_target_field = Arc::new(Field::new_struct( - "", - projected_schema.fields().clone(), - false, - )); - let session = self.session.clone(); - let conversion_concurrency = if self.output_partition_count() == 1 { - self.target_parallelism - } else { - 1 - }; - let ordered = self.ordered; let limit = self.limit; // Pre-build the leftover projector (if any) so we can apply it after batch conversion. @@ -571,64 +633,33 @@ impl VortexDataSource { .map(|proj| proj.make_projector(&self.projected_schema)) .transpose()?; - // Defer the async DataSource::scan() call to the first poll of the stream. - let stream = stream::once(async move { - let scan_streams = scan_partitions.map(|split| split?.execute()); - - // When ordering is requested we must emit partition output in partition order, so we - // flatten the split streams sequentially. Otherwise we use try_flatten_unordered to - // poll multiple split streams concurrently so that the next split is already warm when - // the current one finishes. - let flattened = if ordered { - scan_streams.try_flatten().left_stream() - } else { - scan_streams - .try_flatten_unordered(Some(SCAN_PARTITION_READ_AHEAD)) - .right_stream() - }; + let stream = + batches.map(|result| result.map_err(|e| DataFusionError::External(Box::new(e)))); + + // With one output partition DataFusion drops its own limit operator once `with_fetch` + // accepts the limit, so the fetch must be exact here. With several, the fetch bounds each + // partition and DataFusion keeps a global limit above. + let stream = match limit { + Some(limit) => LimitStream::new( + Box::pin(RecordBatchStreamAdapter::new(projected_schema, stream)), + 0, + Some(limit), + BaselineMetrics::new(&ExecutionPlanMetricsSet::new(), partition), + ) + .boxed(), + None => stream.boxed(), + }; - let handle = session.handle(); - let stream = flattened - .map(move |result| { - let session = session.clone(); - let target_field = Arc::clone(&projected_target_field); - let metrics = metrics.intermediate(); - handle.spawn_cpu(move || { - let _timer = metrics.elapsed_compute().timer(); - to_record_batch(result?, &target_field, &session) - }) + // Apply leftover projection (expressions that couldn't be pushed into Vortex). + let stream = if let Some(projector) = leftover_projector { + stream + .map(move |batch_result| { + batch_result.and_then(|batch| projector.project_batch(&batch)) }) - .buffered(conversion_concurrency) - .map(|result| result.map_err(|e| DataFusionError::External(Box::new(e)))); - - // DataFusion drops its own limit operator once `with_fetch` accepts the limit, so the - // fetch must be exact here. Unordered scans share the limit across partitions, but - // ordered partitions each apply it locally and rely on this trim. - let stream = match limit { - Some(limit) => LimitStream::new( - Box::pin(RecordBatchStreamAdapter::new(projected_schema, stream)), - 0, - Some(limit), - BaselineMetrics::new(&ExecutionPlanMetricsSet::new(), partition), - ) - .boxed(), - None => stream.boxed(), - }; - - // Apply leftover projection (expressions that couldn't be pushed into Vortex). - let stream = if let Some(projector) = leftover_projector { - stream - .map(move |batch_result| { - batch_result.and_then(|batch| projector.project_batch(&batch)) - }) - .boxed() - } else { - stream.boxed() - }; - - Ok::<_, DataFusionError>(stream) - }) - .try_flatten(); + .boxed() + } else { + stream + }; Ok(Box::pin(RecordBatchStreamAdapter::new( Arc::clone(&self.leftover_schema), @@ -637,29 +668,48 @@ impl VortexDataSource { } } +fn invalid_partition(partition: usize) -> DataFusionError { + DataFusionError::Execution(format!("invalid scan output partition {partition}")) +} + +/// The scan that every output partition of one execution reads. +/// +/// The first output partition polled starts the scan; every other partition reads the same one. +struct ScanExecution { + split: bool, + output_partitions: Vec, + cancelled: AtomicBool, + work: OnceCell>, +} + #[derive(Default)] struct OutputPartitionState { claimed: AtomicBool, waker: AtomicWaker, } -struct ScanExecution { - output_partitions: Vec, - cancelled: AtomicBool, - scan_partitions: OnceCell>>>, +enum ScanWork { + /// Every output partition takes partitions from this shared stream. + Partitions(Arc), + /// Every output partition reads its own stream of the opened scan. + Stream(ScanExec), + /// Output partition `i` takes piece `i`, if there is one. + Pieces(Vec>>), } impl ScanExecution { - fn new(output_partitions: usize) -> Self { + fn new(output_partitions: usize, split: bool) -> Self { Self { + split, output_partitions: (0..output_partitions) .map(|_| OutputPartitionState::default()) .collect(), cancelled: AtomicBool::new(false), - scan_partitions: OnceCell::new(), + work: OnceCell::new(), } } + /// Cancels the execution and wakes every output partition, so each reports the error. fn cancel(&self) { if !self.cancelled.swap(true, Ordering::AcqRel) { for output in &self.output_partitions { @@ -667,16 +717,115 @@ impl ScanExecution { } } } + + /// Drops the scan work that no output partition holds, once the execution is cancelled. + fn release(&self) { + match self.work.get() { + Some(Ok(ScanWork::Partitions(shared))) => { + if let Some(mut partitions) = shared.partitions.try_lock() { + drop(partitions.take()); + } + } + Some(Ok(ScanWork::Pieces(pieces))) => { + for piece in pieces { + if let Some(mut piece) = piece.try_lock() { + drop(piece.take()); + } + } + } + // The streams that output partitions hold end with the execution's error. + Some(Ok(ScanWork::Stream(_)) | Err(_)) | None => {} + } + } + + async fn start( + &self, + data_source: DataSourceRef, + request: ScanRequest, + ) -> VortexResult { + let ordered = request.ordered; + let scan = data_source.scan(request).await?; + if !self.split { + return Ok(ScanWork::Partitions(Arc::new(SharedPartitions { + dtype: scan.dtype().clone(), + partitions: AsyncMutex::new(Some(scan.partitions())), + }))); + } + if !ordered { + return Ok(ScanWork::Stream(scan.open()?)); + } + let pieces = NonZeroUsize::new(self.output_partitions.len()).unwrap_or(NonZeroUsize::MIN); + Ok(ScanWork::Pieces( + scan.split(pieces)? + .into_iter() + .map(|piece| AsyncMutex::new(Some(piece))) + .collect(), + )) + } +} + +/// Scan API partitions shared by every output partition, each taking the next one it needs. +struct SharedPartitions { + dtype: DType, + partitions: AsyncMutex>, +} + +/// The most partitions each output partition reads at once from [`SharedPartitions`]. +const SCAN_PARTITION_READ_AHEAD: usize = 2; + +impl SharedPartitions { + /// Takes the next partition, dropping the stream once it ends. + async fn next(&self) -> Option> { + let mut partitions = self.partitions.lock().await; + let next = partitions.as_mut()?.next().await; + if next.is_none() { + drop(partitions.take()); + } + next + } + + /// The arrays of the partitions this output partition takes, in partition order when + /// `ordered`, or reading a few partitions at once otherwise. + fn arrays(self: Arc, ordered: bool) -> SendableArrayStream { + let dtype = self.dtype.clone(); + let partitions = stream::unfold(self, |shared| async move { + let next = shared.next().await?; + Some((next, shared)) + }) + .map(|partition| partition.and_then(|partition| partition.execute())); + let arrays = if ordered { + partitions.try_flatten().boxed() + } else { + partitions + .try_flatten_unordered(Some(SCAN_PARTITION_READ_AHEAD)) + .boxed() + }; + ArrayStreamExt::boxed(ArrayStreamAdapter::new(dtype, arrays)) + } } +/// One output partition of a [`ScanExecution`], which cancels the execution when it fails or is +/// dropped before it finishes. struct OutputPartitionStream { partition: usize, schema: SchemaRef, + /// The partition's batches, until it finishes. stream: Option, execution: Arc, metrics: BaselineMetrics, } +impl OutputPartitionStream { + fn finish(&mut self) { + self.stream = None; + drop( + self.execution.output_partitions[self.partition] + .waker + .take(), + ); + } +} + impl Stream for OutputPartitionStream { type Item = DFResult; @@ -695,20 +844,13 @@ impl Stream for OutputPartitionStream { } }; if self.stream.is_some() && self.execution.cancelled.load(Ordering::Acquire) { - result = Poll::Ready(Some(Err(DataFusionError::Execution( - "scan execution cancelled".into(), - )))); + result = Poll::Ready(Some(Err(cancelled()))); } if matches!(result, Poll::Ready(Some(Err(_)))) { self.execution.cancel(); } if matches!(result, Poll::Ready(None | Some(Err(_)))) { - self.stream = None; - drop( - self.execution.output_partitions[self.partition] - .waker - .take(), - ); + self.finish(); } metrics.record_poll(result) } @@ -725,38 +867,38 @@ impl Drop for OutputPartitionStream { if self.stream.is_some() { self.execution.cancel(); } - drop(self.stream.take()); - drop( - self.execution.output_partitions[self.partition] - .waker - .take(), - ); - if self.execution.cancelled.load(Ordering::Acquire) - && let Some(Ok(partitions)) = self.execution.scan_partitions.get() - && let Some(mut partitions) = partitions.try_lock() - { - drop(partitions.take()); + self.finish(); + if self.execution.cancelled.load(Ordering::Acquire) { + self.execution.release(); } self.metrics.done(); } } +fn cancelled() -> DataFusionError { + DataFusionError::Execution("scan execution cancelled".into()) +} + impl DataSource for VortexDataSource { fn open( &self, partition: usize, _context: Arc, ) -> DFResult { - if self.output_partition_count() != 1 { + // Several partitions read one scan only through sibling state. + if self.output_partition_count() > 1 { return Err(DataFusionError::Execution( "multiple scan output partitions require sibling execution state".into(), )); } - self.open_partition(partition, Arc::new(ScanExecution::new(1))) + self.open_partition(partition, Arc::new(ScanExecution::new(1, self.split_scan))) } fn create_sibling_state(&self, _config: &ConfigOptions) -> Option> { - Some(Arc::new(ScanExecution::new(self.output_partition_count()))) + Some(Arc::new(ScanExecution::new( + self.output_partition_count(), + self.split_scan, + ))) } fn open_with_args(&self, args: OpenArgs) -> DFResult { @@ -838,14 +980,20 @@ impl DataSource for VortexDataSource { } else { statistics }; - // Fetch is accepted only for one output partition, so it applies globally. - Ok(Arc::new(statistics.with_fetch(self.limit, 0, 1)?)) + // The fetch bounds each output partition. + Ok(Arc::new(statistics.with_fetch( + self.limit, + 0, + self.output_partition_count(), + )?)) } fn with_fetch(&self, limit: Option) -> Option> { - // DataSourceExec retains its partition properties when accepting fetch. + // DataSourceExec retains its partition properties when accepting fetch, so the fetch + // bounds each output partition and DataFusion keeps a global limit above several. if limit.is_some() - && (self.output_partition_count() > 1 || !self.dynamic_filters.is_empty()) + && (!self.dynamic_filters.is_empty() + || (!self.split_scan && self.output_partition_count() > 1)) { return None; } @@ -859,6 +1007,15 @@ impl DataSource for VortexDataSource { self.limit } + fn with_preserve_order(&self, preserve_order: bool) -> Option> { + if !self.split_scan { + return None; + } + let mut this = self.clone(); + this.preserve_order = preserve_order; + Some(Arc::new(this)) + } + // Note that we're explicitly "swapping" the projection. That means everything we do must // be computed over the original input schema, rather than the projected output schema. fn try_swapping_with_projection( @@ -1029,6 +1186,7 @@ fn estimate_to_df_precision(est: &Precision) -> DFPrecision { #[cfg(test)] mod tests { use std::any::Any; + use std::num::NonZeroUsize; use std::sync::Arc; use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering; @@ -1037,6 +1195,7 @@ mod tests { use arrow_array::cast::AsArray; use arrow_array::types::Int32Type; use arrow_schema::DataType; + use arrow_schema::Field; use async_trait::async_trait; use datafusion::prelude::SessionContext; use datafusion_datasource::source::DataSourceExec; @@ -1081,15 +1240,6 @@ mod tests { use super::*; use crate::v2::VortexTable; - #[derive(Default)] - struct WakeCounter(AtomicUsize); - - impl ArcWake for WakeCounter { - fn wake_by_ref(arc_self: &Arc) { - arc_self.0.fetch_add(1, Ordering::Relaxed); - } - } - /// The source enforces a pushed-down `LIMIT` itself: DataFusion removes its limit operator /// once the fetch is accepted, so a filtered scan over several partitions must still return /// exactly `LIMIT` rows. @@ -1210,10 +1360,15 @@ mod tests { } } + /// The values of each test partition. + const TEST_PARTITIONS: [&[i32]; 2] = [&[0, 1], &[100, 101]]; + + /// A scan of some of [`TEST_PARTITIONS`], which splits into one piece per partition. struct TestScan { dtype: DType, limit: Option, polls: Arc, + partitions: Vec, } impl DataSourceScan for TestScan { @@ -1221,18 +1376,41 @@ mod tests { &self.dtype } + fn open(self: Box) -> VortexResult { + Ok(ScanExec::from_partitions(self)) + } + fn partition_count(&self) -> Precision { - Precision::Exact(2) + Precision::Exact(self.partitions.len()) + } + + fn split(self: Box, n: NonZeroUsize) -> VortexResult> { + if n.get() < self.partitions.len() { + return Ok(vec![self]); + } + Ok(self + .partitions + .iter() + .map(|&partition| { + Box::new(TestScan { + dtype: self.dtype.clone(), + limit: self.limit, + polls: Arc::clone(&self.polls), + partitions: vec![partition], + }) as DataSourceScanRef + }) + .collect()) } fn partitions(self: Box) -> PartitionStream { let limit = self .limit .map(|limit| usize::try_from(limit).unwrap_or(usize::MAX)); - let partitions: Vec> = [&[0, 1][..], &[100, 101][..]] - .into_iter() - .enumerate() - .map(|(index, values)| { + let partitions: Vec> = self + .partitions + .iter() + .map(|&index| { + let values = TEST_PARTITIONS[index]; // Ordered partitions enforce their own limit; the adapter must enforce the // global limit when it concatenates their outputs. let values = &values[..limit.unwrap_or(values.len()).min(values.len())]; @@ -1265,6 +1443,7 @@ mod tests { dtype: self.dtype.clone(), limit: request.limit, polls: Arc::clone(&self.polls), + partitions: vec![0, 1], })) } @@ -1330,8 +1509,16 @@ mod tests { Ok(()) } + /// One execution scans once, lazily, and a reset execution scans again. Unordered output + /// partitions share the opened scan's work; output partitions that keep their order read piece + /// `i` of one split, and partitions beyond the piece count return no rows. + #[rstest] + #[case::shared_work(false)] + #[case::ordered_pieces(true)] #[tokio::test] - async fn output_partitions_share_one_lazy_scan_and_reset_reopens_it() -> anyhow::Result<()> { + async fn output_partitions_read_one_scan_per_execution( + #[case] preserve_order: bool, + ) -> anyhow::Result<()> { let scans = Arc::new(AtomicUsize::new(0)); let data_source: DataSourceRef = Arc::new(TestDataSource { dtype: test_dtype(), @@ -1339,6 +1526,7 @@ mod tests { scans: Arc::clone(&scans), }); let source = VortexDataSource::builder(data_source, VortexSession::default()) + .with_split_scan(true) .build() .await?; for requested in [0, 1, 257] { @@ -1356,53 +1544,151 @@ mod tests { source.partition_statistics(Some(0))?.num_rows, DFPrecision::Absent ); - assert!(source.with_fetch(Some(1)).is_none()); - assert!(source.open(0, Arc::new(TaskContext::default())).is_err()); + let fetched = source + .with_fetch(Some(1)) + .expect("fetch bounds each partition"); + assert_eq!(fetched.output_partitioning().partition_count(), 4); + let source = if preserve_order { + source + .with_preserve_order(true) + .expect("order preserved per partition") + } else { + source + }; + let plan = Arc::new(DataSourceExec::new(Arc::clone(&source))) as Arc; - assert_eq!(scans.load(Ordering::Relaxed), 0); let context = Arc::new(TaskContext::default()); - let values = |batches: Vec| { - let mut values = batches - .iter() - .flat_map(|batch| { - batch - .column(0) - .as_primitive::() - .values() - .iter() - .copied() - }) - .collect::>(); + let streams = (0..4) + .map(|partition| plan.execute(partition, Arc::clone(&context))) + .collect::>>()?; + assert_eq!(scans.load(Ordering::Relaxed), 0); + let mut partitions = Vec::new(); + for stream in streams { + let batches: Vec = stream.try_collect().await?; + partitions.push(partition_values(&batches)); + } + if preserve_order { + assert_eq!(partitions, [vec![0, 1], vec![100, 101], vec![], vec![]]); + } else { + let mut values = partitions.concat(); values.sort_unstable(); - values - }; - assert_eq!( - values(collect(Arc::clone(&plan), Arc::clone(&context)).await?), - [0, 1, 100, 101] - ); + assert_eq!(values, [0, 1, 100, 101]); + } assert_eq!(scans.load(Ordering::Relaxed), 1); assert_eq!(plan.metrics().expect("scan metrics").output_rows(), Some(4)); assert!(plan.execute(0, Arc::clone(&context)).is_err()); + assert!(plan.execute(4, Arc::clone(&context)).is_err()); + let reset = Arc::clone(&plan).reset_state()?; - let independent = Arc::new(DataSourceExec::new(source)) as Arc; - let (reset, independent) = futures::try_join!( - collect(reset, Arc::clone(&context)), - collect(independent, context) - )?; - assert_eq!(values(reset), [0, 1, 100, 101]); - assert_eq!(values(independent), [0, 1, 100, 101]); - assert_eq!(scans.load(Ordering::Relaxed), 3); - let cancelled = Arc::clone(&plan).reset_state()?; - let mut output = cancelled.execute(0, Arc::new(TaskContext::default()))?; + let mut values = partition_values(&collect(reset, Arc::clone(&context)).await?); + values.sort_unstable(); + assert_eq!(values, [0, 1, 100, 101]); + assert_eq!(scans.load(Ordering::Relaxed), 2); + + // Without sibling state, several partitions cannot share one scan. + assert!(source.open(0, context).is_err()); + Ok(()) + } + + /// A file of 12 rows in splits of 3, scanned through the v2 table. + async fn split_file_source() -> VortexResult<(DataSourceRef, VortexSession, SchemaRef)> { + let session = VortexSession::default(); + let array = StructArray::from_fields(&[( + "a", + buffer![0i32, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11].into_array(), + )])? + .into_array(); + let mut buf = ByteBufferMut::empty(); + session + .write_options() + .write(&mut buf, array.to_array_stream()) + .await?; + let file = session.open_options().open_buffer(buf)?; + let data_source: DataSourceRef = Arc::new( + LayoutReaderDataSource::new(file.layout_reader()?, session.clone()) + .with_split_max_row_count(3), + ); + let schema = Arc::new(session.arrow().to_arrow_schema(file.dtype())?); + Ok((data_source, session, schema)) + } + + fn partition_values(batches: &[RecordBatch]) -> Vec { + batches + .iter() + .flat_map(|batch| { + batch + .column(0) + .as_primitive::() + .values() + .iter() + .copied() + }) + .collect() + } + + /// Without `open` and `split`, output partitions share the scan's partition stream: a + /// fetch keeps one partition, and direct opens need a single partition. + #[tokio::test] + async fn without_split_scan_partitions_share_the_partition_stream() -> anyhow::Result<()> { + let data_source: DataSourceRef = Arc::new(TestDataSource { + dtype: test_dtype(), + polls: Arc::default(), + scans: Arc::default(), + }); + let source = VortexDataSource::builder(data_source, VortexSession::default()) + .with_split_scan(false) + .build() + .await? + .repartitioned(4, 0, None)? + .expect("repartitioning supported"); + assert!(source.with_fetch(Some(1)).is_none()); + assert!(source.with_preserve_order(true).is_none()); + assert!(source.open(0, Arc::new(TaskContext::default())).is_err()); + + let plan = Arc::new(DataSourceExec::new(Arc::clone(&source))) as Arc; + let mut values = partition_values(&collect(plan, Arc::new(TaskContext::default())).await?); + values.sort_unstable(); + assert_eq!(values, [0, 1, 100, 101]); + Ok(()) + } + + #[derive(Default)] + struct WakeCounter(AtomicUsize); + + impl ArcWake for WakeCounter { + fn wake_by_ref(arc_self: &Arc) { + arc_self.0.fetch_add(1, Ordering::Relaxed); + } + } + + /// Dropping an output partition before it finishes cancels the execution, so the other + /// partitions report an error rather than finish without the rows it held. + #[rstest] + #[case::split(true)] + #[case::shared_partitions(false)] + #[tokio::test] + async fn dropping_an_unfinished_partition_cancels_the_execution( + #[case] split: bool, + ) -> anyhow::Result<()> { + let data_source: DataSourceRef = Arc::new(TestDataSource { + dtype: test_dtype(), + polls: Arc::default(), + scans: Arc::default(), + }); + let source = VortexDataSource::builder(data_source, VortexSession::default()) + .with_split_scan(split) + .build() + .await? + .repartitioned(2, 0, None)? + .expect("repartitioning supported"); + let plan = Arc::new(DataSourceExec::new(source)) as Arc; + let mut output = plan.execute(0, Arc::new(TaskContext::default()))?; assert!(output.try_next().await?.is_some()); drop(output); - assert!( - cancelled - .execute(1, Arc::new(TaskContext::default())) - .is_err() - ); + assert!(plan.execute(1, Arc::new(TaskContext::default())).is_err()); - let execution = Arc::new(ScanExecution::new(2)); + // A partition already waiting is woken and reports the cancellation. + let execution = Arc::new(ScanExecution::new(2, split)); let output = |partition| OutputPartitionStream { partition, schema: plan.schema(), @@ -1413,13 +1699,13 @@ mod tests { execution: Arc::clone(&execution), metrics: BaselineMetrics::new(&ExecutionPlanMetricsSet::new(), partition), }; - let cancelled = output(0); + let dropped = output(0); let mut pending = Box::pin(output(1)); let wakes = Arc::new(WakeCounter::default()); let waker = waker_ref(&wakes); let mut cx = Context::from_waker(&waker); assert!(pending.as_mut().poll_next(&mut cx).is_pending()); - drop(cancelled); + drop(dropped); assert_eq!(wakes.0.load(Ordering::Relaxed), 1); assert!(matches!( pending.as_mut().poll_next(&mut cx), @@ -1428,8 +1714,42 @@ mod tests { Ok(()) } + /// A fetch bounds each of several output partitions, which share the opened scan's work. + #[tokio::test] + async fn fetch_bounds_each_of_several_partitions() -> anyhow::Result<()> { + let (data_source, session, schema) = split_file_source().await?; + let source = VortexDataSource::builder(data_source, session) + .with_arrow_schema(schema) + .with_split_scan(true) + .build() + .await? + .repartitioned(4, 0, None)? + .expect("repartitioning supported") + .with_fetch(Some(5)) + .expect("fetch supported"); + let plan = Arc::new(DataSourceExec::new(source)) as Arc; + assert_eq!(plan.properties().partitioning.partition_count(), 4); + let context = Arc::new(TaskContext::default()); + + let partitions = try_join_all((0..4).map(|partition| { + let stream = plan.execute(partition, Arc::clone(&context)); + async move { + let batches: Vec = stream?.try_collect().await?; + Ok::<_, DataFusionError>(partition_values(&batches)) + } + })) + .await?; + assert!(partitions.iter().all(|values| values.len() <= 5)); + let mut values = partitions.concat(); + assert!(values.len() >= 5, "{partitions:?}"); + values.sort_unstable(); + values.dedup(); + assert_eq!(values.len(), partitions.iter().map(Vec::len).sum::()); + Ok(()) + } + #[tokio::test] - async fn proven_ordering_keeps_one_output_partition_and_remaps_identity_outputs() + async fn proven_ordering_holds_in_each_output_partition_and_remaps_identity_outputs() -> anyhow::Result<()> { let data_source: DataSourceRef = Arc::new(TestDataSource { dtype: test_dtype(), @@ -1442,12 +1762,33 @@ mod tests { LexOrdering::new([PhysicalSortExpr::new_default(Arc::clone(&key))]) .expect("one key"), ) + .with_split_scan(true) .build() .await?; + let mut shared_partitions = source.clone(); + shared_partitions.split_scan = false; + let shared_partitions = shared_partitions + .repartitioned(4, 0, None)? + .expect("repartitioning supported"); + assert_eq!(shared_partitions.output_partitioning().partition_count(), 1); + + // Output partition `i` reads piece `i` of the split, in order. let source = source .repartitioned(4, 0, None)? .expect("repartitioning supported"); - assert_eq!(source.output_partitioning().partition_count(), 1); + assert_eq!(source.output_partitioning().partition_count(), 4); + let plan = Arc::new(DataSourceExec::new(Arc::clone(&source))) as Arc; + let context = Arc::new(TaskContext::default()); + let mut partitions = Vec::new(); + for partition in 0..4 { + let batches: Vec = plan + .execute(partition, Arc::clone(&context))? + .try_collect() + .await?; + partitions.push(partition_values(&batches)); + } + assert_eq!(partitions, [vec![0, 1], vec![100, 101], vec![], vec![]]); + let projected = source .try_swapping_with_projection(&ProjectionExprs::from(vec![ProjectionExpr::new( Arc::clone(&key), diff --git a/vortex-duckdb/src/file_reader.rs b/vortex-duckdb/src/file_reader.rs index 54bdeba6856..c0fbbfd16b2 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; @@ -24,17 +27,19 @@ 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; use vortex::io::runtime::BlockingRuntime as _; use vortex::io::std_file::StdFileSystem; use vortex::layout::LayoutReaderRef; -use vortex::layout::scan::scan_builder::ScanBuilder; -use vortex::layout::scan::v2::ScanBuilder as V2ScanBuilder; -use vortex::layout::scan::v2::ScanFile; +use vortex::layout::scan::layout::LayoutReaderDataSource; 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; use vortex::session::SessionExt as _; use crate::REGISTRY; @@ -48,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; @@ -111,46 +115,62 @@ 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. 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 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 { + // 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)) + } +} + 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(), + plan_source: file.plan_data_source(), + scan: OnceLock::new(), cache: ConversionCache::default(), })), - splits: vec![], - total_splits: 0, }) } @@ -219,59 +239,49 @@ 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 - // 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); - } - - let reader = Arc::clone(file.reader()); + // 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 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 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 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) } -/// 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; +/// 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(); - let rows = filter.row_range.as_ref().map_or(0..row_count, |range| { - range.start.min(row_count)..range.end.min(row_count) - }); - 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) + filter.row_range.as_ref().map_or(0..row_count, |range| { + let end = range.end.min(row_count); + range.start.min(end)..end + }) } /// What a thread's split yields next. @@ -285,43 +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(task)) => Ok(RUNTIME - .block_on(task)? - .map_or(SplitItem::Empty, SplitItem::Array)), - Some(Split::V2) => { + let array = match local.pending.pop() { + Some(array) => array, + None => { + let Some(Split(stream)) = local.split.take() else { + return Ok(SplitItem::Done); + }; 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, @@ -333,14 +342,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 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() - .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 +369,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 +381,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 +463,21 @@ 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()) { - 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 + // 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; + }; + state + .scan + .get() + .and_then(|scan| scan.exec.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/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/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/scan_v2.rs b/vortex-duckdb/src/scan_v2.rs deleted file mode 100644 index 4c778d14acf..00000000000 --- a/vortex-duckdb/src/scan_v2.rs +++ /dev/null @@ -1,321 +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::ops::Range; -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::VortexExpect; -use vortex::error::VortexResult; -use vortex::io::request::IoConsumer; -use vortex::io::request::IoRequestId; -use vortex::io::request::IoResult; -use vortex::io::request::IoService; -use vortex::io::runtime::BlockingRuntime as _; -use vortex::layout::scan::v2::ScanBuilder; -use vortex::mask::Mask; -use vortex::scan::planning::driver::Progress; -use vortex::scan::planning::driver::Run; -use vortex::scan::planning::planner::Planner; -use vortex::scan::planning::planner::PlannerOutput; -use vortex::scan::planning::planner::State; -use vortex::scan::planning::planner::WorkScope; -use vortex::scan::prepare::ChunkPlanner; -use vortex::scan::prepare::PreparedScan; -use vortex::scan::prepare::PrunePlanner; -use vortex::scan::selection::Selection; - -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( - compose(&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) - } -} - -/// The planners of a scan, composed: with a dynamic filter, its pruning plans first over the scan's -/// rows, continuing into the parts of the rows they keep; otherwise, the parts directly. -fn compose(scan: &Arc, splits: &[u64], dynamic: bool) -> Box { - let rows = scan.rows().clone(); - let parts = { - let scan = Arc::clone(scan); - let parts = part_ranges(rows.clone(), splits); - let first_row = rows.start; - move |kept: Option| -> Box { - Box::new(PartPlanner::new(scan, parts, first_row, kept)) - } - }; - if dynamic && scan.filter().is_some() { - Box::new(PrunePlanner::new(Arc::clone(scan), rows, Box::new(parts))) - } else { - parts(None) - } -} - -/// Spawns a planner per part of a scan's rows that zone pruning left something of, in row order. -/// Parts are the file's layout splits, so a layout chunk, and the dictionary it carries, is -/// exported by one thread, which lets DuckDB evaluate an expression over that dictionary once. -/// -/// With a filter, each part prunes over its own rows before its chunks, on the thread that takes -/// it, like the per-split pruning of a V1 scan, so the pruning of a file's parts runs in parallel. -/// A dynamic filter, such as the bound a top-N pushes down, also prunes the scan as a whole before -/// any part is taken, so a file whose zones it rules out takes no thread. It has tightened by the -/// time a later part is taken, so pruning that part again skips more, from the zone maps the -/// scan-wide pruning read. -struct PartPlanner { - scan: Arc, - selection: Selection, - parts: std::vec::IntoIter>, - /// The first row of `kept`. - first_row: u64, - /// The rows scan-wide pruning kept, from `first_row`, or `None` when nothing was pruned. - kept: Option, -} - -impl PartPlanner { - fn new( - scan: Arc, - parts: Vec>, - first_row: u64, - kept: Option, - ) -> Self { - Self { - selection: scan.selection().clone(), - scan, - parts: parts.into_iter(), - first_row, - kept, - } - } - - /// The rows of `part` that scan-wide pruning kept, or `None` when nothing was pruned. - fn kept_in(&self, part: &Range) -> Option { - let kept = self.kept.as_ref()?; - let offset = - |row: u64| usize::try_from(row - self.first_row).vortex_expect("a part fits usize"); - Some(kept.slice(offset(part.start)..offset(part.end))) - } -} - -impl IoConsumer for PartPlanner { - fn set_io_result(&mut self, _request: IoRequestId, _result: IoResult) {} -} - -impl Planner for PartPlanner { - fn state(&self) -> State { - if self.parts.as_slice().is_empty() { - State::Done - } else { - State::NeedsCompute - } - } - - fn compute(&mut self) -> VortexResult { - while let Some(part) = self.parts.next() { - let kept = self.kept_in(&part); - if kept.as_ref().is_some_and(Mask::all_false) { - continue; - } - let chunks = { - let scan = Arc::clone(&self.scan); - let selection = self.selection.clone(); - let part = part.clone(); - move |again: Option| -> Box { - let kept = match (kept, again) { - (Some(kept), Some(again)) => Some(kept & &again), - (kept, again) => kept.or(again), - }; - Box::new(ChunkPlanner::new(scan, part, selection, kept)) - } - }; - let planner: Box = if self.scan.filter().is_some() { - Box::new(PrunePlanner::new( - Arc::clone(&self.scan), - part.clone(), - Box::new(chunks), - )) - } else { - chunks(None) - }; - let scope = WorkScope { - file_ordinal: 0, - rows: part, - }; - return Ok(PlannerOutput::Spawn(scope, planner)); - } - Ok(PlannerOutput::Done) - } -} - -/// The ranges between adjacent `splits`, clipped to `rows`, leaving out empty ones. -fn part_ranges(rows: Range, splits: &[u64]) -> Vec> { - splits - .windows(2) - .map(|w| w[0].max(rows.start)..w[1].min(rows.end)) - .filter(|part| part.start < part.end) - .collect() -} - -#[cfg(test)] -mod tests { - use std::ops::Range; - - use rstest::rstest; - - use super::part_ranges; - - #[rstest] - #[case::whole(0..30, &[0, 10, 20, 30], vec![0..10, 10..20, 20..30])] - #[case::clipped(5..25, &[0, 10, 20, 30], vec![5..10, 10..20, 20..25])] - #[case::inside_one_split(12..18, &[0, 10, 20, 30], vec![12..18])] - #[case::empty(5..5, &[0, 10], vec![])] - fn parts_follow_splits( - #[case] rows: Range, - #[case] splits: &[u64], - #[case] expected: Vec>, - ) { - assert_eq!(part_ranges(rows, splits), expected); - } -} diff --git a/vortex-duckdb/src/table_function.rs b/vortex-duckdb/src/table_function.rs index e96dd83d12c..da22e5c9db7 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; @@ -34,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; @@ -42,7 +40,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::planning::driver::Run; +use vortex::scan::stream::ScanStream; use vortex_utils::aliases::hash_map::HashMap; use crate::SESSION; @@ -182,7 +180,8 @@ impl<'a> TableInitInput<'a> { } pub struct GlobalState { - pub projection: BoundExpression, + /// 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, /// Whether the scan runs on the planner-driven V2 executor. @@ -203,13 +202,11 @@ pub struct AggregateState { } 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>>), - /// 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)>; @@ -220,12 +217,11 @@ 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>, - /// 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. + pub(crate) retired_splits: Vec, + /// 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 +348,8 @@ pub fn init_global(init_input: &TableInitInput) -> VortexResult { "table function scan input" ); - let projection = optimize_and_bind(projection, &bind_data.dtype)?; Ok(GlobalState { - projection, + projection_expr: projection, filter, aggregates: bind_data.aggregates.clone(), has_count_star, @@ -430,16 +425,12 @@ pub fn init_local(bind_data: &BindState, global: &GlobalState) -> LocalState { split: None, file: None, retired_files: Vec::new(), - run: Run::new(), + retired_splits: Vec::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. diff --git a/vortex-file/src/file.rs b/vortex-file/src/file.rs index 0b1c3ccdfcc..d3c1b9288f6 100644 --- a/vortex-file/src/file.rs +++ b/vortex-file/src/file.rs @@ -14,6 +14,7 @@ use itertools::Itertools; use vortex_array::ArrayRef; use vortex_array::dtype::DType; use vortex_array::dtype::FieldMask; +use vortex_array::expr::BoundExpression; use vortex_array::expr::Expression; use vortex_buffer::ByteBuffer; use vortex_error::VortexResult; @@ -21,6 +22,7 @@ use vortex_layout::LayoutReader; use vortex_layout::scan::layout::LayoutReaderDataSource; use vortex_layout::scan::metrics::ScanUsage; use vortex_layout::scan::scan_builder::ScanBuilder; +use vortex_layout::scan::scan_builder::referenced_field_masks; use vortex_layout::scan::split_by::SplitBy; use vortex_layout::scan::v2::ScanFile; use vortex_layout::segments::SegmentSource; @@ -28,6 +30,8 @@ use vortex_layout::segments::UsageSegmentSource; use vortex_scan::DataSourceRef; use vortex_scan::prepare::ScanCache; use vortex_scan::prepare::SegmentLocation; +use vortex_scan::source::PlanChild; +use vortex_scan::source::PlanDataSource; use vortex_session::VortexSession; use vortex_utils::aliases::hash_map::HashMap; @@ -116,7 +120,8 @@ impl VortexFile { /// /// Repeated calls to [`layout_reader`](Self::layout_reader), [`scan`](Self::scan), and /// [`data_source`](Self::data_source) will share the same reader tree. Repeated V2 scans of - /// [`scan_file`](Self::scan_file) will share its segment locations and a [`ScanCache`]. + /// [`scan_file`](Self::scan_file), and so of the plan data sources, will share its segment + /// locations and a [`ScanCache`]. pub fn with_caching(self) -> Self { let scan_cache = FileScanCache { locations: self.footer.segment_locations(), @@ -245,18 +250,70 @@ impl VortexFile { /// Create a [`DataSource`](vortex_scan::DataSource) from this file for scanning. /// - /// Wraps the file's layout reader with [`FileStatsLayoutReader`] (when file-level - /// statistics are available) and [`LayoutReaderDataSource`]. Stored footer aggregates are - /// available through the source statistics methods without reading payloads. + /// Scans run on the file's [layout reader](Self::layout_reader), as with + /// [`layout_reader_data_source`](Self::layout_reader_data_source). Stored footer aggregates + /// are available through the source statistics methods without reading payloads. pub fn data_source(&self) -> VortexResult { - let reader = self.layout_reader()?; + self.layout_reader_data_source() + } + /// Create a [`DataSource`](vortex_scan::DataSource) that scans this file with its + /// [layout reader](Self::layout_reader), whatever its layouts. + /// + /// Use [`data_source`](Self::data_source) unless the layout reader is required, for example + /// to compare it with [`plan_data_source`](Self::plan_data_source). Stored footer aggregates + /// are available through the source statistics methods without reading payloads. + pub fn layout_reader_data_source(&self) -> VortexResult { + let reader = self.layout_reader()?; Ok(Arc::new(FileDataSource::new( LayoutReaderDataSource::new(reader, self.session.clone()), self.file_stats().cloned(), ))) } + /// Create a [`DataSource`](vortex_scan::DataSource) from this file whose scans run on the + /// planner-driven executor. + /// + /// The source is a [`PlanDataSource`] over [`plan_child`](Self::plan_child). Every scan of + /// the source shares one [`ScanCache`]: the file's, with [caching](Self::with_caching), or else + /// one of its own. A scan whose filter the file-level statistics prove false reads nothing. + /// Stored footer aggregates are available through the source statistics methods. Opening the + /// source reads nothing and builds no layout reader. + pub fn plan_data_source(&self) -> DataSourceRef { + let source = PlanDataSource::from_child(self.session.clone(), self.plan_child()); + Arc::new(FileDataSource::new(source, self.file_stats().cloned())) + } + + /// This file as a child of a [`PlanDataSource`]: its V2 scan input, row count, and a pruner + /// that skips scans whose filter the file-level statistics prove false. + /// + /// An opened scan of the child cuts its work on the file's layout splits over the fields it + /// reads, as a V1 scan of the same fields does. + pub fn plan_child(&self) -> PlanChild { + let splitter = { + let file = self.clone(); + Arc::new( + move |projection: &BoundExpression, filter: Option<&BoundExpression>| { + SplitBy::default().splits( + file.layout_reader()?.as_ref(), + &(0..file.row_count()), + &referenced_field_masks(projection, filter)?, + ) + }, + ) + }; + let file = PlanChild::new(self.scan_file().into()) + .with_row_count(self.row_count()) + .with_splitter(splitter); + let Some(statistics) = self.file_stats().cloned() else { + return file; + }; + let (row_count, session) = (self.row_count(), self.session.clone()); + file.with_pruner(Arc::new(move |filter| { + is_falsified_by_file_stats(filter, row_count, &statistics, &session) + })) + } + /// Initiate a scan of the file, returning a builder for projection, filtering, selection, and /// execution options. pub fn scan(&self) -> VortexResult> { diff --git a/vortex-file/src/lib.rs b/vortex-file/src/lib.rs index c6a5d9337bc..b628559e3ba 100644 --- a/vortex-file/src/lib.rs +++ b/vortex-file/src/lib.rs @@ -109,6 +109,8 @@ pub mod flatbuffers; mod footer; pub mod multi; mod open; +#[cfg(test)] +mod plan_tests; mod pruning; /// Segment sources, caches, and sinks used by file readers and writers. pub mod segments; diff --git a/vortex-file/src/plan_tests.rs b/vortex-file/src/plan_tests.rs new file mode 100644 index 00000000000..2f63173d7e8 --- /dev/null +++ b/vortex-file/src/plan_tests.rs @@ -0,0 +1,350 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Plan data sources read through the Scan API's `split` and `open`, over real files whose +//! segments are read through the session's I/O. + +use std::num::NonZeroUsize; +use std::ops::Range; +use std::sync::Arc; +use std::sync::LazyLock; +use std::sync::atomic::AtomicU32; +use std::sync::atomic::Ordering; + +use futures::FutureExt; +use futures::TryStreamExt; +use futures::future::BoxFuture; +use rstest::rstest; +use vortex_array::ArrayRef; +use vortex_array::IntoArray; +use vortex_array::VortexSessionExecute; +use vortex_array::arrays::PrimitiveArray; +use vortex_array::arrays::StructArray; +use vortex_array::buffer::BufferHandle; +use vortex_array::dtype::DType; +use vortex_array::dtype::Nullability; +use vortex_array::dtype::PType; +use vortex_array::expr::Expression; +use vortex_array::expr::get_item; +use vortex_array::expr::gt; +use vortex_array::expr::lit; +use vortex_array::expr::root; +use vortex_array::scalar_fn::builtin::operators::CompareOperator; +use vortex_buffer::Alignment; +use vortex_buffer::Buffer; +use vortex_buffer::ByteBuffer; +use vortex_buffer::ByteBufferMut; +use vortex_error::VortexResult; +use vortex_error::vortex_err; +use vortex_functions::expr::dynamic; +use vortex_io::VortexReadAt; +use vortex_io::session::RuntimeSession; +use vortex_layout::scan::scan_builder::ScanBuilder; +use vortex_layout::session::LayoutSession; +use vortex_scan::DataSourceRef; +use vortex_scan::ScanRequest; +use vortex_scan::source::PlanDataSource; +use vortex_scan::stream::ScanExec; +use vortex_scan::stream::ScanStream; +use vortex_session::VortexSession; + +use crate::OpenOptionsSessionExt; +use crate::VortexFile; +use crate::WriteOptionsSessionExt; +use crate::multi::MultiFileSession; + +static SESSION: LazyLock = LazyLock::new(|| { + let session = VortexSession::empty() + .with::() + .with::() + .with::(); + crate::register_default_encodings(&session); + crate::enable_all_registered_array_encodings(&session); + session +}); + +/// The rows of a one-file source: several parts of the scan, filtered or not. +const ROWS: u32 = 600_000; + +/// The `m` value of row `n`: scrambled, so the column does not compress away and its segments +/// are read during the scan rather than with the footer. +fn scramble(n: u32) -> u32 { + n.wrapping_mul(2_654_435_761) +} + +const THRESHOLD: u32 = u32::MAX / 2; + +/// The filter of filtered cases, which keeps about half of the rows and, with the `n` +/// projection, makes the scan read two columns. +fn m_filter() -> Expression { + gt(get_item("m", root()), lit(THRESHOLD)) +} + +/// The values of `n` in `rows` that a scan returns, with [`m_filter`] when `filtered`. +fn expected(rows: Range, filtered: bool) -> Vec { + rows.filter(|&n| !filtered || scramble(n) > THRESHOLD) + .collect() +} + +/// A file of an `n` column holding `values` and an `m` column of their scrambles. +async fn file_bytes(values: Range) -> VortexResult { + let m = Buffer::from_iter(values.clone().map(scramble)).into_array(); + let array = + StructArray::from_fields(&[("n", Buffer::from_iter(values).into_array()), ("m", m)])? + .into_array(); + let mut buf = ByteBufferMut::empty(); + SESSION + .write_options() + .write(&mut buf, array.to_array_stream()) + .await?; + Ok(buf.freeze()) +} + +/// A reader of in-memory bytes whose reads pend once before they complete, as storage reads do. +#[derive(Clone)] +struct YieldingRead(ByteBuffer); + +impl VortexReadAt for YieldingRead { + fn concurrency(&self) -> usize { + self.0.concurrency() + } + + fn size(&self) -> BoxFuture<'static, VortexResult> { + self.0.size() + } + + fn read_at( + &self, + offset: u64, + length: usize, + alignment: Alignment, + ) -> BoxFuture<'static, VortexResult> { + let read = self.0.read_at(offset, length, alignment); + async move { + tokio::task::yield_now().await; + read.await + } + .boxed() + } +} + +async fn open_one_file() -> VortexResult { + SESSION + .open_options() + .open_read(YieldingRead(file_bytes(0..ROWS).await?)) + .await +} + +async fn one_file() -> VortexResult { + Ok(open_one_file().await?.plan_data_source()) +} + +fn n() -> Expression { + get_item("n", root()) +} + +fn request(ordered: bool) -> ScanRequest { + ScanRequest { + projection: n(), + ordered, + ..Default::default() + } +} + +async fn values(stream: ScanStream) -> VortexResult> { + let arrays: Vec = stream.try_collect().await?; + let mut ctx = SESSION.create_execution_ctx(); + let mut values = Vec::new(); + for array in arrays { + values.extend_from_slice(array.execute::(&mut ctx)?.as_slice::()); + } + Ok(values) +} + +/// Reads `exec` with `workers` streams, each polled on a task of its own. +async fn read_stream(exec: ScanExec, workers: usize) -> VortexResult>> { + let tasks: Vec<_> = (0..workers) + .map(|_| tokio::spawn(values(exec.stream()))) + .collect(); + let mut out = Vec::with_capacity(workers); + for task in tasks { + out.push( + task.await + .map_err(|err| vortex_err!("worker task failed: {err}"))??, + ); + } + Ok(out) +} + +fn sorted(workers: Vec>) -> Vec { + let mut all: Vec = workers.into_iter().flatten().collect(); + all.sort_unstable(); + all +} + +/// The streams of an unordered scan together read every selected row once. +#[rstest] +#[case::projection(false)] +#[case::filter(true)] +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[cfg_attr(miri, ignore)] +async fn open_reads_every_row_once(#[case] filtered: bool) -> VortexResult<()> { + let source = one_file().await?; + let scan = source + .scan(ScanRequest { + filter: filtered.then(m_filter), + ..request(false) + }) + .await?; + let workers = read_stream(scan.open()?, 4).await?; + assert_eq!(sorted(workers), expected(0..ROWS, filtered)); + Ok(()) +} + +/// A child's splits are its parts, each of several chunks, and the workers read every row of them once. +#[rstest] +#[case::unordered(false, false)] +#[case::unordered_filter(false, true)] +#[case::ordered(true, false)] +#[case::ordered_filter(true, true)] +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[cfg_attr(miri, ignore)] +async fn open_cuts_parts_on_file_splits( + #[case] ordered: bool, + #[case] filtered: bool, +) -> VortexResult<()> { + let file = open_one_file().await?; + let splits: Arc<[u64]> = Arc::from([0, 150_000, 400_000, u64::from(ROWS)]); + let source: DataSourceRef = Arc::new(PlanDataSource::from_child( + SESSION.clone(), + file.plan_child().with_splits(splits), + )); + let scan = source + .scan(ScanRequest { + filter: filtered.then(m_filter), + ..request(ordered) + }) + .await?; + let workers = read_stream(scan.open()?, 3).await?; + if ordered { + let reader = workers.iter().find(|values| !values.is_empty()); + assert_eq!(reader, Some(&expected(0..ROWS, filtered))); + } else { + // Each worker returns its parts' rows in order within each part. + assert_eq!(sorted(workers), expected(0..ROWS, filtered)); + } + Ok(()) +} + +/// A file's parts are its layout splits over the fields the scan reads, as a V1 scan of the same +/// fields cuts it: no batch of an unordered scan crosses one. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[cfg_attr(miri, ignore)] +async fn open_cuts_parts_on_layout_splits() -> VortexResult<()> { + let file = open_one_file().await?; + let splits = ScanBuilder::new(SESSION.clone(), file.layout_reader()?) + .with_projection(n().bind(file.dtype())?) + .full_file_splits()?; + assert!(splits.len() > 2, "the file has several layout splits"); + + // One worker takes the parts in row order and finishes each before the next. + let scan = file.plan_data_source().scan(request(false)).await?; + let arrays: Vec = scan.open()?.stream().try_collect().await?; + let mut boundaries = vec![0u64]; + for array in &arrays { + let end = boundaries.last().copied().unwrap_or(0) + array.len() as u64; + boundaries.push(end); + } + for split in splits { + assert!( + boundaries.contains(&split), + "a batch crosses layout split {split}" + ); + } + Ok(()) +} + +/// A dynamic filter, such as a top-N's bound, prunes a file as a whole when the scan is made, +/// before its parts are cut. The rows follow the bound as it stands when the streams read, not as +/// it stood when the scan was made. +#[rstest] +#[case::unordered(false)] +#[case::ordered(true)] +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[cfg_attr(miri, ignore)] +async fn scan_prunes_the_file_first_for_a_dynamic_filter( + #[case] ordered: bool, +) -> VortexResult<()> { + let bound = Arc::new(AtomicU32::new(0)); + let value = Arc::clone(&bound); + let filter = dynamic( + CompareOperator::Gt, + move || Some(value.load(Ordering::Relaxed).into()), + DType::Primitive(PType::U32, Nullability::NonNullable), + true, + n(), + ); + let scan = one_file() + .await? + .scan(ScanRequest { + filter: Some(filter), + ..request(ordered) + }) + .await?; + let stream = scan.open()?; + bound.store(ROWS - 10, Ordering::Relaxed); + assert_eq!( + sorted(read_stream(stream, 3).await?), + (ROWS - 9..ROWS).collect::>() + ); + Ok(()) +} + +/// An ordered scan gives all of its rows, in order, to its first stream. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[cfg_attr(miri, ignore)] +async fn ordered_open_reads_in_order_on_one_stream() -> VortexResult<()> { + let source = one_file().await?; + let mut workers = read_stream(source.scan(request(true)).await?.open()?, 3).await?; + workers.sort_by_key(|values| std::cmp::Reverse(values.len())); + assert_eq!(workers[0], (0..ROWS).collect::>()); + assert!(workers[1..].iter().all(Vec::is_empty)); + Ok(()) +} + +/// A scan's limit holds across its streams; an ordered scan returns the first rows. +#[rstest] +#[case::unordered(false, false)] +#[case::unordered_filter(false, true)] +#[case::ordered(true, false)] +#[case::ordered_filter(true, true)] +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[cfg_attr(miri, ignore)] +async fn open_applies_the_limit(#[case] ordered: bool, #[case] filtered: bool) -> VortexResult<()> { + const LIMIT: usize = 150_000; + let rows = expected(0..ROWS, filtered); + let source = one_file().await?; + let scan = source + .scan(ScanRequest { + filter: filtered.then(m_filter), + limit: Some(LIMIT as u64), + ..request(ordered) + }) + .await?; + // A limit holds across the whole scan, so a limited scan is not split. + let scan = { + let mut pieces = scan.split(NonZeroUsize::new(4).unwrap_or(NonZeroUsize::MIN))?; + assert_eq!(pieces.len(), 1); + pieces.remove(0) + }; + let workers = read_stream(scan.open()?, 3).await?; + if ordered { + let reader = workers.iter().find(|values| !values.is_empty()); + assert_eq!(reader.map(Vec::as_slice), Some(&rows[..LIMIT])); + } + let all = sorted(workers); + assert_eq!(all.len(), LIMIT); + all.windows(2).for_each(|w| assert!(w[0] < w[1])); + assert!(all.iter().all(|value| rows.binary_search(value).is_ok())); + Ok(()) +} diff --git a/vortex-file/src/source.rs b/vortex-file/src/source.rs index 1088a61de88..713278b20d9 100644 --- a/vortex-file/src/source.rs +++ b/vortex-file/src/source.rs @@ -9,7 +9,6 @@ use vortex_array::expr::stats::Precision; use vortex_array::scalar::Scalar; use vortex_array::stats::StatsSet; use vortex_error::VortexResult; -use vortex_layout::scan::layout::LayoutReaderDataSource; use vortex_scan::DataSource; use vortex_scan::DataSourceScanRef; use vortex_scan::PartitionRef; @@ -18,19 +17,20 @@ use vortex_session::VortexSession; use crate::FileStatistics; -pub(crate) struct FileDataSource { - source: LayoutReaderDataSource, +/// A file's scans with the statistics of its footer. +pub(crate) struct FileDataSource { + source: S, statistics: Option, } -impl FileDataSource { - pub(crate) fn new(source: LayoutReaderDataSource, statistics: Option) -> Self { +impl FileDataSource { + pub(crate) fn new(source: S, statistics: Option) -> Self { Self { source, statistics } } } #[async_trait] -impl DataSource for FileDataSource { +impl DataSource for FileDataSource { fn dtype(&self) -> &DType { self.source.dtype() } diff --git a/vortex-file/src/tests.rs b/vortex-file/src/tests.rs index 1f333470f3b..64987188dcc 100644 --- a/vortex-file/src/tests.rs +++ b/vortex-file/src/tests.rs @@ -122,6 +122,9 @@ use vortex_layout::scan::scan_builder::ScanBuilder; use vortex_layout::scan::split_by::DEFAULT_MAX_SPLIT_ROWS; use vortex_layout::scan::split_by::SplitBy; use vortex_layout::session::LayoutSession; +use vortex_scan::DataSourceRef; +use vortex_scan::PartitionRef; +use vortex_scan::ScanRequest; use vortex_scan::strict_sorted_buffer::StrictSortedBuffer; use vortex_session::VortexSession; use vortex_zigzag::ZigZag; @@ -2646,6 +2649,65 @@ async fn file_data_source_returns_mergeable_partials() -> VortexResult<()> { Ok(()) } +/// Scans `source` and concatenates the rows of all its partitions, returning how many partitions +/// the scan had. +async fn scan_source( + source: &DataSourceRef, + request: ScanRequest, +) -> VortexResult<(usize, ArrayRef)> { + let scan = source.scan(request).await?; + let dtype = scan.dtype().clone(); + let partitions: Vec = scan.partitions().try_collect().await?; + let partition_count = partitions.len(); + let mut chunks = Vec::new(); + for partition in partitions { + chunks.push(partition.execute()?.read_all().await?); + } + Ok(( + partition_count, + ChunkedArray::try_new(chunks, dtype)?.into_array(), + )) +} + +/// Both of a file's executors are reachable through the Scan API and read the same rows. +#[rstest] +#[case::plan(false)] +#[case::layout_reader(true)] +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[cfg_attr(miri, ignore)] +async fn file_sources_scan_with_either_executor(#[case] layout_reader: bool) -> VortexResult<()> { + let array = StructArray::from_fields(&[("numbers", buffer![1u32, 2, 3, 4, 5].into_array())])? + .into_array(); + let mut buf = ByteBufferMut::empty(); + SESSION + .write_options() + .write(&mut buf, array.to_array_stream()) + .await?; + let file = SESSION.open_options().open_buffer(buf)?; + let source = if layout_reader { + file.layout_reader_data_source()? + } else { + file.plan_data_source() + }; + + let (_, actual) = scan_source( + &source, + ScanRequest { + projection: get_item("numbers", root()), + filter: Some(gt(get_item("numbers", root()), lit(3u32))), + ordered: true, + ..Default::default() + }, + ) + .await?; + assert_arrays_eq!( + actual, + buffer![4u32, 5].into_array(), + &mut SESSION.create_execution_ctx() + ); + Ok(()) +} + #[tokio::test] async fn test_writer_with_statistics() -> VortexResult<()> { let array = StructArray::from_fields(&[("numbers", buffer![1u32, 2, 3, 4, 5].into_array())])? diff --git a/vortex-file/src/v2/scan/tests.rs b/vortex-file/src/v2/scan/tests.rs index 6b3b030b971..7235c566165 100644 --- a/vortex-file/src/v2/scan/tests.rs +++ b/vortex-file/src/v2/scan/tests.rs @@ -14,16 +14,25 @@ use vortex_array::VortexSessionExecute; use vortex_array::arrays::ChunkedArray; use vortex_array::arrays::StructArray; use vortex_array::arrays::VarBinArray; +use vortex_array::assert_arrays_eq; +use vortex_array::expr::get_item; +use vortex_array::expr::gt; +use vortex_array::expr::lit; +use vortex_array::expr::root; +use vortex_array::expr::stats::Precision; use vortex_arrow::ArrowScanExt; use vortex_arrow::ArrowSessionExt; use vortex_arrow::ExecuteArrowExt; use vortex_buffer::ByteBufferMut; use vortex_buffer::buffer; +use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_io::runtime::tokio::TokioRuntime; use vortex_io::session::RuntimeSession; use vortex_layout::scan::v2::ScanBuilder; use vortex_layout::session::LayoutSession; +use vortex_scan::PartitionRef; +use vortex_scan::ScanRequest; use vortex_session::VortexSession; use super::ScanDriver; @@ -93,3 +102,48 @@ async fn record_batches_match_arrays() -> VortexResult<()> { assert_eq!(given, expected); Ok(()) } + +/// A file's plan data source scans the rows the request asks for, as a V2 scan built from +/// the file directly does. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn plan_data_source_scans_like_the_file() -> VortexResult<()> { + let file = file().await?; + let source = file.plan_data_source(); + assert_eq!(source.row_count(), Precision::exact(file.row_count())); + + let request = || ScanRequest { + projection: get_item("numbers", root()), + filter: Some(gt(get_item("numbers", root()), lit(4))), + row_range: Some(4..28), + ordered: true, + ..Default::default() + }; + let dtype = file.dtype().clone(); + let expected = ScanBuilder::new(SESSION.clone(), file.scan_file()) + .with_projection(request().projection.bind(&dtype)?) + .with_some_filter(request().filter.map(|f| f.bind(&dtype)).transpose()?) + .with_row_range(4..28); + let scan_dtype = expected.dtype().clone(); + let collect = |arrays: Vec| ChunkedArray::try_new(arrays, scan_dtype.clone()); + let expected = collect(driver().run(expected).try_collect().await?)?; + + let partitions: Vec = source + .scan(request()) + .await? + .partitions() + .try_collect() + .await?; + assert_eq!(partitions.len(), 1); + let executed = collect( + partitions + .into_iter() + .next() + .vortex_expect("one partition") + .execute()? + .try_collect() + .await?, + )?; + assert_arrays_eq!(executed, expected, &mut SESSION.create_execution_ctx()); + + Ok(()) +} diff --git a/vortex-io/src/runtime/current.rs b/vortex-io/src/runtime/current.rs index 203d7858359..adea7c77386 100644 --- a/vortex-io/src/runtime/current.rs +++ b/vortex-io/src/runtime/current.rs @@ -2,9 +2,11 @@ // SPDX-FileCopyrightText: Copyright the Vortex contributors use std::future::Future; +use std::pin::pin; use std::sync::Arc; use async_channel::TryRecvError; +use futures::FutureExt; use futures::SinkExt; use futures::Stream; use futures::StreamExt; @@ -136,7 +138,7 @@ impl BlockingRuntime for CurrentThreadRuntime { where Fut: Future, { - block_on(self.executor.run(fut)) + drive(&self.executor, fut) } fn block_on_stream<'a, S, R>(&self, stream: S) -> Self::BlockingIterator<'a, R> @@ -151,6 +153,22 @@ impl BlockingRuntime for CurrentThreadRuntime { } } +/// Drives `fut` to completion on the calling thread. +/// +/// The future is polled once before entering the executor and returned from directly if it is +/// ready. Each entry into [`smol::Executor::run`] registers the thread with the executor's shared +/// state, under a write lock that every thread entering the runtime contends on, and a caller that +/// blocks on many futures which are mostly ready already, such as one batch of a scan after +/// another, would otherwise pay that for each of them. A future that is not ready is polled again +/// inside the executor, which runs the runtime's tasks while the thread waits for it. +fn drive(executor: &SmolExecutor, fut: Fut) -> Fut::Output { + let mut fut = pin!(fut); + if let Some(output) = fut.as_mut().now_or_never() { + return output; + } + block_on(executor.run(fut)) +} + /// An iterator that wraps up a stream to drive it using the current thread execution. pub struct CurrentThreadIterator<'a, T> { executor: Arc, @@ -161,7 +179,7 @@ impl Iterator for CurrentThreadIterator<'_, T> { type Item = T; fn next(&mut self) -> Option { - block_on(self.executor.run(self.stream.next())) + drive(&self.executor, self.stream.next()) } } @@ -259,6 +277,16 @@ mod tests { use super::*; + #[test] + fn block_on_runs_tasks_for_a_future_that_is_not_ready() { + let runtime = CurrentThreadRuntime::new(); + assert_eq!(runtime.block_on(async { 7 }), 7); + // The spawned task has not run when the future is first polled, so it is ready only once + // block_on enters the executor, which runs the task. + let task = runtime.handle().spawn(async { 11 }); + assert_eq!(runtime.block_on(task), 11); + } + #[test] fn test_worker_thread() { let runtime = CurrentThreadRuntime::new(); diff --git a/vortex-layout/src/scan/layout.rs b/vortex-layout/src/scan/layout.rs index bada8995e0c..b4d40d57020 100644 --- a/vortex-layout/src/scan/layout.rs +++ b/vortex-layout/src/scan/layout.rs @@ -15,6 +15,7 @@ use futures::FutureExt; use futures::Stream; 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; @@ -30,6 +31,7 @@ use vortex_array::stream::SendableArrayStream; use vortex_error::VortexResult; use vortex_error::vortex_bail; use vortex_error::vortex_err; +use vortex_io::session::RuntimeSessionExt; use vortex_mask::Mask; use vortex_metrics::MetricsRegistry; use vortex_scan::DataSource; @@ -40,13 +42,17 @@ use vortex_scan::PartitionRef; use vortex_scan::PartitionStream; use vortex_scan::ScanRequest; use vortex_scan::selection::Selection; +use vortex_scan::stream::ExhaustedFlag; +use vortex_scan::stream::ScanExec; use vortex_session::VortexSession; use crate::LayoutReaderRef; use crate::scan::limit::RowLimit; use crate::scan::metrics::ScanMetrics; use crate::scan::metrics::ScanRecorder; +use crate::scan::repeated_scan::DEFAULT_SPLITS_PER_THREAD; use crate::scan::scan_builder::ScanBuilder; +use crate::scan::split_queue::SplitQueue; /// Cursor over absolute split-grid partition indices for a [`LayoutReaderDataSource`]. /// @@ -127,6 +133,20 @@ impl PartitionCursor { Some((partition_idx, split_start..split_end)) } + /// The rows the cursor has left, when they are a whole run of the grid: no partition range + /// or selection trims them. A scan cut into pieces or opened into a queue reads its rows + /// without the grid, so only such a scan can be. + fn whole_rows(&self) -> Option> { + if !matches!(self.partition_selection, Selection::All) { + return None; + } + let split_size = self.split_size.get(); + let start = self.next_partition.saturating_mul(split_size); + let end = self.end_partition.saturating_mul(split_size); + let covers_end = end >= self.row_range.end || self.row_range.start >= self.row_range.end; + (start <= self.row_range.start && covers_end).then(|| self.row_range.clone()) + } + fn remaining_count(&self) -> u64 { if self.next_partition >= self.end_partition { return 0; @@ -337,11 +357,100 @@ struct LayoutReaderScan { cursor: PartitionCursor, } +impl LayoutReaderScan { + /// A scan builder over this scan's reader, with its selection, projection, filter, metrics + /// and split concurrency. Callers give it the row range to read. + fn builder(&self) -> ScanBuilder { + ScanBuilder::new(self.session.clone(), Arc::clone(&self.reader)) + .with_selection(self.selection.clone()) + .with_projection(self.projection.clone()) + .with_some_filter(self.filter.clone()) + .with_some_scan_metrics(self.metrics.clone()) + .with_some_max_splits_in_flight(self.split_concurrency) + } + + /// This scan over `rows` only. Only a scan without a limit is cut into pieces, so a piece + /// has no limit to share. + fn piece(&self, rows: Range) -> Self { + Self { + reader: Arc::clone(&self.reader), + session: self.session.clone(), + dtype: self.dtype.clone(), + projection: self.projection.clone(), + filter: self.filter.clone(), + remaining_limit: None, + row_limit: None, + ordered: self.ordered, + split_concurrency: self.split_concurrency, + selection: self.selection.clone(), + metrics: self.metrics.clone(), + cursor: PartitionCursor::new(rows, self.cursor.split_size, None, Selection::All), + } + } +} + impl DataSourceScan for LayoutReaderScan { fn dtype(&self) -> &DType { &self.dtype } + /// Cuts the scan at the layout's natural split boundaries, into contiguous pieces of about + /// equal rows. + /// + /// A scan with a limit stays whole, because the limit is one budget across all its rows. So + /// does one that selects partitions, because its pieces would read rows outside them. + fn split(self: Box, n: NonZeroUsize) -> VortexResult> { + let rows = match self.cursor.whole_rows() { + Some(rows) if n.get() > 1 && self.remaining_limit.is_none() && !rows.is_empty() => rows, + _ => return Ok(vec![self]), + }; + let ranges = self.builder().prepare()?.split_ranges(Some(rows)); + let pieces: Vec> = group_contiguous(ranges, n) + .into_iter() + .filter_map(|group| Some(group.first()?.start..group.last()?.end)) + .collect(); + if pieces.len() <= 1 { + return Ok(vec![self]); + } + Ok(pieces + .into_iter() + .map(|rows| Box::new(self.piece(rows)) as DataSourceScanRef) + .collect()) + } + + /// Opens the scan into a [`SplitQueue`] of its split futures, each stream of it keeping the + /// stream pipeline's per-thread count of them in flight. + /// + /// Split futures cannot share a limit, and the streams of a queue finish splits out of row + /// order. So a scan with a limit, or an ordered one, opens into its partition pipeline and + /// hands its partitions to the streams. So does one that selects partitions, which the queue + /// does not know. + fn open(self: Box) -> VortexResult { + let rows = match self.cursor.whole_rows() { + Some(rows) if self.remaining_limit.is_none() && !self.ordered => rows, + _ => return Ok(ScanExec::from_partitions(self)), + }; + // A cap on the scan's splits in flight also caps each stream's. + let per_worker = self + .split_concurrency + .map_or(DEFAULT_SPLITS_PER_THREAD, |max| { + max.get().min(DEFAULT_SPLITS_PER_THREAD) + }); + let splits = self.builder().prepare()?.execute(Some(rows))?; + let exhausted = ExhaustedFlag::new(); + let queue = Arc::new(SplitQueue::new( + self.session.handle(), + per_worker, + splits, + exhausted.clone(), + )); + 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 { let (lower, upper) = self.size_hint(); match upper { @@ -356,6 +465,33 @@ impl DataSourceScan for LayoutReaderScan { } } +/// Groups consecutive `ranges` into at most `n` contiguous groups of about equal row counts. +/// +/// Never cuts a range: each range lands whole in one group. +pub(crate) fn group_contiguous(ranges: Vec>, n: NonZeroUsize) -> Vec>> { + let total = ranges + .iter() + .map(|range| u128::from(range.end - range.start)) + .sum::() + .max(1); + let n_groups = n.get() as u128; + let mut groups: Vec>> = Vec::new(); + let mut current_group = None; + let mut before = 0u128; + for range in ranges { + let group = (before * n_groups / total).min(n_groups - 1); + before += u128::from(range.end - range.start); + if current_group != Some(group) { + current_group = Some(group); + groups.push(Vec::new()); + } + if let Some(last) = groups.last_mut() { + last.push(range); + } + } + groups +} + impl Stream for LayoutReaderScan { type Item = VortexResult; @@ -518,6 +654,14 @@ impl DataSourceScan for EmptyScan { &self.dtype } + fn split(self: Box, _n: NonZeroUsize) -> VortexResult> { + Ok(vec![self]) + } + + fn open(self: Box) -> VortexResult { + Ok(ScanExec::from_partitions(self)) + } + fn partition_count(&self) -> Precision { let (lower, upper) = self.size_hint(); match upper { @@ -1064,3 +1208,131 @@ mod tests { Ok(()) } } + +#[cfg(test)] +mod split_open_tests { + use std::num::NonZeroUsize; + use std::sync::Arc; + + use futures::TryStreamExt; + use futures::future::try_join_all; + use vortex_error::VortexResult; + use vortex_io::runtime::BlockingRuntime; + 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; + use crate::scan::test::TestLayoutReader; + use crate::scan::test::collect_scan_values; + use crate::scan::test::session_with_handle; + + fn source(runtime: &SingleThreadRuntime) -> LayoutReaderDataSource { + LayoutReaderDataSource::new( + Arc::new(TestLayoutReader::new(64).with_split_size(4)), + session_with_handle(runtime.handle()), + ) + } + + /// The streams of an opened scan each claim splits until none is left, so together they read + /// every row once, and the scan is exhausted once the last split is claimed. + #[test] + fn opened_streams_read_every_row_once() -> VortexResult<()> { + let runtime = SingleThreadRuntime::default(); + let exec = runtime + .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(()) + } + + /// The pieces of an unordered scan are fixed too: each owns a contiguous run of splits, + /// which it may return in any order. + #[test] + fn unordered_pieces_own_their_rows() -> VortexResult<()> { + let runtime = SingleThreadRuntime::default(); + let scan = runtime.block_on(source(&runtime).scan(ScanRequest::default()))?; + let pieces = scan.split(NonZeroUsize::try_from(4)?)?; + assert_eq!(pieces.len(), 4); + for (i, piece) in (0i32..).zip(pieces) { + let mut values = collect_scan_values(runtime.block_on_stream(piece.open()?.stream()))?; + values.sort_unstable(); + assert_eq!(values, (16 * i..16 * (i + 1)).collect::>()); + } + Ok(()) + } + + /// An ordered scan is cut at the layout's split boundaries, and the pieces read the rows in + /// order. + #[test] + fn ordered_split_cuts_at_split_boundaries() -> VortexResult<()> { + let runtime = SingleThreadRuntime::default(); + let scan = runtime.block_on(source(&runtime).scan(ScanRequest { + ordered: true, + ..Default::default() + }))?; + let pieces = scan.split(NonZeroUsize::try_from(4)?)?; + assert_eq!(pieces.len(), 4); + let mut values = Vec::new(); + for piece in pieces { + values.extend(collect_scan_values( + runtime.block_on_stream(piece.open()?.stream()), + )?); + } + assert_eq!(values, (0..64).collect::>()); + Ok(()) + } + + /// A limit is one budget across the scan, so a limited scan stays whole and opens into its + /// partitions, which apply the limit. + #[test] + fn limited_scan_stays_whole() -> VortexResult<()> { + let runtime = SingleThreadRuntime::default(); + let source = LayoutReaderDataSource::new( + Arc::new(TestLayoutReader::new(64).with_split_size(4)), + session_with_handle(runtime.handle()), + ); + let request = || ScanRequest { + limit: Some(10), + ..Default::default() + }; + let scan = runtime.block_on(source.scan(request()))?; + assert_eq!(scan.split(NonZeroUsize::try_from(4)?)?.len(), 1); + + let stream = runtime.block_on(source.scan(request()))?.open()?.stream(); + let values = collect_scan_values(runtime.block_on_stream(stream))?; + assert_eq!(values.len(), 10); + Ok(()) + } + + #[test] + fn group_contiguous_keeps_ranges_whole() -> VortexResult<()> { + // Each range joins the group its first row falls in. + let ranges = vec![0..10, 10..16, 16..26, 26..32]; + let groups = group_contiguous(ranges, NonZeroUsize::try_from(2)?); + assert_eq!(groups, vec![vec![0..10, 10..16], vec![16..26, 26..32]]); + Ok(()) + } +} diff --git a/vortex-layout/src/scan/limit.rs b/vortex-layout/src/scan/limit.rs index e7791e5961f..42e69a54a56 100644 --- a/vortex-layout/src/scan/limit.rs +++ b/vortex-layout/src/scan/limit.rs @@ -1,22 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors -use std::sync::Arc; -use std::sync::atomic::AtomicU64; -use std::sync::atomic::Ordering; - -use vortex_error::VortexExpect; -use vortex_mask::Mask; - -/// A cloneable row budget shared by all work that can contribute rows to one scan. -/// -/// Filterless scans reserve each split's selected rows before constructing its projection, so -/// rows past the limit are never decoded. Filtered scans cannot know a split's row count up front, -/// so they take rows from the budget as arrays are emitted and discard the excess. Either way, -/// the order in which rows are taken decides which rows are returned: an ordered scan takes them -/// in split order, an unordered one in completion order. -#[derive(Clone)] -pub(crate) struct RowLimit(Arc); +pub(crate) use vortex_scan::limit::RowLimit; /// The row limit of a scan. #[derive(Clone)] @@ -36,109 +21,3 @@ impl ScanLimit { } } } - -impl RowLimit { - pub(crate) fn new(limit: u64) -> Self { - Self(Arc::new(AtomicU64::new(limit))) - } - - /// Reserve rows selected by `mask` and retain only the earliest granted rows in that mask. - pub(crate) fn limit(&self, mask: Mask) -> Mask { - let granted = self.take(mask.true_count()); - mask.limit(granted) - } - - /// Reserve up to `rows` rows, returning how many the remaining budget granted. - pub(crate) fn take(&self, rows: usize) -> usize { - let requested = u64::try_from(rows).unwrap_or(u64::MAX); - usize::try_from(self.reserve(requested)).unwrap_or(usize::MAX) - } - - pub(crate) fn is_exhausted(&self) -> bool { - self.0.load(Ordering::Relaxed) == 0 - } - - fn reserve(&self, requested: u64) -> u64 { - let remaining = self - .0 - .try_update(Ordering::Relaxed, Ordering::Relaxed, |remaining| { - Some(remaining.saturating_sub(requested)) - }) - .ok() - .vortex_expect("row reservation always updates the budget"); - remaining.min(requested) - } -} - -#[cfg(test)] -mod tests { - use std::sync::Arc; - use std::sync::Barrier; - use std::sync::atomic::AtomicU64; - use std::sync::atomic::Ordering; - use std::thread; - - use vortex_mask::Mask; - - use super::RowLimit; - - #[test] - fn reserve_grants_up_to_the_remaining_budget() { - let limit = RowLimit::new(5); - assert_eq!(limit.reserve(3), 3); - assert!(!limit.is_exhausted()); - // Only two rows remain, so a larger request saturates at what is left. - assert_eq!(limit.reserve(10), 2); - assert!(limit.is_exhausted()); - // Once exhausted, further requests grant nothing. - assert_eq!(limit.reserve(1), 0); - } - - #[test] - fn limit_keeps_the_earliest_granted_rows() { - let limit = RowLimit::new(2); - // Rows 0, 2, 3, 5 are selected; only the first two survive the budget of 2. - let mask = Mask::from_iter([true, false, true, true, false, true]); - let limited = limit.limit(mask); - - assert_eq!(limited.true_count(), 2); - assert!(limited.value(0)); - assert!(limited.value(2)); - assert!(!limited.value(3)); - assert!(!limited.value(5)); - assert!(limit.is_exhausted()); - } - - #[test] - fn concurrent_reservations_never_exceed_the_budget() { - const THREADS: usize = 8; - const PER_THREAD: u64 = 10_000; - const LIMIT: u64 = 25_000; - - let limit = RowLimit::new(LIMIT); - let granted_total = Arc::new(AtomicU64::new(0)); - let barrier = Arc::new(Barrier::new(THREADS)); - - thread::scope(|scope| { - for _ in 0..THREADS { - let limit = limit.clone(); - let granted_total = Arc::clone(&granted_total); - let barrier = Arc::clone(&barrier); - scope.spawn(move || { - // Start all threads together to maximize contention on the atomic. - barrier.wait(); - let mut local = 0; - for _ in 0..PER_THREAD { - local += limit.reserve(1); - } - granted_total.fetch_add(local, Ordering::Relaxed); - }); - } - }); - - // Total requested (THREADS * PER_THREAD = 80_000) exceeds the budget, so exactly the - // budget is granted across all threads — no double-grant, over-grant, or lost reservation. - assert_eq!(granted_total.load(Ordering::Relaxed), LIMIT); - assert!(limit.is_exhausted()); - } -} diff --git a/vortex-layout/src/scan/mod.rs b/vortex-layout/src/scan/mod.rs index ea8e8843773..bda570ee1e7 100644 --- a/vortex-layout/src/scan/mod.rs +++ b/vortex-layout/src/scan/mod.rs @@ -10,6 +10,7 @@ pub mod multi; pub mod repeated_scan; pub mod scan_builder; pub mod split_by; +mod split_queue; mod splits; mod tasks; #[cfg(test)] diff --git a/vortex-layout/src/scan/multi.rs b/vortex-layout/src/scan/multi.rs index ba3141628be..819e9dff5d7 100644 --- a/vortex-layout/src/scan/multi.rs +++ b/vortex-layout/src/scan/multi.rs @@ -33,6 +33,7 @@ use std::sync::Arc; use async_trait::async_trait; use futures::FutureExt; use futures::StreamExt; +use futures::TryStreamExt; use futures::stream; use itertools::Itertools; use tracing::Instrument; @@ -58,13 +59,22 @@ use vortex_scan::PartitionRef; use vortex_scan::PartitionStream; use vortex_scan::ScanRequest; use vortex_scan::selection::Selection; +use vortex_scan::stream::ExhaustedFlag; +use vortex_scan::stream::ScanExec; use vortex_session::VortexSession; use vortex_utils::parallelism::get_available_parallelism; use crate::LayoutReaderRef; +use crate::scan::layout::group_contiguous; use crate::scan::limit::RowLimit; use crate::scan::scan_builder::ScanBuilder; +/// How many files each stream of an opened unordered scan reads at once. +/// +/// This matches the read-ahead of the DataFusion `VortexTable` path on develop +/// (`SCAN_PARTITION_READ_AHEAD`), whose partitions share one stream of files as the scan's streams do. +const PARTITION_READ_AHEAD: usize = 2; + /// Default concurrency for opening deferred readers. const DEFAULT_CONCURRENCY: usize = 8; @@ -300,20 +310,26 @@ impl DataSource for MultiLayoutDataSource { let mut ready = VecDeque::new(); let mut deferred = VecDeque::new(); + let mut ready_sizes = VecDeque::new(); + let mut deferred_sizes = VecDeque::new(); for (partition_idx, child) in self.children.iter().enumerate() { if !request.includes_partition(partition_idx as u64) { continue; } match child { - MultiLayoutChild::Opened { reader, .. } => { - ready.push_back((partition_idx, Arc::clone(reader))) + MultiLayoutChild::Opened { reader, byte_size } => { + ready.push_back((partition_idx, Arc::clone(reader))); + ready_sizes.push_back(*byte_size); } - MultiLayoutChild::Deferred { factory, .. } => { - deferred.push_back((partition_idx, Arc::clone(factory))) + MultiLayoutChild::Deferred { factory, byte_size } => { + deferred.push_back((partition_idx, Arc::clone(factory))); + deferred_sizes.push_back(*byte_size); } } } + // The scan reads its opened files first, so its sizes follow that order too. + let byte_sizes = ready_sizes.into_iter().chain(deferred_sizes).collect(); // 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 @@ -330,6 +346,7 @@ impl DataSource for MultiLayoutDataSource { row_limit, ready, deferred, + byte_sizes, handle: self.session.handle(), concurrency: self.concurrency, })) @@ -398,8 +415,12 @@ struct MultiLayoutScan { dtype: DType, request: BoundScanRequest, row_limit: Option, + /// The opened files, each with its partition index among the source's children. ready: VecDeque<(usize, LayoutReaderRef)>, + /// The files still to open, each with its partition index among the source's children. deferred: VecDeque<(usize, Arc)>, + /// The on-storage size of each file, if known: the `ready` files, then the `deferred` ones. + byte_sizes: VecDeque>, handle: vortex_io::runtime::Handle, concurrency: usize, } @@ -409,6 +430,180 @@ impl DataSourceScan for MultiLayoutScan { &self.dtype } + /// Cuts the scan into at most `n` contiguous pieces in file order, reading metadata only. + /// + /// With at least `n` files, each piece is a run of whole files. The runs balance the + /// files' byte sizes when every size is known, and their counts otherwise. With fewer files, + /// each file gets a share of the `n` pieces in proportion to its size, at least one, and no + /// piece holds parts of two files. A file that is open is cut at its natural split + /// boundaries. A file that is not open stays one piece, because cutting it would mean + /// opening it, so the scan may return fewer than `n` pieces. + /// + /// A scan with a limit stays whole, because the limit is one budget across all its files. + /// So does one that selects partitions, because partition indices count from its first + /// file. + fn split(self: Box, n: NonZeroUsize) -> VortexResult> { + let files = self.ready.len() + self.deferred.len(); + if n.get() == 1 + || files == 0 + || self.request.limit.is_some() + || self.request.partition_range.is_some() + || !matches!(self.request.partition_selection, Selection::All) + { + return Ok(vec![self]); + } + let Self { + session, + source_dtype, + dtype, + request, + row_limit, + mut ready, + mut deferred, + mut byte_sizes, + handle, + concurrency, + } = *self; + + let weights: Vec = byte_sizes + .iter() + .map(|size| size.map(|size| u128::from(size.max(1)))) + .collect::>() + .unwrap_or_else(|| vec![1; files]); + let total = weights.iter().sum::(); + let n = n.get(); + + let piece = |ready: VecDeque<(usize, LayoutReaderRef)>, + deferred: VecDeque<(usize, Arc)>, + byte_sizes: VecDeque>, + request: BoundScanRequest| { + Box::new(MultiLayoutScan { + session: session.clone(), + source_dtype: source_dtype.clone(), + dtype: dtype.clone(), + request, + row_limit: row_limit.clone(), + ready, + deferred, + byte_sizes, + handle: handle.clone(), + concurrency, + }) as DataSourceScanRef + }; + + if files >= n { + // Each file joins the piece in which its first byte falls. + let mut runs: Vec = Vec::with_capacity(n); + let mut last_group = None; + let mut before = 0u128; + for weight in &weights { + let group = before * n as u128 / total; + before += weight; + match runs.last_mut() { + Some(run) if last_group == Some(group) => *run += 1, + _ => runs.push(1), + } + last_group = Some(group); + } + return Ok(runs + .into_iter() + .map(|take| { + let from_ready = take.min(ready.len()); + piece( + ready.drain(..from_ready).collect(), + deferred.drain(..take - from_ready).collect(), + byte_sizes.drain(..take).collect(), + request.clone(), + ) + }) + .collect()); + } + + let spare = (n - files) as u128; + let shares = weights + .iter() + .map(|weight| 1 + u64::try_from(weight * spare / total).unwrap_or(0)); + let mut pieces = Vec::with_capacity(n); + let mut sizes = byte_sizes.into_iter(); + let ready_len = ready.len(); + for (file, share) in shares.enumerate() { + let size = sizes.next().flatten(); + if file < ready_len { + let Some((partition_idx, reader)) = ready.pop_front() else { + break; + }; + let cuts = (share > 1) + .then(|| opened_file_cuts(&session, &reader, &request, share)) + .flatten(); + match cuts { + Some(cuts) => { + for rows in cuts { + let mut request = request.clone(); + request.row_range = Some(rows); + pieces.push(piece( + VecDeque::from([(partition_idx, Arc::clone(&reader))]), + VecDeque::new(), + VecDeque::from([size]), + request, + )); + } + } + None => pieces.push(piece( + VecDeque::from([(partition_idx, reader)]), + VecDeque::new(), + VecDeque::from([size]), + request.clone(), + )), + } + } else { + let Some(factory) = deferred.pop_front() else { + break; + }; + pieces.push(piece( + VecDeque::new(), + VecDeque::from([factory]), + VecDeque::from([size]), + request.clone(), + )); + } + } + Ok(pieces) + } + + /// Opens the scan into its partition pipeline, which opens up to `concurrency` files ahead + /// and reads each file as one partition, handing the partitions to the scan's streams. + /// + /// Each stream of an unordered scan without a limit reads [`PARTITION_READ_AHEAD`] files at + /// once, each with its own split concurrency, so that one file's last splits overlap the + /// next file's first. An ordered scan must finish a file before it starts the next, and a + /// limited one would read files the limit may never need, so both read one at a time. + fn open(self: Box) -> VortexResult { + if self.request.ordered || self.request.limit.is_some() { + return Ok(ScanExec::from_partitions(self)); + } + let dtype = self.dtype.clone(); + let exhausted = ExhaustedFlag::new(); + let flag = exhausted.clone(); + let partitions = Arc::new(futures::lock::Mutex::new(self.partitions())); + Ok(ScanExec::new(dtype, exhausted, move || { + let flag = flag.clone(); + stream::unfold(Arc::clone(&partitions), move |shared| { + let flag = flag.clone(); + async move { + let Some(next) = shared.lock().await.next().await else { + flag.set(); + return None; + }; + Some((next, shared)) + } + }) + .map(|partition| partition.and_then(|partition| partition.execute())) + // Matches the read-ahead of the DataFusion `VortexTable` path on develop. + .try_flatten_unordered(Some(PARTITION_READ_AHEAD)) + .boxed() + })) + } + fn partition_count(&self) -> Precision { let count = self.ready.len() + self.deferred.len(); if !self.deferred.is_empty() || matches!(self.request.filter, Ok(Some(_))) { @@ -427,6 +622,7 @@ impl DataSourceScan for MultiLayoutScan { row_limit, ready, deferred, + byte_sizes: _, handle, concurrency, } = *self; @@ -495,6 +691,66 @@ impl DataSourceScan for MultiLayoutScan { } } +/// The row ranges of `reader`'s natural splits within `rows` that `request` reads, or `None` if +/// they cannot be planned, such as when the request does not bind to the file. Reads metadata +/// only. +fn file_split_ranges( + session: &VortexSession, + reader: &LayoutReaderRef, + request: &BoundScanRequest, + rows: Range, +) -> Option>> { + let filter = request.filter.clone().ok()?; + let scan = ScanBuilder::new(session.clone(), Arc::clone(reader)) + .with_selection(request.selection.clone()) + .with_projection(request.projection.clone()) + .with_some_filter(filter) + .prepare() + .ok()?; + Some(scan.split_ranges(Some(rows))) +} + +/// Cuts the rows of an opened file that `request` reads into at most `share` ranges that cover +/// them in order, at the file's natural split boundaries. `None` if the file cannot be cut. +fn opened_file_cuts( + session: &VortexSession, + reader: &LayoutReaderRef, + request: &BoundScanRequest, + share: u64, +) -> Option>> { + let row_count = reader.row_count(); + let rows = request.row_range.clone().map_or(0..row_count, |rows| { + rows.start.min(row_count)..rows.end.min(row_count) + }); + let share = NonZeroUsize::new(usize::try_from(share).ok()?)?; + let splits = file_split_ranges(session, reader, request, rows.clone())?; + let groups = group_contiguous(splits, share); + if groups.len() <= 1 { + return None; + } + let last = groups.len() - 1; + Some( + groups + .iter() + .enumerate() + .filter_map(|(i, group)| { + // The cuts start and end where `rows` does, so no row is lost at either edge. + let start = if i == 0 { + rows.start + } else { + group.first()?.start + }; + let end = if i == last { + rows.end + } else { + group.last()?.end + }; + Some(start..end) + }) + .collect(), + ) +} + /// Generates a partition stream for a single layout reader. /// /// Checks file-level pruning first (via `pruning_evaluation`). If the filter proves no rows @@ -654,7 +910,7 @@ mod tests { #[async_trait] impl LayoutReaderFactory for NeverOpened { async fn open(&self) -> VortexResult> { - unreachable!("byte_size must not open readers") + unreachable!("byte_size and split must not open readers") } } @@ -742,6 +998,212 @@ mod tests { Ok(()) } + /// Reads every partition of `piece`, in order. + fn piece_values( + runtime: &SingleThreadRuntime, + piece: DataSourceScanRef, + ) -> VortexResult> { + let mut values = Vec::new(); + for partition in runtime.block_on(piece.partitions().try_collect::>())? { + values.extend(collect_scan_values( + runtime.block_on_stream(partition.execute()?), + )?); + } + Ok(values) + } + + /// A source of files that are never opened, whose scans run on `runtime`. + fn unopened_files( + runtime: &SingleThreadRuntime, + byte_sizes: Vec>, + ) -> MultiLayoutDataSource { + let factories = byte_sizes + .iter() + .map(|_| Arc::new(NeverOpened) as Arc) + .collect(); + MultiLayoutDataSource::new_deferred( + DType::Bool(Nullability::NonNullable), + factories, + byte_sizes, + &session_with_handle(runtime.handle()), + ) + } + + /// With at least `n` files, splitting hands out runs of whole files in file order, without + /// opening any. + #[test] + fn split_groups_whole_files() -> VortexResult<()> { + let runtime = SingleThreadRuntime::default(); + let session = session_with_handle(runtime.handle()); + let first: LayoutReaderRef = Arc::new(TestLayoutReader::new(2)); + let rest = (1..5) + .map(|file| { + Arc::new(StaticReaderFactory { + reader: Arc::new(TestLayoutReader::new(2).with_base(10 * file)), + }) as Arc + }) + .collect(); + let source = MultiLayoutDataSource::new_with_first(first, rest, vec![], &session); + + let scan = runtime.block_on(source.scan(ScanRequest { + ordered: true, + ..Default::default() + }))?; + let pieces = scan.split(NonZeroUsize::try_from(3)?)?; + let files: Vec<_> = pieces.iter().map(|piece| piece.partition_count()).collect(); + assert_eq!( + files, + [ + Precision::inexact(2usize), + Precision::inexact(2usize), + Precision::inexact(1usize) + ] + ); + + let mut values = Vec::new(); + for piece in pieces { + values.extend(piece_values(&runtime, piece)?); + } + assert_eq!(values, [0, 1, 10, 11, 20, 21, 30, 31, 40, 41]); + Ok(()) + } + + /// Known file sizes balance the runs by bytes rather than by file count. `NeverOpened` + /// panics if splitting opens a file. + #[test] + fn split_balances_whole_files_by_size() -> VortexResult<()> { + let runtime = SingleThreadRuntime::default(); + let scan = runtime.block_on( + unopened_files(&runtime, vec![Some(80), Some(10), Some(10)]).scan(ScanRequest { + ordered: true, + ..Default::default() + }), + )?; + let files: Vec<_> = scan + .split(NonZeroUsize::try_from(2)?)? + .iter() + .map(|piece| piece.partition_count()) + .collect(); + assert_eq!( + files, + [Precision::inexact(1usize), Precision::inexact(2usize)] + ); + Ok(()) + } + + /// An ordered split never opens a file to cut it, so an unopened file stays one piece. + #[test] + fn ordered_split_keeps_unopened_files_whole() -> VortexResult<()> { + let runtime = SingleThreadRuntime::default(); + let scan = runtime.block_on(unopened_files(&runtime, vec![Some(30), Some(10)]).scan( + ScanRequest { + ordered: true, + ..Default::default() + }, + ))?; + assert_eq!(scan.split(NonZeroUsize::try_from(4)?)?.len(), 2); + Ok(()) + } + + /// An opened file is cut at its split boundaries. + #[test] + fn split_cuts_an_opened_file_at_splits() -> VortexResult<()> { + let runtime = SingleThreadRuntime::default(); + let session = session_with_handle(runtime.handle()); + let reader: LayoutReaderRef = Arc::new(TestLayoutReader::new(8).with_split_size(2)); + let source = MultiLayoutDataSource::new_with_first(reader, vec![], vec![], &session); + + let scan = runtime.block_on(source.scan(ScanRequest { + ordered: true, + ..Default::default() + }))?; + let pieces = scan + .split(NonZeroUsize::try_from(4)?)? + .into_iter() + .map(|piece| piece_values(&runtime, piece)) + .collect::>>()?; + assert_eq!(pieces, [vec![0, 1], vec![2, 3], vec![4, 5], vec![6, 7]]); + Ok(()) + } + + /// The pieces of an unordered scan are fixed: each owns its files' rows. Files that cannot + /// be cut stay whole, so there may be fewer pieces than asked for. + #[test] + fn unordered_pieces_own_their_files() -> VortexResult<()> { + let runtime = SingleThreadRuntime::default(); + let session = session_with_handle(runtime.handle()); + let first: LayoutReaderRef = Arc::new(TestLayoutReader::new(2)); + let rest = (1..3) + .map(|file| { + Arc::new(StaticReaderFactory { + reader: Arc::new(TestLayoutReader::new(2).with_base(10 * file)), + }) as Arc + }) + .collect(); + let source = MultiLayoutDataSource::new_with_first(first, rest, vec![], &session); + + let scan = runtime.block_on(source.scan(ScanRequest::default()))?; + let pieces = scan.split(NonZeroUsize::try_from(5)?)?; + let pieces = pieces + .into_iter() + .map(|piece| { + let mut values = piece_values(&runtime, piece)?; + values.sort_unstable(); + Ok(values) + }) + .collect::>>()?; + assert_eq!(pieces, [vec![0, 1], vec![10, 11], vec![20, 21]]); + Ok(()) + } + + /// A stream of an opened unordered scan reads two files at once, each with its own + /// split concurrency. An ordered scan reads one file at a time. + #[rstest] + #[case::unordered(false, 2)] + #[case::ordered(true, 1)] + fn opened_stream_reads_files_ahead( + #[case] ordered: bool, + #[case] expected_peak: usize, + ) -> VortexResult<()> { + let runtime = SingleThreadRuntime::default(); + let session = session_with_handle(runtime.handle()); + let in_flight = Arc::new(InFlight::default()); + let file = |base: i32| { + Arc::new( + TestLayoutReader::new(8) + .with_split_size(1) + .with_base(base) + .with_in_flight(Arc::clone(&in_flight)), + ) as LayoutReaderRef + }; + let rest = (1..3) + .map(|i| { + Arc::new(StaticReaderFactory { + reader: file(10 * i), + }) as Arc + }) + .collect(); + let source = MultiLayoutDataSource::new_with_first(file(0), rest, vec![], &session); + + let stream = runtime + .block_on(source.scan(ScanRequest { + ordered, + split_concurrency: NonZeroUsize::new(1), + ..Default::default() + }))? + .open()? + .stream(); + let mut values = collect_scan_values(runtime.block_on_stream(stream))?; + values.sort_unstable(); + let expected: Vec = [0, 10, 20] + .into_iter() + .flat_map(|base| base..base + 8) + .collect(); + assert_eq!(values, expected); + assert_eq!(in_flight.peak(), expected_peak, "splits read at once"); + Ok(()) + } + /// Scans 64 one-row splits, returning the rows and the most splits read at once. fn scan_with_split_concurrency( split_concurrency: Option, diff --git a/vortex-layout/src/scan/repeated_scan.rs b/vortex-layout/src/scan/repeated_scan.rs index 2a1c7026923..be849306f4a 100644 --- a/vortex-layout/src/scan/repeated_scan.rs +++ b/vortex-layout/src/scan/repeated_scan.rs @@ -32,6 +32,7 @@ use vortex_error::VortexResult; use vortex_error::vortex_bail; use vortex_io::runtime::BlockingRuntime; use vortex_io::session::RuntimeSessionExt; +use vortex_scan::limit::limit_rows; use vortex_scan::row_mask::RowMask; use vortex_scan::selection::Selection; use vortex_session::VortexSession; @@ -188,7 +189,8 @@ impl RepeatedScan { }) } - fn split_ranges(&self, row_range: Option>) -> Vec> { + /// The row ranges of the scan's natural splits within `row_range`, in row order. + pub(crate) fn split_ranges(&self, row_range: Option>) -> Vec> { let selection_range: Option> = match &self.selection { Selection::IncludeByIndex(buf) if !buf.is_empty() => { Some(buf[0]..buf[buf.len() - 1] + 1) @@ -383,43 +385,6 @@ fn map_split( .boxed() } -/// Trim arrays to the budget and drop upstream work as soon as it is exhausted. -fn limit_rows( - arrays: BoxStream<'static, VortexResult>, - limit: RowLimit, -) -> BoxStream<'static, VortexResult> { - let mut arrays = Some(arrays); - stream::poll_fn(move |cx| { - loop { - if limit.is_exhausted() { - arrays = None; - } - let Some(stream) = arrays.as_mut() else { - return Poll::Ready(None); - }; - let array = match ready!(stream.poll_next_unpin(cx)) { - Some(Ok(array)) => array, - end => { - arrays = None; - return Poll::Ready(end); - } - }; - let granted = limit.take(array.len()); - if limit.is_exhausted() { - arrays = None; - } - if granted != 0 { - return Poll::Ready(Some(if granted < array.len() { - array.slice(0..granted) - } else { - Ok(array) - })); - } - } - }) - .boxed() -} - /// Yield the first error and drop upstream without polling it again. fn stop_on_error( stream: BoxStream<'static, VortexResult>, @@ -438,6 +403,10 @@ fn stop_on_error( .boxed() } +/// The splits a scan keeps in flight for each worker thread by default, which allows for some I/O +/// lookahead without too much impact on work-stealing. +pub(crate) const DEFAULT_SPLITS_PER_THREAD: usize = 4; + /// How many splits a scan makes progress on at once: `per_worker` for each worker thread, as /// [`get_available_parallelism`] counts them, and at most `max` in all when that is set. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -500,9 +469,9 @@ mod tests { use vortex_array::arrays::PrimitiveArray; use vortex_error::VortexResult; use vortex_error::vortex_err; + use vortex_scan::limit::limit_rows; use super::SplitConcurrency; - use super::limit_rows; use super::stop_on_error; use crate::scan::limit::RowLimit; diff --git a/vortex-layout/src/scan/scan_builder.rs b/vortex-layout/src/scan/scan_builder.rs index b57162dde0b..6d74559550c 100644 --- a/vortex-layout/src/scan/scan_builder.rs +++ b/vortex-layout/src/scan/scan_builder.rs @@ -40,6 +40,7 @@ use crate::scan::limit::RowLimit; use crate::scan::limit::ScanLimit; use crate::scan::metrics::ScanMetrics; use crate::scan::metrics::ScanUsage; +use crate::scan::repeated_scan::DEFAULT_SPLITS_PER_THREAD; use crate::scan::repeated_scan::RepeatedScan; use crate::scan::repeated_scan::ScanTasks; use crate::scan::repeated_scan::SplitConcurrency; @@ -103,10 +104,8 @@ impl ScanBuilder { selection: Default::default(), split_by: SplitBy::default(), natural_splits: None, - // We default to four tasks per worker thread, which allows for some I/O lookahead - // without too much impact on work-stealing. concurrency: SplitConcurrency { - per_worker: 4, + per_worker: DEFAULT_SPLITS_PER_THREAD, max: None, }, map_fn: Arc::new(Ok), diff --git a/vortex-layout/src/scan/split_queue.rs b/vortex-layout/src/scan/split_queue.rs new file mode 100644 index 00000000000..82cc721ac3b --- /dev/null +++ b/vortex-layout/src/scan/split_queue.rs @@ -0,0 +1,117 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! The queue of splits behind an opened layout scan. + +use std::iter; +use std::sync::Arc; +use std::sync::atomic::AtomicUsize; +use std::sync::atomic::Ordering; +use std::vec; + +use futures::StreamExt; +use futures::future; +use futures::future::BoxFuture; +use futures::stream; +use futures::stream::BoxStream; +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; + +/// One split of a scan, which returns the split's array, or `None` when the filter removes all +/// of its rows. +type SplitTask = BoxFuture<'static, VortexResult>>; + +/// A queue of the split futures of [`RepeatedScan::execute`], in row order, which the streams of +/// an opened scan share. Each stream polls one worker over the queue. +/// +/// Each worker claims splits from the queue and keeps up to `per_worker` of its own in +/// flight, spawned on the session's runtime, yielding them as they finish. This is the scan's +/// stream pipeline with its in-flight bound split across workers: `per_worker` is the per-thread +/// count that the stream multiplies by the cores, so a host polling one worker per core keeps as +/// many splits in flight as the stream does. +/// +/// 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, + per_worker: usize, + splits: Mutex>, + total: usize, + claimed: AtomicUsize, + /// Set once the last split is claimed. + exhausted: ExhaustedFlag, +} + +impl SplitQueue { + pub(crate) fn new( + handle: Handle, + per_worker: usize, + splits: ScanTasks, + exhausted: ExhaustedFlag, + ) -> Self { + if splits.is_empty() { + exhausted.set(); + } + Self { + handle, + per_worker: per_worker.max(1), + total: splits.len(), + splits: Mutex::new(splits.into_iter()), + claimed: AtomicUsize::new(0), + exhausted, + } + } + + /// Claims the next split, if any is left, and marks the queue exhausted when it claims the + /// last. + fn claim(&self) -> Option { + let mut splits = self.splits.lock(); + let split = splits.next()?; + 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(); + 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. + splits + .map(move |split| handle.spawn(split)) + .buffer_unordered(per_worker) + .filter_map(|array| future::ready(array.transpose())) + .boxed() + } +} diff --git a/vortex-scan/src/execution/mod.rs b/vortex-scan/src/execution/mod.rs index caa6a7ce099..2bd2cd06a95 100644 --- a/vortex-scan/src/execution/mod.rs +++ b/vortex-scan/src/execution/mod.rs @@ -25,6 +25,7 @@ pub(crate) mod zone_map; mod adaptor; mod chunk; mod filter; +mod parts; mod projection; mod prune; mod selection; @@ -45,10 +46,10 @@ pub(crate) use self::chunk::ROW_BLOCK_SIZE; #[cfg(test)] pub(crate) use self::chunk::row_chunks; pub(crate) use self::chunk::rows_per_chunk; -#[cfg(test)] pub(crate) use self::chunk::scan_chunks; use self::filter::FilterPlanner; pub use self::filter::FilterPlans; +pub use self::parts::part_root; use self::projection::ProjectionPlanner; pub use self::prune::PruneNext; pub use self::prune::PrunePlanner; diff --git a/vortex-scan/src/execution/parts.rs b/vortex-scan/src/execution/parts.rs new file mode 100644 index 00000000000..606167b6878 --- /dev/null +++ b/vortex-scan/src/execution/parts.rs @@ -0,0 +1,170 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Cutting a prepared scan into parts, the units a host's threads take. + +use std::ops::Range; +use std::sync::Arc; + +use vortex_error::VortexExpect; +use vortex_error::VortexResult; +use vortex_io::request::IoConsumer; +use vortex_io::request::IoRequestId; +use vortex_io::request::IoResult; +use vortex_mask::Mask; + +use super::ChunkPlanner; +use super::PreparedScan; +use super::PrunePlanner; +use crate::planning::planner::Planner; +use crate::planning::planner::PlannerOutput; +use crate::planning::planner::State; +use crate::planning::planner::WorkScope; +use crate::selection::Selection; + +/// The root planner of a scan cut into parts on `splits`, such as a file's layout split +/// boundaries: it spawns one planner per part, in row order. With a dynamic filter, its pruning +/// plans first over the scan's rows, continuing into the parts of the rows they keep; otherwise, +/// the parts directly. +pub fn part_root(scan: &Arc, splits: &[u64], dynamic: bool) -> Box { + let rows = scan.rows().clone(); + let parts = { + let scan = Arc::clone(scan); + let parts = part_ranges(rows.clone(), splits); + let first_row = rows.start; + move |kept: Option| -> Box { + Box::new(PartPlanner::new(scan, parts, first_row, kept)) + } + }; + if dynamic && scan.filter().is_some() { + Box::new(PrunePlanner::new(Arc::clone(scan), rows, Box::new(parts))) + } else { + parts(None) + } +} + +/// Spawns a planner per part of a scan's rows that zone pruning left something of, in row order. +/// Parts are the file's layout splits, so a layout chunk, and the dictionary it carries, is +/// read by one thread, which lets a host evaluate an expression over that dictionary once. +/// +/// With a filter, each part prunes over its own rows before its chunks, on the thread that takes +/// it, like the per-split pruning of a V1 scan, so the pruning of a file's parts runs in parallel. +/// A dynamic filter, such as the bound a top-N pushes down, also prunes the scan as a whole before +/// any part is taken, so a file whose zones it rules out takes no thread. It has tightened by the +/// time a later part is taken, so pruning that part again skips more, from the zone maps the +/// scan-wide pruning read. +struct PartPlanner { + scan: Arc, + selection: Selection, + parts: std::vec::IntoIter>, + /// The first row of `kept`. + first_row: u64, + /// The rows scan-wide pruning kept, from `first_row`, or `None` when nothing was pruned. + kept: Option, +} + +impl PartPlanner { + fn new( + scan: Arc, + parts: Vec>, + first_row: u64, + kept: Option, + ) -> Self { + Self { + selection: scan.selection().clone(), + scan, + parts: parts.into_iter(), + first_row, + kept, + } + } + + /// The rows of `part` that scan-wide pruning kept, or `None` when nothing was pruned. + fn kept_in(&self, part: &Range) -> Option { + let kept = self.kept.as_ref()?; + let offset = + |row: u64| usize::try_from(row - self.first_row).vortex_expect("a part fits usize"); + Some(kept.slice(offset(part.start)..offset(part.end))) + } +} + +impl IoConsumer for PartPlanner { + fn set_io_result(&mut self, _request: IoRequestId, _result: IoResult) {} +} + +impl Planner for PartPlanner { + fn state(&self) -> State { + if self.parts.as_slice().is_empty() { + State::Done + } else { + State::NeedsCompute + } + } + + fn compute(&mut self) -> VortexResult { + while let Some(part) = self.parts.next() { + let kept = self.kept_in(&part); + if kept.as_ref().is_some_and(Mask::all_false) { + continue; + } + let chunks = { + let scan = Arc::clone(&self.scan); + let selection = self.selection.clone(); + let part = part.clone(); + move |again: Option| -> Box { + let kept = match (kept, again) { + (Some(kept), Some(again)) => Some(kept & &again), + (kept, again) => kept.or(again), + }; + Box::new(ChunkPlanner::new(scan, part, selection, kept)) + } + }; + let planner: Box = if self.scan.filter().is_some() { + Box::new(PrunePlanner::new( + Arc::clone(&self.scan), + part.clone(), + Box::new(chunks), + )) + } else { + chunks(None) + }; + let scope = WorkScope { + file_ordinal: 0, + rows: part, + }; + return Ok(PlannerOutput::Spawn(scope, planner)); + } + Ok(PlannerOutput::Done) + } +} + +/// The ranges between adjacent `splits`, clipped to `rows`, leaving out empty ones. +fn part_ranges(rows: Range, splits: &[u64]) -> Vec> { + splits + .windows(2) + .map(|w| w[0].max(rows.start)..w[1].min(rows.end)) + .filter(|part| part.start < part.end) + .collect() +} + +#[cfg(test)] +mod tests { + use std::ops::Range; + + use rstest::rstest; + + use super::part_ranges; + + #[rstest] + #[case::whole(0..30, &[0, 10, 20, 30], vec![0..10, 10..20, 20..30])] + #[case::clipped(5..25, &[0, 10, 20, 30], vec![5..10, 10..20, 20..25])] + #[case::inside_one_split(12..18, &[0, 10, 20, 30], vec![12..18])] + #[case::empty(5..5, &[0, 10], vec![])] + fn parts_follow_splits( + #[case] rows: Range, + #[case] splits: &[u64], + #[case] expected: Vec>, + ) { + assert_eq!(part_ranges(rows, splits), expected); + } +} diff --git a/vortex-scan/src/lib.rs b/vortex-scan/src/lib.rs index ee17f591a64..ffe9af7b216 100644 --- a/vortex-scan/src/lib.rs +++ b/vortex-scan/src/lib.rs @@ -24,12 +24,14 @@ pub mod arrays; pub mod execution; +pub mod limit; pub mod plan; pub mod planning; pub mod prepare; pub mod row_mask; pub mod selection; pub mod source; +pub mod stream; pub mod strict_sorted_buffer; use std::any::Any; @@ -42,6 +44,7 @@ use futures::StreamExt; use futures::TryStreamExt; use futures::stream::BoxStream; use selection::Selection; +use stream::ScanExec; use vortex_array::aggregate_fn::AggregateFnRef; use vortex_array::dtype::DType; use vortex_array::dtype::FieldPath; @@ -180,12 +183,16 @@ pub struct ScanRequest { /// order is completion order, so each partition applies the limit locally and the caller must /// trim the concatenated result. pub limit: Option, - /// The most splits of each partition to decode at once, in all. + /// The most splits decoded at once for each partition being read, or for each stream of an + /// opened scan that reads a single queue of splits. /// - /// `None` keeps the reader's default, which scales with the machine's cores. Each split being - /// decoded holds the decoded chunks of every column it overlaps, so a scan that runs alongside - /// others, such as one task of several on a machine, can set this to bound its memory. It does - /// not bound I/O: segment reads for later splits may still be coalesced ahead of them. + /// It does not bound the whole scan: a scan read by several workers decodes up to this many + /// splits for each partition each worker is reading, and a worker may read more than one + /// partition at once. `None` keeps the source's default. Each + /// split being decoded holds the decoded chunks of every column it overlaps, so a scan that + /// runs alongside others, such as one task of several on a machine, can set this to bound its + /// memory. It does not bound I/O: segment reads for later splits may still be coalesced ahead + /// of them. pub split_concurrency: Option, } @@ -208,7 +215,24 @@ impl Default for ScanRequest { /// A boxed data source scan. pub type DataSourceScanRef = Box; -/// A data source scan produces partitions that can be executed to read data from the source. +/// A data source scan reads data from the source. +/// +/// Each host reads every scan the same way, whatever the source: its execution model is fixed. +/// A host that needs a fixed number of partitions, such as DataFusion with its output partition +/// count, [splits](Self::split) the scan into fixed pieces that each own their rows. A host that +/// runs its own threads, such as DuckDB, or that wants its partitions to share work, never +/// splits: it [opens](Self::open) the scan once and has each of its threads or partitions read a +/// [stream](ScanExec::stream) of the returned [`ScanExec`]. The host states the properties it needs, such as row +/// order or a limit, on the [`ScanRequest`], and the source decides what the pieces are and how +/// they run. +/// +/// A source does the reads it needs to know a scan's units of work, such as pruning against zone +/// maps before cutting the scan into pieces, in the async [`DataSource::scan`], which the host +/// awaits. [`split`](Self::split) and [`open`](Self::open) are synchronous and read nothing, so +/// no stream of an opened scan waits on another for its first work. +/// +/// A scan never starts threads. Its work may run as tasks on the session's runtime, which the +/// host owns. pub trait DataSourceScan: 'static + Send { /// The returned dtype of the scan. fn dtype(&self) -> &DType; @@ -218,6 +242,24 @@ pub trait DataSourceScan: 'static + Send { /// Returns a stream of partitions to be processed. fn partitions(self: Box) -> PartitionStream; + + /// Partitions the scan into at most `n` fixed pieces. + /// + /// Each piece owns its rows: the pieces together return every row of the scan exactly once, + /// and no two return the same row. When the request is ordered, the pieces are contiguous, + /// and reading them one after another returns the rows in scan order. + /// + /// Splitting reads metadata only. The result is never empty, and a scan with no cut points + /// returns itself as the one piece. A host that wants its threads to share the scan's work + /// instead [opens](Self::open) the scan and reads a stream of it on each thread. + fn split(self: Box, n: NonZeroUsize) -> VortexResult>; + + /// Opens the scan into a [`ScanExec`], whose work host threads share by each reading a + /// [stream](ScanExec::stream) of it. + /// + /// A source that has no queue of work of its own may return + /// [`ScanExec::from_partitions`] over itself. + fn open(self: Box) -> VortexResult; } impl dyn DataSourceScan { diff --git a/vortex-scan/src/limit.rs b/vortex-scan/src/limit.rs new file mode 100644 index 00000000000..845a7525d89 --- /dev/null +++ b/vortex-scan/src/limit.rs @@ -0,0 +1,173 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Row limits that the work of one scan shares. + +use std::sync::Arc; +use std::sync::atomic::AtomicU64; +use std::sync::atomic::Ordering; +use std::task::Poll; + +use futures::StreamExt; +use futures::ready; +use futures::stream; +use futures::stream::BoxStream; +use vortex_array::ArrayRef; +use vortex_error::VortexExpect; +use vortex_error::VortexResult; +use vortex_mask::Mask; + +/// A cloneable row budget shared by all work that can contribute rows to one scan. +/// +/// Filterless scans reserve each split's selected rows before constructing its projection, so +/// rows past the limit are never decoded. Filtered scans cannot know a split's row count up front, +/// so they take rows from the budget as arrays are emitted and discard the excess. Either way, +/// the order in which rows are taken decides which rows are returned: an ordered scan takes them +/// in split order, an unordered one in completion order. +#[derive(Clone)] +pub struct RowLimit(Arc); + +impl RowLimit { + /// A budget of `limit` rows. + pub fn new(limit: u64) -> Self { + Self(Arc::new(AtomicU64::new(limit))) + } + + /// Reserve rows selected by `mask` and retain only the earliest granted rows in that mask. + pub fn limit(&self, mask: Mask) -> Mask { + let granted = self.take(mask.true_count()); + mask.limit(granted) + } + + /// Reserve up to `rows` rows, returning how many the remaining budget granted. + pub fn take(&self, rows: usize) -> usize { + let requested = u64::try_from(rows).unwrap_or(u64::MAX); + usize::try_from(self.reserve(requested)).unwrap_or(usize::MAX) + } + + /// Whether the budget is spent. + pub fn is_exhausted(&self) -> bool { + self.0.load(Ordering::Relaxed) == 0 + } + + fn reserve(&self, requested: u64) -> u64 { + let remaining = self + .0 + .try_update(Ordering::Relaxed, Ordering::Relaxed, |remaining| { + Some(remaining.saturating_sub(requested)) + }) + .ok() + .vortex_expect("row reservation always updates the budget"); + remaining.min(requested) + } +} + +/// Trim arrays to the budget and drop upstream work as soon as it is exhausted. +pub fn limit_rows( + arrays: BoxStream<'static, VortexResult>, + limit: RowLimit, +) -> BoxStream<'static, VortexResult> { + let mut arrays = Some(arrays); + stream::poll_fn(move |cx| { + loop { + if limit.is_exhausted() { + arrays = None; + } + let Some(stream) = arrays.as_mut() else { + return Poll::Ready(None); + }; + let array = match ready!(stream.poll_next_unpin(cx)) { + Some(Ok(array)) => array, + end => { + arrays = None; + return Poll::Ready(end); + } + }; + let granted = limit.take(array.len()); + if limit.is_exhausted() { + arrays = None; + } + if granted != 0 { + return Poll::Ready(Some(if granted < array.len() { + array.slice(0..granted) + } else { + Ok(array) + })); + } + } + }) + .boxed() +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + use std::sync::Barrier; + use std::sync::atomic::AtomicU64; + use std::sync::atomic::Ordering; + use std::thread; + + use vortex_mask::Mask; + + use super::RowLimit; + + #[test] + fn reserve_grants_up_to_the_remaining_budget() { + let limit = RowLimit::new(5); + assert_eq!(limit.reserve(3), 3); + assert!(!limit.is_exhausted()); + // Only two rows remain, so a larger request saturates at what is left. + assert_eq!(limit.reserve(10), 2); + assert!(limit.is_exhausted()); + // Once exhausted, further requests grant nothing. + assert_eq!(limit.reserve(1), 0); + } + + #[test] + fn limit_keeps_the_earliest_granted_rows() { + let limit = RowLimit::new(2); + // Rows 0, 2, 3, 5 are selected; only the first two survive the budget of 2. + let mask = Mask::from_iter([true, false, true, true, false, true]); + let limited = limit.limit(mask); + + assert_eq!(limited.true_count(), 2); + assert!(limited.value(0)); + assert!(limited.value(2)); + assert!(!limited.value(3)); + assert!(!limited.value(5)); + assert!(limit.is_exhausted()); + } + + #[test] + fn concurrent_reservations_never_exceed_the_budget() { + const THREADS: usize = 8; + const PER_THREAD: u64 = 10_000; + const LIMIT: u64 = 25_000; + + let limit = RowLimit::new(LIMIT); + let granted_total = Arc::new(AtomicU64::new(0)); + let barrier = Arc::new(Barrier::new(THREADS)); + + thread::scope(|scope| { + for _ in 0..THREADS { + let limit = limit.clone(); + let granted_total = Arc::clone(&granted_total); + let barrier = Arc::clone(&barrier); + scope.spawn(move || { + // Start all threads together to maximize contention on the atomic. + barrier.wait(); + let mut local = 0; + for _ in 0..PER_THREAD { + local += limit.reserve(1); + } + granted_total.fetch_add(local, Ordering::Relaxed); + }); + } + }); + + // Total requested (THREADS * PER_THREAD = 80_000) exceeds the budget, so exactly the + // budget is granted across all threads — no double-grant, over-grant, or lost reservation. + assert_eq!(granted_total.load(Ordering::Relaxed), LIMIT); + assert!(limit.is_exhausted()); + } +} diff --git a/vortex-scan/src/prepare.rs b/vortex-scan/src/prepare.rs index 8ee70868d71..24ac1dad6ee 100644 --- a/vortex-scan/src/prepare.rs +++ b/vortex-scan/src/prepare.rs @@ -24,6 +24,7 @@ pub use crate::execution::SegmentLocation; pub use crate::execution::cache::ScanCache; pub use crate::execution::cache::WeakScanCache; use crate::execution::io::segment_ranges; +pub use crate::execution::part_root; use crate::execution::rows_per_chunk; use crate::plan::optimize; use crate::plan::plan_row_idx_expression; diff --git a/vortex-scan/src/source.rs b/vortex-scan/src/source.rs index 08a3f38c296..34a6f819b1a 100644 --- a/vortex-scan/src/source.rs +++ b/vortex-scan/src/source.rs @@ -1,7 +1,8 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors -//! Source inputs and byte access for scans. +//! Source inputs and byte access for scans, and the [`DataSource`](crate::DataSource) that scans +//! them. use std::sync::Arc; @@ -32,3 +33,14 @@ pub struct ScanInput { /// State shared by repeated scans of this input. pub cache: Option, } + +mod plan; +mod plan_stream; + +pub use plan::FilePruner; +pub use plan::PlanChild; +pub use plan::PlanDataSource; +pub use plan::PlanSplitter; + +#[cfg(test)] +mod tests; diff --git a/vortex-scan/src/source/plan.rs b/vortex-scan/src/source/plan.rs new file mode 100644 index 00000000000..aaefdce7c9a --- /dev/null +++ b/vortex-scan/src/source/plan.rs @@ -0,0 +1,417 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! [`PlanDataSource`]: a [`DataSource`] over plan children, scanned by the planner-driven +//! executor. +//! +//! Nothing here is about one format. A child is a [`ScanInput`], a plan over placed segments, +//! from a Vortex file, a Parquet file whose column chunks are segments, or any store that lowers +//! its data to plans. + +use std::any::Any; +use std::num::NonZeroUsize; +use std::ops::Range; +use std::sync::Arc; + +use async_trait::async_trait; +use futures::StreamExt; +use futures::stream; +use vortex_array::dtype::DType; +use vortex_array::dtype::FieldPath; +use vortex_array::expr::BoundExpression; +use vortex_array::expr::stats::Precision; +use vortex_array::stats::StatsSet; +use vortex_array::stream::SendableArrayStream; +use vortex_error::VortexResult; +use vortex_session::VortexSession; + +use super::ScanInput; +use super::plan_stream; +use crate::DataSource; +use crate::DataSourceScan; +use crate::DataSourceScanRef; +use crate::Partition; +use crate::PartitionRef; +use crate::PartitionStream; +use crate::ScanRequest; +use crate::prepare::ScanBuilder; +use crate::selection::Selection; +use crate::stream::ScanExec; + +/// Whether a child's own statistics, such as a file footer's, prove a filter, bound to the +/// child's dtype, false for every row of the child. +pub type FilePruner = Arc VortexResult + Send + Sync>; + +/// The row boundaries an opened scan cuts a child's work at, for the scan's projection and filter, +/// both bound to the child's dtype: ascending, covering the child's rows. A Vortex file gives its +/// layout splits over the fields the scan reads, as a V1 scan of the same fields cuts it. +pub type PlanSplitter = + Arc) -> VortexResult> + Send + Sync>; + +/// A child of a [`PlanDataSource`]: its [`ScanInput`] and what the source knows of it without +/// reading payloads. +#[derive(Clone)] +pub struct PlanChild { + input: ScanInput, + row_count: Option, + splitter: Option, + pruner: Option, +} + +impl PlanChild { + /// A child scanning `input`. Without a cache, the input gets a fresh one that every scan of + /// the child shares. + pub fn new(mut input: ScanInput) -> Self { + input.cache.get_or_insert_default(); + Self { + input, + row_count: None, + splitter: None, + pruner: None, + } + } + + /// Sets the child's exact row count. Without it, the source lowers the child's root plan to + /// learn the count when a scan needs it. + pub fn with_row_count(mut self, row_count: u64) -> Self { + self.row_count = Some(row_count); + self + } + + /// Sets fixed row boundaries that an opened scan cuts the child's work at, whatever it reads, + /// ascending and covering the child's rows. Without boundaries, the work is cut on the scan's + /// chunk grid. + pub fn with_splits(self, splits: Arc<[u64]>) -> Self { + self.with_splitter(Arc::new(move |_, _| Ok(splits.to_vec()))) + } + + /// Sets how an opened scan finds the row boundaries to cut the child's work at, from the + /// fields it reads. Without boundaries, the work is cut on the scan's chunk grid. + pub fn with_splitter(mut self, splitter: PlanSplitter) -> Self { + self.splitter = Some(splitter); + self + } + + /// Sets how the child's statistics rule out a scan's filter, so a scan they rule out reads + /// nothing of the child. + pub fn with_pruner(mut self, pruner: FilePruner) -> Self { + self.pruner = Some(pruner); + self + } + + /// The input this child scans. + pub fn input(&self) -> &ScanInput { + &self.input + } + + /// The child's rows, from the row count when set, else from its root plan. + fn rows(&self) -> VortexResult { + match self.row_count { + Some(rows) => Ok(rows), + None => Ok(self.input.root.get()?.row_count()), + } + } + + /// The bytes of all of the child's segments. + fn byte_size(&self) -> u64 { + self.input + .locations + .iter() + .map(|location| u64::from(location.length)) + .sum() + } + + /// The boundaries an opened scan of `projection` and `filter` cuts the child's work at, if the + /// child has them. + pub(super) fn splits( + &self, + projection: &BoundExpression, + filter: Option<&BoundExpression>, + ) -> VortexResult>> { + self.splitter + .as_ref() + .map(|splitter| splitter(projection, filter)) + .transpose() + } + + fn is_pruned(&self, filter: Option<&BoundExpression>) -> VortexResult { + match (&self.pruner, filter) { + (Some(pruner), Some(filter)) => pruner(filter), + _ => Ok(false), + } + } +} + +/// A [`DataSource`] over plan children, scanned by the planner-driven executor. +/// +/// This is the standard way to expose sources that can lower their data to plans over placed +/// segments, whatever their format. Every scan of a child shares the child's [`ScanCache`], so +/// scans that overlap in time plan it once. +/// +/// A scan's request applies to each child: its row range and row selection are in the child's +/// own rows, and its `partition_range` and `partition_selection` select children by ordinal. A +/// scan reads its children in order. +/// +/// Making an unordered scan does the reads it needs to know its units of work: it prepares each +/// child and cuts it into parts, which for a dynamic filter reads zone maps. +/// [`split`](DataSourceScan::split) and [`open`](DataSourceScan::open) read nothing. +/// [`split`](DataSourceScan::split) returns a scan whole. [`open`](DataSourceScan::open) runs it +/// on V2's planners and [`Run`](crate::planning::driver::Run) driver; see `plan_stream.rs`. A +/// scan's one partition reads its opened stream. +/// +/// [`ScanCache`]: crate::prepare::ScanCache +#[derive(Clone)] +pub struct PlanDataSource { + session: VortexSession, + dtype: DType, + children: Arc<[PlanChild]>, + row_count: Precision, + byte_size: Precision, +} + +impl PlanDataSource { + /// A source scanning one `input` with `session`. + pub fn new(session: VortexSession, input: ScanInput) -> Self { + Self::from_child(session, PlanChild::new(input)) + } + + /// A source scanning one `child` with `session`. + pub fn from_child(session: VortexSession, child: PlanChild) -> Self { + let dtype = child.input.dtype.clone(); + Self::from_children(session, dtype, vec![child]) + } + + /// A source scanning `children` in order with `session`. Every child must have `dtype`. + pub fn from_children(session: VortexSession, dtype: DType, children: Vec) -> Self { + let row_count = children + .iter() + .map(|child| child.row_count) + .sum::>() + .map_or(Precision::Absent, Precision::exact); + let byte_size = Precision::inexact(children.iter().map(PlanChild::byte_size).sum::()); + Self { + session, + dtype, + children: children.into(), + row_count, + byte_size, + } + } + + /// Sets the exact row count of a one-child source, which scans report. + pub fn with_row_count(mut self, row_count: u64) -> Self { + if let [child] = &*self.children { + self.children = Arc::new([child.clone().with_row_count(row_count)]); + } + self.row_count = Precision::exact(row_count); + self + } + + /// Sets an estimate of the source's byte size. + pub fn with_byte_size(mut self, byte_size: Precision) -> Self { + self.byte_size = byte_size; + self + } + + /// The children this source scans, in order. + pub fn children(&self) -> &[PlanChild] { + &self.children + } + + /// The session scans of this source run with. + pub fn session(&self) -> &VortexSession { + &self.session + } +} + +#[async_trait] +impl DataSource for PlanDataSource { + fn dtype(&self) -> &DType { + &self.dtype + } + + fn row_count(&self) -> Precision { + self.row_count + } + + fn byte_size(&self) -> Precision { + self.byte_size + } + + async fn scan(&self, request: ScanRequest) -> VortexResult { + let projection = request.projection.bind(&self.dtype)?.optimize_recursive()?; + let filter = request + .filter + .map(|filter| filter.bind(&self.dtype)?.optimize_recursive()) + .transpose()?; + let mut units = Vec::new(); + let scans_rows = + request.limit != Some(0) && !request.row_range.as_ref().is_some_and(Range::is_empty); + for (ordinal, child) in self.children.iter().enumerate().filter(|_| scans_rows) { + let index = ordinal as u64; + let selected = request + .partition_range + .as_ref() + .is_none_or(|range| range.contains(&index)) + && request + .partition_selection + .row_count_in_range(&(index..index + 1)) + == 1; + if !selected || child.is_pruned(filter.as_ref())? { + continue; + } + let rows = child + .row_count + .map(|count| clamp_rows(request.row_range.clone(), count)); + if rows.as_ref().is_some_and(Range::is_empty) { + continue; + } + units.push(Unit { + child: ordinal, + rows, + }); + } + let state = ScanState { + session: self.session.clone(), + children: Arc::clone(&self.children), + dtype: projection.dtype().clone(), + projection, + filter, + row_range: request.row_range, + selection: request.selection, + ordered: request.ordered, + limit: request.limit, + }; + // An unordered scan's parts are its units of work, and cutting them can read zone maps, + // so it happens here, where the host awaits the scan, and opening reads nothing. + let planned = if state.ordered { + None + } else { + Some(plan_stream::plan(&state, &units).await?) + }; + Ok(Box::new(PlanScan { + state: Arc::new(state), + units, + planned, + })) + } + + async fn field_statistics(&self, _field_path: &FieldPath) -> VortexResult { + Ok(StatsSet::default()) + } +} + +/// The request's `rows`, or all of them, clamped to a child of `count` rows. +fn clamp_rows(rows: Option>, count: u64) -> Range { + let rows = rows.unwrap_or(0..count); + let end = rows.end.min(count); + rows.start.min(end)..end +} + +/// What every piece and stream of one scan of a [`PlanDataSource`] shares. +pub(super) struct ScanState { + pub(super) session: VortexSession, + children: Arc<[PlanChild]>, + /// The dtype of the scan's output. + pub(super) dtype: DType, + pub(super) projection: BoundExpression, + pub(super) filter: Option, + row_range: Option>, + selection: Selection, + pub(super) ordered: bool, + pub(super) limit: Option, +} + +impl ScanState { + /// The source's child at `ordinal`. + pub(super) fn child(&self, ordinal: usize) -> &PlanChild { + &self.children[ordinal] + } + + /// The rows of `unit` this scan reads: its own, or else the request's row range clamped to + /// its child. + pub(super) fn unit_rows(&self, unit: &Unit) -> VortexResult> { + match &unit.rows { + Some(rows) => Ok(rows.clone()), + None => Ok(clamp_rows( + self.row_range.clone(), + self.child(unit.child).rows()?, + )), + } + } + + /// A builder of this scan's `rows` of `child`. + pub(super) fn builder(&self, child: &PlanChild, rows: Range) -> ScanBuilder { + ScanBuilder::new(self.session.clone(), child.input.clone()) + .with_projection(self.projection.clone()) + .with_some_filter(self.filter.clone()) + .with_selection(self.selection.clone()) + .with_row_range(rows) + } +} + +/// Rows of one child that a scan reads. +#[derive(Clone, Debug)] +pub(super) struct Unit { + /// The child's ordinal in the source. + pub(super) child: usize, + /// The child's rows, or `None` for the request's rows of a child whose row count is not known + /// until its plan is lowered. + pub(super) rows: Option>, +} + +/// A scan of a [`PlanDataSource`], or a piece split from one. +struct PlanScan { + state: Arc, + /// The scan's units, in child and row order. + units: Vec, + /// The parts of an unordered scan, cut when the scan was made. + planned: Option, +} + +impl DataSourceScan for PlanScan { + fn dtype(&self) -> &DType { + &self.state.dtype + } + + fn split(self: Box, _n: NonZeroUsize) -> VortexResult> { + Ok(vec![self]) + } + + fn open(self: Box) -> VortexResult { + plan_stream::open(self.state, self.units, self.planned) + } + + fn partition_count(&self) -> Precision { + Precision::exact(1usize) + } + + fn partitions(self: Box) -> PartitionStream { + stream::iter([Ok(Box::new(PlanPartition(self)) as PartitionRef)]).boxed() + } +} + +/// A scan of a [`PlanDataSource`] as its one partition, which reads one stream of the opened scan. +struct PlanPartition(Box); + +impl Partition for PlanPartition { + fn as_any(&self) -> &dyn Any { + self + } + + fn index(&self) -> usize { + 0 + } + + fn row_count(&self) -> Precision { + Precision::Absent + } + + fn byte_size(&self) -> Precision { + Precision::Absent + } + + fn execute(self: Box) -> VortexResult { + Ok(Box::pin(self.0.open()?.stream())) + } +} diff --git a/vortex-scan/src/source/plan_stream.rs b/vortex-scan/src/source/plan_stream.rs new file mode 100644 index 00000000000..549294bb694 --- /dev/null +++ b/vortex-scan/src/source/plan_stream.rs @@ -0,0 +1,327 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! An opened [`PlanDataSource`](super::PlanDataSource) scan: V2's planners and [`Run`] driver +//! behind [`ScanExec`] and its [`ScanStream`](crate::stream::ScanStream)s. +//! +//! When an unordered scan is made, it prepares each child once and runs its [`part_root`], which +//! cuts the child into parts: the rows between the child's splits for the fields the scan reads, +//! such as a file's layout splits, or the scan's chunks for a child without splits. With a dynamic +//! filter, such as the bound a top-N pushes down, the root first prunes the child as a whole +//! against the bound as it stands, which reads zone maps. Those are the reads the scan needs to +//! know its units of work, so they run in the async [`scan`](crate::DataSource::scan), which the +//! host awaits. Opening the scan reads nothing: it only queues the parts, so no stream waits on +//! another for its work. Each part prunes again against the bound as it stands when a stream +//! takes it. +//! +//! Every stream of the scan takes parts from the one queue, and the scan is exhausted once the +//! last part is taken. Each stream owns a [`Run`], driven on the task that polls the stream, and +//! runs one part on it at a time: the part's chunks run side by side, so one chunk's reads overlap +//! another's compute, batches are returned as they are produced, and reads are awaited with +//! [`Run::poll_completion`]. Nothing is spawned, so a host that polls a stream with `block_on` +//! runs the scan's compute on its own thread. +//! +//! An ordered scan returns its rows in order through its first stream, running one child after +//! another on [`ScanDriver`], which keeps a scan's chunks in order. The scan is exhausted once +//! that stream exists, and later streams return nothing. A host that reads an ordered scan in +//! parallel [splits](crate::DataSourceScan::split) it first. +//! +//! A limit is one [`RowLimit`] for the whole scan: streams stop taking parts once it is spent, +//! which also exhausts the scan, and each stream's output is trimmed to it. + +use std::collections::VecDeque; +use std::future; +use std::iter; +use std::ops::Range; +use std::sync::Arc; +use std::sync::atomic::AtomicUsize; +use std::sync::atomic::Ordering; + +use futures::StreamExt; +use futures::stream; +use futures::stream::BoxStream; +use parking_lot::Mutex; +use vortex_array::ArrayRef; +use vortex_error::VortexExpect; +use vortex_error::VortexResult; +use vortex_functions::dynamic::DynamicExprUpdates; +use vortex_io::request::IoService; +use vortex_io::session::RuntimeSessionExt; + +use super::plan::ScanState; +use super::plan::Unit; +use crate::execution::driver::ScanDriver; +use crate::execution::scan_chunks; +use crate::limit::RowLimit; +use crate::limit::limit_rows; +use crate::planning::driver::Progress; +use crate::planning::driver::Run; +use crate::planning::planner::Planner; +use crate::planning::planner::WorkScope; +use crate::prepare::PreparedScan; +use crate::prepare::part_root; +use crate::stream::Claims; +use crate::stream::ExhaustedFlag; +use crate::stream::ScanExec; + +/// The parts of an unordered scan, cut when the scan is made. +pub(super) struct Planned { + work: Vec, +} + +/// Prepares each of the scan's `units` once and runs its root, awaiting the zone maps a dynamic +/// filter's root reads, and returns the work the roots produce, in unit and row order. +pub(super) async fn plan(state: &ScanState, units: &[Unit]) -> VortexResult { + let mut work = Vec::new(); + for unit in units { + let rows = state.unit_rows(unit)?; + if rows.is_empty() { + continue; + } + let (child, root) = prepare(state, unit, rows)?; + work.extend(run_root(child, root).await?); + } + Ok(Planned { work }) +} + +/// Opens a scan of `units`. An unordered scan reads the parts it `planned`. +pub(super) fn open( + state: Arc, + units: Vec, + planned: Option, +) -> VortexResult { + let dtype = state.dtype.clone(); + let limit = state.limit.map(RowLimit::new); + let exhausted = ExhaustedFlag::new(); + if state.ordered { + let arrays = Arc::new(Mutex::new(Some(in_order(state, units)))); + let flag = exhausted.clone(); + return Ok(ScanExec::new(dtype, exhausted, move || { + // The first stream returns every row, so later ones would find nothing. + flag.set(); + let arrays = arrays + .lock() + .take() + .unwrap_or_else(|| stream::empty().boxed()); + limited(arrays, limit.clone()) + })); + } + + let planned = planned.vortex_expect("an unordered scan cuts its parts when it is made"); + if planned.work.is_empty() { + exhausted.set(); + } + let queue = Arc::new(Queue { + total: planned.work.len(), + work: Mutex::new(planned.work.into()), + taken: AtomicUsize::new(0), + exhausted: exhausted.clone(), + }); + let progress = Arc::clone(&queue); + Ok(ScanExec::new(dtype, exhausted, move || { + let worker = Worker { + queue: Arc::clone(&queue), + limit: limit.clone(), + run: Run::new(), + child: None, + }; + let arrays = stream::unfold(Some(worker), |worker| async move { + let mut worker = worker?; + match worker.next_array().await { + Ok(Some(array)) => Some((Ok(array), Some(worker))), + Ok(None) => None, + Err(err) => Some((Err(err), None)), + } + }) + .boxed(); + limited(arrays, limit.clone()) + }) + .with_progress(move || progress.claims())) +} + +/// One child's prepared scan, shared by the parts of it that streams run. +struct PreparedChild { + rows: Range, + io: Arc, +} + +/// A part of a child: the planner its root spawned for some of its rows. +struct Part { + child: Arc, + scope: WorkScope, + planner: Box, +} + +/// Prepares the scan of `rows` of the unit's child once and composes its root. +fn prepare( + state: &ScanState, + unit: &Unit, + rows: Range, +) -> VortexResult<(Arc, Box)> { + let child = state.child(unit.child); + let splits = child.splits(&state.projection, state.filter.as_ref())?; + let scan = Arc::new(state.builder(child, rows).prepare()?); + let splits = splits.unwrap_or_else(|| chunk_bounds(&scan)); + let dynamic = state + .filter + .as_ref() + .is_some_and(|filter| DynamicExprUpdates::new(filter).is_some()); + let root = part_root(&scan, &splits, dynamic); + let prepared = PreparedChild { + rows: scan.rows().clone(), + io: scan.io(), + }; + Ok((Arc::new(prepared), root)) +} + +/// The boundaries of `scan`'s chunks, which cut the work of a child without splits of its own. +fn chunk_bounds(scan: &PreparedScan) -> Vec { + let rows = scan.rows().clone(); + let chunks = scan_chunks(rows.clone(), scan.chunk_rows); + iter::once(rows.start) + .chain(chunks.iter().map(|chunk| chunk.end)) + .collect() +} + +/// Runs a child's root on a run of its own, awaiting only its reads, and returns the work it +/// produces, in row order: the parts it spawns, and any batch it returns itself. +async fn run_root(child: Arc, root: Box) -> VortexResult> { + let mut run = Run::new(); + let scope = WorkScope { + file_ordinal: 0, + rows: child.rows.clone(), + }; + run.admit(root, scope, child.io.session()); + let mut work = Vec::new(); + loop { + match run.advance()? { + Progress::Spawn(scope, planner) => work.push(Work::Part(Part { + child: Arc::clone(&child), + scope, + planner, + })), + Progress::Batch(batch) => work.push(Work::Batch(batch.array)), + Progress::RootDone(_) if run.live_roots() > 0 => {} + Progress::RootDone(_) | Progress::Idle => break, + Progress::Waiting => future::poll_fn(|cx| run.poll_completion(cx)).await?, + } + } + Ok(work) +} + +/// A unit of work in the queue of an unordered scan. +enum Work { + Part(Part), + /// A batch a root returned itself. + Batch(ArrayRef), +} + +/// The queue of an unordered scan, which every stream of it takes from. +struct Queue { + /// The work no stream has taken yet, in unit and row order. + work: Mutex>, + /// The work the queue started with. + total: usize, + /// The work streams have taken. + taken: AtomicUsize, + /// Set once the last work is taken, or the scan's limit is spent. + exhausted: ExhaustedFlag, +} + +impl Queue { + /// Takes the next work, or `None` once every one has been taken, and marks the scan exhausted + /// when it takes the last. + fn take(&self) -> Option { + let mut work = self.work.lock(); + let next = work.pop_front()?; + if work.is_empty() { + self.exhausted.set(); + } + drop(work); + self.taken.fetch_add(1, Ordering::Relaxed); + Some(next) + } + + /// How much of the queue's work streams have taken, out of how much in all. + fn claims(&self) -> Claims { + Claims { + claimed: self.taken.load(Ordering::Relaxed).min(self.total), + total: self.total, + } + } +} + +/// One stream's worker: a run of its own, fed one part at a time from the scan's queue, and driven +/// on the task that polls the stream. +struct Worker { + queue: Arc, + limit: Option, + run: Run, + /// The child of the part live on the run, whose I/O the planners that part spawns read through. + child: Option>, +} + +impl Worker { + /// The worker's next array, or `None` once the scan has no more work for it. + async fn next_array(&mut self) -> VortexResult> { + loop { + if self.run.live_roots() == 0 { + if self.limit.as_ref().is_some_and(RowLimit::is_exhausted) { + self.queue.exhausted.set(); + return Ok(None); + } + match self.queue.take() { + None => return Ok(None), + Some(Work::Batch(array)) => return Ok(Some(array)), + Some(Work::Part(part)) => { + self.run + .admit(part.planner, part.scope, part.child.io.session()); + self.child = Some(part.child); + } + } + } + match self.run.advance()? { + Progress::Batch(batch) => return Ok(Some(batch.array)), + Progress::Spawn(scope, planner) => { + let child = self + .child + .as_ref() + .vortex_expect("a planner is spawned by a live part"); + self.run.admit(planner, scope, child.io.session()); + } + Progress::RootDone(_) | Progress::Idle => {} + Progress::Waiting => { + future::poll_fn(|cx| self.run.poll_completion(cx)).await?; + } + } + } + } +} + +/// The arrays of an ordered scan: each unit's rows in order, one unit after another. +fn in_order(state: Arc, units: Vec) -> BoxStream<'static, VortexResult> { + stream::iter(units) + .flat_map(move |unit| { + let rows = match state.unit_rows(&unit) { + Ok(rows) => rows, + Err(err) => return stream::once(future::ready(Err(err))).boxed(), + }; + if rows.is_empty() { + return stream::empty().boxed(); + } + ScanDriver::new(state.session.handle(), 1, true) + .run(state.builder(state.child(unit.child), rows)) + }) + .boxed() +} + +/// `arrays`, trimmed to the scan's limit. +fn limited( + arrays: BoxStream<'static, VortexResult>, + limit: Option, +) -> BoxStream<'static, VortexResult> { + match limit { + Some(limit) => limit_rows(arrays, limit), + None => arrays, + } +} diff --git a/vortex-scan/src/source/tests.rs b/vortex-scan/src/source/tests.rs new file mode 100644 index 00000000000..3319640e543 --- /dev/null +++ b/vortex-scan/src/source/tests.rs @@ -0,0 +1,210 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +use std::ops::Range; +use std::sync::Arc; + +use futures::TryStreamExt; +use futures::future::try_join_all; +use roaring::RoaringTreemap; +use rstest::rstest; +use vortex_array::ArrayRef; +use vortex_array::IntoArray; +use vortex_array::VortexSessionExecute; +use vortex_array::arrays::ChunkedArray; +use vortex_array::arrays::PrimitiveArray; +use vortex_array::assert_arrays_eq; +use vortex_array::expr::checked_add; +use vortex_array::expr::gt; +use vortex_array::expr::lit; +use vortex_array::expr::root; +use vortex_buffer::Buffer; +use vortex_error::VortexResult; +use vortex_error::vortex_bail; +use vortex_io::session::RuntimeSessionExt; +use vortex_session::VortexSession; + +use super::PlanDataSource; +use super::ScanInput; +use super::SegmentFuture; +use super::SegmentId; +use super::SegmentSource; +use crate::DataSource; +use crate::PartitionRef; +use crate::ScanRequest; +use crate::execution::pipeline::synthetic::RowSource; +use crate::plan::LazyPlanRef; +use crate::selection::Selection; + +struct NoSegments; + +impl SegmentSource for NoSegments { + fn request(&self, _id: SegmentId) -> SegmentFuture { + Box::pin(async { vortex_bail!("an in-memory source must not request bytes") }) + } +} + +fn source() -> PlanDataSource { + source_of(20) +} + +fn source_of(row_count: u64) -> PlanDataSource { + let plan = RowSource::plan(row_count, vec![4, 7, 9], None, false); + let input = ScanInput { + dtype: plan.dtype().clone(), + root: LazyPlanRef::ready(plan), + locations: Arc::new([]), + segments: Arc::new(NoSegments), + cache: None, + }; + PlanDataSource::new(VortexSession::empty().with_tokio(), input).with_row_count(row_count) +} + +async fn partitions(request: ScanRequest) -> VortexResult> { + partitions_of(&source(), request).await +} + +async fn partitions_of( + source: &PlanDataSource, + request: ScanRequest, +) -> VortexResult> { + source.scan(request).await?.partitions().try_collect().await +} + +async fn collect(partitions: Vec) -> VortexResult { + let dtype = source().dtype().clone(); + let mut arrays = Vec::new(); + for partition in partitions { + let batches: Vec = partition.execute()?.try_collect().await?; + arrays.extend(batches); + } + Ok(ChunkedArray::try_new(arrays, dtype)?.into_array()) +} + +#[rstest] +#[case::unordered(false)] +#[case::ordered(true)] +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn execute_applies_the_request(#[case] ordered: bool) -> VortexResult<()> { + let partitions = partitions(ScanRequest { + projection: checked_add(root(), lit(100_u64)), + filter: Some(gt(root(), lit(5_u64))), + row_range: Some(2..18), + ordered, + ..Default::default() + }) + .await?; + assert_eq!(partitions.len(), 1); + let mut ctx = VortexSession::empty().create_execution_ctx(); + let actual = collect(partitions) + .await? + .execute::(&mut ctx)?; + let mut values = actual.as_slice::().to_vec(); + if !ordered { + values.sort_unstable(); + } + assert_eq!(values, (106_u64..118).collect::>()); + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn execute_applies_the_limit() -> VortexResult<()> { + let partitions = partitions(ScanRequest { + filter: Some(gt(root(), lit(5_u64))), + ordered: true, + limit: Some(5), + ..Default::default() + }) + .await?; + assert_arrays_eq!( + collect(partitions).await?, + Buffer::from_iter(6_u64..11).into_array(), + &mut VortexSession::empty().create_execution_ctx() + ); + Ok(()) +} + +/// A request that selects no rows of the source scans one partition, which reads nothing. +#[rstest] +#[case::zero_limit(ScanRequest { limit: Some(0), ..Default::default() })] +#[case::empty_rows(ScanRequest { row_range: Some(30..40), ..Default::default() })] +#[case::other_units(ScanRequest { partition_range: Some(1..4), ..Default::default() })] +#[case::unit_excluded(ScanRequest { + partition_selection: Selection::ExcludeRoaring(RoaringTreemap::from_iter([0_u64])), + ..Default::default() +})] +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn requests_without_rows_read_nothing(#[case] request: ScanRequest) -> VortexResult<()> { + let scan = source().scan(request).await?; + let partitions: Vec = scan.partitions().try_collect().await?; + assert_eq!(collect(partitions).await?.len(), 0); + Ok(()) +} + +/// The sorted values of every partition's output. +async fn sorted_values(partitions: Vec) -> VortexResult> { + let mut ctx = VortexSession::empty().create_execution_ctx(); + let mut values = collect(partitions) + .await? + .execute::(&mut ctx)? + .as_slice::() + .to_vec(); + values.sort_unstable(); + Ok(values) +} + +/// Selecting the source's unit, by range or by selection, returns its one partition. +#[rstest] +#[case::range(Some(0..1), Selection::All)] +#[case::wide_range(Some(0..5), Selection::All)] +#[case::selection(None, Selection::IncludeRoaring(RoaringTreemap::from_iter([0_u64, 3])))] +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn selecting_the_unit_returns_its_partition( + #[case] partition_range: Option>, + #[case] partition_selection: Selection, +) -> VortexResult<()> { + let partitions = partitions(ScanRequest { + partition_selection, + partition_range, + ..Default::default() + }) + .await?; + assert_eq!(partitions.len(), 1); + assert_eq!(partitions[0].index(), 0); + assert_eq!( + sorted_values(partitions).await?, + (0..20).collect::>() + ); + Ok(()) +} + +/// The streams of an opened scan share its parts: polled together, they return every row once, +/// and the scan is exhausted once they have taken every part. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn streams_share_the_scan() -> VortexResult<()> { + let exec = source_of(100_000) + .scan(ScanRequest::default()) + .await? + .open()?; + assert!(!exec.is_exhausted()); + let streams = [exec.stream(), exec.stream(), exec.stream()]; + let batches = try_join_all( + streams + .into_iter() + .map(|stream| stream.try_collect::>()), + ) + .await?; + assert!(exec.is_exhausted()); + assert!( + exec.progress() + .is_some_and(|claims| claims.total > 0 && claims.claimed == claims.total) + ); + let mut ctx = VortexSession::empty().create_execution_ctx(); + let mut values = Vec::new(); + for batch in batches.into_iter().flatten() { + values.extend_from_slice(batch.execute::(&mut ctx)?.as_slice::()); + } + values.sort_unstable(); + assert_eq!(values, (0..100_000).collect::>()); + Ok(()) +} diff --git a/vortex-scan/src/stream.rs b/vortex-scan/src/stream.rs new file mode 100644 index 00000000000..2de6ce2cd3e --- /dev/null +++ b/vortex-scan/src/stream.rs @@ -0,0 +1,349 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! An opened scan: the work its host threads share, and the streams that read it. + +use std::fmt; +use std::pin::Pin; +use std::sync::Arc; +use std::sync::atomic::AtomicBool; +use std::sync::atomic::Ordering; +use std::task::Context; +use std::task::Poll; + +use async_lock::Mutex; +use futures::Stream; +use futures::StreamExt; +use futures::stream; +use futures::stream::BoxStream; +use vortex_array::ArrayRef; +use vortex_array::dtype::DType; +use vortex_array::stream::ArrayStream; +use vortex_error::VortexResult; + +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 +/// never written. Clones share the flag: a source keeps one clone where it hands out work and +/// gives another to its [`ScanExec`]. +#[derive(Clone, Debug, Default)] +pub struct ExhaustedFlag(Arc); + +impl ExhaustedFlag { + /// A flag that is not yet set. + pub fn new() -> Self { + Self::default() + } + + /// Marks the scan exhausted. Later calls do nothing. + pub fn set(&self) { + if !self.0.load(Ordering::Relaxed) { + self.0.store(true, Ordering::Release); + } + } + + /// Whether the flag is set. + pub fn is_set(&self) -> bool { + self.0.load(Ordering::Acquire) + } +} + +/// An opened scan: the work that its host threads share. +/// +/// A host that runs its own threads, or whose partitions share the scan's work, opens the scan +/// once and has each thread or partition read a [`stream`](Self::stream) of it. The streams take +/// work until none is left, so together they return every row of the scan exactly once, in no +/// particular order across streams. The number of streams a host reads is its parallelism. +/// Clones of a `ScanExec` share the same work, so a host keeps one per scan wherever its threads +/// can reach it. +/// +/// A host decides whether another thread should join the scan with +/// [`is_exhausted`](Self::is_exhausted), which never blocks and writes nothing, so it is cheap +/// under a host's own lock. It creates the joining thread's stream after releasing that lock. +#[derive(Clone)] +pub struct ScanExec { + dtype: DType, + exhausted: ExhaustedFlag, + new_worker: Arc, + progress: Option>, +} + +impl ScanExec { + /// An opened scan whose streams each read a worker from `new_worker`. + /// + /// The workers that `new_worker` returns must share one queue of work, so that together they + /// return every row exactly once. Creating a worker must be cheap and read nothing: a worker + /// takes its first work when it is first polled. The source sets `exhausted` once a worker + /// created afterwards would find no work. + pub fn new( + dtype: DType, + exhausted: ExhaustedFlag, + new_worker: impl Fn() -> BoxStream<'static, VortexResult> + Send + Sync + 'static, + ) -> Self { + Self { + 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 + /// work up front, so it is exhausted only once a stream finds the partitions have run out. + pub fn from_partitions(scan: DataSourceScanRef) -> Self { + let dtype = scan.dtype().clone(); + let exhausted = ExhaustedFlag::new(); + let partitions = Arc::new(Mutex::new(scan.partitions())); + let flag = exhausted.clone(); + Self::new(dtype, exhausted, move || { + let flag = flag.clone(); + let partitions = stream::unfold(Arc::clone(&partitions), move |shared| { + let flag = flag.clone(); + async move { + let Some(next) = shared.lock().await.next().await else { + flag.set(); + return None; + }; + Some((next, shared)) + } + }); + partitions + .flat_map( + |partition| match partition.and_then(|partition| partition.execute()) { + Ok(arrays) => arrays.left_stream(), + Err(err) => stream::once(async move { Err(err) }).right_stream(), + }, + ) + .boxed() + }) + } + + /// The dtype of the scan's arrays. + pub fn dtype(&self) -> &DType { + &self.dtype + } + + /// Whether a stream created now would find no work. Never blocks, and writes nothing. + /// + /// Once true it stays true. While it is false a new stream may still find nothing, because + /// streams take their work only when first polled. + pub fn is_exhausted(&self) -> bool { + 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 { + dtype: self.dtype.clone(), + worker: (self.new_worker)(), + } + } +} + +impl fmt::Debug for ScanExec { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("ScanExec") + .field("dtype", &self.dtype) + .field("exhausted", &self.is_exhausted()) + .finish_non_exhaustive() + } +} + +/// One worker over the work of a [`ScanExec`], which one host thread or partition reads. +/// +/// The work may run as tasks on the session's runtime, which the host owns, and nothing starts +/// threads of its own. A host whose runtime has no threads of its own, such as a +/// `CurrentThreadRuntime`, must therefore drive that runtime while it waits on a stream, for +/// example with `block_on`. Dropping a stream before it ends gives up any work it had taken, so a +/// host drops a stream early only when it abandons the scan. +pub struct ScanStream { + dtype: DType, + worker: BoxStream<'static, VortexResult>, +} + +impl fmt::Debug for ScanStream { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("ScanStream") + .field("dtype", &self.dtype) + .finish_non_exhaustive() + } +} + +impl Stream for ScanStream { + type Item = VortexResult; + + fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + self.worker.poll_next_unpin(cx) + } +} + +impl ArrayStream for ScanStream { + fn dtype(&self) -> &DType { + &self.dtype + } +} + +#[cfg(test)] +mod tests { + use std::any::Any; + use std::num::NonZeroUsize; + + use futures::StreamExt; + use futures::TryStreamExt; + use futures::executor::block_on; + use futures::future::try_join_all; + use futures::stream; + use vortex_array::ArrayRef; + use vortex_array::IntoArray; + use vortex_array::dtype::DType; + use vortex_array::dtype::Nullability; + use vortex_array::dtype::PType; + use vortex_array::expr::stats::Precision; + use vortex_array::stream::ArrayStreamAdapter; + use vortex_array::stream::ArrayStreamExt; + use vortex_array::stream::SendableArrayStream; + use vortex_buffer::Buffer; + use vortex_error::VortexResult; + + use super::ScanExec; + use super::ScanStream; + use crate::DataSourceScan; + use crate::DataSourceScanRef; + use crate::Partition; + use crate::PartitionRef; + use crate::PartitionStream; + + static DTYPE: DType = DType::Primitive(PType::I32, Nullability::NonNullable); + + /// A partition of `rows` rows, returned as one array. + struct RowsPartition { + index: usize, + rows: usize, + } + + impl Partition for RowsPartition { + fn as_any(&self) -> &dyn Any { + self + } + + fn index(&self) -> usize { + self.index + } + + fn row_count(&self) -> Precision { + Precision::exact(self.rows as u64) + } + + fn byte_size(&self) -> Precision { + Precision::Absent + } + + fn execute(self: Box) -> VortexResult { + let array = rows_array(self.rows)?; + Ok(ArrayStreamExt::boxed(ArrayStreamAdapter::new( + DTYPE.clone(), + stream::iter([Ok(array)]), + ))) + } + } + + /// The array of `rows` rows that a test partition returns. + fn rows_array(rows: usize) -> VortexResult { + Ok(Buffer::from_iter(0..i32::try_from(rows)?).into_array()) + } + + /// A scan that has no queue of work of its own, so it opens into [`ScanExec::from_partitions`]. + struct PartitionOnlyScan { + rows: Vec, + } + + impl DataSourceScan for PartitionOnlyScan { + fn dtype(&self) -> &DType { + &DTYPE + } + + fn split(self: Box, _n: NonZeroUsize) -> VortexResult> { + Ok(vec![self]) + } + + fn open(self: Box) -> VortexResult { + Ok(ScanExec::from_partitions(self)) + } + + fn partition_count(&self) -> Precision { + Precision::exact(self.rows.len()) + } + + fn partitions(self: Box) -> PartitionStream { + stream::iter( + self.rows.into_iter().enumerate().map(|(index, rows)| { + Ok(Box::new(RowsPartition { index, rows }) as PartitionRef) + }), + ) + .boxed() + } + } + + /// The rows that `streams` return together, each polled concurrently. + fn total_rows(streams: impl IntoIterator) -> VortexResult { + let workers = streams + .into_iter() + .map(|stream| stream.try_fold(0, |rows, array| async move { Ok(rows + array.len()) })); + Ok(block_on(try_join_all(workers))?.into_iter().sum()) + } + + #[test] + fn streams_share_partitions() -> VortexResult<()> { + let exec = Box::new(PartitionOnlyScan { + rows: vec![2, 3, 4, 5], + }) + .open()?; + assert!(!exec.is_exhausted()); + assert_eq!( + total_rows([exec.stream(), exec.stream(), exec.stream()])?, + 14 + ); + assert!(exec.is_exhausted()); + assert_eq!(total_rows([exec.stream()])?, 0); + Ok(()) + } +} diff --git a/vortex-scan/src/test.rs b/vortex-scan/src/test.rs index f57b5559b31..a00404caf54 100644 --- a/vortex-scan/src/test.rs +++ b/vortex-scan/src/test.rs @@ -4,6 +4,7 @@ //! Source-independent fixtures shared by plan and engine tests. use std::any::Any; +use std::num::NonZeroUsize; use std::ops::Range; use std::sync::Arc; use std::sync::LazyLock; @@ -69,6 +70,7 @@ use crate::source::ScanInput; use crate::source::SegmentFuture; use crate::source::SegmentId; use crate::source::SegmentSource; +use crate::stream::ScanExec; pub static SESSION: LazyLock = LazyLock::new(VortexSession::empty); @@ -99,6 +101,14 @@ impl DataSourceScan for TestArrayScan { &self.dtype } + fn split(self: Box, _n: NonZeroUsize) -> VortexResult> { + Ok(vec![self]) + } + + fn open(self: Box) -> VortexResult { + Ok(ScanExec::from_partitions(self)) + } + fn partition_count(&self) -> Precision { Precision::Exact(self.arrays.len()) }