diff --git a/Cargo.lock b/Cargo.lock index ab273f5e43d..1ffbead0ccc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -12357,6 +12357,7 @@ dependencies = [ name = "vortex-scan" version = "0.1.0" dependencies = [ + "async-channel", "async-lock", "async-trait", "bit-vec 0.10.2", diff --git a/bench-orchestrator/bench_orchestrator/ci_matrix/catalog.py b/bench-orchestrator/bench_orchestrator/ci_matrix/catalog.py index e905cd85c91..a28b2a373c8 100644 --- a/bench-orchestrator/bench_orchestrator/ci_matrix/catalog.py +++ b/bench-orchestrator/bench_orchestrator/ci_matrix/catalog.py @@ -70,7 +70,7 @@ # Vortex targets name an integration (`file`, `datasource`) and a scan engine (`v1`, `v2`); see # `BenchmarkTarget`. Declared targets run the file integration on the suite's default engine. # `ScanCoverage.ALL` adds every other valid combination for the `vortex` format: DataFusion file-v1 and -# datasource-v1 beside file-v2, and DuckDB file-v1 beside file-v2, on V2 suites. Each combination runs +# datasource-v2 and datasource-v1 beside file-v2, and DuckDB file-v1 beside file-v2, on V2 suites. Each combination runs # as a matrix entry, and so a machine, of its own, so covering them all adds machines, not wall time. @@ -108,6 +108,10 @@ def with_all_scans(coverage: Coverage) -> Coverage: BenchmarkTarget(Engine.DATAFUSION, Format.VORTEX, Integration.FILE, ScanEngine.V1), "DataFusion, Vortex, file v1", ), + ( + BenchmarkTarget(Engine.DATAFUSION, Format.VORTEX, Integration.DATASOURCE, ScanEngine.V2), + "DataFusion, Vortex, datasource v2", + ), ( BenchmarkTarget(Engine.DATAFUSION, Format.VORTEX, Integration.DATASOURCE, ScanEngine.V1), "DataFusion, Vortex, datasource v1", diff --git a/bench-orchestrator/bench_orchestrator/config.py b/bench-orchestrator/bench_orchestrator/config.py index 7be6cff9e29..38a4ce09e10 100644 --- a/bench-orchestrator/bench_orchestrator/config.py +++ b/bench-orchestrator/bench_orchestrator/config.py @@ -132,9 +132,7 @@ class Benchmark(Enum): SUPPORTED_SCANS: dict[Engine, dict[Integration, frozenset[ScanEngine]]] = { Engine.DATAFUSION: { Integration.FILE: frozenset({ScanEngine.V1, ScanEngine.V2}), - # `VortexTable` reaches only V1: `MultiFileDataSource` opens `LayoutReader`s. V2 needs the V2 - # scan behind `split`/`open` (#11626). - Integration.DATASOURCE: frozenset({ScanEngine.V1}), + Integration.DATASOURCE: frozenset({ScanEngine.V1, ScanEngine.V2}), }, Engine.DUCKDB: { Integration.FILE: frozenset({ScanEngine.V1, ScanEngine.V2}), @@ -168,11 +166,6 @@ def scan_support_error(engine: Engine, integration: Integration, scan: ScanEngin return "duckdb has no DataSource table function yet, so it has no datasource targets" return f"{engine.value} has no {integration.value} integration" if scan is not None and scan not in integrations[integration]: - if engine is Engine.DATAFUSION and integration is Integration.DATASOURCE and scan is ScanEngine.V2: - return ( - "datafusion datasource targets run only the v1 scan: MultiFileDataSource opens " - "LayoutReaders, and v2 needs the V2 scan behind split/open (#11626)" - ) return f"{engine.value} {integration.value} targets cannot run the {scan.value} scan" return None diff --git a/bench-orchestrator/tests/test_config.py b/bench-orchestrator/tests/test_config.py index f73b8bffaf7..68fa7c33094 100644 --- a/bench-orchestrator/tests/test_config.py +++ b/bench-orchestrator/tests/test_config.py @@ -202,9 +202,9 @@ def test_parse_targets_json_rejects_unknown_axes() -> None: (Engine.DATAFUSION, Integration.FILE, ScanEngine.V1, None), (Engine.DATAFUSION, Integration.FILE, ScanEngine.V2, None), (Engine.DATAFUSION, Integration.DATASOURCE, ScanEngine.V1, None), + (Engine.DATAFUSION, Integration.DATASOURCE, ScanEngine.V2, None), (Engine.DUCKDB, Integration.FILE, ScanEngine.V1, None), (Engine.DUCKDB, Integration.FILE, ScanEngine.V2, None), - (Engine.DATAFUSION, Integration.DATASOURCE, ScanEngine.V2, "datasource targets run only the v1 scan"), (Engine.DUCKDB, Integration.DATASOURCE, ScanEngine.V1, "duckdb has no DataSource table function yet"), (Engine.DUCKDB, Integration.DATASOURCE, ScanEngine.V2, "duckdb has no DataSource table function yet"), ], diff --git a/bench-orchestrator/tests/test_matrix.py b/bench-orchestrator/tests/test_matrix.py index 67abe1b8812..a96f0a487c2 100644 --- a/bench-orchestrator/tests/test_matrix.py +++ b/bench-orchestrator/tests/test_matrix.py @@ -75,6 +75,7 @@ "duckdb-parquet", "duckdb-vortex", "datafusion-vortex-file-v1", + "datafusion-vortex-datasource-v2", "datafusion-vortex-datasource-v1", "duckdb-vortex-file-v1", ) @@ -83,7 +84,7 @@ "tpch-nested-s3", ), } -SCAN_SUFFIXES = ("datafusion-file-v1", "datafusion-datasource-v1", "duckdb-file-v1") +SCAN_SUFFIXES = ("datafusion-file-v1", "datafusion-datasource-v2", "datafusion-datasource-v1", "duckdb-file-v1") def _entries(preset: str) -> list[dict[str, object]]: @@ -121,6 +122,7 @@ def _group_targets(preset: str) -> dict[str, set[tuple[str, str]]]: ("datafusion", "parquet"), ("datafusion", "vortex [file, v2]"), ("datafusion", "vortex [file, v1]"), + ("datafusion", "vortex [datasource, v2]"), ("datafusion", "vortex [datasource, v1]"), ("duckdb", "parquet"), ("duckdb", "vortex [file, v2]"), @@ -197,11 +199,11 @@ def test_tpcds_sf100_runs_one_target_per_job() -> None: entry for entry in _entries("nightly") if str(entry["id"]).startswith("tpcds-") and "-100-" in str(entry["id"]) ] - assert len(nightly) == 14 + assert len(nightly) == 16 assert all(len(_targets(entry)) == 1 for entry in nightly) assert {target for entry in nightly for target in _targets(entry)} == ALL_SCANS s3_keys = [entry["remote_key"] for entry in nightly if "remote_key" in entry] - assert len(s3_keys) == len(set(s3_keys)) == 7 + assert len(s3_keys) == len(set(s3_keys)) == 8 def test_nightly_runs_every_scan() -> None: @@ -251,6 +253,8 @@ def test_nightly_runs_every_valid_scan() -> None: ) if not benchmark_id.startswith("tpch-nested"): expected |= {(engine, "vortex [file, v2]") for engine in engines} + if "datafusion" in engines: + expected.add(("datafusion", "vortex [datasource, v2]")) assert scans == expected, benchmark_id diff --git a/benchmarks/datafusion-bench/src/main.rs b/benchmarks/datafusion-bench/src/main.rs index d5d6d328513..9b140a6ed86 100644 --- a/benchmarks/datafusion-bench/src/main.rs +++ b/benchmarks/datafusion-bench/src/main.rs @@ -30,7 +30,6 @@ use vortex::file::multi::MultiFileDataSource; use vortex::io::filesystem::FileSystemRef; use vortex::io::object_store::ObjectStoreFileSystem; use vortex::io::session::RuntimeSessionExt; -use vortex::scan::DataSource as _; use vortex::scan::DataSourceRef; use vortex_arrow::ArrowSessionExt; use vortex_bench::Benchmark; @@ -125,8 +124,7 @@ struct Args { scan_v1: bool, /// Register Vortex tables through the Scan API (`VortexTable` over a `MultiFileDataSource`) - /// instead of a listing table, whatever `--scan-v1` says. `MultiFileDataSource` runs the V1 - /// scan. + /// instead of a listing table. `--scan-v1` still picks the scan the tables run on. #[arg(long, default_value_t = false, action = clap::ArgAction::Set)] scan_api: bool, @@ -268,7 +266,7 @@ async fn register_benchmark_tables( scan_api: bool, ) -> anyhow::Result<()> { if scan_api && matches!(format, Format::OnDiskVortex | Format::VortexCompact) { - register_v2_tables(session, benchmark, format).await + register_scan_api_tables(session, benchmark, format, scan_v2).await } else { let benchmark_base = benchmark.data_url().join(&format!("{}/", format.name()))?; let file_format = format_to_df_format(format, scan_v2)?; @@ -304,11 +302,16 @@ async fn register_benchmark_tables( } } -/// Register tables using the Scan API path: a `VortexTable` over a `MultiFileDataSource`. -async fn register_v2_tables( +/// Register tables through the Scan API: a `VortexTable` over a `MultiFileDataSource`. +/// +/// With `scan_v2`, the table scans its files on the planner-driven scan through +/// [`MultiFileDataSource::build_plan`], whose files open as the scan reaches them. Otherwise it +/// scans them on layout readers through [`MultiFileDataSource::build`]. +async fn register_scan_api_tables( session: &SessionContext, benchmark: &B, format: Format, + scan_v2: bool, ) -> anyhow::Result<()> { let benchmark_base = benchmark.data_url().join(&format!("{}/", format.name()))?; @@ -332,13 +335,14 @@ async fn register_v2_tables( None => format!("*.{}", format.ext()), }; - let multi_ds = MultiFileDataSource::new(SESSION.clone()) - .with_glob(glob_pattern, Some(fs)) - .build() - .await?; + let builder = MultiFileDataSource::new(SESSION.clone()).with_glob(glob_pattern, Some(fs)); + let data_source: DataSourceRef = if scan_v2 { + builder.build_plan().await? + } else { + Arc::new(builder.build().await?) + }; - let arrow_schema = Arc::new(SESSION.arrow().to_arrow_schema(multi_ds.dtype())?); - let data_source: DataSourceRef = Arc::new(multi_ds); + let arrow_schema = Arc::new(SESSION.arrow().to_arrow_schema(data_source.dtype())?); let table_provider = Arc::new(VortexTable::new(data_source, SESSION.clone(), arrow_schema)); session.register_table(table.name, table_provider)?; diff --git a/vortex-file/src/file.rs b/vortex-file/src/file.rs index f610495f90a..1e584ec7bb7 100644 --- a/vortex-file/src/file.rs +++ b/vortex-file/src/file.rs @@ -14,13 +14,16 @@ 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; 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; +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 +31,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 +73,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, @@ -114,9 +142,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(), @@ -245,18 +274,97 @@ 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. + /// + /// 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. + /// + /// 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 0321127a3d3..48caddbd245 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/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/plan_tests.rs b/vortex-file/src/plan_tests.rs new file mode 100644 index 00000000000..08258fefa20 --- /dev/null +++ b/vortex-file/src/plan_tests.rs @@ -0,0 +1,706 @@ +// 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::fmt; +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 async_trait::async_trait; +use futures::FutureExt; +use futures::StreamExt; +use futures::TryStreamExt; +use futures::future::BoxFuture; +use futures::stream; +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::dynamic; +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_array::scalar_fn::fns::operators::CompareOperator; +use vortex_array::stream::SendableArrayStream; +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_io::VortexReadAt; +use vortex_io::filesystem::FileListing; +use vortex_io::filesystem::FileSystem; +use vortex_io::filesystem::FileSystemRef; +use vortex_io::session::RuntimeSession; +use vortex_layout::scan::scan_builder::ScanBuilder; +use vortex_layout::session::LayoutSession; +use vortex_scan::DataSource; +use vortex_scan::DataSourceRef; +use vortex_scan::DataSourceScanRef; +use vortex_scan::PartitionRef; +use vortex_scan::ScanRequest; +use vortex_scan::pool::ScanPoolRef; +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::WriteOptionsSessionExt; +use crate::multi::MultiFileDataSource; +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: SendableArrayStream) -> 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 `pool` with `workers` workers, each polled on a task of its own, in the order the +/// workers were taken. +async fn read_pool(pool: ScanPoolRef, workers: usize) -> VortexResult>> { + let tasks: Vec<_> = (0..workers) + .map(|_| tokio::spawn(values(Arc::clone(&pool).worker()))) + .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) +} + +/// Reads a scan with one worker of its pool. +async fn read_one(scan: DataSourceScanRef) -> VortexResult> { + values(scan.open()?.worker()).await +} + +fn sorted(workers: Vec>) -> Vec { + let mut all: Vec = workers.into_iter().flatten().collect(); + all.sort_unstable(); + all +} + +/// A pool reports no progress before any worker takes work, and all of it, and exhaustion, once +/// its workers have taken every unit: of one file, or of files opened as they are reached. +#[rstest] +#[case::one_file_unordered(false, false)] +#[case::one_file_ordered(false, true)] +#[case::three_files_unordered(true, false)] +#[case::three_files_ordered(true, true)] +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[cfg_attr(miri, ignore)] +async fn pool_reports_progress_and_exhaustion( + #[case] deferred: bool, + #[case] ordered: bool, +) -> VortexResult<()> { + let source = if deferred { + three_files().await? + } else { + one_file().await? + }; + let pool = source.scan(request(ordered)).await?.open()?; + assert_eq!(pool.progress(), 0.0); + assert!(!pool.is_exhausted()); + + let rows = sorted(read_pool(Arc::clone(&pool), 3).await?); + assert_eq!(rows, (0..ROWS).collect::>()); + assert!(pool.is_exhausted()); + assert!((pool.progress() - 1.0).abs() < 1e-9, "{}", pool.progress()); + Ok(()) +} + +/// Split pieces are contiguous, never empty, and read every row in order. +#[rstest] +#[case::one(1)] +#[case::two(2)] +#[case::seven(7)] +#[case::many(1000)] +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[cfg_attr(miri, ignore)] +async fn split_pieces_cover_all_rows_in_order(#[case] n: usize) -> VortexResult<()> { + let source = one_file().await?; + let scan = source.scan(request(true)).await?; + assert_eq!(scan.row_count(), Precision::exact(u64::from(ROWS))); + let pieces = scan.split(NonZeroUsize::new(n).unwrap_or(NonZeroUsize::MIN))?; + assert!(!pieces.is_empty() && pieces.len() <= n); + if n > 1 { + assert!(pieces.len() > 1); + } + let mut counted = 0; + let mut read = Vec::new(); + for piece in pieces { + let rows = piece.row_count(); + let rows = rows + .as_exact() + .ok_or_else(|| vortex_err!("inexact {rows:?}"))?; + assert!(rows > 0); + counted += rows; + let values = read_one(piece).await?; + assert_eq!(values.len() as u64, rows); + read.extend(values); + } + assert_eq!(counted, u64::from(ROWS)); + assert_eq!(read, (0..ROWS).collect::>()); + Ok(()) +} + +/// The workers of an unordered pool 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), + split_concurrency: NonZeroUsize::new(2), + ..request(false) + }) + .await?; + let workers = read_pool(scan.open()?, 4).await?; + assert_eq!(sorted(workers), expected(0..ROWS, filtered)); + Ok(()) +} + +/// A file's splits are its parts, each of several chunks, which a worker returns in row order. +#[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_pool(scan.open()?, 3).await?; + if ordered { + assert_eq!(workers[0], 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 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"); + + let scan = file.plan_data_source().scan(request(true)).await?; + let arrays: Vec = scan.open()?.worker().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 before its parts are cut, +/// as queued work rather than in `open`. The rows follow the bound as it stands when the workers +/// read, not as it stood when the scan was opened. +#[rstest] +#[case::unordered(false)] +#[case::ordered(true)] +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[cfg_attr(miri, ignore)] +async fn open_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 pool = scan.open()?; + bound.store(ROWS - 10, Ordering::Relaxed); + assert_eq!( + sorted(read_pool(pool, 3).await?), + (ROWS - 9..ROWS).collect::>() + ); + Ok(()) +} + +/// An ordered pool gives all of its rows, in order, to its first worker. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[cfg_attr(miri, ignore)] +async fn ordered_open_reads_in_order_on_the_first_worker() -> VortexResult<()> { + let source = one_file().await?; + let workers = read_pool(source.scan(request(true)).await?.open()?, 3).await?; + assert_eq!(workers[0], (0..ROWS).collect::>()); + assert!(workers[1..].iter().all(Vec::is_empty)); + Ok(()) +} + +/// A pool's limit holds across its workers; an ordered pool 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_pool(scan.open()?, 3).await?; + if ordered { + assert_eq!(workers[0], 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(()) +} + +/// An in-memory file system over named files. +struct MemoryFileSystem { + files: Vec<(String, ByteBuffer)>, +} + +impl fmt::Debug for MemoryFileSystem { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("MemoryFileSystem").finish() + } +} + +impl MemoryFileSystem { + fn file(&self, path: &str) -> Option<&ByteBuffer> { + self.files + .iter() + .find(|(name, _)| name == path) + .map(|(_, bytes)| bytes) + } +} + +#[async_trait] +impl FileSystem for MemoryFileSystem { + fn list(&self, _prefix: &str) -> stream::BoxStream<'_, VortexResult> { + stream::empty().boxed() + } + + async fn head(&self, path: &str) -> VortexResult> { + Ok(self.file(path).map(|bytes| FileListing { + path: path.to_string(), + size: Some(bytes.len() as u64), + })) + } + + async fn open_read(&self, path: &str) -> VortexResult> { + let bytes = self + .file(path) + .ok_or_else(|| vortex_err!("no file {path}"))? + .clone(); + Ok(Arc::new(YieldingRead(bytes))) + } + + async fn delete(&self, _path: &str) -> VortexResult<()> { + Ok(()) + } +} + +/// The values of the files of [`three_files`]. +const FILES: [Range; 3] = [0..200_000, 200_000..400_000, 400_000..600_000]; + +/// A V2 source over three files, of which all but the first are opened during scans. +async fn three_files() -> VortexResult { + let mut files = Vec::new(); + for (i, values) in FILES.into_iter().enumerate() { + files.push((format!("{i}.vortex"), file_bytes(values).await?)); + } + let fs: FileSystemRef = Arc::new(MemoryFileSystem { files }); + let mut builder = MultiFileDataSource::new(SESSION.clone()); + for i in 0..FILES.len() { + builder = builder.with_glob(format!("{i}.vortex"), Some(Arc::clone(&fs))); + } + builder.build_plan().await +} + +/// Deferred files are opened by the workers that take them, and every row of every file is read +/// once. A file the filter rules out by its statistics is skipped. +#[rstest] +#[case::all(false)] +#[case::filter(true)] +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[cfg_attr(miri, ignore)] +async fn open_reads_deferred_files(#[case] filtered: bool) -> VortexResult<()> { + let source = three_files().await?; + assert_eq!(source.row_count(), Precision::inexact(u64::from(ROWS))); + let request = ScanRequest { + filter: filtered.then(m_filter), + ..request(false) + }; + let workers = read_pool(source.scan(request.clone()).await?.open()?, 4).await?; + assert_eq!(sorted(workers), expected(0..ROWS, filtered)); + + // Ordered, the files are read in order. + let ordered = ScanRequest { + ordered: true, + ..request + }; + let workers = read_pool(source.scan(ordered).await?.open()?, 2).await?; + assert_eq!(workers[0], expected(0..ROWS, filtered)); + Ok(()) +} + +/// A multi-file scan splits on files that are not open yet and on the rows of the open one. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[cfg_attr(miri, ignore)] +async fn split_keeps_deferred_files_whole() -> VortexResult<()> { + let source = three_files().await?; + let scan = source.scan(request(true)).await?; + let pieces = scan.split(NonZeroUsize::new(4).unwrap_or(NonZeroUsize::MIN))?; + assert!(pieces.len() > 1 && pieces.len() <= 4); + let mut read = Vec::new(); + for piece in pieces { + let values = read_one(piece).await?; + assert!(!values.is_empty()); + read.extend(values); + } + assert_eq!(read, expected(0..ROWS, false)); + Ok(()) +} + +/// An unordered multi-file limit holds across files and workers. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[cfg_attr(miri, ignore)] +async fn open_limits_across_deferred_files() -> VortexResult<()> { + let source = three_files().await?; + let scan = source + .scan(ScanRequest { + limit: Some(300_000), + ..request(false) + }) + .await?; + let all = sorted(read_pool(scan.open()?, 4).await?); + assert_eq!(all.len(), 300_000); + all.windows(2).for_each(|w| assert!(w[0] < w[1])); + Ok(()) +} + +/// The partitions of a multi-file scan are its files, deferred ones included. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[cfg_attr(miri, ignore)] +async fn partitions_are_files() -> VortexResult<()> { + let source = three_files().await?; + let partitions: Vec = source + .scan(request(true)) + .await? + .partitions() + .try_collect() + .await?; + assert_eq!( + partitions.iter().map(|p| p.index()).collect::>(), + vec![0, 1, 2] + ); + let mut read = Vec::new(); + for partition in partitions { + read.extend(values(partition.execute()?).await?); + } + assert_eq!(read, expected(0..ROWS, false)); + Ok(()) +} + +/// A deferred child that expands into `children`, as a manifest lists its files. +struct Manifest(Vec); + +#[async_trait] +impl DeferredPlanChild for Manifest { + async fn expand(&self) -> VortexResult> { + Ok(self.0.clone()) + } +} + +/// A deferred child that opens a file of `values` when expanded. +struct LazyFile(Range); + +#[async_trait] +impl DeferredPlanChild for LazyFile { + async fn expand(&self) -> VortexResult> { + let file = SESSION + .open_options() + .open_read(YieldingRead(file_bytes(self.0.clone()).await?)) + .await?; + Ok(vec![PlanSourceChild::Ready(file.plan_child())]) + } +} + +fn deferred(child: impl DeferredPlanChild) -> PlanSourceChild { + PlanSourceChild::Deferred { + child: Arc::new(child), + byte_size: None, + } +} + +/// A source whose second child is a manifest of deferred files: expanding a child queues its +/// children's work, however deep, and reads them in the manifest's place. +async fn nested() -> VortexResult { + let first = open_one_file_of(0..200_000).await?; + let dtype = first.dtype().clone(); + let manifest = Manifest(vec![ + deferred(LazyFile(200_000..400_000)), + deferred(Manifest(vec![deferred(LazyFile(400_000..600_000))])), + ]); + Ok(Arc::new(PlanDataSource::from_children( + SESSION.clone(), + dtype, + vec![ + PlanSourceChild::Ready(first.plan_child()), + deferred(manifest), + ], + ))) +} + +async fn open_one_file_of(values: Range) -> VortexResult { + SESSION + .open_options() + .open_read(YieldingRead(file_bytes(values).await?)) + .await +} + +#[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_expands_nested_children( + #[case] ordered: bool, + #[case] filtered: bool, +) -> VortexResult<()> { + let source = nested().await?; + let request = ScanRequest { + filter: filtered.then(m_filter), + ..request(ordered) + }; + let workers = read_pool(source.scan(request.clone()).await?.open()?, 4).await?; + if ordered { + assert_eq!(workers[0], expected(0..ROWS, filtered)); + } else { + assert_eq!(sorted(workers), expected(0..ROWS, filtered)); + } + + // The partitions are the source's two children; the manifest's runs all of its files. + let partitions: Vec = source + .scan(ScanRequest { + ordered: true, + ..request + }) + .await? + .partitions() + .try_collect() + .await?; + assert_eq!(partitions.len(), 2); + let mut read = Vec::new(); + for partition in partitions { + read.extend(values(partition.execute()?).await?); + } + assert_eq!(read, expected(0..ROWS, filtered)); + Ok(()) +} + +/// A child whose dtype is not the source's fails the scan that expands it. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[cfg_attr(miri, ignore)] +async fn expanding_a_child_of_another_dtype_fails() -> VortexResult<()> { + let first = open_one_file_of(0..10).await?; + let other = SESSION.open_options().open_buffer({ + let array = StructArray::from_fields(&[("n", Buffer::from_iter(0..10u64).into_array())])? + .into_array(); + let mut buf = ByteBufferMut::empty(); + SESSION + .write_options() + .write(&mut buf, array.to_array_stream()) + .await?; + buf.freeze() + })?; + let source = PlanDataSource::from_children( + SESSION.clone(), + first.dtype().clone(), + vec![ + PlanSourceChild::Ready(first.plan_child()), + deferred(Manifest(vec![PlanSourceChild::Ready(other.plan_child())])), + ], + ); + let scan = source.scan(request(false)).await?; + assert!(read_pool(scan.open()?, 2).await.is_err()); + 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 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 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(()) +} diff --git a/vortex-scan/Cargo.toml b/vortex-scan/Cargo.toml index 9c1d41b1aa2..b2e0df7138b 100644 --- a/vortex-scan/Cargo.toml +++ b/vortex-scan/Cargo.toml @@ -15,6 +15,7 @@ version = { workspace = true } all-features = true [dependencies] +async-channel = { workspace = true } async-lock = { workspace = true } async-trait = { workspace = true } bit-vec = { workspace = true } 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/execution/mod.rs b/vortex-scan/src/execution/mod.rs index caa6a7ce099..2bd2cd06a95 100644 --- a/vortex-scan/src/execution/mod.rs +++ b/vortex-scan/src/execution/mod.rs @@ -25,6 +25,7 @@ pub(crate) mod zone_map; mod adaptor; mod chunk; mod filter; +mod parts; mod projection; mod prune; mod selection; @@ -45,10 +46,10 @@ pub(crate) use self::chunk::ROW_BLOCK_SIZE; #[cfg(test)] pub(crate) use self::chunk::row_chunks; pub(crate) use self::chunk::rows_per_chunk; -#[cfg(test)] pub(crate) use self::chunk::scan_chunks; use self::filter::FilterPlanner; pub use self::filter::FilterPlans; +pub use self::parts::part_root; use self::projection::ProjectionPlanner; pub use self::prune::PruneNext; pub use self::prune::PrunePlanner; diff --git a/vortex-scan/src/execution/parts.rs b/vortex-scan/src/execution/parts.rs new file mode 100644 index 00000000000..441808df489 --- /dev/null +++ b/vortex-scan/src/execution/parts.rs @@ -0,0 +1,178 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Cutting a prepared scan into parts, the units its threads take. + +use std::ops::Range; +use std::sync::Arc; + +use vortex_error::VortexExpect; +use vortex_error::VortexResult; +use vortex_io::request::IoConsumer; +use vortex_io::request::IoRequestId; +use vortex_io::request::IoResult; +use vortex_mask::Mask; + +use super::ChunkPlanner; +use super::PreparedScan; +use super::PrunePlanner; +use super::scan_chunks; +use crate::planning::planner::Planner; +use crate::planning::planner::PlannerOutput; +use crate::planning::planner::State; +use crate::planning::planner::WorkScope; + +/// The root planner of a scan cut into parts: it spawns one planner per part, in row order. +/// +/// Parts are the ranges between `splits`, such as a file's layout splits, so that a layout chunk, +/// and the dictionary it carries, is read by one thread; without splits, they are the scan's +/// chunks. With a `dynamic` filter, such as the bound a top-N pushes down, the root first prunes +/// the scan as a whole, so a scan whose zones the filter rules out spawns nothing, reading zone +/// maps to do so. Otherwise the root only cuts parts and reads nothing. +pub fn part_root( + scan: &Arc, + splits: Option<&[u64]>, + dynamic: bool, +) -> Box { + let rows = scan.rows().clone(); + let parts = match splits { + Some(splits) => part_ranges(rows.clone(), splits), + None => scan_chunks(rows.clone(), scan.chunk_rows), + }; + let parts = { + let scan = Arc::clone(scan); + let first_row = rows.start; + move |kept: Option| -> Box { + Box::new(PartPlanner::new(scan, parts, first_row, kept)) + } + }; + if dynamic && scan.filter().is_some() { + Box::new(PrunePlanner::new(Arc::clone(scan), rows, Box::new(parts))) + } else { + parts(None) + } +} + +/// Spawns a planner per part of a scan's rows that the selection and scan-wide pruning left +/// something of, in row order. +/// +/// With a filter, each part prunes over its own rows before its chunks, on the thread that takes +/// it, like the per-split pruning of a V1 scan, so the pruning of a scan's parts runs in parallel. +/// A dynamic filter has tightened by the time a later part is taken, so pruning that part again +/// skips more than the scan-wide pruning did. +struct PartPlanner { + scan: Arc, + parts: std::vec::IntoIter>, + /// The first row of `kept`. + first_row: u64, + /// The rows scan-wide pruning kept, from `first_row`, or `None` when nothing was pruned. + kept: Option, +} + +impl PartPlanner { + fn new( + scan: Arc, + parts: Vec>, + first_row: u64, + kept: Option, + ) -> Self { + Self { + scan, + parts: parts.into_iter(), + first_row, + kept, + } + } + + /// The rows of `part` that scan-wide pruning kept, or `None` when nothing was pruned. + fn kept_in(&self, part: &Range) -> Option { + let kept = self.kept.as_ref()?; + let offset = + |row: u64| usize::try_from(row - self.first_row).vortex_expect("a part fits usize"); + Some(kept.slice(offset(part.start)..offset(part.end))) + } +} + +impl IoConsumer for PartPlanner { + fn set_io_result(&mut self, _request: IoRequestId, _result: IoResult) {} +} + +impl Planner for PartPlanner { + fn state(&self) -> State { + if self.parts.as_slice().is_empty() { + State::Done + } else { + State::NeedsCompute + } + } + + fn compute(&mut self) -> VortexResult { + while let Some(part) = self.parts.next() { + if self.scan.selection().row_count_in_range(&part) == 0 { + continue; + } + let kept = self.kept_in(&part); + if kept.as_ref().is_some_and(Mask::all_false) { + continue; + } + let chunks = { + let scan = Arc::clone(&self.scan); + let part = part.clone(); + move |again: Option| -> Box { + let kept = match (kept, again) { + (Some(kept), Some(again)) => Some(kept & &again), + (kept, again) => kept.or(again), + }; + let selection = scan.selection().clone(); + Box::new(ChunkPlanner::new(scan, part, selection, kept)) + } + }; + let planner: Box = if self.scan.filter().is_some() { + Box::new(PrunePlanner::new( + Arc::clone(&self.scan), + part.clone(), + Box::new(chunks), + )) + } else { + chunks(None) + }; + let scope = WorkScope { + file_ordinal: 0, + rows: part, + }; + return Ok(PlannerOutput::Spawn(scope, planner)); + } + Ok(PlannerOutput::Done) + } +} + +/// The ranges between adjacent `splits`, clipped to `rows`, leaving out empty ones. +fn part_ranges(rows: Range, splits: &[u64]) -> Vec> { + splits + .windows(2) + .map(|w| w[0].max(rows.start)..w[1].min(rows.end)) + .filter(|part| part.start < part.end) + .collect() +} + +#[cfg(test)] +mod tests { + use std::ops::Range; + + use rstest::rstest; + + use super::part_ranges; + + #[rstest] + #[case::whole(0..30, &[0, 10, 20, 30], vec![0..10, 10..20, 20..30])] + #[case::clipped(5..25, &[0, 10, 20, 30], vec![5..10, 10..20, 20..25])] + #[case::inside_one_split(12..18, &[0, 10, 20, 30], vec![12..18])] + #[case::empty(5..5, &[0, 10], vec![])] + fn parts_follow_splits( + #[case] rows: Range, + #[case] splits: &[u64], + #[case] expected: Vec>, + ) { + assert_eq!(part_ranges(rows, splits), expected); + } +} diff --git a/vortex-scan/src/pool.rs b/vortex-scan/src/pool.rs index 26dbeedc8b2..949f016281d 100644 --- a/vortex-scan/src/pool.rs +++ b/vortex-scan/src/pool.rs @@ -4,20 +4,27 @@ //! Pools of work that host threads share by each polling a worker. use std::any::Any; +use std::num::NonZeroUsize; use std::sync::Arc; use std::sync::atomic::AtomicBool; +use std::sync::atomic::AtomicU64; use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering; use async_lock::Mutex; 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::expr::stats::Precision; use vortex_array::stream::ArrayStreamAdapter; use vortex_array::stream::ArrayStreamExt; use vortex_array::stream::SendableArrayStream; +use vortex_error::VortexExpect; use vortex_error::VortexResult; +use vortex_mask::Mask; use crate::DataSourceScanRef; use crate::Partition; @@ -58,6 +65,113 @@ pub trait ScanPool: 'static + Send + Sync { } } +/// A cloneable row budget shared by all work that can contribute rows to one scan. +/// +/// Filterless scans can reserve each unit's selected rows before decoding it, so rows past the +/// limit are never decoded. Filtered scans cannot know a unit's row count up front, so they take +/// rows from the budget as arrays are emitted and discard the excess. Either way, the order in +/// which rows are taken decides which rows are returned: an ordered scan takes them in row order, +/// an unordered one in completion order. +#[derive(Clone, Debug)] +pub struct RowLimit(Arc); + +impl RowLimit { + /// A budget of `limit` rows. + pub fn new(limit: u64) -> Self { + Self(Arc::new(AtomicU64::new(limit))) + } + + /// Reserves the rows selected by `mask` and keeps only the earliest granted rows of it. + pub fn limit(&self, mask: Mask) -> Mask { + let granted = self.take(mask.true_count()); + mask.limit(granted) + } + + /// Reserves up to `rows` rows, returning how many the remaining budget granted. + pub fn take(&self, rows: usize) -> usize { + let requested = u64::try_from(rows).unwrap_or(u64::MAX); + usize::try_from(self.reserve(requested)).unwrap_or(usize::MAX) + } + + /// Whether the budget is spent. + pub fn is_exhausted(&self) -> bool { + self.0.load(Ordering::Relaxed) == 0 + } + + fn reserve(&self, requested: u64) -> u64 { + let remaining = self + .0 + .try_update(Ordering::Relaxed, Ordering::Relaxed, |remaining| { + Some(remaining.saturating_sub(requested)) + }) + .ok() + .vortex_expect("row reservation always updates the budget"); + remaining.min(requested) + } +} + +/// Ends `arrays` once `limit` is spent, taking each array's rows from it as the array is yielded +/// and slicing the array that spends it. Also ends after the first error. +pub fn trim_to_limit( + arrays: BoxStream<'static, VortexResult>, + limit: RowLimit, +) -> BoxStream<'static, VortexResult> { + stream::unfold(Some(arrays), move |arrays| { + let limit = limit.clone(); + async move { + let mut arrays = arrays?; + if limit.is_exhausted() { + return None; + } + let array = match arrays.next().await? { + Ok(array) => array, + Err(err) => return Some((Err(err), None)), + }; + let granted = limit.take(array.len()); + if granted == array.len() { + return Some((Ok(array), Some(arrays))); + } + if granted == 0 { + return None; + } + Some((array.slice(0..granted), None)) + } + }) + .filter(|array| future::ready(array.as_ref().map_or(true, |array| !array.is_empty()))) + .boxed() +} + +/// Groups consecutive `items` into at most `n` contiguous groups of about equal total `weight`. +/// +/// Never cuts an item: each lands whole in one group. Every group is non-empty. +pub fn group_contiguous( + items: Vec, + n: NonZeroUsize, + weight: impl Fn(&T) -> u64, +) -> Vec> { + let total = items + .iter() + .map(|item| u128::from(weight(item))) + .sum::() + .max(1); + let n_groups = n.get() as u128; + let mut groups: Vec> = Vec::new(); + let mut current_group = None; + let mut before = 0u128; + for item in items { + let group = (before * n_groups / total).min(n_groups - 1); + before += u128::from(weight(&item)); + if current_group != Some(group) { + current_group = Some(group); + groups.push(Vec::new()); + } + if let Some(last) = groups.last_mut() { + last.push(item); + } + } + groups +} + /// A pool whose workers take partitions one at a time from a scan's shared partition stream. /// /// A source without a pool of its own can open into this one, as long as it implements @@ -171,6 +285,10 @@ mod tests { use std::collections::VecDeque; use std::num::NonZeroUsize; use std::sync::Arc; + use std::sync::Barrier; + use std::sync::atomic::AtomicU64; + use std::sync::atomic::Ordering; + use std::thread; use futures::StreamExt; use futures::TryStreamExt; @@ -189,10 +307,14 @@ mod tests { use vortex_array::stream::SendableArrayStream; use vortex_buffer::Buffer; use vortex_error::VortexResult; + use vortex_mask::Mask; use super::PartitionPool; + use super::RowLimit; use super::ScanPool; use super::ScanPoolRef; + use super::group_contiguous; + use super::trim_to_limit; use crate::DataSourceScan; use crate::DataSourceScanRef; use crate::Partition; @@ -384,4 +506,77 @@ mod tests { assert_eq!(rows.into_iter().sum::(), 14); Ok(()) } + + #[test] + fn reserve_grants_up_to_the_remaining_budget() { + let limit = RowLimit::new(5); + assert_eq!(limit.reserve(3), 3); + assert!(!limit.is_exhausted()); + assert_eq!(limit.reserve(10), 2); + assert!(limit.is_exhausted()); + assert_eq!(limit.reserve(1), 0); + } + + #[test] + fn limit_keeps_the_earliest_granted_rows() { + let limit = RowLimit::new(2); + let mask = Mask::from_iter([true, false, true, true, false, true]); + let limited = limit.limit(mask); + assert_eq!(limited.true_count(), 2); + assert!(limited.value(0)); + assert!(limited.value(2)); + assert!(!limited.value(3)); + assert!(!limited.value(5)); + assert!(limit.is_exhausted()); + } + + #[test] + fn concurrent_reservations_never_exceed_the_budget() { + const THREADS: usize = 8; + const PER_THREAD: u64 = 10_000; + const LIMIT: u64 = 25_000; + + let limit = RowLimit::new(LIMIT); + let granted_total = Arc::new(AtomicU64::new(0)); + let barrier = Arc::new(Barrier::new(THREADS)); + thread::scope(|scope| { + for _ in 0..THREADS { + let limit = limit.clone(); + let granted_total = Arc::clone(&granted_total); + let barrier = Arc::clone(&barrier); + scope.spawn(move || { + barrier.wait(); + let mut local = 0; + for _ in 0..PER_THREAD { + local += limit.reserve(1); + } + granted_total.fetch_add(local, Ordering::Relaxed); + }); + } + }); + assert_eq!(granted_total.load(Ordering::Relaxed), LIMIT); + assert!(limit.is_exhausted()); + } + + #[test] + fn trim_to_limit_slices_the_array_that_spends_it() -> VortexResult<()> { + let arrays = stream::iter((0..4).map(|_| Ok(Buffer::from_iter(0..3i32).into_array()))); + let trimmed: Vec<_> = + block_on(trim_to_limit(arrays.boxed(), RowLimit::new(7)).try_collect())?; + assert_eq!( + trimmed.iter().map(|a| a.len()).collect::>(), + vec![3, 3, 1] + ); + Ok(()) + } + + #[test] + fn group_contiguous_balances_weights() { + let groups = group_contiguous( + vec![4u64, 4, 4, 4, 1, 1], + NonZeroUsize::new(3).unwrap_or(NonZeroUsize::MIN), + |w| *w, + ); + assert_eq!(groups, vec![vec![4, 4], vec![4], vec![4, 1, 1]]); + } } diff --git a/vortex-scan/src/prepare.rs b/vortex-scan/src/prepare.rs index 62de742a81b..625f614f7d9 100644 --- a/vortex-scan/src/prepare.rs +++ b/vortex-scan/src/prepare.rs @@ -24,6 +24,7 @@ pub use crate::execution::SegmentLocation; pub use crate::execution::cache::ScanCache; pub use crate::execution::cache::WeakScanCache; use crate::execution::io::segment_ranges; +pub use crate::execution::part_root; use crate::execution::rows_per_chunk; use crate::plan::optimize; use crate::plan::plan_row_idx_expression; diff --git a/vortex-scan/src/source.rs b/vortex-scan/src/source.rs index 08a3f38c296..7988ac2b72f 100644 --- a/vortex-scan/src/source.rs +++ b/vortex-scan/src/source.rs @@ -1,7 +1,8 @@ // 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`](crate::DataSource) that scans +//! them. use std::sync::Arc; @@ -32,3 +33,17 @@ pub struct ScanInput { /// State shared by repeated scans of this input. pub cache: Option, } + +mod bind_cache; +mod plan; +mod plan_pool; + +pub use plan::DeferredPlanChild; +pub use plan::FilePruner; +pub use plan::PlanChild; +pub use plan::PlanDataSource; +pub use plan::PlanSourceChild; +pub use plan::PlanSplitter; + +#[cfg(test)] +mod tests; diff --git a/vortex-scan/src/source/bind_cache.rs b/vortex-scan/src/source/bind_cache.rs new file mode 100644 index 00000000000..8e297c73bcc --- /dev/null +++ b/vortex-scan/src/source/bind_cache.rs @@ -0,0 +1,172 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Bound request expressions, shared by the sources of one session. + +use std::any::Any; +use std::collections::VecDeque; +use std::fmt; +use std::sync::Arc; + +use parking_lot::Mutex; +use vortex_array::dtype::DType; +use vortex_array::expr::BoundExpression; +use vortex_array::expr::Expression; +use vortex_error::VortexResult; +use vortex_session::SessionExt; +use vortex_session::SessionVar; +use vortex_session::VortexSession; + +/// How many bound expressions a session keeps. +/// +/// Each scan of a source looks up two entries, its projection and its filter, so 32 entries hold +/// the expressions of about 16 queries scanning at once against one dtype each, or fewer queries +/// over tables whose files differ in dtype. A miss costs only the bind the cache saves, so the +/// bound need not be tight; it keeps each lookup a short scan and the session's memory small. +const ENTRIES: usize = 32; + +/// The expressions recently bound against a dtype and optimized, most recently used last. One +/// cache lives on each [`VortexSession`], shared by every source scanned in it. +/// +/// Requests stay unbound so that every source binds them against its own dtype. Binding and +/// optimizing a wide projection is real CPU, which an engine opening a source per file would +/// otherwise pay once per file rather than once per query. With this cache, each (expression, +/// dtype) pair binds once. +/// +/// A lookup hashes nothing: it compares the request against each entry. Expression children and +/// struct fields sit behind [`Arc`]s whose equality first compares pointers, so the clones of one +/// request an engine sends to each file compare in a few pointer checks, and files whose dtypes +/// share their fields, as files opened from one cached footer do, compare likewise. Distinct but +/// equal dtypes compare field by field, which is still a fraction of the bind that walks the same +/// fields and builds a tree. +/// +/// Dynamic expressions compare by identity, so an entry is only found again for the same +/// dynamic value, never for an equal-looking one of another query. +#[derive(Clone, Default)] +pub(super) struct BindCache(Arc>>); + +struct Entry { + dtype: DType, + expr: Expression, + bound: BoundExpression, +} + +impl BindCache { + /// `expr` bound against `dtype` and optimized, from an earlier scan of the session where one + /// bound it already. + pub(super) fn bind( + session: &VortexSession, + expr: &Expression, + dtype: &DType, + ) -> VortexResult { + let cache = BindCache::clone(&session.get::()); + if let Some(bound) = cache.find(expr, dtype) { + return Ok(bound); + } + let bound = expr.bind(dtype)?.optimize_recursive()?; + let mut entries = cache.0.lock(); + if entries.len() == ENTRIES { + entries.pop_front(); + } + entries.push_back(Entry { + dtype: dtype.clone(), + expr: expr.clone(), + bound: bound.clone(), + }); + Ok(bound) + } + + fn find(&self, expr: &Expression, dtype: &DType) -> Option { + let mut entries = self.0.lock(); + let index = entries + .iter() + .rposition(|entry| entry.expr == *expr && entry.dtype == *dtype)?; + // Keep entries in use at the back, so the least recently used is evicted first. + let entry = entries.remove(index)?; + let bound = entry.bound.clone(); + entries.push_back(entry); + Some(bound) + } +} + +impl fmt::Debug for BindCache { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("BindCache") + .field("entries", &self.0.lock().len()) + .finish() + } +} + +impl SessionVar for BindCache { + fn as_any(&self) -> &dyn Any { + self + } + + fn as_any_mut(&mut self) -> &mut dyn Any { + self + } +} + +#[cfg(test)] +mod tests { + 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_error::VortexResult; + use vortex_session::SessionExt; + use vortex_session::VortexSession; + + use super::BindCache; + + fn ints() -> Expression { + get_item("ints", root()) + } + + fn table(ints: PType) -> DType { + DType::struct_( + [("ints", DType::Primitive(ints, Nullability::NonNullable))], + Nullability::NonNullable, + ) + } + + fn entries(session: &VortexSession) -> usize { + session.get::().0.lock().len() + } + + #[test] + fn files_sharing_a_dtype_bind_once() -> VortexResult<()> { + let session = VortexSession::empty(); + let filter = gt(ints(), lit(5i32)); + let first = BindCache::bind(&session, &filter, &table(PType::I32))?; + let second = BindCache::bind(&session, &filter, &table(PType::I32))?; + assert_eq!(first, second); + assert_eq!( + first, + filter.bind(&table(PType::I32))?.optimize_recursive()? + ); + assert_eq!(entries(&session), 1); + Ok(()) + } + + #[test] + fn another_dtype_binds_again() -> VortexResult<()> { + let session = VortexSession::empty(); + let narrow = BindCache::bind(&session, &ints(), &table(PType::I32))?; + let wide = BindCache::bind(&session, &ints(), &table(PType::I64))?; + assert_eq!( + narrow.dtype(), + &DType::Primitive(PType::I32, Nullability::NonNullable) + ); + assert_eq!( + wide.dtype(), + &DType::Primitive(PType::I64, Nullability::NonNullable) + ); + assert_eq!(entries(&session), 2); + Ok(()) + } +} diff --git a/vortex-scan/src/source/plan.rs b/vortex-scan/src/source/plan.rs new file mode 100644 index 00000000000..5bd7cb5a691 --- /dev/null +++ b/vortex-scan/src/source/plan.rs @@ -0,0 +1,813 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! [`PlanDataSource`]: a [`DataSource`] over plan children, scanned by the planner-driven +//! executor. +//! +//! Nothing here is about one format. A child is a [`ScanInput`], a plan over placed segments, +//! from a Vortex file, a Parquet file whose column chunks are segments, or any store that lowers +//! its data to plans; a deferred child is anything that expands into children, such as a file to +//! open, a table format's manifest, or a partition to list. + +use std::any::Any; +use std::collections::VecDeque; +use std::future; +use std::num::NonZeroUsize; +use std::ops::Range; +use std::sync::Arc; + +use async_trait::async_trait; +use futures::StreamExt; +use futures::TryStreamExt; +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_error::vortex_bail; +use vortex_io::session::RuntimeSessionExt; +use vortex_session::VortexSession; + +use super::ScanInput; +use super::bind_cache::BindCache; +use super::plan_pool; +use crate::DataSource; +use crate::DataSourceScan; +use crate::DataSourceScanRef; +use crate::Partition; +use crate::PartitionRef; +use crate::PartitionStream; +use crate::ScanRequest; +use crate::execution::ROW_BLOCK_SIZE; +use crate::execution::driver::ScanDriver; +use crate::pool::RowLimit; +use crate::pool::ScanPoolRef; +use crate::pool::group_contiguous; +use crate::pool::trim_to_limit; +use crate::prepare::ScanBuilder; +use crate::selection::Selection; + +/// Whether a child's own statistics, such as a file footer's, prove a filter, bound to the +/// child's dtype, false for every row of the child. +pub type FilePruner = Arc VortexResult + Send + Sync>; + +/// The row boundaries an opened scan cuts a child's work at, for the scan's projection and filter, +/// both bound to the child's dtype: ascending, covering the child's rows. A Vortex file gives its +/// layout splits over the fields the scan reads, as a V1 scan of the same fields cuts it. +pub type PlanSplitter = + Arc) -> VortexResult> + Send + Sync>; + +/// A child of a [`PlanDataSource`] whose plan is ready to prepare: its [`ScanInput`] and what the +/// source knows of it without reading payloads. +#[derive(Clone)] +pub struct PlanChild { + input: ScanInput, + row_count: Option, + splitter: Option, + pruner: Option, +} + +impl PlanChild { + /// A child scanning `input`. Without a cache, the input gets a fresh one that every scan of + /// the child shares. + pub fn new(mut input: ScanInput) -> Self { + input.cache.get_or_insert_default(); + Self { + input, + row_count: None, + splitter: None, + pruner: None, + } + } + + /// Sets the child's exact row count. Without it, the source lowers the child's root plan to + /// learn the count when a scan needs it. + pub fn with_row_count(mut self, row_count: u64) -> Self { + self.row_count = Some(row_count); + self + } + + /// Sets fixed row boundaries that an opened scan cuts the child's work at, whatever it reads, + /// ascending and covering the child's rows. Without boundaries, the work is cut on the scan's + /// chunk grid. + pub fn with_splits(self, splits: Arc<[u64]>) -> Self { + self.with_splitter(Arc::new(move |_, _| Ok(splits.to_vec()))) + } + + /// Sets how an opened scan finds the row boundaries to cut the child's work at, from the + /// fields it reads. Without boundaries, the work is cut on the scan's chunk grid. + pub fn with_splitter(mut self, splitter: PlanSplitter) -> Self { + self.splitter = Some(splitter); + self + } + + /// Sets how the child's statistics rule out a scan's filter, so a scan they rule out reads + /// nothing of the child. + pub fn with_pruner(mut self, pruner: FilePruner) -> Self { + self.pruner = Some(pruner); + self + } + + /// The input this child scans. + pub fn input(&self) -> &ScanInput { + &self.input + } + + /// The child's rows, from the row count when set, else from its root plan. + pub(super) fn rows(&self) -> VortexResult { + match self.row_count { + Some(rows) => Ok(rows), + None => Ok(self.input.root.get()?.row_count()), + } + } + + /// The bytes of all of the child's segments. + fn byte_size(&self) -> u64 { + self.input + .locations + .iter() + .map(|location| u64::from(location.length)) + .sum() + } + + /// The boundaries an opened scan of `projection` and `filter` cuts the child's work at, if the + /// child has them. + pub(super) fn splits( + &self, + projection: &BoundExpression, + filter: Option<&BoundExpression>, + ) -> VortexResult>> { + self.splitter + .as_ref() + .map(|splitter| splitter(projection, filter)) + .transpose() + } + + fn is_pruned(&self, filter: Option<&BoundExpression>) -> VortexResult { + match (&self.pruner, filter) { + (Some(pruner), Some(filter)) => pruner(filter), + _ => Ok(false), + } + } +} + +/// A child of a [`PlanDataSource`] that a scan expands when it reaches it: a file to open, a +/// manifest entry to read, a table partition to list. +/// +/// Expanding is work like any other unit of an opened scan: the worker that takes the child +/// expands it and queues the work of what it expanded into, for any worker to take. +#[async_trait] +pub trait DeferredPlanChild: 'static + Send + Sync { + /// The children this child stands for, in row order. They may be deferred in turn, as a + /// manifest's children are. An empty list skips the child. + async fn expand(&self) -> VortexResult>; +} + +/// A child of a [`PlanDataSource`]. +#[derive(Clone)] +pub enum PlanSourceChild { + /// A child whose plan is ready to prepare. + Ready(PlanChild), + /// A child that a scan expands when it reaches it, so a source over many children reads only + /// the metadata its scans need. + Deferred { + /// Expands the child. + child: Arc, + /// The child's size in bytes, if known. + byte_size: Option, + }, +} + +/// A [`DataSource`] over plan children, scanned by the planner-driven executor. +/// +/// This is the standard way to expose sources that can lower their data to plans over placed +/// segments, whatever their format. Every scan of a ready child shares the child's +/// [`ScanCache`], so scans that overlap in time plan it once. +/// +/// A scan's request applies to each child: its row range and row selection are in the child's +/// own rows. A scan reads its children in order, and a deferred child's children in its place. +/// +/// # Splitting and opening +/// +/// The work of a scan is plan work: chunks of a prepared plan, and the expansion of deferred +/// children, which queues the work of their children. A Vortex multi-file scan is one case. +/// +/// [`split`](DataSourceScan::split) cuts a scan into contiguous pieces of about equal row counts, +/// each a list of children and row ranges of them, on the 8,192-row block grid that every chunk +/// boundary of the executor lies on. It reads nothing; a deferred child is one indivisible unit. +/// +/// [`open`](DataSourceScan::open) runs the scan on V2's own driver, as develop's V2 DuckDB scan +/// does: it prepares each ready child of the scan once and queues its parts, the chunks of its +/// plan, or the rows between the child's [splits](PlanChild::with_splits) when it has them. Each +/// worker drives a planning run of its own on the task that polls it, fed with parts from that +/// queue. Expanding a deferred child is queued work too: the worker that takes it expands it and +/// queues the work of its children for any worker to take. See the pool's documentation in +/// `plan_pool.rs`. +/// +/// # Partitions +/// +/// A scan has one partition per child, whose [`index`](Partition::index) is the child's ordinal, +/// so a request's `partition_range` and `partition_selection` select children. A partition runs +/// its child, or each child a deferred one expands into, with a [`ScanDriver`] on the session's +/// runtime. +/// +/// [`ScanCache`]: crate::prepare::ScanCache +#[derive(Clone)] +pub struct PlanDataSource { + session: VortexSession, + dtype: DType, + children: Arc<[PlanSourceChild]>, + row_count: Precision, + byte_size: Precision, +} + +impl PlanDataSource { + /// A source scanning one ready `input` with `session`. + pub fn new(session: VortexSession, input: ScanInput) -> Self { + Self::from_child(session, PlanChild::new(input)) + } + + /// A source scanning one ready `child` with `session`. + pub fn from_child(session: VortexSession, child: PlanChild) -> Self { + let dtype = child.input.dtype.clone(); + let row_count = child.row_count.map_or(Precision::Absent, Precision::exact); + Self { + session, + dtype, + children: Arc::new([PlanSourceChild::Ready(child)]), + row_count, + byte_size: Precision::Absent, + } + } + + /// A source scanning `children` in order with `session`. Every child must have `dtype`; a + /// scan that expands a child of another dtype fails. + pub fn from_children( + session: VortexSession, + dtype: DType, + children: Vec, + ) -> Self { + let mut rows = Some(0u64); + let mut bytes = Some(0u64); + let mut known_rows = 0; + let mut known_files = 0; + for file in &children { + match file { + PlanSourceChild::Ready(file) => { + match file.row_count { + Some(count) => { + known_rows += count; + known_files += 1; + } + None => rows = None, + } + bytes = bytes.map(|bytes| bytes + file.byte_size()); + } + PlanSourceChild::Deferred { byte_size, .. } => { + rows = None; + bytes = bytes.zip(*byte_size).map(|(bytes, size)| bytes + size); + } + } + } + // Deferred children are estimated at the average row count of the ready ones. + let row_count = match rows { + Some(rows) => Precision::exact(rows + known_rows), + None if known_files > 0 => { + Precision::inexact(known_rows / known_files * children.len() as u64) + } + None => Precision::Absent, + }; + Self { + session, + dtype, + children: children.into(), + row_count, + byte_size: bytes.map_or(Precision::Absent, Precision::inexact), + } + } + + /// Sets the exact row count of a one-child source, which scans and partitions report. + pub fn with_row_count(mut self, row_count: u64) -> Self { + if let [PlanSourceChild::Ready(file)] = &*self.children { + self.children = Arc::new([PlanSourceChild::Ready( + file.clone().with_row_count(row_count), + )]); + } + self.row_count = Precision::exact(row_count); + self + } + + /// Sets an estimate of the source's byte size. + pub fn with_byte_size(mut self, byte_size: Precision) -> Self { + self.byte_size = byte_size; + self + } + + /// The children this source scans, in order. + pub fn children(&self) -> &[PlanSourceChild] { + &self.children + } + + /// 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.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 = BindCache::bind(&self.session, &request.projection, &self.dtype)?; + let filter = request + .filter + .map(|filter| BindCache::bind(&self.session, &filter, &self.dtype)) + .transpose()?; + let mut units = Vec::new(); + let scans_rows = + request.limit != Some(0) && !request.row_range.as_ref().is_some_and(Range::is_empty); + for (ordinal, file) in self.children.iter().enumerate().filter(|_| scans_rows) { + let index = ordinal as u64; + let selected = request + .partition_range + .as_ref() + .is_none_or(|range| range.contains(&index)) + && request + .partition_selection + .row_count_in_range(&(index..index + 1)) + == 1; + if !selected { + continue; + } + let rows = match file { + PlanSourceChild::Ready(file) => { + if file.is_pruned(filter.as_ref())? { + continue; + } + file.row_count + .map(|count| clamp_rows(request.row_range.clone(), count)) + } + PlanSourceChild::Deferred { .. } => None, + }; + if rows.as_ref().is_some_and(Range::is_empty) { + continue; + } + units.push(Unit { + child: ordinal, + rows, + }); + } + let state = ScanState { + session: self.session.clone(), + source_dtype: self.dtype.clone(), + children: Arc::clone(&self.children), + dtype: projection.dtype().clone(), + projection, + filter, + row_range: request.row_range, + selection: request.selection, + ordered: request.ordered, + limit: request.limit, + split_concurrency: request.split_concurrency, + }; + Ok(Box::new(PlanScan { + state: Arc::new(state), + units, + })) + } + + async fn field_statistics(&self, _field_path: &FieldPath) -> VortexResult { + Ok(StatsSet::default()) + } +} + +/// The request's `rows`, or all of them, clamped to a child of `count` rows. +fn clamp_rows(rows: Option>, count: u64) -> Range { + let rows = rows.unwrap_or(0..count); + let end = rows.end.min(count); + rows.start.min(end)..end +} + +/// What every piece, partition and pool of one scan of a [`PlanDataSource`] shares. +pub(super) struct ScanState { + pub(super) session: VortexSession, + source_dtype: DType, + children: Arc<[PlanSourceChild]>, + /// The dtype of the scan's output. + pub(super) dtype: DType, + pub(super) projection: BoundExpression, + pub(super) filter: Option, + row_range: Option>, + pub(super) selection: Selection, + pub(super) ordered: bool, + pub(super) limit: Option, + pub(super) split_concurrency: Option, +} + +impl ScanState { + /// The source's child at `ordinal`. + pub(super) fn child(&self, ordinal: usize) -> &PlanSourceChild { + &self.children[ordinal] + } + + /// The child at `ordinal` if it is ready. + pub(super) fn ready(&self, ordinal: usize) -> Option<&PlanChild> { + match &self.children[ordinal] { + PlanSourceChild::Ready(child) => Some(child), + PlanSourceChild::Deferred { .. } => None, + } + } + + /// Admits a child that expanding produced: `None` when its statistics rule out the filter, + /// and an error when its dtype is not the source's. + pub(super) fn admit(&self, child: PlanChild) -> VortexResult> { + if child.input.dtype != self.source_dtype { + vortex_bail!( + "a child of the source has dtype {}, but the source has dtype {}", + child.input.dtype, + self.source_dtype + ); + } + if child.is_pruned(self.filter.as_ref())? { + return Ok(None); + } + Ok(Some(child)) + } + + /// Expands `children` depth-first, in order, into the admitted ready children they stand for, + /// expanding each deferred child only once the children before it are taken. + /// + /// Each child comes with its share of the scan's work, which a deferred child divides evenly + /// among the children it expands into. The share of a child that is pruned, or that expands + /// into nothing, goes to `skipped`. + pub(super) fn expand_in_order( + self: &Arc, + children: Vec<(PlanSourceChild, f64)>, + skipped: Arc, + ) -> BoxStream<'static, VortexResult<(PlanChild, f64)>> { + let state = Arc::clone(self); + stream::try_unfold(VecDeque::from(children), move |mut queue| { + let state = Arc::clone(&state); + let skipped = Arc::clone(&skipped); + async move { + while let Some((child, share)) = queue.pop_front() { + match child { + PlanSourceChild::Ready(child) => match state.admit(child)? { + Some(child) => return Ok(Some(((child, share), queue))), + None => skipped(share), + }, + PlanSourceChild::Deferred { child, .. } => { + let children = child.expand().await?; + if children.is_empty() { + skipped(share); + } + let share = share / children.len().max(1) as f64; + for child in children.into_iter().rev() { + queue.push_front((child, share)); + } + } + } + } + Ok(None) + } + }) + .boxed() + } + + /// Runs `rows` of `child`, or the request's rows of it when `None`, with a [`ScanDriver`]. + fn drive( + &self, + child: &PlanChild, + rows: Option>, + ) -> BoxStream<'static, VortexResult> { + let rows = match rows.map_or_else(|| self.child_rows(child), Ok) { + Ok(rows) => rows, + Err(err) => return stream::once(future::ready(Err(err))).boxed(), + }; + if rows.is_empty() { + return stream::empty().boxed(); + } + ScanDriver::new(self.session.handle(), 1, self.ordered) + .with_max_in_flight(self.split_concurrency) + .run(self.builder(child, rows)) + } + + /// The rows of `child` this scan reads: the request's row range, clamped to the child. + pub(super) fn child_rows(&self, child: &PlanChild) -> VortexResult> { + Ok(clamp_rows(self.row_range.clone(), child.rows()?)) + } + + /// A builder of this scan's `rows` of `child`. + pub(super) fn builder(&self, child: &PlanChild, rows: Range) -> ScanBuilder { + ScanBuilder::new(self.session.clone(), child.input.clone()) + .with_projection(self.projection.clone()) + .with_some_filter(self.filter.clone()) + .with_selection(self.selection.clone()) + .with_row_range(rows) + } +} + +/// Rows of one child that a scan reads. +#[derive(Clone, Debug)] +pub(super) struct Unit { + /// The child's ordinal in the source. + pub(super) child: usize, + /// The child's rows, or `None` for the request's rows of a child whose row count is not known + /// until it is open. + pub(super) rows: Option>, +} + +/// A scan of a [`PlanDataSource`], or a piece split from one. +struct PlanScan { + state: Arc, + /// The scan's units, in child and row order. + units: Vec, +} + +impl PlanScan { + /// The rows of `unit` the scan selects before filtering, or `None` when not known yet. + fn unit_rows(&self, unit: &Unit) -> Option { + let rows = unit.rows.as_ref()?; + Some(self.state.selection.row_count_in_range(rows)) + } + + /// The bytes of `unit`, in proportion to its share of its child's rows. + fn unit_bytes(&self, unit: &Unit) -> Option { + match &self.state.children[unit.child] { + PlanSourceChild::Ready(file) => { + let bytes = file.byte_size(); + match (&unit.rows, file.row_count) { + (Some(rows), Some(count)) if count > 0 => Some( + u64::try_from( + u128::from(bytes) * u128::from(rows.end - rows.start) + / u128::from(count), + ) + .unwrap_or(u64::MAX), + ), + _ => Some(bytes), + } + } + PlanSourceChild::Deferred { byte_size, .. } => *byte_size, + } + } +} + +impl DataSourceScan for PlanScan { + fn dtype(&self) -> &DType { + &self.state.dtype + } + + fn partition_count(&self) -> Precision { + Precision::exact(self.units.len()) + } + + fn partitions(self: Box) -> PartitionStream { + // An unordered scan's partitions share one budget; an ordered scan's each apply the limit + // locally, and the caller trims the concatenated result. + let shared = (!self.state.ordered) + .then(|| self.state.limit.map(RowLimit::new)) + .flatten(); + let state = self.state; + stream::iter(self.units.into_iter().map(move |unit| { + let limit = shared.clone().or_else(|| state.limit.map(RowLimit::new)); + Ok(Box::new(PlanPartition { + state: Arc::clone(&state), + unit, + limit, + }) as PartitionRef) + })) + .boxed() + } + + fn row_count(&self) -> Precision { + let Some(rows) = self + .units + .iter() + .map(|unit| self.unit_rows(unit)) + .sum::>() + else { + return Precision::Absent; + }; + let rows = self.state.limit.map_or(rows, |limit| rows.min(limit)); + if self.state.filter.is_some() { + Precision::inexact(rows) + } else { + Precision::exact(rows) + } + } + + fn byte_size(&self) -> Precision { + self.units + .iter() + .map(|unit| self.unit_bytes(unit)) + .sum::>() + .map_or(Precision::Absent, Precision::inexact) + } + + fn split(self: Box, n: NonZeroUsize) -> VortexResult> { + // A limit holds across the whole scan, which pieces read independently cannot share. + if self.state.limit.is_some() || n.get() == 1 { + return Ok(vec![self]); + } + let atoms = split_atoms(&self.units, n); + if atoms.len() <= 1 { + return Ok(vec![self]); + } + let known: Vec = atoms + .iter() + .filter_map(|unit| unit.rows.as_ref().map(|rows| rows.end - rows.start)) + .collect(); + // A deferred child weighs as much as the average ready unit. + let unknown = (known.iter().sum::() / known.len().max(1) as u64).max(1); + let weight = |unit: &Unit| { + unit.rows + .as_ref() + .map_or(unknown, |rows| rows.end - rows.start) + }; + let state = self.state; + Ok(group_contiguous(atoms, n, weight) + .into_iter() + .map(|atoms| { + Box::new(PlanScan { + state: Arc::clone(&state), + units: join_atoms(atoms), + }) as DataSourceScanRef + }) + .collect()) + } + + fn open(self: Box) -> VortexResult { + plan_pool::open(self.state, self.units) + } +} + +/// The pieces a split may not cut further: the scan's known rows on a grid of whole 8,192-row +/// blocks, coarse enough that each of `n` pieces gets about 64 of them, and each unit whose rows +/// are not known yet whole. +fn split_atoms(units: &[Unit], n: NonZeroUsize) -> Vec { + let block = ROW_BLOCK_SIZE as u64; + let known: u64 = units + .iter() + .filter_map(|unit| unit.rows.as_ref().map(|rows| rows.end - rows.start)) + .sum(); + let per_atom = known.div_ceil(n.get() as u64 * 64).div_ceil(block).max(1) * block; + let mut atoms = Vec::new(); + for unit in units { + let Some(rows) = &unit.rows else { + atoms.push(unit.clone()); + continue; + }; + let mut start = rows.start; + while start < rows.end { + let end = ((start / per_atom + 1) * per_atom).min(rows.end); + atoms.push(Unit { + child: unit.child, + rows: Some(start..end), + }); + start = end; + } + } + atoms +} + +/// Joins adjacent atoms of the same child back into one unit. +fn join_atoms(atoms: Vec) -> Vec { + let mut units: Vec = Vec::new(); + for atom in atoms { + if let Some(last) = units.last_mut() + && last.child == atom.child + && let (Some(rows), Some(next)) = (&mut last.rows, &atom.rows) + && rows.end == next.start + { + rows.end = next.end; + continue; + } + units.push(atom); + } + units +} + +/// One child's rows of a scan of a [`PlanDataSource`]. +struct PlanPartition { + state: Arc, + unit: Unit, + limit: Option, +} + +impl Partition for PlanPartition { + fn as_any(&self) -> &dyn Any { + self + } + + fn index(&self) -> usize { + self.unit.child + } + + fn row_count(&self) -> Precision { + let rows = match (&self.unit.rows, self.state.ready(self.unit.child)) { + (Some(rows), _) => rows.clone(), + (None, Some(file)) if file.row_count.is_some() => match self.state.child_rows(file) { + Ok(rows) => rows, + Err(_) => return Precision::Absent, + }, + _ => return Precision::Absent, + }; + let rows = self.state.selection.row_count_in_range(&rows); + let rows = self.state.limit.map_or(rows, |limit| rows.min(limit)); + if self.state.filter.is_some() { + Precision::inexact(rows) + } else { + Precision::exact(rows) + } + } + + fn byte_size(&self) -> Precision { + Precision::Absent + } + + fn execute(self: Box) -> VortexResult { + let PlanPartition { state, unit, limit } = *self; + let dtype = state.dtype.clone(); + // A ready child runs as it is; a deferred one runs each child it expands into, in order. + let children = match state.ready(unit.child) { + Some(child) => stream::iter([Ok((child.clone(), unit.rows))]).boxed(), + None => state + .expand_in_order( + vec![(state.child(unit.child).clone(), 0.0)], + Arc::new(|_| {}), + ) + .map_ok(|(child, _)| (child, None)) + .boxed(), + }; + let driver = Arc::clone(&state); + let arrays = children + .map_ok(move |(child, rows)| driver.drive(&child, rows)) + .try_flatten() + .boxed(); + let arrays = match limit { + Some(limit) => trim_to_limit(arrays, limit), + None => arrays, + }; + Ok(ArrayStreamExt::boxed(ArrayStreamAdapter::new( + dtype, arrays, + ))) + } +} + +#[cfg(test)] +mod tests { + use std::num::NonZeroUsize; + + use rstest::rstest; + + use super::Unit; + use super::join_atoms; + use super::split_atoms; + + fn unit(child: usize, rows: std::ops::Range) -> Unit { + Unit { + child, + rows: Some(rows), + } + } + + #[rstest] + #[case::one_block(vec![unit(0, 0..100)], 4, 1)] + #[case::grid_aligned(vec![unit(0, 10..40_000)], 1, 5)] + fn atoms_lie_on_the_block_grid( + #[case] units: Vec, + #[case] n: usize, + #[case] expected: usize, + ) { + let n = NonZeroUsize::new(n).unwrap_or(NonZeroUsize::MIN); + let atoms = split_atoms(&units, n); + assert_eq!(atoms.len(), expected); + for atom in &atoms[1..] { + let start = atom.rows.as_ref().map_or(0, |rows| rows.start); + assert_eq!(start % 8192, 0); + } + let joined = join_atoms(atoms); + assert_eq!( + joined.iter().map(|u| u.rows.clone()).collect::>(), + units.iter().map(|u| u.rows.clone()).collect::>() + ); + } +} diff --git a/vortex-scan/src/source/plan_pool.rs b/vortex-scan/src/source/plan_pool.rs new file mode 100644 index 00000000000..063a278a4a0 --- /dev/null +++ b/vortex-scan/src/source/plan_pool.rs @@ -0,0 +1,620 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! The work that the workers of an opened [`PlanDataSource`](super::PlanDataSource) scan share. +//! +//! An opened scan runs V2's own driver, the planners, morsels and [`Run`] that develop's V2 DuckDB +//! and DataFusion scans run, behind [`ScanPool`]. Nothing here is a general work pool. +//! +//! - An unordered pool runs as develop's V2 DuckDB scan (`vortex-duckdb/src/scan_v2.rs`) does. +//! Opening it prepares each ready child once, which plans without reading, and runs its root up +//! front, which spawns its parts: a part is the rows between two of the child's splits for the +//! fields the scan reads, such as a file's layout splits, else one of the scan's chunks. A root +//! whose filter changes while the scan runs, as a top-N's bound does, prunes the child as a +//! whole before it spawns parts; it reads zone maps to do so, so the worker that takes it runs +//! it instead. Each worker owns a [`Run`], driven on the task that polls the worker, as a DuckDB +//! thread drives its own run: it takes parts from a queue every worker shares, runs a part's +//! chunks on its run beside each other, so one chunk's reads overlap another's compute, yields +//! batches as they are produced, and awaits reads with [`Run::poll_completion`]. Nothing is +//! spawned per part. Expanding a deferred child, whether a file to open, a manifest entry or a +//! table partition, is queued work too: the worker that takes it expands it and queues the work +//! of its children, which may be deferred in turn. +//! - An ordered pool gives every child, in row order, to its first worker, which expands each +//! deferred child in its place and runs the parts in row order on a run of its own, a part's +//! chunks beside each other, returning each part's batches in row order. Later workers get +//! nothing. Parallel ordered reads cut the scan with `split` first. +//! +//! A limit is a [`RowLimit`] the workers take rows from as they yield them; workers stop taking +//! work once it is spent. + +use std::future; +use std::ops::Range; +use std::sync::Arc; + +use async_channel::Receiver; +use async_channel::Sender; +use futures::FutureExt; +use futures::StreamExt; +use futures::future::BoxFuture; +use futures::stream; +use futures::stream::BoxStream; +use parking_lot::Mutex; +use vortex_array::ArrayRef; +use vortex_array::dtype::DType; +use vortex_array::scalar_fn::fns::dynamic::DynamicExprUpdates; +use vortex_array::stream::ArrayStreamAdapter; +use vortex_array::stream::ArrayStreamExt; +use vortex_array::stream::SendableArrayStream; +use vortex_error::VortexExpect; +use vortex_error::VortexResult; +use vortex_error::vortex_bail; +use vortex_io::request::IoService; + +use super::plan::DeferredPlanChild; +use super::plan::PlanChild; +use super::plan::PlanSourceChild; +use super::plan::ScanState; +use super::plan::Unit; +use crate::execution::planning::driver::Progress; +use crate::execution::planning::driver::Run; +use crate::execution::planning::planner::Planner; +use crate::execution::planning::planner::WorkScope; +use crate::pool::RowLimit; +use crate::pool::ScanPool; +use crate::pool::ScanPoolRef; +use crate::pool::trim_to_limit; +use crate::prepare::PreparedScan; +use crate::prepare::part_root; + +/// The parts a worker runs on its run at once when the request's +/// [`split_concurrency`](crate::ScanRequest::split_concurrency) does not say: one, as a DuckDB +/// thread runs one chunk of develop's V2 scan at a time. A part's chunks still run beside each +/// other on the run. +const PARTS_PER_WORKER: usize = 1; + +/// One child's prepared scan, shared by the workers running its parts. +struct PreparedChild { + scan: Arc, + io: Arc, +} + +/// A part of a child: the planner its root spawned for some of its rows, which a worker runs on +/// its run. +struct Part { + child: Arc, + scope: WorkScope, + planner: Box, + /// The part's share of the pool's work, for its progress. + share: f64, +} + +/// The share of a pool's work that workers have taken, from 0.0 to 1.0. +/// +/// Each top-level child of the pool has an equal share. A deferred child divides its share evenly +/// among the children it expands into, and a prepared child divides its share among its parts by +/// their rows. The share of rows that pruning skips counts as taken once they are skipped. +#[derive(Default)] +struct Taken(Mutex); + +impl Taken { + fn add(&self, share: f64) { + *self.0.lock() += share; + } + + fn get(&self) -> f64 { + self.0.lock().clamp(0.0, 1.0) + } +} + +/// The parts a child's root spawns, in row order. +type PartsFuture = BoxFuture<'static, VortexResult>>; + +/// A child of a pool, in row order. +enum PoolChild { + /// A child whose root has run, with the parts it spawned. + Parts(Vec), + /// A child whose root reads before it spawns parts: it prunes the child as a whole first. + Root(PartsFuture), + /// A deferred child, and its share of the pool's work. + Deferred(Arc, f64), +} + +impl PoolChild { + /// The child's parts once its root has run. + fn into_parts(self) -> PartsFuture { + match self { + Self::Parts(parts) => future::ready(Ok(parts)).boxed(), + Self::Root(parts) => parts, + Self::Deferred(..) => unreachable!("a deferred child has no root"), + } + } +} + +/// Opens a pool over the scan's `units`. +pub(super) fn open(state: Arc, units: Vec) -> VortexResult { + let taken = Arc::new(Taken::default()); + let share = 1.0 / units.len().max(1) as f64; + let dtype = state.dtype.clone(); + let shared = Arc::new(Shared { + limit: state.limit.map(RowLimit::new), + parts_per_worker: state + .split_concurrency + .map_or(PARTS_PER_WORKER, |parts| parts.get()), + state, + taken, + }); + let mut children = Vec::with_capacity(units.len()); + for unit in units { + children.push(match shared.state.child(unit.child) { + PlanSourceChild::Ready(child) => shared.prepare(child, unit.rows, share)?, + PlanSourceChild::Deferred { child, .. } => { + PoolChild::Deferred(Arc::clone(child), share) + } + }); + } + if shared.state.ordered { + return Ok(Arc::new(OrderedPool { + dtype, + shared, + children: Mutex::new(Some(children)), + })); + } + + let (sender, receiver) = async_channel::unbounded(); + for child in children { + queue(&sender, child); + } + Ok(Arc::new(UnorderedPool { + dtype, + shared, + receiver, + })) +} + +/// Runs a child's root on a planning run of its own, awaiting only its reads, and returns the +/// parts it spawns, in row order, dividing the child's `share` among them by their rows. The share +/// of the rows they leave out counts as taken. +fn run_root( + child: Arc, + root: Box, + share: f64, + taken: Arc, +) -> PartsFuture { + async move { + let rows = child.scan.rows(); + let per_row = share / (rows.end - rows.start).max(1) as f64; + let mut unassigned = rows.end - rows.start; + let mut run = Run::new(); + run.admit( + root, + WorkScope { + file_ordinal: 0, + rows: child.scan.rows().clone(), + }, + child.io.session(), + ); + let mut parts = Vec::new(); + loop { + match run.advance()? { + Progress::Spawn(scope, planner) => { + let part_rows = scope.rows.end - scope.rows.start; + unassigned = unassigned.saturating_sub(part_rows); + let share = per_row * part_rows as f64; + parts.push(Part { + child: Arc::clone(&child), + scope, + planner, + share, + }); + } + Progress::Batch(_) => vortex_bail!("a scan's root produced a batch"), + Progress::RootDone(_) if run.live_roots() > 0 => {} + Progress::RootDone(_) | Progress::Idle => break, + Progress::Waiting => future::poll_fn(|cx| run.poll_completion(cx)).await?, + } + } + if unassigned > 0 { + taken.add(per_row * unassigned as f64); + } + Ok(parts) + } + .boxed() +} + +/// Runs a part alone on a planning run of its own, awaiting only its reads, and returns its +/// batches in row order. +async fn run_part(part: Part) -> VortexResult> { + let Part { + child, + scope, + planner, + .. + } = part; + let mut run = Run::new(); + run.admit(planner, scope, child.io.session()); + let mut batches = Vec::new(); + loop { + match run.advance()? { + Progress::Batch(batch) => batches.push((batch.scope.rows.start, batch.array)), + Progress::Spawn(scope, planner) => { + run.admit(planner, scope, child.io.session()); + } + Progress::RootDone(_) if run.live_roots() > 0 => {} + Progress::RootDone(_) | Progress::Idle => break, + Progress::Waiting => future::poll_fn(|cx| run.poll_completion(cx)).await?, + } + } + // A part's chunks finish in whatever order their reads arrive. + batches.sort_by_key(|(start, _)| *start); + Ok(batches.into_iter().map(|(_, array)| array).collect()) +} + +/// What every worker of a pool shares. +struct Shared { + state: Arc, + limit: Option, + taken: Arc, + /// The parts a worker runs on its run at once. + parts_per_worker: usize, +} + +impl Shared { + /// Prepares the scan of `rows` of `child`, or of the request's rows when `None`, once, and runs + /// its root up front, like the splits of a V1 scan, unless the root reads before it spawns + /// parts. + /// + /// Parts are cut on the child's splits for the fields the scan reads, when it has them, else + /// on the scan's chunks. A filter whose value changes while the scan runs, as a top-N's bound + /// does, prunes the child as a whole first, so a child it rules out takes no worker. + fn prepare( + &self, + child: &PlanChild, + rows: Option>, + share: f64, + ) -> VortexResult { + let state = &self.state; + let rows = match rows { + Some(rows) => rows, + None => state.child_rows(child)?, + }; + if rows.is_empty() { + self.taken.add(share); + return Ok(PoolChild::Parts(Vec::new())); + } + let splits = child.splits(&state.projection, state.filter.as_ref())?; + let scan = Arc::new(state.builder(child, rows).prepare()?); + let dynamic = state + .filter + .as_ref() + .is_some_and(|filter| DynamicExprUpdates::new(filter).is_some()); + let root = part_root(&scan, splits.as_deref(), dynamic); + let io = scan.io(); + let child = Arc::new(PreparedChild { scan, io }); + let parts = run_root(child, root, share, Arc::clone(&self.taken)); + if dynamic { + return Ok(PoolChild::Root(parts)); + } + let parts = parts + .now_or_never() + .vortex_expect("a root that only cuts parts reads nothing")?; + Ok(PoolChild::Parts(parts)) + } + + fn is_limit_spent(&self) -> bool { + self.limit.as_ref().is_some_and(RowLimit::is_exhausted) + } + + /// The parts of the children that `children` expand into, in row order, expanding each + /// deferred child only once the parts before it are taken. + fn parts_in_order( + self: &Arc, + children: Vec<(PlanSourceChild, f64)>, + ) -> BoxStream<'static, VortexResult>> { + let shared = Arc::clone(self); + let taken = Arc::clone(&self.taken); + self.state + .expand_in_order(children, Arc::new(move |share| taken.add(share))) + .then(move |child| { + match child.and_then(|(child, share)| shared.prepare(&child, None, share)) { + Ok(child) => child.into_parts(), + Err(err) => future::ready(Err(err)).boxed(), + } + }) + .boxed() + } + + /// Expands a deferred child and queues the work of the children it expands into. + async fn expand( + &self, + child: Arc, + share: f64, + sender: &Sender, + ) -> VortexResult<()> { + let children = child.expand().await?; + if children.is_empty() { + self.taken.add(share); + } + let share = share / children.len().max(1) as f64; + for child in children { + match child { + PlanSourceChild::Ready(child) => match self.state.admit(child)? { + Some(child) => queue(sender, self.prepare(&child, None, share)?), + None => self.taken.add(share), + }, + PlanSourceChild::Deferred { child, .. } => { + send(sender, Work::Expand(child, share, sender.clone())); + } + } + } + Ok(()) + } + + /// A worker's output: `arrays`, trimmed to the limit. + fn output(&self, arrays: BoxStream<'static, VortexResult>) -> SendableArrayStream { + let arrays = match &self.limit { + Some(limit) => trim_to_limit(arrays, limit.clone()), + None => arrays, + }; + ArrayStreamExt::boxed(ArrayStreamAdapter::new(self.state.dtype.clone(), arrays)) + } +} + +/// A unit of an unordered pool. +enum Work { + Part(Part), + /// A child's root that reads before it spawns parts, and where to send the parts. The sender + /// keeps the channel open until they are in it. + Root(PartsFuture, Sender), + /// A deferred child, its share of the pool's work, and where to send the units of its children + /// once it is expanded. + Expand(Arc, f64, Sender), +} + +fn send(sender: &Sender, work: Work) { + // The channel is unbounded and closes only once the pool is dropped, when the work is moot. + drop(sender.try_send(work)); +} + +/// Queues the units of `child`. +fn queue(sender: &Sender, child: PoolChild) { + match child { + PoolChild::Parts(parts) => { + for part in parts { + send(sender, Work::Part(part)); + } + } + PoolChild::Root(parts) => send(sender, Work::Root(parts, sender.clone())), + PoolChild::Deferred(child, share) => { + send(sender, Work::Expand(child, share, sender.clone())); + } + } +} + +/// A pool whose workers share its units through a channel. +struct UnorderedPool { + dtype: DType, + shared: Arc, + receiver: Receiver, +} + +impl ScanPool for UnorderedPool { + fn dtype(&self) -> &DType { + &self.dtype + } + + fn worker(self: Arc) -> SendableArrayStream { + let shared = Arc::clone(&self.shared); + let worker = Worker { + receiver: self.receiver.clone(), + shared: Arc::clone(&shared), + run: Run::new(), + child: None, + held: None, + _pool: self, + }; + let arrays = stream::unfold(Some(worker), |worker| async move { + let mut worker = worker?; + match worker.next_array().await { + Ok(Some(array)) => Some((Ok(array), Some(worker))), + Ok(None) => None, + Err(err) => Some((Err(err), None)), + } + }) + .boxed(); + shared.output(arrays) + } + + fn progress(&self) -> f64 { + if self.is_exhausted() { + return 1.0; + } + self.shared.taken.get() + } + + fn is_exhausted(&self) -> bool { + // Roots and expansions hold senders, so the channel closes only once every unit is in it. + self.shared.is_limit_spent() || (self.receiver.is_closed() && self.receiver.is_empty()) + } +} + +impl Drop for UnorderedPool { + fn drop(&mut self) { + // Pending roots and expansions hold senders of the channel itself; drain them so it can be + // freed. + self.receiver.close(); + while self.receiver.try_recv().is_ok() {} + } +} + +/// One worker of an unordered pool: a run of its own, fed with parts from the pool's queue, and +/// driven on the task that polls the worker. +struct Worker { + receiver: Receiver, + shared: Arc, + run: Run, + /// The child whose parts are live on the run. A run reads each root through the child's IO, + /// and a planner a part spawns does not say which part it came from, so a worker runs one + /// child's parts at a time. + child: Option>, + /// A part of another child, taken while the run still held parts of `child`. + held: Option, + /// Holds the pool, so the pool is dropped only after its last worker. + _pool: Arc, +} + +impl Worker { + /// The worker's next array, or `None` once the pool has no more work for it. Keeps the run fed + /// with parts, and awaits reads when every live part waits for them. + async fn next_array(&mut self) -> VortexResult> { + loop { + while self.run.live_roots() < self.shared.parts_per_worker + && !self.shared.is_limit_spent() + { + let part = match self.held.take() { + Some(part) => part, + // A worker with nothing live waits for work; one with parts live only takes + // work that is already queued. + None => match self.take(self.run.live_roots() == 0).await? { + Some(part) => part, + None => break, + }, + }; + if self.run.live_roots() > 0 + && !self + .child + .as_ref() + .is_some_and(|child| Arc::ptr_eq(child, &part.child)) + { + self.held = Some(part); + break; + } + self.admit(part); + } + if self.run.live_roots() == 0 { + return Ok(None); + } + match self.run.advance()? { + Progress::Batch(batch) => return Ok(Some(batch.array)), + Progress::Spawn(scope, planner) => { + let child = self + .child + .as_ref() + .vortex_expect("a planner is spawned by a live part"); + self.run.admit(planner, scope, child.io.session()); + } + Progress::RootDone(_) | Progress::Idle => {} + Progress::Waiting => { + future::poll_fn(|cx| self.run.poll_completion(cx)).await?; + } + } + } + } + + /// Admits `part` to the run. + fn admit(&mut self, part: Part) { + let Part { + child, + scope, + planner, + share, + } = part; + self.shared.taken.add(share); + self.run.admit(planner, scope, child.io.session()); + self.child = Some(child); + } + + /// Takes the next part from the pool's queue, running the roots and expansions it finds there + /// first, which queue parts of their own. With `wait`, waits for work until the queue closes; + /// otherwise takes only what is queued already. + async fn take(&mut self, wait: bool) -> VortexResult> { + loop { + let work = if wait { + match self.receiver.recv().await { + Ok(work) => work, + Err(_) => return Ok(None), + } + } else { + match self.receiver.try_recv() { + Ok(work) => work, + Err(_) => return Ok(None), + } + }; + match work { + Work::Part(part) => return Ok(Some(part)), + Work::Root(parts, sender) => { + for part in parts.await? { + send(&sender, Work::Part(part)); + } + } + Work::Expand(child, share, sender) => { + self.shared.expand(child, share, &sender).await?; + } + } + } + } +} + +/// A pool that gives all of its children, in row order, to its first worker. +struct OrderedPool { + dtype: DType, + shared: Arc, + /// The children, until the first worker takes them. + children: Mutex>>, +} + +impl ScanPool for OrderedPool { + fn dtype(&self) -> &DType { + &self.dtype + } + + fn worker(self: Arc) -> SendableArrayStream { + let Some(children) = self.children.lock().take() else { + return ArrayStreamExt::boxed(ArrayStreamAdapter::new( + self.dtype.clone(), + stream::empty(), + )); + }; + let expander = Arc::clone(&self.shared); + let shared = Arc::clone(&self.shared); + let runner = Arc::clone(&self.shared); + let arrays = stream::iter(children) + .flat_map(move |child| match child { + PoolChild::Deferred(child, share) => expander.parts_in_order(vec![( + PlanSourceChild::Deferred { + child, + byte_size: None, + }, + share, + )]), + child => stream::once(child.into_parts()).boxed(), + }) + .flat_map(|parts| match parts { + Ok(parts) => stream::iter(parts.into_iter().map(Ok)).left_stream(), + Err(err) => stream::once(future::ready(Err(err))).right_stream(), + }) + .take_while(move |_| future::ready(!shared.is_limit_spent())) + .then(move |part| { + let runner = Arc::clone(&runner); + async move { + let part = part?; + runner.taken.add(part.share); + run_part(part).await + } + }) + .flat_map(|arrays| match arrays { + Ok(arrays) => stream::iter(arrays.into_iter().map(Ok)).left_stream(), + Err(err) => stream::once(future::ready(Err(err))).right_stream(), + }) + .boxed(); + self.shared.output(arrays) + } + + fn progress(&self) -> f64 { + self.shared.taken.get() + } + + fn is_exhausted(&self) -> bool { + // The first worker takes every child. + self.shared.is_limit_spent() || self.children.lock().is_none() + } +} diff --git a/vortex-scan/src/source/tests.rs b/vortex-scan/src/source/tests.rs new file mode 100644 index 00000000000..f0a98a3c8d6 --- /dev/null +++ b/vortex-scan/src/source/tests.rs @@ -0,0 +1,189 @@ +// 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::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([]), + segments: 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(()) +}