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    MIN_COMPACTION_SPLIT_ROWS, PartitionMetrics, PartitionMetricsList, SplitRecordBatchStream,
50    compute_parallel_channel_size, scan_flat_file_ranges, scan_flat_mem_ranges,
51    should_split_flat_batches_for_merge,
52};
53use crate::read::stream::{ConvertBatchStream, ScanBatch, ScanBatchStream};
54use crate::read::{BoxedRecordBatchStream, ScannerMetrics, scan_util};
55use crate::region::options::MergeMode;
56use crate::sst::parquet::DEFAULT_READ_BATCH_SIZE;
57
58/// Scans a region and returns rows in a sorted sequence.
59///
60/// The output order is always `order by primary keys, time index` inside every
61/// [`PartitionRange`]. Each "partition" may contains many [`PartitionRange`]s.
62pub struct SeqScan {
63    /// Properties of the scanner.
64    properties: ScannerProperties,
65    /// Context of streams.
66    stream_ctx: Arc<StreamContext>,
67    /// Shared pruner for file range building.
68    pruner: Arc<Pruner>,
69    /// Metrics for each partition.
70    /// The scanner only sets in query and keeps it empty during compaction.
71    metrics_list: PartitionMetricsList,
72}
73
74impl SeqScan {
75    /// Creates a new [SeqScan] with the given input.
76    /// If `input.compaction` is true, the scanner will not attempt to split ranges.
77    pub(crate) fn new(input: ScanInput) -> Self {
78        let mut properties = ScannerProperties::default()
79            .with_append_mode(input.append_mode)
80            .with_total_rows(input.total_rows())
81            .with_total_rows_is_exact(input.append_mode && input.total_rows_is_exact());
82        if let Some(counters) = input.query_stat_counters.clone() {
83            properties.set_query_stat_counters(counters);
84        }
85        let stream_ctx = Arc::new(StreamContext::seq_scan_ctx(input));
86        properties.partitions = vec![stream_ctx.partition_ranges()];
87
88        // Create the shared pruner with number of workers equal to CPU cores.
89        let num_workers = common_stat::get_total_cpu_cores().max(1);
90        let pruner = Arc::new(Pruner::new(stream_ctx.clone(), num_workers));
91
92        Self {
93            properties,
94            stream_ctx,
95            pruner,
96            metrics_list: PartitionMetricsList::default(),
97        }
98    }
99
100    /// Builds a stream for the query.
101    ///
102    /// The returned stream is not partitioned and will contains all the data. If want
103    /// partitioned scan, use [`RegionScanner::scan_partition`].
104    #[tracing::instrument(
105        skip_all,
106        fields(region_id = %self.stream_ctx.input.mapper.metadata().region_id)
107    )]
108    pub fn build_stream(&self) -> Result<SendableRecordBatchStream, BoxedError> {
109        let metrics_set = ExecutionPlanMetricsSet::new();
110        let ctx = QueryScanContext::default();
111        let streams = (0..self.properties.partitions.len())
112            .map(|partition: usize| self.scan_partition(&ctx, &metrics_set, partition))
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        if self.stream_ctx.input.uses_scan_memory_limit() {
509            return Ok(());
510        }
511        // Check max file count limit for all partitions since we scan them in parallel.
512        let total_max_files: usize = self
513            .properties
514            .partitions
515            .iter()
516            .map(|partition| Self::max_files_in_partition(&self.stream_ctx.ranges, partition))
517            .sum();
518
519        let max_concurrent_files = self.stream_ctx.input.max_concurrent_scan_files;
520        if total_max_files > max_concurrent_files {
521            return TooManyFilesToReadSnafu {
522                actual: total_max_files,
523                max: max_concurrent_files,
524            }
525            .fail();
526        }
527
528        Ok(())
529    }
530}
531
532impl RegionScanner for SeqScan {
533    fn name(&self) -> &str {
534        "SeqScan"
535    }
536
537    fn properties(&self) -> &ScannerProperties {
538        &self.properties
539    }
540
541    fn schema(&self) -> SchemaRef {
542        self.stream_ctx.input.mapper.output_schema()
543    }
544
545    fn metadata(&self) -> RegionMetadataRef {
546        self.stream_ctx.input.mapper.metadata().clone()
547    }
548
549    fn scan_partition(
550        &self,
551        ctx: &QueryScanContext,
552        metrics_set: &ExecutionPlanMetricsSet,
553        partition: usize,
554    ) -> Result<SendableRecordBatchStream, BoxedError> {
555        self.scan_partition_impl(ctx, metrics_set, partition)
556            .map_err(BoxedError::new)
557    }
558
559    fn prepare(&mut self, request: PrepareRequest) -> Result<(), BoxedError> {
560        self.properties.prepare(request);
561
562        self.check_scan_limit().map_err(BoxedError::new)?;
563
564        Ok(())
565    }
566
567    fn has_predicate_without_region(&self) -> bool {
568        let predicate = self
569            .stream_ctx
570            .input
571            .predicate_group()
572            .predicate_without_region();
573        predicate.is_some()
574    }
575
576    fn add_dyn_filter_to_predicate(
577        &mut self,
578        filter_exprs: Vec<Arc<dyn datafusion::physical_plan::PhysicalExpr>>,
579    ) -> Vec<bool> {
580        self.stream_ctx.add_dyn_filter_to_predicate(filter_exprs)
581    }
582
583    fn reset_state(&mut self) {
584        self.stream_ctx.input.predicate.clear_dyn_filters();
585        let num_workers = common_stat::get_total_cpu_cores().max(1);
586        self.pruner = Arc::new(Pruner::new(self.stream_ctx.clone(), num_workers));
587        self.metrics_list = PartitionMetricsList::default();
588    }
589
590    fn set_logical_region(&mut self, logical_region: bool) {
591        self.properties.set_logical_region(logical_region);
592    }
593
594    fn set_query_load_region_id(&mut self, region_id: store_api::storage::RegionId) {
595        self.properties.set_query_load_region_id(region_id);
596    }
597
598    fn snapshot_sequence(&self) -> Option<u64> {
599        self.stream_ctx.input.snapshot_sequence
600    }
601}
602
603impl DisplayAs for SeqScan {
604    fn fmt_as(&self, t: DisplayFormatType, f: &mut fmt::Formatter) -> fmt::Result {
605        write!(
606            f,
607            "SeqScan: region={}, ",
608            self.stream_ctx.input.mapper.metadata().region_id
609        )?;
610        match t {
611            // TODO(LFC): Implement all the "TreeRender" display format.
612            DisplayFormatType::Default | DisplayFormatType::TreeRender => {
613                self.stream_ctx.format_for_explain(false, f)
614            }
615            DisplayFormatType::Verbose => {
616                self.stream_ctx.format_for_explain(true, f)?;
617                self.metrics_list.format_verbose_metrics(f)
618            }
619        }
620    }
621}
622
623impl fmt::Debug for SeqScan {
624    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
625        f.debug_struct("SeqScan")
626            .field("num_ranges", &self.stream_ctx.ranges.len())
627            .finish()
628    }
629}
630
631/// Builds flat sources for the partition range and push them to the `sources` vector.
632/// Returns the estimated rows per batch after splitting if splitting is applied, or `None`.
633pub(crate) async fn build_flat_sources(
634    stream_ctx: &Arc<StreamContext>,
635    part_range: &PartitionRange,
636    compaction: bool,
637    part_metrics: &PartitionMetrics,
638    partition_pruner: Arc<PartitionPruner>,
639    sources: &mut Vec<BoxedRecordBatchStream>,
640    semaphore: Option<Arc<Semaphore>>,
641) -> Result<Option<usize>> {
642    // Gets range meta.
643    let range_meta = &stream_ctx.ranges[part_range.identifier];
644    #[cfg(debug_assertions)]
645    if compaction {
646        // Compaction expects input sources are not been split.
647        debug_assert_eq!(range_meta.indices.len(), range_meta.row_group_indices.len());
648        for (i, row_group_idx) in range_meta.row_group_indices.iter().enumerate() {
649            // It should scan all row groups.
650            debug_assert_eq!(
651                -1, row_group_idx.row_group_index,
652                "Expect {} range scan all row groups, given: {}",
653                i, row_group_idx.row_group_index,
654            );
655        }
656    }
657
658    let read_type = if compaction {
659        "compaction"
660    } else {
661        "seq_scan_files"
662    };
663    let num_indices = range_meta.row_group_indices.len();
664    if num_indices == 0 {
665        return Ok(None);
666    }
667
668    sources.reserve(num_indices);
669    let mut ordered_sources = Vec::with_capacity(num_indices);
670    ordered_sources.resize_with(num_indices, || None);
671    let mut file_scan_tasks = Vec::new();
672    let pre_filter_mode = stream_ctx.range_pre_filter_mode(part_range);
673
674    for (position, index) in range_meta.row_group_indices.iter().enumerate() {
675        if stream_ctx.is_mem_range_index(*index) {
676            let stream = scan_flat_mem_ranges(
677                stream_ctx.clone(),
678                part_metrics.clone(),
679                *index,
680                range_meta.time_range,
681            );
682            ordered_sources[position] = Some(Box::pin(stream) as _);
683        } else if stream_ctx.is_file_range_index(*index) {
684            // Common manifest-level fast-skip shared by SeqScan and UnorderedScan.
685            // Compaction should keep reading its selected input ranges completely.
686            if !compaction
687                && partition_pruner.try_skip_manifest_pruned_file_range(*index, part_metrics)
688            {
689                continue;
690            }
691            if let Some(semaphore_ref) = semaphore.as_ref() {
692                // run in parallel, controlled by semaphore
693                let stream_ctx = stream_ctx.clone();
694                let part_metrics = part_metrics.clone();
695                let partition_pruner = partition_pruner.clone();
696                let semaphore = Arc::clone(semaphore_ref);
697                let row_group_index = *index;
698                file_scan_tasks.push(async move {
699                    let _permit = semaphore.acquire().await.unwrap();
700                    let stream = scan_flat_file_ranges(
701                        stream_ctx,
702                        part_metrics,
703                        row_group_index,
704                        read_type,
705                        partition_pruner,
706                    )
707                    .await?;
708                    Ok((position, Box::pin(stream) as _))
709                });
710            } else {
711                // no semaphore, run sequentially
712                let stream = scan_flat_file_ranges(
713                    stream_ctx.clone(),
714                    part_metrics.clone(),
715                    *index,
716                    read_type,
717                    partition_pruner.clone(),
718                )
719                .await?;
720                ordered_sources[position] = Some(Box::pin(stream) as _);
721            }
722        } else {
723            let stream = scan_util::maybe_scan_flat_other_ranges(
724                stream_ctx,
725                *index,
726                part_metrics,
727                pre_filter_mode,
728            )
729            .await?;
730            ordered_sources[position] = Some(stream);
731        }
732    }
733
734    if !file_scan_tasks.is_empty() {
735        let results = futures::future::try_join_all(file_scan_tasks).await?;
736        for (position, stream) in results {
737            ordered_sources[position] = Some(stream);
738        }
739    }
740
741    // Queries merge one range at a time; compaction merges sources from all ranges.
742    let needs_merge =
743        ordered_sources.iter().flatten().count() > 1 || (compaction && stream_ctx.ranges.len() > 1);
744    let split_batch_size = if needs_merge {
745        should_split_flat_batches_for_merge(stream_ctx, range_meta).filter(|rows_per_series| {
746            // Compaction writes every merged batch out, so splitting short series
747            // would hand the SST writer and indexer one tiny batch per series.
748            !compaction || *rows_per_series >= MIN_COMPACTION_SPLIT_ROWS
749        })
750    } else {
751        None
752    };
753    let should_split = split_batch_size.is_some();
754
755    for stream in ordered_sources.into_iter().flatten() {
756        if should_split {
757            sources.push(Box::pin(SplitRecordBatchStream::new(stream)));
758        } else {
759            sources.push(stream);
760        }
761    }
762
763    if should_split {
764        common_telemetry::debug!(
765            "Splitting record batches, region: {}, sources: {}, part_range: {:?}",
766            stream_ctx.input.region_metadata().region_id,
767            sources.len(),
768            part_range,
769        );
770    }
771
772    Ok(split_batch_size)
773}
774
775#[cfg(test)]
776impl SeqScan {
777    /// Returns the input.
778    pub(crate) fn input(&self) -> &ScanInput {
779        &self.stream_ctx.input
780    }
781}
782
783/// Returns the scanner type.
784fn get_scanner_type(compaction: bool) -> &'static str {
785    if compaction {
786        "SeqScan(compaction)"
787    } else {
788        "SeqScan"
789    }
790}