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