From 617f37620b0660cf34b3040b6e78b833013abcbf Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Fri, 20 Nov 2026 13:33:40 -0500 Subject: [PATCH] Run opened V2 plan scans on V2's own driver A PartitionPool runs each partition of a PlanDataSource scan with its own ScanDriver, which spends a driver, an I/O session and a task per partition. open instead runs the scan as develop's V2 DuckDB scan does: it prepares each child once and queues its parts, and each worker drives a planning run of its own over them, on the task that polls it. A file's parts follow its layout splits over the fields the scan reads, as a V1 scan's do, and a dynamic filter prunes the whole child before its parts are cut. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- Cargo.lock | 1 + vortex-file/src/file.rs | 21 +- vortex-file/src/lib.rs | 2 + vortex-file/src/plan_tests.rs | 706 ++++++++++++++++++++++++++++ vortex-scan/Cargo.toml | 1 + vortex-scan/src/execution/mod.rs | 3 +- vortex-scan/src/execution/parts.rs | 178 +++++++ vortex-scan/src/prepare.rs | 1 + vortex-scan/src/source.rs | 2 + vortex-scan/src/source/plan.rs | 50 +- vortex-scan/src/source/plan_pool.rs | 620 ++++++++++++++++++++++++ 11 files changed, 1578 insertions(+), 7 deletions(-) create mode 100644 vortex-file/src/plan_tests.rs create mode 100644 vortex-scan/src/execution/parts.rs create mode 100644 vortex-scan/src/source/plan_pool.rs 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/vortex-file/src/file.rs b/vortex-file/src/file.rs index e10d788d32d..6b5b5707a84 100644 --- a/vortex-file/src/file.rs +++ b/vortex-file/src/file.rs @@ -14,6 +14,7 @@ use itertools::Itertools; use vortex_array::ArrayRef; use vortex_array::dtype::DType; use vortex_array::dtype::FieldMask; +use vortex_array::expr::BoundExpression; use vortex_array::expr::Expression; use vortex_buffer::ByteBuffer; use vortex_error::VortexResult; @@ -21,6 +22,7 @@ use vortex_layout::LayoutReader; use vortex_layout::scan::layout::LayoutReaderDataSource; use vortex_layout::scan::metrics::ScanUsage; use vortex_layout::scan::scan_builder::ScanBuilder; +use vortex_layout::scan::scan_builder::referenced_field_masks; use vortex_layout::scan::split_by::SplitBy; use vortex_layout::scan::v2::ScanFile; use vortex_layout::segments::SegmentSource; @@ -310,8 +312,25 @@ impl VortexFile { /// 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 file = PlanChild::new(self.scan_file().into()).with_row_count(self.row_count()); + 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; }; 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/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-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/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/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 2f2785bac1e..7988ac2b72f 100644 --- a/vortex-scan/src/source.rs +++ b/vortex-scan/src/source.rs @@ -36,12 +36,14 @@ pub struct ScanInput { 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/plan.rs b/vortex-scan/src/source/plan.rs index ebf457b5a49..5bd7cb5a691 100644 --- a/vortex-scan/src/source/plan.rs +++ b/vortex-scan/src/source/plan.rs @@ -37,6 +37,7 @@ 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; @@ -46,7 +47,6 @@ use crate::PartitionStream; use crate::ScanRequest; use crate::execution::ROW_BLOCK_SIZE; use crate::execution::driver::ScanDriver; -use crate::pool::PartitionPool; use crate::pool::RowLimit; use crate::pool::ScanPoolRef; use crate::pool::group_contiguous; @@ -58,12 +58,19 @@ use crate::selection::Selection; /// 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, } @@ -75,6 +82,7 @@ impl PlanChild { Self { input, row_count: None, + splitter: None, pruner: None, } } @@ -86,6 +94,20 @@ impl PlanChild { 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 { @@ -115,6 +137,19 @@ impl PlanChild { .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), @@ -162,14 +197,19 @@ pub enum PlanSourceChild { /// # Splitting and opening /// /// The work of a scan is plan work: chunks of a prepared plan, and the expansion of deferred -/// children. +/// 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) reads the scan's partitions through a [`PartitionPool`], each -/// worker taking one partition at a time. +/// [`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 /// @@ -615,7 +655,7 @@ impl DataSourceScan for PlanScan { } fn open(self: Box) -> VortexResult { - Ok(Arc::new(PartitionPool::new(self))) + plan_pool::open(self.state, self.units) } } 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() + } +}