Skip to main content

mito2/read/
seq_scan.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Sequential scan.
16
17use std::fmt;
18use std::sync::Arc;
19use std::time::Instant;
20
21use async_stream::try_stream;
22use common_error::ext::BoxedError;
23use common_recordbatch::util::ChainedRecordBatchStream;
24use common_recordbatch::{RecordBatchStreamWrapper, SendableRecordBatchStream};
25use common_telemetry::tracing;
26use datafusion::physical_plan::metrics::ExecutionPlanMetricsSet;
27use datafusion::physical_plan::{DisplayAs, DisplayFormatType};
28use datatypes::schema::SchemaRef;
29use futures::{StreamExt, TryStreamExt};
30use snafu::ensure;
31use store_api::metadata::RegionMetadataRef;
32use store_api::region_engine::{
33    PartitionRange, PrepareRequest, QueryScanContext, RegionScanner, ScannerProperties,
34};
35use store_api::storage::TimeSeriesRowSelector;
36use tokio::sync::Semaphore;
37
38use crate::error::{PartitionOutOfRangeSnafu, Result, TooManyFilesToReadSnafu};
39use crate::read::flat_dedup::{FlatDedupReader, FlatLastNonNull, FlatLastRow};
40use crate::read::flat_merge::FlatMergeReader;
41use crate::read::last_row::FlatLastRowReader;
42use crate::read::pruner::{PartitionPruner, Pruner};
43use crate::read::range::RangeMeta;
44use crate::read::range_cache::{
45    build_range_cache_key, cache_flat_range_stream, cached_flat_range_stream,
46};
47use crate::read::scan_region::{ScanInput, StreamContext};
48use crate::read::scan_util::{
49    PartitionMetrics, PartitionMetricsList, SplitRecordBatchStream, compute_parallel_channel_size,
50    scan_flat_file_ranges, scan_flat_mem_ranges, should_split_flat_batches_for_merge,
51};
52use crate::read::stream::{ConvertBatchStream, ScanBatch, ScanBatchStream};
53use crate::read::{BoxedRecordBatchStream, ScannerMetrics, scan_util};
54use crate::region::options::MergeMode;
55use crate::sst::parquet::DEFAULT_READ_BATCH_SIZE;
56
57/// Scans a region and returns rows in a sorted sequence.
58///
59/// The output order is always `order by primary keys, time index` inside every
60/// [`PartitionRange`]. Each "partition" may contains many [`PartitionRange`]s.
61pub struct SeqScan {
62    /// Properties of the scanner.
63    properties: ScannerProperties,
64    /// Context of streams.
65    stream_ctx: Arc<StreamContext>,
66    /// Shared pruner for file range building.
67    pruner: Arc<Pruner>,
68    /// Metrics for each partition.
69    /// The scanner only sets in query and keeps it empty during compaction.
70    metrics_list: PartitionMetricsList,
71}
72
73impl SeqScan {
74    /// Creates a new [SeqScan] with the given input.
75    /// If `input.compaction` is true, the scanner will not attempt to split ranges.
76    pub(crate) fn new(input: ScanInput) -> Self {
77        let mut properties = ScannerProperties::default()
78            .with_append_mode(input.append_mode)
79            .with_total_rows(input.total_rows())
80            .with_total_rows_is_exact(input.append_mode && input.total_rows_is_exact());
81        if let Some(counters) = input.query_stat_counters.clone() {
82            properties.set_query_stat_counters(counters);
83        }
84        let stream_ctx = Arc::new(StreamContext::seq_scan_ctx(input));
85        properties.partitions = vec![stream_ctx.partition_ranges()];
86
87        // Create the shared pruner with number of workers equal to CPU cores.
88        let num_workers = common_stat::get_total_cpu_cores().max(1);
89        let pruner = Arc::new(Pruner::new(stream_ctx.clone(), num_workers));
90
91        Self {
92            properties,
93            stream_ctx,
94            pruner,
95            metrics_list: PartitionMetricsList::default(),
96        }
97    }
98
99    /// Builds a stream for the query.
100    ///
101    /// The returned stream is not partitioned and will contains all the data. If want
102    /// partitioned scan, use [`RegionScanner::scan_partition`].
103    #[tracing::instrument(
104        skip_all,
105        fields(region_id = %self.stream_ctx.input.mapper.metadata().region_id)
106    )]
107    pub fn build_stream(&self) -> Result<SendableRecordBatchStream, BoxedError> {
108        let metrics_set = ExecutionPlanMetricsSet::new();
109        let streams = (0..self.properties.partitions.len())
110            .map(|partition: usize| {
111                self.scan_partition(&QueryScanContext::default(), &metrics_set, partition)
112            })
113            .collect::<Result<Vec<_>, _>>()?;
114
115        let aggr_stream = ChainedRecordBatchStream::new(streams).map_err(BoxedError::new)?;
116        Ok(Box::pin(aggr_stream))
117    }
118
119    /// Scan [`Batch`] in all partitions one by one.
120    pub(crate) fn scan_all_partitions(&self) -> Result<ScanBatchStream> {
121        let metrics_set = ExecutionPlanMetricsSet::new();
122
123        let streams = (0..self.properties.partitions.len())
124            .map(|partition| {
125                let metrics = self.new_partition_metrics(false, &metrics_set, partition);
126                self.scan_flat_batch_in_partition(partition, metrics)
127            })
128            .collect::<Result<Vec<_>>>()?;
129
130        Ok(Box::pin(futures::stream::iter(streams).flatten()))
131    }
132
133    /// Builds a [BoxedRecordBatchStream] from sequential scan for flat format compaction.
134    ///
135    /// # Panics
136    /// Panics if the compaction flag is not set.
137    pub(crate) async fn build_flat_reader_for_compaction(&self) -> Result<BoxedRecordBatchStream> {
138        assert!(self.stream_ctx.input.compaction);
139
140        let metrics_set = ExecutionPlanMetricsSet::new();
141        let part_metrics = self.new_partition_metrics(false, &metrics_set, 0);
142        debug_assert_eq!(1, self.properties.partitions.len());
143        let partition_ranges = &self.properties.partitions[0];
144
145        let reader = Self::merge_all_flat_ranges_for_compaction(
146            &self.stream_ctx,
147            partition_ranges,
148            &part_metrics,
149            self.pruner.clone(),
150        )
151        .await?;
152        Ok(reader)
153    }
154
155    /// Builds a merge reader that reads all flat ranges.
156    /// Callers MUST not split ranges before calling this method.
157    async fn merge_all_flat_ranges_for_compaction(
158        stream_ctx: &Arc<StreamContext>,
159        partition_ranges: &[PartitionRange],
160        part_metrics: &PartitionMetrics,
161        pruner: Arc<Pruner>,
162    ) -> Result<BoxedRecordBatchStream> {
163        pruner.add_partition_ranges(partition_ranges);
164        let partition_pruner = Arc::new(PartitionPruner::new(pruner, partition_ranges));
165
166        let mut sources = Vec::new();
167        for part_range in partition_ranges {
168            build_flat_sources(
169                stream_ctx,
170                part_range,
171                true,
172                part_metrics,
173                partition_pruner.clone(),
174                &mut sources,
175                None,
176            )
177            .await?;
178        }
179
180        common_telemetry::debug!(
181            "Build flat reader to read all parts, region_id: {}, num_part_ranges: {}, num_sources: {}",
182            stream_ctx.input.mapper.metadata().region_id,
183            partition_ranges.len(),
184            sources.len()
185        );
186        Self::build_flat_reader_from_sources(
187            stream_ctx,
188            sources,
189            None,
190            None,
191            false,
192            compute_parallel_channel_size(DEFAULT_READ_BATCH_SIZE),
193        )
194        .await
195    }
196
197    /// Builds a flat reader to read sources that returns RecordBatch.
198    /// If `semaphore` is provided, reads sources in parallel if possible.
199    /// If `skip_dedup` is true, the merged stream is returned without applying flat dedup.
200    #[tracing::instrument(level = tracing::Level::DEBUG, skip_all)]
201    pub(crate) async fn build_flat_reader_from_sources(
202        stream_ctx: &StreamContext,
203        mut sources: Vec<BoxedRecordBatchStream>,
204        semaphore: Option<Arc<Semaphore>>,
205        part_metrics: Option<&PartitionMetrics>,
206        skip_dedup: bool,
207        channel_size: usize,
208    ) -> Result<BoxedRecordBatchStream> {
209        if let Some(semaphore) = semaphore.as_ref() {
210            // Read sources in parallel.
211            if sources.len() > 1 {
212                sources = stream_ctx.input.create_parallel_flat_sources(
213                    sources,
214                    semaphore.clone(),
215                    channel_size,
216                )?;
217            }
218        }
219
220        let mapper = &stream_ctx.input.mapper;
221        let reader: BoxedRecordBatchStream = if sources.len() == 1 {
222            // Currently, we can't skip dedup when there is only one source because
223            // that source may have duplicate rows.
224            sources.pop().unwrap()
225        } else {
226            let schema = mapper.input_arrow_schema(stream_ctx.input.compaction);
227            let metrics_reporter = part_metrics.map(|m| m.merge_metrics_reporter());
228            let reader = FlatMergeReader::new(
229                schema,
230                sources,
231                stream_ctx.input.batch_size(),
232                metrics_reporter,
233            )
234            .await?;
235            Box::pin(reader.into_stream())
236        };
237
238        let dedup = !skip_dedup && !stream_ctx.input.append_mode;
239        let dedup_metrics_reporter = part_metrics.map(|m| m.dedup_metrics_reporter());
240        let reader = if dedup {
241            match stream_ctx.input.merge_mode {
242                MergeMode::LastRow => Box::pin(
243                    FlatDedupReader::new(
244                        reader,
245                        FlatLastRow::new(stream_ctx.input.filter_deleted),
246                        dedup_metrics_reporter,
247                    )
248                    .into_stream(),
249                ) as _,
250                MergeMode::LastNonNull => Box::pin(
251                    FlatDedupReader::new(
252                        reader,
253                        FlatLastNonNull::new(
254                            mapper.field_column_start(),
255                            stream_ctx.input.filter_deleted,
256                        ),
257                        dedup_metrics_reporter,
258                    )
259                    .into_stream(),
260                ) as _,
261            }
262        } else {
263            reader
264        };
265
266        let reader = match &stream_ctx.input.series_row_selector {
267            Some(TimeSeriesRowSelector::LastRow { .. }) => {
268                Box::pin(FlatLastRowReader::new(reader).into_stream()) as _
269            }
270            None => reader,
271        };
272
273        Ok(reader)
274    }
275
276    /// Builds a flat read stream for one partition range.
277    pub(crate) async fn build_flat_partition_range_read(
278        stream_ctx: &Arc<StreamContext>,
279        part_range: &PartitionRange,
280        compaction: bool,
281        part_metrics: &PartitionMetrics,
282        partition_pruner: Arc<PartitionPruner>,
283        file_scan_semaphore: Option<Arc<Semaphore>>,
284        merge_semaphore: Option<Arc<Semaphore>>,
285    ) -> Result<(BoxedRecordBatchStream, usize)> {
286        let cache_key = build_range_cache_key(stream_ctx, part_range);
287
288        if let Some(key) = cache_key.as_ref() {
289            if let Some(value) = stream_ctx.input.cache_strategy.get_range_result(key) {
290                part_metrics.inc_range_cache_hit();
291                return Ok((cached_flat_range_stream(value), DEFAULT_READ_BATCH_SIZE));
292            }
293            part_metrics.inc_range_cache_miss();
294        }
295
296        let mut sources = Vec::new();
297        let split_batch_size = build_flat_sources(
298            stream_ctx,
299            part_range,
300            compaction,
301            part_metrics,
302            partition_pruner,
303            &mut sources,
304            file_scan_semaphore,
305        )
306        .await?;
307        let estimated_rows_per_batch = split_batch_size.unwrap_or(DEFAULT_READ_BATCH_SIZE);
308        let channel_size = compute_parallel_channel_size(estimated_rows_per_batch);
309        let stream = Self::build_flat_reader_from_sources(
310            stream_ctx,
311            sources,
312            merge_semaphore,
313            Some(part_metrics),
314            false,
315            channel_size,
316        )
317        .await?;
318
319        let stream = match cache_key {
320            Some(key) => cache_flat_range_stream(
321                stream,
322                stream_ctx.input.cache_strategy.clone(),
323                key,
324                part_metrics.clone(),
325            ),
326            None => stream,
327        };
328
329        Ok((stream, estimated_rows_per_batch))
330    }
331
332    /// Scans the given partition when the part list is set properly.
333    /// Otherwise the returned stream might not contains any data.
334    fn scan_partition_impl(
335        &self,
336        ctx: &QueryScanContext,
337        metrics_set: &ExecutionPlanMetricsSet,
338        partition: usize,
339    ) -> Result<SendableRecordBatchStream> {
340        if ctx.explain_verbose {
341            common_telemetry::info!(
342                "SeqScan partition {}, region_id: {}",
343                partition,
344                self.stream_ctx.input.region_metadata().region_id
345            );
346        }
347
348        let metrics = self.new_partition_metrics(ctx.explain_verbose, metrics_set, partition);
349        let input = &self.stream_ctx.input;
350
351        let batch_stream = self.scan_flat_batch_in_partition(partition, metrics.clone())?;
352        let record_batch_stream = ConvertBatchStream::new(
353            batch_stream,
354            input.mapper.clone(),
355            input.cache_strategy.clone(),
356            metrics,
357        );
358
359        Ok(Box::pin(RecordBatchStreamWrapper::new(
360            input.mapper.output_schema(),
361            Box::pin(record_batch_stream),
362        )))
363    }
364
365    #[tracing::instrument(
366        skip_all,
367        fields(
368            region_id = %self.stream_ctx.input.mapper.metadata().region_id,
369            partition = partition
370        )
371    )]
372    fn scan_flat_batch_in_partition(
373        &self,
374        partition: usize,
375        part_metrics: PartitionMetrics,
376    ) -> Result<ScanBatchStream> {
377        ensure!(
378            partition < self.properties.partitions.len(),
379            PartitionOutOfRangeSnafu {
380                given: partition,
381                all: self.properties.partitions.len(),
382            }
383        );
384
385        if self.properties.partitions[partition].is_empty() {
386            return Ok(Box::pin(futures::stream::empty()));
387        }
388
389        let stream_ctx = self.stream_ctx.clone();
390        let semaphore = self.new_semaphore();
391        let partition_ranges = self.properties.partitions[partition].clone();
392        let compaction = self.stream_ctx.input.compaction;
393        let file_scan_semaphore = if compaction { None } else { semaphore.clone() };
394        let pruner = self.pruner.clone();
395        // Initializes ref counts for the pruner.
396        // If we call scan_batch_in_partition() multiple times but don't read all batches from the stream,
397        // then the ref count won't be decremented.
398        // This is a rare case and keeping all remaining entries still uses less memory than a per partition cache.
399        pruner.add_partition_ranges(&partition_ranges);
400        let partition_pruner = Arc::new(PartitionPruner::new(pruner, &partition_ranges));
401
402        let stream = try_stream! {
403            part_metrics.on_first_poll();
404            // Start fetch time before building sources so scan cost contains
405            // build part cost.
406            let mut fetch_start = Instant::now();
407
408            // Scans each part.
409            for part_range in partition_ranges {
410                let (mut reader, _) = Self::build_flat_partition_range_read(
411                    &stream_ctx,
412                    &part_range,
413                    compaction,
414                    &part_metrics,
415                    partition_pruner.clone(),
416                    file_scan_semaphore.clone(),
417                    semaphore.clone(),
418                )
419                .await?;
420
421                let mut metrics = ScannerMetrics {
422                    scan_cost: fetch_start.elapsed(),
423                    ..Default::default()
424                };
425                fetch_start = Instant::now();
426
427                while let Some(record_batch) = reader.try_next().await? {
428                    metrics.scan_cost += fetch_start.elapsed();
429                    metrics.num_batches += 1;
430                    metrics.num_rows += record_batch.num_rows();
431
432                    debug_assert!(record_batch.num_rows() > 0);
433                    if record_batch.num_rows() == 0 {
434                        fetch_start = Instant::now();
435                        continue;
436                    }
437
438                    let yield_start = Instant::now();
439                    yield ScanBatch::RecordBatch(record_batch);
440                    metrics.yield_cost += yield_start.elapsed();
441
442                    fetch_start = Instant::now();
443                }
444
445                metrics.scan_cost += fetch_start.elapsed();
446                fetch_start = Instant::now();
447                part_metrics.merge_metrics(&metrics);
448            }
449
450            part_metrics.on_finish();
451        };
452        Ok(Box::pin(stream))
453    }
454
455    fn new_semaphore(&self) -> Option<Arc<Semaphore>> {
456        if self.properties.target_partitions() > self.properties.num_partitions() {
457            // We can use additional tasks to read the data if we have more target partitions than actual partitions.
458            // This semaphore is partition level.
459            // We don't use a global semaphore to avoid a partition waiting for others. The final concurrency
460            // of tasks usually won't exceed the target partitions a lot as compaction can reduce the number of
461            // files in a part range.
462            Some(Arc::new(Semaphore::new(
463                self.properties.target_partitions() - self.properties.num_partitions() + 1,
464            )))
465        } else {
466            None
467        }
468    }
469
470    /// Creates a new partition metrics instance.
471    /// Sets the partition metrics for the given partition if it is not for compaction.
472    fn new_partition_metrics(
473        &self,
474        explain_verbose: bool,
475        metrics_set: &ExecutionPlanMetricsSet,
476        partition: usize,
477    ) -> PartitionMetrics {
478        let metrics = PartitionMetrics::new(
479            self.stream_ctx.input.mapper.metadata().region_id,
480            partition,
481            get_scanner_type(self.stream_ctx.input.compaction),
482            self.stream_ctx.query_start,
483            explain_verbose,
484            metrics_set,
485        );
486
487        if !self.stream_ctx.input.compaction {
488            self.metrics_list.set(partition, metrics.clone());
489        }
490
491        metrics
492    }
493
494    /// Finds the maximum number of files to read in a single partition range.
495    fn max_files_in_partition(ranges: &[RangeMeta], partition_ranges: &[PartitionRange]) -> usize {
496        partition_ranges
497            .iter()
498            .map(|part_range| {
499                let range_meta = &ranges[part_range.identifier];
500                range_meta.indices.len()
501            })
502            .max()
503            .unwrap_or(0)
504    }
505
506    /// Checks resource limit for the scanner.
507    pub(crate) fn check_scan_limit(&self) -> Result<()> {
508        // Check max file count limit for all partitions since we scan them in parallel.
509        let total_max_files: usize = self
510            .properties
511            .partitions
512            .iter()
513            .map(|partition| Self::max_files_in_partition(&self.stream_ctx.ranges, partition))
514            .sum();
515
516        let max_concurrent_files = self.stream_ctx.input.max_concurrent_scan_files;
517        if total_max_files > max_concurrent_files {
518            return TooManyFilesToReadSnafu {
519                actual: total_max_files,
520                max: max_concurrent_files,
521            }
522            .fail();
523        }
524
525        Ok(())
526    }
527}
528
529impl RegionScanner for SeqScan {
530    fn name(&self) -> &str {
531        "SeqScan"
532    }
533
534    fn properties(&self) -> &ScannerProperties {
535        &self.properties
536    }
537
538    fn schema(&self) -> SchemaRef {
539        self.stream_ctx.input.mapper.output_schema()
540    }
541
542    fn metadata(&self) -> RegionMetadataRef {
543        self.stream_ctx.input.mapper.metadata().clone()
544    }
545
546    fn scan_partition(
547        &self,
548        ctx: &QueryScanContext,
549        metrics_set: &ExecutionPlanMetricsSet,
550        partition: usize,
551    ) -> Result<SendableRecordBatchStream, BoxedError> {
552        self.scan_partition_impl(ctx, metrics_set, partition)
553            .map_err(BoxedError::new)
554    }
555
556    fn prepare(&mut self, request: PrepareRequest) -> Result<(), BoxedError> {
557        self.properties.prepare(request);
558
559        self.check_scan_limit().map_err(BoxedError::new)?;
560
561        Ok(())
562    }
563
564    fn has_predicate_without_region(&self) -> bool {
565        let predicate = self
566            .stream_ctx
567            .input
568            .predicate_group()
569            .predicate_without_region();
570        predicate.is_some()
571    }
572
573    fn add_dyn_filter_to_predicate(
574        &mut self,
575        filter_exprs: Vec<Arc<dyn datafusion::physical_plan::PhysicalExpr>>,
576    ) -> Vec<bool> {
577        self.stream_ctx.add_dyn_filter_to_predicate(filter_exprs)
578    }
579
580    fn reset_state(&mut self) {
581        self.stream_ctx.input.predicate.clear_dyn_filters();
582        let num_workers = common_stat::get_total_cpu_cores().max(1);
583        self.pruner = Arc::new(Pruner::new(self.stream_ctx.clone(), num_workers));
584        self.metrics_list = PartitionMetricsList::default();
585    }
586
587    fn set_logical_region(&mut self, logical_region: bool) {
588        self.properties.set_logical_region(logical_region);
589    }
590
591    fn set_query_load_region_id(&mut self, region_id: store_api::storage::RegionId) {
592        self.properties.set_query_load_region_id(region_id);
593    }
594
595    fn snapshot_sequence(&self) -> Option<u64> {
596        self.stream_ctx.input.snapshot_sequence
597    }
598}
599
600impl DisplayAs for SeqScan {
601    fn fmt_as(&self, t: DisplayFormatType, f: &mut fmt::Formatter) -> fmt::Result {
602        write!(
603            f,
604            "SeqScan: region={}, ",
605            self.stream_ctx.input.mapper.metadata().region_id
606        )?;
607        match t {
608            // TODO(LFC): Implement all the "TreeRender" display format.
609            DisplayFormatType::Default | DisplayFormatType::TreeRender => {
610                self.stream_ctx.format_for_explain(false, f)
611            }
612            DisplayFormatType::Verbose => {
613                self.stream_ctx.format_for_explain(true, f)?;
614                self.metrics_list.format_verbose_metrics(f)
615            }
616        }
617    }
618}
619
620impl fmt::Debug for SeqScan {
621    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
622        f.debug_struct("SeqScan")
623            .field("num_ranges", &self.stream_ctx.ranges.len())
624            .finish()
625    }
626}
627
628/// Builds flat sources for the partition range and push them to the `sources` vector.
629/// Returns the estimated rows per batch after splitting if splitting is applied, or `None`.
630pub(crate) async fn build_flat_sources(
631    stream_ctx: &Arc<StreamContext>,
632    part_range: &PartitionRange,
633    compaction: bool,
634    part_metrics: &PartitionMetrics,
635    partition_pruner: Arc<PartitionPruner>,
636    sources: &mut Vec<BoxedRecordBatchStream>,
637    semaphore: Option<Arc<Semaphore>>,
638) -> Result<Option<usize>> {
639    // Gets range meta.
640    let range_meta = &stream_ctx.ranges[part_range.identifier];
641    #[cfg(debug_assertions)]
642    if compaction {
643        // Compaction expects input sources are not been split.
644        debug_assert_eq!(range_meta.indices.len(), range_meta.row_group_indices.len());
645        for (i, row_group_idx) in range_meta.row_group_indices.iter().enumerate() {
646            // It should scan all row groups.
647            debug_assert_eq!(
648                -1, row_group_idx.row_group_index,
649                "Expect {} range scan all row groups, given: {}",
650                i, row_group_idx.row_group_index,
651            );
652        }
653    }
654
655    let read_type = if compaction {
656        "compaction"
657    } else {
658        "seq_scan_files"
659    };
660    let num_indices = range_meta.row_group_indices.len();
661    if num_indices == 0 {
662        return Ok(None);
663    }
664
665    let split_batch_size = should_split_flat_batches_for_merge(stream_ctx, range_meta);
666    let should_split = split_batch_size.is_some();
667    sources.reserve(num_indices);
668    let mut ordered_sources = Vec::with_capacity(num_indices);
669    ordered_sources.resize_with(num_indices, || None);
670    let mut file_scan_tasks = Vec::new();
671    let pre_filter_mode = stream_ctx.range_pre_filter_mode(part_range);
672
673    for (position, index) in range_meta.row_group_indices.iter().enumerate() {
674        if stream_ctx.is_mem_range_index(*index) {
675            let stream = scan_flat_mem_ranges(
676                stream_ctx.clone(),
677                part_metrics.clone(),
678                *index,
679                range_meta.time_range,
680            );
681            ordered_sources[position] = Some(Box::pin(stream) as _);
682        } else if stream_ctx.is_file_range_index(*index) {
683            // Common manifest-level fast-skip shared by SeqScan and UnorderedScan.
684            // Compaction should keep reading its selected input ranges completely.
685            if !compaction
686                && partition_pruner.try_skip_manifest_pruned_file_range(*index, part_metrics)
687            {
688                continue;
689            }
690            if let Some(semaphore_ref) = semaphore.as_ref() {
691                // run in parallel, controlled by semaphore
692                let stream_ctx = stream_ctx.clone();
693                let part_metrics = part_metrics.clone();
694                let partition_pruner = partition_pruner.clone();
695                let semaphore = Arc::clone(semaphore_ref);
696                let row_group_index = *index;
697                file_scan_tasks.push(async move {
698                    let _permit = semaphore.acquire().await.unwrap();
699                    let stream = scan_flat_file_ranges(
700                        stream_ctx,
701                        part_metrics,
702                        row_group_index,
703                        read_type,
704                        partition_pruner,
705                    )
706                    .await?;
707                    Ok((position, Box::pin(stream) as _))
708                });
709            } else {
710                // no semaphore, run sequentially
711                let stream = scan_flat_file_ranges(
712                    stream_ctx.clone(),
713                    part_metrics.clone(),
714                    *index,
715                    read_type,
716                    partition_pruner.clone(),
717                )
718                .await?;
719                ordered_sources[position] = Some(Box::pin(stream) as _);
720            }
721        } else {
722            let stream = scan_util::maybe_scan_flat_other_ranges(
723                stream_ctx,
724                *index,
725                part_metrics,
726                pre_filter_mode,
727            )
728            .await?;
729            ordered_sources[position] = Some(stream);
730        }
731    }
732
733    if !file_scan_tasks.is_empty() {
734        let results = futures::future::try_join_all(file_scan_tasks).await?;
735        for (position, stream) in results {
736            ordered_sources[position] = Some(stream);
737        }
738    }
739
740    for stream in ordered_sources.into_iter().flatten() {
741        if should_split {
742            sources.push(Box::pin(SplitRecordBatchStream::new(stream)));
743        } else {
744            sources.push(stream);
745        }
746    }
747
748    if should_split {
749        common_telemetry::debug!(
750            "Splitting record batches, region: {}, sources: {}, part_range: {:?}",
751            stream_ctx.input.region_metadata().region_id,
752            sources.len(),
753            part_range,
754        );
755    }
756
757    Ok(split_batch_size)
758}
759
760#[cfg(test)]
761impl SeqScan {
762    /// Returns the input.
763    pub(crate) fn input(&self) -> &ScanInput {
764        &self.stream_ctx.input
765    }
766}
767
768/// Returns the scanner type.
769fn get_scanner_type(compaction: bool) -> &'static str {
770    if compaction {
771        "SeqScan(compaction)"
772    } else {
773        "SeqScan"
774    }
775}