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