Skip to main content

mito2/read/
scan_region.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//! Scans a region according to the scan request.
16
17use std::collections::{HashMap, HashSet};
18use std::fmt;
19use std::num::NonZeroU64;
20use std::sync::Arc;
21use std::time::Instant;
22
23use api::v1::SemanticType;
24use common_error::ext::BoxedError;
25use common_recordbatch::SendableRecordBatchStream;
26use common_recordbatch::adapter::RegionQueryStatCounters;
27use common_recordbatch::filter::SimpleFilterEvaluator;
28use common_telemetry::tracing::Instrument;
29use common_telemetry::{debug, error, tracing, warn};
30use common_time::range::TimestampRange;
31use datafusion::physical_plan::expressions::DynamicFilterPhysicalExpr;
32use datafusion_common::pruning::PruningStatistics;
33use datafusion_common::{Column, ScalarValue};
34use datafusion_expr::Expr;
35use datafusion_expr::utils::expr_to_columns;
36use datatypes::arrow::array::{ArrayRef, BooleanArray, UInt64Array};
37use datatypes::extension::json::is_structured_json_field;
38use datatypes::types::json_type::JsonNativeType;
39use datatypes::value::timestamp_to_scalar_value;
40use futures::StreamExt;
41use itertools::Itertools;
42use partition::expr::PartitionExpr;
43use smallvec::SmallVec;
44use snafu::ResultExt;
45use store_api::metadata::{RegionMetadata, RegionMetadataRef};
46use store_api::region_engine::{PartitionRange, RegionScannerRef};
47use store_api::storage::{
48    NestedPath, RegionId, ScanRequest, SequenceNumber, SequenceRange, TimeSeriesDistribution,
49    TimeSeriesRowSelector,
50};
51use table::predicate::{Predicate, build_time_range_predicate, extract_time_range_from_expr};
52use tokio::sync::{Semaphore, mpsc};
53use tokio_stream::wrappers::ReceiverStream;
54
55use crate::access_layer::AccessLayerRef;
56use crate::cache::CacheStrategy;
57use crate::config::DEFAULT_MAX_CONCURRENT_SCAN_FILES;
58use crate::error::{InvalidPartitionExprSnafu, Result};
59#[cfg(feature = "enterprise")]
60use crate::extension::{BoxedExtensionRange, BoxedExtensionRangeProvider};
61use crate::memtable::{MemtableRange, RangesOptions};
62use crate::metrics::READ_SST_COUNT;
63use crate::read::compat::{self, FlatCompatBatch};
64use crate::read::flat_projection::FlatProjectionMapper;
65use crate::read::range::{FileRangeBuilder, MemRangeBuilder, RangeMeta, RowGroupIndex};
66use crate::read::range_cache::{ScanRequestFingerprint, implied_time_range_from_exprs};
67use crate::read::read_columns::{
68    ReadColumns, merge, merge_nested_paths, read_columns_from_predicate,
69    read_columns_from_projection,
70};
71use crate::read::seq_scan::SeqScan;
72use crate::read::series_scan::SeriesScan;
73use crate::read::stream::ScanBatchStream;
74use crate::read::unordered_scan::UnorderedScan;
75use crate::read::{BoxedRecordBatchStream, RecordBatch};
76use crate::region::options::MergeMode;
77use crate::region::version::VersionRef;
78use crate::sst::file::FileHandle;
79use crate::sst::index::bloom_filter::applier::{
80    BloomFilterIndexApplierBuilder, BloomFilterIndexApplierRef,
81};
82use crate::sst::index::fulltext_index::applier::FulltextIndexApplierRef;
83use crate::sst::index::fulltext_index::applier::builder::FulltextIndexApplierBuilder;
84use crate::sst::index::inverted_index::applier::InvertedIndexApplierRef;
85use crate::sst::index::inverted_index::applier::builder::InvertedIndexApplierBuilder;
86#[cfg(feature = "vector_index")]
87use crate::sst::index::vector_index::applier::{VectorIndexApplier, VectorIndexApplierRef};
88use crate::sst::parquet::file_range::PreFilterMode;
89use crate::sst::parquet::reader::ReaderMetrics;
90
91#[cfg(feature = "vector_index")]
92const VECTOR_INDEX_OVERFETCH_MULTIPLIER: usize = 2;
93
94/// A scanner scans a region and returns a [SendableRecordBatchStream].
95pub(crate) enum Scanner {
96    /// Sequential scan.
97    Seq(SeqScan),
98    /// Unordered scan.
99    Unordered(UnorderedScan),
100    /// Per-series scan.
101    Series(SeriesScan),
102}
103
104impl Scanner {
105    /// Returns a [SendableRecordBatchStream] to retrieve scan results from all partitions.
106    #[tracing::instrument(level = tracing::Level::DEBUG, skip_all)]
107    pub(crate) async fn scan(&self) -> Result<SendableRecordBatchStream, BoxedError> {
108        match self {
109            Scanner::Seq(seq_scan) => seq_scan.build_stream(),
110            Scanner::Unordered(unordered_scan) => unordered_scan.build_stream().await,
111            Scanner::Series(series_scan) => series_scan.build_stream().await,
112        }
113    }
114
115    /// Create a stream of [`Batch`] by this scanner.
116    pub(crate) fn scan_batch(&self) -> Result<ScanBatchStream> {
117        match self {
118            Scanner::Seq(x) => x.scan_all_partitions(),
119            Scanner::Unordered(x) => x.scan_all_partitions(),
120            Scanner::Series(x) => x.scan_all_partitions(),
121        }
122    }
123}
124
125#[cfg(test)]
126impl Scanner {
127    /// Returns number of files to scan.
128    pub(crate) fn num_files(&self) -> usize {
129        match self {
130            Scanner::Seq(seq_scan) => seq_scan.input().num_files(),
131            Scanner::Unordered(unordered_scan) => unordered_scan.input().num_files(),
132            Scanner::Series(series_scan) => series_scan.input().num_files(),
133        }
134    }
135
136    /// Returns number of memtables to scan.
137    pub(crate) fn num_memtables(&self) -> usize {
138        match self {
139            Scanner::Seq(seq_scan) => seq_scan.input().num_memtables(),
140            Scanner::Unordered(unordered_scan) => unordered_scan.input().num_memtables(),
141            Scanner::Series(series_scan) => series_scan.input().num_memtables(),
142        }
143    }
144
145    /// Returns SST file ids to scan.
146    pub(crate) fn file_ids(&self) -> Vec<crate::sst::file::RegionFileId> {
147        match self {
148            Scanner::Seq(seq_scan) => seq_scan.input().file_ids(),
149            Scanner::Unordered(unordered_scan) => unordered_scan.input().file_ids(),
150            Scanner::Series(series_scan) => series_scan.input().file_ids(),
151        }
152    }
153
154    pub(crate) fn index_ids(&self) -> Vec<crate::sst::file::RegionIndexId> {
155        match self {
156            Scanner::Seq(seq_scan) => seq_scan.input().index_ids(),
157            Scanner::Unordered(unordered_scan) => unordered_scan.input().index_ids(),
158            Scanner::Series(series_scan) => series_scan.input().index_ids(),
159        }
160    }
161
162    pub(crate) fn snapshot_sequence(&self) -> Option<SequenceNumber> {
163        match self {
164            Scanner::Seq(seq_scan) => seq_scan.input().snapshot_sequence,
165            Scanner::Unordered(unordered_scan) => unordered_scan.input().snapshot_sequence,
166            Scanner::Series(series_scan) => series_scan.input().snapshot_sequence,
167        }
168    }
169
170    /// Sets the target partitions for the scanner. It can controls the parallelism of the scanner.
171    pub(crate) fn set_target_partitions(&mut self, target_partitions: usize) {
172        use store_api::region_engine::{PrepareRequest, RegionScanner};
173
174        let request = PrepareRequest::default().with_target_partitions(target_partitions);
175        match self {
176            Scanner::Seq(seq_scan) => seq_scan.prepare(request).unwrap(),
177            Scanner::Unordered(unordered_scan) => unordered_scan.prepare(request).unwrap(),
178            Scanner::Series(series_scan) => series_scan.prepare(request).unwrap(),
179        }
180    }
181}
182
183#[cfg_attr(doc, aquamarine::aquamarine)]
184/// Helper to scans a region by [ScanRequest].
185///
186/// [ScanRegion] collects SSTs and memtables to scan without actually reading them. It
187/// creates a [Scanner] to actually scan these targets in [Scanner::scan()].
188///
189/// ```mermaid
190/// classDiagram
191/// class ScanRegion {
192///     -VersionRef version
193///     -ScanRequest request
194///     ~scanner() Scanner
195///     ~seq_scan() SeqScan
196/// }
197/// class Scanner {
198///     <<enumeration>>
199///     SeqScan
200///     UnorderedScan
201///     +scan() SendableRecordBatchStream
202/// }
203/// class SeqScan {
204///     -ScanInput input
205///     +build() SendableRecordBatchStream
206/// }
207/// class UnorderedScan {
208///     -ScanInput input
209///     +build() SendableRecordBatchStream
210/// }
211/// class ScanInput {
212///     -ProjectionMapper mapper
213///     -Option~TimeRange~ time_range
214///     -Option~Predicate~ predicate
215///     -Vec~MemtableRef~ memtables
216///     -Vec~FileHandle~ files
217/// }
218/// class ProjectionMapper {
219///     ~output_schema() SchemaRef
220///     ~convert(Batch) RecordBatch
221/// }
222/// ScanRegion -- Scanner
223/// ScanRegion o-- ScanRequest
224/// Scanner o-- SeqScan
225/// Scanner o-- UnorderedScan
226/// SeqScan o-- ScanInput
227/// UnorderedScan o-- ScanInput
228/// Scanner -- SendableRecordBatchStream
229/// ScanInput o-- ProjectionMapper
230/// SeqScan -- SendableRecordBatchStream
231/// UnorderedScan -- SendableRecordBatchStream
232/// ```
233pub(crate) struct ScanRegion {
234    /// Version of the region at scan.
235    version: VersionRef,
236    /// Access layer of the region.
237    access_layer: AccessLayerRef,
238    /// Scan request.
239    request: ScanRequest,
240    /// Cache.
241    cache_strategy: CacheStrategy,
242    /// Maximum number of SST files to scan concurrently.
243    max_concurrent_scan_files: usize,
244    /// Whether to ignore inverted index.
245    ignore_inverted_index: bool,
246    /// Whether to ignore fulltext index.
247    ignore_fulltext_index: bool,
248    /// Whether to ignore bloom filter.
249    ignore_bloom_filter: bool,
250    /// Start time of the scan task.
251    start_time: Option<Instant>,
252    /// Whether to filter out the deleted rows.
253    /// Usually true for normal read, and false for scan for compaction.
254    filter_deleted: bool,
255    /// Counters that should receive query-load metrics.
256    query_stat_counters: Option<RegionQueryStatCounters>,
257    #[cfg(feature = "enterprise")]
258    extension_range_provider: Option<BoxedExtensionRangeProvider>,
259}
260
261impl ScanRegion {
262    /// Creates a [ScanRegion].
263    pub(crate) fn new(
264        version: VersionRef,
265        access_layer: AccessLayerRef,
266        request: ScanRequest,
267        cache_strategy: CacheStrategy,
268    ) -> ScanRegion {
269        ScanRegion {
270            version,
271            access_layer,
272            request,
273            cache_strategy,
274            max_concurrent_scan_files: DEFAULT_MAX_CONCURRENT_SCAN_FILES,
275            ignore_inverted_index: false,
276            ignore_fulltext_index: false,
277            ignore_bloom_filter: false,
278            start_time: None,
279            filter_deleted: true,
280            query_stat_counters: None,
281            #[cfg(feature = "enterprise")]
282            extension_range_provider: None,
283        }
284    }
285
286    /// Sets counters that should receive query-load metrics.
287    #[must_use]
288    pub(crate) fn with_query_stat_counters(mut self, counters: RegionQueryStatCounters) -> Self {
289        self.query_stat_counters = Some(counters);
290        self
291    }
292
293    /// Sets maximum number of SST files to scan concurrently.
294    #[must_use]
295    pub(crate) fn with_max_concurrent_scan_files(
296        mut self,
297        max_concurrent_scan_files: usize,
298    ) -> Self {
299        self.max_concurrent_scan_files = max_concurrent_scan_files;
300        self
301    }
302
303    /// Sets whether to ignore inverted index.
304    #[must_use]
305    pub(crate) fn with_ignore_inverted_index(mut self, ignore: bool) -> Self {
306        self.ignore_inverted_index = ignore;
307        self
308    }
309
310    /// Sets whether to ignore fulltext index.
311    #[must_use]
312    pub(crate) fn with_ignore_fulltext_index(mut self, ignore: bool) -> Self {
313        self.ignore_fulltext_index = ignore;
314        self
315    }
316
317    /// Sets whether to ignore bloom filter.
318    #[must_use]
319    pub(crate) fn with_ignore_bloom_filter(mut self, ignore: bool) -> Self {
320        self.ignore_bloom_filter = ignore;
321        self
322    }
323
324    #[must_use]
325    pub(crate) fn with_start_time(mut self, now: Instant) -> Self {
326        self.start_time = Some(now);
327        self
328    }
329
330    pub(crate) fn set_filter_deleted(&mut self, filter_deleted: bool) {
331        self.filter_deleted = filter_deleted;
332    }
333
334    #[cfg(feature = "enterprise")]
335    pub(crate) fn set_extension_range_provider(
336        &mut self,
337        extension_range_provider: BoxedExtensionRangeProvider,
338    ) {
339        self.extension_range_provider = Some(extension_range_provider);
340    }
341
342    /// Returns a [Scanner] to scan the region.
343    #[tracing::instrument(skip_all, fields(region_id = %self.region_id()))]
344    pub(crate) async fn scanner(self) -> Result<Scanner> {
345        if self.use_series_scan() {
346            self.series_scan().await.map(Scanner::Series)
347        } else if self.use_unordered_scan() {
348            // If table is append only and there is no series row selector, we use unordered scan in query.
349            // We still use seq scan in compaction.
350            self.unordered_scan().await.map(Scanner::Unordered)
351        } else {
352            self.seq_scan().await.map(Scanner::Seq)
353        }
354    }
355
356    /// Returns a [RegionScanner] to scan the region.
357    #[tracing::instrument(
358        level = tracing::Level::DEBUG,
359        skip_all,
360        fields(region_id = %self.region_id())
361    )]
362    pub(crate) async fn region_scanner(self) -> Result<RegionScannerRef> {
363        if self.use_series_scan() {
364            self.series_scan()
365                .await
366                .map(|scanner| Box::new(scanner) as _)
367        } else if self.use_unordered_scan() {
368            self.unordered_scan()
369                .await
370                .map(|scanner| Box::new(scanner) as _)
371        } else {
372            self.seq_scan().await.map(|scanner| Box::new(scanner) as _)
373        }
374    }
375
376    /// Scan sequentially.
377    #[tracing::instrument(skip_all, fields(region_id = %self.region_id()))]
378    pub(crate) async fn seq_scan(self) -> Result<SeqScan> {
379        let input = self.scan_input().await?.with_compaction(false);
380        Ok(SeqScan::new(input))
381    }
382
383    /// Unordered scan.
384    #[tracing::instrument(skip_all, fields(region_id = %self.region_id()))]
385    pub(crate) async fn unordered_scan(self) -> Result<UnorderedScan> {
386        let input = self.scan_input().await?;
387        Ok(UnorderedScan::new(input))
388    }
389
390    /// Scans by series.
391    #[tracing::instrument(skip_all, fields(region_id = %self.region_id()))]
392    pub(crate) async fn series_scan(self) -> Result<SeriesScan> {
393        let input = self.scan_input().await?;
394        Ok(SeriesScan::new(input))
395    }
396
397    /// Returns true if the region can use unordered scan for current request.
398    fn use_unordered_scan(&self) -> bool {
399        // We use unordered scan when:
400        // 1. The region is in append mode.
401        // 2. There is no series row selector.
402        // 3. The required distribution is None or TimeSeriesDistribution::TimeWindowed.
403        //
404        // We still use seq scan in compaction.
405        self.version.options.append_mode
406            && self.request.series_row_selector.is_none()
407            && (self.request.distribution.is_none()
408                || self.request.distribution == Some(TimeSeriesDistribution::TimeWindowed))
409    }
410
411    /// Returns true if the region can use series scan for current request.
412    fn use_series_scan(&self) -> bool {
413        self.request.distribution == Some(TimeSeriesDistribution::PerSeries)
414    }
415
416    /// Creates a scan input.
417    #[tracing::instrument(skip_all, fields(region_id = %self.region_id()))]
418    async fn scan_input(self) -> Result<ScanInput> {
419        let sst_min_sequence = self.request.sst_min_sequence.and_then(NonZeroU64::new);
420        let time_range = self.build_time_range_predicate();
421        let predicate = PredicateGroup::new(&self.version.metadata, &self.request.filters)?;
422
423        let mut read_cols = match &self.request.projection_input {
424            Some(p) => {
425                // Read columns include the pushed-down projection and columns
426                // resolved from the predicate.
427                let metadata = &self.version.metadata;
428                let from_projection = read_columns_from_projection(p.clone(), metadata)?;
429                let from_predicate = read_columns_from_predicate(&predicate, metadata);
430                merge(from_projection, from_predicate)
431            }
432            None => {
433                let read_col_ids = self
434                    .version
435                    .metadata
436                    .column_metadatas
437                    .iter()
438                    .map(|col| col.column_id);
439                ReadColumns::from_deduped_column_ids(read_col_ids)
440            }
441        };
442        // Only narrow read columns and pass JSON type hints for structured JSON (JSON2)
443        // columns. Legacy JSONB columns have JSON extension metadata but their physical
444        // Arrow type is Binary, not Struct, so they must not enter structured JSON paths.
445        let has_structured_json = self
446            .version
447            .metadata
448            .schema
449            .arrow_schema()
450            .fields()
451            .iter()
452            .any(is_structured_json_field);
453        if has_structured_json {
454            narrow_read_columns_by_json_type_hint(
455                &mut read_cols,
456                &self.request.json_type_hint,
457                &self.version.metadata,
458            );
459        }
460        let read_col_ids = read_cols.column_ids();
461
462        // The mapper always computes projected column ids as the schema of SSTs may change.
463        let projection = self
464            .request
465            .projection_indices()
466            .map(|x| x.to_vec())
467            .unwrap_or_else(|| (0..self.version.metadata.column_metadatas.len()).collect());
468        let json_type_hint = has_structured_json
469            .then_some(&self.request.json_type_hint)
470            .inspect(|json_type_hint| {
471                debug!(
472                    "Concretized JSON type: {{{}}}",
473                    json_type_hint
474                        .iter()
475                        .map(|(k, v)| format!("{}: {}", k, v))
476                        .join(", ")
477                );
478            });
479        let mapper = FlatProjectionMapper::new_with_read_columns(
480            &self.version.metadata,
481            projection,
482            read_cols,
483            json_type_hint,
484        )?;
485        let mapper = if self.request.preserve_pk_dictionary_encoding {
486            mapper.with_pk_dictionary_encoding()
487        } else {
488            mapper
489        };
490
491        let ssts = &self.version.ssts;
492        let mut files = Vec::new();
493        if !self.request.skip_sst_files {
494            for level in ssts.levels() {
495                for file in level.files.values() {
496                    let exceed_min_sequence = match (sst_min_sequence, file.meta_ref().sequence) {
497                        (Some(min_sequence), Some(file_sequence)) => file_sequence > min_sequence,
498                        // If the file's sequence is None (or actually is zero), it could mean the file
499                        // is generated and added to the region "directly". In this case, its data should
500                        // be considered as fresh as the memtable. So its sequence is treated greater than
501                        // the min_sequence, whatever the value of min_sequence is. Hence the default
502                        // "true" in this arm.
503                        (Some(_), None) => true,
504                        (None, _) => true,
505                    };
506
507                    // Finds SST files in range.
508                    if exceed_min_sequence && file_in_range(file, &time_range) {
509                        files.push(file.clone());
510                    }
511                    // There is no need to check and prune for file's sequence here as the sequence number is usually very new,
512                    // unless the timing is too good, or the sequence number wouldn't be in file.
513                    // and the batch will be filtered out by tree reader anyway.
514                }
515            }
516        }
517
518        let memtables = self.version.memtables.list_memtables();
519        // Skip empty memtables and memtables out of time range.
520        let mut mem_range_builders = Vec::new();
521        let filter_mode = pre_filter_mode(
522            self.version.options.append_mode,
523            self.version.options.merge_mode(),
524        );
525
526        for m in memtables {
527            // check if memtable is empty by reading stats.
528            let Some((start, end)) = m.stats().time_range() else {
529                continue;
530            };
531            // The time range of the memtable is inclusive.
532            let memtable_range = TimestampRange::new_inclusive(Some(start), Some(end));
533            if !memtable_range.intersects(&time_range) {
534                continue;
535            }
536            let ranges_in_memtable = m.ranges(
537                Some(&read_col_ids),
538                RangesOptions::default()
539                    .with_predicate(predicate.clone())
540                    .with_sequence(SequenceRange::new(
541                        self.request.memtable_min_sequence,
542                        self.request.memtable_max_sequence,
543                    ))
544                    .with_pre_filter_mode(filter_mode),
545            )?;
546            mem_range_builders.extend(ranges_in_memtable.ranges.into_values().map(|v| {
547                let stats = v.stats().clone();
548                MemRangeBuilder::new(v, stats)
549            }));
550        }
551
552        let region_id = self.region_id();
553        debug!(
554            "Scan region {}, request: {:?}, time range: {:?}, memtables: {}, ssts_to_read: {}, append_mode: {}",
555            region_id,
556            self.request,
557            time_range,
558            mem_range_builders.len(),
559            files.len(),
560            self.version.options.append_mode,
561        );
562
563        let (non_field_filters, field_filters) = self.partition_by_field_filters();
564        let inverted_index_appliers = [
565            self.build_invereted_index_applier(&non_field_filters),
566            self.build_invereted_index_applier(&field_filters),
567        ];
568        let bloom_filter_appliers = [
569            self.build_bloom_filter_applier(&non_field_filters),
570            self.build_bloom_filter_applier(&field_filters),
571        ];
572        let fulltext_index_appliers = [
573            self.build_fulltext_index_applier(&non_field_filters),
574            self.build_fulltext_index_applier(&field_filters),
575        ];
576        #[cfg(feature = "vector_index")]
577        let vector_index_applier = self.build_vector_index_applier();
578        #[cfg(feature = "vector_index")]
579        let vector_index_k = self.request.vector_search.as_ref().map(|search| {
580            if self.request.filters.is_empty() {
581                search.k
582            } else {
583                search.k.saturating_mul(VECTOR_INDEX_OVERFETCH_MULTIPLIER)
584            }
585        });
586
587        let input = ScanInput::new(self.access_layer, mapper)
588            .with_time_range(Some(time_range))
589            .with_predicate(predicate)
590            .with_memtables(mem_range_builders)
591            .with_files(files)
592            .with_cache(self.cache_strategy)
593            .with_inverted_index_appliers(inverted_index_appliers)
594            .with_bloom_filter_index_appliers(bloom_filter_appliers)
595            .with_fulltext_index_appliers(fulltext_index_appliers)
596            .with_max_concurrent_scan_files(self.max_concurrent_scan_files)
597            .with_start_time(self.start_time)
598            .with_append_mode(self.version.options.append_mode)
599            .with_filter_deleted(self.filter_deleted)
600            .with_merge_mode(self.version.options.merge_mode())
601            .with_series_row_selector(self.request.series_row_selector)
602            .with_distribution(self.request.distribution)
603            .with_explain_flat_format(
604                self.version.options.sst_format == Some(crate::sst::FormatType::Flat),
605            )
606            .with_snapshot_sequence(
607                self.request
608                    .snapshot_on_scan
609                    .then_some(self.request.memtable_max_sequence)
610                    .flatten(),
611            )
612            .with_query_stat_counters(self.query_stat_counters);
613        #[cfg(feature = "vector_index")]
614        let input = input
615            .with_vector_index_applier(vector_index_applier)
616            .with_vector_index_k(vector_index_k);
617
618        #[cfg(feature = "enterprise")]
619        let input = if !self.request.skip_sst_files
620            && let Some(provider) = self.extension_range_provider
621        {
622            let ranges = provider
623                .find_extension_ranges(self.version.flushed_sequence, time_range, &self.request)
624                .await?;
625            debug!("Find extension ranges: {ranges:?}");
626            input.with_extension_ranges(ranges)
627        } else {
628            input
629        };
630        Ok(input)
631    }
632
633    fn region_id(&self) -> RegionId {
634        self.version.metadata.region_id
635    }
636
637    /// Build time range predicate from filters.
638    fn build_time_range_predicate(&self) -> TimestampRange {
639        let time_index = self.version.metadata.time_index_column();
640        let unit = time_index
641            .column_schema
642            .data_type
643            .as_timestamp()
644            .expect("Time index must have timestamp-compatible type")
645            .unit();
646        build_time_range_predicate(&time_index.column_schema.name, unit, &self.request.filters)
647    }
648
649    /// Partitions filters into two groups: non-field filters and field filters.
650    /// Returns `(non_field_filters, field_filters)`.
651    fn partition_by_field_filters(&self) -> (Vec<Expr>, Vec<Expr>) {
652        let field_columns = self
653            .version
654            .metadata
655            .field_columns()
656            .map(|col| &col.column_schema.name)
657            .collect::<HashSet<_>>();
658
659        let mut columns = HashSet::new();
660
661        self.request.filters.iter().cloned().partition(|expr| {
662            columns.clear();
663            // `expr_to_columns` won't return error.
664            if expr_to_columns(expr, &mut columns).is_err() {
665                // If we can't extract columns, treat it as non-field filter
666                return true;
667            }
668            // Return true for non-field filters (partition puts true cases in first vec)
669            !columns
670                .iter()
671                .any(|column| field_columns.contains(&column.name))
672        })
673    }
674
675    /// Use the latest schema to build the inverted index applier.
676    fn build_invereted_index_applier(&self, filters: &[Expr]) -> Option<InvertedIndexApplierRef> {
677        if self.ignore_inverted_index {
678            return None;
679        }
680
681        let file_cache = self.cache_strategy.write_cache().map(|w| w.file_cache());
682        let inverted_index_cache = self.cache_strategy.inverted_index_cache().cloned();
683
684        let puffin_metadata_cache = self.cache_strategy.puffin_metadata_cache().cloned();
685
686        InvertedIndexApplierBuilder::new(
687            self.access_layer.table_dir().to_string(),
688            self.access_layer.path_type(),
689            self.access_layer.object_store().clone(),
690            self.version.metadata.as_ref(),
691            self.version.metadata.inverted_indexed_column_ids(
692                self.version
693                    .options
694                    .index_options
695                    .inverted_index
696                    .ignore_column_ids
697                    .iter(),
698            ),
699            self.access_layer.puffin_manager_factory().clone(),
700        )
701        .with_file_cache(file_cache)
702        .with_inverted_index_cache(inverted_index_cache)
703        .with_puffin_metadata_cache(puffin_metadata_cache)
704        .build(filters)
705        .inspect_err(|err| warn!(err; "Failed to build invereted index applier"))
706        .ok()
707        .flatten()
708        .map(Arc::new)
709    }
710
711    /// Use the latest schema to build the bloom filter index applier.
712    fn build_bloom_filter_applier(&self, filters: &[Expr]) -> Option<BloomFilterIndexApplierRef> {
713        if self.ignore_bloom_filter {
714            return None;
715        }
716
717        let file_cache = self.cache_strategy.write_cache().map(|w| w.file_cache());
718        let bloom_filter_index_cache = self.cache_strategy.bloom_filter_index_cache().cloned();
719        let puffin_metadata_cache = self.cache_strategy.puffin_metadata_cache().cloned();
720
721        BloomFilterIndexApplierBuilder::new(
722            self.access_layer.table_dir().to_string(),
723            self.access_layer.path_type(),
724            self.access_layer.object_store().clone(),
725            self.version.metadata.as_ref(),
726            self.access_layer.puffin_manager_factory().clone(),
727        )
728        .with_file_cache(file_cache)
729        .with_bloom_filter_index_cache(bloom_filter_index_cache)
730        .with_puffin_metadata_cache(puffin_metadata_cache)
731        .build(filters)
732        .inspect_err(|err| warn!(err; "Failed to build bloom filter index applier"))
733        .ok()
734        .flatten()
735        .map(Arc::new)
736    }
737
738    /// Use the latest schema to build the fulltext index applier.
739    fn build_fulltext_index_applier(&self, filters: &[Expr]) -> Option<FulltextIndexApplierRef> {
740        if self.ignore_fulltext_index {
741            return None;
742        }
743
744        let file_cache = self.cache_strategy.write_cache().map(|w| w.file_cache());
745        let puffin_metadata_cache = self.cache_strategy.puffin_metadata_cache().cloned();
746        let bloom_filter_index_cache = self.cache_strategy.bloom_filter_index_cache().cloned();
747        FulltextIndexApplierBuilder::new(
748            self.access_layer.table_dir().to_string(),
749            self.access_layer.path_type(),
750            self.access_layer.object_store().clone(),
751            self.access_layer.puffin_manager_factory().clone(),
752            self.version.metadata.as_ref(),
753        )
754        .with_file_cache(file_cache)
755        .with_puffin_metadata_cache(puffin_metadata_cache)
756        .with_bloom_filter_cache(bloom_filter_index_cache)
757        .build(filters)
758        .inspect_err(|err| warn!(err; "Failed to build fulltext index applier"))
759        .ok()
760        .flatten()
761        .map(Arc::new)
762    }
763
764    /// Build the vector index applier from vector search request.
765    #[cfg(feature = "vector_index")]
766    fn build_vector_index_applier(&self) -> Option<VectorIndexApplierRef> {
767        let vector_search = self.request.vector_search.as_ref()?;
768
769        let file_cache = self.cache_strategy.write_cache().map(|w| w.file_cache());
770        let puffin_metadata_cache = self.cache_strategy.puffin_metadata_cache().cloned();
771        let vector_index_cache = self.cache_strategy.vector_index_cache().cloned();
772
773        let applier = VectorIndexApplier::new(
774            self.access_layer.table_dir().to_string(),
775            self.access_layer.path_type(),
776            self.access_layer.object_store().clone(),
777            self.access_layer.puffin_manager_factory().clone(),
778            vector_search.column_id,
779            vector_search.query_vector.clone(),
780            vector_search.metric,
781        )
782        .with_file_cache(file_cache)
783        .with_puffin_metadata_cache(puffin_metadata_cache)
784        .with_vector_index_cache(vector_index_cache);
785
786        Some(Arc::new(applier))
787    }
788}
789
790/// Returns true if the time range of a SST `file` matches the `predicate`.
791fn file_in_range(file: &FileHandle, predicate: &TimestampRange) -> bool {
792    if predicate == &TimestampRange::min_to_max() {
793        return true;
794    }
795    // end timestamp of a SST is inclusive.
796    let (start, end) = file.time_range();
797    let file_ts_range = TimestampRange::new_inclusive(Some(start), Some(end));
798    file_ts_range.intersects(predicate)
799}
800
801/// Common input for different scanners.
802pub struct ScanInput {
803    /// Region SST access layer.
804    access_layer: AccessLayerRef,
805    /// Maps projected Batches to RecordBatches.
806    pub(crate) mapper: Arc<FlatProjectionMapper>,
807    /// The columns to read from memtables and SSTs.
808    /// Notice this is different from the columns in `mapper` which are projected columns.
809    /// But this read columns might also include non-projected columns needed for filtering.
810    pub(crate) read_cols: ReadColumns,
811    /// Time range filter for time index.
812    pub(crate) time_range: Option<TimestampRange>,
813    /// Predicate to push down.
814    pub(crate) predicate: PredicateGroup,
815    /// Region partition expr applied at read time.
816    region_partition_expr: Option<PartitionExpr>,
817    /// Memtable range builders for memtables in the time range..
818    pub(crate) memtables: Vec<MemRangeBuilder>,
819    /// Handles to SST files to scan.
820    pub(crate) files: Vec<FileHandle>,
821    /// Cache.
822    pub(crate) cache_strategy: CacheStrategy,
823    /// Ignores file not found error.
824    ignore_file_not_found: bool,
825    /// Maximum number of SST files to scan concurrently.
826    pub(crate) max_concurrent_scan_files: usize,
827    /// Index appliers.
828    inverted_index_appliers: [Option<InvertedIndexApplierRef>; 2],
829    bloom_filter_index_appliers: [Option<BloomFilterIndexApplierRef>; 2],
830    fulltext_index_appliers: [Option<FulltextIndexApplierRef>; 2],
831    /// Vector index applier for KNN search.
832    #[cfg(feature = "vector_index")]
833    pub(crate) vector_index_applier: Option<VectorIndexApplierRef>,
834    /// Over-fetched k for vector index scan.
835    #[cfg(feature = "vector_index")]
836    pub(crate) vector_index_k: Option<usize>,
837    /// Start time of the query.
838    pub(crate) query_start: Option<Instant>,
839    /// The region is using append mode.
840    pub(crate) append_mode: bool,
841    /// Whether to remove deletion markers.
842    pub(crate) filter_deleted: bool,
843    /// Mode to merge duplicate rows.
844    pub(crate) merge_mode: MergeMode,
845    /// Hint to select rows from time series.
846    pub(crate) series_row_selector: Option<TimeSeriesRowSelector>,
847    /// Hint for the required distribution of the scanner.
848    pub(crate) distribution: Option<TimeSeriesDistribution>,
849    /// Whether the region's configured SST format is flat.
850    explain_flat_format: bool,
851    /// Snapshot upper bound bound at scan open and propagated back to the caller.
852    pub(crate) snapshot_sequence: Option<SequenceNumber>,
853    /// Whether this scan is for compaction.
854    pub(crate) compaction: bool,
855    /// Counters that should receive query-load metrics.
856    pub(crate) query_stat_counters: Option<RegionQueryStatCounters>,
857    #[cfg(feature = "enterprise")]
858    extension_ranges: Vec<BoxedExtensionRange>,
859}
860
861impl ScanInput {
862    /// Creates a new [ScanInput].
863    #[must_use]
864    pub(crate) fn new(access_layer: AccessLayerRef, mapper: FlatProjectionMapper) -> ScanInput {
865        ScanInput {
866            access_layer,
867            read_cols: mapper.read_columns().clone(),
868            mapper: Arc::new(mapper),
869            time_range: None,
870            predicate: PredicateGroup::default(),
871            region_partition_expr: None,
872            memtables: Vec::new(),
873            files: Vec::new(),
874            cache_strategy: CacheStrategy::Disabled,
875            ignore_file_not_found: false,
876            max_concurrent_scan_files: DEFAULT_MAX_CONCURRENT_SCAN_FILES,
877            inverted_index_appliers: [None, None],
878            bloom_filter_index_appliers: [None, None],
879            fulltext_index_appliers: [None, None],
880            #[cfg(feature = "vector_index")]
881            vector_index_applier: None,
882            #[cfg(feature = "vector_index")]
883            vector_index_k: None,
884            query_start: None,
885            append_mode: false,
886            filter_deleted: true,
887            merge_mode: MergeMode::default(),
888            series_row_selector: None,
889            distribution: None,
890            explain_flat_format: false,
891            snapshot_sequence: None,
892            compaction: false,
893            query_stat_counters: None,
894            #[cfg(feature = "enterprise")]
895            extension_ranges: Vec::new(),
896        }
897    }
898
899    /// Sets time range filter for time index.
900    #[must_use]
901    pub(crate) fn with_time_range(mut self, time_range: Option<TimestampRange>) -> Self {
902        self.time_range = time_range;
903        self
904    }
905
906    /// Sets predicate to push down.
907    #[must_use]
908    pub(crate) fn with_predicate(mut self, predicate: PredicateGroup) -> Self {
909        self.region_partition_expr = predicate.region_partition_expr().cloned();
910        self.predicate = predicate;
911        self
912    }
913
914    /// Sets memtable range builders.
915    #[must_use]
916    pub(crate) fn with_memtables(mut self, memtables: Vec<MemRangeBuilder>) -> Self {
917        self.memtables = memtables;
918        self
919    }
920
921    /// Sets files to read.
922    #[must_use]
923    pub(crate) fn with_files(mut self, files: Vec<FileHandle>) -> Self {
924        self.files = files;
925        self
926    }
927
928    /// Sets cache for this query.
929    #[must_use]
930    pub(crate) fn with_cache(mut self, cache: CacheStrategy) -> Self {
931        self.cache_strategy = cache;
932        self
933    }
934
935    /// Ignores file not found error.
936    #[must_use]
937    pub(crate) fn with_ignore_file_not_found(mut self, ignore: bool) -> Self {
938        self.ignore_file_not_found = ignore;
939        self
940    }
941
942    /// Sets maximum number of SST files to scan concurrently.
943    #[must_use]
944    pub(crate) fn with_max_concurrent_scan_files(
945        mut self,
946        max_concurrent_scan_files: usize,
947    ) -> Self {
948        self.max_concurrent_scan_files = max_concurrent_scan_files;
949        self
950    }
951
952    /// Sets inverted index appliers.
953    #[must_use]
954    pub(crate) fn with_inverted_index_appliers(
955        mut self,
956        appliers: [Option<InvertedIndexApplierRef>; 2],
957    ) -> Self {
958        self.inverted_index_appliers = appliers;
959        self
960    }
961
962    /// Sets bloom filter appliers.
963    #[must_use]
964    pub(crate) fn with_bloom_filter_index_appliers(
965        mut self,
966        appliers: [Option<BloomFilterIndexApplierRef>; 2],
967    ) -> Self {
968        self.bloom_filter_index_appliers = appliers;
969        self
970    }
971
972    /// Sets fulltext index appliers.
973    #[must_use]
974    pub(crate) fn with_fulltext_index_appliers(
975        mut self,
976        appliers: [Option<FulltextIndexApplierRef>; 2],
977    ) -> Self {
978        self.fulltext_index_appliers = appliers;
979        self
980    }
981
982    /// Sets vector index applier for KNN search.
983    #[cfg(feature = "vector_index")]
984    #[must_use]
985    pub(crate) fn with_vector_index_applier(
986        mut self,
987        applier: Option<VectorIndexApplierRef>,
988    ) -> Self {
989        self.vector_index_applier = applier;
990        self
991    }
992
993    /// Sets over-fetched k for vector index scan.
994    #[cfg(feature = "vector_index")]
995    #[must_use]
996    pub(crate) fn with_vector_index_k(mut self, k: Option<usize>) -> Self {
997        self.vector_index_k = k;
998        self
999    }
1000
1001    /// Sets start time of the query.
1002    #[must_use]
1003    pub(crate) fn with_start_time(mut self, now: Option<Instant>) -> Self {
1004        self.query_start = now;
1005        self
1006    }
1007
1008    #[must_use]
1009    pub(crate) fn with_append_mode(mut self, is_append_mode: bool) -> Self {
1010        self.append_mode = is_append_mode;
1011        self
1012    }
1013
1014    pub(crate) fn with_query_stat_counters(
1015        mut self,
1016        counters: Option<RegionQueryStatCounters>,
1017    ) -> Self {
1018        self.query_stat_counters = counters;
1019        self
1020    }
1021
1022    /// Sets whether to remove deletion markers during scan.
1023    #[must_use]
1024    pub(crate) fn with_filter_deleted(mut self, filter_deleted: bool) -> Self {
1025        self.filter_deleted = filter_deleted;
1026        self
1027    }
1028
1029    /// Sets the merge mode.
1030    #[must_use]
1031    pub(crate) fn with_merge_mode(mut self, merge_mode: MergeMode) -> Self {
1032        self.merge_mode = merge_mode;
1033        self
1034    }
1035
1036    /// Sets the distribution hint.
1037    #[must_use]
1038    pub(crate) fn with_distribution(
1039        mut self,
1040        distribution: Option<TimeSeriesDistribution>,
1041    ) -> Self {
1042        self.distribution = distribution;
1043        self
1044    }
1045
1046    /// Sets whether the region's configured SST format is flat for explain output.
1047    #[must_use]
1048    pub(crate) fn with_explain_flat_format(mut self, explain_flat_format: bool) -> Self {
1049        self.explain_flat_format = explain_flat_format;
1050        self
1051    }
1052
1053    /// Sets the time series row selector.
1054    #[must_use]
1055    pub(crate) fn with_series_row_selector(
1056        mut self,
1057        series_row_selector: Option<TimeSeriesRowSelector>,
1058    ) -> Self {
1059        self.series_row_selector = series_row_selector;
1060        self
1061    }
1062
1063    #[must_use]
1064    pub(crate) fn with_snapshot_sequence(
1065        mut self,
1066        snapshot_sequence: Option<SequenceNumber>,
1067    ) -> Self {
1068        self.snapshot_sequence = snapshot_sequence;
1069        self
1070    }
1071
1072    /// Sets whether this scan is for compaction.
1073    #[must_use]
1074    pub(crate) fn with_compaction(mut self, compaction: bool) -> Self {
1075        self.compaction = compaction;
1076        self
1077    }
1078
1079    /// Builds memtable ranges to scan by `index`.
1080    pub(crate) fn build_mem_ranges(&self, index: RowGroupIndex) -> SmallVec<[MemtableRange; 2]> {
1081        let memtable = &self.memtables[index.index];
1082        let mut ranges = SmallVec::new();
1083        memtable.build_ranges(index.row_group_index, &mut ranges);
1084        ranges
1085    }
1086
1087    pub(crate) fn predicate_for_file(&self, file: &FileHandle) -> Option<Predicate> {
1088        if self.should_skip_region_partition(file) {
1089            self.predicate.predicate_without_region().cloned()
1090        } else {
1091            self.predicate.predicate().cloned()
1092        }
1093    }
1094
1095    fn should_skip_region_partition(&self, file: &FileHandle) -> bool {
1096        match (
1097            self.region_partition_expr.as_ref(),
1098            file.meta_ref().partition_expr.as_ref(),
1099        ) {
1100            (Some(region_expr), Some(file_expr)) => region_expr == file_expr,
1101            _ => false,
1102        }
1103    }
1104
1105    /// Tries to build file-level pruning statistics using only the [FileHandle]'s manifest-level
1106    /// time range, without reading any parquet metadata.
1107    ///
1108    /// Returns `None` if timestamp unit conversion overflows (conservative: keep the file).
1109    fn try_file_level_pruning_stats(&self, file: &FileHandle) -> Option<FileLevelPruningStats> {
1110        let (ts_min, ts_max) = file.time_range();
1111        let time_index = self.mapper.metadata().time_index_column();
1112        let time_index_unit = time_index.column_schema.data_type.as_timestamp()?.unit();
1113
1114        // Convert file timestamps to the time index column's unit. Use `convert_to_ceil` for
1115        // the upper bound to avoid accidentally shrinking the manifest range.
1116        let min_ts = ts_min.convert_to(time_index_unit)?;
1117        let max_ts = ts_max.convert_to_ceil(time_index_unit)?;
1118
1119        Some(FileLevelPruningStats {
1120            min_scalar: timestamp_to_scalar_value(time_index_unit, Some(min_ts.value())),
1121            max_scalar: timestamp_to_scalar_value(time_index_unit, Some(max_ts.value())),
1122            time_index_col_name: time_index.column_schema.name.clone(),
1123        })
1124    }
1125
1126    /// Checks whether a file can be definitively pruned using only its manifest-level
1127    /// time range and the current predicate, without reading any parquet metadata.
1128    ///
1129    /// Returns `true` if [PruningStatistics] proves the file cannot contain matching rows.
1130    #[inline]
1131    pub(crate) fn can_manifest_prune_file(&self, file: &FileHandle) -> bool {
1132        let predicate = self.predicate_for_file(file);
1133        self.manifest_prunes_file(file, predicate.as_ref())
1134    }
1135
1136    fn manifest_prunes_file(&self, file: &FileHandle, predicate: Option<&Predicate>) -> bool {
1137        if let Some(pred) = predicate
1138            && !pred.is_empty()
1139            && let Some(file_level_stats) = self.try_file_level_pruning_stats(file)
1140        {
1141            let pruning_results = pred.prune_with_stats(
1142                &file_level_stats,
1143                self.mapper.metadata().schema.arrow_schema(),
1144            );
1145            pruning_results.first() == Some(&false)
1146        } else {
1147            false
1148        }
1149    }
1150
1151    /// Prunes a file to scan and returns the builder to build readers.
1152    ///
1153    /// This is the public entry point used by direct tests and non-pruner callers.
1154    /// It performs its own manifest-level pruning check internally.
1155    #[tracing::instrument(
1156        skip_all,
1157        fields(
1158            region_id = %self.region_metadata().region_id,
1159            file_id = %file.file_id()
1160        )
1161    )]
1162    pub async fn prune_file(
1163        &self,
1164        file: &FileHandle,
1165        pre_filter_mode: PreFilterMode,
1166        reader_metrics: &mut ReaderMetrics,
1167    ) -> Result<FileRangeBuilder> {
1168        let predicate = self.predicate_for_file(file);
1169
1170        // Early file-level pruning using manifest time range before any parquet metadata access.
1171        if self.manifest_prunes_file(file, predicate.as_ref()) {
1172            reader_metrics.filter_metrics.files_time_range_pruned += 1;
1173            return Ok(FileRangeBuilder::default());
1174        }
1175
1176        self.prune_file_after_manifest_check(file, pre_filter_mode, predicate, reader_metrics)
1177            .await
1178    }
1179
1180    /// Second half of `prune_file` — performs the actual parquet metadata /
1181    /// reader setup. Callers that already performed manifest-level pruning
1182    /// (e.g. the `Pruner` via its shared `manifest_pruned_files` cache) should
1183    /// call this directly to avoid a redundant manifest check.
1184    ///
1185    /// `predicate` is the result of `self.predicate_for_file(file)` computed
1186    /// externally so the caller can reuse it if needed.
1187    pub(crate) async fn prune_file_after_manifest_check(
1188        &self,
1189        file: &FileHandle,
1190        pre_filter_mode: PreFilterMode,
1191        predicate: Option<Predicate>,
1192        reader_metrics: &mut ReaderMetrics,
1193    ) -> Result<FileRangeBuilder> {
1194        let may_build_selective_row_selection = predicate.is_some();
1195        let decode_pk_values = !self.compaction
1196            && self
1197                .mapper
1198                .read_columns()
1199                .column_ids_iter()
1200                .any(|column_id| self.mapper.metadata().primary_key.contains(&column_id));
1201        let reader = self
1202            .access_layer
1203            .read_sst(file.clone())
1204            .predicate(predicate)
1205            .projection(Some(self.read_cols.clone()))
1206            .cache(self.cache_strategy.clone())
1207            .inverted_index_appliers(self.inverted_index_appliers.clone())
1208            .bloom_filter_index_appliers(self.bloom_filter_index_appliers.clone())
1209            .fulltext_index_appliers(self.fulltext_index_appliers.clone());
1210        let reader = if !self.compaction && may_build_selective_row_selection {
1211            reader.deferred_optional_page_index()
1212        } else {
1213            reader
1214        };
1215        #[cfg(feature = "vector_index")]
1216        let reader = {
1217            let mut reader = reader;
1218            reader =
1219                reader.vector_index_applier(self.vector_index_applier.clone(), self.vector_index_k);
1220            reader
1221        };
1222        let res = reader
1223            .expected_metadata(Some(self.mapper.metadata().clone()))
1224            .compaction(self.compaction)
1225            .pre_filter_mode(pre_filter_mode)
1226            .decode_primary_key_values(decode_pk_values)
1227            .build_reader_input(reader_metrics)
1228            .await;
1229        let read_input = match res {
1230            Ok(x) => x,
1231            Err(e) => {
1232                if e.is_object_not_found() && self.ignore_file_not_found {
1233                    error!(e; "File to scan does not exist, region_id: {}, file: {}", file.region_id(), file.file_id());
1234                    return Ok(FileRangeBuilder::default());
1235                } else {
1236                    return Err(e);
1237                }
1238            }
1239        };
1240
1241        let Some((mut file_range_ctx, selection)) = read_input else {
1242            return Ok(FileRangeBuilder::default());
1243        };
1244
1245        let need_compat = !compat::has_same_columns_and_pk_encoding(
1246            &self.mapper,
1247            file_range_ctx.read_format(),
1248            self.compaction,
1249        );
1250        if need_compat {
1251            // They have different schema. We need to adapt the batch first so the
1252            // mapper can convert it.
1253            let compat = FlatCompatBatch::try_new(
1254                &self.mapper,
1255                file_range_ctx.read_format(),
1256                self.compaction,
1257            )?;
1258            file_range_ctx.set_compat_batch(compat);
1259        }
1260        Ok(FileRangeBuilder::new(Arc::new(file_range_ctx), selection))
1261    }
1262
1263    /// Scans flat sources (RecordBatch streams) in parallel.
1264    ///
1265    /// # Panics if the input doesn't allow parallel scan.
1266    #[tracing::instrument(
1267        skip(self, sources, semaphore),
1268        fields(
1269            region_id = %self.region_metadata().region_id,
1270            source_count = sources.len()
1271        )
1272    )]
1273    pub(crate) fn create_parallel_flat_sources(
1274        &self,
1275        sources: Vec<BoxedRecordBatchStream>,
1276        semaphore: Arc<Semaphore>,
1277        channel_size: usize,
1278    ) -> Result<Vec<BoxedRecordBatchStream>> {
1279        if sources.len() <= 1 {
1280            return Ok(sources);
1281        }
1282
1283        // Spawn a task for each source.
1284        let sources = sources
1285            .into_iter()
1286            .map(|source| {
1287                let (sender, receiver) = mpsc::channel(channel_size);
1288                self.spawn_flat_scan_task(source, semaphore.clone(), sender);
1289                let stream = Box::pin(ReceiverStream::new(receiver));
1290                Box::pin(stream) as _
1291            })
1292            .collect();
1293        Ok(sources)
1294    }
1295
1296    /// Spawns a task to scan a flat source (RecordBatch stream) asynchronously.
1297    #[tracing::instrument(
1298        skip(self, input, semaphore, sender),
1299        fields(region_id = %self.region_metadata().region_id)
1300    )]
1301    pub(crate) fn spawn_flat_scan_task(
1302        &self,
1303        mut input: BoxedRecordBatchStream,
1304        semaphore: Arc<Semaphore>,
1305        sender: mpsc::Sender<Result<RecordBatch>>,
1306    ) {
1307        let region_id = self.region_metadata().region_id;
1308        let span = tracing::info_span!(
1309            "ScanInput::parallel_scan_task",
1310            region_id = %region_id,
1311            stream_kind = "flat"
1312        );
1313        common_runtime::spawn_query(
1314            async move {
1315                loop {
1316                    // We release the permit before sending result to avoid the task waiting on
1317                    // the channel with the permit held.
1318                    let maybe_batch = {
1319                        // Safety: We never close the semaphore.
1320                        let _permit = semaphore.acquire().await.unwrap();
1321                        input.next().await
1322                    };
1323                    match maybe_batch {
1324                        Some(Ok(batch)) => {
1325                            let _ = sender.send(Ok(batch)).await;
1326                        }
1327                        Some(Err(e)) => {
1328                            let _ = sender.send(Err(e)).await;
1329                            break;
1330                        }
1331                        None => break,
1332                    }
1333                }
1334            }
1335            .instrument(span),
1336        );
1337    }
1338
1339    pub(crate) fn total_rows(&self) -> usize {
1340        let rows_in_files: usize = self.files.iter().map(|f| f.num_rows()).sum();
1341        let rows_in_memtables: usize = self.memtables.iter().map(|m| m.stats().num_rows()).sum();
1342
1343        let rows = rows_in_files + rows_in_memtables;
1344        #[cfg(feature = "enterprise")]
1345        let rows = rows
1346            + self
1347                .extension_ranges
1348                .iter()
1349                .map(|x| x.num_rows())
1350                .sum::<u64>() as usize;
1351        rows
1352    }
1353
1354    pub(crate) fn predicate_group(&self) -> &PredicateGroup {
1355        &self.predicate
1356    }
1357
1358    /// Returns number of memtables to scan.
1359    pub(crate) fn num_memtables(&self) -> usize {
1360        self.memtables.len()
1361    }
1362
1363    /// Returns number of SST files to scan.
1364    pub(crate) fn num_files(&self) -> usize {
1365        self.files.len()
1366    }
1367
1368    /// Gets the file handle from a row group index.
1369    pub(crate) fn file_from_index(&self, index: RowGroupIndex) -> &FileHandle {
1370        let file_index = index.index - self.num_memtables();
1371        &self.files[file_index]
1372    }
1373
1374    pub fn region_metadata(&self) -> &RegionMetadataRef {
1375        self.mapper.metadata()
1376    }
1377
1378    fn range_pre_filter_mode(&self, source_count: usize) -> PreFilterMode {
1379        if source_count <= 1 {
1380            // Duplicated rows in the same source is not a normal case and we don't provide
1381            // strict dedup semantic (last_row/last_non_null) for it. We expect the duplicated rows
1382            // are exactly identical in the same source so we use PreFilterMode::All for
1383            // performance reason.
1384            return PreFilterMode::All;
1385        }
1386
1387        pre_filter_mode(self.append_mode, self.merge_mode)
1388    }
1389}
1390
1391#[cfg(feature = "enterprise")]
1392impl ScanInput {
1393    #[must_use]
1394    pub(crate) fn with_extension_ranges(self, extension_ranges: Vec<BoxedExtensionRange>) -> Self {
1395        Self {
1396            extension_ranges,
1397            ..self
1398        }
1399    }
1400
1401    #[cfg(feature = "enterprise")]
1402    pub(crate) fn extension_ranges(&self) -> &[BoxedExtensionRange] {
1403        &self.extension_ranges
1404    }
1405
1406    /// Get a boxed [ExtensionRange] by the index in all ranges.
1407    #[cfg(feature = "enterprise")]
1408    pub(crate) fn extension_range(&self, i: usize) -> &BoxedExtensionRange {
1409        &self.extension_ranges[i - self.num_memtables() - self.num_files()]
1410    }
1411}
1412
1413/// Lightweight [PruningStatistics] that only uses the file-level time range from manifest
1414/// metadata, avoiding any parquet metadata reads. Used for early file-level pruning before
1415/// accessing row-group-level statistics.
1416pub(crate) struct FileLevelPruningStats {
1417    /// Scalar value for the file's minimum timestamp in the time index column's unit.
1418    pub(crate) min_scalar: ScalarValue,
1419    /// Scalar value for the file's maximum timestamp in the time index column's unit.
1420    pub(crate) max_scalar: ScalarValue,
1421    /// Name of the time index column.
1422    pub(crate) time_index_col_name: String,
1423}
1424
1425impl PruningStatistics for FileLevelPruningStats {
1426    fn min_values(&self, column: &Column) -> Option<ArrayRef> {
1427        if column.name == self.time_index_col_name {
1428            ScalarValue::iter_to_array(std::iter::once(self.min_scalar.clone())).ok()
1429        } else {
1430            None
1431        }
1432    }
1433
1434    fn max_values(&self, column: &Column) -> Option<ArrayRef> {
1435        if column.name == self.time_index_col_name {
1436            ScalarValue::iter_to_array(std::iter::once(self.max_scalar.clone())).ok()
1437        } else {
1438            None
1439        }
1440    }
1441
1442    fn num_containers(&self) -> usize {
1443        1
1444    }
1445
1446    fn null_counts(&self, column: &Column) -> Option<ArrayRef> {
1447        if column.name == self.time_index_col_name {
1448            // The time index column is NOT NULL.
1449            Some(Arc::new(UInt64Array::from(vec![0u64])))
1450        } else {
1451            None
1452        }
1453    }
1454
1455    fn row_counts(&self, _column: &Column) -> Option<ArrayRef> {
1456        None
1457    }
1458
1459    fn contained(&self, _column: &Column, _values: &HashSet<ScalarValue>) -> Option<BooleanArray> {
1460        None
1461    }
1462}
1463
1464#[cfg(test)]
1465impl ScanInput {
1466    /// Returns SST file ids to scan.
1467    pub(crate) fn file_ids(&self) -> Vec<crate::sst::file::RegionFileId> {
1468        self.files.iter().map(|file| file.file_id()).collect()
1469    }
1470
1471    pub(crate) fn index_ids(&self) -> Vec<crate::sst::file::RegionIndexId> {
1472        self.files.iter().map(|file| file.index_id()).collect()
1473    }
1474}
1475
1476fn pre_filter_mode(append_mode: bool, merge_mode: MergeMode) -> PreFilterMode {
1477    if append_mode {
1478        return PreFilterMode::All;
1479    }
1480
1481    match merge_mode {
1482        MergeMode::LastRow => PreFilterMode::SkipFields,
1483        MergeMode::LastNonNull => PreFilterMode::SkipFields,
1484    }
1485}
1486
1487fn narrow_read_columns_by_json_type_hint(
1488    read_columns: &mut ReadColumns,
1489    json_type_hint: &HashMap<String, JsonNativeType>,
1490    metadata: &RegionMetadata,
1491) {
1492    if json_type_hint.is_empty() {
1493        return;
1494    }
1495
1496    for read_column in &mut read_columns.cols {
1497        let Some(column) = metadata.column_by_id(read_column.column_id) else {
1498            continue;
1499        };
1500        let column_name = &column.column_schema.name;
1501        let Some(json_type) = json_type_hint.get(column_name) else {
1502            continue;
1503        };
1504
1505        let mut paths = Vec::new();
1506        let mut current = vec![column_name.clone()];
1507        collect_json_nested_paths(json_type, &mut current, &mut paths);
1508        merge_nested_paths(&mut read_column.nested_paths, paths)
1509    }
1510}
1511
1512fn collect_json_nested_paths(
1513    json_type: &JsonNativeType,
1514    current: &mut NestedPath,
1515    paths: &mut Vec<NestedPath>,
1516) {
1517    match json_type {
1518        JsonNativeType::Object(fields) if !fields.is_empty() => {
1519            for (field, child) in fields {
1520                current.push(field.clone());
1521                collect_json_nested_paths(child, current, paths);
1522                current.pop();
1523            }
1524        }
1525        _ => paths.push(current.clone()),
1526    }
1527}
1528
1529/// Output of [build_scan_fingerprint]: the cache fingerprint plus the derived
1530/// implied time range used to decide whether the cache key can drop the time
1531/// predicates for a given partition (see `build_range_cache_key`).
1532pub(crate) struct ScanFingerprintBundle {
1533    pub(crate) fingerprint: ScanRequestFingerprint,
1534    /// `Some(r)` = all time-only predicates are guaranteed true on `r` (in the
1535    /// column's `TimeUnit`).
1536    /// `None`    = at least one time-only predicate could not be proven (e.g.
1537    /// `OR`), so the cache-key optimization is disabled for this scan.
1538    pub(crate) implied_time_range: Option<TimestampRange>,
1539}
1540
1541/// Builds a [ScanFingerprintBundle] from a [ScanInput] if the scan is eligible
1542/// for partition range caching.
1543pub(crate) fn build_scan_fingerprint(input: &ScanInput) -> Option<ScanFingerprintBundle> {
1544    let eligible = !input.compaction
1545        && !input.files.is_empty()
1546        && matches!(input.cache_strategy, CacheStrategy::EnableAll(_));
1547
1548    if !eligible {
1549        return None;
1550    }
1551
1552    let metadata = input.region_metadata();
1553    let tag_names: HashSet<&str> = metadata
1554        .column_metadatas
1555        .iter()
1556        .filter(|col| col.semantic_type == SemanticType::Tag)
1557        .map(|col| col.column_schema.name.as_str())
1558        .collect();
1559
1560    let time_index = metadata.time_index_column();
1561    let time_index_name = time_index.column_schema.name.clone();
1562    let ts_col_unit = time_index
1563        .column_schema
1564        .data_type
1565        .as_timestamp()
1566        .expect("Time index must have timestamp-compatible type")
1567        .unit();
1568
1569    let exprs = input
1570        .predicate_group()
1571        .predicate_without_region()
1572        .map(|predicate| predicate.exprs())
1573        .unwrap_or_default();
1574
1575    let mut filters = Vec::new();
1576    let mut time_only_exprs: Vec<&Expr> = Vec::new();
1577    let mut has_tag_filter = false;
1578    let mut columns = HashSet::new();
1579
1580    for expr in exprs {
1581        columns.clear();
1582        let is_time_only = match expr_to_columns(expr, &mut columns) {
1583            Ok(()) if !columns.is_empty() => {
1584                has_tag_filter |= columns
1585                    .iter()
1586                    .any(|col| tag_names.contains(col.name.as_str()));
1587                columns.iter().all(|col| col.name == time_index_name)
1588            }
1589            _ => false,
1590        };
1591
1592        // Route time-only exprs that the legacy extractor recognizes into
1593        // `time_only_exprs` so the implication walker
1594        // (`implied_time_range_from_exprs`, called below) can attempt to drop
1595        // them from the cache key when the partition's `FileTimeRange` is fully
1596        // covered, then stringify them into the fingerprint's `time_filters`
1597        // bucket. Time-only exprs that the extractor doesn't recognize stay in
1598        // `filters` and never get stripped — conservatively correct.
1599        if is_time_only
1600            && extract_time_range_from_expr(&time_index_name, ts_col_unit, expr).is_some()
1601        {
1602            time_only_exprs.push(expr);
1603        } else {
1604            filters.push(expr.to_string());
1605        }
1606    }
1607
1608    if !has_tag_filter {
1609        // We only cache requests that have tag filters to avoid caching all series.
1610        return None;
1611    }
1612
1613    let implied_time_range =
1614        implied_time_range_from_exprs(&time_index_name, ts_col_unit, &time_only_exprs);
1615    let mut time_filters: Vec<String> = time_only_exprs.iter().map(|e| e.to_string()).collect();
1616
1617    // Ensure the filters are sorted for consistent fingerprinting.
1618    filters.sort_unstable();
1619    time_filters.sort_unstable();
1620    let read_columns = input.read_cols.clone();
1621    let fingerprint = crate::read::range_cache::ScanRequestFingerprintBuilder {
1622        read_column_types: read_columns
1623            .column_ids_iter()
1624            .map(|id| {
1625                metadata
1626                    .column_by_id(id)
1627                    .map(|col| col.column_schema.data_type.clone())
1628            })
1629            .collect(),
1630        read_columns,
1631        filters,
1632        time_filters,
1633        series_row_selector: input.series_row_selector,
1634        append_mode: input.append_mode,
1635        filter_deleted: input.filter_deleted,
1636        merge_mode: input.merge_mode,
1637        partition_expr_version: metadata.partition_expr_version,
1638    }
1639    .build();
1640
1641    Some(ScanFingerprintBundle {
1642        fingerprint,
1643        implied_time_range,
1644    })
1645}
1646
1647/// Context shared by different streams from a scanner.
1648/// It contains the input and ranges to scan.
1649pub struct StreamContext {
1650    /// Input memtables and files.
1651    pub input: ScanInput,
1652    /// Metadata for partition ranges.
1653    pub(crate) ranges: Vec<RangeMeta>,
1654    /// Precomputed scan fingerprint for partition range caching.
1655    /// `None` when the scan is not eligible for caching.
1656    #[allow(dead_code)]
1657    pub(crate) scan_fingerprint: Option<ScanRequestFingerprint>,
1658    /// Implied range of every time-only predicate, in the time index column's
1659    /// `TimeUnit`. Used by `build_range_cache_key` to decide whether the
1660    /// partition's `FileTimeRange` is fully covered (allowing `time_filters`
1661    /// to be stripped from the cache key). `None` when caching is ineligible
1662    /// or when the implication walker bailed on an unsupported shape (e.g.
1663    /// `OR`).
1664    pub(crate) scan_implied_time_range: Option<TimestampRange>,
1665
1666    // Metrics:
1667    /// The start time of the query.
1668    pub(crate) query_start: Instant,
1669}
1670
1671impl StreamContext {
1672    /// Creates a new [StreamContext] for [SeqScan].
1673    pub(crate) fn seq_scan_ctx(input: ScanInput) -> Self {
1674        let query_start = input.query_start.unwrap_or_else(Instant::now);
1675        let ranges = RangeMeta::seq_scan_ranges(&input);
1676        READ_SST_COUNT.observe(input.num_files() as f64);
1677        let (scan_fingerprint, scan_implied_time_range) = match build_scan_fingerprint(&input) {
1678            Some(b) => (Some(b.fingerprint), b.implied_time_range),
1679            None => (None, None),
1680        };
1681
1682        Self {
1683            input,
1684            ranges,
1685            scan_fingerprint,
1686            scan_implied_time_range,
1687            query_start,
1688        }
1689    }
1690
1691    /// Creates a new [StreamContext] for [UnorderedScan].
1692    pub(crate) fn unordered_scan_ctx(input: ScanInput) -> Self {
1693        let query_start = input.query_start.unwrap_or_else(Instant::now);
1694        let ranges = RangeMeta::unordered_scan_ranges(&input);
1695        READ_SST_COUNT.observe(input.num_files() as f64);
1696        let (scan_fingerprint, scan_implied_time_range) = match build_scan_fingerprint(&input) {
1697            Some(b) => (Some(b.fingerprint), b.implied_time_range),
1698            None => (None, None),
1699        };
1700
1701        Self {
1702            input,
1703            ranges,
1704            scan_fingerprint,
1705            scan_implied_time_range,
1706            query_start,
1707        }
1708    }
1709
1710    /// Returns true if the index refers to a memtable.
1711    pub(crate) fn is_mem_range_index(&self, index: RowGroupIndex) -> bool {
1712        self.input.num_memtables() > index.index
1713    }
1714
1715    pub(crate) fn is_file_range_index(&self, index: RowGroupIndex) -> bool {
1716        !self.is_mem_range_index(index)
1717            && index.index < self.input.num_files() + self.input.num_memtables()
1718    }
1719
1720    pub(crate) fn range_pre_filter_mode(&self, part_range: &PartitionRange) -> PreFilterMode {
1721        let range_meta = &self.ranges[part_range.identifier];
1722        let source_count = range_meta.indices.len();
1723
1724        self.input.range_pre_filter_mode(source_count)
1725    }
1726
1727    /// Retrieves the partition ranges.
1728    pub(crate) fn partition_ranges(&self) -> Vec<PartitionRange> {
1729        self.ranges
1730            .iter()
1731            .enumerate()
1732            .map(|(idx, range_meta)| range_meta.new_partition_range(idx))
1733            .collect()
1734    }
1735
1736    /// Format the context for explain.
1737    pub(crate) fn format_for_explain(&self, verbose: bool, f: &mut fmt::Formatter) -> fmt::Result {
1738        let (mut num_mem_ranges, mut num_file_ranges, mut num_other_ranges) = (0, 0, 0);
1739        for range_meta in &self.ranges {
1740            for idx in &range_meta.row_group_indices {
1741                if self.is_mem_range_index(*idx) {
1742                    num_mem_ranges += 1;
1743                } else if self.is_file_range_index(*idx) {
1744                    num_file_ranges += 1;
1745                } else {
1746                    num_other_ranges += 1;
1747                }
1748            }
1749        }
1750        if verbose {
1751            write!(f, "{{")?;
1752        }
1753        write!(
1754            f,
1755            r#""partition_count":{{"count":{}, "mem_ranges":{}, "files":{}, "file_ranges":{}"#,
1756            self.ranges.len(),
1757            num_mem_ranges,
1758            self.input.num_files(),
1759            num_file_ranges,
1760        )?;
1761        if num_other_ranges > 0 {
1762            write!(f, r#", "other_ranges":{}"#, num_other_ranges)?;
1763        }
1764        write!(f, "}}")?;
1765
1766        if let Some(selector) = &self.input.series_row_selector {
1767            write!(f, ", \"selector\":\"{}\"", selector)?;
1768        }
1769        if let Some(distribution) = &self.input.distribution {
1770            write!(f, ", \"distribution\":\"{}\"", distribution)?;
1771        }
1772
1773        if verbose {
1774            self.format_verbose_content(f)?;
1775        }
1776
1777        Ok(())
1778    }
1779
1780    fn format_verbose_content(&self, f: &mut fmt::Formatter) -> fmt::Result {
1781        struct FileWrapper<'a> {
1782            file: &'a FileHandle,
1783        }
1784
1785        impl fmt::Debug for FileWrapper<'_> {
1786            fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1787                let (start, end) = self.file.time_range();
1788                write!(
1789                    f,
1790                    r#"{{"file_id":"{}","time_range_start":"{}::{}","time_range_end":"{}::{}","rows":{},"size":{},"index_size":{}}}"#,
1791                    self.file.file_id(),
1792                    start.value(),
1793                    start.unit(),
1794                    end.value(),
1795                    end.unit(),
1796                    self.file.num_rows(),
1797                    self.file.size(),
1798                    self.file.index_size()
1799                )
1800            }
1801        }
1802
1803        struct InputWrapper<'a> {
1804            input: &'a ScanInput,
1805        }
1806
1807        #[cfg(feature = "enterprise")]
1808        impl InputWrapper<'_> {
1809            fn format_extension_ranges(&self, f: &mut fmt::Formatter) -> fmt::Result {
1810                if self.input.extension_ranges.is_empty() {
1811                    return Ok(());
1812                }
1813
1814                let mut delimiter = "";
1815                write!(f, ", extension_ranges: [")?;
1816                for range in self.input.extension_ranges() {
1817                    write!(f, "{}{:?}", delimiter, range)?;
1818                    delimiter = ", ";
1819                }
1820                write!(f, "]")?;
1821                Ok(())
1822            }
1823        }
1824
1825        impl fmt::Debug for InputWrapper<'_> {
1826            fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1827                let output_schema = self.input.mapper.output_schema();
1828                if !output_schema.is_empty() {
1829                    let names: Vec<_> = output_schema
1830                        .column_schemas()
1831                        .iter()
1832                        .map(|col| &col.name)
1833                        .collect();
1834                    write!(f, ", \"projection\": {:?}", names)?;
1835                }
1836                if let Some(predicate) = &self.input.predicate.predicate() {
1837                    if !predicate.exprs().is_empty() {
1838                        let exprs: Vec<_> =
1839                            predicate.exprs().iter().map(|e| e.to_string()).collect();
1840                        write!(f, ", \"filters\": {:?}", exprs)?;
1841                    }
1842                    if !predicate.dyn_filters().is_empty() {
1843                        let dyn_filters: Vec<_> = predicate
1844                            .dyn_filters()
1845                            .iter()
1846                            .map(|f| format!("{}", f))
1847                            .collect();
1848                        write!(f, ", \"dyn_filters\": {:?}", dyn_filters)?;
1849                    }
1850                }
1851                #[cfg(feature = "vector_index")]
1852                if let Some(vector_index_k) = self.input.vector_index_k {
1853                    write!(f, ", \"vector_index_k\": {}", vector_index_k)?;
1854                }
1855                if !self.input.files.is_empty() {
1856                    write!(f, ", \"files\": ")?;
1857                    f.debug_list()
1858                        .entries(self.input.files.iter().map(|file| FileWrapper { file }))
1859                        .finish()?;
1860                }
1861                write!(f, ", \"flat_format\": {}", self.input.explain_flat_format)?;
1862                #[cfg(feature = "enterprise")]
1863                self.format_extension_ranges(f)?;
1864
1865                Ok(())
1866            }
1867        }
1868
1869        write!(f, "{:?}", InputWrapper { input: &self.input })
1870    }
1871
1872    /// Add new dynamic filters to the predicates.
1873    /// Safe after stream creation; in-flight reads may still observe an older snapshot.
1874    pub(crate) fn add_dyn_filter_to_predicate(
1875        self: &Arc<Self>,
1876        filter_exprs: Vec<Arc<dyn datafusion::physical_plan::PhysicalExpr>>,
1877    ) -> Vec<bool> {
1878        let mut supported = Vec::with_capacity(filter_exprs.len());
1879        let filter_expr = filter_exprs
1880            .into_iter()
1881            .filter_map(|expr| {
1882                if let Ok(dyn_filter) = (expr as Arc<dyn std::any::Any + Send + Sync + 'static>)
1883                .downcast::<datafusion::physical_plan::expressions::DynamicFilterPhysicalExpr>()
1884            {
1885                supported.push(true);
1886                Some(dyn_filter)
1887            } else {
1888                supported.push(false);
1889                None
1890            }
1891            })
1892            .collect();
1893        self.input.predicate.add_dyn_filters(filter_expr);
1894        supported
1895    }
1896}
1897
1898/// Predicates to evaluate.
1899/// It only keeps filters that [SimpleFilterEvaluator] supports.
1900#[derive(Clone, Default)]
1901pub struct PredicateGroup {
1902    time_filters: Option<Arc<Vec<SimpleFilterEvaluator>>>,
1903    /// Predicate that includes request filters and region partition expr (if any).
1904    predicate_all: Predicate,
1905    /// Predicate that only includes request filters.
1906    predicate_without_region: Predicate,
1907    /// Region partition expression restored from metadata.
1908    region_partition_expr: Option<PartitionExpr>,
1909}
1910
1911impl PredicateGroup {
1912    /// Creates a new `PredicateGroup` from exprs according to the metadata.
1913    pub fn new(metadata: &RegionMetadata, exprs: &[Expr]) -> Result<Self> {
1914        let mut combined_exprs = exprs.to_vec();
1915        let mut region_partition_expr = None;
1916
1917        if let Some(expr_json) = metadata.partition_expr.as_ref()
1918            && !expr_json.is_empty()
1919            && let Some(expr) = PartitionExpr::from_json_str(expr_json)
1920                .context(InvalidPartitionExprSnafu { expr: expr_json })?
1921        {
1922            let logical_expr = expr
1923                .try_as_logical_expr()
1924                .context(InvalidPartitionExprSnafu {
1925                    expr: expr_json.clone(),
1926                })?;
1927
1928            combined_exprs.push(logical_expr);
1929            region_partition_expr = Some(expr);
1930        }
1931
1932        let mut time_filters = Vec::with_capacity(combined_exprs.len());
1933        // Columns in the expr.
1934        let mut columns = HashSet::new();
1935        for expr in &combined_exprs {
1936            columns.clear();
1937            let Some(filter) = Self::expr_to_filter(expr, metadata, &mut columns) else {
1938                continue;
1939            };
1940            time_filters.push(filter);
1941        }
1942        let time_filters = if time_filters.is_empty() {
1943            None
1944        } else {
1945            Some(Arc::new(time_filters))
1946        };
1947
1948        let predicate_all = Predicate::new(combined_exprs);
1949        let predicate_without_region = Predicate::new(exprs.to_vec());
1950
1951        Ok(Self {
1952            time_filters,
1953            predicate_all,
1954            predicate_without_region,
1955            region_partition_expr,
1956        })
1957    }
1958
1959    /// Returns time filters.
1960    pub(crate) fn time_filters(&self) -> Option<Arc<Vec<SimpleFilterEvaluator>>> {
1961        self.time_filters.clone()
1962    }
1963
1964    /// Returns predicate of all exprs (including region partition expr if present).
1965    pub(crate) fn predicate(&self) -> Option<&Predicate> {
1966        if self.predicate_all.is_empty() {
1967            None
1968        } else {
1969            Some(&self.predicate_all)
1970        }
1971    }
1972
1973    /// Returns predicate that excludes region partition expr.
1974    pub(crate) fn predicate_without_region(&self) -> Option<&Predicate> {
1975        if self.predicate_without_region.is_empty() {
1976            None
1977        } else {
1978            Some(&self.predicate_without_region)
1979        }
1980    }
1981
1982    /// Add dynamic filters in the predicates.
1983    pub(crate) fn add_dyn_filters(&self, dyn_filters: Vec<Arc<DynamicFilterPhysicalExpr>>) {
1984        self.predicate_all.add_dyn_filters(dyn_filters.clone());
1985        self.predicate_without_region.add_dyn_filters(dyn_filters);
1986    }
1987
1988    /// Returns the region partition expr from metadata, if any.
1989    pub(crate) fn region_partition_expr(&self) -> Option<&PartitionExpr> {
1990        self.region_partition_expr.as_ref()
1991    }
1992
1993    fn expr_to_filter(
1994        expr: &Expr,
1995        metadata: &RegionMetadata,
1996        columns: &mut HashSet<Column>,
1997    ) -> Option<SimpleFilterEvaluator> {
1998        columns.clear();
1999        // `expr_to_columns` won't return error.
2000        // We still ignore these expressions for safety.
2001        expr_to_columns(expr, columns).ok()?;
2002        if columns.len() > 1 {
2003            // Simple filter doesn't support multiple columns.
2004            return None;
2005        }
2006        let column = columns.iter().next()?;
2007        let column_meta = metadata.column_by_name(&column.name)?;
2008        if column_meta.semantic_type == SemanticType::Timestamp {
2009            SimpleFilterEvaluator::try_new(expr)
2010        } else {
2011            None
2012        }
2013    }
2014}
2015
2016#[cfg(test)]
2017mod tests {
2018    use std::sync::Arc;
2019
2020    use common_time::timestamp::{TimeUnit, Timestamp};
2021    use datafusion::physical_plan::expressions::{
2022        binary as physical_binary, col as physical_col, lit as physical_lit,
2023    };
2024    use datafusion_common::ScalarValue;
2025    use datafusion_expr::{Operator, col, lit};
2026    use datatypes::arrow::datatypes::{
2027        DataType as ArrowDataType, Field, Schema as ArrowSchema, TimeUnit as ArrowTimeUnit,
2028    };
2029    use datatypes::prelude::ConcreteDataType;
2030    use datatypes::schema::ColumnSchema;
2031    use datatypes::types::json_type::JsonObjectType;
2032    use datatypes::value::Value;
2033    use partition::expr::col as partition_col;
2034    use store_api::metadata::{ColumnMetadata, RegionMetadataBuilder};
2035    use store_api::storage::{RegionId, TimeSeriesDistribution, TimeSeriesRowSelector};
2036
2037    use super::*;
2038    use crate::cache::CacheManager;
2039    use crate::error::InvalidMetadataSnafu;
2040    use crate::read::range_cache::ScanRequestFingerprintBuilder;
2041    use crate::read::read_columns::ReadColumn;
2042    use crate::sst::file::FileMeta;
2043    use crate::test_util::memtable_util::metadata_with_primary_key;
2044    use crate::test_util::scheduler_util::SchedulerEnv;
2045
2046    async fn new_scan_input(metadata: RegionMetadataRef, filters: Vec<Expr>) -> ScanInput {
2047        let env = SchedulerEnv::new().await;
2048        let mapper = FlatProjectionMapper::new(&metadata, [0, 2, 3]).unwrap();
2049        let predicate = PredicateGroup::new(metadata.as_ref(), &filters).unwrap();
2050        let file = FileHandle::new(
2051            crate::sst::file::FileMeta::default(),
2052            Arc::new(crate::sst::file_purger::NoopFilePurger),
2053        );
2054
2055        ScanInput::new(env.access_layer.clone(), mapper)
2056            .with_predicate(predicate)
2057            .with_cache(CacheStrategy::EnableAll(Arc::new(
2058                CacheManager::builder()
2059                    .range_result_cache_size(1024)
2060                    .build(),
2061            )))
2062            .with_files(vec![file])
2063    }
2064
2065    /// Helper to create a timestamp millisecond literal.
2066    fn ts_lit(val: i64) -> datafusion_expr::Expr {
2067        lit(ScalarValue::TimestampMillisecond(Some(val), None))
2068    }
2069
2070    fn metadata_with_time_index_unit(unit: TimeUnit) -> RegionMetadataRef {
2071        let mut builder = RegionMetadataBuilder::new(RegionId::new(123, 456));
2072        builder
2073            .push_column_metadata(ColumnMetadata {
2074                column_schema: ColumnSchema::new(
2075                    "k0".to_string(),
2076                    ConcreteDataType::string_datatype(),
2077                    false,
2078                ),
2079                semantic_type: SemanticType::Tag,
2080                column_id: 0,
2081            })
2082            .push_column_metadata(ColumnMetadata {
2083                column_schema: ColumnSchema::new(
2084                    "k1".to_string(),
2085                    ConcreteDataType::uint32_datatype(),
2086                    false,
2087                ),
2088                semantic_type: SemanticType::Tag,
2089                column_id: 1,
2090            })
2091            .push_column_metadata(ColumnMetadata {
2092                column_schema: ColumnSchema::new(
2093                    "ts".to_string(),
2094                    ConcreteDataType::timestamp_datatype(unit),
2095                    false,
2096                ),
2097                semantic_type: SemanticType::Timestamp,
2098                column_id: 2,
2099            })
2100            .push_column_metadata(ColumnMetadata {
2101                column_schema: ColumnSchema::new(
2102                    "v0".to_string(),
2103                    ConcreteDataType::int64_datatype(),
2104                    true,
2105                ),
2106                semantic_type: SemanticType::Field,
2107                column_id: 3,
2108            })
2109            .primary_key(vec![0, 1]);
2110
2111        Arc::new(builder.build().unwrap())
2112    }
2113
2114    fn file_handle_with_time_range(start: Timestamp, end: Timestamp) -> FileHandle {
2115        FileHandle::new(
2116            FileMeta {
2117                time_range: (start, end),
2118                ..Default::default()
2119            },
2120            Arc::new(crate::sst::file_purger::NoopFilePurger),
2121        )
2122    }
2123
2124    #[test]
2125    fn test_fill_json_nested_paths_from_hint() -> Result<()> {
2126        fn json_projection_test_metadata() -> Result<RegionMetadataRef> {
2127            let mut builder = RegionMetadataBuilder::new(RegionId::new(1024, 0));
2128            builder
2129                .push_column_metadata(ColumnMetadata {
2130                    column_schema: ColumnSchema::new(
2131                        "tag".to_string(),
2132                        ConcreteDataType::string_datatype(),
2133                        true,
2134                    ),
2135                    semantic_type: SemanticType::Tag,
2136                    column_id: 0,
2137                })
2138                .push_column_metadata(ColumnMetadata {
2139                    column_schema: ColumnSchema::new(
2140                        "j".to_string(),
2141                        ConcreteDataType::json2(JsonNativeType::Object(JsonObjectType::new())),
2142                        true,
2143                    ),
2144                    semantic_type: SemanticType::Field,
2145                    column_id: 1,
2146                })
2147                .push_column_metadata(ColumnMetadata {
2148                    column_schema: ColumnSchema::new(
2149                        "ts".to_string(),
2150                        ConcreteDataType::timestamp_millisecond_datatype(),
2151                        false,
2152                    ),
2153                    semantic_type: SemanticType::Timestamp,
2154                    column_id: 2,
2155                });
2156            builder.primary_key(vec![0]);
2157            builder.build().context(InvalidMetadataSnafu).map(Arc::new)
2158        }
2159
2160        let metadata = json_projection_test_metadata()?;
2161        let hint = HashMap::from([(
2162            "j".to_string(),
2163            JsonNativeType::Object(JsonObjectType::from([
2164                ("a".to_string(), JsonNativeType::i64()),
2165                (
2166                    "b".to_string(),
2167                    JsonNativeType::Object(JsonObjectType::from([(
2168                        "c".to_string(),
2169                        JsonNativeType::String,
2170                    )])),
2171                ),
2172            ])),
2173        )]);
2174
2175        fn nested_path(parts: &[&str]) -> NestedPath {
2176            parts.iter().map(|part| part.to_string()).collect()
2177        }
2178
2179        let mut read_columns = ReadColumns {
2180            cols: vec![ReadColumn::new(1, vec![]), ReadColumn::new(0, vec![])],
2181        };
2182        narrow_read_columns_by_json_type_hint(&mut read_columns, &hint, metadata.as_ref());
2183        assert_eq!(
2184            read_columns,
2185            ReadColumns {
2186                cols: vec![
2187                    ReadColumn::new(
2188                        1,
2189                        vec![nested_path(&["j", "a"]), nested_path(&["j", "b", "c"])]
2190                    ),
2191                    ReadColumn::new(0, vec![])
2192                ]
2193            }
2194        );
2195
2196        let mut read_columns = ReadColumns {
2197            cols: vec![ReadColumn::new(0, vec![])],
2198        };
2199        narrow_read_columns_by_json_type_hint(&mut read_columns, &hint, metadata.as_ref());
2200        assert_eq!(
2201            read_columns,
2202            ReadColumns {
2203                cols: vec![ReadColumn::new(0, vec![])]
2204            }
2205        );
2206        Ok(())
2207    }
2208
2209    #[tokio::test]
2210    async fn test_build_scan_fingerprint_for_eligible_scan() {
2211        let metadata = Arc::new(metadata_with_primary_key(vec![0, 1], false));
2212        let input = new_scan_input(
2213            metadata.clone(),
2214            vec![
2215                col("ts").gt_eq(ts_lit(1000)),
2216                col("k0").eq(lit("foo")),
2217                col("v0").gt(lit(1)),
2218            ],
2219        )
2220        .await
2221        .with_distribution(Some(TimeSeriesDistribution::PerSeries))
2222        .with_series_row_selector(Some(TimeSeriesRowSelector::LastRow))
2223        .with_merge_mode(MergeMode::LastNonNull)
2224        .with_filter_deleted(false);
2225
2226        let fingerprint = build_scan_fingerprint(&input).unwrap();
2227
2228        let expected = ScanRequestFingerprintBuilder {
2229            read_columns: input.read_cols,
2230            read_column_types: vec![
2231                metadata
2232                    .column_by_id(0)
2233                    .map(|col| col.column_schema.data_type.clone()),
2234                metadata
2235                    .column_by_id(2)
2236                    .map(|col| col.column_schema.data_type.clone()),
2237                metadata
2238                    .column_by_id(3)
2239                    .map(|col| col.column_schema.data_type.clone()),
2240            ],
2241            filters: vec![
2242                col("k0").eq(lit("foo")).to_string(),
2243                col("v0").gt(lit(1)).to_string(),
2244            ],
2245            time_filters: vec![col("ts").gt_eq(ts_lit(1000)).to_string()],
2246            series_row_selector: Some(TimeSeriesRowSelector::LastRow),
2247            append_mode: false,
2248            filter_deleted: false,
2249            merge_mode: MergeMode::LastNonNull,
2250            partition_expr_version: 0,
2251        }
2252        .build();
2253        assert_eq!(expected, fingerprint.fingerprint);
2254    }
2255
2256    #[tokio::test]
2257    async fn test_build_scan_fingerprint_requires_tag_filter() {
2258        let metadata = Arc::new(metadata_with_primary_key(vec![0, 1], false));
2259        let input = new_scan_input(
2260            metadata,
2261            vec![col("ts").gt_eq(lit(1000)), col("v0").gt(lit(1))],
2262        )
2263        .await;
2264
2265        assert!(build_scan_fingerprint(&input).is_none());
2266    }
2267
2268    #[tokio::test]
2269    async fn test_build_scan_fingerprint_respects_scan_eligibility() {
2270        let metadata = Arc::new(metadata_with_primary_key(vec![0, 1], false));
2271        let filters = vec![col("k0").eq(lit("foo"))];
2272
2273        let disabled = ScanInput::new(
2274            SchedulerEnv::new().await.access_layer.clone(),
2275            FlatProjectionMapper::new(&metadata, [0, 2, 3].into_iter()).unwrap(),
2276        )
2277        .with_predicate(PredicateGroup::new(metadata.as_ref(), &filters).unwrap());
2278        assert!(build_scan_fingerprint(&disabled).is_none());
2279
2280        let compaction = new_scan_input(metadata.clone(), filters.clone())
2281            .await
2282            .with_compaction(true);
2283        assert!(build_scan_fingerprint(&compaction).is_none());
2284
2285        // No files to read.
2286        let no_files = new_scan_input(metadata, filters).await.with_files(vec![]);
2287        assert!(build_scan_fingerprint(&no_files).is_none());
2288    }
2289
2290    #[tokio::test]
2291    async fn test_build_scan_fingerprint_tracks_schema_and_partition_expr_changes() {
2292        let base = metadata_with_primary_key(vec![0, 1], false);
2293        let mut builder = RegionMetadataBuilder::from_existing(base);
2294        let partition_expr = partition_col("k0")
2295            .gt_eq(Value::String("foo".into()))
2296            .as_json_str()
2297            .unwrap();
2298        builder.partition_expr_json(Some(partition_expr));
2299        let metadata = Arc::new(builder.build_without_validation().unwrap());
2300
2301        let input = new_scan_input(metadata.clone(), vec![col("k0").eq(lit("foo"))]).await;
2302        let fingerprint = build_scan_fingerprint(&input).unwrap();
2303
2304        let expected = ScanRequestFingerprintBuilder {
2305            read_columns: input.read_cols,
2306            read_column_types: vec![
2307                metadata
2308                    .column_by_id(0)
2309                    .map(|col| col.column_schema.data_type.clone()),
2310                metadata
2311                    .column_by_id(2)
2312                    .map(|col| col.column_schema.data_type.clone()),
2313                metadata
2314                    .column_by_id(3)
2315                    .map(|col| col.column_schema.data_type.clone()),
2316            ],
2317            filters: vec![col("k0").eq(lit("foo")).to_string()],
2318            time_filters: vec![],
2319            series_row_selector: None,
2320            append_mode: false,
2321            filter_deleted: true,
2322            merge_mode: MergeMode::LastRow,
2323            partition_expr_version: metadata.partition_expr_version,
2324        }
2325        .build();
2326        assert_eq!(expected, fingerprint.fingerprint);
2327        assert_ne!(0, metadata.partition_expr_version);
2328    }
2329
2330    #[test]
2331    fn test_update_dyn_filters_with_empty_base_predicates() {
2332        let metadata = Arc::new(metadata_with_primary_key(vec![0, 1], false));
2333        let predicate_group = PredicateGroup::new(metadata.as_ref(), &[]).unwrap();
2334        assert!(predicate_group.predicate().is_none());
2335        assert!(predicate_group.predicate_without_region().is_none());
2336
2337        let dyn_filter = Arc::new(DynamicFilterPhysicalExpr::new(vec![], physical_lit(false)));
2338        predicate_group.add_dyn_filters(vec![dyn_filter]);
2339
2340        let predicate_all = predicate_group.predicate().unwrap();
2341        assert!(predicate_all.exprs().is_empty());
2342        assert_eq!(1, predicate_all.dyn_filters().len());
2343
2344        let predicate_without_region = predicate_group.predicate_without_region().unwrap();
2345        assert!(predicate_without_region.exprs().is_empty());
2346        assert_eq!(1, predicate_without_region.dyn_filters().len());
2347    }
2348
2349    #[test]
2350    fn test_file_level_pruning_stats_prunes_old_file() {
2351        let ts_col_name = "ts";
2352        let predicate = Predicate::new(vec![col(ts_col_name).gt(ts_lit(1000))]);
2353        let arrow_schema = Arc::new(ArrowSchema::new(vec![Field::new(
2354            ts_col_name,
2355            ArrowDataType::Timestamp(ArrowTimeUnit::Millisecond, None),
2356            false,
2357        )]));
2358
2359        // File with time range [0ms, 500ms] is completely before `ts > 1000ms`.
2360        let stats = FileLevelPruningStats {
2361            min_scalar: ScalarValue::TimestampMillisecond(Some(0), None),
2362            max_scalar: ScalarValue::TimestampMillisecond(Some(500), None),
2363            time_index_col_name: ts_col_name.to_string(),
2364        };
2365        assert_eq!(
2366            vec![false],
2367            predicate.prune_with_stats(&stats, &arrow_schema)
2368        );
2369
2370        // File with time range [0ms, 2000ms] overlaps `ts > 1000ms`, so keep it.
2371        let stats = FileLevelPruningStats {
2372            min_scalar: ScalarValue::TimestampMillisecond(Some(0), None),
2373            max_scalar: ScalarValue::TimestampMillisecond(Some(2000), None),
2374            time_index_col_name: ts_col_name.to_string(),
2375        };
2376        assert_eq!(
2377            vec![true],
2378            predicate.prune_with_stats(&stats, &arrow_schema)
2379        );
2380    }
2381
2382    #[test]
2383    fn test_file_level_pruning_stats_no_predicate_keeps_all() {
2384        let predicate = Predicate::new(vec![]);
2385        assert!(predicate.is_empty());
2386
2387        let stats = FileLevelPruningStats {
2388            min_scalar: ScalarValue::TimestampMillisecond(Some(0), None),
2389            max_scalar: ScalarValue::TimestampMillisecond(Some(500), None),
2390            time_index_col_name: "ts".to_string(),
2391        };
2392        let arrow_schema = Arc::new(ArrowSchema::new(Vec::<Field>::new()));
2393        assert_eq!(
2394            vec![true],
2395            predicate.prune_with_stats(&stats, &arrow_schema)
2396        );
2397    }
2398
2399    #[tokio::test]
2400    async fn test_file_level_pruning_stats_ceil_max_unit_conversion() {
2401        let metadata = metadata_with_time_index_unit(TimeUnit::Millisecond);
2402        let input = new_scan_input(metadata, vec![]).await;
2403        let file = file_handle_with_time_range(
2404            Timestamp::new(1_000_001, TimeUnit::Nanosecond),
2405            Timestamp::new(1_000_001, TimeUnit::Nanosecond),
2406        );
2407
2408        let stats = input.try_file_level_pruning_stats(&file).unwrap();
2409        assert_eq!(
2410            ScalarValue::TimestampMillisecond(Some(1), None),
2411            stats.min_scalar
2412        );
2413        assert_eq!(
2414            ScalarValue::TimestampMillisecond(Some(2), None),
2415            stats.max_scalar
2416        );
2417
2418        // The actual max timestamp is slightly greater than 1ms. It must be kept for `ts > 1ms`.
2419        let predicate = Predicate::new(vec![col("ts").gt(ts_lit(1))]);
2420        assert_eq!(
2421            vec![true],
2422            predicate.prune_with_stats(&stats, input.mapper.metadata().schema.arrow_schema())
2423        );
2424    }
2425
2426    #[tokio::test]
2427    async fn test_file_level_pruning_stats_overflow_keeps_file() {
2428        let metadata = metadata_with_time_index_unit(TimeUnit::Nanosecond);
2429        let input = new_scan_input(metadata, vec![]).await;
2430        let file = file_handle_with_time_range(
2431            Timestamp::new(0, TimeUnit::Second),
2432            Timestamp::new(i64::MAX, TimeUnit::Second),
2433        );
2434
2435        assert!(input.try_file_level_pruning_stats(&file).is_none());
2436    }
2437
2438    #[test]
2439    fn test_file_level_pruning_stats_keeps_inclusive_boundary() {
2440        let ts_col_name = "ts";
2441        let predicate = Predicate::new(vec![col(ts_col_name).gt_eq(ts_lit(1000))]);
2442        let arrow_schema = Arc::new(ArrowSchema::new(vec![Field::new(
2443            ts_col_name,
2444            ArrowDataType::Timestamp(ArrowTimeUnit::Millisecond, None),
2445            false,
2446        )]));
2447        let stats = FileLevelPruningStats {
2448            min_scalar: ScalarValue::TimestampMillisecond(Some(0), None),
2449            max_scalar: ScalarValue::TimestampMillisecond(Some(1000), None),
2450            time_index_col_name: ts_col_name.to_string(),
2451        };
2452
2453        assert_eq!(
2454            vec![true],
2455            predicate.prune_with_stats(&stats, &arrow_schema)
2456        );
2457    }
2458
2459    #[tokio::test]
2460    async fn test_file_level_pruning_with_dyn_filter_only_predicate() {
2461        let metadata = Arc::new(metadata_with_primary_key(vec![0, 1], false));
2462        let mapper = FlatProjectionMapper::new(&metadata, [0, 2, 3]).unwrap();
2463        let predicate_group = PredicateGroup::new(metadata.as_ref(), &[]).unwrap();
2464        predicate_group.add_dyn_filters(vec![Arc::new(DynamicFilterPhysicalExpr::new(
2465            vec![],
2466            physical_lit(false),
2467        ))]);
2468        let input = ScanInput::new(SchedulerEnv::new().await.access_layer.clone(), mapper)
2469            .with_predicate(predicate_group);
2470        let file = file_handle_with_time_range(
2471            Timestamp::new_millisecond(0),
2472            Timestamp::new_millisecond(1000),
2473        );
2474        let mut reader_metrics = ReaderMetrics::default();
2475
2476        let builder = input
2477            .prune_file(&file, PreFilterMode::SkipFields, &mut reader_metrics)
2478            .await
2479            .unwrap();
2480
2481        assert_eq!(1, reader_metrics.filter_metrics.files_time_range_pruned);
2482        let mut ranges = SmallVec::new();
2483        builder.build_ranges(-1, &mut ranges);
2484        assert!(ranges.is_empty());
2485    }
2486
2487    #[tokio::test]
2488    async fn test_manifest_pruning_observes_dynamic_filter_update() {
2489        let metadata = Arc::new(metadata_with_primary_key(vec![0, 1], false));
2490        let mapper = FlatProjectionMapper::new(&metadata, [0, 2, 3]).unwrap();
2491        let predicate_group = PredicateGroup::new(metadata.as_ref(), &[]).unwrap();
2492        let arrow_schema = metadata.schema.arrow_schema();
2493        let ts_expr = physical_col("ts", arrow_schema.as_ref()).unwrap();
2494        let dyn_filter = Arc::new(DynamicFilterPhysicalExpr::new(
2495            vec![ts_expr.clone()],
2496            physical_lit(true),
2497        ));
2498        predicate_group.add_dyn_filters(vec![dyn_filter.clone()]);
2499        let input = ScanInput::new(SchedulerEnv::new().await.access_layer.clone(), mapper)
2500            .with_predicate(predicate_group);
2501        let file = file_handle_with_time_range(
2502            Timestamp::new_millisecond(0),
2503            Timestamp::new_millisecond(1000),
2504        );
2505
2506        assert!(!input.can_manifest_prune_file(&file));
2507
2508        let updated = physical_binary(
2509            ts_expr,
2510            Operator::Gt,
2511            physical_lit(ScalarValue::TimestampMillisecond(Some(1000), None)),
2512            arrow_schema.as_ref(),
2513        )
2514        .unwrap();
2515        dyn_filter.update(updated).unwrap();
2516
2517        assert!(input.can_manifest_prune_file(&file));
2518    }
2519
2520    #[tokio::test]
2521    async fn test_range_pre_filter_mode() {
2522        let metadata = Arc::new(metadata_with_primary_key(vec![0, 1], false));
2523        let cases = [
2524            (true, MergeMode::LastRow, 1, PreFilterMode::All),
2525            (false, MergeMode::LastNonNull, 1, PreFilterMode::All),
2526            (false, MergeMode::LastRow, 2, PreFilterMode::SkipFields),
2527            (true, MergeMode::LastRow, 2, PreFilterMode::All),
2528        ];
2529
2530        for (append_mode, merge_mode, source_count, expected_mode) in cases {
2531            let input = new_scan_input(metadata.clone(), vec![])
2532                .await
2533                .with_append_mode(append_mode)
2534                .with_merge_mode(merge_mode);
2535
2536            assert_eq!(expected_mode, input.range_pre_filter_mode(source_count));
2537        }
2538    }
2539}