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 4390b01aa9a..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( @@ -1038,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; @@ -1076,22 +1234,12 @@ mod tests { use vortex::scan::Partition; use vortex::scan::PartitionRef; use vortex::scan::PartitionStream; - use vortex::scan::stream::ScanExec; use vortex::session::VortexSession; use vortex_arrow::ArrowSessionExt; 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. @@ -1212,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 { @@ -1223,26 +1376,41 @@ mod tests { &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(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())]; @@ -1275,6 +1443,7 @@ mod tests { dtype: self.dtype.clone(), limit: request.limit, polls: Arc::clone(&self.polls), + partitions: vec![0, 1], })) } @@ -1340,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(), @@ -1349,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] { @@ -1366,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(), @@ -1423,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), @@ -1438,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(), @@ -1452,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),