Skip to main content

vortex_io/segments/
file.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use std::any::Any;
5use std::collections::VecDeque;
6use std::future::Future;
7use std::pin::Pin;
8use std::sync::Arc;
9use std::sync::atomic::AtomicUsize;
10use std::sync::atomic::Ordering;
11use std::task::Context;
12use std::task::Poll;
13
14use futures::FutureExt;
15use futures::Stream;
16use futures::StreamExt;
17use futures::channel::mpsc;
18use futures::channel::oneshot;
19use futures::future;
20use futures::future::BoxFuture;
21use futures::future::Shared;
22use futures::stream::BoxStream;
23use futures::stream::Fuse;
24use futures::stream::SelectAll;
25use parking_lot::Mutex;
26use vortex_array::buffer::BufferHandle;
27use vortex_buffer::Alignment;
28use vortex_buffer::ByteBuffer;
29use vortex_error::VortexExpect;
30use vortex_error::VortexResult;
31use vortex_error::vortex_err;
32use vortex_error::vortex_panic;
33use vortex_metrics::Counter;
34use vortex_metrics::Histogram;
35use vortex_metrics::Label;
36use vortex_metrics::MetricBuilder;
37use vortex_metrics::MetricsRegistry;
38
39use super::SegmentFuture;
40use super::SegmentId;
41use super::SegmentLocation;
42use super::SegmentSource;
43use super::read::IoRequest;
44use super::read::IoRequestStream;
45use super::read::ReadRequest;
46use super::read::RequestId;
47use crate::ReadAtRequest;
48use crate::ReadAtStream;
49use crate::VortexReadAt;
50use crate::runtime::Handle;
51use crate::runtime::JoinOutcome;
52
53#[derive(Debug)]
54/// Events sent from segment futures to the coalescing read driver.
55pub enum ReadEvent {
56    /// A segment read has been registered.
57    Request(ReadRequest),
58    /// A registered read future has been polled.
59    Polled(RequestId),
60    /// A registered read future was dropped before completion.
61    Dropped(RequestId),
62}
63
64/// A [`SegmentSource`] for file-like IO.
65/// ## Coalescing and Pre-fetching
66///
67/// It is important to understand the semantics of the read futures returned by a [`FileSegmentSource`].
68/// Under the hood, each instance is backed by a stream that services read requests by
69/// applying coalescing and concurrency constraints.
70///
71/// Each read future has four states:
72/// * `registered` - the read future has been created, but not yet polled.
73/// * `requested` - the read future has been polled.
74/// * `in-flight` - the read request has been sent to the underlying storage system.
75/// * `resolved` - the read future has completed and resolved a result.
76///
77/// When a read request is `registered`, it will not itself trigger any I/O, but is eligible to
78/// be coalesced with other requests.
79///
80/// If a read future is dropped, it will be canceled if possible. This depends on the current
81/// state of the request, as well as whether the underlying storage system supports cancellation.
82///
83/// I/O requests will be processed in the order they are `registered`, however coalescing may mean
84/// other registered requests are lumped together into a single I/O operation.
85/// A cloneable handle to the background read driver, shared by every in-flight [`ReadFuture`].
86///
87/// [`Shared`] fans a single completion out to all readers with correct waker bookkeeping, so a
88/// reader is always woken when the driver finishes — even if another reader polled the driver more
89/// recently and was then dropped. Its output is `()`; a driver panic is carried out of band in
90/// [`DriverPanic`] so it can be re-raised on the reader side.
91type SharedDriver = Shared<BoxFuture<'static, ()>>;
92
93/// Slot holding the driver's panic payload, if it panicked while driving reads. The first reader to
94/// observe completion takes the payload and re-raises it; later readers report a graceful error.
95type DriverPanic = Arc<Mutex<Option<Box<dyn Any + Send>>>>;
96
97fn validate_read_result(
98    request: &IoRequest,
99    result: VortexResult<BufferHandle>,
100) -> VortexResult<BufferHandle> {
101    result.and_then(|buffer| {
102        if request.len() != buffer.len() {
103            return Err(vortex_err!(
104                "FileSegmentSource: expected buffer of length {} but received {}. {:?}",
105                request.len(),
106                buffer.len(),
107                request
108            ));
109        }
110        Ok(buffer)
111    })
112}
113
114type IoBatchStream = Fuse<BoxStream<'static, Vec<IoRequest>>>;
115
116enum ReadRangeResultsState {
117    Reading(ReadAtStream),
118    Missing,
119}
120
121/// Matches streamed range results back to their logical requests.
122struct ReadRangeResults {
123    state: ReadRangeResultsState,
124    remaining: Vec<Option<IoRequest>>,
125}
126
127impl ReadRangeResults {
128    fn new(results: ReadAtStream, requests: Vec<IoRequest>) -> Self {
129        Self {
130            state: ReadRangeResultsState::Reading(results),
131            remaining: requests.into_iter().map(Some).collect(),
132        }
133    }
134}
135
136impl Stream for ReadRangeResults {
137    type Item = (IoRequest, VortexResult<BufferHandle>);
138
139    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
140        loop {
141            match &mut self.state {
142                ReadRangeResultsState::Reading(results) => match results.poll_next_unpin(cx) {
143                    Poll::Ready(Some((request, result))) => {
144                        let Some(position) = self.remaining.iter().position(|req| {
145                            req.as_ref().is_some_and(|req| {
146                                req.offset() == request.offset
147                                    && req.len() == request.length
148                                    && req.alignment() == request.alignment
149                            })
150                        }) else {
151                            tracing::warn!(?request, "reader returned an unknown range");
152                            continue;
153                        };
154                        let req = self.remaining[position]
155                            .take()
156                            .vortex_expect("matched request is present");
157                        return Poll::Ready(Some((req, result)));
158                    }
159                    Poll::Ready(None) => self.state = ReadRangeResultsState::Missing,
160                    Poll::Pending => return Poll::Pending,
161                },
162                ReadRangeResultsState::Missing => {
163                    let Some(req) = self.remaining.iter_mut().find_map(Option::take) else {
164                        return Poll::Ready(None);
165                    };
166                    let error = vortex_err!(
167                        "FileSegmentSource: read_ranges ended before resolving request. {:?}",
168                        req
169                    );
170                    return Poll::Ready(Some((req, Err(error))));
171                }
172            }
173        }
174    }
175}
176
177/// Drives request batches while keeping the reader's concurrency slots occupied.
178struct ReadDriver<R> {
179    reader: Arc<R>,
180    batches: IoBatchStream,
181    pending: VecDeque<IoRequest>,
182    reads: SelectAll<ReadRangeResults>,
183    num_active: usize,
184    batches_done: bool,
185    concurrency: usize,
186    metrics: RequestMetrics,
187}
188
189impl<R: VortexReadAt> ReadDriver<R> {
190    fn new(
191        reader: R,
192        batches: BoxStream<'static, Vec<IoRequest>>,
193        concurrency: usize,
194        metrics: RequestMetrics,
195    ) -> Self {
196        Self {
197            reader: Arc::new(reader),
198            batches: batches.fuse(),
199            pending: VecDeque::new(),
200            reads: SelectAll::new(),
201            num_active: 0,
202            batches_done: false,
203            concurrency,
204            metrics,
205        }
206    }
207
208    fn submit_pending(&mut self) {
209        while self.num_active < self.concurrency && !self.pending.is_empty() {
210            let batch_len = (self.concurrency - self.num_active).min(self.pending.len());
211            let reqs = self.pending.drain(..batch_len).collect::<Vec<_>>();
212            self.num_active += batch_len;
213
214            self.metrics.read_ranges_calls.add(1);
215            self.metrics.read_ranges_num_ranges.update(batch_len as f64);
216            if batch_len > 1 {
217                self.metrics.read_ranges_multi.add(1);
218            }
219            tracing::trace!(
220                target: "vortex_file::read_ranges",
221                num_ranges = batch_len,
222                num_active = self.num_active,
223                "submitting positional read batch"
224            );
225
226            let requests = reqs
227                .iter()
228                .map(|req| ReadAtRequest::new(req.offset(), req.len(), req.alignment()))
229                .collect::<Vec<_>>()
230                .into();
231            let results = self.reader.read_ranges(requests);
232            self.reads.push(ReadRangeResults::new(results, reqs));
233        }
234    }
235}
236
237impl<R: VortexReadAt> Stream for ReadDriver<R> {
238    type Item = ();
239
240    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
241        let this = self.as_mut().get_mut();
242
243        // Observe every batch already available so submission can fill all free slots at once.
244        if !this.batches_done {
245            loop {
246                match this.batches.poll_next_unpin(cx) {
247                    Poll::Ready(Some(batch)) => this.pending.extend(batch),
248                    Poll::Ready(None) => {
249                        this.batches_done = true;
250                        break;
251                    }
252                    Poll::Pending => break,
253                }
254            }
255        }
256
257        this.submit_pending();
258
259        if this.batches_done && this.num_active == 0 {
260            return Poll::Ready(None);
261        }
262
263        match this.reads.poll_next_unpin(cx) {
264            Poll::Ready(Some((req, result))) => {
265                this.num_active -= 1;
266                let result = validate_read_result(&req, result);
267                req.resolve(result);
268                Poll::Ready(Some(()))
269            }
270            Poll::Ready(None) if this.num_active == 0 => Poll::Pending,
271            Poll::Ready(None) => {
272                vortex_panic!("read result streams ended with active requests")
273            }
274            Poll::Pending => Poll::Pending,
275        }
276    }
277}
278
279pub struct FileSegmentSource {
280    segments: Arc<[SegmentLocation]>,
281    /// A queue for sending read request events to the I/O stream.
282    events: mpsc::UnboundedSender<ReadEvent>,
283    /// Background request driver, joined by readers to surface a driver panic.
284    driver: SharedDriver,
285    /// Panic payload captured if the driver panicked while driving reads.
286    driver_panic: DriverPanic,
287    /// The next read request ID.
288    next_id: Arc<AtomicUsize>,
289}
290
291impl FileSegmentSource {
292    /// Open a file-backed segment source over `reader`.
293    ///
294    /// The returned source spawns a background driver on `handle` that coalesces and executes
295    /// random-access read requests.
296    pub fn open<R: VortexReadAt + Clone>(
297        segments: Arc<[SegmentLocation]>,
298        reader: R,
299        handle: Handle,
300        metrics: RequestMetrics,
301    ) -> Self {
302        let (send, recv) = mpsc::unbounded();
303
304        let max_alignment = segments
305            .iter()
306            .map(|segment| segment.alignment)
307            .max()
308            .unwrap_or_else(Alignment::none);
309        let coalesce_config = reader.coalesce_config().map(|mut config| {
310            // Aligning the coalesced start down can add up to (alignment - 1) bytes.
311            // Increase max_size to keep the effective payload window consistent.
312            let extra = (max_alignment.as_usize() as u64).saturating_sub(1);
313            config.max_size = config.max_size.saturating_add(extra);
314            config
315        });
316        let concurrency = reader.concurrency();
317        if concurrency == 0 {
318            vortex_panic!(
319                "VortexReadAt::concurrency returned 0 (uri={:?}); this would stall I/O",
320                reader.uri()
321            );
322        }
323
324        let stream = IoRequestStream::new(
325            StreamExt::boxed(recv),
326            coalesce_config,
327            max_alignment,
328            concurrency,
329            metrics.clone(),
330        )
331        .boxed();
332
333        let drive_fut = ReadDriver::new(reader, stream, concurrency, metrics).collect::<()>();
334
335        // Spawn the driver so the runtime makes I/O progress independently of any reader. Readers
336        // join it (below) only to surface a panic raised while driving reads.
337        let mut task = handle.spawn(drive_fut);
338        let driver_panic: DriverPanic = Arc::new(Mutex::new(None));
339        let driver = {
340            let driver_panic = Arc::clone(&driver_panic);
341            async move {
342                // Poll for the terminal outcome without re-raising: a benign abort (runtime
343                // teardown) resolves to `()` so readers report a graceful error, while a panic is
344                // stashed for the first reader to re-raise.
345                if let JoinOutcome::Panicked(panic) = future::poll_fn(|cx| task.poll_join(cx)).await
346                {
347                    *driver_panic.lock() = Some(panic);
348                }
349            }
350            .boxed()
351            .shared()
352        };
353
354        Self {
355            segments,
356            events: send,
357            driver,
358            driver_panic,
359            next_id: Arc::new(AtomicUsize::new(0)),
360        }
361    }
362}
363
364impl SegmentSource for FileSegmentSource {
365    fn request(&self, id: SegmentId) -> SegmentFuture {
366        // We eagerly register the read request here assuming the behaviour of [`FileSegmentSource`], where
367        // coalescing becomes effective prior to the future being polled.
368        let spec = *match self.segments.get(*id as usize) {
369            Some(spec) => spec,
370            None => {
371                return future::ready(Err(vortex_err!("Missing segment: {}", id))).boxed();
372            }
373        };
374
375        let SegmentLocation {
376            offset,
377            length,
378            alignment,
379        } = spec;
380
381        let (send, recv) = oneshot::channel();
382        let id = self.next_id.fetch_add(1, Ordering::Relaxed);
383        let event = ReadEvent::Request(ReadRequest {
384            id,
385            offset,
386            length: length as usize,
387            alignment,
388            callback: send,
389        });
390
391        // If we fail to submit the event, we create a future that has failed.
392        if let Err(e) = self.events.unbounded_send(event) {
393            return future::ready(Err(vortex_err!("Failed to submit read request: {e}"))).boxed();
394        }
395
396        let fut = ReadFuture {
397            id,
398            recv,
399            polled: false,
400            finished: false,
401            events: self.events.clone(),
402            driver: self.driver.clone(),
403            driver_panic: Arc::clone(&self.driver_panic),
404        };
405
406        // One allocation: we only box the returned SegmentFuture, not the inner ReadFuture.
407        fut.boxed()
408    }
409}
410
411/// A future that resolves a read request from a [`FileSegmentSource`].
412///
413/// See the documentation for [`FileSegmentSource`] for details on coalescing and pre-fetching.
414/// If dropped, the read request will be canceled where possible.
415struct ReadFuture {
416    id: usize,
417    recv: oneshot::Receiver<VortexResult<BufferHandle>>,
418    polled: bool,
419    finished: bool,
420    events: mpsc::UnboundedSender<ReadEvent>,
421    driver: SharedDriver,
422    driver_panic: DriverPanic,
423}
424
425impl Future for ReadFuture {
426    type Output = VortexResult<BufferHandle>;
427
428    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
429        match self.recv.poll_unpin(cx) {
430            // note: we are skipping polled and dropped events for this if the future is ready on
431            //       the first poll, that means this request was completed before it was polled,
432            //       as part of a coalesced request.
433            Poll::Ready(Ok(result)) => {
434                self.finished = true;
435                Poll::Ready(result)
436            }
437            // The request's sender was dropped, so the driver has finished. Join it so a panic
438            // raised while driving reads is re-raised here rather than surfacing as a generic
439            // error. Only report the dropped error once the driver has finished.
440            Poll::Ready(Err(e)) => match self.driver.poll_unpin(cx) {
441                Poll::Ready(()) => {
442                    self.finished = true;
443                    // Re-raise the driver panic on the first reader to observe it; later readers
444                    // fall through to the graceful dropped error.
445                    if let Some(panic) = self.driver_panic.lock().take() {
446                        std::panic::resume_unwind(panic);
447                    }
448                    Poll::Ready(Err(vortex_err!("ReadRequest dropped by runtime: {e}")))
449                }
450                Poll::Pending => Poll::Pending,
451            },
452            Poll::Pending if !self.polled => {
453                self.polled = true;
454                // Notify the I/O stream that this request has been polled.
455                match self.events.unbounded_send(ReadEvent::Polled(self.id)) {
456                    Ok(()) => Poll::Pending,
457                    Err(e) => Poll::Ready(Err(vortex_err!("ReadRequest dropped by runtime: {e}"))),
458                }
459            }
460            _ => Poll::Pending,
461        }
462    }
463}
464
465impl Drop for ReadFuture {
466    fn drop(&mut self) {
467        // Completed requests have already left driver state.
468        if self.finished {
469            return;
470        }
471
472        // Best-effort cancellation signal to the I/O stream.
473        drop(self.events.unbounded_send(ReadEvent::Dropped(self.id)));
474    }
475}
476
477/// Metrics emitted by the file segment request driver.
478#[derive(Clone)]
479pub struct RequestMetrics {
480    /// Number of individual segment requests observed by the driver.
481    pub individual_requests: Counter,
482    /// Number of physical reads after coalescing.
483    pub coalesced_requests: Counter,
484    /// Distribution of how many segment requests were merged into each physical read.
485    pub num_requests_coalesced: Histogram,
486    /// Number of calls made to [`VortexReadAt::read_ranges`].
487    pub read_ranges_calls: Counter,
488    /// Number of `read_ranges` calls containing more than one physical range.
489    pub read_ranges_multi: Counter,
490    /// Distribution of physical range counts submitted per `read_ranges` call.
491    pub read_ranges_num_ranges: Histogram,
492}
493
494impl RequestMetrics {
495    /// Create request metrics in `metrics_registry` with shared labels.
496    pub fn new(metrics_registry: &dyn MetricsRegistry, labels: Vec<Label>) -> Self {
497        Self {
498            individual_requests: MetricBuilder::new(metrics_registry)
499                .add_labels(labels.clone())
500                .counter("io.requests.individual"),
501            coalesced_requests: MetricBuilder::new(metrics_registry)
502                .add_labels(labels.clone())
503                .counter("io.requests.coalesced"),
504            num_requests_coalesced: MetricBuilder::new(metrics_registry)
505                .add_labels(labels.clone())
506                .histogram("io.requests.coalesced.num_coalesced"),
507            read_ranges_calls: MetricBuilder::new(metrics_registry)
508                .add_labels(labels.clone())
509                .counter("io.read_ranges.calls"),
510            read_ranges_multi: MetricBuilder::new(metrics_registry)
511                .add_labels(labels.clone())
512                .counter("io.read_ranges.multi_range_calls"),
513            read_ranges_num_ranges: MetricBuilder::new(metrics_registry)
514                .add_labels(labels)
515                .histogram("io.read_ranges.num_ranges"),
516        }
517    }
518}
519
520/// A [`SegmentSource`] that resolves segments synchronously from an
521/// in-memory [`ByteBuffer`].
522///
523/// Resolves segments synchronously, bypassing the async I/O pipeline.
524pub struct BufferSegmentSource {
525    buffer: ByteBuffer,
526    segments: Arc<[SegmentLocation]>,
527}
528
529impl BufferSegmentSource {
530    /// Create a new `BufferSegmentSource` from a buffer and its segment map.
531    pub fn new(buffer: ByteBuffer, segments: Arc<[SegmentLocation]>) -> Self {
532        Self { buffer, segments }
533    }
534}
535
536impl SegmentSource for BufferSegmentSource {
537    fn request(&self, id: SegmentId) -> SegmentFuture {
538        let spec = match self.segments.get(*id as usize) {
539            Some(spec) => spec,
540            None => {
541                return future::ready(Err(vortex_err!("Missing segment: {}", id))).boxed();
542            }
543        };
544
545        let Ok(start) = usize::try_from(spec.offset) else {
546            return future::ready(Err(vortex_err!(
547                "Segment {} offset {} does not fit in memory",
548                *id,
549                spec.offset
550            )))
551            .boxed();
552        };
553        let end = start + spec.length as usize;
554        if end > self.buffer.len() {
555            return future::ready(Err(vortex_err!(
556                "Segment {} range {}..{} out of bounds for buffer of length {}",
557                *id,
558                start,
559                end,
560                self.buffer.len()
561            )))
562            .boxed();
563        }
564
565        let slice = self.buffer.slice(start..end).aligned(spec.alignment);
566        future::ready(Ok(BufferHandle::new_host(slice))).boxed()
567    }
568}
569
570#[cfg(test)]
571#[cfg(feature = "tokio")]
572mod tests {
573    use std::panic::AssertUnwindSafe;
574    use std::sync::atomic::AtomicBool;
575
576    use futures::future::BoxFuture;
577    use futures::task::ArcWake;
578    use vortex_error::vortex_bail;
579    use vortex_metrics::DefaultMetricsRegistry;
580
581    use super::SegmentSource;
582    use super::*;
583    use crate::runtime::tokio::TokioRuntime;
584
585    fn io_request(id: RequestId, offset: u64, length: usize) -> IoRequest {
586        let (callback, _receiver) = oneshot::channel();
587        IoRequest::new_single(ReadRequest {
588            id,
589            offset,
590            length,
591            alignment: Alignment::none(),
592            callback,
593        })
594    }
595
596    #[tokio::test]
597    async fn read_range_results_matches_results_and_reports_missing_requests() {
598        let requests = vec![io_request(0, 0, 4), io_request(1, 4, 4)];
599        let unknown = ReadAtRequest::new(8, 4, Alignment::none());
600        let returned = ReadAtRequest::new(4, 4, Alignment::none());
601        let buffer = BufferHandle::new_host(ByteBuffer::from(vec![0; 4]));
602        let results =
603            futures::stream::iter([(unknown, Ok(buffer.clone())), (returned, Ok(buffer))]).boxed();
604
605        let resolved = ReadRangeResults::new(results, requests)
606            .collect::<Vec<_>>()
607            .await;
608
609        assert_eq!(resolved.len(), 2);
610        assert_eq!(resolved[0].0.offset(), 4);
611        assert!(resolved[0].1.is_ok());
612        assert_eq!(resolved[1].0.offset(), 0);
613        assert!(resolved[1].1.is_err());
614    }
615
616    #[derive(Clone)]
617    struct PanickingReadAt;
618
619    impl VortexReadAt for PanickingReadAt {
620        fn concurrency(&self) -> usize {
621            1
622        }
623
624        fn size(&self) -> BoxFuture<'static, VortexResult<u64>> {
625            async { Ok(4) }.boxed()
626        }
627
628        fn read_at(
629            &self,
630            _offset: u64,
631            _length: usize,
632            _alignment: Alignment,
633        ) -> BoxFuture<'static, VortexResult<BufferHandle>> {
634            async {
635                panic!("read-at panic");
636            }
637            .boxed()
638        }
639    }
640
641    fn panicking_source() -> FileSegmentSource {
642        let segments: Arc<[SegmentLocation]> = Arc::from([SegmentLocation {
643            offset: 0,
644            length: 4,
645            alignment: Alignment::none(),
646        }]);
647        let metrics = DefaultMetricsRegistry::default();
648        FileSegmentSource::open(
649            segments,
650            PanickingReadAt,
651            TokioRuntime::current(),
652            RequestMetrics::new(&metrics, vec![]),
653        )
654    }
655
656    fn panic_message(payload: &(dyn Any + Send)) -> &str {
657        payload
658            .downcast_ref::<&str>()
659            .copied()
660            .or_else(|| payload.downcast_ref::<String>().map(String::as_str))
661            .unwrap_or("<non-string panic>")
662    }
663
664    #[tokio::test]
665    #[should_panic(expected = "read-at panic")]
666    async fn file_segment_source_propagates_read_driver_panic() {
667        let source = panicking_source();
668        let _result = source.request(SegmentId::from(0)).await;
669    }
670
671    // A read-driver panic must propagate on *every* run rather than sometimes surfacing as a
672    // generic "dropped by runtime" error, which is nondeterministic.
673    #[tokio::test]
674    async fn file_segment_source_read_driver_panic_propagates_deterministically() {
675        for i in 0..100 {
676            let source = panicking_source();
677            let outcome = AssertUnwindSafe(source.request(SegmentId::from(0)))
678                .catch_unwind()
679                .await;
680            assert!(
681                outcome.is_err(),
682                "read-driver panic was not propagated on iteration {i}; \
683                 the request resolved instead of panicking"
684            );
685        }
686    }
687
688    #[derive(Default)]
689    struct WakeFlag(AtomicBool);
690
691    impl ArcWake for WakeFlag {
692        fn wake_by_ref(arc_self: &Arc<Self>) {
693            arc_self.0.store(true, Ordering::SeqCst);
694        }
695    }
696
697    // A driver panic must surface to every reader sharing one driver: exactly one reader re-raises
698    // the original panic, the rest report a graceful error, and none hang. The readers are polled
699    // by hand, so a missed wake-up fails an assertion instead of a wall-clock timeout. The panic
700    // hook can take seconds to symbolize a backtrace on Windows.
701    #[tokio::test]
702    async fn file_segment_source_panic_propagates_to_all_concurrent_readers() {
703        let source = panicking_source();
704
705        let mut readers: Vec<_> = (0..8)
706            .map(|_| {
707                (
708                    source.request(SegmentId::from(0)),
709                    Arc::new(WakeFlag::default()),
710                )
711            })
712            .collect();
713
714        let poll_reader = |reader: &mut SegmentFuture, flag: &Arc<WakeFlag>| {
715            let waker = futures::task::waker(Arc::clone(flag));
716            let mut cx = Context::from_waker(&waker);
717            std::panic::catch_unwind(AssertUnwindSafe(|| reader.poll_unpin(&mut cx)))
718        };
719
720        // The first poll marks each request as polled, which lets the driver issue the read.
721        for (reader, flag) in &mut readers {
722            assert!(
723                matches!(poll_reader(reader, flag), Ok(Poll::Pending)),
724                "a reader resolved before the driver ran"
725            );
726        }
727
728        source.driver.clone().await;
729
730        let mut original_panics = 0;
731        for (i, (reader, flag)) in readers.iter_mut().enumerate() {
732            assert!(
733                flag.0.load(Ordering::SeqCst),
734                "reader {i} was not woken after the driver finished"
735            );
736
737            let outcome = match poll_reader(reader, flag) {
738                Ok(Poll::Ready(result)) => Ok(result),
739                Ok(Poll::Pending) => {
740                    panic!("reader {i} is still pending after the driver finished")
741                }
742                Err(payload) => Err(payload),
743            };
744
745            match outcome {
746                // The first reader to observe completion re-raises the original panic.
747                Err(payload) => {
748                    assert!(
749                        panic_message(&*payload).contains("read-at panic"),
750                        "got: {:?}",
751                        panic_message(&*payload)
752                    );
753                    original_panics += 1;
754                }
755                // Every other reader reports a graceful dropped-by-runtime error.
756                Ok(result) => assert!(result.is_err(), "expected a dropped-by-runtime error"),
757            }
758        }
759
760        assert_eq!(
761            original_panics, 1,
762            "exactly one reader should re-raise the original driver panic"
763        );
764    }
765
766    #[derive(Clone)]
767    struct ReadRangesOnly {
768        calls: Arc<AtomicUsize>,
769    }
770
771    impl VortexReadAt for ReadRangesOnly {
772        fn concurrency(&self) -> usize {
773            4
774        }
775
776        fn size(&self) -> BoxFuture<'static, VortexResult<u64>> {
777            async { Ok(16) }.boxed()
778        }
779
780        fn read_at(
781            &self,
782            _offset: u64,
783            _length: usize,
784            _alignment: Alignment,
785        ) -> BoxFuture<'static, VortexResult<BufferHandle>> {
786            async { panic!("read_at should not be called") }.boxed()
787        }
788
789        fn read_ranges(&self, requests: Arc<[ReadAtRequest]>) -> ReadAtStream {
790            self.calls.fetch_add(1, Ordering::Relaxed);
791            let results = requests
792                .iter()
793                .copied()
794                .map(|request| {
795                    let buffer = BufferHandle::new_host(
796                        ByteBuffer::from(vec![0; request.length]).aligned(request.alignment),
797                    );
798                    (request, Ok(buffer))
799                })
800                .collect::<Vec<_>>();
801            futures::stream::iter(results).boxed()
802        }
803    }
804
805    #[tokio::test]
806    async fn read_driver_batches_ready_requests() -> VortexResult<()> {
807        let calls = Arc::new(AtomicUsize::new(0));
808        let segments: Arc<[SegmentLocation]> = (0..4)
809            .map(|i| SegmentLocation {
810                offset: i * 4,
811                length: 4,
812                alignment: Alignment::none(),
813            })
814            .collect();
815        let metrics = DefaultMetricsRegistry::default();
816        let request_metrics = RequestMetrics::new(&metrics, vec![]);
817        let source = FileSegmentSource::open(
818            segments,
819            ReadRangesOnly {
820                calls: Arc::clone(&calls),
821            },
822            TokioRuntime::current(),
823            request_metrics.clone(),
824        );
825
826        let results = future::join_all((0..4).map(|i| source.request(SegmentId::from(i)))).await;
827
828        for result in results {
829            assert_eq!(result?.len(), 4);
830        }
831        assert_eq!(calls.load(Ordering::Relaxed), 1);
832        assert_eq!(request_metrics.read_ranges_calls.value(), 1);
833        assert_eq!(request_metrics.read_ranges_multi.value(), 1);
834        assert_eq!(request_metrics.read_ranges_num_ranges.count(), 1);
835        assert_eq!(request_metrics.read_ranges_num_ranges.total(), 4.0);
836        Ok(())
837    }
838
839    #[derive(Clone)]
840    struct ControlledReadRanges {
841        active: Arc<AtomicUsize>,
842        max_active: Arc<AtomicUsize>,
843        batch_sizes: Arc<Mutex<Vec<usize>>>,
844        permits: Arc<tokio::sync::Semaphore>,
845    }
846
847    impl VortexReadAt for ControlledReadRanges {
848        fn concurrency(&self) -> usize {
849            4
850        }
851
852        fn size(&self) -> BoxFuture<'static, VortexResult<u64>> {
853            async { Ok(24) }.boxed()
854        }
855
856        fn read_at(
857            &self,
858            _offset: u64,
859            _length: usize,
860            _alignment: Alignment,
861        ) -> BoxFuture<'static, VortexResult<BufferHandle>> {
862            async { panic!("read_at should not be called") }.boxed()
863        }
864
865        fn read_ranges(&self, requests: Arc<[ReadAtRequest]>) -> ReadAtStream {
866            self.batch_sizes.lock().push(requests.len());
867            let active = self.active.fetch_add(requests.len(), Ordering::SeqCst) + requests.len();
868            self.max_active.fetch_max(active, Ordering::SeqCst);
869
870            let reads = requests
871                .iter()
872                .copied()
873                .map(|request| {
874                    let active = Arc::clone(&self.active);
875                    let permits = Arc::clone(&self.permits);
876                    async move {
877                        let Ok(permit) = permits.acquire_owned().await else {
878                            vortex_panic!("test semaphore unexpectedly closed");
879                        };
880                        permit.forget();
881                        active.fetch_sub(1, Ordering::SeqCst);
882                        let buffer = BufferHandle::new_host(
883                            ByteBuffer::from(vec![0; request.length]).aligned(request.alignment),
884                        );
885                        (request, Ok(buffer))
886                    }
887                })
888                .collect::<Vec<_>>();
889            futures::stream::iter(reads).buffer_unordered(4).boxed()
890        }
891    }
892
893    #[tokio::test]
894    async fn read_driver_refills_global_concurrency_across_batches() -> VortexResult<()> {
895        let active = Arc::new(AtomicUsize::new(0));
896        let max_active = Arc::new(AtomicUsize::new(0));
897        let batch_sizes = Arc::new(Mutex::new(Vec::new()));
898        let permits = Arc::new(tokio::sync::Semaphore::new(0));
899        let segments: Arc<[SegmentLocation]> = (0..6)
900            .map(|i| SegmentLocation {
901                offset: i * 4,
902                length: 4,
903                alignment: Alignment::none(),
904            })
905            .collect();
906        let metrics = DefaultMetricsRegistry::default();
907        let source = FileSegmentSource::open(
908            segments,
909            ControlledReadRanges {
910                active: Arc::clone(&active),
911                max_active: Arc::clone(&max_active),
912                batch_sizes: Arc::clone(&batch_sizes),
913                permits: Arc::clone(&permits),
914            },
915            TokioRuntime::current(),
916            RequestMetrics::new(&metrics, vec![]),
917        );
918        let reads = TokioRuntime::current().spawn(async move {
919            future::join_all((0..6).map(|i| source.request(SegmentId::from(i)))).await
920        });
921
922        assert!(
923            tokio::time::timeout(std::time::Duration::from_secs(1), async {
924                while active.load(Ordering::SeqCst) != 4 {
925                    tokio::task::yield_now().await;
926                }
927            })
928            .await
929            .is_ok()
930        );
931
932        permits.add_permits(1);
933        assert!(
934            tokio::time::timeout(std::time::Duration::from_secs(1), async {
935                while batch_sizes.lock().len() < 2 || active.load(Ordering::SeqCst) != 4 {
936                    tokio::task::yield_now().await;
937                }
938            })
939            .await
940            .is_ok()
941        );
942        assert_eq!(batch_sizes.lock().as_slice(), [4, 1]);
943        assert_eq!(max_active.load(Ordering::SeqCst), 4);
944
945        permits.add_permits(5);
946        for result in reads.await {
947            assert_eq!(result?.len(), 4);
948        }
949        assert_eq!(max_active.load(Ordering::SeqCst), 4);
950        Ok(())
951    }
952
953    #[tokio::test]
954    async fn read_driver_keeps_slots_full_while_a_straggler_is_in_flight() -> VortexResult<()> {
955        let active = Arc::new(AtomicUsize::new(0));
956        let max_active = Arc::new(AtomicUsize::new(0));
957        let batch_sizes = Arc::new(Mutex::new(Vec::new()));
958        let permits = Arc::new(tokio::sync::Semaphore::new(0));
959        let segments: Arc<[SegmentLocation]> = (0..8)
960            .map(|i| SegmentLocation {
961                offset: i * 4,
962                length: 4,
963                alignment: Alignment::none(),
964            })
965            .collect();
966        let metrics = DefaultMetricsRegistry::default();
967        let source = FileSegmentSource::open(
968            segments,
969            ControlledReadRanges {
970                active: Arc::clone(&active),
971                max_active: Arc::clone(&max_active),
972                batch_sizes: Arc::clone(&batch_sizes),
973                permits: Arc::clone(&permits),
974            },
975            TokioRuntime::current(),
976            RequestMetrics::new(&metrics, vec![]),
977        );
978        let reads = TokioRuntime::current().spawn(async move {
979            future::join_all((0..8).map(|i| source.request(SegmentId::from(i)))).await
980        });
981
982        wait_for_active_reads(&active, 4).await;
983
984        // Complete three reads while leaving one original read blocked as a straggler. Each freed
985        // slot must be refilled before the next completion; a batch-barrier implementation would
986        // instead fall from four active reads to one and submit no replacement work.
987        for expected_calls in 2..=4 {
988            permits.add_permits(1);
989            assert!(
990                tokio::time::timeout(std::time::Duration::from_secs(1), async {
991                    while batch_sizes.lock().len() < expected_calls
992                        || active.load(Ordering::SeqCst) != 4
993                    {
994                        tokio::task::yield_now().await;
995                    }
996                })
997                .await
998                .is_ok()
999            );
1000        }
1001
1002        assert_eq!(batch_sizes.lock().as_slice(), [4, 1, 1, 1]);
1003        assert_eq!(active.load(Ordering::SeqCst), 4);
1004        assert_eq!(max_active.load(Ordering::SeqCst), 4);
1005
1006        permits.add_permits(5);
1007        for result in reads.await {
1008            assert_eq!(result?.len(), 4);
1009        }
1010        Ok(())
1011    }
1012
1013    async fn wait_for_active_reads(active: &AtomicUsize, expected: usize) {
1014        assert!(
1015            tokio::time::timeout(std::time::Duration::from_secs(1), async {
1016                while active.load(Ordering::SeqCst) != expected {
1017                    tokio::task::yield_now().await;
1018                }
1019            })
1020            .await
1021            .is_ok()
1022        );
1023    }
1024
1025    #[derive(Clone)]
1026    struct SlowErrReadAt;
1027
1028    impl VortexReadAt for SlowErrReadAt {
1029        fn concurrency(&self) -> usize {
1030            4
1031        }
1032
1033        fn size(&self) -> BoxFuture<'static, VortexResult<u64>> {
1034            async { Ok(1024) }.boxed()
1035        }
1036
1037        fn read_at(
1038            &self,
1039            offset: u64,
1040            _length: usize,
1041            _alignment: Alignment,
1042        ) -> BoxFuture<'static, VortexResult<BufferHandle>> {
1043            async move {
1044                // Stagger completions so some reads finish while others are still in flight.
1045                for _ in 0..(offset % 5 + 1) {
1046                    tokio::task::yield_now().await;
1047                }
1048                vortex_bail!("slow read done")
1049            }
1050            .boxed()
1051        }
1052    }
1053
1054    // Many segment reads driven on separate tasks must all make progress and complete.
1055    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
1056    async fn read_driver_concurrent_reads_make_progress() {
1057        let n = 16u32;
1058        let segments: Arc<[SegmentLocation]> = (0..n)
1059            .map(|i| SegmentLocation {
1060                offset: u64::from(i) * 4,
1061                length: 4,
1062                alignment: Alignment::none(),
1063            })
1064            .collect();
1065        let metrics = DefaultMetricsRegistry::default();
1066        let source = Arc::new(FileSegmentSource::open(
1067            segments,
1068            SlowErrReadAt,
1069            TokioRuntime::current(),
1070            RequestMetrics::new(&metrics, vec![]),
1071        ));
1072
1073        let handle = TokioRuntime::current();
1074        let tasks: Vec<_> = (0..n)
1075            .map(|i| {
1076                let source = Arc::clone(&source);
1077                handle.spawn(async move { source.request(SegmentId::from(i)).await })
1078            })
1079            .collect();
1080
1081        let joined =
1082            tokio::time::timeout(std::time::Duration::from_secs(5), future::join_all(tasks)).await;
1083
1084        let results = joined.expect("concurrent reads stalled before completing");
1085        assert_eq!(results.len(), n as usize);
1086        for result in results {
1087            let err = result.expect_err("reader must forward the I/O error");
1088            assert!(err.to_string().contains("slow read done"), "{err}");
1089        }
1090    }
1091}