From 5ab0771ede7ac9f92976b38567c3755056123b9b Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 13:32:44 -0500 Subject: [PATCH] Expose Vortex files as Scan API sources over V2 plans VortexFile::plan_data_source scans one file through PlanDataSource, with the file's statistics pruning scans they rule out, and MultiFileDataSource::build_plan scans many, opening each file after the first as a scan reaches it. Both are opt-in: data_source() and build() still scan with layout readers. build_plan falls back to build() when the schema could hold a list layout, which the V2 scan cannot read yet. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-file/src/file.rs | 74 ++++++++++++++++-- vortex-file/src/multi/mod.rs | 128 ++++++++++++++++++++++++------- vortex-file/src/source.rs | 12 +-- vortex-file/src/tests.rs | 62 +++++++++++++++ vortex-file/src/v2/scan/tests.rs | 54 +++++++++++++ 5 files changed, 293 insertions(+), 37 deletions(-) diff --git a/vortex-file/src/file.rs b/vortex-file/src/file.rs index f610495f90a..e10d788d32d 100644 --- a/vortex-file/src/file.rs +++ b/vortex-file/src/file.rs @@ -28,6 +28,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; @@ -68,6 +70,29 @@ struct FileScanCache { plans: ScanCache, } +/// Whether a layout tree of `dtype` may contain a list layout. +/// +/// A list layout only ever holds a [`DType::List`], and the writer only decomposes the lists it +/// reaches through struct fields and list elements. Maps and variants are conservatively assumed +/// to contain one too, since their storage may be laid out as lists. +pub(crate) fn may_contain_list_layout(dtype: &DType) -> bool { + match dtype { + DType::List(..) | DType::Map(..) | DType::Variant(_) => true, + DType::Null + | DType::Bool(_) + | DType::Primitive(..) + | DType::Decimal(..) + | DType::Utf8(_) + | DType::Binary(_) => false, + DType::FixedSizeList(element, ..) => may_contain_list_layout(element), + DType::Struct(fields, _) => fields.fields().any(|field| may_contain_list_layout(&field)), + DType::Union(variants, _) => variants + .variants() + .any(|variant| may_contain_list_layout(&variant)), + DType::Extension(ext) => may_contain_list_layout(ext.storage_dtype()), + } +} + fn layout_reader( segment_source: Arc, footer: &Footer, @@ -116,7 +141,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 +271,56 @@ 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_file`](Self::plan_child): hosts read its + /// scans through native `split` and `open`, or through one partition covering the requested + /// rows, which runs it with [`ScanDriver`](crate::v2::ScanDriver) from + /// [`Partition::execute`](vortex_scan::Partition::execute). 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. + pub fn plan_child(&self) -> PlanChild { + let file = PlanChild::new(self.scan_file().into()).with_row_count(self.row_count()); + 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/multi/mod.rs b/vortex-file/src/multi/mod.rs index 03a80171ec5..a7c58a2fc4e 100644 --- a/vortex-file/src/multi/mod.rs +++ b/vortex-file/src/multi/mod.rs @@ -26,11 +26,19 @@ use vortex_layout::LayoutReaderRef; use vortex_layout::scan::multi::LayoutReaderFactory; use vortex_layout::scan::multi::MultiLayoutDataSource; use vortex_scan::DataSource; +use vortex_scan::DataSourceRef; +use vortex_scan::source::DeferredPlanChild; +use vortex_scan::source::PlanDataSource; +use vortex_scan::source::PlanSourceChild; use vortex_session::VortexSession; use crate::OpenOptionsSessionExt; use crate::VortexFile; use crate::VortexOpenOptions; +use crate::file::may_contain_list_layout; + +/// Adjusts the options each file of a [`MultiFileDataSource`] is opened with. +type OpenOptionsFn = Arc VortexOpenOptions + Send + Sync>; /// A builder that discovers multiple Vortex files from glob patterns and constructs a /// [`MultiLayoutDataSource`] to scan them as a single data source. @@ -122,6 +130,52 @@ impl MultiFileDataSource { /// Discovers files via glob, opens the first file eagerly to determine the schema, /// and creates lazy factories for the remaining files. pub async fn build(self) -> VortexResult { + let session = self.session.clone(); + let open_options_fn = Arc::clone(&self.open_options_fn); + let (first_file, all_files) = self.discover().await?; + layout_source(&session, &open_options_fn, &first_file, &all_files) + } + + /// Build a [`DataSource`] whose scans run on the planner-driven executor. + /// + /// Discovers files as [`build`](Self::build) does and opens the first file for the schema. + /// The source is a [`PlanDataSource`] whose remaining files are opened when a scan reaches + /// them, as units of the scan's work. The planner-driven executor cannot read list layouts + /// yet, so when the schema could hold one, this returns [`build`](Self::build)'s layout + /// reader source instead. + pub async fn build_plan(self) -> VortexResult { + let session = self.session.clone(); + let open_options_fn = Arc::clone(&self.open_options_fn); + let (first_file, all_files) = self.discover().await?; + if may_contain_list_layout(first_file.dtype()) { + return Ok(Arc::new(layout_source( + &session, + &open_options_fn, + &first_file, + &all_files, + )?)); + } + let mut files = vec![PlanSourceChild::Ready(first_file.plan_child())]; + files.extend( + all_files[1..] + .iter() + .map(|(file, fs)| PlanSourceChild::Deferred { + child: Arc::new(DeferredVortexFile { + fs: Arc::clone(fs), + file: file.clone(), + session: session.clone(), + open_options_fn: Arc::clone(&open_options_fn), + }), + byte_size: file.size, + }), + ); + let source = PlanDataSource::from_children(session, first_file.dtype().clone(), files); + debug!(file_count = all_files.len(), dtype = %source.dtype(), "built a plan MultiFileDataSource"); + Ok(Arc::new(source)) + } + + /// Discovers the files of the globs, in order, and opens the first. + async fn discover(self) -> VortexResult<(VortexFile, Vec<(FileListing, FileSystemRef)>)> { if self.glob_sources.is_empty() { vortex_bail!("MultiFileDataSource requires at least one glob pattern"); } @@ -173,35 +227,35 @@ impl MultiFileDataSource { let (first_file_listing, first_fs) = &all_files[0]; let open_fn = self.open_options_fn.as_ref(); let first_file = open_file(first_fs, first_file_listing, &self.session, open_fn).await?; - let first_reader = first_file.layout_reader()?; - - let byte_sizes: Vec> = all_files.iter().map(|(file, _)| file.size).collect(); - - let factories: Vec> = all_files[1..] - .iter() - .map(|(file, fs)| { - Arc::new(VortexFileReaderFactory { - fs: Arc::clone(fs), - file: file.clone(), - session: self.session.clone(), - open_options_fn: Arc::clone(&self.open_options_fn), - }) as Arc - }) - .collect(); - - let inner = MultiLayoutDataSource::new_with_first( - first_reader, - factories, - byte_sizes, - &self.session, - ); - - debug!(file_count, dtype = %inner.dtype(), "built MultiFileDataSource"); - - Ok(inner) + Ok((first_file, all_files)) } } +/// The layout reader source over `all_files`, whose first is open as `first_file`. +fn layout_source( + session: &VortexSession, + open_options_fn: &OpenOptionsFn, + first_file: &VortexFile, + all_files: &[(FileListing, FileSystemRef)], +) -> VortexResult { + let first_reader = first_file.layout_reader()?; + let byte_sizes: Vec> = all_files.iter().map(|(file, _)| file.size).collect(); + let factories: Vec> = all_files[1..] + .iter() + .map(|(file, fs)| { + Arc::new(VortexFileReaderFactory { + fs: Arc::clone(fs), + file: file.clone(), + session: session.clone(), + open_options_fn: Arc::clone(open_options_fn), + }) as Arc + }) + .collect(); + let inner = MultiLayoutDataSource::new_with_first(first_reader, factories, byte_sizes, session); + debug!(file_count = all_files.len(), dtype = %inner.dtype(), "built MultiFileDataSource"); + Ok(inner) +} + /// Creates a local filesystem backed by `object_store::local::LocalFileSystem`. // TODO(ngates): create a native file system without an object_store dependency. // Turns out it's not a trivial change because we have always used object_store with its own @@ -297,6 +351,28 @@ impl LayoutReaderFactory for VortexFileReaderFactory { } } +/// A [`DeferredPlanChild`] that opens a single Vortex file when a scan reaches it. +struct DeferredVortexFile { + fs: FileSystemRef, + file: FileListing, + session: VortexSession, + open_options_fn: OpenOptionsFn, +} + +#[async_trait] +impl DeferredPlanChild for DeferredVortexFile { + async fn expand(&self) -> VortexResult> { + let file = open_file( + &self.fs, + &self.file, + &self.session, + self.open_options_fn.as_ref(), + ) + .await?; + Ok(vec![PlanSourceChild::Ready(file.plan_child())]) + } +} + #[cfg(test)] mod tests { use std::fmt; 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 111abcf6745..1ceb7dd355a 100644 --- a/vortex-file/src/tests.rs +++ b/vortex-file/src/tests.rs @@ -121,6 +121,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_session::registry::Id; @@ -2595,6 +2598,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(()) +}