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