From ba6e4e59e2a947a9717aae3c756cd6db1f50e47c Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 17:16:17 -0500 Subject: [PATCH 1/4] Read DataFusion file scans through the Scan API DataFusion's default FileOpener reads its V1 path through `DataSource::scan(ScanRequest { row_range, .. })` and `open()` on a `LayoutReaderDataSource` shared per file, instead of building a `ScanBuilder`. The byte-range-to-row mapping uses a new `DataSource::cut_points`, which the layout source caches and reuses for its own scans in place of the opener handing natural splits back. Signed-off-by: Nicholas Gates Co-Authored-By: Claude Fable 5.2 --- vortex-datafusion/src/persistent/opener.rs | 266 +++++++++++++-------- vortex-datafusion/src/persistent/source.rs | 14 +- vortex-file/src/source.rs | 6 + vortex-layout/src/scan/layout.rs | 148 +++++++++++- vortex-scan/src/lib.rs | 19 ++ 5 files changed, 341 insertions(+), 112 deletions(-) diff --git a/vortex-datafusion/src/persistent/opener.rs b/vortex-datafusion/src/persistent/opener.rs index 3ba227d6ca5..0d8fe3972ca 100644 --- a/vortex-datafusion/src/persistent/opener.rs +++ b/vortex-datafusion/src/persistent/opener.rs @@ -2,6 +2,7 @@ // SPDX-FileCopyrightText: Copyright the Vortex contributors use std::future::ready; +use std::num::NonZeroUsize; use std::ops::Range; use std::sync::Arc; use std::sync::Weak; @@ -43,27 +44,32 @@ use futures::FutureExt; use futures::StreamExt; use futures::TryStreamExt; use futures::stream; +use futures::stream::BoxStream; use object_store::path::Path; use tracing::Instrument; use vortex::error::VortexError; use vortex::error::VortexExpect; +use vortex::error::VortexResult; use vortex::expr::Expression; use vortex::expr::and_collect; use vortex::file::OpenOptionsSessionExt; +use vortex::file::VortexFile; use vortex::io::InstrumentedReadAt; use vortex::io::session::RuntimeSessionExt; -use vortex::layout::LayoutReader; +use vortex::layout::scan::layout::LayoutReaderDataSource; use vortex::layout::scan::metrics::ScanMetrics; -use vortex::layout::scan::scan_builder::ScanBuilder; use vortex::layout::scan::v2::ScanBuilder as V2ScanBuilder; use vortex::layout::scan::v2::partition_row_range; use vortex::layout::segments::SegmentSource; use vortex::metrics::Label; use vortex::metrics::MetricsRegistry; +use vortex::scan::DataSource; +use vortex::scan::ScanRequest; use vortex::scan::execution::driver::ScanDriver; use vortex::scan::prepare::ScanCache; use vortex::scan::prepare::WeakScanCache; use vortex::session::VortexSession; +use vortex_arrow::ArrowArrayStreamExt; use vortex_arrow::ArrowSessionExt; use vortex_utils::aliases::dash_map::DashMap; use vortex_utils::aliases::dash_map::Entry; @@ -109,11 +115,11 @@ pub(crate) struct VortexOpener { pub scan_metrics: ScanMetrics, /// DataFusion-native metrics exposed through `DataSourceExec`. pub df_metrics: ExecutionPlanMetricsSet, - /// A shared cache of file readers. + /// A shared cache of each file's V1 data source. /// - /// To save on the overhead of reparsing FlatBuffers and rebuilding the layout tree, we cache - /// a file reader the first time we read a file. - pub layout_readers: Arc>>, + /// To save on the overhead of reparsing FlatBuffers and rebuilding the layout tree, the + /// partitions of a file read through one source, which also keeps the file's cut points. + pub data_sources: Arc>>, /// Shared V2 segment sources keyed by file path. /// /// Partitions of one file read through one source, so a chunk straddling a partition @@ -123,7 +129,7 @@ pub(crate) struct VortexOpener { /// The V2 scan cache each open file's partitions share: its lowered layout, filter and /// projection plans, pruned zones and dictionary values, built once per file. pub scan_caches: Arc>, - /// Shared V1 full-file natural splits keyed by file path. + /// Shared V1 full-file cut points keyed by file path. pub natural_splits: Arc>>, /// Shared physical Arrow schemas of each file, keyed by file path. pub file_schemas: Arc>, @@ -220,7 +226,7 @@ impl FileOpener for VortexOpener { let unified_file_schema = Arc::clone(self.table_schema.file_schema()); let limit = self.limit; - let layout_readers = Arc::clone(&self.layout_readers); + let data_sources = Arc::clone(&self.data_sources); let segment_sources = Arc::clone(&self.segment_sources); let scan_caches = Arc::clone(&self.scan_caches); let natural_splits = Arc::clone(&self.natural_splits); @@ -411,7 +417,9 @@ impl FileOpener for VortexOpener { .map(|(_, expression)| expression.clone()), ); let residual_filter = conjunction_opt(residual_filters); - let native_filter = and_collect(native_filters) + let request_filter = and_collect(native_filters); + let native_filter = request_filter + .as_ref() .map(|filter| filter.bind(vxf.dtype())?.optimize_recursive()) .transpose() .map_err(|e| { @@ -445,6 +453,7 @@ impl FileOpener for VortexOpener { // The schema of the stream returned from the vortex scan. // We use a reference schema for types that don't roundtrip (Dictionary, Utf8, etc.). + let request_projection = scan_projection.clone(); let scan_projection = scan_projection .bind(vxf.dtype()) .and_then(|projection| projection.optimize_recursive()) @@ -478,13 +487,14 @@ impl FileOpener for VortexOpener { }) .transpose()?; - let stream_target_field = Field::new_struct("", stream_schema.fields().clone(), false); let residual_path = file.path().clone(); let native_limit = limit .filter(|_| scan_v2 && residual_filter.is_none()) .map(|limit| (limit, Arc::clone(&output_schema))); - let map_batch = move |chunk| to_record_batch(chunk, &stream_target_field, &session); let stream = if scan_v2 { + let stream_target_field = + Field::new_struct("", stream_schema.fields().clone(), false); + let map_batch = move |chunk| to_record_batch(chunk, &stream_target_field, &session); let mut scan_file = vxf.scan_file(); scan_file.segments = shared_segment_source( &segment_sources, @@ -530,51 +540,28 @@ impl FileOpener for VortexOpener { let driver = ScanDriver::new(handle, concurrency, has_output_ordering); Ok(driver.run_prepared(scan, map_batch)) } else { - // Share V1 layout readers across partitions of the file. - let layout_reader = match layout_readers.entry(file.object_meta.location.clone()) { - Entry::Occupied(mut occupied_entry) => { - if let Some(reader) = occupied_entry.get().upgrade() { - tracing::trace!("reusing layout reader for {}", occupied_entry.key()); - reader - } else { - tracing::trace!("creating layout reader for {}", occupied_entry.key()); - let reader = vxf.layout_reader().map_err(|e| { - DataFusionError::Execution(format!( - "Failed to create layout reader: {e}" - )) - })?; - occupied_entry.insert(Arc::downgrade(&reader)); - reader - } - } - Entry::Vacant(vacant_entry) => { - tracing::trace!("creating layout reader for {}", vacant_entry.key()); - let reader = vxf.layout_reader().map_err(|e| { - DataFusionError::Execution(format!( - "Failed to create layout reader: {e}" - )) - })?; - vacant_entry.insert(Arc::downgrade(&reader)); - - reader - } + let data_source = shared_data_source( + &data_sources, + &file.object_meta.location, + &vxf, + &scan_metrics, + )?; + let mut request = ScanRequest { + projection: request_projection, + filter: request_filter, + ordered: has_output_ordering, + // Residual filters need the full scan output before DataFusion applies the + // limit. + limit: limit.filter(|_| residual_filter.is_none()), + split_concurrency: scan_concurrency.and_then(NonZeroUsize::new), + ..ScanRequest::default() }; - - let mut scan_builder = ScanBuilder::new(vxf.session().clone(), layout_reader) - .with_projection(scan_projection) - .with_some_filter(native_filter); - if let Some(vortex_plan) = file.extensions.get::() { - scan_builder = vortex_plan.apply_to_builder(scan_builder); - } - // Residual filters need the full scan output before DataFusion applies the limit. - if let Some(limit) = limit - && residual_filter.is_none() + if let Some(selection) = file + .extensions + .get::() + .and_then(VortexAccessPlan::selection) { - scan_builder = scan_builder.with_limit(limit); - } - // V1 requires positive concurrency; V2 also accepts zero. - if let Some(concurrency) = scan_concurrency.filter(|&concurrency| concurrency > 0) { - scan_builder = scan_builder.with_concurrency(concurrency); + request.selection = selection.clone(); } if let Some(bytes) = byte_range && (bytes.start != 0 || bytes.end != file.object_meta.size) @@ -582,22 +569,23 @@ impl FileOpener for VortexOpener { let splits = natural_splits_for_file( natural_splits.as_ref(), &file.object_meta.location, - &scan_builder, + data_source.as_ref(), + &request, + vxf.row_count(), file.object_meta.size, - )?; + ) + .await?; let Some(rows) = split_aligned_row_range(bytes, splits.as_ref()) else { return Ok(stream::empty().boxed()); }; - scan_builder = scan_builder - .with_row_range(rows) - .with_natural_splits(Arc::clone(&splits.row_boundaries)); + request.row_range = Some(rows); } - scan_builder - .with_scan_metrics(scan_metrics) - .with_ordered(has_output_ordering) - .map(map_batch) - .into_stream() - .map(StreamExt::boxed) + Ok(read_data_source( + data_source, + request, + session, + Arc::new(stream_schema.clone()), + )) } .map_err(|e| exec_datafusion_err!("Failed to create Vortex stream: {e}"))? .map_err(move |e: VortexError| { @@ -669,10 +657,9 @@ impl FileOpener for VortexOpener { /// tiling the file's rows exactly once. #[derive(Debug)] pub(crate) struct NaturalSplits { - /// Sorted row boundaries of the natural splits; split `i` covers - /// `row_boundaries[i]..row_boundaries[i + 1]`. Shared so partitions can hand the - /// boundaries back to the scan via [`ScanBuilder::with_natural_splits`], skipping the - /// per-partition layout walk in `prepare`. + /// Sorted row boundaries of the natural splits, the source's + /// [cut points](DataSource::cut_points); split `i` covers + /// `row_boundaries[i]..row_boundaries[i + 1]`. row_boundaries: Arc<[u64]>, /// For each split, the byte a DataFusion byte range must contain to own it (see /// [`split_assignment_byte`]); one entry per split, sorted because split midpoints @@ -759,44 +746,117 @@ fn shared_segment_source( } } +/// Returns the data source other partitions of `path` are reading through, or opens one over +/// `file`. Each stream that reads the source holds it, so it lives as long as one scan of the +/// file, as the layout readers do. +fn shared_data_source( + data_sources: &DashMap>, + path: &Path, + file: &VortexFile, + scan_metrics: &ScanMetrics, +) -> DFResult> { + let open = || -> DFResult> { + tracing::trace!("creating layout reader for {path}"); + let reader = file.layout_reader().map_err(|e| { + DataFusionError::Execution(format!("Failed to create layout reader: {e}")) + })?; + Ok(Arc::new( + LayoutReaderDataSource::new(reader, file.session().clone()) + .with_scan_metrics(scan_metrics.clone()), + )) + }; + match data_sources.entry(path.clone()) { + Entry::Occupied(mut entry) => { + if let Some(source) = entry.get().upgrade() { + tracing::trace!("reusing layout reader for {path}"); + Ok(source) + } else { + let source = open()?; + entry.insert(Arc::downgrade(&source)); + Ok(source) + } + } + Entry::Vacant(entry) => { + let source = open()?; + entry.insert(Arc::downgrade(&source)); + Ok(source) + } + } +} + /// Return the cached [`NaturalSplits`] for `path`, computing and caching them on first use. -fn natural_splits_for_file( +/// +/// The first partition to cache them wins, so every partition maps its byte range through the +/// same boundaries. A source without cut points reads the file as one piece. +async fn natural_splits_for_file( natural_splits: &DashMap>, path: &Path, - scan_builder: &ScanBuilder, + data_source: &LayoutReaderDataSource, + request: &ScanRequest, + row_count: u64, total_size: u64, ) -> DFResult> { if let Some(splits) = natural_splits.get(path) { return Ok(Arc::clone(splits.value())); } - // Compute while holding the entry so concurrent partitions opening the same file wait - // for the winner instead of all walking the layout tree; the redundant walks contend on - // the lazily-initialized layout children and dominate the cost of the computation itself. - match natural_splits.entry(path.clone()) { - Entry::Occupied(entry) => Ok(Arc::clone(entry.get())), - Entry::Vacant(entry) => { - let splits = compute_natural_splits(scan_builder, total_size)?; - entry.insert(Arc::clone(&splits)); - Ok(splits) - } - } + // The source computes its cut points once under its own lock, so concurrent partitions + // opening the same file wait for one layout walk. + let row_boundaries = data_source + .cut_points(request) + .await + .map_err(|e| exec_datafusion_err!("Failed to compute Vortex cut points: {e}"))? + .unwrap_or_else(|| Arc::from([0, row_count])); + let splits = Arc::new(NaturalSplits::new(row_boundaries, total_size)); + Ok(Arc::clone( + natural_splits.entry(path.clone()).or_insert(splits).value(), + )) } -/// Walk the layout tree to compute the file's full natural split boundaries for the fields -/// referenced by the scan's projection and filter. -fn compute_natural_splits( - scan_builder: &ScanBuilder, - total_size: u64, -) -> DFResult> { - let row_boundaries = scan_builder - .full_file_splits() - .map_err(|e| exec_datafusion_err!("Failed to compute Vortex natural splits: {e}"))?; - - Ok(Arc::new(NaturalSplits::new( - row_boundaries.into(), - total_size, - ))) +/// Reads `request` from `data_source` as Arrow batches with `schema`. +/// +/// The scan is planned and opened when the stream is first polled, so that it sees the dynamic +/// filters as they are when the file's turn comes, not when DataFusion opens the file ahead. +/// Opening walks the layout and builds the split tasks, so it runs where compute runs. +/// +/// An unordered scan without a limit is polled through one clone of its stream per core, each +/// converting its own arrays, which keeps as many splits in flight for the partition as a scan +/// pipeline does. An ordered or limited scan is one piece, read through one clone. +fn read_data_source( + data_source: Arc, + request: ScanRequest, + session: VortexSession, + schema: SchemaRef, +) -> BoxStream<'static, VortexResult> { + let source = Arc::clone(&data_source); + let batches = stream::once(async move { + let single = request.ordered || request.limit.is_some(); + let scan = source.scan(request).await?; + let arrays = session.handle().spawn_cpu(move || scan.open()).await?; + let parallelism = get_available_parallelism().unwrap_or(1).max(1); + let batches = if single { + let concurrency = NonZeroUsize::new(parallelism).unwrap_or(NonZeroUsize::MIN); + arrays.to_arrow(&session, Some(schema), concurrency) + } else { + stream::select_all((0..parallelism).map(|_| { + arrays + .clone() + .to_arrow(&session, Some(Arc::clone(&schema)), NonZeroUsize::MIN) + })) + .boxed() + }; + VortexResult::Ok(batches) + }) + .try_flatten(); + // Hold the source until the stream ends, so that the file's other partitions share it. + batches + .chain( + stream::once(async move { + drop(data_source); + }) + .filter_map(|()| ready(None::>)), + ) + .boxed() } /// Translate a DataFusion byte range to the contiguous natural split ranges it owns. @@ -1124,7 +1184,7 @@ mod tests { } assert_eq!(concat_batches(&batch.schema(), &data)?, batch); if scan_v2 { - assert!(opener.layout_readers.is_empty()); + assert!(opener.data_sources.is_empty()); assert!(opener.natural_splits.is_empty()); } Ok(()) @@ -1168,7 +1228,7 @@ mod tests { metrics_registry: Arc::::clone(&metrics_registry), scan_metrics: ScanMetrics::new(metrics_registry.as_ref()), df_metrics: ExecutionPlanMetricsSet::new(), - layout_readers: Default::default(), + data_sources: Default::default(), segment_sources: Default::default(), scan_caches: Default::default(), partitions: 1, @@ -1621,7 +1681,7 @@ mod tests { metrics_registry: Arc::::clone(&metrics_registry), scan_metrics: ScanMetrics::new(metrics_registry.as_ref()), df_metrics: ExecutionPlanMetricsSet::new(), - layout_readers: Default::default(), + data_sources: Default::default(), segment_sources: Default::default(), scan_caches: Default::default(), partitions: 1, @@ -1716,7 +1776,7 @@ mod tests { metrics_registry: Arc::::clone(&metrics_registry), scan_metrics: ScanMetrics::new(metrics_registry.as_ref()), df_metrics: ExecutionPlanMetricsSet::new(), - layout_readers: Default::default(), + data_sources: Default::default(), segment_sources: Default::default(), scan_caches: Default::default(), partitions: 1, @@ -1902,7 +1962,7 @@ mod tests { metrics_registry: Arc::::clone(&metrics_registry), scan_metrics: ScanMetrics::new(metrics_registry.as_ref()), df_metrics: ExecutionPlanMetricsSet::new(), - layout_readers: Default::default(), + data_sources: Default::default(), segment_sources: Default::default(), scan_caches: Default::default(), partitions: 1, @@ -1970,7 +2030,7 @@ mod tests { metrics_registry: Arc::::clone(&metrics_registry), scan_metrics: ScanMetrics::new(metrics_registry.as_ref()), df_metrics: ExecutionPlanMetricsSet::new(), - layout_readers: Default::default(), + data_sources: Default::default(), segment_sources: Default::default(), scan_caches: Default::default(), partitions: 1, @@ -2189,7 +2249,7 @@ mod tests { metrics_registry: Arc::::clone(&metrics_registry), scan_metrics: ScanMetrics::new(metrics_registry.as_ref()), df_metrics: ExecutionPlanMetricsSet::new(), - layout_readers: Default::default(), + data_sources: Default::default(), segment_sources: Default::default(), scan_caches: Default::default(), partitions: 1, diff --git a/vortex-datafusion/src/persistent/source.rs b/vortex-datafusion/src/persistent/source.rs index 99b5c528c83..7eac8fc8a49 100644 --- a/vortex-datafusion/src/persistent/source.rs +++ b/vortex-datafusion/src/persistent/source.rs @@ -35,7 +35,7 @@ use object_store::ObjectStore; use object_store::path::Path; use vortex::expr::Expression; use vortex::file::VORTEX_FILE_EXTENSION; -use vortex::layout::LayoutReader; +use vortex::layout::scan::layout::LayoutReaderDataSource; use vortex::layout::scan::metrics::ScanMetrics; use vortex::layout::segments::SegmentSource; use vortex::metrics::DefaultMetricsRegistry; @@ -202,14 +202,14 @@ pub struct VortexSource { pub(crate) vortex_predicate: Option, /// DataFusion-native metrics exposed through `DataSourceExec`. df_metrics: ExecutionPlanMetricsSet, - /// Shared layout readers, the source only lives as long as one scan. + /// Shared V1 data sources, each living only as long as one scan of its file. /// - /// Sharing the readers allows us to only read every layout once from the file, even across partitions. - layout_readers: Arc>>, + /// Sharing them allows us to only read every layout once from the file, even across partitions. + data_sources: Arc>>, /// Shared V2 segment sources, keyed by path and alive only while a scan reads the file. segment_sources: Arc>>, scan_caches: Arc>, - /// Shared full-file natural splits keyed by path. + /// Shared full-file cut points keyed by path. natural_splits: Arc>>, /// Shared physical Arrow schemas of each file, keyed by path. file_schemas: Arc>, @@ -250,7 +250,7 @@ impl VortexSource { full_predicate: None, vortex_predicate: None, df_metrics: Default::default(), - layout_readers: Arc::new(DashMap::default()), + data_sources: Arc::new(DashMap::default()), segment_sources: Arc::new(DashMap::default()), scan_caches: Arc::new(DashMap::default()), natural_splits: Arc::new(DashMap::default()), @@ -390,7 +390,7 @@ impl VortexSource { metrics_registry: Arc::clone(&self.vx_metrics_registry), scan_metrics: self.scan_metrics.clone(), df_metrics: self.df_metrics.clone(), - layout_readers: Arc::clone(&self.layout_readers), + data_sources: Arc::clone(&self.data_sources), segment_sources: Arc::clone(&self.segment_sources), scan_caches: Arc::clone(&self.scan_caches), natural_splits: Arc::clone(&self.natural_splits), diff --git a/vortex-file/src/source.rs b/vortex-file/src/source.rs index 1088a61de88..a45a86973a6 100644 --- a/vortex-file/src/source.rs +++ b/vortex-file/src/source.rs @@ -1,6 +1,8 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +use std::sync::Arc; + use async_trait::async_trait; use vortex_array::aggregate_fn::AggregateFnRef; use vortex_array::dtype::DType; @@ -55,6 +57,10 @@ impl DataSource for FileDataSource { self.source.scan(request).await } + async fn cut_points(&self, request: &ScanRequest) -> VortexResult>> { + self.source.cut_points(request).await + } + async fn field_statistics(&self, field_path: &FieldPath) -> VortexResult { Ok(self .statistics diff --git a/vortex-layout/src/scan/layout.rs b/vortex-layout/src/scan/layout.rs index 9f555b7a1bc..3a3fec78404 100644 --- a/vortex-layout/src/scan/layout.rs +++ b/vortex-layout/src/scan/layout.rs @@ -2,6 +2,7 @@ // SPDX-FileCopyrightText: Copyright the Vortex contributors use std::any::Any; +use std::iter; use std::num::NonZeroUsize; use std::ops::Range; use std::pin::Pin; @@ -14,10 +15,12 @@ use futures::FutureExt; use futures::Stream; use futures::stream; use futures::stream::StreamExt; +use parking_lot::Mutex; use vortex_array::ArrayRef; use vortex_array::IntoArray; use vortex_array::arrays::ConstantArray; use vortex_array::dtype::DType; +use vortex_array::dtype::FieldMask; use vortex_array::dtype::FieldPath; use vortex_array::dtype::Nullability; use vortex_array::expr::BoundExpression; @@ -49,6 +52,8 @@ 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::scan_builder::referenced_field_masks; +use crate::scan::split_by::SplitBy; use crate::scan::split_queue::SplitQueue; /// An implementation of a [`DataSource`] that reads data from a [`LayoutReaderRef`]. @@ -57,6 +62,10 @@ pub struct LayoutReaderDataSource { session: VortexSession, split_max_row_count: u64, metrics: Option, + /// The whole-source cut points computed by [`DataSource::cut_points`], keyed by the fields + /// whose layout decides them. Scans whose fields match reuse them instead of walking the + /// layout again. + cut_points: Mutex, Arc<[u64]>)>>, } impl LayoutReaderDataSource { @@ -72,6 +81,7 @@ impl LayoutReaderDataSource { session, split_max_row_count: u64::MAX, metrics: None, + cut_points: Mutex::new(Vec::new()), } } @@ -96,6 +106,25 @@ impl LayoutReaderDataSource { self.metrics = metrics.as_deref().map(ScanMetrics::new); self } + + /// Adds this source's scans to counters registered elsewhere, without new registry entries. + /// + /// A host that opens one source per file registers the counters once with + /// [`ScanMetrics::new`] and shares them across its sources. + pub fn with_scan_metrics(mut self, metrics: ScanMetrics) -> Self { + self.metrics = Some(metrics); + self + } + + /// The cached whole-source cut points for `field_mask`, if [`DataSource::cut_points`] + /// computed them. + fn cached_cut_points(&self, field_mask: &[FieldMask]) -> Option> { + self.cut_points + .lock() + .iter() + .find(|(mask, _)| mask.as_slice() == field_mask) + .map(|(_, boundaries)| Arc::clone(boundaries)) + } } #[async_trait] @@ -133,6 +162,8 @@ impl DataSource for LayoutReaderDataSource { .map(|expr| expr.bind(self.reader.dtype())?.optimize_recursive()) .transpose()?; let dtype = projection.dtype().clone(); + let natural_splits = + self.cached_cut_points(&referenced_field_masks(&projection, filter.as_ref())?); // If the dtype is an empty struct, and there is no filter, we can return a special // length-only scan. @@ -212,12 +243,73 @@ impl DataSource for LayoutReaderDataSource { ordered: scan_request.ordered, split_concurrency: scan_request.split_concurrency, metrics: self.metrics.clone(), + natural_splits, next_row: row_range.start, end_row: row_range.end, split_size: self.split_max_row_count, })) } + /// The layout's split boundaries for the fields the request reads, as a scan of the whole + /// source would compute them, clamped to the request's row range. + /// + /// The whole-source boundaries are computed once for each set of fields and cached, and later + /// scans of this source that read the same fields cut at them instead of walking the layout. + async fn cut_points(&self, scan_request: &ScanRequest) -> VortexResult>> { + let projection = scan_request + .projection + .bind(self.reader.dtype())? + .optimize_recursive()?; + let filter = scan_request + .filter + .as_ref() + .map(|expr| expr.bind(self.reader.dtype())?.optimize_recursive()) + .transpose()?; + let field_mask = referenced_field_masks(&projection, filter.as_ref())?; + + // Compute under the lock, so that concurrent callers wait for one layout walk instead of + // each contending on the layout's lazily initialized children. + let boundaries = { + let mut cache = self.cut_points.lock(); + let cached = cache + .iter() + .find(|(mask, _)| *mask == field_mask) + .map(|(_, boundaries)| Arc::clone(boundaries)); + match cached { + Some(boundaries) => boundaries, + None => { + let boundaries: Arc<[u64]> = SplitBy::default() + .splits( + self.reader.as_ref(), + &(0..self.reader.row_count()), + &field_mask, + )? + .into(); + cache.push((field_mask, Arc::clone(&boundaries))); + boundaries + } + } + }; + + let Some(row_range) = &scan_request.row_range else { + return Ok(Some(boundaries)); + }; + if row_range.start >= row_range.end { + return Ok(Some(Arc::from([row_range.start]))); + } + Ok(Some( + iter::once(row_range.start) + .chain( + boundaries + .iter() + .copied() + .filter(|&row| row > row_range.start && row < row_range.end), + ) + .chain(iter::once(row_range.end)) + .collect(), + )) + } + async fn field_statistics(&self, _field_path: &FieldPath) -> VortexResult { Ok(StatsSet::default()) } @@ -239,6 +331,8 @@ struct LayoutReaderScan { split_concurrency: Option, selection: Selection, metrics: Option, + /// The source's cached whole-source cut points for this scan's fields, if any. + natural_splits: Option>, next_row: u64, end_row: u64, split_size: u64, @@ -248,12 +342,16 @@ 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)) + let builder = 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) + .with_some_max_splits_in_flight(self.split_concurrency); + match &self.natural_splits { + Some(boundaries) => builder.with_natural_splits(Arc::clone(boundaries)), + None => builder, + } } /// This scan over `rows` only. Only a scan without a limit is cut into pieces, so a piece @@ -271,6 +369,7 @@ impl LayoutReaderScan { split_concurrency: self.split_concurrency, selection: self.selection.clone(), metrics: self.metrics.clone(), + natural_splits: self.natural_splits.clone(), next_row: rows.start, end_row: rows.end, split_size: self.split_size, @@ -424,6 +523,7 @@ impl Stream for LayoutReaderScan { row_range, selection: this.selection.clone(), metrics: this.metrics.clone(), + natural_splits: this.natural_splits.clone(), }) as PartitionRef; this.next_row = split_end; @@ -458,6 +558,7 @@ struct LayoutReaderSplit { row_range: Range, selection: Selection, metrics: Option, + natural_splits: Option>, } impl Partition for LayoutReaderSplit { @@ -495,6 +596,10 @@ impl Partition for LayoutReaderSplit { .with_some_scan_metrics(self.metrics) .with_ordered(self.ordered) .with_some_max_splits_in_flight(self.split_concurrency); + let builder = match self.natural_splits { + Some(boundaries) => builder.with_natural_splits(boundaries), + None => builder, + }; let builder = match self.row_limit { Some(row_limit) => builder.with_shared_limit(row_limit), None => builder.with_some_limit(self.limit), @@ -755,6 +860,7 @@ mod split_open_tests { use futures::TryStreamExt; use futures::future::try_join_all; + use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_io::runtime::BlockingRuntime; use vortex_io::runtime::single::SingleThreadRuntime; @@ -848,6 +954,44 @@ mod split_open_tests { Ok(()) } + /// Cut points are the layout's split boundaries clamped to the request's row range, and + /// scans cut at row ranges between them read each row once. + #[test] + fn cut_points_tile_the_rows() -> VortexResult<()> { + let runtime = SingleThreadRuntime::default(); + let source = source(&runtime); + let whole = runtime + .block_on(source.cut_points(&ScanRequest::default()))? + .vortex_expect("a layout source has cut points"); + assert_eq!( + whole.as_ref(), + (0..=16u64).map(|i| i * 4).collect::>() + ); + + let clamped = runtime + .block_on(source.cut_points(&ScanRequest { + row_range: Some(6..18), + ..Default::default() + }))? + .vortex_expect("a layout source has cut points"); + assert_eq!(clamped.as_ref(), [6, 8, 12, 16, 18]); + + let mut values = Vec::new(); + let cuts = whole.iter().copied().step_by(4).collect::>(); + for rows in cuts.windows(2).map(|pair| pair[0]..pair[1]) { + let stream = runtime + .block_on(source.scan(ScanRequest { + row_range: Some(rows), + ordered: true, + ..Default::default() + }))? + .open()?; + values.extend(collect_scan_values(runtime.block_on_stream(stream))?); + } + assert_eq!(values, (0..64).collect::>()); + Ok(()) + } + #[test] fn group_contiguous_keeps_ranges_whole() -> VortexResult<()> { // Each range joins the group its first row falls in. diff --git a/vortex-scan/src/lib.rs b/vortex-scan/src/lib.rs index 0c355a1a428..f3748af1dc4 100644 --- a/vortex-scan/src/lib.rs +++ b/vortex-scan/src/lib.rs @@ -129,6 +129,25 @@ pub trait DataSource: 'static + Send + Sync { /// Returns a scan over the source. async fn scan(&self, scan_request: ScanRequest) -> VortexResult; + /// Returns the rows at which a scan of `scan_request` can be cut without splitting the + /// source's own units of work, or `None` when the source has no such cut points. + /// + /// The boundaries are sorted and strictly increasing. The first is the start of the request's + /// row range and the last its end, or `0` and the row count when the request has no row + /// range, so consecutive boundaries cover the range exactly once. They depend on the + /// request's projection and filter, which decide the columns whose layout is read, but not + /// on its selection, limit or ordering. Computing them reads metadata only. + /// + /// A host that cuts a source's rows itself, such as one that assigns byte ranges of a file to + /// its partitions, maps its own pieces onto these boundaries and passes each piece as the + /// [`row_range`](ScanRequest::row_range) of its own scan. Pieces that start and end on + /// boundaries each read whole units of work, and together read every row once. A host that + /// wants the source to group them instead calls [`DataSourceScan::split`]. + async fn cut_points(&self, scan_request: &ScanRequest) -> VortexResult>> { + let _ = scan_request; + Ok(None) + } + /// Returns the statistics for a given field. async fn field_statistics(&self, field_path: &FieldPath) -> VortexResult; From b1a5c7ce1243faeeb168c1b73bbd59641c28711a Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 17:18:20 -0500 Subject: [PATCH 2/4] Read each DataFusion partition's V1 scan through one stream An opened layout scan keeps the request's `split_concurrency` in flight per stream as given, instead of capping each stream at the pipeline's per-thread default. The opener sets it to the scan pipeline's total, per thread times the machine's threads, and reads one stream per partition instead of merging a clone per core. Signed-off-by: Nicholas Gates Co-Authored-By: Claude Opus 5.5 --- vortex-datafusion/src/persistent/opener.rs | 42 +++++++++++----------- vortex-layout/src/scan/layout.rs | 9 +++-- 2 files changed, 26 insertions(+), 25 deletions(-) diff --git a/vortex-datafusion/src/persistent/opener.rs b/vortex-datafusion/src/persistent/opener.rs index 0d8fe3972ca..43bd4138acf 100644 --- a/vortex-datafusion/src/persistent/opener.rs +++ b/vortex-datafusion/src/persistent/opener.rs @@ -553,7 +553,7 @@ impl FileOpener for VortexOpener { // Residual filters need the full scan output before DataFusion applies the // limit. limit: limit.filter(|_| residual_filter.is_none()), - split_concurrency: scan_concurrency.and_then(NonZeroUsize::new), + split_concurrency: splits_in_flight(scan_concurrency), ..ScanRequest::default() }; if let Some(selection) = file @@ -813,15 +813,28 @@ async fn natural_splits_for_file( )) } +/// The splits a V1 scan keeps in flight per thread when `scan_concurrency` is unset, the scan +/// pipeline's default. +const SPLITS_PER_THREAD: usize = 4; + +/// The splits a partition's V1 scan keeps in flight in all: `scan_concurrency`, or +/// [`SPLITS_PER_THREAD`], for each thread of the machine. +/// +/// The partition reads its scan through one stream, so the request's `split_concurrency` is the +/// partition's total. +fn splits_in_flight(scan_concurrency: Option) -> Option { + let per_thread = scan_concurrency + .filter(|&concurrency| concurrency > 0) + .unwrap_or(SPLITS_PER_THREAD); + NonZeroUsize::new(per_thread.saturating_mul(get_available_parallelism().unwrap_or(1))) +} + /// Reads `request` from `data_source` as Arrow batches with `schema`. /// /// The scan is planned and opened when the stream is first polled, so that it sees the dynamic /// filters as they are when the file's turn comes, not when DataFusion opens the file ahead. -/// Opening walks the layout and builds the split tasks, so it runs where compute runs. -/// -/// An unordered scan without a limit is polled through one clone of its stream per core, each -/// converting its own arrays, which keeps as many splits in flight for the partition as a scan -/// pipeline does. An ordered or limited scan is one piece, read through one clone. +/// Opening walks the layout and builds the split tasks, so it runs where compute runs. The +/// partition reads one stream of the scan, and converts up to one array per thread at once. fn read_data_source( data_source: Arc, request: ScanRequest, @@ -830,22 +843,11 @@ fn read_data_source( ) -> BoxStream<'static, VortexResult> { let source = Arc::clone(&data_source); let batches = stream::once(async move { - let single = request.ordered || request.limit.is_some(); let scan = source.scan(request).await?; let arrays = session.handle().spawn_cpu(move || scan.open()).await?; - let parallelism = get_available_parallelism().unwrap_or(1).max(1); - let batches = if single { - let concurrency = NonZeroUsize::new(parallelism).unwrap_or(NonZeroUsize::MIN); - arrays.to_arrow(&session, Some(schema), concurrency) - } else { - stream::select_all((0..parallelism).map(|_| { - arrays - .clone() - .to_arrow(&session, Some(Arc::clone(&schema)), NonZeroUsize::MIN) - })) - .boxed() - }; - VortexResult::Ok(batches) + let concurrency = NonZeroUsize::new(get_available_parallelism().unwrap_or(1)) + .unwrap_or(NonZeroUsize::MIN); + VortexResult::Ok(arrays.to_arrow(&session, Some(schema), concurrency)) }) .try_flatten(); // Hold the source until the stream ends, so that the file's other partitions share it. diff --git a/vortex-layout/src/scan/layout.rs b/vortex-layout/src/scan/layout.rs index 3a3fec78404..4517858d0d4 100644 --- a/vortex-layout/src/scan/layout.rs +++ b/vortex-layout/src/scan/layout.rs @@ -408,7 +408,9 @@ impl DataSourceScan for LayoutReaderScan { } /// Opens the scan into a stream over a [`SplitQueue`] of its split futures, each clone of the - /// stream keeping the stream pipeline's per-thread count of them in flight. + /// stream keeping the request's `split_concurrency` of them in flight, or the stream + /// pipeline's per-thread count when the request leaves it unset. A host that reads the scan + /// through one stream sets it to the splits it wants in flight in all. /// /// Split futures cannot share a limit, and the clones 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 @@ -417,12 +419,9 @@ impl DataSourceScan for LayoutReaderScan { if self.remaining_limit.is_some() || self.ordered { return Ok(ScanStream::from_partitions(self)); } - // A cap on the scan's splits in flight also caps each clone's. let per_worker = self .split_concurrency - .map_or(DEFAULT_SPLITS_PER_THREAD, |max| { - max.get().min(DEFAULT_SPLITS_PER_THREAD) - }); + .map_or(DEFAULT_SPLITS_PER_THREAD, NonZeroUsize::get); let splits = self .builder() .prepare()? From 03f4a3af2b609a1ad3f6d69970f57f0179436b08 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 17:20:41 -0500 Subject: [PATCH 3/4] Fix lints in the layout source's cut-point cache Signed-off-by: Nicholas Gates Co-Authored-By: Claude Opus 5.5 --- vortex-layout/src/scan/layout.rs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/vortex-layout/src/scan/layout.rs b/vortex-layout/src/scan/layout.rs index 4517858d0d4..d3c3e1f9d0b 100644 --- a/vortex-layout/src/scan/layout.rs +++ b/vortex-layout/src/scan/layout.rs @@ -65,9 +65,12 @@ pub struct LayoutReaderDataSource { /// The whole-source cut points computed by [`DataSource::cut_points`], keyed by the fields /// whose layout decides them. Scans whose fields match reuse them instead of walking the /// layout again. - cut_points: Mutex, Arc<[u64]>)>>, + cut_points: Mutex>, } +/// Whole-source cut points and the fields whose layout decided them. +type CachedCutPoints = (Vec, Arc<[u64]>); + impl LayoutReaderDataSource { /// Creates a new [`LayoutReaderDataSource`]. /// @@ -665,7 +668,7 @@ impl Partition for Empty { let dtype = self.dtype.clone(); // Create an iterator of arrays with the correct row count, respecting u64::MAX limits. - let iter = std::iter::from_fn(move || { + let iter = iter::from_fn(move || { if self.row_count == 0 { return None; } From 2cae10f830f028e710f86c4c6e1ee45080837319 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 17:28:34 -0500 Subject: [PATCH 4/4] Name the error type of the opener's V1 stream Signed-off-by: Nicholas Gates Co-Authored-By: Claude Opus 5.5 --- vortex-datafusion/src/persistent/opener.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vortex-datafusion/src/persistent/opener.rs b/vortex-datafusion/src/persistent/opener.rs index 43bd4138acf..e30126c7b2f 100644 --- a/vortex-datafusion/src/persistent/opener.rs +++ b/vortex-datafusion/src/persistent/opener.rs @@ -580,7 +580,7 @@ impl FileOpener for VortexOpener { }; request.row_range = Some(rows); } - Ok(read_data_source( + VortexResult::Ok(read_data_source( data_source, request, session,