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        Self::merge_flat_sources(
240            stream_ctx,
241            sources,
242            part_metrics,
243            skip_dedup,
244            stream_ctx
245                .input
246                .mapper
247                .input_arrow_schema(stream_ctx.input.compaction),
248            stream_ctx.input.mapper.field_column_start(),
249        )
250        .await
251    }
252
253    /// Merges flat batches with an explicit schema, including identity-only samples.
254    pub(crate) async fn merge_flat_sources(
255        stream_ctx: &StreamContext,
256        mut sources: Vec<BoxedRecordBatchStream>,
257        part_metrics: Option<&PartitionMetrics>,
258        skip_dedup: bool,
259        schema: datatypes::arrow::datatypes::SchemaRef,
260        field_column_start: usize,
261    ) -> Result<BoxedRecordBatchStream> {
262        let reader: BoxedRecordBatchStream = if sources.len() == 1 {
263            // Currently, we can't skip dedup when there is only one source because
264            // that source may have duplicate rows.
265            sources.pop().unwrap()
266        } else {
267            let metrics_reporter = part_metrics.map(|m| m.merge_metrics_reporter());
268            let reader = FlatMergeReader::new(
269                schema,
270                sources,
271                stream_ctx.input.batch_size(),
272                metrics_reporter,
273            )
274            .await?;
275            Box::pin(reader.into_stream())
276        };
277
278        let dedup = !skip_dedup && !stream_ctx.input.append_mode;
279        let dedup_metrics_reporter = part_metrics.map(|m| m.dedup_metrics_reporter());
280        let reader = if dedup {
281            match stream_ctx.input.merge_mode {
282                MergeMode::LastRow => Box::pin(
283                    FlatDedupReader::new(
284                        reader,
285                        FlatLastRow::new(stream_ctx.input.filter_deleted),
286                        dedup_metrics_reporter,
287                    )
288                    .into_stream(),
289                ) as _,
290                MergeMode::LastNonNull => Box::pin(
291                    FlatDedupReader::new(
292                        reader,
293                        FlatLastNonNull::new(field_column_start, stream_ctx.input.filter_deleted),
294                        dedup_metrics_reporter,
295                    )
296                    .into_stream(),
297                ) as _,
298            }
299        } else {
300            reader
301        };
302
303        let reader = match &stream_ctx.input.series_row_selector {
304            Some(TimeSeriesRowSelector::LastRow { .. }) => {
305                Box::pin(FlatLastRowReader::new(reader).into_stream()) as _
306            }
307            None => reader,
308        };
309
310        Ok(reader)
311    }
312
313    /// Builds a flat read stream for one partition range.
314    pub(crate) async fn build_flat_partition_range_read(
315        stream_ctx: &Arc<StreamContext>,
316        part_range: &PartitionRange,
317        read_mode: FlatReadMode,
318        part_metrics: &PartitionMetrics,
319        partition_pruner: Arc<PartitionPruner>,
320        file_scan_semaphore: Option<Arc<Semaphore>>,
321        merge_semaphore: Option<Arc<Semaphore>>,
322    ) -> Result<(BoxedRecordBatchStream, usize)> {
323        let cache_key =
324            build_range_cache_key(stream_ctx, part_range, Some(&partition_pruner)).map(|key| {
325                if read_mode == FlatReadMode::CrossRangeMerge {
326                    key.for_cross_range_merge()
327                } else {
328                    key
329                }
330            });
331        let ctx = stream_ctx.clone();
332        let range = *part_range;
333        let metrics = part_metrics.clone();
334        CachedRangeReader {
335            stream_ctx,
336            part_range,
337            key: cache_key,
338            metrics: part_metrics,
339        }
340        .build(move || async move {
341            Self::build_uncached_partition_range(
342                &ctx,
343                &range,
344                read_mode,
345                &metrics,
346                partition_pruner,
347                file_scan_semaphore,
348                merge_semaphore,
349            )
350            .await
351        })
352        .await
353    }
354
355    async fn build_uncached_partition_range(
356        stream_ctx: &Arc<StreamContext>,
357        part_range: &PartitionRange,
358        read_mode: FlatReadMode,
359        part_metrics: &PartitionMetrics,
360        partition_pruner: Arc<PartitionPruner>,
361        file_scan_semaphore: Option<Arc<Semaphore>>,
362        merge_semaphore: Option<Arc<Semaphore>>,
363    ) -> Result<(BoxedRecordBatchStream, usize)> {
364        let mut sources = Vec::new();
365        let split_batch_size = build_flat_sources(
366            stream_ctx,
367            part_range,
368            read_mode,
369            part_metrics,
370            partition_pruner,
371            &mut sources,
372            file_scan_semaphore,
373        )
374        .await?;
375        let estimated_rows_per_batch = split_batch_size.unwrap_or(DEFAULT_READ_BATCH_SIZE);
376        let channel_size = compute_parallel_channel_size(estimated_rows_per_batch);
377        let stream = Self::build_flat_reader_from_sources(
378            stream_ctx,
379            sources,
380            merge_semaphore,
381            Some(part_metrics),
382            false,
383            channel_size,
384        )
385        .await?;
386
387        Ok((stream, estimated_rows_per_batch))
388    }
389
390    /// Scans the given partition when the part list is set properly.
391    /// Otherwise the returned stream might not contains any data.
392    fn scan_partition_impl(
393        &self,
394        ctx: &QueryScanContext,
395        metrics_set: &ExecutionPlanMetricsSet,
396        partition: usize,
397    ) -> Result<SendableRecordBatchStream> {
398        if ctx.explain_verbose {
399            common_telemetry::info!(
400                "SeqScan partition {}, region_id: {}",
401                partition,
402                self.stream_ctx.input.region_metadata().region_id
403            );
404        }
405
406        let metrics = self.new_partition_metrics(ctx.explain_verbose, metrics_set, partition);
407        let input = &self.stream_ctx.input;
408
409        let batch_stream = self.scan_flat_batch_in_partition(partition, metrics.clone())?;
410        let record_batch_stream = ConvertBatchStream::new(
411            batch_stream,
412            input.mapper.clone(),
413            input.cache_strategy.clone(),
414            metrics,
415        );
416
417        Ok(Box::pin(RecordBatchStreamWrapper::new(
418            input.mapper.output_schema(),
419            Box::pin(record_batch_stream),
420        )))
421    }
422
423    #[tracing::instrument(
424        skip_all,
425        fields(
426            region_id = %self.stream_ctx.input.mapper.metadata().region_id,
427            partition = partition
428        )
429    )]
430    fn scan_flat_batch_in_partition(
431        &self,
432        partition: usize,
433        part_metrics: PartitionMetrics,
434    ) -> Result<ScanBatchStream> {
435        ensure!(
436            partition < self.properties.partitions.len(),
437            PartitionOutOfRangeSnafu {
438                given: partition,
439                all: self.properties.partitions.len(),
440            }
441        );
442
443        if self.properties.partitions[partition].is_empty() {
444            return Ok(Box::pin(futures::stream::empty()));
445        }
446
447        let stream_ctx = self.stream_ctx.clone();
448        let semaphore = self.new_semaphore();
449        let partition_ranges = self.properties.partitions[partition].clone();
450        let compaction = self.stream_ctx.input.compaction;
451        let file_scan_semaphore = if compaction { None } else { semaphore.clone() };
452        let pruner = self.pruner.clone();
453        // Initializes ref counts for the pruner.
454        // If we call scan_batch_in_partition() multiple times but don't read all batches from the stream,
455        // then the ref count won't be decremented.
456        // This is a rare case and keeping all remaining entries still uses less memory than a per partition cache.
457        pruner.add_partition_ranges(&partition_ranges);
458        let partition_pruner = Arc::new(PartitionPruner::new(pruner, &partition_ranges));
459
460        let stream = try_stream! {
461            part_metrics.on_first_poll();
462            // Start fetch time before building sources so scan cost contains
463            // build part cost.
464            let mut fetch_start = Instant::now();
465
466            // Scans each part.
467            for part_range in partition_ranges {
468                let (mut reader, _) = Self::build_flat_partition_range_read(
469                    &stream_ctx,
470                    &part_range,
471                    if compaction {
472                        FlatReadMode::Compaction
473                    } else {
474                        FlatReadMode::Sequential
475                    },
476                    &part_metrics,
477                    partition_pruner.clone(),
478                    file_scan_semaphore.clone(),
479                    semaphore.clone(),
480                )
481                .await?;
482
483                let mut metrics = ScannerMetrics {
484                    scan_cost: fetch_start.elapsed(),
485                    ..Default::default()
486                };
487                fetch_start = Instant::now();
488
489                while let Some(record_batch) = reader.try_next().await? {
490                    metrics.scan_cost += fetch_start.elapsed();
491                    metrics.num_batches += 1;
492                    metrics.num_rows += record_batch.num_rows();
493
494                    debug_assert!(record_batch.num_rows() > 0);
495                    if record_batch.num_rows() == 0 {
496                        fetch_start = Instant::now();
497                        continue;
498                    }
499
500                    let yield_start = Instant::now();
501                    yield ScanBatch::RecordBatch(record_batch);
502                    metrics.yield_cost += yield_start.elapsed();
503
504                    fetch_start = Instant::now();
505                }
506
507                metrics.scan_cost += fetch_start.elapsed();
508                fetch_start = Instant::now();
509                part_metrics.merge_metrics(&metrics);
510            }
511
512            part_metrics.on_finish();
513        };
514        Ok(Box::pin(stream))
515    }
516
517    fn new_semaphore(&self) -> Option<Arc<Semaphore>> {
518        if self.properties.target_partitions() > self.properties.num_partitions() {
519            // We can use additional tasks to read the data if we have more target partitions than actual partitions.
520            // This semaphore is partition level.
521            // We don't use a global semaphore to avoid a partition waiting for others. The final concurrency
522            // of tasks usually won't exceed the target partitions a lot as compaction can reduce the number of
523            // files in a part range.
524            Some(Arc::new(Semaphore::new(
525                self.properties.target_partitions() - self.properties.num_partitions() + 1,
526            )))
527        } else {
528            None
529        }
530    }
531
532    /// Creates a new partition metrics instance.
533    /// Sets the partition metrics for the given partition if it is not for compaction.
534    fn new_partition_metrics(
535        &self,
536        explain_verbose: bool,
537        metrics_set: &ExecutionPlanMetricsSet,
538        partition: usize,
539    ) -> PartitionMetrics {
540        let metrics = PartitionMetrics::new(
541            self.stream_ctx.input.mapper.metadata().region_id,
542            partition,
543            get_scanner_type(self.stream_ctx.input.compaction),
544            self.stream_ctx.query_start,
545            explain_verbose,
546            metrics_set,
547        );
548
549        if !self.stream_ctx.input.compaction {
550            self.metrics_list.set(partition, metrics.clone());
551        }
552
553        metrics
554    }
555
556    /// Finds the maximum number of files to read in a single partition range.
557    fn max_files_in_partition(ranges: &[RangeMeta], partition_ranges: &[PartitionRange]) -> usize {
558        partition_ranges
559            .iter()
560            .map(|part_range| {
561                let range_meta = &ranges[part_range.identifier];
562                range_meta.indices.len()
563            })
564            .max()
565            .unwrap_or(0)
566    }
567
568    /// Checks resource limit for the scanner.
569    pub(crate) fn check_scan_limit(&self) -> Result<()> {
570        // Check max file count limit for all partitions since we scan them in parallel.
571        let total_max_files: usize = self
572            .properties
573            .partitions
574            .iter()
575            .map(|partition| Self::max_files_in_partition(&self.stream_ctx.ranges, partition))
576            .sum();
577
578        if !self.stream_ctx.input.compaction {
579            SCAN_MAX_CONCURRENT_FILES
580                .with_label_values(&["query"])
581                .observe(total_max_files as f64);
582        }
583        if self.stream_ctx.input.uses_scan_memory_limit() {
584            return Ok(());
585        }
586
587        let max_concurrent_files = self.stream_ctx.input.max_concurrent_scan_files;
588        if total_max_files > max_concurrent_files {
589            return TooManyFilesToReadSnafu {
590                actual: total_max_files,
591                max: max_concurrent_files,
592            }
593            .fail();
594        }
595
596        Ok(())
597    }
598}
599
600impl RegionScanner for SeqScan {
601    fn name(&self) -> &str {
602        "SeqScan"
603    }
604
605    fn properties(&self) -> &ScannerProperties {
606        &self.properties
607    }
608
609    fn schema(&self) -> SchemaRef {
610        self.stream_ctx.input.mapper.output_schema()
611    }
612
613    fn metadata(&self) -> RegionMetadataRef {
614        self.stream_ctx.input.mapper.metadata().clone()
615    }
616
617    fn scan_partition(
618        &self,
619        ctx: &QueryScanContext,
620        metrics_set: &ExecutionPlanMetricsSet,
621        partition: usize,
622    ) -> Result<SendableRecordBatchStream, BoxedError> {
623        self.scan_partition_impl(ctx, metrics_set, partition)
624            .map_err(BoxedError::new)
625    }
626
627    fn prepare(&mut self, request: PrepareRequest) -> Result<(), BoxedError> {
628        self.properties.prepare(request);
629
630        self.check_scan_limit().map_err(BoxedError::new)?;
631
632        Ok(())
633    }
634
635    fn has_predicate_without_region(&self) -> bool {
636        let predicate = self
637            .stream_ctx
638            .input
639            .predicate_group()
640            .predicate_without_region();
641        predicate.is_some()
642    }
643
644    fn add_dyn_filter_to_predicate(
645        &mut self,
646        filter_exprs: Vec<Arc<dyn datafusion::physical_plan::PhysicalExpr>>,
647    ) -> Vec<bool> {
648        self.stream_ctx.add_dyn_filter_to_predicate(filter_exprs)
649    }
650
651    fn reset_state(&mut self) {
652        self.stream_ctx.input.predicate.clear_dyn_filters();
653        let num_workers = common_stat::get_total_cpu_cores().max(1);
654        self.pruner = Arc::new(Pruner::new(self.stream_ctx.clone(), num_workers));
655        self.metrics_list = PartitionMetricsList::default();
656    }
657
658    fn set_logical_region(&mut self, logical_region: bool) {
659        self.properties.set_logical_region(logical_region);
660    }
661
662    fn set_query_load_region_id(&mut self, region_id: store_api::storage::RegionId) {
663        self.properties.set_query_load_region_id(region_id);
664    }
665
666    fn snapshot_sequence(&self) -> Option<u64> {
667        self.stream_ctx.input.snapshot_sequence
668    }
669}
670
671impl DisplayAs for SeqScan {
672    fn fmt_as(&self, t: DisplayFormatType, f: &mut fmt::Formatter) -> fmt::Result {
673        write!(
674            f,
675            "SeqScan: region={}, ",
676            self.stream_ctx.input.mapper.metadata().region_id
677        )?;
678        match t {
679            // TODO(LFC): Implement all the "TreeRender" display format.
680            DisplayFormatType::Default | DisplayFormatType::TreeRender => {
681                self.stream_ctx.format_for_explain(false, f)
682            }
683            DisplayFormatType::Verbose => {
684                self.stream_ctx.format_for_explain(true, f)?;
685                self.metrics_list.format_verbose_metrics(f)
686            }
687        }
688    }
689}
690
691impl fmt::Debug for SeqScan {
692    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
693        f.debug_struct("SeqScan")
694            .field("num_ranges", &self.stream_ctx.ranges.len())
695            .finish()
696    }
697}
698
699/// Builds flat sources for the partition range and push them to the `sources` vector.
700/// Returns the estimated rows per batch after splitting if splitting is applied, or `None`.
701pub(crate) async fn build_flat_sources(
702    stream_ctx: &Arc<StreamContext>,
703    part_range: &PartitionRange,
704    read_mode: FlatReadMode,
705    part_metrics: &PartitionMetrics,
706    partition_pruner: Arc<PartitionPruner>,
707    sources: &mut Vec<BoxedRecordBatchStream>,
708    semaphore: Option<Arc<Semaphore>>,
709) -> Result<Option<usize>> {
710    let compaction = read_mode == FlatReadMode::Compaction;
711    // Gets range meta.
712    let range_meta = &stream_ctx.ranges[part_range.identifier];
713    #[cfg(debug_assertions)]
714    if compaction {
715        // Compaction expects input sources are not been split.
716        debug_assert_eq!(range_meta.indices.len(), range_meta.row_group_indices.len());
717        for (i, row_group_idx) in range_meta.row_group_indices.iter().enumerate() {
718            // It should scan all row groups.
719            debug_assert_eq!(
720                -1, row_group_idx.row_group_index,
721                "Expect {} range scan all row groups, given: {}",
722                i, row_group_idx.row_group_index,
723            );
724        }
725    }
726
727    let read_type = if compaction {
728        "compaction"
729    } else {
730        "seq_scan_files"
731    };
732    let num_indices = range_meta.row_group_indices.len();
733    if num_indices == 0 {
734        return Ok(None);
735    }
736
737    sources.reserve(num_indices);
738    let mut ordered_sources = Vec::with_capacity(num_indices);
739    ordered_sources.resize_with(num_indices, || None);
740    let mut file_scan_tasks = Vec::new();
741    let pre_filter_mode = stream_ctx.range_pre_filter_mode(part_range);
742
743    for (position, index) in range_meta.row_group_indices.iter().enumerate() {
744        if stream_ctx.is_mem_range_index(*index) {
745            let stream = scan_flat_mem_ranges(
746                stream_ctx.clone(),
747                part_metrics.clone(),
748                *index,
749                range_meta.time_range,
750            );
751            ordered_sources[position] = Some(prepare_flat_mem_stream(stream_ctx.clone(), stream));
752        } else if stream_ctx.is_file_range_index(*index) {
753            // Common manifest-level fast-skip shared by SeqScan and UnorderedScan.
754            // Compaction should keep reading its selected input ranges completely.
755            if !compaction
756                && partition_pruner.try_skip_manifest_pruned_file_range(*index, part_metrics)
757            {
758                continue;
759            }
760            if let Some(semaphore_ref) = semaphore.as_ref() {
761                // run in parallel, controlled by semaphore
762                let stream_ctx = stream_ctx.clone();
763                let part_metrics = part_metrics.clone();
764                let partition_pruner = partition_pruner.clone();
765                let semaphore = Arc::clone(semaphore_ref);
766                let row_group_index = *index;
767                file_scan_tasks.push(async move {
768                    let _permit = semaphore.acquire().await.unwrap();
769                    let stream = scan_flat_file_ranges(
770                        stream_ctx,
771                        part_metrics,
772                        row_group_index,
773                        read_type,
774                        partition_pruner,
775                    )
776                    .await?;
777                    Ok((position, Box::pin(stream) as _))
778                });
779            } else {
780                // no semaphore, run sequentially
781                let stream = scan_flat_file_ranges(
782                    stream_ctx.clone(),
783                    part_metrics.clone(),
784                    *index,
785                    read_type,
786                    partition_pruner.clone(),
787                )
788                .await?;
789                ordered_sources[position] = Some(Box::pin(stream) as _);
790            }
791        } else {
792            let stream = scan_util::maybe_scan_flat_other_ranges(
793                stream_ctx,
794                *index,
795                part_metrics,
796                pre_filter_mode,
797            )
798            .await?;
799            ordered_sources[position] = Some(stream);
800        }
801    }
802
803    if !file_scan_tasks.is_empty() {
804        let results = futures::future::try_join_all(file_scan_tasks).await?;
805        for (position, stream) in results {
806            ordered_sources[position] = Some(stream);
807        }
808    }
809
810    // SeriesScan also merges range outputs. Split at the source, before deduplication
811    // and LastRow selection, so their output batching is preserved by the range cache.
812    let needs_merge =
813        ordered_sources.iter().flatten().count() > 1 || (compaction && stream_ctx.ranges.len() > 1);
814    let split_batch_size = if needs_merge || read_mode == FlatReadMode::CrossRangeMerge {
815        should_split_flat_batches_for_merge(stream_ctx, range_meta).filter(|rows_per_series| {
816            // A single-source range only benefits at the downstream merge. Tiny
817            // splits add cache replay, channel and distribution work per batch.
818            if !needs_merge && *rows_per_series < BATCH_SIZE_THRESHOLD as usize {
819                return false;
820            }
821            // Compaction writes every merged batch out, so splitting short series
822            // would hand the SST writer and indexer one tiny batch per series.
823            !compaction || *rows_per_series >= MIN_COMPACTION_SPLIT_ROWS
824        })
825    } else {
826        None
827    };
828    let should_split = split_batch_size.is_some();
829
830    for stream in ordered_sources.into_iter().flatten() {
831        if should_split {
832            sources.push(Box::pin(SplitRecordBatchStream::new(stream)));
833        } else {
834            sources.push(stream);
835        }
836    }
837
838    if should_split {
839        common_telemetry::debug!(
840            "Splitting record batches, region: {}, sources: {}, part_range: {:?}",
841            stream_ctx.input.region_metadata().region_id,
842            sources.len(),
843            part_range,
844        );
845    }
846
847    Ok(split_batch_size)
848}
849
850#[cfg(test)]
851impl SeqScan {
852    /// Returns the input.
853    pub(crate) fn input(&self) -> &ScanInput {
854        &self.stream_ctx.input
855    }
856}
857
858/// Returns the scanner type.
859fn get_scanner_type(compaction: bool) -> &'static str {
860    if compaction {
861        "SeqScan(compaction)"
862    } else {
863        "SeqScan"
864    }
865}