diff --git a/vortex-file/src/file.rs b/vortex-file/src/file.rs index 0b1c3ccdfcc..d3c1b9288f6 100644 --- a/vortex-file/src/file.rs +++ b/vortex-file/src/file.rs @@ -14,6 +14,7 @@ use itertools::Itertools; use vortex_array::ArrayRef; use vortex_array::dtype::DType; use vortex_array::dtype::FieldMask; +use vortex_array::expr::BoundExpression; use vortex_array::expr::Expression; use vortex_buffer::ByteBuffer; use vortex_error::VortexResult; @@ -21,6 +22,7 @@ use vortex_layout::LayoutReader; use vortex_layout::scan::layout::LayoutReaderDataSource; use vortex_layout::scan::metrics::ScanUsage; use vortex_layout::scan::scan_builder::ScanBuilder; +use vortex_layout::scan::scan_builder::referenced_field_masks; use vortex_layout::scan::split_by::SplitBy; use vortex_layout::scan::v2::ScanFile; use vortex_layout::segments::SegmentSource; @@ -28,6 +30,8 @@ use vortex_layout::segments::UsageSegmentSource; use vortex_scan::DataSourceRef; use vortex_scan::prepare::ScanCache; use vortex_scan::prepare::SegmentLocation; +use vortex_scan::source::PlanChild; +use vortex_scan::source::PlanDataSource; use vortex_session::VortexSession; use vortex_utils::aliases::hash_map::HashMap; @@ -116,7 +120,8 @@ impl VortexFile { /// /// Repeated calls to [`layout_reader`](Self::layout_reader), [`scan`](Self::scan), and /// [`data_source`](Self::data_source) will share the same reader tree. Repeated V2 scans of - /// [`scan_file`](Self::scan_file) will share its segment locations and a [`ScanCache`]. + /// [`scan_file`](Self::scan_file), and so of the plan data sources, will share its segment + /// locations and a [`ScanCache`]. pub fn with_caching(self) -> Self { let scan_cache = FileScanCache { locations: self.footer.segment_locations(), @@ -245,18 +250,70 @@ impl VortexFile { /// Create a [`DataSource`](vortex_scan::DataSource) from this file for scanning. /// - /// Wraps the file's layout reader with [`FileStatsLayoutReader`] (when file-level - /// statistics are available) and [`LayoutReaderDataSource`]. Stored footer aggregates are - /// available through the source statistics methods without reading payloads. + /// Scans run on the file's [layout reader](Self::layout_reader), as with + /// [`layout_reader_data_source`](Self::layout_reader_data_source). Stored footer aggregates + /// are available through the source statistics methods without reading payloads. pub fn data_source(&self) -> VortexResult { - let reader = self.layout_reader()?; + self.layout_reader_data_source() + } + /// Create a [`DataSource`](vortex_scan::DataSource) that scans this file with its + /// [layout reader](Self::layout_reader), whatever its layouts. + /// + /// Use [`data_source`](Self::data_source) unless the layout reader is required, for example + /// to compare it with [`plan_data_source`](Self::plan_data_source). Stored footer aggregates + /// are available through the source statistics methods without reading payloads. + pub fn layout_reader_data_source(&self) -> VortexResult { + let reader = self.layout_reader()?; Ok(Arc::new(FileDataSource::new( LayoutReaderDataSource::new(reader, self.session.clone()), self.file_stats().cloned(), ))) } + /// Create a [`DataSource`](vortex_scan::DataSource) from this file whose scans run on the + /// planner-driven executor. + /// + /// The source is a [`PlanDataSource`] over [`plan_child`](Self::plan_child). Every scan of + /// the source shares one [`ScanCache`]: the file's, with [caching](Self::with_caching), or else + /// one of its own. A scan whose filter the file-level statistics prove false reads nothing. + /// Stored footer aggregates are available through the source statistics methods. Opening the + /// source reads nothing and builds no layout reader. + pub fn plan_data_source(&self) -> DataSourceRef { + let source = PlanDataSource::from_child(self.session.clone(), self.plan_child()); + Arc::new(FileDataSource::new(source, self.file_stats().cloned())) + } + + /// This file as a child of a [`PlanDataSource`]: its V2 scan input, row count, and a pruner + /// that skips scans whose filter the file-level statistics prove false. + /// + /// An opened scan of the child cuts its work on the file's layout splits over the fields it + /// reads, as a V1 scan of the same fields does. + pub fn plan_child(&self) -> PlanChild { + let splitter = { + let file = self.clone(); + Arc::new( + move |projection: &BoundExpression, filter: Option<&BoundExpression>| { + SplitBy::default().splits( + file.layout_reader()?.as_ref(), + &(0..file.row_count()), + &referenced_field_masks(projection, filter)?, + ) + }, + ) + }; + let file = PlanChild::new(self.scan_file().into()) + .with_row_count(self.row_count()) + .with_splitter(splitter); + let Some(statistics) = self.file_stats().cloned() else { + return file; + }; + let (row_count, session) = (self.row_count(), self.session.clone()); + file.with_pruner(Arc::new(move |filter| { + is_falsified_by_file_stats(filter, row_count, &statistics, &session) + })) + } + /// Initiate a scan of the file, returning a builder for projection, filtering, selection, and /// execution options. pub fn scan(&self) -> VortexResult> { diff --git a/vortex-file/src/lib.rs b/vortex-file/src/lib.rs index c6a5d9337bc..b628559e3ba 100644 --- a/vortex-file/src/lib.rs +++ b/vortex-file/src/lib.rs @@ -109,6 +109,8 @@ pub mod flatbuffers; mod footer; pub mod multi; mod open; +#[cfg(test)] +mod plan_tests; mod pruning; /// Segment sources, caches, and sinks used by file readers and writers. pub mod segments; diff --git a/vortex-file/src/plan_tests.rs b/vortex-file/src/plan_tests.rs new file mode 100644 index 00000000000..2f63173d7e8 --- /dev/null +++ b/vortex-file/src/plan_tests.rs @@ -0,0 +1,350 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Plan data sources read through the Scan API's `split` and `open`, over real files whose +//! segments are read through the session's I/O. + +use std::num::NonZeroUsize; +use std::ops::Range; +use std::sync::Arc; +use std::sync::LazyLock; +use std::sync::atomic::AtomicU32; +use std::sync::atomic::Ordering; + +use futures::FutureExt; +use futures::TryStreamExt; +use futures::future::BoxFuture; +use rstest::rstest; +use vortex_array::ArrayRef; +use vortex_array::IntoArray; +use vortex_array::VortexSessionExecute; +use vortex_array::arrays::PrimitiveArray; +use vortex_array::arrays::StructArray; +use vortex_array::buffer::BufferHandle; +use vortex_array::dtype::DType; +use vortex_array::dtype::Nullability; +use vortex_array::dtype::PType; +use vortex_array::expr::Expression; +use vortex_array::expr::get_item; +use vortex_array::expr::gt; +use vortex_array::expr::lit; +use vortex_array::expr::root; +use vortex_array::scalar_fn::builtin::operators::CompareOperator; +use vortex_buffer::Alignment; +use vortex_buffer::Buffer; +use vortex_buffer::ByteBuffer; +use vortex_buffer::ByteBufferMut; +use vortex_error::VortexResult; +use vortex_error::vortex_err; +use vortex_functions::expr::dynamic; +use vortex_io::VortexReadAt; +use vortex_io::session::RuntimeSession; +use vortex_layout::scan::scan_builder::ScanBuilder; +use vortex_layout::session::LayoutSession; +use vortex_scan::DataSourceRef; +use vortex_scan::ScanRequest; +use vortex_scan::source::PlanDataSource; +use vortex_scan::stream::ScanExec; +use vortex_scan::stream::ScanStream; +use vortex_session::VortexSession; + +use crate::OpenOptionsSessionExt; +use crate::VortexFile; +use crate::WriteOptionsSessionExt; +use crate::multi::MultiFileSession; + +static SESSION: LazyLock = LazyLock::new(|| { + let session = VortexSession::empty() + .with::() + .with::() + .with::(); + crate::register_default_encodings(&session); + crate::enable_all_registered_array_encodings(&session); + session +}); + +/// The rows of a one-file source: several parts of the scan, filtered or not. +const ROWS: u32 = 600_000; + +/// The `m` value of row `n`: scrambled, so the column does not compress away and its segments +/// are read during the scan rather than with the footer. +fn scramble(n: u32) -> u32 { + n.wrapping_mul(2_654_435_761) +} + +const THRESHOLD: u32 = u32::MAX / 2; + +/// The filter of filtered cases, which keeps about half of the rows and, with the `n` +/// projection, makes the scan read two columns. +fn m_filter() -> Expression { + gt(get_item("m", root()), lit(THRESHOLD)) +} + +/// The values of `n` in `rows` that a scan returns, with [`m_filter`] when `filtered`. +fn expected(rows: Range, filtered: bool) -> Vec { + rows.filter(|&n| !filtered || scramble(n) > THRESHOLD) + .collect() +} + +/// A file of an `n` column holding `values` and an `m` column of their scrambles. +async fn file_bytes(values: Range) -> VortexResult { + let m = Buffer::from_iter(values.clone().map(scramble)).into_array(); + let array = + StructArray::from_fields(&[("n", Buffer::from_iter(values).into_array()), ("m", m)])? + .into_array(); + let mut buf = ByteBufferMut::empty(); + SESSION + .write_options() + .write(&mut buf, array.to_array_stream()) + .await?; + Ok(buf.freeze()) +} + +/// A reader of in-memory bytes whose reads pend once before they complete, as storage reads do. +#[derive(Clone)] +struct YieldingRead(ByteBuffer); + +impl VortexReadAt for YieldingRead { + fn concurrency(&self) -> usize { + self.0.concurrency() + } + + fn size(&self) -> BoxFuture<'static, VortexResult> { + self.0.size() + } + + fn read_at( + &self, + offset: u64, + length: usize, + alignment: Alignment, + ) -> BoxFuture<'static, VortexResult> { + let read = self.0.read_at(offset, length, alignment); + async move { + tokio::task::yield_now().await; + read.await + } + .boxed() + } +} + +async fn open_one_file() -> VortexResult { + SESSION + .open_options() + .open_read(YieldingRead(file_bytes(0..ROWS).await?)) + .await +} + +async fn one_file() -> VortexResult { + Ok(open_one_file().await?.plan_data_source()) +} + +fn n() -> Expression { + get_item("n", root()) +} + +fn request(ordered: bool) -> ScanRequest { + ScanRequest { + projection: n(), + ordered, + ..Default::default() + } +} + +async fn values(stream: ScanStream) -> VortexResult> { + let arrays: Vec = stream.try_collect().await?; + let mut ctx = SESSION.create_execution_ctx(); + let mut values = Vec::new(); + for array in arrays { + values.extend_from_slice(array.execute::(&mut ctx)?.as_slice::()); + } + Ok(values) +} + +/// Reads `exec` with `workers` streams, each polled on a task of its own. +async fn read_stream(exec: ScanExec, workers: usize) -> VortexResult>> { + let tasks: Vec<_> = (0..workers) + .map(|_| tokio::spawn(values(exec.stream()))) + .collect(); + let mut out = Vec::with_capacity(workers); + for task in tasks { + out.push( + task.await + .map_err(|err| vortex_err!("worker task failed: {err}"))??, + ); + } + Ok(out) +} + +fn sorted(workers: Vec>) -> Vec { + let mut all: Vec = workers.into_iter().flatten().collect(); + all.sort_unstable(); + all +} + +/// The streams of an unordered scan together read every selected row once. +#[rstest] +#[case::projection(false)] +#[case::filter(true)] +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[cfg_attr(miri, ignore)] +async fn open_reads_every_row_once(#[case] filtered: bool) -> VortexResult<()> { + let source = one_file().await?; + let scan = source + .scan(ScanRequest { + filter: filtered.then(m_filter), + ..request(false) + }) + .await?; + let workers = read_stream(scan.open()?, 4).await?; + assert_eq!(sorted(workers), expected(0..ROWS, filtered)); + Ok(()) +} + +/// A child's splits are its parts, each of several chunks, and the workers read every row of them once. +#[rstest] +#[case::unordered(false, false)] +#[case::unordered_filter(false, true)] +#[case::ordered(true, false)] +#[case::ordered_filter(true, true)] +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[cfg_attr(miri, ignore)] +async fn open_cuts_parts_on_file_splits( + #[case] ordered: bool, + #[case] filtered: bool, +) -> VortexResult<()> { + let file = open_one_file().await?; + let splits: Arc<[u64]> = Arc::from([0, 150_000, 400_000, u64::from(ROWS)]); + let source: DataSourceRef = Arc::new(PlanDataSource::from_child( + SESSION.clone(), + file.plan_child().with_splits(splits), + )); + let scan = source + .scan(ScanRequest { + filter: filtered.then(m_filter), + ..request(ordered) + }) + .await?; + let workers = read_stream(scan.open()?, 3).await?; + if ordered { + let reader = workers.iter().find(|values| !values.is_empty()); + assert_eq!(reader, Some(&expected(0..ROWS, filtered))); + } else { + // Each worker returns its parts' rows in order within each part. + assert_eq!(sorted(workers), expected(0..ROWS, filtered)); + } + Ok(()) +} + +/// A file's parts are its layout splits over the fields the scan reads, as a V1 scan of the same +/// fields cuts it: no batch of an unordered scan crosses one. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[cfg_attr(miri, ignore)] +async fn open_cuts_parts_on_layout_splits() -> VortexResult<()> { + let file = open_one_file().await?; + let splits = ScanBuilder::new(SESSION.clone(), file.layout_reader()?) + .with_projection(n().bind(file.dtype())?) + .full_file_splits()?; + assert!(splits.len() > 2, "the file has several layout splits"); + + // One worker takes the parts in row order and finishes each before the next. + let scan = file.plan_data_source().scan(request(false)).await?; + let arrays: Vec = scan.open()?.stream().try_collect().await?; + let mut boundaries = vec![0u64]; + for array in &arrays { + let end = boundaries.last().copied().unwrap_or(0) + array.len() as u64; + boundaries.push(end); + } + for split in splits { + assert!( + boundaries.contains(&split), + "a batch crosses layout split {split}" + ); + } + Ok(()) +} + +/// A dynamic filter, such as a top-N's bound, prunes a file as a whole when the scan is made, +/// before its parts are cut. The rows follow the bound as it stands when the streams read, not as +/// it stood when the scan was made. +#[rstest] +#[case::unordered(false)] +#[case::ordered(true)] +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[cfg_attr(miri, ignore)] +async fn scan_prunes_the_file_first_for_a_dynamic_filter( + #[case] ordered: bool, +) -> VortexResult<()> { + let bound = Arc::new(AtomicU32::new(0)); + let value = Arc::clone(&bound); + let filter = dynamic( + CompareOperator::Gt, + move || Some(value.load(Ordering::Relaxed).into()), + DType::Primitive(PType::U32, Nullability::NonNullable), + true, + n(), + ); + let scan = one_file() + .await? + .scan(ScanRequest { + filter: Some(filter), + ..request(ordered) + }) + .await?; + let stream = scan.open()?; + bound.store(ROWS - 10, Ordering::Relaxed); + assert_eq!( + sorted(read_stream(stream, 3).await?), + (ROWS - 9..ROWS).collect::>() + ); + Ok(()) +} + +/// An ordered scan gives all of its rows, in order, to its first stream. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[cfg_attr(miri, ignore)] +async fn ordered_open_reads_in_order_on_one_stream() -> VortexResult<()> { + let source = one_file().await?; + let mut workers = read_stream(source.scan(request(true)).await?.open()?, 3).await?; + workers.sort_by_key(|values| std::cmp::Reverse(values.len())); + assert_eq!(workers[0], (0..ROWS).collect::>()); + assert!(workers[1..].iter().all(Vec::is_empty)); + Ok(()) +} + +/// A scan's limit holds across its streams; an ordered scan returns the first rows. +#[rstest] +#[case::unordered(false, false)] +#[case::unordered_filter(false, true)] +#[case::ordered(true, false)] +#[case::ordered_filter(true, true)] +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[cfg_attr(miri, ignore)] +async fn open_applies_the_limit(#[case] ordered: bool, #[case] filtered: bool) -> VortexResult<()> { + const LIMIT: usize = 150_000; + let rows = expected(0..ROWS, filtered); + let source = one_file().await?; + let scan = source + .scan(ScanRequest { + filter: filtered.then(m_filter), + limit: Some(LIMIT as u64), + ..request(ordered) + }) + .await?; + // A limit holds across the whole scan, so a limited scan is not split. + let scan = { + let mut pieces = scan.split(NonZeroUsize::new(4).unwrap_or(NonZeroUsize::MIN))?; + assert_eq!(pieces.len(), 1); + pieces.remove(0) + }; + let workers = read_stream(scan.open()?, 3).await?; + if ordered { + let reader = workers.iter().find(|values| !values.is_empty()); + assert_eq!(reader.map(Vec::as_slice), Some(&rows[..LIMIT])); + } + let all = sorted(workers); + assert_eq!(all.len(), LIMIT); + all.windows(2).for_each(|w| assert!(w[0] < w[1])); + assert!(all.iter().all(|value| rows.binary_search(value).is_ok())); + Ok(()) +} diff --git a/vortex-file/src/source.rs b/vortex-file/src/source.rs index 1088a61de88..713278b20d9 100644 --- a/vortex-file/src/source.rs +++ b/vortex-file/src/source.rs @@ -9,7 +9,6 @@ use vortex_array::expr::stats::Precision; use vortex_array::scalar::Scalar; use vortex_array::stats::StatsSet; use vortex_error::VortexResult; -use vortex_layout::scan::layout::LayoutReaderDataSource; use vortex_scan::DataSource; use vortex_scan::DataSourceScanRef; use vortex_scan::PartitionRef; @@ -18,19 +17,20 @@ use vortex_session::VortexSession; use crate::FileStatistics; -pub(crate) struct FileDataSource { - source: LayoutReaderDataSource, +/// A file's scans with the statistics of its footer. +pub(crate) struct FileDataSource { + source: S, statistics: Option, } -impl FileDataSource { - pub(crate) fn new(source: LayoutReaderDataSource, statistics: Option) -> Self { +impl FileDataSource { + pub(crate) fn new(source: S, statistics: Option) -> Self { Self { source, statistics } } } #[async_trait] -impl DataSource for FileDataSource { +impl DataSource for FileDataSource { fn dtype(&self) -> &DType { self.source.dtype() } diff --git a/vortex-file/src/tests.rs b/vortex-file/src/tests.rs index 1f333470f3b..64987188dcc 100644 --- a/vortex-file/src/tests.rs +++ b/vortex-file/src/tests.rs @@ -122,6 +122,9 @@ use vortex_layout::scan::scan_builder::ScanBuilder; use vortex_layout::scan::split_by::DEFAULT_MAX_SPLIT_ROWS; use vortex_layout::scan::split_by::SplitBy; use vortex_layout::session::LayoutSession; +use vortex_scan::DataSourceRef; +use vortex_scan::PartitionRef; +use vortex_scan::ScanRequest; use vortex_scan::strict_sorted_buffer::StrictSortedBuffer; use vortex_session::VortexSession; use vortex_zigzag::ZigZag; @@ -2646,6 +2649,65 @@ async fn file_data_source_returns_mergeable_partials() -> VortexResult<()> { Ok(()) } +/// Scans `source` and concatenates the rows of all its partitions, returning how many partitions +/// the scan had. +async fn scan_source( + source: &DataSourceRef, + request: ScanRequest, +) -> VortexResult<(usize, ArrayRef)> { + let scan = source.scan(request).await?; + let dtype = scan.dtype().clone(); + let partitions: Vec = scan.partitions().try_collect().await?; + let partition_count = partitions.len(); + let mut chunks = Vec::new(); + for partition in partitions { + chunks.push(partition.execute()?.read_all().await?); + } + Ok(( + partition_count, + ChunkedArray::try_new(chunks, dtype)?.into_array(), + )) +} + +/// Both of a file's executors are reachable through the Scan API and read the same rows. +#[rstest] +#[case::plan(false)] +#[case::layout_reader(true)] +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[cfg_attr(miri, ignore)] +async fn file_sources_scan_with_either_executor(#[case] layout_reader: bool) -> VortexResult<()> { + let array = StructArray::from_fields(&[("numbers", buffer![1u32, 2, 3, 4, 5].into_array())])? + .into_array(); + let mut buf = ByteBufferMut::empty(); + SESSION + .write_options() + .write(&mut buf, array.to_array_stream()) + .await?; + let file = SESSION.open_options().open_buffer(buf)?; + let source = if layout_reader { + file.layout_reader_data_source()? + } else { + file.plan_data_source() + }; + + let (_, actual) = scan_source( + &source, + ScanRequest { + projection: get_item("numbers", root()), + filter: Some(gt(get_item("numbers", root()), lit(3u32))), + ordered: true, + ..Default::default() + }, + ) + .await?; + assert_arrays_eq!( + actual, + buffer![4u32, 5].into_array(), + &mut SESSION.create_execution_ctx() + ); + Ok(()) +} + #[tokio::test] async fn test_writer_with_statistics() -> VortexResult<()> { let array = StructArray::from_fields(&[("numbers", buffer![1u32, 2, 3, 4, 5].into_array())])? diff --git a/vortex-file/src/v2/scan/tests.rs b/vortex-file/src/v2/scan/tests.rs index 6b3b030b971..7235c566165 100644 --- a/vortex-file/src/v2/scan/tests.rs +++ b/vortex-file/src/v2/scan/tests.rs @@ -14,16 +14,25 @@ use vortex_array::VortexSessionExecute; use vortex_array::arrays::ChunkedArray; use vortex_array::arrays::StructArray; use vortex_array::arrays::VarBinArray; +use vortex_array::assert_arrays_eq; +use vortex_array::expr::get_item; +use vortex_array::expr::gt; +use vortex_array::expr::lit; +use vortex_array::expr::root; +use vortex_array::expr::stats::Precision; use vortex_arrow::ArrowScanExt; use vortex_arrow::ArrowSessionExt; use vortex_arrow::ExecuteArrowExt; use vortex_buffer::ByteBufferMut; use vortex_buffer::buffer; +use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_io::runtime::tokio::TokioRuntime; use vortex_io::session::RuntimeSession; use vortex_layout::scan::v2::ScanBuilder; use vortex_layout::session::LayoutSession; +use vortex_scan::PartitionRef; +use vortex_scan::ScanRequest; use vortex_session::VortexSession; use super::ScanDriver; @@ -93,3 +102,48 @@ async fn record_batches_match_arrays() -> VortexResult<()> { assert_eq!(given, expected); Ok(()) } + +/// A file's plan data source scans the rows the request asks for, as a V2 scan built from +/// the file directly does. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn plan_data_source_scans_like_the_file() -> VortexResult<()> { + let file = file().await?; + let source = file.plan_data_source(); + assert_eq!(source.row_count(), Precision::exact(file.row_count())); + + let request = || ScanRequest { + projection: get_item("numbers", root()), + filter: Some(gt(get_item("numbers", root()), lit(4))), + row_range: Some(4..28), + ordered: true, + ..Default::default() + }; + let dtype = file.dtype().clone(); + let expected = ScanBuilder::new(SESSION.clone(), file.scan_file()) + .with_projection(request().projection.bind(&dtype)?) + .with_some_filter(request().filter.map(|f| f.bind(&dtype)).transpose()?) + .with_row_range(4..28); + let scan_dtype = expected.dtype().clone(); + let collect = |arrays: Vec| ChunkedArray::try_new(arrays, scan_dtype.clone()); + let expected = collect(driver().run(expected).try_collect().await?)?; + + let partitions: Vec = source + .scan(request()) + .await? + .partitions() + .try_collect() + .await?; + assert_eq!(partitions.len(), 1); + let executed = collect( + partitions + .into_iter() + .next() + .vortex_expect("one partition") + .execute()? + .try_collect() + .await?, + )?; + assert_arrays_eq!(executed, expected, &mut SESSION.create_execution_ctx()); + + Ok(()) +}