From 66012dd15f50d9cc9337de83feacc09ebae886f0 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Wed, 18 Nov 2026 20:20:04 -0500 Subject: [PATCH 01/20] Move segment sources into vortex-io Move SegmentId, SegmentSource, SegmentLocation, the coalescing FileSegmentSource and its read driver, BufferSegmentSource and SharedSegmentSource into vortex_io::segments, so the I/O layer can read segments without depending on vortex-file or vortex-layout. The old paths re-export the moved items; behaviour is unchanged. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-file/src/file.rs | 16 +--- vortex-file/src/footer/mod.rs | 13 +++ vortex-file/src/lib.rs | 1 - vortex-file/src/open.rs | 8 +- vortex-file/src/segments/mod.rs | 6 +- vortex-io/Cargo.toml | 2 +- vortex-io/src/lib.rs | 1 + .../src/segments/file.rs | 72 +++++++++------- vortex-io/src/segments/mod.rs | 86 +++++++++++++++++++ .../src/segments}/read/driver.rs | 12 +-- .../src/segments}/read/mod.rs | 0 .../src/segments}/read/request.rs | 0 vortex-io/src/segments/shared.rs | 64 ++++++++++++++ vortex-layout/src/segments/mod.rs | 3 +- vortex-layout/src/segments/shared.rs | 68 ++------------- vortex-scan/src/execution/adaptor.rs | 3 +- vortex-scan/src/execution/filter.rs | 3 +- vortex-scan/src/execution/mod.rs | 27 ++---- vortex-scan/src/source.rs | 58 +------------ 19 files changed, 241 insertions(+), 202 deletions(-) rename vortex-file/src/segments/source.rs => vortex-io/src/segments/file.rs (96%) create mode 100644 vortex-io/src/segments/mod.rs rename {vortex-file/src => vortex-io/src/segments}/read/driver.rs (99%) rename {vortex-file/src => vortex-io/src/segments}/read/mod.rs (100%) rename {vortex-file/src => vortex-io/src/segments}/read/request.rs (100%) create mode 100644 vortex-io/src/segments/shared.rs diff --git a/vortex-file/src/file.rs b/vortex-file/src/file.rs index b461244f056..f610495f90a 100644 --- a/vortex-file/src/file.rs +++ b/vortex-file/src/file.rs @@ -68,18 +68,6 @@ struct FileScanCache { plans: ScanCache, } -fn segment_locations(footer: &Footer) -> Arc<[SegmentLocation]> { - footer - .segment_specs_with_metadata() - .iter() - .map(|spec| SegmentLocation { - offset: spec.offset, - length: spec.length, - alignment: spec.alignment, - }) - .collect() -} - fn layout_reader( segment_source: Arc, footer: &Footer, @@ -131,7 +119,7 @@ impl VortexFile { /// [`scan_file`](Self::scan_file) will share its segment locations and a [`ScanCache`]. pub fn with_caching(self) -> Self { let scan_cache = FileScanCache { - locations: segment_locations(&self.footer), + locations: self.footer.segment_locations(), plans: ScanCache::default(), }; Self { @@ -286,7 +274,7 @@ impl VortexFile { pub fn scan_file(&self) -> ScanFile { let (locations, cache) = match &self.scan_cache { Some(cache) => (Arc::clone(&cache.locations), Some(cache.plans.clone())), - None => (segment_locations(&self.footer), None), + None => (self.footer.segment_locations(), None), }; ScanFile { layout: Arc::clone(self.footer.layout()), diff --git a/vortex-file/src/footer/mod.rs b/vortex-file/src/footer/mod.rs index a677a6e1063..9ffc875519e 100644 --- a/vortex-file/src/footer/mod.rs +++ b/vortex-file/src/footer/mod.rs @@ -32,6 +32,7 @@ use vortex_buffer::ByteBuffer; use vortex_error::VortexResult; use vortex_error::vortex_bail; use vortex_error::vortex_err; +use vortex_io::segments::SegmentLocation; use vortex_layout::LayoutId; use vortex_layout::LayoutRef; use vortex_layout::layout_from_flatbuffer_with_options; @@ -225,6 +226,18 @@ impl Footer { Arc::clone(&self.segments_with_metadata) } + /// Where every segment of the file lives, metadata segments included, indexed by id. + pub(crate) fn segment_locations(&self) -> Arc<[SegmentLocation]> { + self.segments_with_metadata + .iter() + .map(|spec| SegmentLocation { + offset: spec.offset, + length: spec.length, + alignment: spec.alignment, + }) + .collect() + } + /// Computes the compressed size in bytes of every field in the file, keyed by field path. /// /// Sizes are derived by attributing each segment in the [segment map][Self::segment_map] to a diff --git a/vortex-file/src/lib.rs b/vortex-file/src/lib.rs index 8e3ea25e26d..0321127a3d3 100644 --- a/vortex-file/src/lib.rs +++ b/vortex-file/src/lib.rs @@ -110,7 +110,6 @@ mod footer; pub mod multi; mod open; mod pruning; -mod read; /// Segment sources, caches, and sinks used by file readers and writers. pub mod segments; mod source; diff --git a/vortex-file/src/open.rs b/vortex-file/src/open.rs index 5a419c8a008..7c32851674a 100644 --- a/vortex-file/src/open.rs +++ b/vortex-file/src/open.rs @@ -262,10 +262,8 @@ impl VortexOpenOptions { }; footer.validate_file_size(buffer.len() as u64)?; - let segment_source: Arc = Arc::new(BufferSegmentSource::new( - buffer, - footer.segment_specs_with_metadata(), - )); + let segment_source: Arc = + Arc::new(BufferSegmentSource::new(buffer, footer.segment_locations())); let metadata = if include_metadata { block_on(resolve_metadata(&footer, Arc::clone(&segment_source)))? } else { @@ -331,7 +329,7 @@ impl VortexOpenOptions { // Create a segment source backed by the VortexRead implementation. let segment_source = Arc::new(SharedSegmentSource::new(FileSegmentSource::open( - footer.segment_specs_with_metadata(), + footer.segment_locations(), reader, self.session.handle(), metrics, diff --git a/vortex-file/src/segments/mod.rs b/vortex-file/src/segments/mod.rs index d96620fca23..b262209ada1 100644 --- a/vortex-file/src/segments/mod.rs +++ b/vortex-file/src/segments/mod.rs @@ -2,8 +2,10 @@ // SPDX-FileCopyrightText: Copyright the Vortex contributors mod cache; -mod source; pub(crate) mod writer; pub use cache::*; -pub use source::*; +pub use vortex_io::segments::BufferSegmentSource; +pub use vortex_io::segments::FileSegmentSource; +pub use vortex_io::segments::ReadEvent; +pub use vortex_io::segments::RequestMetrics; diff --git a/vortex-io/Cargo.toml b/vortex-io/Cargo.toml index 1dba921a779..4bfd298817b 100644 --- a/vortex-io/Cargo.toml +++ b/vortex-io/Cargo.toml @@ -39,7 +39,7 @@ vortex-buffer = { workspace = true } vortex-error = { workspace = true } vortex-metrics = { workspace = true } vortex-session = { workspace = true } -vortex-utils = { workspace = true } +vortex-utils = { workspace = true, features = ["dashmap"] } [target.'cfg(unix)'.dependencies] custom-labels = { workspace = true } diff --git a/vortex-io/src/lib.rs b/vortex-io/src/lib.rs index c9949e40533..96bb4fee175 100644 --- a/vortex-io/src/lib.rs +++ b/vortex-io/src/lib.rs @@ -24,6 +24,7 @@ pub mod object_store; mod read_at; pub mod request; pub mod runtime; +pub mod segments; pub mod session; #[cfg(not(target_arch = "wasm32"))] pub mod std_file; diff --git a/vortex-file/src/segments/source.rs b/vortex-io/src/segments/file.rs similarity index 96% rename from vortex-file/src/segments/source.rs rename to vortex-io/src/segments/file.rs index 704750d346f..480ab64245c 100644 --- a/vortex-file/src/segments/source.rs +++ b/vortex-io/src/segments/file.rs @@ -30,25 +30,25 @@ use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_error::vortex_err; use vortex_error::vortex_panic; -use vortex_io::ReadAtRequest; -use vortex_io::ReadAtStream; -use vortex_io::VortexReadAt; -use vortex_io::runtime::Handle; -use vortex_io::runtime::JoinOutcome; -use vortex_layout::segments::SegmentFuture; -use vortex_layout::segments::SegmentId; -use vortex_layout::segments::SegmentSource; use vortex_metrics::Counter; use vortex_metrics::Histogram; use vortex_metrics::Label; use vortex_metrics::MetricBuilder; use vortex_metrics::MetricsRegistry; -use crate::SegmentSpec; -use crate::read::IoRequest; -use crate::read::IoRequestStream; -use crate::read::ReadRequest; -use crate::read::RequestId; +use super::SegmentFuture; +use super::SegmentId; +use super::SegmentLocation; +use super::SegmentSource; +use super::read::IoRequest; +use super::read::IoRequestStream; +use super::read::ReadRequest; +use super::read::RequestId; +use crate::ReadAtRequest; +use crate::ReadAtStream; +use crate::VortexReadAt; +use crate::runtime::Handle; +use crate::runtime::JoinOutcome; #[derive(Debug)] /// Events sent from segment futures to the coalescing read driver. @@ -277,7 +277,7 @@ impl Stream for ReadDriver { } pub struct FileSegmentSource { - segments: Arc<[SegmentSpec]>, + segments: Arc<[SegmentLocation]>, /// A queue for sending read request events to the I/O stream. events: mpsc::UnboundedSender, /// Background request driver, joined by readers to surface a driver panic. @@ -294,7 +294,7 @@ impl FileSegmentSource { /// The returned source spawns a background driver on `handle` that coalesces and executes /// random-access read requests. pub fn open( - segments: Arc<[SegmentSpec]>, + segments: Arc<[SegmentLocation]>, reader: R, handle: Handle, metrics: RequestMetrics, @@ -372,7 +372,7 @@ impl SegmentSource for FileSegmentSource { } }; - let SegmentSpec { + let SegmentLocation { offset, length, alignment, @@ -521,14 +521,14 @@ impl RequestMetrics { /// in-memory [`ByteBuffer`]. /// /// Resolves segments synchronously, bypassing the async I/O pipeline. -pub(crate) struct BufferSegmentSource { +pub struct BufferSegmentSource { buffer: ByteBuffer, - segments: Arc<[SegmentSpec]>, + segments: Arc<[SegmentLocation]>, } impl BufferSegmentSource { /// Create a new `BufferSegmentSource` from a buffer and its segment map. - pub fn new(buffer: ByteBuffer, segments: Arc<[SegmentSpec]>) -> Self { + pub fn new(buffer: ByteBuffer, segments: Arc<[SegmentLocation]>) -> Self { Self { buffer, segments } } } @@ -542,7 +542,14 @@ impl SegmentSource for BufferSegmentSource { } }; - let start = spec.offset as usize; + let Ok(start) = usize::try_from(spec.offset) else { + return future::ready(Err(vortex_err!( + "Segment {} offset {} does not fit in memory", + *id, + spec.offset + ))) + .boxed(); + }; let end = start + spec.length as usize; if end > self.buffer.len() { return future::ready(Err(vortex_err!( @@ -561,6 +568,7 @@ impl SegmentSource for BufferSegmentSource { } #[cfg(test)] +#[cfg(feature = "tokio")] mod tests { use std::panic::AssertUnwindSafe; use std::sync::atomic::AtomicBool; @@ -568,11 +576,11 @@ mod tests { use futures::future::BoxFuture; use futures::task::ArcWake; use vortex_error::vortex_bail; - use vortex_io::runtime::tokio::TokioRuntime; - use vortex_layout::segments::SegmentSource; use vortex_metrics::DefaultMetricsRegistry; + use super::SegmentSource; use super::*; + use crate::runtime::tokio::TokioRuntime; fn io_request(id: RequestId, offset: u64, length: usize) -> IoRequest { let (callback, _receiver) = oneshot::channel(); @@ -631,7 +639,7 @@ mod tests { } fn panicking_source() -> FileSegmentSource { - let segments: Arc<[SegmentSpec]> = Arc::from([SegmentSpec { + let segments: Arc<[SegmentLocation]> = Arc::from([SegmentLocation { offset: 0, length: 4, alignment: Alignment::none(), @@ -797,8 +805,8 @@ mod tests { #[tokio::test] async fn read_driver_batches_ready_requests() -> VortexResult<()> { let calls = Arc::new(AtomicUsize::new(0)); - let segments: Arc<[SegmentSpec]> = (0..4) - .map(|i| SegmentSpec { + let segments: Arc<[SegmentLocation]> = (0..4) + .map(|i| SegmentLocation { offset: i * 4, length: 4, alignment: Alignment::none(), @@ -888,8 +896,8 @@ mod tests { let max_active = Arc::new(AtomicUsize::new(0)); let batch_sizes = Arc::new(Mutex::new(Vec::new())); let permits = Arc::new(tokio::sync::Semaphore::new(0)); - let segments: Arc<[SegmentSpec]> = (0..6) - .map(|i| SegmentSpec { + let segments: Arc<[SegmentLocation]> = (0..6) + .map(|i| SegmentLocation { offset: i * 4, length: 4, alignment: Alignment::none(), @@ -948,8 +956,8 @@ mod tests { let max_active = Arc::new(AtomicUsize::new(0)); let batch_sizes = Arc::new(Mutex::new(Vec::new())); let permits = Arc::new(tokio::sync::Semaphore::new(0)); - let segments: Arc<[SegmentSpec]> = (0..8) - .map(|i| SegmentSpec { + let segments: Arc<[SegmentLocation]> = (0..8) + .map(|i| SegmentLocation { offset: i * 4, length: 4, alignment: Alignment::none(), @@ -1034,7 +1042,7 @@ mod tests { ) -> BoxFuture<'static, VortexResult> { async move { // Stagger completions so some reads finish while others are still in flight. - for _ in 0..(offset as usize % 5 + 1) { + for _ in 0..(offset % 5 + 1) { tokio::task::yield_now().await; } vortex_bail!("slow read done") @@ -1047,8 +1055,8 @@ mod tests { #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn read_driver_concurrent_reads_make_progress() { let n = 16u32; - let segments: Arc<[SegmentSpec]> = (0..n) - .map(|i| SegmentSpec { + let segments: Arc<[SegmentLocation]> = (0..n) + .map(|i| SegmentLocation { offset: u64::from(i) * 4, length: 4, alignment: Alignment::none(), diff --git a/vortex-io/src/segments/mod.rs b/vortex-io/src/segments/mod.rs new file mode 100644 index 00000000000..83cc7dee9d0 --- /dev/null +++ b/vortex-io/src/segments/mod.rs @@ -0,0 +1,86 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Segments: the blobs a source names before a scan runs, and the sources that read them. + +mod file; +mod read; +mod shared; + +use std::fmt; +use std::fmt::Display; +use std::ops::Deref; +use std::sync::Arc; + +pub use file::*; +use futures::future::BoxFuture; +pub use shared::*; +use vortex_array::buffer::BufferHandle; +use vortex_buffer::Alignment; +use vortex_error::VortexError; +use vortex_error::VortexResult; + +/// Identifier for a single physical segment referenced by a layout. +/// +/// Segment ids are local to a source. A Vortex file's footer maps ids to physical offsets; other +/// formats assign ids to the blobs their metadata names, and custom storage systems may map them +/// to object-store keys or other random-access locations. +#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct SegmentId(u32); + +impl From for SegmentId { + fn from(value: u32) -> Self { + Self(value) + } +} + +impl TryFrom for SegmentId { + type Error = VortexError; + + fn try_from(value: usize) -> Result { + Ok(Self::from(u32::try_from(value)?)) + } +} + +impl Deref for SegmentId { + type Target = u32; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl Display for SegmentId { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "SegmentId({})", self.0) + } +} + +/// Static future resolving to a segment byte buffer. +pub type SegmentFuture = BoxFuture<'static, VortexResult>; + +/// Reads segments by id. +/// +/// Implementations may issue asynchronous file reads, object-store requests, cache lookups, or +/// in-memory buffer slices. Returned futures must be independent and safe to poll concurrently. +pub trait SegmentSource: 'static + Send + Sync { + /// Request a segment, returning a future that will eventually resolve to the segment data. + fn request(&self, id: SegmentId) -> SegmentFuture; +} + +impl SegmentSource for Arc { + fn request(&self, id: SegmentId) -> SegmentFuture { + self.as_ref().request(id) + } +} + +/// Where a segment's bytes live in its source. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct SegmentLocation { + /// Byte offset of the segment from the start of the source. + pub offset: u64, + /// Length of the segment in bytes. + pub length: u32, + /// Alignment the segment's bytes must have once delivered. + pub alignment: Alignment, +} diff --git a/vortex-file/src/read/driver.rs b/vortex-io/src/segments/read/driver.rs similarity index 99% rename from vortex-file/src/read/driver.rs rename to vortex-io/src/segments/read/driver.rs index ad9c6570202..edf80820fcb 100644 --- a/vortex-file/src/read/driver.rs +++ b/vortex-io/src/segments/read/driver.rs @@ -12,13 +12,13 @@ use pin_project_lite::pin_project; use tracing::trace; use vortex_buffer::Alignment; use vortex_error::VortexExpect; -use vortex_io::CoalesceConfig; use vortex_utils::aliases::hash_set::HashSet; -use crate::read::ReadRequest; -use crate::read::RequestId; -use crate::read::request::CoalescedRequest; -use crate::read::request::IoRequest; +use super::ReadRequest; +use super::RequestId; +use super::request::CoalescedRequest; +use super::request::IoRequest; +use crate::CoalesceConfig; use crate::segments::ReadEvent; use crate::segments::RequestMetrics; @@ -348,7 +348,7 @@ mod tests { use vortex_metrics::MetricsRegistry; use super::*; - use crate::read::request::IoRequestInner; + use crate::segments::read::request::IoRequestInner; fn create_request( id: usize, diff --git a/vortex-file/src/read/mod.rs b/vortex-io/src/segments/read/mod.rs similarity index 100% rename from vortex-file/src/read/mod.rs rename to vortex-io/src/segments/read/mod.rs diff --git a/vortex-file/src/read/request.rs b/vortex-io/src/segments/read/request.rs similarity index 100% rename from vortex-file/src/read/request.rs rename to vortex-io/src/segments/read/request.rs diff --git a/vortex-io/src/segments/shared.rs b/vortex-io/src/segments/shared.rs new file mode 100644 index 00000000000..dbaf553264a --- /dev/null +++ b/vortex-io/src/segments/shared.rs @@ -0,0 +1,64 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +use std::sync::Arc; + +use futures::FutureExt; +use futures::TryFutureExt; +use futures::future::BoxFuture; +use futures::future::WeakShared; +use vortex_array::buffer::BufferHandle; +use vortex_error::SharedVortexResult; +use vortex_error::VortexError; +use vortex_error::VortexExpect; +use vortex_utils::aliases::dash_map::DashMap; +use vortex_utils::aliases::dash_map::Entry; + +use super::SegmentFuture; +use super::SegmentId; +use super::SegmentSource; + +/// A [`SegmentSource`] that allows multiple requesters to await the same underlying segment +/// request. +pub struct SharedSegmentSource { + inner: S, + in_flight: DashMap>, +} + +type SharedSegmentFuture = BoxFuture<'static, SharedVortexResult>; + +impl SharedSegmentSource { + /// Create a new `SharedSegmentSource` wrapping the provided inner source. + pub fn new(inner: S) -> Self { + Self { + inner, + in_flight: DashMap::with_hasher_and_shard_amount(Default::default(), 64), + } + } +} + +impl SegmentSource for SharedSegmentSource { + fn request(&self, id: SegmentId) -> SegmentFuture { + loop { + match self.in_flight.entry(id) { + Entry::Occupied(e) => { + if let Some(shared_future) = e.get().upgrade() { + return shared_future.map_err(VortexError::from).boxed(); + } else { + // The future has been dropped, remove the entry and try again. + e.remove(); + } + } + Entry::Vacant(e) => { + let future = self.inner.request(id).map_err(Arc::new).boxed().shared(); + e.insert( + future + .downgrade() + .vortex_expect("just created, cannot be polled to completion"), + ); + return future.map_err(VortexError::from).boxed(); + } + } + } + } +} diff --git a/vortex-layout/src/segments/mod.rs b/vortex-layout/src/segments/mod.rs index d20cf14f6c0..3d2f47e4c73 100644 --- a/vortex-layout/src/segments/mod.rs +++ b/vortex-layout/src/segments/mod.rs @@ -9,6 +9,7 @@ //! scans. mod cache; +#[cfg(test)] mod shared; mod sink; mod source; @@ -18,10 +19,10 @@ mod usage; mod test; pub use cache::*; -pub use shared::*; pub use sink::*; pub use source::*; #[cfg(any(test, feature = "_test-harness"))] pub use test::*; pub use usage::*; +pub use vortex_io::segments::SharedSegmentSource; pub use vortex_scan::source::SegmentId; diff --git a/vortex-layout/src/segments/shared.rs b/vortex-layout/src/segments/shared.rs index 6abc4145299..0f9253bc13e 100644 --- a/vortex-layout/src/segments/shared.rs +++ b/vortex-layout/src/segments/shared.rs @@ -1,75 +1,17 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors -use std::sync::Arc; - -use futures::FutureExt; -use futures::TryFutureExt; -use futures::future::BoxFuture; -use futures::future::WeakShared; -use vortex_array::buffer::BufferHandle; -use vortex_error::SharedVortexResult; -use vortex_error::VortexError; -use vortex_error::VortexExpect; -use vortex_utils::aliases::dash_map::DashMap; -use vortex_utils::aliases::dash_map::Entry; - -use crate::segments::SegmentFuture; -use crate::segments::SegmentId; -use crate::segments::SegmentSource; - -/// A [`SegmentSource`] that allows multiple requesters to await the same underlying segment -/// request. -pub struct SharedSegmentSource { - inner: S, - in_flight: DashMap>, -} - -type SharedSegmentFuture = BoxFuture<'static, SharedVortexResult>; - -impl SharedSegmentSource { - /// Create a new `SharedSegmentSource` wrapping the provided inner source. - pub fn new(inner: S) -> Self { - Self { - inner, - in_flight: DashMap::with_hasher_and_shard_amount(Default::default(), 64), - } - } -} - -impl SegmentSource for SharedSegmentSource { - fn request(&self, id: SegmentId) -> SegmentFuture { - loop { - match self.in_flight.entry(id) { - Entry::Occupied(e) => { - if let Some(shared_future) = e.get().upgrade() { - return shared_future.map_err(VortexError::from).boxed(); - } else { - // The future has been dropped, remove the entry and try again. - e.remove(); - } - } - Entry::Vacant(e) => { - let future = self.inner.request(id).map_err(Arc::new).boxed().shared(); - e.insert( - future - .downgrade() - .vortex_expect("just created, cannot be polled to completion"), - ); - return future.map_err(VortexError::from).boxed(); - } - } - } - } -} - #[cfg(test)] mod tests { + use std::sync::Arc; + use vortex_buffer::ByteBuffer; + use vortex_io::segments::SharedSegmentSource; - use super::*; use crate::segments::CountingSegmentSource; + use crate::segments::SegmentId; use crate::segments::SegmentSink; + use crate::segments::SegmentSource; use crate::segments::TestSegments; use crate::sequence::SequenceId; diff --git a/vortex-scan/src/execution/adaptor.rs b/vortex-scan/src/execution/adaptor.rs index c23684aca0b..9964baf4370 100644 --- a/vortex-scan/src/execution/adaptor.rs +++ b/vortex-scan/src/execution/adaptor.rs @@ -22,6 +22,7 @@ use crate::execution::SegmentLocation; use crate::execution::pipeline::ReadId; use crate::execution::pipeline::Scan; use crate::execution::pipeline::Turn; +use crate::execution::segment_target; use crate::planning::planner::State; use crate::source::SegmentId; @@ -150,7 +151,7 @@ impl ScanAdaptor { Ok(request::IoRequest { intent: IoIntent::Fetch, request: request::IoRequestId(id), - target: location.target(), + target: segment_target(&location), }) } diff --git a/vortex-scan/src/execution/filter.rs b/vortex-scan/src/execution/filter.rs index 29afd51771e..16cc3db2292 100644 --- a/vortex-scan/src/execution/filter.rs +++ b/vortex-scan/src/execution/filter.rs @@ -31,6 +31,7 @@ use super::adaptor::AdaptorStep; use super::adaptor::Piece; use super::adaptor::ScanAdaptor; use super::projection::ProjectionPlanner; +use super::segment_target; use crate::execution::filter_expr::FilterExpr; use crate::execution::pipeline::Scan; use crate::execution::pipeline::Split; @@ -228,7 +229,7 @@ pub(super) fn hint( batch.push(IoRequest { intent, request: IoRequestId(*next_hint), - target: locations[*segment as usize].target(), + target: segment_target(&locations[*segment as usize]), }); *next_hint -= 1; } diff --git a/vortex-scan/src/execution/mod.rs b/vortex-scan/src/execution/mod.rs index 80cfcafbd6e..caa6a7ce099 100644 --- a/vortex-scan/src/execution/mod.rs +++ b/vortex-scan/src/execution/mod.rs @@ -32,9 +32,9 @@ mod selection; use std::ops::Range; use std::sync::Arc; -use vortex_buffer::Alignment; use vortex_io::request::IoService; use vortex_io::request::IoTarget; +pub use vortex_io::segments::SegmentLocation; use vortex_mask::Mask; use vortex_session::VortexSession; @@ -62,25 +62,12 @@ use crate::planning::planner::WorkScope; use crate::selection::Selection; use crate::source::SegmentSource; -/// Where a segment's bytes live in the file. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub struct SegmentLocation { - /// Byte offset of the segment from the start of the source. - pub offset: u64, - /// Length of the segment in bytes. - pub length: u32, - /// Alignment the segment's bytes must have once delivered. - pub alignment: Alignment, -} - -impl SegmentLocation { - /// The byte range a read of the segment asks for. - fn target(&self) -> IoTarget { - IoTarget::Range { - offset: self.offset, - len: self.length as usize, - alignment: self.alignment, - } +/// The byte range a read of the segment at `location` asks for. +fn segment_target(location: &SegmentLocation) -> IoTarget { + IoTarget::Range { + offset: location.offset, + len: location.length as usize, + alignment: location.alignment, } } diff --git a/vortex-scan/src/source.rs b/vortex-scan/src/source.rs index 69d14f40484..08a3f38c296 100644 --- a/vortex-scan/src/source.rs +++ b/vortex-scan/src/source.rs @@ -3,69 +3,17 @@ //! Source inputs and byte access for scans. -use std::fmt; -use std::fmt::Display; -use std::ops::Deref; use std::sync::Arc; -use futures::future::BoxFuture; -use vortex_array::buffer::BufferHandle; use vortex_array::dtype::DType; -use vortex_error::VortexError; -use vortex_error::VortexResult; +pub use vortex_io::segments::SegmentFuture; +pub use vortex_io::segments::SegmentId; +pub use vortex_io::segments::SegmentSource; use crate::execution::SegmentLocation; use crate::execution::cache::ScanCache; use crate::plan::LazyPlanRef; -/// Identifier for a single physical segment referenced by a layout. -/// -/// Segment ids are local to a file or segment source. The file footer maps ids to physical offsets; -/// custom storage systems may map them to object-store keys or other random-access locations. -// TODO(ngates): should this be a `[u8]` instead? Allowing for arbitrary segment identifiers? -#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] -pub struct SegmentId(u32); - -impl From for SegmentId { - fn from(value: u32) -> Self { - Self(value) - } -} - -impl TryFrom for SegmentId { - type Error = VortexError; - - fn try_from(value: usize) -> Result { - Ok(Self::from(u32::try_from(value)?)) - } -} - -impl Deref for SegmentId { - type Target = u32; - - fn deref(&self) -> &Self::Target { - &self.0 - } -} - -impl Display for SegmentId { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "SegmentId({})", self.0) - } -} - -/// Static future resolving to a segment byte buffer. -pub type SegmentFuture = BoxFuture<'static, VortexResult>; - -/// Provides bytes to scan sources. -/// -/// Implementations may issue asynchronous file reads, object-store requests, cache lookups, or -/// in-memory buffer slices. Returned futures must be independent and safe to poll concurrently. -pub trait SegmentSource: 'static + Send + Sync { - /// Request a segment, returning a future that will eventually resolve to the segment data. - fn request(&self, id: SegmentId) -> SegmentFuture; -} - /// The plan and byte source used to prepare a scan. /// /// The lazy root defers lowering until preparation runs on a compute task. Segment identifiers From a11813abbc2b16ce1bf01395f5eeb460555e9e06 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Wed, 18 Nov 2026 20:20:12 -0500 Subject: [PATCH 02/20] Name scan reads by source and segment Scan I/O requests carry a SourceId and a segment target instead of a byte range, and one IoScheduler per session serves them. Placed sources read through the coalescing FileSegmentSource, serve the segments the footer read already fetched, share in-flight reads through SharedSegmentSource, and reuse a live registration across concurrent scans of one file; opaque sources read segments themselves. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-datafusion/src/persistent/opener.rs | 14 +- vortex-file/src/file.rs | 18 +- vortex-file/src/open.rs | 24 +- vortex-file/src/v2/scan/tests.rs | 73 +- vortex-io/src/request/mod.rs | 92 ++- .../src/request}/retain.rs | 34 +- vortex-io/src/request/scheduler.rs | 736 ++++++++++++++++++ vortex-io/src/request/source.rs | 108 --- vortex-io/src/request/source/tests.rs | 155 ---- vortex-io/src/request/tests.rs | 46 +- vortex-io/src/session.rs | 31 + vortex-layout/src/scan/v2/mod.rs | 8 +- vortex-layout/src/scan/v2/tests.rs | 9 +- vortex-scan/src/execution/adaptor.rs | 15 +- vortex-scan/src/execution/cache.rs | 55 +- vortex-scan/src/execution/driver/tests.rs | 3 +- vortex-scan/src/execution/filter.rs | 21 +- vortex-scan/src/execution/io.rs | 404 ---------- vortex-scan/src/execution/mod.rs | 34 +- .../src/execution/planning/driver/mod.rs | 2 +- .../src/execution/planning/driver/tests.rs | 27 +- .../src/execution/planning/tests/scripted.rs | 11 +- vortex-scan/src/execution/projection.rs | 6 +- vortex-scan/src/execution/prune.rs | 8 +- vortex-scan/src/prepare.rs | 12 +- vortex-scan/src/source.rs | 5 +- vortex-scan/src/test.rs | 3 +- 27 files changed, 1103 insertions(+), 851 deletions(-) rename {vortex-scan/src/execution => vortex-io/src/request}/retain.rs (86%) create mode 100644 vortex-io/src/request/scheduler.rs delete mode 100644 vortex-io/src/request/source.rs delete mode 100644 vortex-io/src/request/source/tests.rs delete mode 100644 vortex-scan/src/execution/io.rs diff --git a/vortex-datafusion/src/persistent/opener.rs b/vortex-datafusion/src/persistent/opener.rs index 3ba227d6ca5..1676b3ef956 100644 --- a/vortex-datafusion/src/persistent/opener.rs +++ b/vortex-datafusion/src/persistent/opener.rs @@ -56,6 +56,7 @@ use vortex::layout::LayoutReader; use vortex::layout::scan::metrics::ScanMetrics; use vortex::layout::scan::scan_builder::ScanBuilder; use vortex::layout::scan::v2::ScanBuilder as V2ScanBuilder; +use vortex::layout::scan::v2::SegmentReader; use vortex::layout::scan::v2::partition_row_range; use vortex::layout::segments::SegmentSource; use vortex::metrics::Label; @@ -486,11 +487,14 @@ impl FileOpener for VortexOpener { let map_batch = move |chunk| to_record_batch(chunk, &stream_target_field, &session); let stream = if scan_v2 { let mut scan_file = vxf.scan_file(); - scan_file.segments = shared_segment_source( - &segment_sources, - &file.object_meta.location, - scan_file.segments, - ); + // A placed file is shared through its scan cache's scheduler registration. + if let SegmentReader::Opaque(segments) = scan_file.reader { + scan_file.reader = SegmentReader::Opaque(shared_segment_source( + &segment_sources, + &file.object_meta.location, + segments, + )); + } scan_file.cache = Some(shared_scan_cache(&scan_caches, &file.object_meta.location)); let mut builder = V2ScanBuilder::new(vxf.session().clone(), scan_file) .with_projection(scan_projection) diff --git a/vortex-file/src/file.rs b/vortex-file/src/file.rs index f610495f90a..6f27eaa0eb6 100644 --- a/vortex-file/src/file.rs +++ b/vortex-file/src/file.rs @@ -17,6 +17,7 @@ use vortex_array::dtype::FieldMask; use vortex_array::expr::Expression; use vortex_buffer::ByteBuffer; use vortex_error::VortexResult; +use vortex_io::request::SegmentReader; use vortex_layout::LayoutReader; use vortex_layout::scan::layout::LayoutReaderDataSource; use vortex_layout::scan::metrics::ScanUsage; @@ -58,6 +59,9 @@ pub struct VortexFile { scan_cache: Option, /// Resource usage that segment reads and scans of this handle add to. usage: Option>, + /// How V2 scans read the file's segments when the session's I/O scheduler can read them + /// directly, or `None` to read through [`Self::segment_source`]. + scan_reader: Option, } /// What repeated V2 scans of a file share: its segment locations, read from the footer once, and @@ -104,9 +108,15 @@ impl VortexFile { layout_reader_cache: None, scan_cache: None, usage: None, + scan_reader: None, } } + pub(crate) fn with_scan_reader(mut self, scan_reader: Option) -> Self { + self.scan_reader = scan_reader; + self + } + pub(crate) fn with_metadata(mut self, metadata: Arc>) -> Self { self.metadata = metadata; self @@ -130,6 +140,7 @@ impl VortexFile { layout_reader_cache: Some(OnceLock::new()), scan_cache: Some(scan_cache), usage: self.usage, + scan_reader: self.scan_reader, } } @@ -187,6 +198,7 @@ impl VortexFile { pub fn with_segment_source(mut self, segment_source: Arc) -> Self { self.segment_source = segment_source; self.usage = None; + self.scan_reader = None; if self.layout_reader_cache.is_some() { self.layout_reader_cache = Some(OnceLock::new()); } @@ -276,10 +288,14 @@ impl VortexFile { Some(cache) => (Arc::clone(&cache.locations), Some(cache.plans.clone())), None => (self.footer.segment_locations(), None), }; + let reader = self + .scan_reader + .clone() + .unwrap_or_else(|| SegmentReader::Opaque(Arc::clone(&self.segment_source))); ScanFile { layout: Arc::clone(self.footer.layout()), locations, - segments: Arc::clone(&self.segment_source), + reader, cache, } } diff --git a/vortex-file/src/open.rs b/vortex-file/src/open.rs index 7c32851674a..1c96934c143 100644 --- a/vortex-file/src/open.rs +++ b/vortex-file/src/open.rs @@ -14,6 +14,8 @@ use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_error::vortex_err; use vortex_io::VortexReadAt; +use vortex_io::request::PlacedSegments; +use vortex_io::request::SegmentReader; use vortex_io::session::RuntimeSessionExt; use vortex_layout::segments::InstrumentedSegmentCache; use vortex_layout::segments::NoOpSegmentCache; @@ -316,6 +318,21 @@ impl VortexOpenOptions { } } + let metrics = RequestMetrics::new(metrics_registry.as_ref(), self.labels.clone()); + + // Without a user segment cache, V2 scans register the file with the session's I/O + // scheduler, which reads and coalesces its segments itself. + let scan_reader = self.segment_cache.is_none().then(|| { + let placed = PlacedSegments::new( + Arc::new(reader.clone()), + self.session.handle(), + metrics.clone(), + ); + SegmentReader::Placed(Arc::new( + placed.with_initial_segments(initial_segments.clone()), + )) + }); + let segment_cache = Arc::new(InstrumentedSegmentCache::new( InitialReadSegmentCache { initial: initial_segments, @@ -325,8 +342,6 @@ impl VortexOpenOptions { self.labels.clone(), )); - let metrics = RequestMetrics::new(metrics_registry.as_ref(), self.labels); - // Create a segment source backed by the VortexRead implementation. let segment_source = Arc::new(SharedSegmentSource::new(FileSegmentSource::open( footer.segment_locations(), @@ -346,8 +361,9 @@ impl VortexOpenOptions { } else { Arc::new(HashMap::new()) }; - let file = - VortexFile::new(footer, segment_source, self.session.clone()).with_metadata(metadata); + let file = VortexFile::new(footer, segment_source, self.session.clone()) + .with_metadata(metadata) + .with_scan_reader(scan_reader); Ok(if self.cache_layout_reader { file.with_caching() } else { diff --git a/vortex-file/src/v2/scan/tests.rs b/vortex-file/src/v2/scan/tests.rs index 6b3b030b971..16e9b499347 100644 --- a/vortex-file/src/v2/scan/tests.rs +++ b/vortex-file/src/v2/scan/tests.rs @@ -3,26 +3,35 @@ use std::sync::Arc; use std::sync::LazyLock; +use std::sync::atomic::AtomicUsize; +use std::sync::atomic::Ordering; use arrow_array::RecordBatch; use arrow_array::cast::AsArray; use arrow_schema::Field; use futures::TryStreamExt; +use futures::future::BoxFuture; use vortex_array::ArrayRef; use vortex_array::IntoArray; 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::buffer::BufferHandle; use vortex_arrow::ArrowScanExt; use vortex_arrow::ArrowSessionExt; use vortex_arrow::ExecuteArrowExt; +use vortex_buffer::Alignment; +use vortex_buffer::ByteBuffer; use vortex_buffer::ByteBufferMut; use vortex_buffer::buffer; use vortex_error::VortexResult; +use vortex_io::VortexReadAt; use vortex_io::runtime::tokio::TokioRuntime; use vortex_io::session::RuntimeSession; use vortex_layout::scan::v2::ScanBuilder; +use vortex_layout::scan::v2::SegmentReader; use vortex_layout::session::LayoutSession; use vortex_session::VortexSession; @@ -40,7 +49,7 @@ static SESSION: LazyLock = LazyLock::new(|| { session }); -async fn file() -> VortexResult { +async fn file_bytes() -> VortexResult { let chunks = 8; let numbers = ChunkedArray::from_iter( (0..chunks).map(|chunk| buffer![chunk, chunk + 1, chunk + 2, chunk + 3].into_array()), @@ -56,7 +65,11 @@ async fn file() -> VortexResult { .write_options() .write(&mut buf, array.into_array().to_array_stream()) .await?; - SESSION.open_options().open_buffer(buf) + Ok(buf.freeze()) +} + +async fn file() -> VortexResult { + SESSION.open_options().open_buffer(file_bytes().await?) } fn driver() -> ScanDriver { @@ -93,3 +106,59 @@ async fn record_batches_match_arrays() -> VortexResult<()> { assert_eq!(given, expected); Ok(()) } + +/// A reader of an in-memory file that counts its reads. +#[derive(Clone)] +struct CountingRead { + bytes: ByteBuffer, + reads: Arc, +} + +impl VortexReadAt for CountingRead { + fn concurrency(&self) -> usize { + self.bytes.concurrency() + } + + fn size(&self) -> BoxFuture<'static, VortexResult> { + self.bytes.size() + } + + fn read_at( + &self, + offset: u64, + length: usize, + alignment: Alignment, + ) -> BoxFuture<'static, VortexResult> { + self.reads.fetch_add(1, Ordering::Relaxed); + self.bytes.read_at(offset, length, alignment) + } +} + +/// A file opened from a reader is placed: the session's scheduler reads its segments directly, +/// starting from the ones the footer read already fetched. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn placed_files_scan_like_buffered_ones() -> VortexResult<()> { + let bytes = file_bytes().await?; + let reads = Arc::new(AtomicUsize::new(0)); + let reader = CountingRead { + bytes: bytes.clone(), + reads: Arc::clone(&reads), + }; + let placed = SESSION.open_options().open_read(reader).await?; + let buffered = SESSION.open_options().open_buffer(bytes)?; + assert!(matches!( + placed.scan_file().reader, + SegmentReader::Placed(_) + )); + let opened = reads.load(Ordering::Relaxed); + + let scan = |file: &VortexFile| ScanBuilder::new(SESSION.clone(), file.scan_file()); + let dtype = scan(&placed).dtype().clone(); + let collect = |arrays: Vec| ChunkedArray::try_new(arrays, dtype.clone()); + let actual = collect(driver().run(scan(&placed)).try_collect().await?)?; + let expected = collect(driver().run(scan(&buffered)).try_collect().await?)?; + assert_arrays_eq!(actual, expected, &mut SESSION.create_execution_ctx()); + // The footer read covered the whole small file, so the scan reads nothing more. + assert_eq!(reads.load(Ordering::Relaxed), opened); + Ok(()) +} diff --git a/vortex-io/src/request/mod.rs b/vortex-io/src/request/mod.rs index efce222ba0f..fbc0b15a783 100644 --- a/vortex-io/src/request/mod.rs +++ b/vortex-io/src/request/mod.rs @@ -1,58 +1,79 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors -//! IO requests, results, and the source that fulfils them. +//! IO requests, results, and the scheduler that fulfils them. //! -//! The protocol moves bytes at a range. A source has exactly one other property a consumer may -//! ask for, its length, because a Vortex file cannot be located from its start without it. -//! Nothing else is a request: anything a stage needs that is not bytes at a range is -//! construction-time data for that stage. +//! A request names a registered source, a segment of that source, and the bytes of the segment it +//! wants. A source has exactly one other property a consumer may ask for, its length, because a +//! Vortex file cannot be located from its start without it. Where a segment's bytes live is +//! construction-time data the scheduler holds, so every read keeps its name from the operator that +//! asks for it to the source that serves it. +use std::ops::Range; use std::sync::Arc; use std::task::Context; use std::task::Poll; use vortex_array::buffer::BufferHandle; -use vortex_buffer::Alignment; use vortex_error::VortexResult; use vortex_error::vortex_panic; -mod source; +mod retain; +mod scheduler; -pub use source::ReadAtIoSource; +pub use retain::DEFAULT_RETAINED_BYTES; +pub use scheduler::IoScheduler; +pub use scheduler::PlacedSegments; +pub use scheduler::RegisteredSource; +pub use scheduler::SegmentReader; + +pub use crate::segments::SegmentId; /// Consumer-chosen label for one request, unique within the issuing object. #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] pub struct IoRequestId(pub u32); -/// What to fetch from the source: its length, or bytes at a range. This enum is closed; see the -/// module documentation. +/// A source registered with an [`IoScheduler`], unique among the scheduler's live sources. #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] +pub struct SourceId(pub u32); + +/// What to fetch from a source: its length, or bytes of one of its segments. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] pub enum IoTarget { /// Total length of the source in bytes. Size, - /// An absolute byte range. - Range { - /// Absolute byte offset of the first byte. - offset: u64, - /// Number of bytes to read. - len: usize, - /// The alignment the delivered bytes have at least. - alignment: Alignment, + /// Bytes of one segment. + Segment { + /// The segment, local to the request's source. + segment: SegmentId, + /// Which bytes of the segment. + bytes: SegmentBytes, }, } impl IoTarget { - /// A byte range whose bytes need no particular alignment. - pub fn range(offset: u64, len: usize) -> Self { - Self::Range { - offset, - len, - alignment: Alignment::none(), + /// The whole of `segment`. + pub fn segment(segment: SegmentId) -> Self { + Self::Segment { + segment, + bytes: SegmentBytes::All, } } } +/// The bytes of a segment a request wants. Either way they are delivered as one buffer at the +/// segment's alignment. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub enum SegmentBytes { + /// The whole segment. + All, + /// Sorted, disjoint ranges, relative to the start of the segment, delivered concatenated in + /// order with no padding. A consumer that rounds each range out to the segment's alignment + /// gets every buffer inside it aligned, because a segment's buffers are padded relative to + /// its start. One buffer per range is one request per range. + Ranges(Arc<[Range]>), +} + /// A stage's reason for registering bytes. Optional hints may be declined by the service. #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] pub enum IoIntent { @@ -64,13 +85,15 @@ pub enum IoIntent { Announce, } -/// One request: a consumer-chosen id and the target it names. -#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] +/// One request: a consumer-chosen id, the source it reads, and the target it names. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] pub struct IoRequest { /// Required delivery, background prefetch, or coalescing-only interest. pub intent: IoIntent, /// Identifies the request within the issuing object. pub request: IoRequestId, + /// The source to read. + pub source: SourceId, /// What to fetch. pub target: IoTarget, } @@ -79,7 +102,7 @@ pub struct IoRequest { pub type IoBatch = Vec; /// Result for one request. The variant matches the target: `Size` for `Size`, `Bytes` for -/// `Range`. The driver checks this before delivering, so a consumer never sees a mismatch. +/// `Segment`. The driver checks this before delivering, so a consumer never sees a mismatch. #[derive(Debug, Clone)] pub enum IoResult { /// Total length of the source in bytes. @@ -93,7 +116,7 @@ impl IoResult { pub fn matches(&self, target: &IoTarget) -> bool { matches!( (self, target), - (Self::Size(_), IoTarget::Size) | (Self::Bytes(_), IoTarget::Range { .. }) + (Self::Size(_), IoTarget::Size) | (Self::Bytes(_), IoTarget::Segment { .. }) ) } @@ -146,10 +169,10 @@ pub trait IoSource: Send + Sync { fn clear(&self); } -/// A byte source's IO service, shared by everything that reads the source. +/// An IO service, shared by everything that reads its sources. /// /// Each registration scope reads through its own [`IoSource`], and the service is free to share -/// and coalesce the reads of all of them. +/// and coalesce the reads of all of them. [`IoScheduler`] is the default implementation. pub trait IoService: Send + Sync { /// A fresh source for one registration scope. fn session(&self) -> Arc; @@ -176,19 +199,20 @@ pub struct IoSlot { } impl IoSlot { - /// Issues a request for `target` with a fresh id. Panics if one is already outstanding or - /// its result has not been taken, since that is a bug in the owner. - pub fn issue(&mut self, target: IoTarget) -> IoBatch { + /// Issues a request for `target` of `source` with a fresh id. Panics if one is already + /// outstanding or its result has not been taken, since that is a bug in the owner. + pub fn issue(&mut self, source: SourceId, target: IoTarget) -> IoBatch { if self.request.is_some() || self.result.is_some() { vortex_panic!("IoSlot: issue while a request is outstanding"); } let request = IoRequest { intent: IoIntent::Fetch, request: IoRequestId(self.next_id), + source, target, }; self.next_id += 1; - self.request = Some(request); + self.request = Some(request.clone()); vec![request] } diff --git a/vortex-scan/src/execution/retain.rs b/vortex-io/src/request/retain.rs similarity index 86% rename from vortex-scan/src/execution/retain.rs rename to vortex-io/src/request/retain.rs index 688bf59b1e6..989b37d7ec0 100644 --- a/vortex-scan/src/execution/retain.rs +++ b/vortex-io/src/request/retain.rs @@ -9,46 +9,40 @@ use std::sync::Arc; use futures::FutureExt; use futures::TryFutureExt; use parking_lot::Mutex; -use rustc_hash::FxHashMap; use vortex_array::buffer::BufferHandle; +use vortex_utils::aliases::hash_map::HashMap; -use crate::source::SegmentFuture; -use crate::source::SegmentId; -use crate::source::SegmentSource; +use crate::segments::SegmentFuture; +use crate::segments::SegmentId; +use crate::segments::SegmentSource; /// The host bytes of recently read segments, evicting the least recently used past a budget. /// /// A V2 scan cuts its rows into chunks that each read through a session of their own, and a -/// stored segment that spans a chunk boundary is read by every chunk it overlaps. The file's segment +/// stored segment that spans a chunk boundary is read by every chunk it overlaps. A registered /// source shares a read only while it is in flight, so a chunk that starts after its neighbour /// finished would read the segment again. Neighbouring chunks run close together, so a small /// budget is enough to read each such segment once. -pub(super) struct RetainedSegments { +pub(crate) struct RetainedSegments { budget: u64, state: Mutex, } -/// The bytes a file's scans retain by default. -const DEFAULT_RETAINED_BYTES: u64 = 64 << 20; - -impl Default for RetainedSegments { - fn default() -> Self { - Self::new(DEFAULT_RETAINED_BYTES) - } -} +/// The bytes a registered source retains by default. +pub const DEFAULT_RETAINED_BYTES: u64 = 64 << 20; #[derive(Default)] struct State { bytes: u64, tick: u64, /// Each retained segment and the tick of its last use. - segments: FxHashMap, + segments: HashMap, /// Retained segments by the tick of their last use, oldest first. by_use: BTreeMap, } impl RetainedSegments { - pub(super) fn new(budget: u64) -> Self { + pub(crate) fn new(budget: u64) -> Self { Self { budget, state: Mutex::default(), @@ -94,9 +88,9 @@ impl RetainedSegments { /// Serves segments from [`RetainedSegments`] before reading them from `inner`, and retains /// what it reads. -pub(super) struct RetainingSegmentSource { - pub(super) inner: Arc, - pub(super) retained: Arc, +pub(crate) struct RetainingSegmentSource { + pub(crate) inner: Arc, + pub(crate) retained: Arc, } impl SegmentSource for RetainingSegmentSource { @@ -118,7 +112,7 @@ mod tests { use vortex_buffer::ByteBuffer; use super::RetainedSegments; - use crate::source::SegmentId; + use crate::segments::SegmentId; fn buffer(len: usize) -> BufferHandle { BufferHandle::new_host(ByteBuffer::from(vec![0u8; len])) diff --git a/vortex-io/src/request/scheduler.rs b/vortex-io/src/request/scheduler.rs new file mode 100644 index 00000000000..0443bcd2dbf --- /dev/null +++ b/vortex-io/src/request/scheduler.rs @@ -0,0 +1,736 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! The default [`IoService`]: one scheduler for every source a session reads. +//! +//! A source registers once and every request names it by [`SourceId`]. A placed source's +//! segments live at known offsets of one object, and the scheduler reads them through a +//! coalescing driver it spawns for the source; an opaque source reads each segment itself. For +//! both kinds the scheduler shares in-flight reads across sessions, retains recently read +//! segments, serves prefetch and announce hints, and delivers the bytes a request names as one +//! buffer. + +use std::collections::VecDeque; +use std::ptr; +use std::sync::Arc; +use std::sync::Weak; +use std::sync::atomic::AtomicU32; +use std::sync::atomic::Ordering; +use std::task::Context; +use std::task::Poll; +use std::task::Waker; + +use futures::FutureExt; +use futures::StreamExt; +use futures::TryFutureExt; +use futures::future; +use futures::future::BoxFuture; +use futures::future::Shared; +use futures::stream::FuturesUnordered; +use parking_lot::Mutex; +use vortex_array::buffer::BufferHandle; +use vortex_buffer::Alignment; +use vortex_buffer::ByteBuffer; +use vortex_buffer::ByteBufferMut; +use vortex_error::VortexError; +use vortex_error::VortexResult; +use vortex_error::vortex_bail; +use vortex_error::vortex_ensure; +use vortex_error::vortex_err; +use vortex_utils::aliases::hash_map::HashMap; + +use super::Completion; +use super::IoBatch; +use super::IoIntent; +use super::IoOwnerId; +use super::IoResult; +use super::IoService; +use super::IoSource; +use super::IoTarget; +use super::SegmentBytes; +use super::SourceId; +use super::retain::RetainedSegments; +use super::retain::RetainingSegmentSource; +use crate::VortexReadAt; +use crate::runtime::Handle; +use crate::segments::FileSegmentSource; +use crate::segments::RequestMetrics; +use crate::segments::SegmentFuture; +use crate::segments::SegmentId; +use crate::segments::SegmentLocation; +use crate::segments::SegmentSource; +use crate::segments::SharedSegmentSource; + +/// How a registered source reads its segments. +#[derive(Clone)] +pub enum SegmentReader { + /// Segments at their locations in one object, which the scheduler reads and coalesces. + Placed(Arc), + /// A source that reads each segment itself, such as a key/value store or an in-memory one. + Opaque(Arc), +} + +/// The segments of one object that the scheduler reads through a coalescing driver. +/// +/// Registering the same `PlacedSegments` again while an earlier registration lives returns that +/// registration, so concurrent scans of one object share its driver, reads and retained segments. +pub struct PlacedSegments { + read: Arc, + handle: Handle, + metrics: RequestMetrics, + initial: Arc>, + registration: Mutex>, +} + +impl PlacedSegments { + /// Segments of `read`, whose driver runs on `handle` and records its reads in `metrics`. + pub fn new(read: Arc, handle: Handle, metrics: RequestMetrics) -> Self { + Self { + read, + handle, + metrics, + initial: Arc::default(), + registration: Mutex::default(), + } + } + + /// Serves `initial`, segments already read, without reading them again. + pub fn with_initial_segments(mut self, initial: HashMap) -> Self { + self.initial = Arc::new(initial); + self + } +} + +/// The default [`IoService`], held once per Vortex session and shared by every scan in it. +/// +/// Clones share their sources. +#[derive(Clone, Default)] +pub struct IoScheduler { + inner: Arc, +} + +#[derive(Default)] +struct Sources { + live: Mutex>>, + next: AtomicU32, +} + +impl IoScheduler { + /// Registers a source whose segments are `locations`, retaining up to `retained_bytes` of + /// its recently read segments. The source stays registered while the returned handle lives. + /// + /// A placed reader whose earlier registration with this scheduler still lives gets that + /// registration back, with the budget it was registered with. + pub fn register( + &self, + locations: Arc<[SegmentLocation]>, + reader: SegmentReader, + retained_bytes: u64, + ) -> VortexResult> { + let placed = match reader { + SegmentReader::Placed(placed) => placed, + SegmentReader::Opaque(segments) => { + let segments = Arc::new(SharedSegmentSource::new(segments)); + return self.insert(locations, segments, None, retained_bytes); + } + }; + let mut registration = placed.registration.lock(); + if let Some(source) = registration + .upgrade() + .filter(|source| source.is_registered_with(self)) + { + return Ok(source); + } + let driver = FileSegmentSource::open( + Arc::clone(&locations), + Arc::clone(&placed.read), + placed.handle.clone(), + placed.metrics.clone(), + ); + let segments = Arc::new(InitialSegments { + initial: Arc::clone(&placed.initial), + inner: SharedSegmentSource::new(driver), + }); + let source = self.insert( + locations, + segments, + Some(Arc::clone(&placed.read)), + retained_bytes, + )?; + *registration = Arc::downgrade(&source); + Ok(source) + } + + fn insert( + &self, + locations: Arc<[SegmentLocation]>, + segments: Arc, + read: Option>, + retained_bytes: u64, + ) -> VortexResult> { + let id = self + .inner + .next + .try_update(Ordering::Relaxed, Ordering::Relaxed, |id| id.checked_add(1)) + .map(SourceId) + .map_err(|_| vortex_err!("IoScheduler ran out of source ids"))?; + let segments = Arc::new(RetainingSegmentSource { + inner: segments, + retained: Arc::new(RetainedSegments::new(retained_bytes)), + }); + let source = Arc::new(RegisteredSource { + id, + scheduler: Arc::downgrade(&self.inner), + locations, + segments, + read, + }); + self.inner.live.lock().insert(id, Arc::downgrade(&source)); + Ok(source) + } + + fn source(&self, id: SourceId) -> VortexResult> { + self.inner + .live + .lock() + .get(&id) + .and_then(Weak::upgrade) + .ok_or_else(|| vortex_err!("{id:?} is not registered")) + } +} + +impl IoService for IoScheduler { + fn session(&self) -> Arc { + Arc::new(SchedulerSession::new(self.clone())) + } +} + +/// A source registered with an [`IoScheduler`], unregistered when the last handle drops. +pub struct RegisteredSource { + id: SourceId, + scheduler: Weak, + locations: Arc<[SegmentLocation]>, + segments: Arc, + /// The object a placed source reads, which also answers its size. + read: Option>, +} + +impl RegisteredSource { + /// The id requests name the source by. + pub fn id(&self) -> SourceId { + self.id + } + + /// Whether the source is registered with `scheduler`, rather than with another one. + pub fn is_registered_with(&self, scheduler: &IoScheduler) -> bool { + ptr::eq(self.scheduler.as_ptr(), Arc::as_ptr(&scheduler.inner)) + } + + fn alignment(&self, segment: SegmentId) -> VortexResult { + self.locations + .get(*segment as usize) + .map(|location| location.alignment) + .ok_or_else(|| vortex_err!("{segment} of {:?} has no known location", self.id)) + } + + fn size(&self) -> BoxFuture<'static, VortexResult> { + match &self.read { + Some(read) => read.size(), + None => future::ready(Err(vortex_err!( + "{:?} has no size: it reads segments itself", + self.id + ))) + .boxed(), + } + } +} + +impl Drop for RegisteredSource { + fn drop(&mut self) { + if let Some(scheduler) = self.scheduler.upgrade() { + scheduler.live.lock().remove(&self.id); + } + } +} + +/// Serves the segments a placed source's opener already read before asking its driver. +struct InitialSegments { + initial: Arc>, + inner: S, +} + +impl SegmentSource for InitialSegments { + fn request(&self, id: SegmentId) -> SegmentFuture { + match self.initial.get(&id) { + Some(buffer) => future::ready(Ok(BufferHandle::new_host(buffer.clone()))).boxed(), + None => self.inner.request(id), + } + } +} + +/// The bytes `bytes` names of a segment, as one buffer at the segment's alignment. +fn select( + segment: BufferHandle, + bytes: &SegmentBytes, + alignment: Alignment, +) -> VortexResult { + let SegmentBytes::Ranges(ranges) = bytes else { + return Ok(segment); + }; + let len = segment.len() as u64; + let mut end = 0; + for range in ranges.iter() { + vortex_ensure!( + end <= range.start && range.start <= range.end && range.end <= len, + "{ranges:?} are not sorted, disjoint ranges of a {len}-byte segment" + ); + end = range.end; + } + if let [range] = ranges.as_ref() { + let range = usize::try_from(range.start)?..usize::try_from(range.end)?; + return segment.slice(range).ensure_aligned(alignment); + } + let host = segment.try_into_host_sync()?; + let total = ranges + .iter() + .map(|range| range.end - range.start) + .sum::(); + let mut packed = ByteBufferMut::with_capacity_aligned(usize::try_from(total)?, alignment); + for range in ranges.iter() { + packed.extend_from_slice(&host[usize::try_from(range.start)?..usize::try_from(range.end)?]); + } + Ok(BufferHandle::new_host(packed.freeze())) +} + +/// One registration scope's reads, served without blocking. +/// +/// [`submit`](IoSource::submit) starts each read at once, [`poll`](IoSource::poll) takes a +/// finished one if there is any, and the scope's future awaits the next with +/// [`poll_completion`](IoSource::poll_completion) when the driver has nothing else to run. +/// [`wait`](IoSource::wait) is never called. +/// +/// An announcement requests the segment and holds the request, never polled, until a prefetch or +/// fetch consumes it, so a placed source's driver can fold it into a nearby read. +struct SchedulerSession { + scheduler: IoScheduler, + reads: Mutex>>, + ready: Mutex>, + /// Every read the session has started, by segment, shared by later fetches of the segment + /// until the session is cleared. + prefetched: Mutex>, + /// Announced segments, requested and never polled. + announced: Mutex>>, + /// The sources the session's requests named, resolved once each. + sources: Mutex>>, +} + +/// A read started ahead of the fetch that needs it. +type Prefetched = Shared>>>; + +impl SchedulerSession { + fn new(scheduler: IoScheduler) -> Self { + Self { + scheduler, + reads: Mutex::new(FuturesUnordered::new()), + ready: Mutex::default(), + prefetched: Mutex::default(), + announced: Mutex::default(), + sources: Mutex::default(), + } + } + + /// The segment's read: an announced one if there is one, else a new one. + fn read( + &self, + source: &RegisteredSource, + segment: SegmentId, + ) -> Shared>>> { + self.announced + .lock() + .get_mut(&(source.id, segment)) + .and_then(VecDeque::pop_front) + .unwrap_or_else(|| source.segments.request(segment)) + .map_err(Arc::new) + .boxed() + .shared() + } +} + +impl IoSource for SchedulerSession { + fn submit(&self, owner: IoOwnerId, batch: IoBatch) -> VortexResult<()> { + let reads = self.reads.lock(); + let mut ready = self.ready.lock(); + let mut prefetched = self.prefetched.lock(); + let mut sources = self.sources.lock(); + for request in batch { + let source = match sources.get(&request.source) { + Some(source) => Arc::clone(source), + None => { + let source = self.scheduler.source(request.source)?; + sources.insert(request.source, Arc::clone(&source)); + source + } + }; + let id = request.request; + let (segment, bytes) = match request.target { + IoTarget::Size => { + if request.intent == IoIntent::Fetch { + let size = source.size(); + reads.push( + async move { + Completion { + owner, + request: id, + result: size.await.map(IoResult::Size), + } + } + .boxed(), + ); + } + continue; + } + IoTarget::Segment { segment, bytes } => (segment, bytes), + }; + let key = (source.id, segment); + if request.intent == IoIntent::Announce { + self.announced + .lock() + .entry(key) + .or_default() + .push_back(source.segments.request(segment)); + continue; + } + if request.intent == IoIntent::Prefetch { + prefetched.entry(key).or_insert_with(|| { + let read = self.read(&source, segment); + // Polling registers the read as wanted, so the source starts it now. + drop( + read.clone() + .poll_unpin(&mut Context::from_waker(Waker::noop())), + ); + read + }); + continue; + } + // A segment stays with the session once read, so a later stage or morsel of the + // scope that reads it again shares the read instead of starting another once the + // first has completed. + let alignment = source.alignment(segment)?; + let source_id = source.id; + let mut bytes = prefetched + .entry(key) + .or_insert_with(|| self.read(&source, segment)) + .clone() + .map(move |result| { + result + .map_err(|err| { + vortex_err!("read of {segment} of {source_id:?} failed: {err}") + }) + .and_then(|buffer| select(buffer, &bytes, alignment)) + }) + .boxed(); + // In-memory and retained segments need no allocated asynchronous task. A pending + // read is polled again by FuturesUnordered before the driver can go to sleep. + if let Poll::Ready(result) = bytes.poll_unpin(&mut Context::from_waker(Waker::noop())) { + ready.push_back(Completion { + owner, + request: id, + result: result.map(IoResult::Bytes), + }); + continue; + } + reads.push( + async move { + Completion { + owner, + request: id, + result: bytes.await.map(IoResult::Bytes), + } + } + .boxed(), + ); + } + Ok(()) + } + + fn poll(&self) -> VortexResult> { + if let Some(completion) = self.ready.lock().pop_front() { + return Ok(Some(completion)); + } + // The scope's future polls again with its own waker before it waits, so a read that + // finishes after this check is not missed. + let mut cx = Context::from_waker(Waker::noop()); + match self.reads.lock().poll_next_unpin(&mut cx) { + Poll::Ready(completion) => Ok(completion), + Poll::Pending => Ok(None), + } + } + + fn poll_completion(&self, cx: &mut Context<'_>) -> Poll> { + if let Some(completion) = self.ready.lock().pop_front() { + return Poll::Ready(Ok(completion)); + } + match self.reads.lock().poll_next_unpin(cx) { + Poll::Ready(Some(completion)) => Poll::Ready(Ok(completion)), + Poll::Ready(None) => Poll::Ready(Err(vortex_err!( + "The scope's driver is waiting with no reads in flight" + ))), + Poll::Pending => Poll::Pending, + } + } + + fn wait(&self) -> VortexResult { + vortex_bail!("SchedulerSession is awaited through poll_completion, not waited on") + } + + fn release(&self, _owner: IoOwnerId) {} + + fn clear(&self) { + self.reads.lock().clear(); + self.ready.lock().clear(); + self.prefetched.lock().clear(); + self.announced.lock().clear(); + self.sources.lock().clear(); + } +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + use std::sync::atomic::AtomicUsize; + use std::sync::atomic::Ordering; + + use futures::FutureExt; + use futures::channel::oneshot; + use futures::future; + use parking_lot::Mutex; + use vortex_array::buffer::BufferHandle; + use vortex_buffer::Alignment; + use vortex_buffer::ByteBuffer; + use vortex_error::VortexResult; + use vortex_error::vortex_err; + + use super::IoScheduler; + use super::RegisteredSource; + use super::SegmentReader; + use crate::request::IoIntent; + use crate::request::IoOwnerId; + use crate::request::IoRequest; + use crate::request::IoRequestId; + use crate::request::IoResult; + use crate::request::IoService; + use crate::request::IoTarget; + use crate::request::SegmentBytes; + use crate::segments::SegmentFuture; + use crate::segments::SegmentId; + use crate::segments::SegmentLocation; + use crate::segments::SegmentSource; + + /// Registers `segments` as an opaque source of four-byte segments that retains nothing. + fn register( + scheduler: &IoScheduler, + segments: Arc, + count: u64, + ) -> VortexResult> { + let locations = (0..count) + .map(|segment| SegmentLocation { + offset: segment * 4, + length: 4, + alignment: Alignment::none(), + }) + .collect(); + scheduler.register(locations, SegmentReader::Opaque(segments), 0) + } + + /// Serves four bytes per segment and counts the reads it is asked for. + #[derive(Default)] + struct CountingSegments(AtomicUsize); + + impl SegmentSource for CountingSegments { + fn request(&self, id: SegmentId) -> SegmentFuture { + self.0.fetch_add(1, Ordering::Relaxed); + let bytes = ByteBuffer::from(vec![u8::try_from(*id).unwrap_or(u8::MAX); 4]); + future::ready(Ok(BufferHandle::new_host(bytes))).boxed() + } + } + + fn request(source: &RegisteredSource, intent: IoIntent, id: u32) -> IoRequest { + IoRequest { + intent, + request: IoRequestId(id), + source: source.id(), + target: IoTarget::segment(SegmentId::from(0)), + } + } + + struct MixedSegments(Mutex>>); + + impl SegmentSource for MixedSegments { + fn request(&self, id: SegmentId) -> SegmentFuture { + if *id == 0 { + return future::ready(Ok(BufferHandle::new_host(ByteBuffer::from(vec![0; 4])))) + .boxed(); + } + let receiver = self.0.lock().take().expect("one pending read"); + async move { + receiver + .await + .map(BufferHandle::new_host) + .map_err(|err| vortex_err!("{err}")) + } + .boxed() + } + } + + #[tokio::test] + async fn pending_read_wakes_after_an_immediate_completion() -> VortexResult<()> { + let (sender, receiver) = oneshot::channel(); + let scheduler = IoScheduler::default(); + let source = register( + &scheduler, + Arc::new(MixedSegments(Mutex::new(Some(receiver)))), + 2, + )?; + let io = scheduler.session(); + let mut pending = request(&source, IoIntent::Fetch, 1); + pending.target = IoTarget::segment(SegmentId::from(1)); + io.submit( + IoOwnerId(0), + vec![pending, request(&source, IoIntent::Fetch, 0)], + )?; + let immediate = io.poll()?.expect("the in-memory read is already ready"); + assert_eq!(immediate.request, IoRequestId(0)); + assert!(immediate.result.is_ok()); + assert!(io.poll()?.is_none()); + + let delivery = tokio::spawn(async move { + tokio::task::yield_now().await; + sender + .send(ByteBuffer::from(vec![1; 4])) + .expect("read is live"); + }); + let completed = std::future::poll_fn(|cx| io.poll_completion(cx)).await?; + assert_eq!(completed.request, IoRequestId(1)); + assert!(completed.result.is_ok()); + delivery.await.expect("delivery task succeeds"); + assert!(io.poll()?.is_none()); + Ok(()) + } + + /// A fetch of a prefetched segment waits on the prefetch's read rather than reading again, + /// only the fetch is delivered, and a later fetch of the segment shares the same read. + #[tokio::test] + async fn fetch_reuses_a_prefetched_read() -> VortexResult<()> { + let segments = Arc::new(CountingSegments::default()); + let scheduler = IoScheduler::default(); + let source = register(&scheduler, Arc::clone(&segments) as _, 1)?; + let io = scheduler.session(); + + io.submit(IoOwnerId(0), vec![request(&source, IoIntent::Prefetch, 0)])?; + assert_eq!(segments.0.load(Ordering::Relaxed), 1); + io.submit(IoOwnerId(0), vec![request(&source, IoIntent::Fetch, 1)])?; + assert_eq!(segments.0.load(Ordering::Relaxed), 1); + + let completion = std::future::poll_fn(|cx| io.poll_completion(cx)).await?; + assert_eq!(completion.request, IoRequestId(1)); + assert!(completion.result.is_ok()); + assert!(io.poll()?.is_none()); + + io.submit(IoOwnerId(0), vec![request(&source, IoIntent::Fetch, 2)])?; + let completion = std::future::poll_fn(|cx| io.poll_completion(cx)).await?; + assert_eq!(completion.request, IoRequestId(2)); + assert!(completion.result.is_ok()); + assert_eq!(segments.0.load(Ordering::Relaxed), 1); + + io.clear(); + io.submit(IoOwnerId(0), vec![request(&source, IoIntent::Fetch, 3)])?; + assert!( + std::future::poll_fn(|cx| io.poll_completion(cx)) + .await? + .result + .is_ok() + ); + assert_eq!(segments.0.load(Ordering::Relaxed), 2); + Ok(()) + } + + #[tokio::test] + async fn announcements_keep_independent_consumers() -> VortexResult<()> { + let segments = Arc::new(CountingSegments::default()); + let scheduler = IoScheduler::default(); + let source = register(&scheduler, Arc::clone(&segments) as _, 1)?; + let io = scheduler.session(); + io.submit( + IoOwnerId(0), + vec![ + request(&source, IoIntent::Announce, 0), + request(&source, IoIntent::Announce, 1), + ], + )?; + // The second announcement shares the first's read, which the source keeps in flight. + assert_eq!(segments.0.load(Ordering::Relaxed), 1); + for id in 2..5 { + io.submit(IoOwnerId(0), vec![request(&source, IoIntent::Fetch, id)])?; + assert!( + std::future::poll_fn(|cx| io.poll_completion(cx)) + .await? + .result + .is_ok() + ); + // The first fetch takes one announcement and the session keeps its read, so the + // later fetches share it and the other announcement is never consumed. + assert_eq!(segments.0.load(Ordering::Relaxed), 1); + } + Ok(()) + } + + /// Ranges of a segment arrive as one buffer, concatenated in order. + #[tokio::test] + async fn ranges_arrive_packed() -> VortexResult<()> { + struct Counting16; + impl SegmentSource for Counting16 { + fn request(&self, _id: SegmentId) -> SegmentFuture { + let bytes = ByteBuffer::from((0..16).collect::>()); + future::ready(Ok(BufferHandle::new_host(bytes))).boxed() + } + } + let scheduler = IoScheduler::default(); + let source = register(&scheduler, Arc::new(Counting16), 1)?; + let io = scheduler.session(); + let mut packed = request(&source, IoIntent::Fetch, 0); + packed.target = IoTarget::Segment { + segment: SegmentId::from(0), + bytes: SegmentBytes::Ranges(Arc::from([2..4, 8..11])), + }; + let mut unsorted = request(&source, IoIntent::Fetch, 1); + unsorted.target = IoTarget::Segment { + segment: SegmentId::from(0), + bytes: SegmentBytes::Ranges(Arc::from([8..11, 2..4])), + }; + io.submit(IoOwnerId(0), vec![packed, unsorted])?; + let Some(Ok(IoResult::Bytes(bytes))) = io.poll()?.map(|done| done.result) else { + panic!("the packed ranges are ready"); + }; + assert_eq!(bytes.try_into_host_sync()?.as_slice(), &[2, 3, 8, 9, 10]); + assert!( + io.poll()? + .expect("the unsorted ranges are ready") + .result + .is_err() + ); + Ok(()) + } + + /// A dropped source leaves the scheduler, and a request for it fails. + #[test] + fn dropped_sources_unregister() -> VortexResult<()> { + let scheduler = IoScheduler::default(); + let source = register(&scheduler, Arc::new(CountingSegments::default()), 1)?; + let id = source.id(); + assert!(source.is_registered_with(&scheduler)); + assert!(!source.is_registered_with(&IoScheduler::default())); + drop(source); + assert!(scheduler.source(id).is_err()); + Ok(()) + } +} diff --git a/vortex-io/src/request/source.rs b/vortex-io/src/request/source.rs deleted file mode 100644 index cda9e2ebed3..00000000000 --- a/vortex-io/src/request/source.rs +++ /dev/null @@ -1,108 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// SPDX-FileCopyrightText: Copyright the Vortex contributors - -//! A blocking byte source for exercising the protocol with real footer reads. - -use std::collections::VecDeque; -use std::sync::Arc; -use std::task::Context; -use std::task::Poll; - -use parking_lot::Mutex; -use vortex_error::VortexResult; -use vortex_error::vortex_bail; -use vortex_error::vortex_err; - -use super::Completion; -use super::IoBatch; -use super::IoIntent; -use super::IoOwnerId; -use super::IoRequest; -use super::IoResult; -use super::IoSource; -use super::IoTarget; -use crate::VortexReadAt; -use crate::runtime::BlockingRuntime; - -/// A simple source that registers batches and performs one fetch per `wait()`. -/// Optional hints are declined. Shared reads, prefetching, and priority scheduling -/// belong to a later IO service implementation. -pub struct ReadAtIoSource { - read: Arc, - runtime: Arc, - queued: Mutex>, -} - -impl ReadAtIoSource { - /// Creates a source that drives its reads on `runtime`. - pub fn new(read: Arc, runtime: Arc) -> Self { - Self { - read, - runtime, - queued: Mutex::default(), - } - } -} - -impl IoSource for ReadAtIoSource { - fn submit(&self, work: IoOwnerId, batch: IoBatch) -> VortexResult<()> { - for request in &batch { - if let IoTarget::Range { offset, len, .. } = &request.target - && offset.checked_add(*len as u64).is_none() - { - vortex_bail!("ReadAtIoSource: range overflow for {:?}", request.request); - } - } - self.queued.lock().extend( - batch - .into_iter() - .filter(|request| request.intent == IoIntent::Fetch) - .map(|request| (work, request)), - ); - Ok(()) - } - - fn poll(&self) -> VortexResult> { - Ok(None) - } - - /// Performs the next queued read on the polling thread: this source has no background IO. - fn poll_completion(&self, _cx: &mut Context<'_>) -> Poll> { - Poll::Ready(self.wait()) - } - - fn wait(&self) -> VortexResult { - let (work, request) = self - .queued - .lock() - .pop_front() - .ok_or_else(|| vortex_err!("ReadAtIoSource: wait with nothing outstanding"))?; - let result = match request.target { - IoTarget::Size => self.runtime.block_on(self.read.size()).map(IoResult::Size), - IoTarget::Range { - offset, - len, - alignment, - } => self - .runtime - .block_on(self.read.read_at(offset, len, alignment)) - .map(IoResult::Bytes), - }; - Ok(Completion { - owner: work, - request: request.request, - result, - }) - } - - fn release(&self, work: IoOwnerId) { - self.queued.lock().retain(|(owner, _)| *owner != work); - } - - fn clear(&self) { - self.queued.lock().clear(); - } -} - -#[cfg(test)] -mod tests; diff --git a/vortex-io/src/request/source/tests.rs b/vortex-io/src/request/source/tests.rs deleted file mode 100644 index fd6bcfd12a9..00000000000 --- a/vortex-io/src/request/source/tests.rs +++ /dev/null @@ -1,155 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// SPDX-FileCopyrightText: Copyright the Vortex contributors - -use std::sync::LazyLock; - -use futures::future::BoxFuture; -use rstest::rstest; -use vortex_array::buffer::BufferHandle; -use vortex_buffer::Alignment; -use vortex_buffer::ByteBuffer; -use vortex_buffer::buffer; - -use super::*; -use crate::request::IoRequestId; -use crate::runtime::current::CurrentThreadRuntime; - -fn request(intent: IoIntent) -> IoRequest { - IoRequest { - intent, - request: IoRequestId(0), - target: IoTarget::range(0, 4), - } -} - -#[rstest] -#[case(IoIntent::Announce)] -#[case(IoIntent::Prefetch)] -fn optional_hints_can_be_declined(#[case] intent: IoIntent) -> VortexResult<()> { - let source = ReadAtIoSource::new(Arc::new(PanickingReadAt), Arc::new(RUNTIME.clone())); - source.submit(IoOwnerId(1), vec![request(intent)])?; - assert!(source.poll()?.is_none()); - assert!(source.queued.lock().is_empty()); - Ok(()) -} - -#[test] -fn registration_does_not_read_and_delivery_keeps_its_identity() -> VortexResult<()> { - let read = Arc::new(RecordingReadAt::new(buffer![7u8; 4].into_byte_buffer())); - let source = ReadAtIoSource::new(Arc::clone(&read) as _, Arc::new(RUNTIME.clone())); - source.submit(IoOwnerId(3), vec![request(IoIntent::Fetch)])?; - assert!(read.reads().is_empty()); - let completion = source.wait()?; - assert_eq!(completion.owner, IoOwnerId(3)); - assert_eq!(completion.request, IoRequestId(0)); - assert!(matches!(completion.result?, IoResult::Bytes(bytes) if bytes.len() == 4)); - assert_eq!(read.reads(), vec![(0, 4)]); - assert!(source.queued.lock().is_empty()); - Ok(()) -} - -#[test] -fn retirement_and_run_cleanup_cancel_queued_reads() -> VortexResult<()> { - let source = ReadAtIoSource::new(Arc::new(PanickingReadAt), Arc::new(RUNTIME.clone())); - source.submit(IoOwnerId(1), vec![request(IoIntent::Fetch)])?; - source.submit(IoOwnerId(2), vec![request(IoIntent::Fetch)])?; - source.release(IoOwnerId(1)); - assert_eq!(source.queued.lock().len(), 1); - assert_eq!(source.queued.lock()[0].0, IoOwnerId(2)); - source.clear(); - assert!(source.queued.lock().is_empty()); - Ok(()) -} - -#[test] -fn a_range_is_read_at_its_alignment() -> VortexResult<()> { - let read = Arc::new(RecordingReadAt::new(buffer![7u8; 16].into_byte_buffer())); - let source = ReadAtIoSource::new(Arc::clone(&read) as _, Arc::new(RUNTIME.clone())); - let alignment = Alignment::new(8); - source.submit( - IoOwnerId(0), - vec![IoRequest { - intent: IoIntent::Fetch, - request: IoRequestId(0), - target: IoTarget::Range { - offset: 3, - len: 8, - alignment, - }, - }], - )?; - let IoResult::Bytes(bytes) = source.wait()?.result? else { - vortex_bail!("expected bytes"); - }; - assert!(bytes.try_into_host_sync()?.is_aligned(alignment)); - assert_eq!(read.alignments(), vec![alignment]); - Ok(()) -} - -static RUNTIME: LazyLock = LazyLock::new(CurrentThreadRuntime::new); - -struct PanickingReadAt; - -impl VortexReadAt for PanickingReadAt { - fn concurrency(&self) -> usize { - 1 - } - - fn size(&self) -> BoxFuture<'static, VortexResult> { - panic!("unexpected size request") - } - - fn read_at( - &self, - _offset: u64, - _len: usize, - _alignment: Alignment, - ) -> BoxFuture<'static, VortexResult> { - panic!("unexpected read") - } -} - -struct RecordingReadAt { - buffer: ByteBuffer, - reads: Mutex>, - alignments: Mutex>, -} - -impl RecordingReadAt { - fn new(buffer: ByteBuffer) -> Self { - Self { - buffer, - reads: Mutex::default(), - alignments: Mutex::default(), - } - } - - fn reads(&self) -> Vec<(u64, usize)> { - self.reads.lock().clone() - } - - fn alignments(&self) -> Vec { - self.alignments.lock().clone() - } -} - -impl VortexReadAt for RecordingReadAt { - fn concurrency(&self) -> usize { - 1 - } - - fn size(&self) -> BoxFuture<'static, VortexResult> { - self.buffer.size() - } - - fn read_at( - &self, - offset: u64, - len: usize, - alignment: Alignment, - ) -> BoxFuture<'static, VortexResult> { - self.reads.lock().push((offset, len)); - self.alignments.lock().push(alignment); - self.buffer.read_at(offset, len, alignment) - } -} diff --git a/vortex-io/src/request/tests.rs b/vortex-io/src/request/tests.rs index f3e1218e79f..657b6a834b1 100644 --- a/vortex-io/src/request/tests.rs +++ b/vortex-io/src/request/tests.rs @@ -5,11 +5,15 @@ use vortex_utils::aliases::hash_map::HashMap; use super::*; +fn segment(id: u32) -> IoTarget { + IoTarget::segment(SegmentId::from(id)) +} + #[test] fn request_id_is_a_map_key() { let mut pending: HashMap = HashMap::default(); pending.insert(IoRequestId(0), IoTarget::Size); - pending.insert(IoRequestId(1), IoTarget::range(8, 16)); + pending.insert(IoRequestId(1), segment(1)); assert_eq!(pending.remove(&IoRequestId(0)), Some(IoTarget::Size)); assert!(pending.contains_key(&IoRequestId(1))); assert!(!pending.contains_key(&IoRequestId(0))); @@ -20,28 +24,34 @@ fn batches_compare_structurally() { let batch: IoBatch = vec![IoRequest { intent: IoIntent::Fetch, request: IoRequestId(3), - target: IoTarget::range(0, 4), + source: SourceId(0), + target: segment(0), }]; assert_eq!( batch, vec![IoRequest { intent: IoIntent::Fetch, request: IoRequestId(3), - target: IoTarget::range(0, 4), + source: SourceId(0), + target: segment(0), }] ); for request in [ IoRequest { intent: IoIntent::Prefetch, - ..batch[0] + ..batch[0].clone() }, IoRequest { request: IoRequestId(4), - ..batch[0] + ..batch[0].clone() + }, + IoRequest { + source: SourceId(1), + ..batch[0].clone() }, IoRequest { - target: IoTarget::range(0, 5), - ..batch[0] + target: segment(1), + ..batch[0].clone() }, ] { assert_ne!(batch, vec![request]); @@ -53,36 +63,36 @@ fn batches_compare_structurally() { fn slot_allocates_fresh_ids_and_hands_back_one_result() { let mut slot = IoSlot::default(); assert!(!slot.is_waiting()); - let batch = slot.issue(IoTarget::Size); + let batch = slot.issue(SourceId(0), IoTarget::Size); assert_eq!(batch[0].request, IoRequestId(0)); assert!(slot.is_waiting()); slot.deliver(IoRequestId(0), IoResult::Size(9)); assert!(!slot.is_waiting()); assert!(matches!(slot.take(), Some(IoResult::Size(9)))); assert!(slot.take().is_none()); - let batch = slot.issue(IoTarget::range(0, 1)); + let batch = slot.issue(SourceId(0), segment(0)); assert_eq!(batch[0].request, IoRequestId(1)); } #[test] -fn ranges_carry_their_alignment() { - let aligned = IoTarget::Range { - offset: 0, - len: 4, - alignment: Alignment::new(8), +fn segment_targets_name_their_bytes() { + let ranges = IoTarget::Segment { + segment: SegmentId::from(0), + bytes: SegmentBytes::Ranges(Arc::from([0..4, 8..12])), }; - assert_ne!(aligned, IoTarget::range(0, 4)); + assert_ne!(ranges, segment(0)); assert!( IoResult::Bytes(BufferHandle::new_host(vortex_buffer::ByteBuffer::empty())) - .matches(&aligned) + .matches(&ranges) ); + assert!(!IoResult::Size(0).matches(&ranges)); } #[test] #[should_panic(expected = "not outstanding")] fn slot_rejects_unknown_ids() { let mut slot = IoSlot::default(); - slot.issue(IoTarget::Size); + slot.issue(SourceId(0), IoTarget::Size); slot.deliver(IoRequestId(7), IoResult::Size(1)); } @@ -90,7 +100,7 @@ fn slot_rejects_unknown_ids() { #[should_panic(expected = "answered with bytes")] fn slot_rejects_mismatched_variants() { let mut slot = IoSlot::default(); - slot.issue(IoTarget::Size); + slot.issue(SourceId(0), IoTarget::Size); slot.deliver( IoRequestId(0), IoResult::Bytes(BufferHandle::new_host(vortex_buffer::ByteBuffer::empty())), diff --git a/vortex-io/src/session.rs b/vortex-io/src/session.rs index 68df61c77d0..3d229b5c65d 100644 --- a/vortex-io/src/session.rs +++ b/vortex-io/src/session.rs @@ -9,6 +9,7 @@ use vortex_session::SessionExt; use vortex_session::SessionVar; use vortex_session::VortexSession; +use crate::request::IoScheduler; use crate::runtime::Handle; /// Session state for Vortex async runtimes. @@ -68,3 +69,33 @@ pub trait RuntimeSessionExt: SessionExt { } } impl RuntimeSessionExt for S {} + +/// The session's I/O scheduler, shared by every scan that reads through the session. +#[derive(Clone, Default)] +pub struct IoSchedulerSession(IoScheduler); + +impl SessionVar for IoSchedulerSession { + fn as_any(&self) -> &dyn Any { + self + } + + fn as_any_mut(&mut self) -> &mut dyn Any { + self + } +} + +impl Debug for IoSchedulerSession { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("IoSchedulerSession").finish_non_exhaustive() + } +} + +/// Extension trait for the session's I/O scheduler. +pub trait IoSchedulerSessionExt: SessionExt { + /// The scheduler every scan of this session registers its sources with and reads through. + fn io_scheduler(&self) -> IoScheduler { + self.get::().0.clone() + } +} + +impl IoSchedulerSessionExt for S {} diff --git a/vortex-layout/src/scan/v2/mod.rs b/vortex-layout/src/scan/v2/mod.rs index a7e04c5bd3e..7719f2ab24b 100644 --- a/vortex-layout/src/scan/v2/mod.rs +++ b/vortex-layout/src/scan/v2/mod.rs @@ -10,6 +10,7 @@ use vortex_array::dtype::DType; use vortex_array::expr::BoundExpression; use vortex_error::VortexExpect; use vortex_error::VortexResult; +pub use vortex_io::request::SegmentReader; use vortex_scan::plan::LazyPlanRef; pub use vortex_scan::prepare::ChunkPlanner; pub use vortex_scan::prepare::FilterPlans; @@ -26,7 +27,6 @@ use vortex_scan::strict_sorted_buffer::StrictSortedBuffer; use vortex_session::VortexSession; use crate::LayoutRef; -use crate::segments::SegmentSource; // Match the scan executor's row grid so byte partitions and scan chunks stay aligned. const ROW_BLOCK_SIZE: usize = 8192; @@ -54,8 +54,8 @@ pub struct ScanFile { pub layout: LayoutRef, /// The location of every segment, indexed by segment id. pub locations: Arc<[SegmentLocation]>, - /// Fetches segment bytes by id. - pub segments: Arc, + /// How the session's I/O scheduler reads segments by id. + pub reader: SegmentReader, /// State shared by every scan of this file, or `None` to rebuild it for each scan. pub cache: Option, } @@ -66,7 +66,7 @@ impl From for ScanInput { dtype: file.layout.dtype().clone(), root: LazyPlanRef::lazy(move || file.layout.new_plan()), locations: file.locations, - segments: file.segments, + reader: file.reader, cache: file.cache, } } diff --git a/vortex-layout/src/scan/v2/tests.rs b/vortex-layout/src/scan/v2/tests.rs index 289bbbd56ab..0c774601d2b 100644 --- a/vortex-layout/src/scan/v2/tests.rs +++ b/vortex-layout/src/scan/v2/tests.rs @@ -40,6 +40,7 @@ use vortex_arrow::ArrowSessionExt; use vortex_buffer::Alignment; use vortex_buffer::Buffer; use vortex_error::VortexResult; +use vortex_error::vortex_bail; use vortex_io::session::RuntimeSessionExt; use vortex_mask::Mask; use vortex_scan::execution::SegmentLocation; @@ -57,6 +58,7 @@ use super::PrunePlanner; use super::ROW_BLOCK_SIZE; use super::ScanBuilder; use super::ScanFile; +use super::SegmentReader; use crate::LayoutRef; use crate::LayoutStrategy; use crate::layouts::chunked::writer::ChunkedLayoutStrategy; @@ -181,7 +183,7 @@ fn scan_file(segments: &Arc, layout: &LayoutRef) -> VortexRes Ok(ScanFile { layout: Arc::clone(layout), locations, - segments: Arc::clone(segments), + reader: SegmentReader::Opaque(Arc::clone(segments)), cache: None, }) } @@ -280,9 +282,12 @@ async fn assert_same_as_v1( ) -> VortexResult<()> { let builder = make()?; let dtype = builder.dtype().clone(); + let SegmentReader::Opaque(segments) = &builder.file.reader else { + vortex_bail!("test files read through an opaque source"); + }; let reader = builder.file.layout.new_reader( "".into(), - Arc::clone(&builder.file.segments), + Arc::clone(segments), session, &Default::default(), )?; diff --git a/vortex-scan/src/execution/adaptor.rs b/vortex-scan/src/execution/adaptor.rs index 9964baf4370..5cc079f7f26 100644 --- a/vortex-scan/src/execution/adaptor.rs +++ b/vortex-scan/src/execution/adaptor.rs @@ -17,12 +17,13 @@ use vortex_io::request; use vortex_io::request::IoBatch; use vortex_io::request::IoIntent; use vortex_io::request::IoResult; +use vortex_io::request::IoTarget; +use vortex_io::request::SourceId; use crate::execution::SegmentLocation; use crate::execution::pipeline::ReadId; use crate::execution::pipeline::Scan; use crate::execution::pipeline::Turn; -use crate::execution::segment_target; use crate::planning::planner::State; use crate::source::SegmentId; @@ -48,7 +49,7 @@ pub(super) enum AdaptorStep { /// Adapts a pipeline [`Scan`] to the planner I/O and compute protocol. /// /// The scan names segments by id; the protocol names byte ranges. Each scan read becomes a -/// `Fetch` of the segment's range at the segment's alignment, and each delivery is handed back to +/// `Fetch` of the whole segment from the scan's source, and each delivery is handed back to /// the scan under its own id. pub(super) struct ScanAdaptor { scan: Scan, @@ -58,6 +59,8 @@ pub(super) struct ScanAdaptor { /// Orders the pieces handed out. next_piece: u64, locations: Arc<[SegmentLocation]>, + /// The scheduler's id for the file the scan reads. + source: SourceId, /// Published and undelivered requests, with the scan read and segment each one answers. outstanding: FxHashMap, /// A delivery the scan could not take, reported by the next compute. @@ -68,13 +71,14 @@ pub(super) struct ScanAdaptor { impl ScanAdaptor { /// Wraps a scan, numbering requests uniquely within this adaptor's lifetime. - pub(super) fn new(scan: Scan, locations: Arc<[SegmentLocation]>) -> Self { + pub(super) fn new(scan: Scan, locations: Arc<[SegmentLocation]>, source: SourceId) -> Self { Self { scan, pending: None, done: false, next_piece: 0, locations, + source, outstanding: FxHashMap::default(), failed: None, next_id: 0, @@ -141,7 +145,7 @@ impl ScanAdaptor { } fn request(&mut self, read: ReadId, segment_id: SegmentId) -> VortexResult { - let location = self.location(segment_id)?; + self.location(segment_id)?; let id = self.next_id; self.next_id = self .next_id @@ -151,7 +155,8 @@ impl ScanAdaptor { Ok(request::IoRequest { intent: IoIntent::Fetch, request: request::IoRequestId(id), - target: segment_target(&location), + source: self.source, + target: IoTarget::segment(segment_id), }) } diff --git a/vortex-scan/src/execution/cache.rs b/vortex-scan/src/execution/cache.rs index 84e98d49804..3bd9c1e1db4 100644 --- a/vortex-scan/src/execution/cache.rs +++ b/vortex-scan/src/execution/cache.rs @@ -11,14 +11,16 @@ use std::sync::Weak; use parking_lot::Mutex; use rustc_hash::FxHashMap; use vortex_array::expr::BoundExpression; +use vortex_error::VortexResult; +use vortex_io::request::DEFAULT_RETAINED_BYTES; +use vortex_io::request::IoScheduler; +use vortex_io::request::RegisteredSource; +use vortex_io::request::SegmentReader; +use vortex_io::segments::SegmentLocation; -use super::io::SegmentRanges; -use super::retain::RetainedSegments; -use super::retain::RetainingSegmentSource; use crate::execution::FilterPlans; use crate::execution::pipeline::ValueCache; use crate::plan::PlanRef; -use crate::source::SegmentSource; /// Reusable state for repeated scans of one source. /// @@ -28,8 +30,9 @@ use crate::source::SegmentSource; /// scans. The lowered plan keeps the children it has initialized, each distinct projection keeps /// its optimized plan, each distinct filter keeps its conjunct and pruning plans along with the /// zones those plans have already excluded, and dictionary values stay keyed by the cached plan -/// that produced them. Recently read segments are retained up to a byte budget, so the chunks of -/// the file's scans that share a stored segment read it once. +/// that produced them. The source stays registered with the session's I/O scheduler, which +/// retains its recently read segments up to a byte budget, so the chunks of the file's scans that +/// share a stored segment read it once. /// /// A cache describes one root plan, segment locations, and segment source. Use a new cache /// when any of them changes. Cached plans and values live as long as the cache, one set per @@ -43,13 +46,14 @@ struct Inner { /// Optimized plans of non-identity projections. Values are cached by the plan that produced /// them, so a projection must reuse its plan for its values to be found again. projections: Mutex>, - ranges: Mutex>, /// Plans of filters, keyed by the filter expression. A pruning plan remembers the zones it /// excluded, so sharing the plans prunes a file's zones once for every scan of that filter. filters: Mutex>>, values: ValueCache, - /// Recently read segments, shared by the chunks of every scan of the file. - retained: Arc, + /// The scheduler's budget for the source's recently read segments, or `None` for the default. + retained_bytes: Option, + /// The source's registration, shared by every scan of the file. + source: Mutex>>, } impl ScanCache { @@ -57,7 +61,7 @@ impl ScanCache { /// a stored segment read it once. The default retains 64 MiB; zero retains nothing. pub fn with_retained_bytes(bytes: u64) -> Self { Self(Arc::new(Inner { - retained: Arc::new(RetainedSegments::new(bytes)), + retained_bytes: Some(bytes), ..Inner::default() })) } @@ -92,16 +96,6 @@ impl ScanCache { .clone() } - /// The segment byte-range index an earlier scan kept. - pub(crate) fn ranges(&self) -> Option { - self.0.ranges.lock().clone() - } - - /// Keeps `ranges`, returning the index already kept if another scan got there first. - pub(crate) fn insert_ranges(&self, ranges: SegmentRanges) -> SegmentRanges { - Arc::clone(self.0.ranges.lock().get_or_insert(ranges)) - } - /// The plans of `filter` an earlier scan kept. pub(crate) fn filter_plans(&self, filter: &BoundExpression) -> Option> { self.0.filters.lock().get(&ExprKey(filter.clone())).cloned() @@ -123,12 +117,21 @@ impl ScanCache { ) } - /// Serves `segments` through the segments the file's scans retain. - pub(crate) fn retaining(&self, segments: Arc) -> Arc { - Arc::new(RetainingSegmentSource { - inner: segments, - retained: Arc::clone(&self.0.retained), - }) + /// The source's registration with `scheduler`, registering it on the first scan. + pub(crate) fn register( + &self, + scheduler: &IoScheduler, + locations: Arc<[SegmentLocation]>, + reader: SegmentReader, + ) -> VortexResult> { + let mut source = self.0.source.lock(); + if let Some(source) = source.as_ref().filter(|s| s.is_registered_with(scheduler)) { + return Ok(Arc::clone(source)); + } + let retained_bytes = self.0.retained_bytes.unwrap_or(DEFAULT_RETAINED_BYTES); + let registered = scheduler.register(locations, reader, retained_bytes)?; + *source = Some(Arc::clone(®istered)); + Ok(registered) } pub(crate) fn values(&self) -> ValueCache { diff --git a/vortex-scan/src/execution/driver/tests.rs b/vortex-scan/src/execution/driver/tests.rs index a26ddf5c94c..8656482f724 100644 --- a/vortex-scan/src/execution/driver/tests.rs +++ b/vortex-scan/src/execution/driver/tests.rs @@ -19,6 +19,7 @@ use vortex_array::expr::root; use vortex_buffer::Buffer; use vortex_error::VortexResult; use vortex_error::vortex_bail; +use vortex_io::request::SegmentReader; use vortex_io::session::RuntimeSessionExt; use vortex_session::VortexSession; @@ -48,7 +49,7 @@ fn builder() -> ScanBuilder { dtype: plan.dtype().clone(), root: LazyPlanRef::ready(plan), locations: Arc::new([]), - segments: Arc::new(NoSegments), + reader: SegmentReader::Opaque(Arc::new(NoSegments)), cache: Some(ScanCache::default()), }, ) diff --git a/vortex-scan/src/execution/filter.rs b/vortex-scan/src/execution/filter.rs index 16cc3db2292..bf351614fc8 100644 --- a/vortex-scan/src/execution/filter.rs +++ b/vortex-scan/src/execution/filter.rs @@ -20,18 +20,18 @@ use vortex_io::request::IoIntent; use vortex_io::request::IoRequest; use vortex_io::request::IoRequestId; use vortex_io::request::IoResult; +use vortex_io::request::IoTarget; +use vortex_io::request::SourceId; use vortex_mask::Mask; use vortex_session::VortexSession; use super::FILTERED_ROWS_PER_CHUNK; use super::PreparedScan; -use super::SegmentLocation; use super::SelectedRows; use super::adaptor::AdaptorStep; use super::adaptor::Piece; use super::adaptor::ScanAdaptor; use super::projection::ProjectionPlanner; -use super::segment_target; use crate::execution::filter_expr::FilterExpr; use crate::execution::pipeline::Scan; use crate::execution::pipeline::Split; @@ -215,7 +215,7 @@ impl FilterPlanner { /// Publishes a hint for each of `segments` not in `seen`, and adds it there. pub(super) fn hint( - locations: &[SegmentLocation], + source: SourceId, next_hint: &mut u32, intent: IoIntent, segments: &[SegmentId], @@ -229,7 +229,8 @@ pub(super) fn hint( batch.push(IoRequest { intent, request: IoRequestId(*next_hint), - target: segment_target(&locations[*segment as usize]), + source, + target: IoTarget::segment(segment), }); *next_hint -= 1; } @@ -288,9 +289,9 @@ impl Planner for FilterPlanner { )?; let mut batch = Vec::new(); let mut seen = FxHashSet::default(); - let locations = &self.scan.locations; + let source = self.scan.source.id(); hint( - locations, + source, &mut self.next_hint, IoIntent::Prefetch, &predicates, @@ -298,7 +299,7 @@ impl Planner for FilterPlanner { &mut batch, ); hint( - locations, + source, &mut self.next_hint, IoIntent::Announce, &projection, @@ -379,7 +380,11 @@ impl Planner for FilterPlanner { self.active = Some(( index, version, - ScanAdaptor::new(scan, Arc::clone(&self.scan.locations)), + ScanAdaptor::new( + scan, + Arc::clone(&self.scan.locations), + self.scan.source.id(), + ), )); return Ok(PlannerOutput::Continue); } diff --git a/vortex-scan/src/execution/io.rs b/vortex-scan/src/execution/io.rs deleted file mode 100644 index 712e60df8ec..00000000000 --- a/vortex-scan/src/execution/io.rs +++ /dev/null @@ -1,404 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// SPDX-FileCopyrightText: Copyright the Vortex contributors - -use std::collections::VecDeque; -use std::sync::Arc; -use std::task::Context; -use std::task::Poll; -use std::task::Waker; - -use futures::FutureExt; -use futures::StreamExt; -use futures::TryFutureExt; -use futures::future::BoxFuture; -use futures::future::Shared; -use futures::stream::FuturesUnordered; -use parking_lot::Mutex; -use vortex_array::buffer::BufferHandle; -use vortex_error::VortexError; -use vortex_error::VortexResult; -use vortex_error::vortex_bail; -use vortex_error::vortex_err; -use vortex_io::request::Completion; -use vortex_io::request::IoBatch; -use vortex_io::request::IoIntent; -use vortex_io::request::IoOwnerId; -use vortex_io::request::IoResult; -use vortex_io::request::IoService; -use vortex_io::request::IoSource; -use vortex_io::request::IoTarget; -use vortex_utils::aliases::hash_map::HashMap; - -use crate::execution::SegmentLocation; -use crate::source::SegmentFuture; -use crate::source::SegmentId; -use crate::source::SegmentSource; - -/// Byte ranges of a file's segments, keyed by `(offset, length)`, back to their segment ids. -pub(crate) type SegmentRanges = Arc>; - -pub(crate) fn segment_ranges(locations: &[SegmentLocation]) -> SegmentRanges { - let ranges = locations.iter().enumerate().map(|(id, location)| { - let id = SegmentId::from(u32::try_from(id).unwrap_or(u32::MAX)); - ((location.offset, location.length as usize), id) - }); - Arc::new(ranges.collect()) -} - -/// Serves splits from any [`SegmentSource`], by segment id. -pub(crate) struct SegmentScanIo { - segments: Arc, - ranges: SegmentRanges, -} - -impl SegmentScanIo { - pub(crate) fn new(segments: Arc, ranges: SegmentRanges) -> Self { - Self { segments, ranges } - } -} - -impl IoService for SegmentScanIo { - fn session(&self) -> Arc { - Arc::new(SegmentIoSource::new( - Arc::clone(&self.segments), - Arc::clone(&self.ranges), - )) - } -} - -/// Serves a split's range requests from a segment source, without blocking. -/// -/// Each requested range names one segment. [`submit`](IoSource::submit) starts its read at once, -/// [`poll`](IoSource::poll) takes a finished one if there is any, and the split's future awaits -/// the next with [`poll_completion`](IoSource::poll_completion) when the driver has nothing else -/// to run. [`wait`](IoSource::wait) is never called. -/// -/// An announcement requests the segment and holds the request, never polled, until a prefetch or -/// fetch consumes it, so a source that coalesces requests can fold it into a nearby read. -pub(super) struct SegmentIoSource { - segments: Arc, - ranges: SegmentRanges, - reads: Mutex>>, - ready: Mutex>, - /// Every read the session has started, by segment, shared by later fetches of the segment - /// until the session is cleared. - prefetched: Mutex>, - /// Announced segments, requested and never polled. - announced: Mutex>>, -} - -/// A read started ahead of the fetch that needs it. -type Prefetched = Shared>>>; - -impl SegmentIoSource { - pub(super) fn new(segments: Arc, ranges: SegmentRanges) -> Self { - Self { - segments, - ranges, - reads: Mutex::new(FuturesUnordered::new()), - ready: Mutex::default(), - prefetched: Mutex::default(), - announced: Mutex::default(), - } - } -} - -impl IoSource for SegmentIoSource { - fn submit(&self, owner: IoOwnerId, batch: IoBatch) -> VortexResult<()> { - let reads = self.reads.lock(); - let mut ready = self.ready.lock(); - let mut prefetched = self.prefetched.lock(); - for request in batch { - let IoTarget::Range { offset, len, .. } = request.target else { - vortex_bail!( - "SegmentIoSource only serves byte ranges, not {:?}", - request.target - ); - }; - let segment = *self - .ranges - .get(&(offset, len)) - .ok_or_else(|| vortex_err!("No segment at bytes {offset}+{len}"))?; - if request.intent == IoIntent::Announce { - self.announced - .lock() - .entry(segment) - .or_default() - .push_back(self.segments.request(segment)); - continue; - } - if request.intent == IoIntent::Prefetch { - prefetched.entry(segment).or_insert_with(|| { - let read = self - .announced - .lock() - .get_mut(&segment) - .and_then(VecDeque::pop_front) - .unwrap_or_else(|| self.segments.request(segment)) - .map_err(Arc::new) - .boxed() - .shared(); - // Polling registers the read as wanted, so the source starts it now. - drop( - read.clone() - .poll_unpin(&mut Context::from_waker(Waker::noop())), - ); - read - }); - continue; - } - // A segment stays with the session once read, so a later stage or morsel of the - // split that reads it again shares the read instead of starting another once the - // first has completed. - let mut bytes = prefetched - .entry(segment) - .or_insert_with(|| { - self.announced - .lock() - .get_mut(&segment) - .and_then(VecDeque::pop_front) - .unwrap_or_else(|| self.segments.request(segment)) - .map_err(Arc::new) - .boxed() - .shared() - }) - .clone() - .map_err(move |err| vortex_err!("read of segment {segment} failed: {err}")) - .boxed(); - let id = request.request; - // In-memory and cached segments need no allocated asynchronous task. A pending - // read is polled again by FuturesUnordered before the driver can go to sleep. - if let Poll::Ready(result) = bytes.poll_unpin(&mut Context::from_waker(Waker::noop())) { - ready.push_back(Completion { - owner, - request: id, - result: result.map(IoResult::Bytes), - }); - continue; - } - reads.push( - async move { - Completion { - owner, - request: id, - result: bytes.await.map(IoResult::Bytes), - } - } - .boxed(), - ); - } - Ok(()) - } - - fn poll(&self) -> VortexResult> { - if let Some(completion) = self.ready.lock().pop_front() { - return Ok(Some(completion)); - } - // The split's future polls again with its own waker before it waits, so a read that - // finishes after this check is not missed. - let mut cx = Context::from_waker(Waker::noop()); - match self.reads.lock().poll_next_unpin(&mut cx) { - Poll::Ready(completion) => Ok(completion), - Poll::Pending => Ok(None), - } - } - - fn poll_completion(&self, cx: &mut Context<'_>) -> Poll> { - if let Some(completion) = self.ready.lock().pop_front() { - return Poll::Ready(Ok(completion)); - } - match self.reads.lock().poll_next_unpin(cx) { - Poll::Ready(Some(completion)) => Poll::Ready(Ok(completion)), - Poll::Ready(None) => Poll::Ready(Err(vortex_err!( - "The split's driver is waiting with no reads in flight" - ))), - Poll::Pending => Poll::Pending, - } - } - - fn wait(&self) -> VortexResult { - vortex_bail!("SegmentIoSource is awaited through poll_completion, not waited on") - } - - fn release(&self, _owner: IoOwnerId) {} - - fn clear(&self) { - self.reads.lock().clear(); - self.ready.lock().clear(); - self.prefetched.lock().clear(); - self.announced.lock().clear(); - } -} - -#[cfg(test)] -mod tests { - use std::sync::Arc; - use std::sync::atomic::AtomicUsize; - use std::sync::atomic::Ordering; - - use futures::FutureExt; - use futures::channel::oneshot; - use futures::future; - use parking_lot::Mutex; - use vortex_array::buffer::BufferHandle; - use vortex_buffer::Alignment; - use vortex_buffer::ByteBuffer; - use vortex_error::VortexResult; - use vortex_error::vortex_err; - use vortex_io::request::IoIntent; - use vortex_io::request::IoOwnerId; - use vortex_io::request::IoRequest; - use vortex_io::request::IoRequestId; - use vortex_io::request::IoSource; - use vortex_io::request::IoTarget; - - use super::SegmentIoSource; - use super::segment_ranges; - use crate::execution::SegmentLocation; - use crate::source::SegmentFuture; - use crate::source::SegmentId; - use crate::source::SegmentSource; - - /// Serves four bytes per segment and counts the reads it is asked for. - #[derive(Default)] - struct CountingSegments(AtomicUsize); - - impl SegmentSource for CountingSegments { - fn request(&self, id: SegmentId) -> SegmentFuture { - self.0.fetch_add(1, Ordering::Relaxed); - let bytes = ByteBuffer::from(vec![u8::try_from(*id).unwrap_or(u8::MAX); 4]); - future::ready(Ok(BufferHandle::new_host(bytes))).boxed() - } - } - - fn request(intent: IoIntent, id: u32) -> IoRequest { - IoRequest { - intent, - request: IoRequestId(id), - target: IoTarget::range(0, 4), - } - } - - struct MixedSegments(Mutex>>); - - impl SegmentSource for MixedSegments { - fn request(&self, id: SegmentId) -> SegmentFuture { - if *id == 0 { - return future::ready(Ok(BufferHandle::new_host(ByteBuffer::from(vec![0; 4])))) - .boxed(); - } - let receiver = self.0.lock().take().expect("one pending read"); - async move { - receiver - .await - .map(BufferHandle::new_host) - .map_err(|err| vortex_err!("{err}")) - } - .boxed() - } - } - - #[tokio::test] - async fn pending_read_wakes_after_an_immediate_completion() -> VortexResult<()> { - let (sender, receiver) = oneshot::channel(); - let segments = Arc::new(MixedSegments(Mutex::new(Some(receiver)))); - let locations = [0, 4].map(|offset| SegmentLocation { - offset, - length: 4, - alignment: Alignment::none(), - }); - let io = SegmentIoSource::new(segments, segment_ranges(&locations)); - let mut pending = request(IoIntent::Fetch, 1); - pending.target = IoTarget::range(4, 4); - io.submit(IoOwnerId(0), vec![pending, request(IoIntent::Fetch, 0)])?; - let immediate = io.poll()?.expect("the in-memory read is already ready"); - assert_eq!(immediate.request, IoRequestId(0)); - assert!(immediate.result.is_ok()); - assert!(io.poll()?.is_none()); - - let delivery = tokio::spawn(async move { - tokio::task::yield_now().await; - sender - .send(ByteBuffer::from(vec![1; 4])) - .expect("read is live"); - }); - let completed = std::future::poll_fn(|cx| io.poll_completion(cx)).await?; - assert_eq!(completed.request, IoRequestId(1)); - assert!(completed.result.is_ok()); - delivery.await.expect("delivery task succeeds"); - assert!(io.poll()?.is_none()); - Ok(()) - } - - /// A fetch of a prefetched segment waits on the prefetch's read rather than reading again, - /// only the fetch is delivered, and a later fetch of the segment shares the same read. - #[tokio::test] - async fn fetch_reuses_a_prefetched_read() -> VortexResult<()> { - let segments = Arc::new(CountingSegments::default()); - let location = SegmentLocation { - offset: 0, - length: 4, - alignment: Alignment::none(), - }; - let io = SegmentIoSource::new(Arc::clone(&segments) as _, segment_ranges(&[location])); - - io.submit(IoOwnerId(0), vec![request(IoIntent::Prefetch, 0)])?; - assert_eq!(segments.0.load(Ordering::Relaxed), 1); - io.submit(IoOwnerId(0), vec![request(IoIntent::Fetch, 1)])?; - assert_eq!(segments.0.load(Ordering::Relaxed), 1); - - let completion = std::future::poll_fn(|cx| io.poll_completion(cx)).await?; - assert_eq!(completion.request, IoRequestId(1)); - assert!(completion.result.is_ok()); - assert!(io.poll()?.is_none()); - - io.submit(IoOwnerId(0), vec![request(IoIntent::Fetch, 2)])?; - let completion = std::future::poll_fn(|cx| io.poll_completion(cx)).await?; - assert_eq!(completion.request, IoRequestId(2)); - assert!(completion.result.is_ok()); - assert_eq!(segments.0.load(Ordering::Relaxed), 1); - - io.clear(); - io.submit(IoOwnerId(0), vec![request(IoIntent::Fetch, 3)])?; - assert!( - std::future::poll_fn(|cx| io.poll_completion(cx)) - .await? - .result - .is_ok() - ); - assert_eq!(segments.0.load(Ordering::Relaxed), 2); - Ok(()) - } - - #[tokio::test] - async fn announcements_keep_independent_consumers() -> VortexResult<()> { - let segments = Arc::new(CountingSegments::default()); - let location = SegmentLocation { - offset: 0, - length: 4, - alignment: Alignment::none(), - }; - let io = SegmentIoSource::new(Arc::clone(&segments) as _, segment_ranges(&[location])); - io.submit( - IoOwnerId(0), - vec![ - request(IoIntent::Announce, 0), - request(IoIntent::Announce, 1), - ], - )?; - assert_eq!(segments.0.load(Ordering::Relaxed), 2); - for id in 2..5 { - io.submit(IoOwnerId(0), vec![request(IoIntent::Fetch, id)])?; - assert!( - std::future::poll_fn(|cx| io.poll_completion(cx)) - .await? - .result - .is_ok() - ); - // The first fetch takes one announcement and the session keeps its read, so the - // later fetches share it and the other announcement is never consumed. - assert_eq!(segments.0.load(Ordering::Relaxed), 2); - } - Ok(()) - } -} diff --git a/vortex-scan/src/execution/mod.rs b/vortex-scan/src/execution/mod.rs index caa6a7ce099..34c2d07b381 100644 --- a/vortex-scan/src/execution/mod.rs +++ b/vortex-scan/src/execution/mod.rs @@ -14,12 +14,10 @@ pub mod cache; pub mod driver; pub mod filter_expr; -pub(crate) mod io; pub mod operator; pub(crate) mod operators; pub mod pipeline; pub mod planning; -mod retain; pub(crate) mod zone_map; mod adaptor; @@ -32,8 +30,9 @@ mod selection; use std::ops::Range; use std::sync::Arc; +use vortex_io::request::IoScheduler; use vortex_io::request::IoService; -use vortex_io::request::IoTarget; +use vortex_io::request::RegisteredSource; pub use vortex_io::segments::SegmentLocation; use vortex_mask::Mask; use vortex_session::VortexSession; @@ -53,23 +52,11 @@ use self::projection::ProjectionPlanner; pub use self::prune::PruneNext; pub use self::prune::PrunePlanner; use crate::execution::cache::ScanCache; -use crate::execution::io::SegmentRanges; -use crate::execution::io::SegmentScanIo; use crate::execution::pipeline::ValueCache; use crate::plan::PlanRef; use crate::planning::planner::Planner; use crate::planning::planner::WorkScope; use crate::selection::Selection; -use crate::source::SegmentSource; - -/// The byte range a read of the segment at `location` asks for. -fn segment_target(location: &SegmentLocation) -> IoTarget { - IoTarget::Range { - offset: location.offset, - len: location.length as usize, - alignment: location.alignment, - } -} /// A scan's plans over one file, built once from the file's footer and read by every planner of /// the scan. Nothing here touches a segment, and no planner plans again. @@ -80,10 +67,10 @@ pub struct PreparedScan { pub(crate) rows: Range, /// The rows of `rows` the scan selects. pub(crate) selection: Selection, - /// Fetches segment bytes by id. - pub(crate) segments: Arc, - /// The segments' byte ranges, back to their ids. - pub(crate) ranges: SegmentRanges, + /// The session's I/O scheduler, which serves every read of the scan. + pub(crate) scheduler: IoScheduler, + /// The file's registration with `scheduler`; reads name it by id. + pub(crate) source: Arc, /// Held for the scan's life, so scans of the file that start meanwhile share it. #[expect(dead_code, reason = "kept alive, never read")] pub(crate) cache: ScanCache, @@ -118,13 +105,10 @@ impl PreparedScan { self.filter.as_deref() } - /// The service a driver takes IO sessions from: every read a planner of the scan requests is - /// served from it by segment. + /// The service a driver takes IO sessions from: the session's I/O scheduler, which serves + /// every read a planner of the scan requests by source and segment. pub fn io(&self) -> Arc { - Arc::new(SegmentScanIo::new( - Arc::clone(&self.segments), - Arc::clone(&self.ranges), - )) + Arc::new(self.scheduler.clone()) } /// The planner of one chunk's selected rows: its conjuncts when the scan has a filter, else diff --git a/vortex-scan/src/execution/planning/driver/mod.rs b/vortex-scan/src/execution/planning/driver/mod.rs index e9cf27da3c2..b367825ca09 100644 --- a/vortex-scan/src/execution/planning/driver/mod.rs +++ b/vortex-scan/src/execution/planning/driver/mod.rs @@ -493,7 +493,7 @@ impl Run { if request.intent == IoIntent::Fetch && work .outstanding - .insert(request.request, request.target) + .insert(request.request, request.target.clone()) .is_some() { vortex_bail!( diff --git a/vortex-scan/src/execution/planning/driver/tests.rs b/vortex-scan/src/execution/planning/driver/tests.rs index 22263686b20..85a3a9f30d6 100644 --- a/vortex-scan/src/execution/planning/driver/tests.rs +++ b/vortex-scan/src/execution/planning/driver/tests.rs @@ -11,6 +11,8 @@ use vortex_array::assert_arrays_eq; use vortex_buffer::buffer; use vortex_error::VortexResult; use vortex_io::request::IoRequest; +use vortex_io::request::SourceId; +use vortex_io::segments::SegmentId; use super::*; use crate::execution::planning::tests::scripted::Log; @@ -22,14 +24,19 @@ use crate::execution::planning::tests::scripted::array_of; use crate::execution::planning::tests::scripted::ctx; use crate::execution::planning::tests::scripted::scope; -fn request(id: u32, offset: u64) -> IoRequest { +fn request(id: u32, segment: u32) -> IoRequest { IoRequest { intent: IoIntent::Fetch, request: IoRequestId(id), - target: IoTarget::range(offset, 4), + source: SourceId(0), + target: segment_target(segment), } } +fn segment_target(segment: u32) -> IoTarget { + IoTarget::segment(SegmentId::from(segment)) +} + fn driver(source: &Arc) -> Driver { Driver::new(Arc::clone(source) as Arc).with_step_limit(1_000) } @@ -157,7 +164,7 @@ fn needs_io_delivers_every_request_in_order() -> VortexResult<()> { assert!(batches.is_empty()); assert_eq!( source.performed(), - vec![IoTarget::range(4, 4), IoTarget::range(0, 4)] + vec![segment_target(4), segment_target(0)] ); assert_eq!( log.events(), @@ -188,7 +195,7 @@ fn fetch_published_ahead_is_delivered_when_awaited() -> VortexResult<()> { &log, ); driver(&source).run(root)?; - assert_eq!(source.performed(), vec![IoTarget::range(0, 4)]); + assert_eq!(source.performed(), vec![segment_target(0)]); assert_eq!( log.events(), vec![ @@ -228,7 +235,7 @@ fn continue_requeues() -> VortexResult<()> { fn io_failure_propagates_after_two_performs() -> VortexResult<()> { let log = Log::default(); let source = source(); - source.fail(IoTarget::range(4, 4), "disk on fire"); + source.fail(segment_target(4), "disk on fire"); let root = ScriptedPlanner::boxed( "root", vec![ @@ -261,7 +268,7 @@ fn completions_out_of_order_within_one_batch() -> VortexResult<()> { driver(&source).run(root)?; assert_eq!( source.performed(), - vec![IoTarget::range(0, 4), IoTarget::range(4, 4)], + vec![segment_target(0), segment_target(4)], "submitted in request order" ); assert_eq!( @@ -280,7 +287,7 @@ fn completions_out_of_order_within_one_batch() -> VortexResult<()> { fn completions_out_of_order_across_parked_items() -> VortexResult<()> { let log = Log::default(); let source = lifo_source(); - let child = |id: u32, offset: u64| { + let child = |id: u32, offset: u32| { PlannerStep::Planner( scope(0..1), vec![ @@ -312,7 +319,7 @@ fn completions_out_of_order_across_parked_items() -> VortexResult<()> { fn lying_source_fails_before_delivery() -> VortexResult<()> { let log = Log::default(); let source = source(); - source.answer_with_size(IoTarget::range(0, 4), 4); + source.answer_with_size(segment_target(0), 4); let root = ScriptedPlanner::boxed( "root", vec![PlannerStep::Io(vec![request(0, 0)]), PlannerStep::Done], @@ -641,8 +648,8 @@ fn a_waiting_item_is_not_revisited_per_delivery() -> VortexResult<()> { let io = RecordingIoSource::default(); let batch: Vec = (0..FETCHES) .map(|id| { - io.canned_bytes(u64::from(id) * 4, buffer![0u8; 4].into_byte_buffer()); - request(id, u64::from(id) * 4) + io.canned_bytes(id * 4, buffer![0u8; 4].into_byte_buffer()); + request(id, id * 4) }) .collect(); let io = Arc::new(io); diff --git a/vortex-scan/src/execution/planning/tests/scripted.rs b/vortex-scan/src/execution/planning/tests/scripted.rs index 5573dafa7df..a13a56b50e6 100644 --- a/vortex-scan/src/execution/planning/tests/scripted.rs +++ b/vortex-scan/src/execution/planning/tests/scripted.rs @@ -32,6 +32,7 @@ use vortex_io::request::IoRequestId; use vortex_io::request::IoResult; use vortex_io::request::IoSource; use vortex_io::request::IoTarget; +use vortex_io::segments::SegmentId; use vortex_session::VortexSession; use vortex_utils::aliases::hash_map::HashMap; @@ -316,11 +317,11 @@ impl RecordingIoSource { } } - /// Answers a range at `offset` with `bytes`. - pub fn canned_bytes(&self, offset: u64, bytes: ByteBuffer) { + /// Answers segment `id` with `bytes`. + pub fn canned_bytes(&self, id: u32, bytes: ByteBuffer) { self.canned .lock() - .insert(IoTarget::range(offset, bytes.len()), Canned::Bytes(bytes)); + .insert(IoTarget::segment(SegmentId::from(id)), Canned::Bytes(bytes)); } /// Answers `target` with a size regardless of what it asked for, to test the driver's check. @@ -351,11 +352,11 @@ impl RecordingIoSource { impl IoSource for RecordingIoSource { fn submit(&self, work: IoOwnerId, batch: Vec) -> VortexResult<()> { for request in batch { - self.submissions.lock().push((work, request)); + self.submissions.lock().push((work, request.clone())); if request.intent != IoIntent::Fetch { continue; } - self.performed.lock().push(request.target); + self.performed.lock().push(request.target.clone()); let result = match self.canned.lock().get(&request.target) { Some(Canned::Bytes(bytes)) => { Ok(IoResult::Bytes(BufferHandle::new_host(bytes.clone()))) diff --git a/vortex-scan/src/execution/projection.rs b/vortex-scan/src/execution/projection.rs index 29ffcbe50f6..6ab37d16646 100644 --- a/vortex-scan/src/execution/projection.rs +++ b/vortex-scan/src/execution/projection.rs @@ -177,7 +177,11 @@ impl Morsel for ProjectionMorsel { )? .with_row_offset(self.scan.row_offset) .with_value_cache(self.scan.values.clone()); - self.adaptor = Some(ScanAdaptor::new(scan, Arc::clone(&self.scan.locations))); + self.adaptor = Some(ScanAdaptor::new( + scan, + Arc::clone(&self.scan.locations), + self.scan.source.id(), + )); return Ok(MorselOutput::Continue); }; if adaptor.state() == State::Done { diff --git a/vortex-scan/src/execution/prune.rs b/vortex-scan/src/execution/prune.rs index 551fa6c2912..45573f44cca 100644 --- a/vortex-scan/src/execution/prune.rs +++ b/vortex-scan/src/execution/prune.rs @@ -118,7 +118,7 @@ impl Planner for PrunePlanner { let mut batch = Vec::new(); let mut seen = FxHashSet::default(); hint( - &self.scan.locations, + self.scan.source.id(), &mut self.next_hint, IoIntent::Prefetch, &segments, @@ -170,7 +170,11 @@ impl Planner for PrunePlanner { )? .with_row_offset(self.scan.row_offset) .with_value_cache(self.scan.values.clone()); - self.active = Some(ScanAdaptor::new(scan, Arc::clone(&self.scan.locations))); + self.active = Some(ScanAdaptor::new( + scan, + Arc::clone(&self.scan.locations), + self.scan.source.id(), + )); return Ok(PlannerOutput::Continue); } // Every pruning plan has run: the planner this one continues into gets the kept rows. diff --git a/vortex-scan/src/prepare.rs b/vortex-scan/src/prepare.rs index 62de742a81b..5a1f4e8af6e 100644 --- a/vortex-scan/src/prepare.rs +++ b/vortex-scan/src/prepare.rs @@ -10,6 +10,7 @@ use vortex_array::dtype::DType; use vortex_array::expr::BoundExpression; use vortex_error::VortexResult; use vortex_expr::analysis::referenced_field_paths; +use vortex_io::session::IoSchedulerSessionExt; use vortex_session::VortexSession; pub use crate::execution::ChunkPlanner; @@ -23,7 +24,6 @@ use crate::execution::ROW_BLOCK_SIZE; pub use crate::execution::SegmentLocation; pub use crate::execution::cache::ScanCache; pub use crate::execution::cache::WeakScanCache; -use crate::execution::io::segment_ranges; use crate::execution::rows_per_chunk; use crate::plan::optimize; use crate::plan::plan_row_idx_expression; @@ -180,17 +180,15 @@ impl ScanBuilder { } else { MAX_ROWS_PER_CHUNK }; - let ranges = match cache.ranges() { - Some(ranges) => ranges, - None => cache.insert_ranges(segment_ranges(&file.locations)), - }; + let scheduler = self.session.io_scheduler(); + let source = cache.register(&scheduler, Arc::clone(&file.locations), file.reader)?; let values = cache.values(); Ok(PreparedScan { session: self.session, rows: self.row_range.unwrap_or(0..row_count), selection: self.selection, - segments: cache.retaining(file.segments), - ranges, + scheduler, + source, cache, locations: file.locations, projection, diff --git a/vortex-scan/src/source.rs b/vortex-scan/src/source.rs index 08a3f38c296..a335e42d6d0 100644 --- a/vortex-scan/src/source.rs +++ b/vortex-scan/src/source.rs @@ -6,6 +6,7 @@ use std::sync::Arc; use vortex_array::dtype::DType; +use vortex_io::request::SegmentReader; pub use vortex_io::segments::SegmentFuture; pub use vortex_io::segments::SegmentId; pub use vortex_io::segments::SegmentSource; @@ -27,8 +28,8 @@ pub struct ScanInput { pub root: LazyPlanRef, /// Byte locations indexed by source-local segment identifiers. pub locations: Arc<[SegmentLocation]>, - /// Fetches bytes by source-local segment identifier. - pub segments: Arc, + /// How the session's I/O scheduler reads segments by source-local identifier. + pub reader: SegmentReader, /// State shared by repeated scans of this input. pub cache: Option, } diff --git a/vortex-scan/src/test.rs b/vortex-scan/src/test.rs index da8a6e9df82..1b13d4abe70 100644 --- a/vortex-scan/src/test.rs +++ b/vortex-scan/src/test.rs @@ -25,6 +25,7 @@ use vortex_buffer::Alignment; use vortex_buffer::ByteBufferMut; use vortex_error::VortexResult; use vortex_error::vortex_err; +use vortex_io::request::SegmentReader; use vortex_mask::Mask; use vortex_session::VortexSession; use vortex_session::registry::CachedId; @@ -265,7 +266,7 @@ impl Store { dtype: plan.dtype().clone(), root: LazyPlanRef::ready(plan), locations, - segments: Arc::clone(self) as Arc, + reader: SegmentReader::Opaque(Arc::clone(self) as Arc), cache: None, } } From 578ae107d5247228df2e9f858049c5fcbe2cb493 Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Wed, 18 Nov 2026 21:02:20 -0500 Subject: [PATCH 03/20] Let any data source hand engines a planner-driven scan A partition can now return its scan as a `PartitionPlan::Scan` builder from `Partition::plan`, so engines that drive the V2 executor themselves reach it through `DataSource` instead of a concrete `VortexFile`. `PlannedDataSource` is the standard implementation for any source that can name its segments, and `VortexFile::planned_data_source` exposes a file through it. The DataFusion opener and DuckDB's V2 scan now plan through the file's data source. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Nicholas Gates --- vortex-datafusion/src/persistent/opener.rs | 360 +++++++++++++-------- vortex-datafusion/src/persistent/source.rs | 13 +- vortex-duckdb/src/file_reader.rs | 55 ++-- vortex-duckdb/src/projection.rs | 7 +- vortex-duckdb/src/scan_v2.rs | 2 +- vortex-duckdb/src/table_function.rs | 11 + vortex-file/src/file.rs | 17 + vortex-file/src/source.rs | 12 +- vortex-file/src/v2/scan/tests.rs | 66 ++++ vortex-scan/src/execution/driver.rs | 13 + vortex-scan/src/lib.rs | 25 ++ vortex-scan/src/source.rs | 269 ++++++++++++++- vortex-scan/src/source/tests.rs | 147 +++++++++ 13 files changed, 825 insertions(+), 172 deletions(-) create mode 100644 vortex-scan/src/source/tests.rs diff --git a/vortex-datafusion/src/persistent/opener.rs b/vortex-datafusion/src/persistent/opener.rs index 1676b3ef956..04e5d577bd7 100644 --- a/vortex-datafusion/src/persistent/opener.rs +++ b/vortex-datafusion/src/persistent/opener.rs @@ -5,6 +5,7 @@ use std::future::ready; use std::ops::Range; use std::sync::Arc; use std::sync::Weak; +use std::task::Poll; use arrow_array::RecordBatchOptions; use arrow_schema::DataType; @@ -50,20 +51,22 @@ use vortex::error::VortexExpect; use vortex::expr::Expression; use vortex::expr::and_collect; use vortex::file::OpenOptionsSessionExt; +use vortex::file::VortexFile; use vortex::io::InstrumentedReadAt; +use vortex::io::VortexReadAt; use vortex::io::session::RuntimeSessionExt; use vortex::layout::LayoutReader; use vortex::layout::scan::metrics::ScanMetrics; use vortex::layout::scan::scan_builder::ScanBuilder; -use vortex::layout::scan::v2::ScanBuilder as V2ScanBuilder; -use vortex::layout::scan::v2::SegmentReader; use vortex::layout::scan::v2::partition_row_range; -use vortex::layout::segments::SegmentSource; use vortex::metrics::Label; use vortex::metrics::MetricsRegistry; +use vortex::scan::DataSource; +use vortex::scan::DataSourceRef; +use vortex::scan::PartitionPlan; +use vortex::scan::PartitionRef; +use vortex::scan::ScanRequest; use vortex::scan::execution::driver::ScanDriver; -use vortex::scan::prepare::ScanCache; -use vortex::scan::prepare::WeakScanCache; use vortex::session::VortexSession; use vortex_arrow::ArrowSessionExt; use vortex_utils::aliases::dash_map::DashMap; @@ -115,15 +118,13 @@ pub(crate) struct VortexOpener { /// To save on the overhead of reparsing FlatBuffers and rebuilding the layout tree, we cache /// a file reader the first time we read a file. pub layout_readers: Arc>>, - /// Shared V2 segment sources keyed by file path. + /// The V2 data source each open file's partitions scan, keyed by file path. /// - /// Partitions of one file read through one source, so a chunk straddling a partition - /// boundary and the file's metadata segments are read once, as they are for V1 through the - /// shared layout reader. - pub segment_sources: Arc>>, - /// The V2 scan cache each open file's partitions share: its lowered layout, filter and - /// projection plans, pruned zones and dictionary values, built once per file. - pub scan_caches: Arc>, + /// Partitions of one file share its source, and with it one segment reader and one scan + /// cache: a chunk straddling a partition boundary and the file's metadata segments are read + /// once, and the lowered layout, filter and projection plans, pruned zones and dictionary + /// values are built once per file. A source lives as long as one of its scans. + pub data_sources: Arc>>, /// Shared V1 full-file natural splits keyed by file path. pub natural_splits: Arc>>, /// Shared physical Arrow schemas of each file, keyed by file path. @@ -222,8 +223,7 @@ impl FileOpener for VortexOpener { let unified_file_schema = Arc::clone(self.table_schema.file_schema()); let limit = self.limit; let layout_readers = Arc::clone(&self.layout_readers); - let segment_sources = Arc::clone(&self.segment_sources); - let scan_caches = Arc::clone(&self.scan_caches); + let data_sources = Arc::clone(&self.data_sources); let natural_splits = Arc::clone(&self.natural_splits); let file_schemas = Arc::clone(&self.file_schemas); let has_output_ordering = self.has_output_ordering; @@ -280,50 +280,48 @@ impl FileOpener for VortexOpener { return Ok(stream::empty().boxed()); } - let mut open_opts = session - .open_options() - .with_file_size(file.object_meta.size) - .with_metrics_registry(Arc::clone(&metrics_registry)) - .with_labels(labels); - - let cached_footer = file_metadata_cache - .as_ref() - .and_then(|cache| cache.get(file.path())) - .filter(|entry| entry.is_valid_for(&file.object_meta)) - .and_then(|entry| { - entry - .file_metadata - .as_any() - .downcast_ref::() - .map(|vortex_metadata| vortex_metadata.footer().clone()) - }); - let footer_cache_hit = cached_footer.is_some(); - - if let Some(footer) = cached_footer { - open_opts = open_opts.with_footer(footer); - } - - let vxf = open_opts - .open_read(reader) - .await - .map_err(|e| exec_datafusion_err!("Failed to open Vortex file {e}"))?; - - // On a miss, cache the parsed footer so other partitions and later executions - // skip the footer fetch and parse. `infer_schema`/`infer_stats` also populate - // this cache, but only when planning goes through `VortexFormat`. - if !footer_cache_hit && let Some(cache) = &file_metadata_cache { - cache.put( - file.path(), - CachedFileMetadataEntry::new( - file.object_meta.clone(), - Arc::new(CachedVortexMetadata::new(&vxf)), + let open_file = || { + open_file( + &session, + reader, + &file, + metrics_registry, + labels, + file_metadata_cache.as_deref(), + ) + }; + // A V2 scan reads the file through its data source, which the file's other + // partitions may have opened already. A V1 scan reads it through its layout reader. + let (vxf, data_source) = if scan_v2 { + let shared = data_sources + .get(&file.object_meta.location) + .and_then(|source| source.upgrade()); + let data_source = match shared { + Some(source) => source, + None => shared_data_source( + &data_sources, + &file.object_meta.location, + open_file().await?.planned_data_source(), ), - ); - } + }; + (None, Some(data_source)) + } else { + (Some(open_file().await?), None) + }; + let (file_dtype, file_rows) = match (&vxf, &data_source) { + (Some(vxf), _) => (vxf.dtype().clone(), vxf.row_count()), + (None, Some(source)) => ( + source.dtype().clone(), + source.row_count().as_exact().ok_or_else(|| { + exec_datafusion_err!("Vortex file {} has no exact row count", file.path()) + })?, + ), + (None, None) => unreachable!("a file is opened for every scan"), + }; // Check if there are rows in this file. If not, we can save // ourselves some work and return an empty stream. - if vxf.row_count() == 0 { + if file_rows == 0 { return Ok(stream::empty().boxed()); } @@ -334,7 +332,7 @@ impl FileOpener for VortexOpener { None => { let schema = Arc::new( calculate_physical_schema( - vxf.dtype(), + &file_dtype, &unified_file_schema, &session.arrow(), ) @@ -412,8 +410,10 @@ impl FileOpener for VortexOpener { .map(|(_, expression)| expression.clone()), ); let residual_filter = conjunction_opt(residual_filters); - let native_filter = and_collect(native_filters) - .map(|filter| filter.bind(vxf.dtype())?.optimize_recursive()) + let native_filter = and_collect(native_filters); + let bound_native_filter = native_filter + .as_ref() + .map(|filter| filter.bind(&file_dtype)?.optimize_recursive()) .transpose() .map_err(|e| { exec_datafusion_err!("Couldn't bind Vortex scan filter in {}: {e}", file.path()) @@ -446,13 +446,13 @@ impl FileOpener for VortexOpener { // The schema of the stream returned from the vortex scan. // We use a reference schema for types that don't roundtrip (Dictionary, Utf8, etc.). - let scan_projection = scan_projection - .bind(vxf.dtype()) + let bound_scan_projection = scan_projection + .bind(&file_dtype) .and_then(|projection| projection.optimize_recursive()) .map_err(|_e| { exec_datafusion_err!("Couldn't get the dtype for the underlying Vortex scan") })?; - let scan_dtype = scan_projection.dtype().clone(); + let scan_dtype = bound_scan_projection.dtype().clone(); let stream_schema = calculate_physical_schema(&scan_dtype, &scan_reference_schema, &session.arrow())?; @@ -484,40 +484,32 @@ impl FileOpener for VortexOpener { let native_limit = limit .filter(|_| scan_v2 && residual_filter.is_none()) .map(|limit| (limit, Arc::clone(&output_schema))); + let handle = session.handle(); let map_batch = move |chunk| to_record_batch(chunk, &stream_target_field, &session); - let stream = if scan_v2 { - let mut scan_file = vxf.scan_file(); - // A placed file is shared through its scan cache's scheduler registration. - if let SegmentReader::Opaque(segments) = scan_file.reader { - scan_file.reader = SegmentReader::Opaque(shared_segment_source( - &segment_sources, - &file.object_meta.location, - segments, - )); - } - scan_file.cache = Some(shared_scan_cache(&scan_caches, &file.object_meta.location)); - let mut builder = V2ScanBuilder::new(vxf.session().clone(), scan_file) - .with_projection(scan_projection) - .with_some_filter(native_filter) - // Dynamic filters are pushed down inexactly: the TopK or join that produces - // one applies it again, so the scan may stop evaluating one that rejects - // almost nothing. - .with_skip_unselective_dynamic(true); + let stream = if let Some(data_source) = data_source { + let mut row_range = None; if let Some(bytes) = byte_range { // Every partition maps the same byte boundary to the same row boundary. - let rows = partition_row_range(bytes, file.object_meta.size, vxf.row_count()); + let rows = partition_row_range(bytes, file.object_meta.size, file_rows); if rows.is_empty() { return Ok(stream::empty().boxed()); } - builder = builder.with_row_range(rows); + row_range = Some(rows); } - if let Some(selection) = file + let selection = file .extensions .get::() .and_then(VortexAccessPlan::selection) - { - builder = builder.with_selection(selection.clone()); - } + .cloned() + .unwrap_or_default(); + let request = ScanRequest { + projection: scan_projection, + filter: native_filter, + row_range, + selection, + ordered: has_output_ordering, + ..Default::default() + }; // Scale per-scan concurrency by the number of DataFusion partitions by default. let concurrency = scan_concurrency.unwrap_or_else(|| { get_available_parallelism() @@ -525,15 +517,59 @@ impl FileOpener for VortexOpener { .div_ceil(partitions) .max(1) }); - let handle = vxf.session().handle(); - // Lowering and planning a wide file is real CPU: it runs where compute runs. - let scan = handle - .spawn_cpu(move || builder.prepare()) + let map_batch = Arc::new(map_batch); + let partitions: Vec = data_source + .scan(request) + .await + .map_err(|e| exec_datafusion_err!("Failed to plan Vortex scan: {e}"))? + .partitions() + .try_collect() .await .map_err(|e| exec_datafusion_err!("Failed to plan Vortex scan: {e}"))?; - let driver = ScanDriver::new(handle, concurrency, has_output_ordering); - Ok(driver.run_prepared(scan, map_batch)) + let mut streams = Vec::with_capacity(partitions.len()); + for partition in partitions { + let map_batch = Arc::clone(&map_batch); + let plan = partition + .plan() + .map_err(|e| exec_datafusion_err!("Failed to plan Vortex scan: {e}"))?; + streams.push(match plan { + PartitionPlan::Scan(builder) => { + // Dynamic filters are pushed down inexactly: the TopK or join that + // produces one applies it again, so the scan may stop evaluating one + // that rejects almost nothing. + let builder = builder.with_skip_unselective_dynamic(true); + // Lowering and planning a wide file is real CPU: it runs where + // compute runs. + let scan = + handle + .spawn_cpu(move || builder.prepare()) + .await + .map_err(|e| { + exec_datafusion_err!("Failed to plan Vortex scan: {e}") + })?; + ScanDriver::new(handle.clone(), concurrency, has_output_ordering) + .run_prepared(scan, move |chunk| map_batch(chunk)) + } + PartitionPlan::Arrays(arrays) => arrays + .map(move |chunk| chunk.and_then(|chunk| map_batch(chunk))) + .boxed(), + }); + } + let stream = if has_output_ordering { + stream::iter(streams).flatten().boxed() + } else { + stream::select_all(streams).boxed() + }; + // The source holds the file's shared scan cache and segment reader: keep it + // until the stream ends, so partitions of the file that open meanwhile find it. + Ok(stream + .chain(stream::poll_fn(move |_| { + let _ = &data_source; + Poll::Ready(None) + })) + .boxed()) } else { + let vxf = vxf.vortex_expect("a V1 scan opens its file"); // Share V1 layout readers across partitions of the file. let layout_reader = match layout_readers.entry(file.object_meta.location.clone()) { Entry::Occupied(mut occupied_entry) => { @@ -565,8 +601,8 @@ impl FileOpener for VortexOpener { }; let mut scan_builder = ScanBuilder::new(vxf.session().clone(), layout_reader) - .with_projection(scan_projection) - .with_some_filter(native_filter); + .with_projection(bound_scan_projection) + .with_some_filter(bound_native_filter); if let Some(vortex_plan) = file.extensions.get::() { scan_builder = vortex_plan.apply_to_builder(scan_builder); } @@ -717,39 +753,17 @@ impl NaturalSplits { } } -/// Returns the scan cache other partitions of `path` are planning with, or registers a new one. -/// A scan holds its cache until its stream ends, so the cache lives as long as one scan. -fn shared_scan_cache(scan_caches: &DashMap, path: &Path) -> ScanCache { - match scan_caches.entry(path.clone()) { - Entry::Occupied(mut entry) => { - if let Some(shared) = entry.get().upgrade() { - tracing::trace!("reusing scan cache for {path}"); - shared - } else { - let fresh = ScanCache::default(); - entry.insert(fresh.downgrade()); - fresh - } - } - Entry::Vacant(entry) => { - let fresh = ScanCache::default(); - entry.insert(fresh.downgrade()); - fresh - } - } -} - -/// Returns the segment source other partitions of `path` are reading through, or registers -/// `fresh` as that source. Like the layout readers, a source lives only as long as one scan. -fn shared_segment_source( - segment_sources: &DashMap>, +/// Returns the data source other partitions of `path` are scanning, or registers `fresh` as +/// that source. A source lives as long as one of its scans. +fn shared_data_source( + data_sources: &DashMap>, path: &Path, - fresh: Arc, -) -> Arc { - match segment_sources.entry(path.clone()) { + fresh: DataSourceRef, +) -> DataSourceRef { + match data_sources.entry(path.clone()) { Entry::Occupied(mut entry) => { if let Some(shared) = entry.get().upgrade() { - tracing::trace!("reusing segment source for {path}"); + tracing::trace!("reusing data source for {path}"); shared } else { entry.insert(Arc::downgrade(&fresh)); @@ -763,6 +777,57 @@ fn shared_segment_source( } } +/// Opens `file`, through DataFusion's file metadata cache when it holds the footer. +async fn open_file( + session: &VortexSession, + reader: InstrumentedReadAt, + file: &PartitionedFile, + metrics_registry: Arc, + labels: Vec