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