diff --git a/vortex-file/src/file.rs b/vortex-file/src/file.rs index 6f27eaa0eb6..c5fbb61cb68 100644 --- a/vortex-file/src/file.rs +++ b/vortex-file/src/file.rs @@ -19,6 +19,7 @@ use vortex_buffer::ByteBuffer; use vortex_error::VortexResult; use vortex_io::request::SegmentReader; use vortex_layout::LayoutReader; +use vortex_layout::layouts::list::List; use vortex_layout::scan::layout::LayoutReaderDataSource; use vortex_layout::scan::metrics::ScanUsage; use vortex_layout::scan::scan_builder::ScanBuilder; @@ -29,6 +30,7 @@ use vortex_layout::segments::UsageSegmentSource; use vortex_scan::DataSourceRef; use vortex_scan::prepare::ScanCache; use vortex_scan::prepare::SegmentLocation; +use vortex_scan::source::PlanDataSource; use vortex_session::VortexSession; use vortex_utils::aliases::hash_map::HashMap; @@ -72,6 +74,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. +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, @@ -124,9 +149,10 @@ impl VortexFile { /// Enable layout reader and V2 scan caching. /// - /// 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`]. + /// Repeated calls to [`layout_reader`](Self::layout_reader) and [`scan`](Self::scan), and to + /// [`data_source`](Self::data_source) for a file it scans with the layout reader, will share the + /// same reader tree. Repeated V2 scans of [`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(), @@ -257,18 +283,70 @@ impl VortexFile { /// Create a [`DataSource`](vortex_scan::DataSource) from this file for scanning. /// - /// Wraps the file's layout reader with [`FileStatsLayoutReader`] (when file-level - /// statistics are available) and [`LayoutReaderDataSource`]. Stored footer aggregates are - /// available through the source statistics methods without reading payloads. + /// Scans run on the planner-driven executor, as with + /// [`plan_data_source`](Self::plan_data_source), unless the file has a layout that + /// executor cannot read yet. Such files are scanned on the layout reader instead, as with + /// [`layout_reader_data_source`](Self::layout_reader_data_source). Either way, a scan whose + /// filter the file-level statistics prove false reads nothing, and stored footer aggregates + /// are available through the source statistics methods without reading payloads. pub fn data_source(&self) -> VortexResult { - let reader = self.layout_reader()?; + if self.planned_scan_supported()? { + return Ok(self.plan_data_source()); + } + 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(), ))) } + /// Whether the planner-driven executor can scan this file, which + /// [`data_source`](Self::data_source) uses to choose its executor. + /// + /// The planner-driven executor cannot read list layouts yet (tracked with making it the + /// default in #11502), so files that contain one are scanned by the layout reader instead. The + /// layout tree is only walked when the file's dtype could hold a list layout. + pub(crate) fn planned_scan_supported(&self) -> VortexResult { + if !may_contain_list_layout(self.dtype()) { + return Ok(true); + } + for layout in self.footer.layout().depth_first_traversal() { + if layout?.is::() { + return Ok(false); + } + } + Ok(true) + } + + /// Create a [`DataSource`](vortex_scan::DataSource) from this file whose scans run on the + /// planner-driven executor. + /// + /// A scan has 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 has no partitions. 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::new(self.session.clone(), self.scan_file().into()) + .with_row_count(self.row_count()); + Arc::new( + FileDataSource::new(source, self.file_stats().cloned()) + .with_file_pruning(self.row_count(), self.session.clone()), + ) + } + /// 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/source.rs b/vortex-file/src/source.rs index 1088a61de88..84d5c121718 100644 --- a/vortex-file/src/source.rs +++ b/vortex-file/src/source.rs @@ -2,35 +2,79 @@ // SPDX-FileCopyrightText: Copyright the Vortex contributors use async_trait::async_trait; +use futures::StreamExt; +use futures::stream; use vortex_array::aggregate_fn::AggregateFnRef; use vortex_array::dtype::DType; use vortex_array::dtype::FieldPath; +use vortex_array::expr::Expression; 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::DataSourceScan; use vortex_scan::DataSourceScanRef; use vortex_scan::PartitionRef; +use vortex_scan::PartitionStream; use vortex_scan::ScanRequest; use vortex_session::VortexSession; use crate::FileStatistics; +use crate::pruning::is_falsified_by_file_stats; -pub(crate) struct FileDataSource { - source: LayoutReaderDataSource, +/// A file's scans with the statistics of its footer. +pub(crate) struct FileDataSource { + source: S, statistics: Option, + /// Set when the inner source does not prune with the file's statistics itself. + pruning: Option, } -impl FileDataSource { - pub(crate) fn new(source: LayoutReaderDataSource, statistics: Option) -> Self { - Self { source, statistics } +/// What [`FileDataSource`] needs to prove a scan's filter false over the whole file. +struct FilePruning { + row_count: u64, + session: VortexSession, +} + +impl FileDataSource { + pub(crate) fn new(source: S, statistics: Option) -> Self { + Self { + source, + statistics, + pruning: None, + } + } + + /// Skip scans whose filter the file's statistics prove false over all `row_count` rows of + /// the file, before the inner source reads anything. + pub(crate) fn with_file_pruning(mut self, row_count: u64, session: VortexSession) -> Self { + self.pruning = Some(FilePruning { row_count, session }); + self + } + + /// Whether the file's statistics prove `filter` false for every row of the file, and so for + /// every row range of it. + /// + /// A filter that does not bind is not pruned: the inner scan reports the error. + fn is_pruned(&self, filter: Option<&Expression>) -> VortexResult { + let (Some(pruning), Some(statistics), Some(filter)) = + (&self.pruning, &self.statistics, filter) + else { + return Ok(false); + }; + let Ok(filter) = filter + .bind(self.source.dtype()) + .and_then(|filter| filter.optimize_recursive()) + else { + return Ok(false); + }; + is_falsified_by_file_stats(&filter, pruning.row_count, statistics, &pruning.session) } } #[async_trait] -impl DataSource for FileDataSource { +impl DataSource for FileDataSource { fn dtype(&self) -> &DType { self.source.dtype() } @@ -52,7 +96,15 @@ impl DataSource for FileDataSource { } async fn scan(&self, request: ScanRequest) -> VortexResult { - self.source.scan(request).await + let filter = request.filter.clone(); + let scan = self.source.scan(request).await?; + Ok(if self.is_pruned(filter.as_ref())? { + Box::new(PrunedScan { + dtype: scan.dtype().clone(), + }) + } else { + scan + }) } async fn field_statistics(&self, field_path: &FieldPath) -> VortexResult { @@ -84,3 +136,22 @@ impl DataSource for FileDataSource { .map_or(Precision::Absent, Precision::Exact)) } } + +/// A scan of a file whose statistics rule out every row: it has no partitions. +struct PrunedScan { + dtype: DType, +} + +impl DataSourceScan for PrunedScan { + fn dtype(&self) -> &DType { + &self.dtype + } + + fn partition_count(&self) -> Precision { + Precision::exact(0usize) + } + + fn partitions(self: Box) -> PartitionStream { + stream::empty().boxed() + } +} diff --git a/vortex-file/src/tests.rs b/vortex-file/src/tests.rs index 111abcf6745..fb35ccf94fa 100644 --- a/vortex-file/src/tests.rs +++ b/vortex-file/src/tests.rs @@ -113,6 +113,7 @@ use vortex_layout::layouts::buffered::BufferedStrategy; use vortex_layout::layouts::chunked::writer::ChunkedLayoutStrategy; use vortex_layout::layouts::file_stats::AggregateStats; use vortex_layout::layouts::flat::writer::FlatLayoutStrategy; +use vortex_layout::layouts::list::List; use vortex_layout::layouts::struct_::StructStrategy; use vortex_layout::layouts::table::TableStrategy; use vortex_layout::layouts::zoned::LegacyStats; @@ -121,6 +122,9 @@ use vortex_layout::scan::scan_builder::ScanBuilder; use vortex_layout::scan::split_by::DEFAULT_MAX_SPLIT_ROWS; use vortex_layout::scan::split_by::SplitBy; use vortex_layout::session::LayoutSession; +use vortex_scan::DataSourceRef; +use vortex_scan::PartitionRef; +use vortex_scan::ScanRequest; use vortex_scan::strict_sorted_buffer::StrictSortedBuffer; use vortex_session::VortexSession; use vortex_session::registry::Id; @@ -2595,6 +2599,186 @@ 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(()) +} + +/// A file whose statistics rule out a filter is scanned with no partitions, which the layout +/// reader's source never returns, so this also shows the file is scanned on the planner-driven +/// executor. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[cfg_attr(miri, ignore)] +async fn data_source_prunes_files_with_statistics() -> 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() + .with_file_statistics(pruning_aggregate_fns()) + .write(&mut buf, array.to_array_stream()) + .await?; + let file = SESSION.open_options().open_buffer(buf)?; + assert!(file.planned_scan_supported()?); + let source = file.data_source()?; + let request = |filter: Expression| ScanRequest { + projection: get_item("numbers", root()), + filter: Some(filter), + ordered: true, + ..Default::default() + }; + + let pruned = source + .scan(request(gt(get_item("numbers", root()), lit(10u32)))) + .await?; + assert_eq!( + pruned.dtype(), + &DType::Primitive(PType::U32, Nullability::NonNullable) + ); + assert_eq!(pruned.partition_count(), Precision::exact(0usize)); + assert_eq!(pruned.partitions().try_collect::>().await?.len(), 0); + + let (partitions, actual) = + scan_source(&source, request(gt(get_item("numbers", root()), lit(3u32)))).await?; + assert_eq!(partitions, 1); + assert_arrays_eq!( + actual, + buffer![4u32, 5].into_array(), + &mut SESSION.create_execution_ctx() + ); + + // A filter that does not bind is not pruned away: the scan reports the error. + assert!( + source + .scan(request(gt(get_item("missing", root()), lit(10u32)))) + .await + .is_err() + ); + Ok(()) +} + +/// A file with a list layout, which the planner-driven executor cannot read yet, is scanned with +/// the layout reader instead, list column included. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[cfg_attr(miri, ignore)] +async fn data_source_scans_list_layouts_with_the_layout_reader() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let lists = ListArray::try_new( + buffer![1i32, 2, 3, 4, 5, 6].into_array(), + buffer![0u32, 2, 5, 5, 6].into_array(), + Validity::NonNullable, + &mut ctx, + )? + .into_array(); + let array = StructArray::from_fields(&[ + ("numbers", buffer![1i32, 2, 3, 4].into_array()), + ("lists", lists), + ])? + .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 mut has_list_layout = false; + for layout in file.footer().layout().depth_first_traversal() { + has_list_layout |= layout?.is::(); + } + assert!(has_list_layout); + assert!(!file.planned_scan_supported()?); + + let planned = scan_source(&file.plan_data_source(), ScanRequest::default()).await; + let error = planned.expect_err("the planner-driven executor rejects list layouts"); + assert!(error.to_string().contains("vortex.plan.list_pack")); + + let (_, actual) = scan_source(&file.data_source()?, ScanRequest::default()).await?; + assert_arrays_eq!(actual, array, &mut ctx); + Ok(()) +} + +/// A file with list columns but no list layout is scanned on the planner-driven executor. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[cfg_attr(miri, ignore)] +async fn data_source_scans_flat_lists_with_the_planner() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let lists = ListArray::try_new( + buffer![1i32, 2, 3, 4, 5, 6].into_array(), + buffer![0u32, 2, 5, 5, 6].into_array(), + Validity::NonNullable, + &mut ctx, + )? + .into_array(); + let array = StructArray::from_fields(&[("lists", lists)])?.into_array(); + let mut buf = ByteBufferMut::empty(); + SESSION + .write_options() + .with_strategy(Arc::new(FlatLayoutStrategy::default())) + .write(&mut buf, array.to_array_stream()) + .await?; + let file = SESSION.open_options().open_buffer(buf)?; + assert!(file.planned_scan_supported()?); + + let (partitions, actual) = scan_source(&file.data_source()?, ScanRequest::default()).await?; + assert_eq!(partitions, 1); + assert_arrays_eq!(actual, array, &mut 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 16e9b499347..e08e7adb439 100644 --- a/vortex-file/src/v2/scan/tests.rs +++ b/vortex-file/src/v2/scan/tests.rs @@ -19,6 +19,11 @@ use vortex_array::arrays::StructArray; use vortex_array::arrays::VarBinArray; use vortex_array::assert_arrays_eq; use vortex_array::buffer::BufferHandle; +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; @@ -26,6 +31,7 @@ use vortex_buffer::Alignment; use vortex_buffer::ByteBuffer; use vortex_buffer::ByteBufferMut; use vortex_buffer::buffer; +use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_io::VortexReadAt; use vortex_io::runtime::tokio::TokioRuntime; @@ -33,6 +39,8 @@ use vortex_io::session::RuntimeSession; use vortex_layout::scan::v2::ScanBuilder; use vortex_layout::scan::v2::SegmentReader; use vortex_layout::session::LayoutSession; +use vortex_scan::PartitionRef; +use vortex_scan::ScanRequest; use vortex_session::VortexSession; use super::ScanDriver; @@ -162,3 +170,48 @@ async fn placed_files_scan_like_buffered_ones() -> VortexResult<()> { assert_eq!(reads.load(Ordering::Relaxed), opened); Ok(()) } + +/// A file's plan data source scans the rows the request asks for, as a V2 scan built from +/// the file directly does. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn plan_data_source_scans_like_the_file() -> VortexResult<()> { + let file = file().await?; + let source = file.plan_data_source(); + assert_eq!(source.row_count(), Precision::exact(file.row_count())); + + let request = || ScanRequest { + projection: get_item("numbers", root()), + filter: Some(gt(get_item("numbers", root()), lit(4))), + row_range: Some(4..28), + ordered: true, + ..Default::default() + }; + let dtype = file.dtype().clone(); + let expected = ScanBuilder::new(SESSION.clone(), file.scan_file()) + .with_projection(request().projection.bind(&dtype)?) + .with_some_filter(request().filter.map(|f| f.bind(&dtype)).transpose()?) + .with_row_range(4..28); + let scan_dtype = expected.dtype().clone(); + let collect = |arrays: Vec| ChunkedArray::try_new(arrays, scan_dtype.clone()); + let expected = collect(driver().run(expected).try_collect().await?)?; + + let partitions: Vec = source + .scan(request()) + .await? + .partitions() + .try_collect() + .await?; + assert_eq!(partitions.len(), 1); + let executed = collect( + partitions + .into_iter() + .next() + .vortex_expect("one partition") + .execute()? + .try_collect() + .await?, + )?; + assert_arrays_eq!(executed, expected, &mut SESSION.create_execution_ctx()); + + Ok(()) +} diff --git a/vortex-scan/src/execution/driver.rs b/vortex-scan/src/execution/driver.rs index 7a904f80343..fd19cc9f485 100644 --- a/vortex-scan/src/execution/driver.rs +++ b/vortex-scan/src/execution/driver.rs @@ -12,6 +12,7 @@ //! produced the batch, beside the scan's other chunks. use std::future; +use std::num::NonZeroUsize; use std::sync::Arc; use std::task::Poll; @@ -42,6 +43,7 @@ use crate::prepare::ScanBuilder; pub struct ScanDriver { handle: Handle, concurrency: usize, + max_in_flight: Option, ordered: bool, } @@ -54,10 +56,18 @@ impl ScanDriver { Self { handle, concurrency, + max_in_flight: None, ordered, } } + /// Caps the chunks the scan decodes at once, in all, below the per-worker limit. `None` + /// keeps the per-worker limit only. + pub fn with_max_in_flight(mut self, max_in_flight: Option) -> Self { + self.max_in_flight = max_in_flight; + self + } + /// Prepares `builder` where compute runs, composes its planners, and streams their batches. /// Preparation errors are the stream's first item. pub fn run( @@ -101,6 +111,9 @@ impl ScanDriver { let scan = Arc::new(scan); let map_fn: MapFn = Arc::new(map_fn); let in_flight = self.concurrency * get_available_parallelism().unwrap_or(1); + let in_flight = self + .max_in_flight + .map_or(in_flight, |max| in_flight.min(max.get())); let inline = in_flight <= 1; let scope = WorkScope { file_ordinal: 0, diff --git a/vortex-scan/src/source.rs b/vortex-scan/src/source.rs index a335e42d6d0..f4225bc9b6a 100644 --- a/vortex-scan/src/source.rs +++ b/vortex-scan/src/source.rs @@ -1,19 +1,48 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors -//! Source inputs and byte access for scans. +//! Source inputs and byte access for scans, and the [`DataSource`] that scans them. +use std::any::Any; +use std::num::NonZeroUsize; +use std::ops::Range; use std::sync::Arc; +use async_trait::async_trait; +use futures::StreamExt; +use futures::future; +use futures::stream; +use futures::stream::BoxStream; +use vortex_array::ArrayRef; use vortex_array::dtype::DType; +use vortex_array::dtype::FieldPath; +use vortex_array::expr::BoundExpression; +use vortex_array::expr::stats::Precision; +use vortex_array::stats::StatsSet; +use vortex_array::stream::ArrayStreamAdapter; +use vortex_array::stream::ArrayStreamExt; +use vortex_array::stream::SendableArrayStream; +use vortex_error::VortexResult; use vortex_io::request::SegmentReader; pub use vortex_io::segments::SegmentFuture; pub use vortex_io::segments::SegmentId; pub use vortex_io::segments::SegmentSource; +use vortex_io::session::RuntimeSessionExt; +use vortex_session::VortexSession; +use crate::DataSource; +use crate::DataSourceScan; +use crate::DataSourceScanRef; +use crate::Partition; +use crate::PartitionRef; +use crate::PartitionStream; +use crate::ScanRequest; use crate::execution::SegmentLocation; use crate::execution::cache::ScanCache; +use crate::execution::driver::ScanDriver; use crate::plan::LazyPlanRef; +use crate::prepare::ScanBuilder; +use crate::selection::Selection; /// The plan and byte source used to prepare a scan. /// @@ -33,3 +62,249 @@ pub struct ScanInput { /// State shared by repeated scans of this input. pub cache: Option, } + +/// A [`DataSource`] over one [`ScanInput`], scanned by the planner-driven executor. +/// +/// This is the standard way to expose a source that can name its segments, whatever its format: +/// a Vortex file, a Parquet file whose column chunks are placed segments, or any store that can +/// lower its data to plans. Every scan of the source shares the input's [`ScanCache`], so scans +/// that overlap in time plan the input and register its reader once. +/// +/// A scan of the source has one partition covering the request's row range, clamped to the +/// input's rows when the row count is known. The partition has [`index`](Partition::index) 0, so a +/// request's `partition_range` and `partition_selection` either select it or leave the scan with +/// no partitions. +/// +/// The partition's [`execute`](Partition::execute) runs the planner-driven scan of its rows with a +/// [`ScanDriver`] on the session's runtime and applies the request's limit. +#[derive(Clone)] +pub struct PlanDataSource { + session: VortexSession, + input: ScanInput, + row_count: Precision, + byte_size: Precision, +} + +impl PlanDataSource { + /// A source scanning `input` with `session`. Without a cache, the input gets a fresh one that + /// all of the source's scans share. + pub fn new(session: VortexSession, mut input: ScanInput) -> Self { + input.cache.get_or_insert_default(); + Self { + session, + input, + row_count: Precision::Absent, + byte_size: Precision::Absent, + } + } + + /// Sets the exact row count of the input, which scans and partitions report. + pub fn with_row_count(mut self, row_count: u64) -> Self { + self.row_count = Precision::exact(row_count); + self + } + + /// Sets an estimate of the input's byte size. + pub fn with_byte_size(mut self, byte_size: Precision) -> Self { + self.byte_size = byte_size; + self + } + + /// The input this source scans. + pub fn input(&self) -> &ScanInput { + &self.input + } + + /// The session scans of this source run with. + pub fn session(&self) -> &VortexSession { + &self.session + } +} + +#[async_trait] +impl DataSource for PlanDataSource { + fn dtype(&self) -> &DType { + &self.input.dtype + } + + fn row_count(&self) -> Precision { + self.row_count + } + + fn byte_size(&self) -> Precision { + self.byte_size + } + + async fn scan(&self, request: ScanRequest) -> VortexResult { + let projection = request + .projection + .bind(&self.input.dtype)? + .optimize_recursive()?; + let filter = request + .filter + .map(|filter| filter.bind(&self.input.dtype)?.optimize_recursive()) + .transpose()?; + let dtype = projection.dtype().clone(); + let row_range = match (request.row_range, self.row_count.as_exact()) { + (Some(rows), Some(count)) => Some(rows.start.min(count)..rows.end.min(count)), + (rows, _) => rows, + }; + // The source is the single unit 0, so a request that does not select it scans nothing. + let selected = request + .partition_range + .as_ref() + .is_none_or(|range| range.contains(&0)) + && request.partition_selection.row_count_in_range(&(0..1)) == 1; + if !selected || request.limit == Some(0) || row_range.as_ref().is_some_and(Range::is_empty) + { + return Ok(Box::new(PlanScan { + dtype, + partitions: Vec::new(), + })); + } + let partition = PlanPartition { + session: self.session.clone(), + input: self.input.clone(), + row_count: self.row_count, + projection, + filter, + row_range, + selection: request.selection, + ordered: request.ordered, + limit: request.limit, + split_concurrency: request.split_concurrency, + }; + Ok(Box::new(PlanScan { + dtype, + partitions: vec![partition], + })) + } + + async fn field_statistics(&self, _field_path: &FieldPath) -> VortexResult { + Ok(StatsSet::default()) + } +} + +struct PlanScan { + dtype: DType, + partitions: Vec, +} + +impl DataSourceScan for PlanScan { + fn dtype(&self) -> &DType { + &self.dtype + } + + fn partition_count(&self) -> Precision { + Precision::exact(self.partitions.len()) + } + + fn partitions(self: Box) -> PartitionStream { + stream::iter( + self.partitions + .into_iter() + .map(|partition| Ok(Box::new(partition) as PartitionRef)), + ) + .boxed() + } +} + +/// The rows of a [`PlanDataSource`] that one partition of a scan reads. +struct PlanPartition { + session: VortexSession, + input: ScanInput, + row_count: Precision, + projection: BoundExpression, + filter: Option, + row_range: Option>, + selection: Selection, + ordered: bool, + limit: Option, + split_concurrency: Option, +} + +impl PlanPartition { + fn builder(self) -> ScanBuilder { + let mut builder = ScanBuilder::new(self.session, self.input) + .with_projection(self.projection) + .with_some_filter(self.filter) + .with_selection(self.selection); + if let Some(rows) = self.row_range { + builder = builder.with_row_range(rows); + } + builder + } +} + +impl Partition for PlanPartition { + fn as_any(&self) -> &dyn Any { + self + } + + fn index(&self) -> usize { + 0 + } + + fn row_count(&self) -> Precision { + let rows = match (&self.row_range, self.row_count.as_exact()) { + (Some(rows), _) => rows.clone(), + (None, Some(count)) => 0..count, + (None, None) => return Precision::Absent, + }; + let rows = self.selection.row_count_in_range(&rows); + let rows = self.limit.map_or(rows, |limit| rows.min(limit)); + if self.filter.is_some() { + Precision::inexact(rows) + } else { + Precision::exact(rows) + } + } + + fn byte_size(&self) -> Precision { + Precision::Absent + } + + fn execute(self: Box) -> VortexResult { + let dtype = self.projection.dtype().clone(); + let (ordered, limit, max_in_flight) = (self.ordered, self.limit, self.split_concurrency); + let driver = + ScanDriver::new(self.session.handle(), 1, ordered).with_max_in_flight(max_in_flight); + let arrays = driver.run(self.builder()); + let arrays = match limit { + Some(limit) => limit_arrays(arrays, limit), + None => arrays, + }; + Ok(ArrayStreamExt::boxed(ArrayStreamAdapter::new( + dtype, arrays, + ))) + } +} + +/// Ends `arrays` after its first `limit` rows. +fn limit_arrays( + arrays: BoxStream<'static, VortexResult>, + limit: u64, +) -> BoxStream<'static, VortexResult> { + arrays + .scan(limit, |remaining, array| { + if *remaining == 0 { + return future::ready(None); + } + let array = array.and_then(|array| { + let len = array.len() as u64; + if len <= *remaining { + *remaining -= len; + Ok(array) + } else { + let keep = usize::try_from(*remaining).unwrap_or(usize::MAX); + *remaining = 0; + array.slice(0..keep) + } + }); + future::ready(Some(array)) + }) + .boxed() +} + +#[cfg(test)] +mod tests; diff --git a/vortex-scan/src/source/tests.rs b/vortex-scan/src/source/tests.rs new file mode 100644 index 00000000000..ad8c09f6aa9 --- /dev/null +++ b/vortex-scan/src/source/tests.rs @@ -0,0 +1,190 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +use std::ops::Range; +use std::sync::Arc; + +use futures::TryStreamExt; +use roaring::RoaringTreemap; +use rstest::rstest; +use vortex_array::ArrayRef; +use vortex_array::IntoArray; +use vortex_array::VortexSessionExecute; +use vortex_array::arrays::ChunkedArray; +use vortex_array::arrays::PrimitiveArray; +use vortex_array::assert_arrays_eq; +use vortex_array::expr::checked_add; +use vortex_array::expr::gt; +use vortex_array::expr::lit; +use vortex_array::expr::root; +use vortex_array::expr::stats::Precision; +use vortex_buffer::Buffer; +use vortex_error::VortexResult; +use vortex_error::vortex_bail; +use vortex_io::request::SegmentReader; +use vortex_io::session::RuntimeSessionExt; +use vortex_session::VortexSession; + +use super::PlanDataSource; +use super::ScanInput; +use super::SegmentFuture; +use super::SegmentId; +use super::SegmentSource; +use crate::DataSource; +use crate::PartitionRef; +use crate::ScanRequest; +use crate::execution::pipeline::synthetic::RowSource; +use crate::plan::LazyPlanRef; +use crate::selection::Selection; + +struct NoSegments; + +impl SegmentSource for NoSegments { + fn request(&self, _id: SegmentId) -> SegmentFuture { + Box::pin(async { vortex_bail!("an in-memory source must not request bytes") }) + } +} + +fn source() -> PlanDataSource { + source_of(20) +} + +fn source_of(row_count: u64) -> PlanDataSource { + let plan = RowSource::plan(row_count, vec![4, 7, 9], None, false); + let input = ScanInput { + dtype: plan.dtype().clone(), + root: LazyPlanRef::ready(plan), + locations: Arc::new([]), + reader: SegmentReader::Opaque(Arc::new(NoSegments)), + cache: None, + }; + PlanDataSource::new(VortexSession::empty().with_tokio(), input).with_row_count(row_count) +} + +async fn partitions(request: ScanRequest) -> VortexResult> { + partitions_of(&source(), request).await +} + +async fn partitions_of( + source: &PlanDataSource, + request: ScanRequest, +) -> VortexResult> { + source.scan(request).await?.partitions().try_collect().await +} + +async fn collect(partitions: Vec) -> VortexResult { + let dtype = source().dtype().clone(); + let mut arrays = Vec::new(); + for partition in partitions { + let batches: Vec = partition.execute()?.try_collect().await?; + arrays.extend(batches); + } + Ok(ChunkedArray::try_new(arrays, dtype)?.into_array()) +} + +#[rstest] +#[case::unordered(false)] +#[case::ordered(true)] +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn execute_applies_the_request(#[case] ordered: bool) -> VortexResult<()> { + let partitions = partitions(ScanRequest { + projection: checked_add(root(), lit(100_u64)), + filter: Some(gt(root(), lit(5_u64))), + row_range: Some(2..18), + ordered, + ..Default::default() + }) + .await?; + assert_eq!(partitions.len(), 1); + let mut ctx = VortexSession::empty().create_execution_ctx(); + let actual = collect(partitions) + .await? + .execute::(&mut ctx)?; + let mut values = actual.as_slice::().to_vec(); + if !ordered { + values.sort_unstable(); + } + assert_eq!(values, (106_u64..118).collect::>()); + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn execute_applies_the_limit() -> VortexResult<()> { + let partitions = partitions(ScanRequest { + filter: Some(gt(root(), lit(5_u64))), + ordered: true, + limit: Some(5), + ..Default::default() + }) + .await?; + assert_arrays_eq!( + collect(partitions).await?, + Buffer::from_iter(6_u64..11).into_array(), + &mut VortexSession::empty().create_execution_ctx() + ); + Ok(()) +} + +#[tokio::test] +async fn partitions_report_their_rows() -> VortexResult<()> { + let partitions = partitions(ScanRequest { + row_range: Some(4..9), + ..Default::default() + }) + .await?; + assert_eq!(partitions[0].row_count(), Precision::exact(5_u64)); + Ok(()) +} + +#[rstest] +#[case::zero_limit(ScanRequest { limit: Some(0), ..Default::default() })] +#[case::empty_rows(ScanRequest { row_range: Some(30..40), ..Default::default() })] +#[case::other_units(ScanRequest { partition_range: Some(1..4), ..Default::default() })] +#[case::unit_excluded(ScanRequest { + partition_selection: Selection::ExcludeRoaring(RoaringTreemap::from_iter([0_u64])), + ..Default::default() +})] +#[tokio::test] +async fn requests_without_rows_have_no_partitions( + #[case] request: ScanRequest, +) -> VortexResult<()> { + assert!(partitions(request).await?.is_empty()); + Ok(()) +} + +/// The sorted values of every partition's output. +async fn sorted_values(partitions: Vec) -> VortexResult> { + let mut ctx = VortexSession::empty().create_execution_ctx(); + let mut values = collect(partitions) + .await? + .execute::(&mut ctx)? + .as_slice::() + .to_vec(); + values.sort_unstable(); + Ok(values) +} + +/// Selecting the source's unit, by range or by selection, returns its one partition. +#[rstest] +#[case::range(Some(0..1), Selection::All)] +#[case::wide_range(Some(0..5), Selection::All)] +#[case::selection(None, Selection::IncludeRoaring(RoaringTreemap::from_iter([0_u64, 3])))] +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn selecting_the_unit_returns_its_partition( + #[case] partition_range: Option>, + #[case] partition_selection: Selection, +) -> VortexResult<()> { + let partitions = partitions(ScanRequest { + partition_selection, + partition_range, + ..Default::default() + }) + .await?; + assert_eq!(partitions.len(), 1); + assert_eq!(partitions[0].index(), 0); + assert_eq!( + sorted_values(partitions).await?, + (0..20).collect::>() + ); + Ok(()) +}