Skip to main content

datafusion_datasource/file_stream/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5//! A generic stream over file format readers that can be used by
6//! any file format that read its files from start to end.
7//!
8//! Note: Most traits here need to be marked `Sync + Send` to be
9//! compliant with the `SendableRecordBatchStream` trait.
10
11mod builder;
12mod metrics;
13mod scan_state;
14pub(crate) mod work_source;
15
16use std::pin::Pin;
17use std::sync::Arc;
18use std::task::{Context, Poll};
19
20use crate::PartitionedFile;
21use crate::file_scan_config::FileScanConfig;
22use arrow::datatypes::SchemaRef;
23use datafusion_common::Result;
24use datafusion_execution::RecordBatchStream;
25use datafusion_physical_plan::metrics::{BaselineMetrics, ExecutionPlanMetricsSet};
26
27use arrow::record_batch::RecordBatch;
28
29use futures::Stream;
30use futures::future::BoxFuture;
31use futures::stream::BoxStream;
32
33use self::scan_state::{ScanAndReturn, ScanState};
34
35pub use builder::FileStreamBuilder;
36pub use metrics::{FileStreamMetrics, StartableTime};
37
38/// A stream that iterates record batch by record batch, file over file.
39pub struct FileStream {
40    /// The stream schema (file schema including partition columns and after
41    /// projection).
42    projected_schema: SchemaRef,
43    /// The stream state
44    state: FileStreamState,
45    /// runtime baseline metrics
46    baseline_metrics: BaselineMetrics,
47}
48
49impl FileStream {
50    /// Create a new `FileStream` using the give `FileOpener` to scan underlying files
51    #[deprecated(since = "54.0.0", note = "Use FileStreamBuilder instead")]
52    pub fn new(
53        config: &FileScanConfig,
54        partition: usize,
55        file_opener: Arc<dyn FileOpener>,
56        metrics: &ExecutionPlanMetricsSet,
57    ) -> Result<Self> {
58        FileStreamBuilder::new(config)
59            .with_partition(partition)
60            .with_file_opener(file_opener)
61            .with_metrics(metrics)
62            .build()
63    }
64
65    /// Specify the behavior when an error occurs opening or scanning a file
66    ///
67    /// If `OnError::Skip` the stream will skip files which encounter an error and continue
68    /// If `OnError:Fail` (default) the stream will fail and stop processing when an error occurs
69    pub fn with_on_error(mut self, on_error: OnError) -> Self {
70        match &mut self.state {
71            FileStreamState::Scan { scan_state } => scan_state.set_on_error(on_error),
72            FileStreamState::Error | FileStreamState::Done => {
73                // no effect as there are no more files to process
74            }
75        }
76        self
77    }
78
79    fn poll_inner(&mut self, cx: &mut Context<'_>) -> Poll<Option<Result<RecordBatch>>> {
80        loop {
81            match &mut self.state {
82                FileStreamState::Scan { scan_state: queue } => {
83                    let action = queue.poll_scan(cx);
84                    match action {
85                        ScanAndReturn::Continue => {}
86                        ScanAndReturn::Done(result) => {
87                            self.state = FileStreamState::Done;
88                            return Poll::Ready(result);
89                        }
90                        ScanAndReturn::Error(err) => {
91                            self.state = FileStreamState::Error;
92                            return Poll::Ready(Some(Err(err)));
93                        }
94                        ScanAndReturn::Return(result) => return result,
95                    }
96                }
97                FileStreamState::Error | FileStreamState::Done => {
98                    return Poll::Ready(None);
99                }
100            }
101        }
102    }
103}
104
105impl Stream for FileStream {
106    type Item = Result<RecordBatch>;
107
108    fn poll_next(
109        mut self: Pin<&mut Self>,
110        cx: &mut Context<'_>,
111    ) -> Poll<Option<Self::Item>> {
112        let result = self.poll_inner(cx);
113        self.baseline_metrics.record_poll(result)
114    }
115}
116
117impl RecordBatchStream for FileStream {
118    fn schema(&self) -> SchemaRef {
119        Arc::clone(&self.projected_schema)
120    }
121}
122
123/// A fallible future that resolves to a stream of [`RecordBatch`]
124pub type FileOpenFuture =
125    BoxFuture<'static, Result<BoxStream<'static, Result<RecordBatch>>>>;
126
127/// Describes the behavior of the `FileStream` if file opening or scanning fails
128#[derive(Default)]
129pub enum OnError {
130    /// Fail the entire stream and return the underlying error
131    #[default]
132    Fail,
133    /// Continue scanning, ignoring the failed file
134    Skip,
135}
136
137/// Generic API for opening a file using an [`ObjectStore`] and resolving to a
138/// stream of [`RecordBatch`]
139///
140/// [`ObjectStore`]: object_store::ObjectStore
141pub trait FileOpener: Unpin + Send + Sync {
142    /// Asynchronously open the specified file and return a stream
143    /// of [`RecordBatch`]
144    fn open(&self, partitioned_file: PartitionedFile) -> Result<FileOpenFuture>;
145}
146
147enum FileStreamState {
148    /// Actively processing readers, ready morsels, and planner work.
149    Scan {
150        /// The ready queues and active reader for the current file.
151        scan_state: Box<ScanState>,
152    },
153    /// Encountered an error
154    Error,
155    /// Finished scanning all requested data, possibly because a limit was reached
156    Done,
157}
158
159#[cfg(test)]
160mod tests {
161    use crate::file_scan_config::{FileScanConfig, FileScanConfigBuilder};
162    use crate::morsel::mocks::{
163        IoFutureId, MockMorselizer, MockPlanBuilder, MockPlanner, MorselId,
164        PendingPlannerBuilder, PollsToResolve,
165    };
166    use crate::source::DataSource;
167    use crate::tests::make_partition;
168    use crate::{PartitionedFile, TableSchema};
169    use arrow::array::{AsArray, RecordBatch};
170    use arrow::datatypes::{DataType, Field, Int32Type, Schema};
171    use datafusion_common::DataFusionError;
172    use datafusion_common::config::ConfigOptions;
173    use datafusion_common::error::Result;
174    use datafusion_execution::object_store::ObjectStoreUrl;
175    use datafusion_physical_plan::metrics::ExecutionPlanMetricsSet;
176    use futures::{FutureExt as _, StreamExt as _};
177    use std::collections::{BTreeMap, VecDeque};
178    use std::sync::Arc;
179    use std::sync::atomic::{AtomicUsize, Ordering};
180
181    use crate::file_stream::{
182        FileOpenFuture, FileOpener, FileStream, FileStreamBuilder, OnError,
183        work_source::SharedWorkSource,
184    };
185    use crate::test_util::MockSource;
186
187    use datafusion_common::{assert_batches_eq, exec_err, internal_err};
188
189    /// Test identifier for one `FileStream` partition.
190    #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
191    struct PartitionId(usize);
192
193    /// Test `FileOpener` which will simulate errors during file opening or scanning
194    #[derive(Default)]
195    struct TestOpener {
196        /// Index in stream of files which should throw an error while opening
197        error_opening_idx: Vec<usize>,
198        /// Index in stream of files which should throw an error while scanning
199        error_scanning_idx: Vec<usize>,
200        /// Index of last file in stream
201        current_idx: AtomicUsize,
202        /// `RecordBatch` to return
203        records: Vec<RecordBatch>,
204    }
205
206    impl FileOpener for TestOpener {
207        fn open(&self, _partitioned_file: PartitionedFile) -> Result<FileOpenFuture> {
208            let idx = self.current_idx.fetch_add(1, Ordering::SeqCst);
209
210            if self.error_opening_idx.contains(&idx) {
211                Ok(futures::future::ready(internal_err!("error opening")).boxed())
212            } else if self.error_scanning_idx.contains(&idx) {
213                let error = futures::future::ready(exec_err!("error scanning"));
214                let stream = futures::stream::once(error).boxed();
215                Ok(futures::future::ready(Ok(stream)).boxed())
216            } else {
217                let iterator = self.records.clone().into_iter().map(Ok);
218                let stream = futures::stream::iter(iterator).boxed();
219                Ok(futures::future::ready(Ok(stream)).boxed())
220            }
221        }
222    }
223
224    #[derive(Default)]
225    struct FileStreamTest {
226        /// Number of files in the stream
227        num_files: usize,
228        /// Global limit of records emitted by the stream
229        limit: Option<usize>,
230        /// Error-handling behavior of the stream
231        on_error: OnError,
232        /// Mock `FileOpener`
233        opener: TestOpener,
234    }
235
236    impl FileStreamTest {
237        pub fn new() -> Self {
238            Self::default()
239        }
240
241        /// Specify the number of files in the stream
242        pub fn with_num_files(mut self, num_files: usize) -> Self {
243            self.num_files = num_files;
244            self
245        }
246
247        /// Specify the limit
248        pub fn with_limit(mut self, limit: Option<usize>) -> Self {
249            self.limit = limit;
250            self
251        }
252
253        /// Specify the index of files in the stream which should
254        /// throw an error when opening
255        pub fn with_open_errors(mut self, idx: Vec<usize>) -> Self {
256            self.opener.error_opening_idx = idx;
257            self
258        }
259
260        /// Specify the index of files in the stream which should
261        /// throw an error when scanning
262        pub fn with_scan_errors(mut self, idx: Vec<usize>) -> Self {
263            self.opener.error_scanning_idx = idx;
264            self
265        }
266
267        /// Specify the behavior of the stream when an error occurs
268        pub fn with_on_error(mut self, on_error: OnError) -> Self {
269            self.on_error = on_error;
270            self
271        }
272
273        /// Specify the record batches that should be returned from each
274        /// file that is successfully scanned
275        pub fn with_records(mut self, records: Vec<RecordBatch>) -> Self {
276            self.opener.records = records;
277            self
278        }
279
280        /// Collect the results of the `FileStream`
281        pub async fn result(self) -> Result<Vec<RecordBatch>> {
282            let file_schema = self
283                .opener
284                .records
285                .first()
286                .map(|batch| batch.schema())
287                .unwrap_or_else(|| Arc::new(Schema::empty()));
288
289            // let ctx = SessionContext::new();
290            let mock_files: Vec<(String, u64)> = (0..self.num_files)
291                .map(|idx| (format!("mock_file{idx}"), 10_u64))
292                .collect();
293
294            // let mock_files_ref: Vec<(&str, u64)> = mock_files
295            //     .iter()
296            //     .map(|(name, size)| (name.as_str(), *size))
297            //     .collect();
298
299            let file_group = mock_files
300                .into_iter()
301                .map(|(name, size)| PartitionedFile::new(name, size))
302                .collect();
303
304            let on_error = self.on_error;
305
306            let table_schema = TableSchema::from(file_schema);
307            let config = FileScanConfigBuilder::new(
308                ObjectStoreUrl::parse("test:///").unwrap(),
309                Arc::new(MockSource::new(table_schema)),
310            )
311            .with_file_group(file_group)
312            .with_limit(self.limit)
313            .build();
314            let metrics_set = ExecutionPlanMetricsSet::new();
315            let file_stream = FileStreamBuilder::new(&config)
316                .with_partition(0)
317                .with_file_opener(Arc::new(self.opener))
318                .with_metrics(&metrics_set)
319                .with_on_error(on_error)
320                .build()?;
321
322            file_stream
323                .collect::<Vec<_>>()
324                .await
325                .into_iter()
326                .collect::<Result<Vec<_>>>()
327        }
328    }
329
330    /// helper that creates a stream of 2 files with the same pair of batches in each ([0,1,2] and [0,1])
331    async fn create_and_collect(limit: Option<usize>) -> Vec<RecordBatch> {
332        FileStreamTest::new()
333            .with_records(vec![make_partition(3), make_partition(2)])
334            .with_num_files(2)
335            .with_limit(limit)
336            .result()
337            .await
338            .expect("error executing stream")
339    }
340
341    /// Create the smallest valid file scan config for builder validation tests.
342    fn builder_test_config() -> FileScanConfig {
343        let table_schema = TableSchema::from(Arc::new(Schema::empty()));
344        FileScanConfigBuilder::new(
345            ObjectStoreUrl::parse("test:///").unwrap(),
346            Arc::new(MockSource::new(table_schema)),
347        )
348        .with_file(PartitionedFile::new("mock_file", 10))
349        .build()
350    }
351
352    /// Convenience helper to keep builder error assertions focused on the
353    /// specific missing or invalid input under test.
354    fn builder_error(builder: FileStreamBuilder<'_>) -> String {
355        builder.build().err().unwrap().to_string()
356    }
357
358    #[tokio::test]
359    async fn on_error_opening() -> Result<()> {
360        let batches = FileStreamTest::new()
361            .with_records(vec![make_partition(3), make_partition(2)])
362            .with_num_files(2)
363            .with_on_error(OnError::Skip)
364            .with_open_errors(vec![0])
365            .result()
366            .await?;
367
368        #[rustfmt::skip]
369        assert_batches_eq!(&[
370            "+---+",
371            "| i |",
372            "+---+",
373            "| 0 |",
374            "| 1 |",
375            "| 2 |",
376            "| 0 |",
377            "| 1 |",
378            "+---+",
379        ], &batches);
380
381        let batches = FileStreamTest::new()
382            .with_records(vec![make_partition(3), make_partition(2)])
383            .with_num_files(2)
384            .with_on_error(OnError::Skip)
385            .with_open_errors(vec![1])
386            .result()
387            .await?;
388
389        #[rustfmt::skip]
390        assert_batches_eq!(&[
391            "+---+",
392            "| i |",
393            "+---+",
394            "| 0 |",
395            "| 1 |",
396            "| 2 |",
397            "| 0 |",
398            "| 1 |",
399            "+---+",
400        ], &batches);
401
402        let batches = FileStreamTest::new()
403            .with_records(vec![make_partition(3), make_partition(2)])
404            .with_num_files(2)
405            .with_on_error(OnError::Skip)
406            .with_open_errors(vec![0, 1])
407            .result()
408            .await?;
409
410        #[rustfmt::skip]
411        assert_batches_eq!(&[
412            "++",
413            "++",
414        ], &batches);
415
416        Ok(())
417    }
418
419    #[tokio::test]
420    async fn on_error_scanning_fail() -> Result<()> {
421        let result = FileStreamTest::new()
422            .with_records(vec![make_partition(3), make_partition(2)])
423            .with_num_files(2)
424            .with_on_error(OnError::Fail)
425            .with_scan_errors(vec![1])
426            .result()
427            .await;
428
429        assert!(result.is_err());
430
431        Ok(())
432    }
433
434    #[tokio::test]
435    async fn on_error_opening_fail() -> Result<()> {
436        let result = FileStreamTest::new()
437            .with_records(vec![make_partition(3), make_partition(2)])
438            .with_num_files(2)
439            .with_on_error(OnError::Fail)
440            .with_open_errors(vec![1])
441            .result()
442            .await;
443
444        assert!(result.is_err());
445
446        Ok(())
447    }
448
449    #[tokio::test]
450    async fn on_error_scanning() -> Result<()> {
451        let batches = FileStreamTest::new()
452            .with_records(vec![make_partition(3), make_partition(2)])
453            .with_num_files(2)
454            .with_on_error(OnError::Skip)
455            .with_scan_errors(vec![0])
456            .result()
457            .await?;
458
459        #[rustfmt::skip]
460        assert_batches_eq!(&[
461            "+---+",
462            "| i |",
463            "+---+",
464            "| 0 |",
465            "| 1 |",
466            "| 2 |",
467            "| 0 |",
468            "| 1 |",
469            "+---+",
470        ], &batches);
471
472        let batches = FileStreamTest::new()
473            .with_records(vec![make_partition(3), make_partition(2)])
474            .with_num_files(2)
475            .with_on_error(OnError::Skip)
476            .with_scan_errors(vec![1])
477            .result()
478            .await?;
479
480        #[rustfmt::skip]
481        assert_batches_eq!(&[
482            "+---+",
483            "| i |",
484            "+---+",
485            "| 0 |",
486            "| 1 |",
487            "| 2 |",
488            "| 0 |",
489            "| 1 |",
490            "+---+",
491        ], &batches);
492
493        let batches = FileStreamTest::new()
494            .with_records(vec![make_partition(3), make_partition(2)])
495            .with_num_files(2)
496            .with_on_error(OnError::Skip)
497            .with_scan_errors(vec![0, 1])
498            .result()
499            .await?;
500
501        #[rustfmt::skip]
502        assert_batches_eq!(&[
503            "++",
504            "++",
505        ], &batches);
506
507        Ok(())
508    }
509
510    #[tokio::test]
511    async fn on_error_mixed() -> Result<()> {
512        let batches = FileStreamTest::new()
513            .with_records(vec![make_partition(3), make_partition(2)])
514            .with_num_files(3)
515            .with_on_error(OnError::Skip)
516            .with_open_errors(vec![1])
517            .with_scan_errors(vec![0])
518            .result()
519            .await?;
520
521        #[rustfmt::skip]
522        assert_batches_eq!(&[
523            "+---+",
524            "| i |",
525            "+---+",
526            "| 0 |",
527            "| 1 |",
528            "| 2 |",
529            "| 0 |",
530            "| 1 |",
531            "+---+",
532        ], &batches);
533
534        let batches = FileStreamTest::new()
535            .with_records(vec![make_partition(3), make_partition(2)])
536            .with_num_files(3)
537            .with_on_error(OnError::Skip)
538            .with_open_errors(vec![0])
539            .with_scan_errors(vec![1])
540            .result()
541            .await?;
542
543        #[rustfmt::skip]
544        assert_batches_eq!(&[
545            "+---+",
546            "| i |",
547            "+---+",
548            "| 0 |",
549            "| 1 |",
550            "| 2 |",
551            "| 0 |",
552            "| 1 |",
553            "+---+",
554        ], &batches);
555
556        let batches = FileStreamTest::new()
557            .with_records(vec![make_partition(3), make_partition(2)])
558            .with_num_files(3)
559            .with_on_error(OnError::Skip)
560            .with_open_errors(vec![2])
561            .with_scan_errors(vec![0, 1])
562            .result()
563            .await?;
564
565        #[rustfmt::skip]
566        assert_batches_eq!(&[
567            "++",
568            "++",
569        ], &batches);
570
571        let batches = FileStreamTest::new()
572            .with_records(vec![make_partition(3), make_partition(2)])
573            .with_num_files(3)
574            .with_on_error(OnError::Skip)
575            .with_open_errors(vec![0, 2])
576            .with_scan_errors(vec![1])
577            .result()
578            .await?;
579
580        #[rustfmt::skip]
581        assert_batches_eq!(&[
582            "++",
583            "++",
584        ], &batches);
585
586        Ok(())
587    }
588
589    #[tokio::test]
590    async fn without_limit() -> Result<()> {
591        let batches = create_and_collect(None).await;
592
593        #[rustfmt::skip]
594        assert_batches_eq!(&[
595            "+---+",
596            "| i |",
597            "+---+",
598            "| 0 |",
599            "| 1 |",
600            "| 2 |",
601            "| 0 |",
602            "| 1 |",
603            "| 0 |",
604            "| 1 |",
605            "| 2 |",
606            "| 0 |",
607            "| 1 |",
608            "+---+",
609        ], &batches);
610
611        Ok(())
612    }
613
614    #[tokio::test]
615    async fn with_limit_between_files() -> Result<()> {
616        let batches = create_and_collect(Some(5)).await;
617        #[rustfmt::skip]
618        assert_batches_eq!(&[
619            "+---+",
620            "| i |",
621            "+---+",
622            "| 0 |",
623            "| 1 |",
624            "| 2 |",
625            "| 0 |",
626            "| 1 |",
627            "+---+",
628        ], &batches);
629
630        Ok(())
631    }
632
633    #[tokio::test]
634    async fn with_limit_at_middle_of_batch() -> Result<()> {
635        let batches = create_and_collect(Some(6)).await;
636        #[rustfmt::skip]
637        assert_batches_eq!(&[
638            "+---+",
639            "| i |",
640            "+---+",
641            "| 0 |",
642            "| 1 |",
643            "| 2 |",
644            "| 0 |",
645            "| 1 |",
646            "| 0 |",
647            "+---+",
648        ], &batches);
649
650        Ok(())
651    }
652
653    #[test]
654    fn builder_requires_partition_file_opener_and_metrics() {
655        let config = builder_test_config();
656
657        let err = builder_error(FileStreamBuilder::new(&config));
658        assert!(err.contains("FileStreamBuilder missing required partition"));
659
660        let err = builder_error(FileStreamBuilder::new(&config).with_partition(0));
661        assert!(err.contains("FileStreamBuilder missing required morselizer"));
662
663        let err = builder_error(
664            FileStreamBuilder::new(&config)
665                .with_partition(0)
666                .with_file_opener(Arc::new(TestOpener::default())),
667        );
668        assert!(err.contains("FileStreamBuilder missing required metrics"));
669    }
670
671    #[test]
672    fn builder_errors_on_invalid_partition() {
673        let config = builder_test_config();
674        let metrics = ExecutionPlanMetricsSet::new();
675
676        let err = builder_error(
677            FileStreamBuilder::new(&config)
678                .with_partition(1)
679                .with_file_opener(Arc::new(TestOpener::default()))
680                .with_metrics(&metrics),
681        );
682        assert!(err.contains("FileStreamBuilder invalid partition index: 1"));
683    }
684
685    /// Verifies the simplest morsel-driven flow: one planner produces one
686    /// morsel immediately, and that morsel is then scanned to completion.
687    #[tokio::test]
688    async fn morsel_no_io() -> Result<()> {
689        let test = FileStreamMorselTest::new().with_file(
690            MockPlanner::builder("file1.parquet")
691                .add_plan(MockPlanBuilder::new().with_morsel(MorselId(10), 42))
692                .return_none(),
693        );
694
695        insta::assert_snapshot!(test.run().await.unwrap(), @r"
696        ----- Output Stream -----
697        Batch: 42
698        Done
699        ----- File Stream Events -----
700        morselize_file: file1.parquet
701        planner_created: file1.parquet
702        planner_called: file1.parquet
703        morsel_produced: file1.parquet, MorselId(10)
704        morsel_stream_started: MorselId(10)
705        morsel_stream_batch_produced: MorselId(10), BatchId(42)
706        morsel_stream_finished: MorselId(10)
707        ");
708
709        Ok(())
710    }
711
712    /// Verifies that a planner can block on one I/O phase and then produce a
713    /// morsel containing two batches.
714    #[tokio::test]
715    async fn morsel_single_io_two_batches() -> Result<()> {
716        let test = FileStreamMorselTest::new().with_file(
717            MockPlanner::builder("file1.parquet")
718                .add_plan(
719                    PendingPlannerBuilder::new(IoFutureId(1))
720                        .with_polls_to_resolve(PollsToResolve(1)),
721                )
722                .add_plan(
723                    MockPlanBuilder::new()
724                        .with_morsel_batches(MorselId(10), vec![42, 43]),
725                )
726                .return_none(),
727        );
728
729        insta::assert_snapshot!(test.run().await.unwrap(), @r"
730        ----- Output Stream -----
731        Batch: 42
732        Batch: 43
733        Done
734        ----- File Stream Events -----
735        morselize_file: file1.parquet
736        planner_created: file1.parquet
737        planner_called: file1.parquet
738        io_future_created: file1.parquet, IoFutureId(1)
739        io_future_polled: file1.parquet, IoFutureId(1)
740        io_future_polled: file1.parquet, IoFutureId(1)
741        io_future_resolved: file1.parquet, IoFutureId(1)
742        planner_called: file1.parquet
743        morsel_produced: file1.parquet, MorselId(10)
744        morsel_stream_started: MorselId(10)
745        morsel_stream_batch_produced: MorselId(10), BatchId(42)
746        morsel_stream_batch_produced: MorselId(10), BatchId(43)
747        morsel_stream_finished: MorselId(10)
748        ");
749
750        Ok(())
751    }
752
753    /// Verifies that a planner can traverse two sequential I/O phases before
754    /// producing one batch, similar to Parquet.
755    #[tokio::test]
756    async fn morsel_two_ios_one_batch() -> Result<()> {
757        let test = FileStreamMorselTest::new().with_file(
758            MockPlanner::builder("file1.parquet")
759                .add_plan(PendingPlannerBuilder::new(IoFutureId(1)))
760                .add_plan(PendingPlannerBuilder::new(IoFutureId(2)))
761                .add_plan(MockPlanBuilder::new().with_morsel(MorselId(10), 42))
762                .return_none(),
763        );
764
765        insta::assert_snapshot!(test.run().await.unwrap(), @r"
766        ----- Output Stream -----
767        Batch: 42
768        Done
769        ----- File Stream Events -----
770        morselize_file: file1.parquet
771        planner_created: file1.parquet
772        planner_called: file1.parquet
773        io_future_created: file1.parquet, IoFutureId(1)
774        io_future_polled: file1.parquet, IoFutureId(1)
775        io_future_resolved: file1.parquet, IoFutureId(1)
776        planner_called: file1.parquet
777        io_future_created: file1.parquet, IoFutureId(2)
778        io_future_polled: file1.parquet, IoFutureId(2)
779        io_future_resolved: file1.parquet, IoFutureId(2)
780        planner_called: file1.parquet
781        morsel_produced: file1.parquet, MorselId(10)
782        morsel_stream_started: MorselId(10)
783        morsel_stream_batch_produced: MorselId(10), BatchId(42)
784        morsel_stream_finished: MorselId(10)
785        ");
786
787        Ok(())
788    }
789
790    /// Verifies that a planner I/O future can fail and terminate the stream.
791    #[tokio::test]
792    async fn morsel_io_error() -> Result<()> {
793        let test = FileStreamMorselTest::new().with_file(
794            MockPlanner::builder("file1.parquet").add_plan(
795                PendingPlannerBuilder::new(IoFutureId(1))
796                    .with_error("io failed while opening file"),
797            ),
798        );
799
800        insta::assert_snapshot!(test.run().await.unwrap(), @r"
801        ----- Output Stream -----
802        Error: io failed while opening file
803        Done
804        ----- File Stream Events -----
805        morselize_file: file1.parquet
806        planner_created: file1.parquet
807        planner_called: file1.parquet
808        io_future_created: file1.parquet, IoFutureId(1)
809        io_future_polled: file1.parquet, IoFutureId(1)
810        io_future_errored: file1.parquet, IoFutureId(1), io failed while opening file
811        ");
812
813        Ok(())
814    }
815
816    /// Verifies that pending planner I/O does not block draining the current
817    /// morsel stream.
818    #[tokio::test]
819    async fn morsel_pending_planner_does_not_block_active_reader() -> Result<()> {
820        let test = FileStreamMorselTest::new().with_file(
821            MockPlanner::builder("file1.parquet")
822                .add_plan(
823                    MockPlanBuilder::new()
824                        .with_morsel_batches(MorselId(10), vec![41, 42])
825                        .with_pending_planner(IoFutureId(1), PollsToResolve(3), Ok(())),
826                )
827                .add_plan(MockPlanBuilder::new().with_morsel(MorselId(11), 43))
828                .return_none(),
829        );
830
831        // The key events are:
832        // 1. the first `planner_called` produces `MorselId(10)` and creates `IoFutureId(1)`
833        // 2. `MorselId(10)` continues yielding both batches while that I/O is pending
834        // 3. after the I/O resolves, planning resumes and yields `MorselId(11)`
835        insta::assert_snapshot!(test.run().await.unwrap(), @r"
836        ----- Output Stream -----
837        Batch: 41
838        Batch: 42
839        Batch: 43
840        Done
841        ----- File Stream Events -----
842        morselize_file: file1.parquet
843        planner_created: file1.parquet
844        planner_called: file1.parquet
845        morsel_produced: file1.parquet, MorselId(10)
846        io_future_created: file1.parquet, IoFutureId(1)
847        io_future_polled: file1.parquet, IoFutureId(1)
848        morsel_stream_started: MorselId(10)
849        io_future_polled: file1.parquet, IoFutureId(1)
850        morsel_stream_batch_produced: MorselId(10), BatchId(41)
851        io_future_polled: file1.parquet, IoFutureId(1)
852        morsel_stream_batch_produced: MorselId(10), BatchId(42)
853        io_future_polled: file1.parquet, IoFutureId(1)
854        io_future_resolved: file1.parquet, IoFutureId(1)
855        morsel_stream_finished: MorselId(10)
856        planner_called: file1.parquet
857        morsel_produced: file1.parquet, MorselId(11)
858        morsel_stream_started: MorselId(11)
859        morsel_stream_batch_produced: MorselId(11), BatchId(43)
860        morsel_stream_finished: MorselId(11)
861        ");
862
863        Ok(())
864    }
865
866    /// Verifies that one `plan()` call can return a ready child planner, which
867    /// is then called to produce the morsel.
868    #[tokio::test]
869    async fn morsel_ready_child_planner() -> Result<()> {
870        let child_planner = MockPlanner::builder("child planner")
871            .add_plan(MockPlanBuilder::new().with_morsel(MorselId(10), 42))
872            .return_none();
873
874        let test = FileStreamMorselTest::new().with_file(
875            MockPlanner::builder("file1.parquet")
876                .add_plan(MockPlanBuilder::new().with_ready_planner(child_planner))
877                .return_none(),
878        );
879
880        insta::assert_snapshot!(test.run().await.unwrap(), @r"
881        ----- Output Stream -----
882        Batch: 42
883        Done
884        ----- File Stream Events -----
885        morselize_file: file1.parquet
886        planner_created: file1.parquet
887        planner_called: file1.parquet
888        planner_created: child planner
889        planner_called: child planner
890        morsel_produced: child planner, MorselId(10)
891        morsel_stream_started: MorselId(10)
892        morsel_stream_batch_produced: MorselId(10), BatchId(42)
893        morsel_stream_finished: MorselId(10)
894        ");
895
896        Ok(())
897    }
898
899    /// Verifies that planning can fail after a successful I/O phase.
900    #[tokio::test]
901    async fn morsel_plan_error_after_io() -> Result<()> {
902        let test = FileStreamMorselTest::new().with_file(
903            MockPlanner::builder("file1.parquet")
904                .add_plan(PendingPlannerBuilder::new(IoFutureId(1)))
905                .return_error("planner failed after io"),
906        );
907
908        insta::assert_snapshot!(test.run().await.unwrap(), @r"
909        ----- Output Stream -----
910        Error: planner failed after io
911        Done
912        ----- File Stream Events -----
913        morselize_file: file1.parquet
914        planner_created: file1.parquet
915        planner_called: file1.parquet
916        io_future_created: file1.parquet, IoFutureId(1)
917        io_future_polled: file1.parquet, IoFutureId(1)
918        io_future_resolved: file1.parquet, IoFutureId(1)
919        planner_called: file1.parquet
920        ");
921
922        Ok(())
923    }
924
925    /// Verifies that `FileStream` scans multiple files in order.
926    #[tokio::test]
927    async fn morsel_multiple_files() -> Result<()> {
928        let test = FileStreamMorselTest::new()
929            .with_file(
930                MockPlanner::builder("file1.parquet")
931                    .add_plan(MockPlanBuilder::new().with_morsel(MorselId(10), 41))
932                    .return_none(),
933            )
934            .with_file(
935                MockPlanner::builder("file2.parquet")
936                    .add_plan(MockPlanBuilder::new().with_morsel(MorselId(11), 42))
937                    .return_none(),
938            );
939
940        insta::assert_snapshot!(test.run().await.unwrap(), @r"
941        ----- Output Stream -----
942        Batch: 41
943        Batch: 42
944        Done
945        ----- File Stream Events -----
946        morselize_file: file1.parquet
947        planner_created: file1.parquet
948        planner_called: file1.parquet
949        morsel_produced: file1.parquet, MorselId(10)
950        morsel_stream_started: MorselId(10)
951        morsel_stream_batch_produced: MorselId(10), BatchId(41)
952        morsel_stream_finished: MorselId(10)
953        morselize_file: file2.parquet
954        planner_created: file2.parquet
955        planner_called: file2.parquet
956        morsel_produced: file2.parquet, MorselId(11)
957        morsel_stream_started: MorselId(11)
958        morsel_stream_batch_produced: MorselId(11), BatchId(42)
959        morsel_stream_finished: MorselId(11)
960        ");
961
962        Ok(())
963    }
964
965    /// Verifies that a global limit can stop the stream before a second file is opened.
966    #[tokio::test]
967    async fn morsel_limit_prevents_second_file() -> Result<()> {
968        let test = FileStreamMorselTest::new()
969            .with_file(
970                MockPlanner::builder("file1.parquet")
971                    .add_plan(
972                        MockPlanBuilder::new()
973                            .with_morsel_batches(MorselId(10), vec![41, 42]),
974                    )
975                    .return_none(),
976            )
977            .with_file(
978                MockPlanner::builder("file2.parquet")
979                    .add_plan(MockPlanBuilder::new().with_morsel(MorselId(11), 43))
980                    .return_none(),
981            )
982            .with_limit(1);
983
984        // Note the snapshot should not ever see planner id2
985        insta::assert_snapshot!(test.run().await.unwrap(), @r"
986        ----- Output Stream -----
987        Batch: 41
988        Done
989        ----- File Stream Events -----
990        morselize_file: file1.parquet
991        planner_created: file1.parquet
992        planner_called: file1.parquet
993        morsel_produced: file1.parquet, MorselId(10)
994        morsel_stream_started: MorselId(10)
995        morsel_stream_batch_produced: MorselId(10), BatchId(41)
996        ");
997
998        Ok(())
999    }
1000
1001    /// Return a morsel test with two partitions:
1002    /// Partition 0: file1, file2, file3
1003    /// Partition 1: file4
1004    ///
1005    /// Partition 1 has only 1 file but it polled first 4 times
1006    fn two_partition_morsel_test() -> FileStreamMorselTest {
1007        FileStreamMorselTest::new()
1008            // Partition 0 has three files
1009            .with_file_in_partition(
1010                PartitionId(0),
1011                MockPlanner::builder("file1.parquet")
1012                    .add_plan(MockPlanBuilder::new().with_morsel(MorselId(10), 101))
1013                    .return_none(),
1014            )
1015            .with_file_in_partition(
1016                PartitionId(0),
1017                MockPlanner::builder("file2.parquet")
1018                    .add_plan(MockPlanBuilder::new().with_morsel(MorselId(11), 102))
1019                    .return_none(),
1020            )
1021            .with_file_in_partition(
1022                PartitionId(0),
1023                MockPlanner::builder("file3.parquet")
1024                    .add_plan(MockPlanBuilder::new().with_morsel(MorselId(12), 103))
1025                    .return_none(),
1026            )
1027            // Partition 1 has only one file, but is polled first
1028            .with_file_in_partition(
1029                PartitionId(1),
1030                MockPlanner::builder("file4.parquet")
1031                    .add_plan(MockPlanBuilder::new().with_morsel(MorselId(13), 201))
1032                    .return_none(),
1033            )
1034            .with_reads(vec![
1035                PartitionId(1),
1036                PartitionId(1),
1037                PartitionId(1),
1038                PartitionId(1),
1039                PartitionId(1),
1040            ])
1041    }
1042
1043    /// Verifies that an idle sibling stream can steal shared files from
1044    /// another stream once it exhausts its own local work.
1045    #[tokio::test]
1046    async fn morsel_shared_files_can_be_stolen() -> Result<()> {
1047        let test = two_partition_morsel_test().with_file_stream_events(false);
1048
1049        // Partition 0 starts with 3 files, but Partition 1 is polled first.
1050        // Since Partition 1 is polled first, it will run all the files even those
1051        // that were assigned to Partition 0.
1052        insta::assert_snapshot!(test.run().await.unwrap(), @r"
1053        ----- Partition 0 -----
1054        Done
1055        ----- Partition 1 -----
1056        Batch: 101
1057        Batch: 102
1058        Batch: 103
1059        Batch: 201
1060        Done
1061        ----- File Stream Events -----
1062        (omitted due to with_file_stream_events(false))
1063        ");
1064
1065        Ok(())
1066    }
1067
1068    /// Verifies that a stream that must preserve order keeps its files local
1069    /// and therefore cannot steal from a sibling shared queue.
1070    #[tokio::test]
1071    async fn morsel_preserve_order_keeps_files_local() -> Result<()> {
1072        // same fixture as `morsel_shared_files_can_be_stolen` but marked as
1073        // preserve-order
1074        let test = two_partition_morsel_test()
1075            .with_preserve_order(true)
1076            .with_file_stream_events(false);
1077
1078        // Even though that Partition 1 is polled first, it can not steal files
1079        // from partition 0. The three files originally assigned to Partition 0
1080        // must be evaluated by Partition 0.
1081        insta::assert_snapshot!(test.run().await.unwrap(), @r"
1082        ----- Partition 0 -----
1083        Batch: 101
1084        Batch: 102
1085        Batch: 103
1086        Done
1087        ----- Partition 1 -----
1088        Batch: 201
1089        Done
1090        ----- File Stream Events -----
1091        (omitted due to with_file_stream_events(false))
1092        ");
1093
1094        Ok(())
1095    }
1096
1097    /// Verifies that declared output partitioning disables shared work stealing.
1098    #[tokio::test]
1099    async fn morsel_declared_output_partitioning_keeps_files_local() -> Result<()> {
1100        // same fixture as `morsel_shared_files_can_be_stolen` but marked as
1101        // preserve-partitioned
1102        let test = two_partition_morsel_test()
1103            .with_declared_output_partitioning(true)
1104            .with_file_stream_events(false);
1105
1106        insta::assert_snapshot!(test.run().await.unwrap(), @r"
1107        ----- Partition 0 -----
1108        Batch: 101
1109        Batch: 102
1110        Batch: 103
1111        Done
1112        ----- Partition 1 -----
1113        Batch: 201
1114        Done
1115        ----- File Stream Events -----
1116        (omitted due to with_file_stream_events(false))
1117        ");
1118
1119        Ok(())
1120    }
1121
1122    /// Verifies that disabling `enable_file_stream_work_stealing` keeps each
1123    /// stream's files local, so a sibling cannot steal them at runtime.
1124    ///
1125    /// Covers <https://github.com/apache/datafusion/issues/23293>: executors
1126    /// that run each output partition as an isolated task in a separate process
1127    /// (Ballista, datafusion-distributed) poll only their own partition, so the
1128    /// shared work queue would let that one partition drain files belonging to
1129    /// its siblings. Disabling the flag falls back to per-partition file groups.
1130    #[tokio::test]
1131    async fn morsel_disabled_work_stealing_keeps_files_local() -> Result<()> {
1132        // same fixture as `morsel_shared_files_can_be_stolen`, but with work
1133        // stealing disabled via config
1134        let test = two_partition_morsel_test()
1135            .with_enable_file_stream_work_stealing(false)
1136            .with_file_stream_events(false);
1137
1138        // Even though Partition 1 is polled first, it cannot steal the three
1139        // files assigned to Partition 0; each partition reads only its own.
1140        insta::assert_snapshot!(test.run().await.unwrap(), @r"
1141        ----- Partition 0 -----
1142        Batch: 101
1143        Batch: 102
1144        Batch: 103
1145        Done
1146        ----- Partition 1 -----
1147        Batch: 201
1148        Done
1149        ----- File Stream Events -----
1150        (omitted due to with_file_stream_events(false))
1151        ");
1152
1153        Ok(())
1154    }
1155
1156    /// Verifies that an empty sibling can immediately steal shared files when
1157    /// it is polled before the stream that originally owned them.
1158    #[tokio::test]
1159    async fn morsel_empty_sibling_can_steal() -> Result<()> {
1160        let test = FileStreamMorselTest::new()
1161            .with_file_in_partition(
1162                PartitionId(0),
1163                MockPlanner::builder("file1.parquet")
1164                    .add_plan(MockPlanBuilder::new().with_morsel(MorselId(10), 101))
1165                    .return_none(),
1166            )
1167            .with_file_in_partition(
1168                PartitionId(0),
1169                MockPlanner::builder("file2.parquet")
1170                    .add_plan(MockPlanBuilder::new().with_morsel(MorselId(11), 102))
1171                    .return_none(),
1172            )
1173            // Poll the empty sibling first so it steals both files.
1174            .with_reads(vec![PartitionId(1), PartitionId(1), PartitionId(1)])
1175            .with_file_stream_events(false);
1176
1177        insta::assert_snapshot!(test.run().await.unwrap(), @r"
1178        ----- Partition 0 -----
1179        Done
1180        ----- Partition 1 -----
1181        Batch: 101
1182        Batch: 102
1183        Done
1184        ----- File Stream Events -----
1185        (omitted due to with_file_stream_events(false))
1186        ");
1187
1188        Ok(())
1189    }
1190
1191    /// Ensures that if a sibling is built and polled
1192    /// before another sibling has been built and contributed its files to the
1193    /// shared queue, the first sibling does not finish prematurely.
1194    #[tokio::test]
1195    async fn morsel_empty_sibling_can_finish_before_shared_work_exists() -> Result<()> {
1196        let test = FileStreamMorselTest::new()
1197            .with_file_in_partition(
1198                PartitionId(0),
1199                MockPlanner::builder("file1.parquet")
1200                    .add_plan(MockPlanBuilder::new().with_morsel(MorselId(10), 101))
1201                    .return_none(),
1202            )
1203            .with_file_in_partition(
1204                PartitionId(0),
1205                MockPlanner::builder("file2.parquet")
1206                    .add_plan(MockPlanBuilder::new().with_morsel(MorselId(11), 102))
1207                    .return_none(),
1208            )
1209            // Build streams lazily so partition 1 can poll the shared queue
1210            // before partition 0 has contributed its files. Once partition 0
1211            // is built, a later poll of partition 1 can still steal one of
1212            // them from the shared queue.
1213            .with_build_streams_on_first_read(true)
1214            .with_reads(vec![PartitionId(1), PartitionId(0), PartitionId(1)])
1215            .with_file_stream_events(false);
1216
1217        // Partition 1 polls too early once, then later steals one file after
1218        // partition 0 has populated the shared queue.
1219        insta::assert_snapshot!(test.run().await.unwrap(), @r"
1220        ----- Partition 0 -----
1221        Batch: 102
1222        Done
1223        ----- Partition 1 -----
1224        Batch: 101
1225        Done
1226        ----- File Stream Events -----
1227        (omitted due to with_file_stream_events(false))
1228        ");
1229
1230        Ok(())
1231    }
1232
1233    /// Verifies that a sibling hitting its limit does not count shared files
1234    /// left in the queue as already processed by that stream.
1235    #[tokio::test]
1236    async fn morsel_shared_limit_does_not_double_count_files_processed() -> Result<()> {
1237        let test = two_partition_morsel_test();
1238        let unlimited_config = test.test_config();
1239        let limited_config = test.clone().with_limit(1).test_config();
1240        let shared_work_source = limited_config
1241            .create_sibling_state(&ConfigOptions::default())
1242            .and_then(|state| state.as_ref().downcast_ref::<SharedWorkSource>().cloned())
1243            .expect("shared work source");
1244        let limited_metrics = ExecutionPlanMetricsSet::new();
1245        let unlimited_metrics = ExecutionPlanMetricsSet::new();
1246
1247        let limited_stream = FileStreamBuilder::new(&limited_config)
1248            .with_partition(1)
1249            .with_shared_work_source(Some(shared_work_source.clone()))
1250            .with_morselizer(Box::new(test.morselizer.clone()))
1251            .with_metrics(&limited_metrics)
1252            .build()?;
1253
1254        let unlimited_stream = FileStreamBuilder::new(&unlimited_config)
1255            .with_partition(0)
1256            .with_shared_work_source(Some(shared_work_source))
1257            .with_morselizer(Box::new(test.morselizer))
1258            .with_metrics(&unlimited_metrics)
1259            .build()?;
1260
1261        let limited_output = drain_stream_output(limited_stream).await?;
1262        let unlimited_output = drain_stream_output(unlimited_stream).await?;
1263
1264        insta::assert_snapshot!(format!(
1265            "----- Limited Stream -----\n{limited_output}\n----- Unlimited Stream -----\n{unlimited_output}"
1266        ), @r"
1267        ----- Limited Stream -----
1268        Batch: 101
1269        ----- Unlimited Stream -----
1270        Batch: 102
1271        Batch: 103
1272        Batch: 201
1273        ");
1274
1275        assert_eq!(
1276            metric_count(&limited_metrics, "files_opened"),
1277            1,
1278            "the limited stream should only open the file that produced its output"
1279        );
1280        assert_eq!(
1281            metric_count(&limited_metrics, "files_processed"),
1282            1,
1283            "the limited stream should only mark its own file as processed"
1284        );
1285        assert_eq!(
1286            metric_count(&unlimited_metrics, "files_opened"),
1287            3,
1288            "the draining stream should open the remaining shared files"
1289        );
1290        assert_eq!(
1291            metric_count(&unlimited_metrics, "files_processed"),
1292            3,
1293            "the draining stream should process exactly the files it opened"
1294        );
1295
1296        Ok(())
1297    }
1298
1299    /// Verifies that one fast sibling can drain shared files that originated
1300    /// in more than one other partition.
1301    #[tokio::test]
1302    async fn morsel_one_sibling_can_drain_multiple_siblings() -> Result<()> {
1303        let test = FileStreamMorselTest::new()
1304            .with_file_in_partition(
1305                PartitionId(0),
1306                MockPlanner::builder("file1.parquet")
1307                    .add_plan(MockPlanBuilder::new().with_morsel(MorselId(10), 101))
1308                    .return_none(),
1309            )
1310            // Partition 1 has two files
1311            .with_file_in_partition(
1312                PartitionId(1),
1313                MockPlanner::builder("file2.parquet")
1314                    .add_plan(MockPlanBuilder::new().with_morsel(MorselId(11), 102))
1315                    .return_none(),
1316            )
1317            .with_file_in_partition(
1318                PartitionId(1),
1319                MockPlanner::builder("file3.parquet")
1320                    .add_plan(MockPlanBuilder::new().with_morsel(MorselId(12), 103))
1321                    .return_none(),
1322            )
1323            // Partition 2 starts empty but is polled first, so it should drain
1324            // the shared queue across both sibling partitions.
1325            .with_reads(vec![
1326                PartitionId(2),
1327                PartitionId(2),
1328                PartitionId(1),
1329                PartitionId(2),
1330            ])
1331            .with_file_stream_events(false);
1332
1333        insta::assert_snapshot!(test.run().await.unwrap(), @r"
1334        ----- Partition 0 -----
1335        Done
1336        ----- Partition 1 -----
1337        Batch: 103
1338        Done
1339        ----- Partition 2 -----
1340        Batch: 101
1341        Batch: 102
1342        Done
1343        ----- File Stream Events -----
1344        (omitted due to with_file_stream_events(false))
1345        ");
1346
1347        Ok(())
1348    }
1349
1350    /// Tests how one or more `FileStream`s consume morselized file work.
1351    #[derive(Clone)]
1352    struct FileStreamMorselTest {
1353        morselizer: MockMorselizer,
1354        partition_files: BTreeMap<PartitionId, Vec<String>>,
1355        preserve_order: bool,
1356        declared_output_partitioning: bool,
1357        enable_file_stream_work_stealing: bool,
1358        file_stream_events: bool,
1359        build_streams_on_first_read: bool,
1360        reads: Vec<PartitionId>,
1361        limit: Option<usize>,
1362    }
1363
1364    impl FileStreamMorselTest {
1365        /// Creates an empty test harness.
1366        fn new() -> Self {
1367            Self {
1368                morselizer: MockMorselizer::new(),
1369                partition_files: BTreeMap::new(),
1370                preserve_order: false,
1371                declared_output_partitioning: false,
1372                enable_file_stream_work_stealing: true,
1373                file_stream_events: true,
1374                build_streams_on_first_read: false,
1375                reads: vec![],
1376                limit: None,
1377            }
1378        }
1379
1380        /// Adds one file and its root planner to partition 0.
1381        fn with_file(self, planner: impl Into<MockPlanner>) -> Self {
1382            self.with_file_in_partition(PartitionId(0), planner)
1383        }
1384
1385        /// Adds one file and its root planner to the specified input partition.
1386        fn with_file_in_partition(
1387            mut self,
1388            partition: PartitionId,
1389            planner: impl Into<MockPlanner>,
1390        ) -> Self {
1391            let planner = planner.into();
1392            let file_path = planner.file_path().to_string();
1393            self.morselizer = self.morselizer.with_planner(planner);
1394            self.partition_files
1395                .entry(partition)
1396                .or_default()
1397                .push(file_path);
1398            self
1399        }
1400
1401        /// Marks the stream (and all partitions) to preserve the specified file
1402        /// order.
1403        fn with_preserve_order(mut self, preserve_order: bool) -> Self {
1404            self.preserve_order = preserve_order;
1405            self
1406        }
1407
1408        /// Declares the test scan's output partitioning, which should force
1409        /// each stream to keep its own files local.
1410        fn with_declared_output_partitioning(
1411            mut self,
1412            declared_output_partitioning: bool,
1413        ) -> Self {
1414            self.declared_output_partitioning = declared_output_partitioning;
1415            self
1416        }
1417
1418        /// Sets `datafusion.execution.enable_file_stream_work_stealing`. When
1419        /// disabled, each stream keeps its own files local instead of sharing a
1420        /// work queue with its siblings.
1421        fn with_enable_file_stream_work_stealing(mut self, enable: bool) -> Self {
1422            self.enable_file_stream_work_stealing = enable;
1423            self
1424        }
1425
1426        /// Controls whether scheduler events are included in the snapshot.
1427        ///
1428        /// When disabled, `run()` still includes the event section header but
1429        /// replaces the trace with a fixed placeholder so tests can focus only
1430        /// on the output batches.
1431        fn with_file_stream_events(mut self, file_stream_events: bool) -> Self {
1432            self.file_stream_events = file_stream_events;
1433            self
1434        }
1435
1436        /// Controls whether streams are all built up front or lazily on their
1437        /// first read.
1438        ///
1439        /// The default builds all streams before polling begins, which matches
1440        /// normal execution. Tests may enable lazy creation to model races
1441        /// where one sibling polls before another has contributed its files to
1442        /// the shared queue.
1443        fn with_build_streams_on_first_read(
1444            mut self,
1445            build_streams_on_first_read: bool,
1446        ) -> Self {
1447            self.build_streams_on_first_read = build_streams_on_first_read;
1448            self
1449        }
1450
1451        /// Sets the partition polling order.
1452        ///
1453        /// `run()` polls these partitions in the listed order first. After
1454        /// those explicit reads are exhausted, it completes to round
1455        /// robin across all configured partitions, skipping any streams that
1456        /// have already finished.
1457        ///
1458        /// This allows testing early scheduling decisions explicit in a test
1459        /// while avoiding a fully scripted poll trace for the remainder.
1460        fn with_reads(mut self, reads: Vec<PartitionId>) -> Self {
1461            self.reads = reads;
1462            self
1463        }
1464
1465        /// Sets a global output limit for all streams created by this test.
1466        fn with_limit(mut self, limit: usize) -> Self {
1467            self.limit = Some(limit);
1468            self
1469        }
1470
1471        /// Runs the test and returns combined stream output and scheduler
1472        /// trace text.
1473        async fn run(self) -> Result<String> {
1474            let observer = self.morselizer.observer().clone();
1475            observer.clear();
1476
1477            let metrics_set = ExecutionPlanMetricsSet::new();
1478            let partition_count = self.num_partitions();
1479
1480            let mut partitions = (0..partition_count)
1481                .map(|_| PartitionState::new())
1482                .collect::<Vec<_>>();
1483
1484            let mut build_order = Vec::new();
1485            for partition in self.reads.iter().map(|partition| partition.0) {
1486                if !build_order.contains(&partition) {
1487                    build_order.push(partition);
1488                }
1489            }
1490            for partition in 0..partition_count {
1491                if !build_order.contains(&partition) {
1492                    build_order.push(partition);
1493                }
1494            }
1495
1496            let config = self.test_config();
1497            // `DataSourceExec::execute` creates one execution-local shared
1498            // state object via `create_sibling_state()` and then passes it
1499            // to `open_with_sibling_state(...)`. These tests build
1500            // `FileStream`s directly, bypassing `DataSourceExec`, so they must
1501            // perform the same setup explicitly when exercising sibling-stream
1502            // work stealing.
1503            let mut options = ConfigOptions::default();
1504            options.execution.enable_file_stream_work_stealing =
1505                self.enable_file_stream_work_stealing;
1506            let shared_work_source =
1507                config.create_sibling_state(&options).and_then(|state| {
1508                    state.as_ref().downcast_ref::<SharedWorkSource>().cloned()
1509                });
1510            if !self.build_streams_on_first_read {
1511                for partition in build_order {
1512                    let stream = FileStreamBuilder::new(&config)
1513                        .with_partition(partition)
1514                        .with_shared_work_source(shared_work_source.clone())
1515                        .with_morselizer(Box::new(self.morselizer.clone()))
1516                        .with_metrics(&metrics_set)
1517                        .build()?;
1518                    partitions[partition].set_stream(stream);
1519                }
1520            }
1521
1522            let mut initial_reads: VecDeque<_> = self.reads.into();
1523            let mut next_round_robin = 0;
1524
1525            while !initial_reads.is_empty()
1526                || partitions.iter().any(PartitionState::is_active)
1527            {
1528                let partition = if let Some(partition) = initial_reads.pop_front() {
1529                    partition.0
1530                } else {
1531                    let partition = next_round_robin;
1532                    next_round_robin = (next_round_robin + 1) % partition_count.max(1);
1533                    partition
1534                };
1535
1536                let partition_state = &mut partitions[partition];
1537
1538                if self.build_streams_on_first_read && !partition_state.built {
1539                    let stream = FileStreamBuilder::new(&config)
1540                        .with_partition(partition)
1541                        .with_shared_work_source(shared_work_source.clone())
1542                        .with_morselizer(Box::new(self.morselizer.clone()))
1543                        .with_metrics(&metrics_set)
1544                        .build()?;
1545                    partition_state.set_stream(stream);
1546                }
1547
1548                let Some(stream) = partition_state.stream.as_mut() else {
1549                    continue;
1550                };
1551
1552                match stream.next().await {
1553                    Some(result) => partition_state.push_output(format_result(result)),
1554                    None => partition_state.finish(),
1555                }
1556            }
1557
1558            let output_text = if partition_count == 1 {
1559                format!(
1560                    "----- Output Stream -----\n{}",
1561                    partitions[0].output.join("\n")
1562                )
1563            } else {
1564                partitions
1565                    .into_iter()
1566                    .enumerate()
1567                    .map(|(partition, state)| {
1568                        format!(
1569                            "----- Partition {} -----\n{}",
1570                            partition,
1571                            state.output.join("\n")
1572                        )
1573                    })
1574                    .collect::<Vec<_>>()
1575                    .join("\n")
1576            };
1577
1578            let file_stream_events = if self.file_stream_events {
1579                observer.format_events()
1580            } else {
1581                "(omitted due to with_file_stream_events(false))".to_string()
1582            };
1583
1584            Ok(format!(
1585                "{output_text}\n----- File Stream Events -----\n{file_stream_events}",
1586            ))
1587        }
1588
1589        /// Returns the number of configured partitions, including empty ones
1590        /// that appear only in the explicit read schedule.
1591        fn num_partitions(&self) -> usize {
1592            self.partition_files
1593                .keys()
1594                .map(|partition| partition.0 + 1)
1595                .chain(self.reads.iter().map(|partition| partition.0 + 1))
1596                .max()
1597                .unwrap_or(1)
1598        }
1599
1600        /// Builds a `FileScanConfig` covering every configured partition.
1601        fn test_config(&self) -> FileScanConfig {
1602            let file_groups = (0..self.num_partitions())
1603                .map(|partition| {
1604                    self.partition_files
1605                        .get(&PartitionId(partition))
1606                        .into_iter()
1607                        .flat_map(|files| files.iter())
1608                        .map(|name| PartitionedFile::new(name, 10))
1609                        .collect::<Vec<_>>()
1610                        .into()
1611                })
1612                .collect::<Vec<_>>();
1613
1614            let table_schema =
1615                TableSchema::from(Arc::new(Schema::new(vec![Field::new(
1616                    "i",
1617                    DataType::Int32,
1618                    false,
1619                )])));
1620            // Declaring an output partitioning marks the scan as pre-grouped, which
1621            // keeps each stream's files local (disables shared work stealing).
1622            let output_partitioning = self.declared_output_partitioning.then(|| {
1623                datafusion_physical_expr::Partitioning::Hash(
1624                    vec![Arc::new(
1625                        datafusion_physical_expr::expressions::Column::new("i", 0),
1626                    )],
1627                    file_groups.len(),
1628                )
1629            });
1630            FileScanConfigBuilder::new(
1631                ObjectStoreUrl::parse("test:///").unwrap(),
1632                Arc::new(MockSource::new(table_schema)),
1633            )
1634            .with_file_groups(file_groups)
1635            .with_limit(self.limit)
1636            .with_preserve_order(self.preserve_order)
1637            .with_output_partitioning(output_partitioning)
1638            .build()
1639        }
1640    }
1641
1642    /// Formats one stream poll result into a stable snapshot line.
1643    fn format_result(result: Result<RecordBatch>) -> String {
1644        match result {
1645            Ok(batch) => {
1646                let col = batch.column(0).as_primitive::<Int32Type>();
1647                let batch_id = col.value(0);
1648                format!("Batch: {batch_id}")
1649            }
1650            Err(e) => {
1651                // Pull the actual message for external errors rather than
1652                // relying on DataFusionError formatting, which changes if
1653                // backtraces are enabled, etc.
1654                let message = if let DataFusionError::External(generic) = e {
1655                    generic.to_string()
1656                } else {
1657                    e.to_string()
1658                };
1659                format!("Error: {message}")
1660            }
1661        }
1662    }
1663
1664    async fn drain_stream_output(stream: FileStream) -> Result<String> {
1665        let output = stream
1666            .collect::<Vec<_>>()
1667            .await
1668            .into_iter()
1669            .map(|result| result.map(|batch| format_result(Ok(batch))))
1670            .collect::<Result<Vec<_>>>()?;
1671        Ok(output.join("\n"))
1672    }
1673
1674    fn metric_count(metrics: &ExecutionPlanMetricsSet, name: &str) -> usize {
1675        metrics
1676            .clone_inner()
1677            .sum_by_name(name)
1678            .unwrap_or_else(|| panic!("missing metric: {name}"))
1679            .as_usize()
1680    }
1681
1682    /// Test-only state for one stream partition in [`FileStreamMorselTest`].
1683    struct PartitionState {
1684        /// Whether the `FileStream` for this partition has been built yet.
1685        built: bool,
1686        /// The live stream, if this partition has not finished yet.
1687        stream: Option<FileStream>,
1688        /// Snapshot lines produced by this partition.
1689        output: Vec<String>,
1690    }
1691
1692    impl PartitionState {
1693        /// Create an unbuilt partition with no output yet.
1694        fn new() -> Self {
1695            Self {
1696                built: false,
1697                stream: None,
1698                output: vec![],
1699            }
1700        }
1701
1702        /// Returns true if this partition might still produce output.
1703        fn is_active(&self) -> bool {
1704            !self.built || self.stream.is_some()
1705        }
1706
1707        /// Records that this partition's stream has been built.
1708        fn set_stream(&mut self, stream: FileStream) {
1709            self.stream = Some(stream);
1710            self.built = true;
1711        }
1712
1713        /// Records one formatted output line for this partition.
1714        fn push_output(&mut self, line: String) {
1715            self.output.push(line);
1716        }
1717
1718        /// Marks this partition as finished.
1719        fn finish(&mut self) {
1720            self.push_output("Done".to_string());
1721            self.stream = None;
1722        }
1723    }
1724}