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    /// Scan-wide hint for rows in an execution batch.
822    batch_size: usize,
823    /// Cache.
824    pub(crate) cache_strategy: CacheStrategy,
825    /// Ignores file not found error.
826    ignore_file_not_found: bool,
827    /// Maximum number of SST files to scan concurrently.
828    pub(crate) max_concurrent_scan_files: usize,
829    /// Index appliers.
830    inverted_index_appliers: [Option<InvertedIndexApplierRef>; 2],
831    bloom_filter_index_appliers: [Option<BloomFilterIndexApplierRef>; 2],
832    fulltext_index_appliers: [Option<FulltextIndexApplierRef>; 2],
833    /// Vector index applier for KNN search.
834    #[cfg(feature = "vector_index")]
835    pub(crate) vector_index_applier: Option<VectorIndexApplierRef>,
836    /// Over-fetched k for vector index scan.
837    #[cfg(feature = "vector_index")]
838    pub(crate) vector_index_k: Option<usize>,
839    /// Start time of the query.
840    pub(crate) query_start: Option<Instant>,
841    /// The region is using append mode.
842    pub(crate) append_mode: bool,
843    /// Whether to remove deletion markers.
844    pub(crate) filter_deleted: bool,
845    /// Mode to merge duplicate rows.
846    pub(crate) merge_mode: MergeMode,
847    /// Hint to select rows from time series.
848    pub(crate) series_row_selector: Option<TimeSeriesRowSelector>,
849    /// Hint for the required distribution of the scanner.
850    pub(crate) distribution: Option<TimeSeriesDistribution>,
851    /// Whether the region's configured SST format is flat.
852    explain_flat_format: bool,
853    /// Snapshot upper bound bound at scan open and propagated back to the caller.
854    pub(crate) snapshot_sequence: Option<SequenceNumber>,
855    /// Whether this scan is for compaction.
856    pub(crate) compaction: bool,
857    /// Counters that should receive query-load metrics.
858    pub(crate) query_stat_counters: Option<RegionQueryStatCounters>,
859    #[cfg(feature = "enterprise")]
860    extension_ranges: Vec<BoxedExtensionRange>,
861}
862
863impl ScanInput {
864    /// Creates a new [ScanInput].
865    #[must_use]
866    pub(crate) fn new(access_layer: AccessLayerRef, mapper: FlatProjectionMapper) -> ScanInput {
867        ScanInput {
868            access_layer,
869            read_cols: mapper.read_columns().clone(),
870            mapper: Arc::new(mapper),
871            time_range: None,
872            predicate: PredicateGroup::default(),
873            region_partition_expr: None,
874            memtables: Vec::new(),
875            files: Vec::new(),
876            batch_size: crate::sst::parquet::DEFAULT_READ_BATCH_SIZE,
877            cache_strategy: CacheStrategy::Disabled,
878            ignore_file_not_found: false,
879            max_concurrent_scan_files: DEFAULT_MAX_CONCURRENT_SCAN_FILES,
880            inverted_index_appliers: [None, None],
881            bloom_filter_index_appliers: [None, None],
882            fulltext_index_appliers: [None, None],
883            #[cfg(feature = "vector_index")]
884            vector_index_applier: None,
885            #[cfg(feature = "vector_index")]
886            vector_index_k: None,
887            query_start: None,
888            append_mode: false,
889            filter_deleted: true,
890            merge_mode: MergeMode::default(),
891            series_row_selector: None,
892            distribution: None,
893            explain_flat_format: false,
894            snapshot_sequence: None,
895            compaction: false,
896            query_stat_counters: None,
897            #[cfg(feature = "enterprise")]
898            extension_ranges: Vec::new(),
899        }
900    }
901
902    /// Sets time range filter for time index.
903    #[must_use]
904    pub(crate) fn with_time_range(mut self, time_range: Option<TimestampRange>) -> Self {
905        self.time_range = time_range;
906        self
907    }
908
909    /// Sets predicate to push down.
910    #[must_use]
911    pub(crate) fn with_predicate(mut self, predicate: PredicateGroup) -> Self {
912        self.region_partition_expr = predicate.region_partition_expr().cloned();
913        self.predicate = predicate;
914        self
915    }
916
917    /// Sets memtable range builders.
918    #[must_use]
919    pub(crate) fn with_memtables(mut self, memtables: Vec<MemRangeBuilder>) -> Self {
920        self.memtables = memtables;
921        self
922    }
923
924    /// Sets files to read.
925    #[must_use]
926    pub(crate) fn with_files(mut self, files: Vec<FileHandle>) -> Self {
927        self.files = files;
928        self
929    }
930
931    /// Returns the scan-wide hint for rows in an execution batch.
932    pub(crate) fn batch_size(&self) -> usize {
933        self.batch_size
934    }
935
936    /// Sets the scan-wide hint for rows in an execution batch.
937    #[must_use]
938    pub(crate) fn with_batch_size(mut self, batch_size: usize) -> Self {
939        self.batch_size = batch_size;
940        self
941    }
942
943    /// Sets cache for this query.
944    #[must_use]
945    pub(crate) fn with_cache(mut self, cache: CacheStrategy) -> Self {
946        self.cache_strategy = cache;
947        self
948    }
949
950    /// Ignores file not found error.
951    #[must_use]
952    pub(crate) fn with_ignore_file_not_found(mut self, ignore: bool) -> Self {
953        self.ignore_file_not_found = ignore;
954        self
955    }
956
957    /// Sets maximum number of SST files to scan concurrently.
958    #[must_use]
959    pub(crate) fn with_max_concurrent_scan_files(
960        mut self,
961        max_concurrent_scan_files: usize,
962    ) -> Self {
963        self.max_concurrent_scan_files = max_concurrent_scan_files;
964        self
965    }
966
967    /// Sets inverted index appliers.
968    #[must_use]
969    pub(crate) fn with_inverted_index_appliers(
970        mut self,
971        appliers: [Option<InvertedIndexApplierRef>; 2],
972    ) -> Self {
973        self.inverted_index_appliers = appliers;
974        self
975    }
976
977    /// Sets bloom filter appliers.
978    #[must_use]
979    pub(crate) fn with_bloom_filter_index_appliers(
980        mut self,
981        appliers: [Option<BloomFilterIndexApplierRef>; 2],
982    ) -> Self {
983        self.bloom_filter_index_appliers = appliers;
984        self
985    }
986
987    /// Sets fulltext index appliers.
988    #[must_use]
989    pub(crate) fn with_fulltext_index_appliers(
990        mut self,
991        appliers: [Option<FulltextIndexApplierRef>; 2],
992    ) -> Self {
993        self.fulltext_index_appliers = appliers;
994        self
995    }
996
997    /// Sets vector index applier for KNN search.
998    #[cfg(feature = "vector_index")]
999    #[must_use]
1000    pub(crate) fn with_vector_index_applier(
1001        mut self,
1002        applier: Option<VectorIndexApplierRef>,
1003    ) -> Self {
1004        self.vector_index_applier = applier;
1005        self
1006    }
1007
1008    /// Sets over-fetched k for vector index scan.
1009    #[cfg(feature = "vector_index")]
1010    #[must_use]
1011    pub(crate) fn with_vector_index_k(mut self, k: Option<usize>) -> Self {
1012        self.vector_index_k = k;
1013        self
1014    }
1015
1016    /// Sets start time of the query.
1017    #[must_use]
1018    pub(crate) fn with_start_time(mut self, now: Option<Instant>) -> Self {
1019        self.query_start = now;
1020        self
1021    }
1022
1023    #[must_use]
1024    pub(crate) fn with_append_mode(mut self, is_append_mode: bool) -> Self {
1025        self.append_mode = is_append_mode;
1026        self
1027    }
1028
1029    pub(crate) fn with_query_stat_counters(
1030        mut self,
1031        counters: Option<RegionQueryStatCounters>,
1032    ) -> Self {
1033        self.query_stat_counters = counters;
1034        self
1035    }
1036
1037    /// Sets whether to remove deletion markers during scan.
1038    #[must_use]
1039    pub(crate) fn with_filter_deleted(mut self, filter_deleted: bool) -> Self {
1040        self.filter_deleted = filter_deleted;
1041        self
1042    }
1043
1044    /// Sets the merge mode.
1045    #[must_use]
1046    pub(crate) fn with_merge_mode(mut self, merge_mode: MergeMode) -> Self {
1047        self.merge_mode = merge_mode;
1048        self
1049    }
1050
1051    /// Sets the distribution hint.
1052    #[must_use]
1053    pub(crate) fn with_distribution(
1054        mut self,
1055        distribution: Option<TimeSeriesDistribution>,
1056    ) -> Self {
1057        self.distribution = distribution;
1058        self
1059    }
1060
1061    /// Sets whether the region's configured SST format is flat for explain output.
1062    #[must_use]
1063    pub(crate) fn with_explain_flat_format(mut self, explain_flat_format: bool) -> Self {
1064        self.explain_flat_format = explain_flat_format;
1065        self
1066    }
1067
1068    /// Sets the time series row selector.
1069    #[must_use]
1070    pub(crate) fn with_series_row_selector(
1071        mut self,
1072        series_row_selector: Option<TimeSeriesRowSelector>,
1073    ) -> Self {
1074        self.series_row_selector = series_row_selector;
1075        self
1076    }
1077
1078    #[must_use]
1079    pub(crate) fn with_snapshot_sequence(
1080        mut self,
1081        snapshot_sequence: Option<SequenceNumber>,
1082    ) -> Self {
1083        self.snapshot_sequence = snapshot_sequence;
1084        self
1085    }
1086
1087    /// Sets whether this scan is for compaction.
1088    #[must_use]
1089    pub(crate) fn with_compaction(mut self, compaction: bool) -> Self {
1090        self.compaction = compaction;
1091        self
1092    }
1093
1094    /// Builds memtable ranges to scan by `index`.
1095    pub(crate) fn build_mem_ranges(&self, index: RowGroupIndex) -> SmallVec<[MemtableRange; 2]> {
1096        let memtable = &self.memtables[index.index];
1097        let mut ranges = SmallVec::new();
1098        memtable.build_ranges(index.row_group_index, &mut ranges);
1099        ranges
1100    }
1101
1102    pub(crate) fn predicate_for_file(&self, file: &FileHandle) -> Option<Predicate> {
1103        if self.should_skip_region_partition(file) {
1104            self.predicate.predicate_without_region().cloned()
1105        } else {
1106            self.predicate.predicate().cloned()
1107        }
1108    }
1109
1110    fn should_skip_region_partition(&self, file: &FileHandle) -> bool {
1111        match (
1112            self.region_partition_expr.as_ref(),
1113            file.meta_ref().partition_expr.as_ref(),
1114        ) {
1115            (Some(region_expr), Some(file_expr)) => region_expr == file_expr,
1116            _ => false,
1117        }
1118    }
1119
1120    /// Tries to build file-level pruning statistics using only the [FileHandle]'s manifest-level
1121    /// time range, without reading any parquet metadata.
1122    ///
1123    /// Returns `None` if timestamp unit conversion overflows (conservative: keep the file).
1124    fn try_file_level_pruning_stats(&self, file: &FileHandle) -> Option<FileLevelPruningStats> {
1125        let (ts_min, ts_max) = file.time_range();
1126        let time_index = self.mapper.metadata().time_index_column();
1127        let time_index_unit = time_index.column_schema.data_type.as_timestamp()?.unit();
1128
1129        // Convert file timestamps to the time index column's unit. Use `convert_to_ceil` for
1130        // the upper bound to avoid accidentally shrinking the manifest range.
1131        let min_ts = ts_min.convert_to(time_index_unit)?;
1132        let max_ts = ts_max.convert_to_ceil(time_index_unit)?;
1133
1134        Some(FileLevelPruningStats {
1135            min_scalar: timestamp_to_scalar_value(time_index_unit, Some(min_ts.value())),
1136            max_scalar: timestamp_to_scalar_value(time_index_unit, Some(max_ts.value())),
1137            time_index_col_name: time_index.column_schema.name.clone(),
1138        })
1139    }
1140
1141    /// Checks whether a file can be definitively pruned using only its manifest-level
1142    /// time range and the current predicate, without reading any parquet metadata.
1143    ///
1144    /// Returns `true` if [PruningStatistics] proves the file cannot contain matching rows.
1145    #[inline]
1146    pub(crate) fn can_manifest_prune_file(&self, file: &FileHandle) -> bool {
1147        let predicate = self.predicate_for_file(file);
1148        self.manifest_prunes_file(file, predicate.as_ref())
1149    }
1150
1151    fn manifest_prunes_file(&self, file: &FileHandle, predicate: Option<&Predicate>) -> bool {
1152        if let Some(pred) = predicate
1153            && !pred.is_empty()
1154            && let Some(file_level_stats) = self.try_file_level_pruning_stats(file)
1155        {
1156            let pruning_results = pred.prune_with_stats(
1157                &file_level_stats,
1158                self.mapper.metadata().schema.arrow_schema(),
1159            );
1160            pruning_results.first() == Some(&false)
1161        } else {
1162            false
1163        }
1164    }
1165
1166    /// Prunes a file to scan and returns the builder to build readers.
1167    ///
1168    /// This is the public entry point used by direct tests and non-pruner callers.
1169    /// It performs its own manifest-level pruning check internally.
1170    #[tracing::instrument(
1171        skip_all,
1172        fields(
1173            region_id = %self.region_metadata().region_id,
1174            file_id = %file.file_id()
1175        )
1176    )]
1177    pub async fn prune_file(
1178        &self,
1179        file: &FileHandle,
1180        pre_filter_mode: PreFilterMode,
1181        reader_metrics: &mut ReaderMetrics,
1182    ) -> Result<FileRangeBuilder> {
1183        let predicate = self.predicate_for_file(file);
1184
1185        // Early file-level pruning using manifest time range before any parquet metadata access.
1186        if self.manifest_prunes_file(file, predicate.as_ref()) {
1187            reader_metrics.filter_metrics.files_time_range_pruned += 1;
1188            return Ok(FileRangeBuilder::default());
1189        }
1190
1191        self.prune_file_after_manifest_check(file, pre_filter_mode, predicate, reader_metrics)
1192            .await
1193    }
1194
1195    /// Second half of `prune_file` — performs the actual parquet metadata /
1196    /// reader setup. Callers that already performed manifest-level pruning
1197    /// (e.g. the `Pruner` via its shared `manifest_pruned_files` cache) should
1198    /// call this directly to avoid a redundant manifest check.
1199    ///
1200    /// `predicate` is the result of `self.predicate_for_file(file)` computed
1201    /// externally so the caller can reuse it if needed.
1202    pub(crate) async fn prune_file_after_manifest_check(
1203        &self,
1204        file: &FileHandle,
1205        pre_filter_mode: PreFilterMode,
1206        predicate: Option<Predicate>,
1207        reader_metrics: &mut ReaderMetrics,
1208    ) -> Result<FileRangeBuilder> {
1209        let may_build_selective_row_selection = predicate.is_some();
1210        let decode_pk_values = !self.compaction
1211            && self
1212                .mapper
1213                .read_columns()
1214                .column_ids_iter()
1215                .any(|column_id| self.mapper.metadata().primary_key.contains(&column_id));
1216        let reader = self
1217            .access_layer
1218            .read_sst(file.clone())
1219            .predicate(predicate)
1220            .projection(Some(self.read_cols.clone()))
1221            .cache(self.cache_strategy.clone())
1222            .inverted_index_appliers(self.inverted_index_appliers.clone())
1223            .bloom_filter_index_appliers(self.bloom_filter_index_appliers.clone())
1224            .fulltext_index_appliers(self.fulltext_index_appliers.clone());
1225        let reader = reader.batch_size(self.batch_size);
1226        let reader = if !self.compaction && may_build_selective_row_selection {
1227            reader.deferred_optional_page_index()
1228        } else {
1229            reader
1230        };
1231        #[cfg(feature = "vector_index")]
1232        let reader = {
1233            let mut reader = reader;
1234            reader =
1235                reader.vector_index_applier(self.vector_index_applier.clone(), self.vector_index_k);
1236            reader
1237        };
1238        let res = reader
1239            .expected_metadata(Some(self.mapper.metadata().clone()))
1240            .compaction(self.compaction)
1241            .pre_filter_mode(pre_filter_mode)
1242            .decode_primary_key_values(decode_pk_values)
1243            .build_reader_input(reader_metrics)
1244            .await;
1245        let read_input = match res {
1246            Ok(x) => x,
1247            Err(e) => {
1248                if e.is_object_not_found() && self.ignore_file_not_found {
1249                    error!(e; "File to scan does not exist, region_id: {}, file: {}", file.region_id(), file.file_id());
1250                    return Ok(FileRangeBuilder::default());
1251                } else {
1252                    return Err(e);
1253                }
1254            }
1255        };
1256
1257        let Some((mut file_range_ctx, selection)) = read_input else {
1258            return Ok(FileRangeBuilder::default());
1259        };
1260
1261        let need_compat = !compat::has_same_columns_and_pk_encoding(
1262            &self.mapper,
1263            file_range_ctx.read_format(),
1264            self.compaction,
1265        );
1266        if need_compat {
1267            // They have different schema. We need to adapt the batch first so the
1268            // mapper can convert it.
1269            let compat = FlatCompatBatch::try_new(
1270                &self.mapper,
1271                file_range_ctx.read_format(),
1272                self.compaction,
1273            )?;
1274            file_range_ctx.set_compat_batch(compat);
1275        }
1276        Ok(FileRangeBuilder::new(Arc::new(file_range_ctx), selection))
1277    }
1278
1279    /// Scans flat sources (RecordBatch streams) in parallel.
1280    ///
1281    /// # Panics if the input doesn't allow parallel scan.
1282    #[tracing::instrument(
1283        skip(self, sources, semaphore),
1284        fields(
1285            region_id = %self.region_metadata().region_id,
1286            source_count = sources.len()
1287        )
1288    )]
1289    pub(crate) fn create_parallel_flat_sources(
1290        &self,
1291        sources: Vec<BoxedRecordBatchStream>,
1292        semaphore: Arc<Semaphore>,
1293        channel_size: usize,
1294    ) -> Result<Vec<BoxedRecordBatchStream>> {
1295        if sources.len() <= 1 {
1296            return Ok(sources);
1297        }
1298
1299        // Spawn a task for each source.
1300        let sources = sources
1301            .into_iter()
1302            .map(|source| {
1303                let (sender, receiver) = mpsc::channel(channel_size);
1304                self.spawn_flat_scan_task(source, semaphore.clone(), sender);
1305                let stream = Box::pin(ReceiverStream::new(receiver));
1306                Box::pin(stream) as _
1307            })
1308            .collect();
1309        Ok(sources)
1310    }
1311
1312    /// Spawns a task to scan a flat source (RecordBatch stream) asynchronously.
1313    #[tracing::instrument(
1314        skip(self, input, semaphore, sender),
1315        fields(region_id = %self.region_metadata().region_id)
1316    )]
1317    pub(crate) fn spawn_flat_scan_task(
1318        &self,
1319        mut input: BoxedRecordBatchStream,
1320        semaphore: Arc<Semaphore>,
1321        sender: mpsc::Sender<Result<RecordBatch>>,
1322    ) {
1323        let region_id = self.region_metadata().region_id;
1324        let span = tracing::info_span!(
1325            "ScanInput::parallel_scan_task",
1326            region_id = %region_id,
1327            stream_kind = "flat"
1328        );
1329        common_runtime::spawn_query(
1330            async move {
1331                loop {
1332                    // We release the permit before sending result to avoid the task waiting on
1333                    // the channel with the permit held.
1334                    let maybe_batch = {
1335                        // Safety: We never close the semaphore.
1336                        let _permit = semaphore.acquire().await.unwrap();
1337                        input.next().await
1338                    };
1339                    match maybe_batch {
1340                        Some(Ok(batch)) => {
1341                            let _ = sender.send(Ok(batch)).await;
1342                        }
1343                        Some(Err(e)) => {
1344                            let _ = sender.send(Err(e)).await;
1345                            break;
1346                        }
1347                        None => break,
1348                    }
1349                }
1350            }
1351            .instrument(span),
1352        );
1353    }
1354
1355    pub(crate) fn total_rows(&self) -> usize {
1356        let rows_in_files: usize = self.files.iter().map(|f| f.num_rows()).sum();
1357        let rows_in_memtables: usize = self.memtables.iter().map(|m| m.stats().num_rows()).sum();
1358
1359        let rows = rows_in_files + rows_in_memtables;
1360        #[cfg(feature = "enterprise")]
1361        let rows = rows
1362            + self
1363                .extension_ranges
1364                .iter()
1365                .map(|x| x.num_rows())
1366                .sum::<u64>() as usize;
1367        rows
1368    }
1369
1370    pub(crate) fn predicate_group(&self) -> &PredicateGroup {
1371        &self.predicate
1372    }
1373
1374    /// Returns number of memtables to scan.
1375    pub(crate) fn num_memtables(&self) -> usize {
1376        self.memtables.len()
1377    }
1378
1379    /// Returns number of SST files to scan.
1380    pub(crate) fn num_files(&self) -> usize {
1381        self.files.len()
1382    }
1383
1384    /// Gets the file handle from a row group index.
1385    pub(crate) fn file_from_index(&self, index: RowGroupIndex) -> &FileHandle {
1386        let file_index = index.index - self.num_memtables();
1387        &self.files[file_index]
1388    }
1389
1390    pub fn region_metadata(&self) -> &RegionMetadataRef {
1391        self.mapper.metadata()
1392    }
1393
1394    fn range_pre_filter_mode(&self, source_count: usize) -> PreFilterMode {
1395        if source_count <= 1 {
1396            // Duplicated rows in the same source is not a normal case and we don't provide
1397            // strict dedup semantic (last_row/last_non_null) for it. We expect the duplicated rows
1398            // are exactly identical in the same source so we use PreFilterMode::All for
1399            // performance reason.
1400            return PreFilterMode::All;
1401        }
1402
1403        pre_filter_mode(self.append_mode, self.merge_mode)
1404    }
1405}
1406
1407#[cfg(feature = "enterprise")]
1408impl ScanInput {
1409    #[must_use]
1410    pub(crate) fn with_extension_ranges(self, extension_ranges: Vec<BoxedExtensionRange>) -> Self {
1411        Self {
1412            extension_ranges,
1413            ..self
1414        }
1415    }
1416
1417    #[cfg(feature = "enterprise")]
1418    pub(crate) fn extension_ranges(&self) -> &[BoxedExtensionRange] {
1419        &self.extension_ranges
1420    }
1421
1422    /// Get a boxed [ExtensionRange] by the index in all ranges.
1423    #[cfg(feature = "enterprise")]
1424    pub(crate) fn extension_range(&self, i: usize) -> &BoxedExtensionRange {
1425        &self.extension_ranges[i - self.num_memtables() - self.num_files()]
1426    }
1427}
1428
1429/// Lightweight [PruningStatistics] that only uses the file-level time range from manifest
1430/// metadata, avoiding any parquet metadata reads. Used for early file-level pruning before
1431/// accessing row-group-level statistics.
1432pub(crate) struct FileLevelPruningStats {
1433    /// Scalar value for the file's minimum timestamp in the time index column's unit.
1434    pub(crate) min_scalar: ScalarValue,
1435    /// Scalar value for the file's maximum timestamp in the time index column's unit.
1436    pub(crate) max_scalar: ScalarValue,
1437    /// Name of the time index column.
1438    pub(crate) time_index_col_name: String,
1439}
1440
1441impl PruningStatistics for FileLevelPruningStats {
1442    fn min_values(&self, column: &Column) -> Option<ArrayRef> {
1443        if column.name == self.time_index_col_name {
1444            ScalarValue::iter_to_array(std::iter::once(self.min_scalar.clone())).ok()
1445        } else {
1446            None
1447        }
1448    }
1449
1450    fn max_values(&self, column: &Column) -> Option<ArrayRef> {
1451        if column.name == self.time_index_col_name {
1452            ScalarValue::iter_to_array(std::iter::once(self.max_scalar.clone())).ok()
1453        } else {
1454            None
1455        }
1456    }
1457
1458    fn num_containers(&self) -> usize {
1459        1
1460    }
1461
1462    fn null_counts(&self, column: &Column) -> Option<ArrayRef> {
1463        if column.name == self.time_index_col_name {
1464            // The time index column is NOT NULL.
1465            Some(Arc::new(UInt64Array::from(vec![0u64])))
1466        } else {
1467            None
1468        }
1469    }
1470
1471    fn row_counts(&self, _column: &Column) -> Option<ArrayRef> {
1472        None
1473    }
1474
1475    fn contained(&self, _column: &Column, _values: &HashSet<ScalarValue>) -> Option<BooleanArray> {
1476        None
1477    }
1478}
1479
1480#[cfg(test)]
1481impl ScanInput {
1482    /// Returns SST file ids to scan.
1483    pub(crate) fn file_ids(&self) -> Vec<crate::sst::file::RegionFileId> {
1484        self.files.iter().map(|file| file.file_id()).collect()
1485    }
1486
1487    pub(crate) fn index_ids(&self) -> Vec<crate::sst::file::RegionIndexId> {
1488        self.files.iter().map(|file| file.index_id()).collect()
1489    }
1490}
1491
1492fn pre_filter_mode(append_mode: bool, merge_mode: MergeMode) -> PreFilterMode {
1493    if append_mode {
1494        return PreFilterMode::All;
1495    }
1496
1497    match merge_mode {
1498        MergeMode::LastRow => PreFilterMode::SkipFields,
1499        MergeMode::LastNonNull => PreFilterMode::SkipFields,
1500    }
1501}
1502
1503fn narrow_read_columns_by_json_type_hint(
1504    read_columns: &mut ReadColumns,
1505    json_type_hint: &HashMap<String, JsonNativeType>,
1506    metadata: &RegionMetadata,
1507) {
1508    if json_type_hint.is_empty() {
1509        return;
1510    }
1511
1512    for read_column in &mut read_columns.cols {
1513        let Some(column) = metadata.column_by_id(read_column.column_id) else {
1514            continue;
1515        };
1516        let column_name = &column.column_schema.name;
1517        let Some(json_type) = json_type_hint.get(column_name) else {
1518            continue;
1519        };
1520
1521        let mut paths = Vec::new();
1522        let mut current = vec![column_name.clone()];
1523        collect_json_nested_paths(json_type, &mut current, &mut paths);
1524        merge_nested_paths(&mut read_column.nested_paths, paths)
1525    }
1526}
1527
1528fn collect_json_nested_paths(
1529    json_type: &JsonNativeType,
1530    current: &mut NestedPath,
1531    paths: &mut Vec<NestedPath>,
1532) {
1533    match json_type {
1534        JsonNativeType::Object(fields) if !fields.is_empty() => {
1535            for (field, child) in fields {
1536                current.push(field.clone());
1537                collect_json_nested_paths(child, current, paths);
1538                current.pop();
1539            }
1540        }
1541        _ => paths.push(current.clone()),
1542    }
1543}
1544
1545/// Output of [build_scan_fingerprint]: the cache fingerprint plus the derived
1546/// implied time range used to decide whether the cache key can drop the time
1547/// predicates for a given partition (see `build_range_cache_key`).
1548pub(crate) struct ScanFingerprintBundle {
1549    pub(crate) fingerprint: ScanRequestFingerprint,
1550    /// `Some(r)` = all time-only predicates are guaranteed true on `r` (in the
1551    /// column's `TimeUnit`).
1552    /// `None`    = at least one time-only predicate could not be proven (e.g.
1553    /// `OR`), so the cache-key optimization is disabled for this scan.
1554    pub(crate) implied_time_range: Option<TimestampRange>,
1555}
1556
1557/// Builds a [ScanFingerprintBundle] from a [ScanInput] if the scan is eligible
1558/// for partition range caching.
1559pub(crate) fn build_scan_fingerprint(input: &ScanInput) -> Option<ScanFingerprintBundle> {
1560    let eligible = !input.compaction
1561        && !input.files.is_empty()
1562        && matches!(input.cache_strategy, CacheStrategy::EnableAll(_));
1563
1564    if !eligible {
1565        return None;
1566    }
1567
1568    let metadata = input.region_metadata();
1569    let tag_names: HashSet<&str> = metadata
1570        .column_metadatas
1571        .iter()
1572        .filter(|col| col.semantic_type == SemanticType::Tag)
1573        .map(|col| col.column_schema.name.as_str())
1574        .collect();
1575
1576    let time_index = metadata.time_index_column();
1577    let time_index_name = time_index.column_schema.name.clone();
1578    let ts_col_unit = time_index
1579        .column_schema
1580        .data_type
1581        .as_timestamp()
1582        .expect("Time index must have timestamp-compatible type")
1583        .unit();
1584
1585    let exprs = input
1586        .predicate_group()
1587        .predicate_without_region()
1588        .map(|predicate| predicate.exprs())
1589        .unwrap_or_default();
1590
1591    let mut filters = Vec::new();
1592    let mut time_only_exprs: Vec<&Expr> = Vec::new();
1593    let mut has_tag_filter = false;
1594    let mut columns = HashSet::new();
1595
1596    for expr in exprs {
1597        columns.clear();
1598        let is_time_only = match expr_to_columns(expr, &mut columns) {
1599            Ok(()) if !columns.is_empty() => {
1600                has_tag_filter |= columns
1601                    .iter()
1602                    .any(|col| tag_names.contains(col.name.as_str()));
1603                columns.iter().all(|col| col.name == time_index_name)
1604            }
1605            _ => false,
1606        };
1607
1608        // Route time-only exprs that the legacy extractor recognizes into
1609        // `time_only_exprs` so the implication walker
1610        // (`implied_time_range_from_exprs`, called below) can attempt to drop
1611        // them from the cache key when the partition's `FileTimeRange` is fully
1612        // covered, then stringify them into the fingerprint's `time_filters`
1613        // bucket. Time-only exprs that the extractor doesn't recognize stay in
1614        // `filters` and never get stripped — conservatively correct.
1615        if is_time_only
1616            && extract_time_range_from_expr(&time_index_name, ts_col_unit, expr).is_some()
1617        {
1618            time_only_exprs.push(expr);
1619        } else {
1620            filters.push(expr.to_string());
1621        }
1622    }
1623
1624    if !has_tag_filter {
1625        // We only cache requests that have tag filters to avoid caching all series.
1626        return None;
1627    }
1628
1629    let implied_time_range =
1630        implied_time_range_from_exprs(&time_index_name, ts_col_unit, &time_only_exprs);
1631    let mut time_filters: Vec<String> = time_only_exprs.iter().map(|e| e.to_string()).collect();
1632
1633    // Ensure the filters are sorted for consistent fingerprinting.
1634    filters.sort_unstable();
1635    time_filters.sort_unstable();
1636    let read_columns = input.read_cols.clone();
1637    let fingerprint = crate::read::range_cache::ScanRequestFingerprintBuilder {
1638        read_column_types: read_columns
1639            .column_ids_iter()
1640            .map(|id| {
1641                metadata
1642                    .column_by_id(id)
1643                    .map(|col| col.column_schema.data_type.clone())
1644            })
1645            .collect(),
1646        read_columns,
1647        filters,
1648        time_filters,
1649        series_row_selector: input.series_row_selector,
1650        append_mode: input.append_mode,
1651        filter_deleted: input.filter_deleted,
1652        merge_mode: input.merge_mode,
1653        partition_expr_version: metadata.partition_expr_version,
1654    }
1655    .build();
1656
1657    Some(ScanFingerprintBundle {
1658        fingerprint,
1659        implied_time_range,
1660    })
1661}
1662
1663/// Context shared by different streams from a scanner.
1664/// It contains the input and ranges to scan.
1665pub struct StreamContext {
1666    /// Input memtables and files.
1667    pub input: ScanInput,
1668    /// Metadata for partition ranges.
1669    pub(crate) ranges: Vec<RangeMeta>,
1670    /// Precomputed scan fingerprint for partition range caching.
1671    /// `None` when the scan is not eligible for caching.
1672    #[allow(dead_code)]
1673    pub(crate) scan_fingerprint: Option<ScanRequestFingerprint>,
1674    /// Implied range of every time-only predicate, in the time index column's
1675    /// `TimeUnit`. Used by `build_range_cache_key` to decide whether the
1676    /// partition's `FileTimeRange` is fully covered (allowing `time_filters`
1677    /// to be stripped from the cache key). `None` when caching is ineligible
1678    /// or when the implication walker bailed on an unsupported shape (e.g.
1679    /// `OR`).
1680    pub(crate) scan_implied_time_range: Option<TimestampRange>,
1681
1682    // Metrics:
1683    /// The start time of the query.
1684    pub(crate) query_start: Instant,
1685}
1686
1687impl StreamContext {
1688    /// Creates a new [StreamContext] for [SeqScan].
1689    pub(crate) fn seq_scan_ctx(input: ScanInput) -> Self {
1690        let query_start = input.query_start.unwrap_or_else(Instant::now);
1691        let ranges = RangeMeta::seq_scan_ranges(&input);
1692        READ_SST_COUNT.observe(input.num_files() as f64);
1693        let (scan_fingerprint, scan_implied_time_range) = match build_scan_fingerprint(&input) {
1694            Some(b) => (Some(b.fingerprint), b.implied_time_range),
1695            None => (None, None),
1696        };
1697
1698        Self {
1699            input,
1700            ranges,
1701            scan_fingerprint,
1702            scan_implied_time_range,
1703            query_start,
1704        }
1705    }
1706
1707    /// Creates a new [StreamContext] for [UnorderedScan].
1708    pub(crate) fn unordered_scan_ctx(input: ScanInput) -> Self {
1709        let query_start = input.query_start.unwrap_or_else(Instant::now);
1710        let ranges = RangeMeta::unordered_scan_ranges(&input);
1711        READ_SST_COUNT.observe(input.num_files() as f64);
1712        let (scan_fingerprint, scan_implied_time_range) = match build_scan_fingerprint(&input) {
1713            Some(b) => (Some(b.fingerprint), b.implied_time_range),
1714            None => (None, None),
1715        };
1716
1717        Self {
1718            input,
1719            ranges,
1720            scan_fingerprint,
1721            scan_implied_time_range,
1722            query_start,
1723        }
1724    }
1725
1726    /// Returns true if the index refers to a memtable.
1727    pub(crate) fn is_mem_range_index(&self, index: RowGroupIndex) -> bool {
1728        self.input.num_memtables() > index.index
1729    }
1730
1731    pub(crate) fn is_file_range_index(&self, index: RowGroupIndex) -> bool {
1732        !self.is_mem_range_index(index)
1733            && index.index < self.input.num_files() + self.input.num_memtables()
1734    }
1735
1736    pub(crate) fn range_pre_filter_mode(&self, part_range: &PartitionRange) -> PreFilterMode {
1737        let range_meta = &self.ranges[part_range.identifier];
1738        let source_count = range_meta.indices.len();
1739
1740        self.input.range_pre_filter_mode(source_count)
1741    }
1742
1743    /// Retrieves the partition ranges.
1744    pub(crate) fn partition_ranges(&self) -> Vec<PartitionRange> {
1745        self.ranges
1746            .iter()
1747            .enumerate()
1748            .map(|(idx, range_meta)| range_meta.new_partition_range(idx))
1749            .collect()
1750    }
1751
1752    /// Format the context for explain.
1753    pub(crate) fn format_for_explain(&self, verbose: bool, f: &mut fmt::Formatter) -> fmt::Result {
1754        let (mut num_mem_ranges, mut num_file_ranges, mut num_other_ranges) = (0, 0, 0);
1755        for range_meta in &self.ranges {
1756            for idx in &range_meta.row_group_indices {
1757                if self.is_mem_range_index(*idx) {
1758                    num_mem_ranges += 1;
1759                } else if self.is_file_range_index(*idx) {
1760                    num_file_ranges += 1;
1761                } else {
1762                    num_other_ranges += 1;
1763                }
1764            }
1765        }
1766        if verbose {
1767            write!(f, "{{")?;
1768        }
1769        write!(
1770            f,
1771            r#""partition_count":{{"count":{}, "mem_ranges":{}, "files":{}, "file_ranges":{}"#,
1772            self.ranges.len(),
1773            num_mem_ranges,
1774            self.input.num_files(),
1775            num_file_ranges,
1776        )?;
1777        if num_other_ranges > 0 {
1778            write!(f, r#", "other_ranges":{}"#, num_other_ranges)?;
1779        }
1780        write!(f, "}}")?;
1781
1782        if let Some(selector) = &self.input.series_row_selector {
1783            write!(f, ", \"selector\":\"{}\"", selector)?;
1784        }
1785        if let Some(distribution) = &self.input.distribution {
1786            write!(f, ", \"distribution\":\"{}\"", distribution)?;
1787        }
1788
1789        if verbose {
1790            self.format_verbose_content(f)?;
1791        }
1792
1793        Ok(())
1794    }
1795
1796    fn format_verbose_content(&self, f: &mut fmt::Formatter) -> fmt::Result {
1797        struct FileWrapper<'a> {
1798            file: &'a FileHandle,
1799        }
1800
1801        impl fmt::Debug for FileWrapper<'_> {
1802            fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1803                let (start, end) = self.file.time_range();
1804                write!(
1805                    f,
1806                    r#"{{"file_id":"{}","time_range_start":"{}::{}","time_range_end":"{}::{}","rows":{},"size":{},"index_size":{}}}"#,
1807                    self.file.file_id(),
1808                    start.value(),
1809                    start.unit(),
1810                    end.value(),
1811                    end.unit(),
1812                    self.file.num_rows(),
1813                    self.file.size(),
1814                    self.file.index_size()
1815                )
1816            }
1817        }
1818
1819        struct InputWrapper<'a> {
1820            input: &'a ScanInput,
1821        }
1822
1823        #[cfg(feature = "enterprise")]
1824        impl InputWrapper<'_> {
1825            fn format_extension_ranges(&self, f: &mut fmt::Formatter) -> fmt::Result {
1826                if self.input.extension_ranges.is_empty() {
1827                    return Ok(());
1828                }
1829
1830                let mut delimiter = "";
1831                write!(f, ", extension_ranges: [")?;
1832                for range in self.input.extension_ranges() {
1833                    write!(f, "{}{:?}", delimiter, range)?;
1834                    delimiter = ", ";
1835                }
1836                write!(f, "]")?;
1837                Ok(())
1838            }
1839        }
1840
1841        impl fmt::Debug for InputWrapper<'_> {
1842            fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1843                let output_schema = self.input.mapper.output_schema();
1844                if !output_schema.is_empty() {
1845                    let names: Vec<_> = output_schema
1846                        .column_schemas()
1847                        .iter()
1848                        .map(|col| &col.name)
1849                        .collect();
1850                    write!(f, ", \"projection\": {:?}", names)?;
1851                }
1852                if let Some(predicate) = &self.input.predicate.predicate() {
1853                    if !predicate.exprs().is_empty() {
1854                        let exprs: Vec<_> =
1855                            predicate.exprs().iter().map(|e| e.to_string()).collect();
1856                        write!(f, ", \"filters\": {:?}", exprs)?;
1857                    }
1858                    if !predicate.dyn_filters().is_empty() {
1859                        let dyn_filters: Vec<_> = predicate
1860                            .dyn_filters()
1861                            .iter()
1862                            .map(|f| format!("{}", f))
1863                            .collect();
1864                        write!(f, ", \"dyn_filters\": {:?}", dyn_filters)?;
1865                    }
1866                }
1867                #[cfg(feature = "vector_index")]
1868                if let Some(vector_index_k) = self.input.vector_index_k {
1869                    write!(f, ", \"vector_index_k\": {}", vector_index_k)?;
1870                }
1871                if !self.input.files.is_empty() {
1872                    write!(f, ", \"files\": ")?;
1873                    f.debug_list()
1874                        .entries(self.input.files.iter().map(|file| FileWrapper { file }))
1875                        .finish()?;
1876                }
1877                write!(f, ", \"flat_format\": {}", self.input.explain_flat_format)?;
1878                #[cfg(feature = "enterprise")]
1879                self.format_extension_ranges(f)?;
1880
1881                Ok(())
1882            }
1883        }
1884
1885        write!(f, "{:?}", InputWrapper { input: &self.input })
1886    }
1887
1888    /// Add new dynamic filters to the predicates.
1889    /// Safe after stream creation; in-flight reads may still observe an older snapshot.
1890    pub(crate) fn add_dyn_filter_to_predicate(
1891        self: &Arc<Self>,
1892        filter_exprs: Vec<Arc<dyn datafusion::physical_plan::PhysicalExpr>>,
1893    ) -> Vec<bool> {
1894        let mut supported = Vec::with_capacity(filter_exprs.len());
1895        let filter_expr = filter_exprs
1896            .into_iter()
1897            .filter_map(|expr| {
1898                if let Ok(dyn_filter) = (expr as Arc<dyn std::any::Any + Send + Sync + 'static>)
1899                .downcast::<datafusion::physical_plan::expressions::DynamicFilterPhysicalExpr>()
1900            {
1901                supported.push(true);
1902                Some(dyn_filter)
1903            } else {
1904                supported.push(false);
1905                None
1906            }
1907            })
1908            .collect();
1909        self.input.predicate.add_dyn_filters(filter_expr);
1910        supported
1911    }
1912}
1913
1914/// Predicates to evaluate.
1915/// It only keeps filters that [SimpleFilterEvaluator] supports.
1916#[derive(Clone, Default)]
1917pub struct PredicateGroup {
1918    time_filters: Option<Arc<Vec<SimpleFilterEvaluator>>>,
1919    /// Predicate that includes request filters and region partition expr (if any).
1920    predicate_all: Predicate,
1921    /// Predicate that only includes request filters.
1922    predicate_without_region: Predicate,
1923    /// Region partition expression restored from metadata.
1924    region_partition_expr: Option<PartitionExpr>,
1925}
1926
1927impl PredicateGroup {
1928    /// Creates a new `PredicateGroup` from exprs according to the metadata.
1929    pub fn new(metadata: &RegionMetadata, exprs: &[Expr]) -> Result<Self> {
1930        let mut combined_exprs = exprs.to_vec();
1931        let mut region_partition_expr = None;
1932
1933        if let Some(expr_json) = metadata.partition_expr.as_ref()
1934            && !expr_json.is_empty()
1935            && let Some(expr) = PartitionExpr::from_json_str(expr_json)
1936                .context(InvalidPartitionExprSnafu { expr: expr_json })?
1937        {
1938            let logical_expr = expr
1939                .try_as_logical_expr()
1940                .context(InvalidPartitionExprSnafu {
1941                    expr: expr_json.clone(),
1942                })?;
1943
1944            combined_exprs.push(logical_expr);
1945            region_partition_expr = Some(expr);
1946        }
1947
1948        let mut time_filters = Vec::with_capacity(combined_exprs.len());
1949        // Columns in the expr.
1950        let mut columns = HashSet::new();
1951        for expr in &combined_exprs {
1952            columns.clear();
1953            let Some(filter) = Self::expr_to_filter(expr, metadata, &mut columns) else {
1954                continue;
1955            };
1956            time_filters.push(filter);
1957        }
1958        let time_filters = if time_filters.is_empty() {
1959            None
1960        } else {
1961            Some(Arc::new(time_filters))
1962        };
1963
1964        let predicate_all = Predicate::new(combined_exprs);
1965        let predicate_without_region = Predicate::new(exprs.to_vec());
1966
1967        Ok(Self {
1968            time_filters,
1969            predicate_all,
1970            predicate_without_region,
1971            region_partition_expr,
1972        })
1973    }
1974
1975    /// Returns time filters.
1976    pub(crate) fn time_filters(&self) -> Option<Arc<Vec<SimpleFilterEvaluator>>> {
1977        self.time_filters.clone()
1978    }
1979
1980    /// Returns predicate of all exprs (including region partition expr if present).
1981    pub(crate) fn predicate(&self) -> Option<&Predicate> {
1982        if self.predicate_all.is_empty() {
1983            None
1984        } else {
1985            Some(&self.predicate_all)
1986        }
1987    }
1988
1989    /// Returns predicate that excludes region partition expr.
1990    pub(crate) fn predicate_without_region(&self) -> Option<&Predicate> {
1991        if self.predicate_without_region.is_empty() {
1992            None
1993        } else {
1994            Some(&self.predicate_without_region)
1995        }
1996    }
1997
1998    /// Add dynamic filters in the predicates.
1999    pub(crate) fn add_dyn_filters(&self, dyn_filters: Vec<Arc<DynamicFilterPhysicalExpr>>) {
2000        self.predicate_all.add_dyn_filters(dyn_filters.clone());
2001        self.predicate_without_region.add_dyn_filters(dyn_filters);
2002    }
2003
2004    /// Returns the region partition expr from metadata, if any.
2005    pub(crate) fn region_partition_expr(&self) -> Option<&PartitionExpr> {
2006        self.region_partition_expr.as_ref()
2007    }
2008
2009    fn expr_to_filter(
2010        expr: &Expr,
2011        metadata: &RegionMetadata,
2012        columns: &mut HashSet<Column>,
2013    ) -> Option<SimpleFilterEvaluator> {
2014        columns.clear();
2015        // `expr_to_columns` won't return error.
2016        // We still ignore these expressions for safety.
2017        expr_to_columns(expr, columns).ok()?;
2018        if columns.len() > 1 {
2019            // Simple filter doesn't support multiple columns.
2020            return None;
2021        }
2022        let column = columns.iter().next()?;
2023        let column_meta = metadata.column_by_name(&column.name)?;
2024        if column_meta.semantic_type == SemanticType::Timestamp {
2025            SimpleFilterEvaluator::try_new(expr)
2026        } else {
2027            None
2028        }
2029    }
2030}
2031
2032#[cfg(test)]
2033mod tests {
2034    use std::sync::Arc;
2035
2036    use common_time::timestamp::{TimeUnit, Timestamp};
2037    use datafusion::physical_plan::expressions::{
2038        binary as physical_binary, col as physical_col, lit as physical_lit,
2039    };
2040    use datafusion_common::ScalarValue;
2041    use datafusion_expr::{Operator, col, lit};
2042    use datatypes::arrow::datatypes::{
2043        DataType as ArrowDataType, Field, Schema as ArrowSchema, TimeUnit as ArrowTimeUnit,
2044    };
2045    use datatypes::prelude::ConcreteDataType;
2046    use datatypes::schema::ColumnSchema;
2047    use datatypes::types::json_type::JsonObjectType;
2048    use datatypes::value::Value;
2049    use partition::expr::col as partition_col;
2050    use store_api::metadata::{ColumnMetadata, RegionMetadataBuilder};
2051    use store_api::storage::{RegionId, TimeSeriesDistribution, TimeSeriesRowSelector};
2052
2053    use super::*;
2054    use crate::cache::CacheManager;
2055    use crate::error::InvalidMetadataSnafu;
2056    use crate::read::range_cache::ScanRequestFingerprintBuilder;
2057    use crate::read::read_columns::ReadColumn;
2058    use crate::sst::file::FileMeta;
2059    use crate::test_util::memtable_util::metadata_with_primary_key;
2060    use crate::test_util::scheduler_util::SchedulerEnv;
2061
2062    async fn new_scan_input(metadata: RegionMetadataRef, filters: Vec<Expr>) -> ScanInput {
2063        let env = SchedulerEnv::new().await;
2064        let mapper = FlatProjectionMapper::new(&metadata, [0, 2, 3]).unwrap();
2065        let predicate = PredicateGroup::new(metadata.as_ref(), &filters).unwrap();
2066        let file = FileHandle::new(
2067            crate::sst::file::FileMeta::default(),
2068            Arc::new(crate::sst::file_purger::NoopFilePurger),
2069        );
2070
2071        ScanInput::new(env.access_layer.clone(), mapper)
2072            .with_predicate(predicate)
2073            .with_cache(CacheStrategy::EnableAll(Arc::new(
2074                CacheManager::builder()
2075                    .range_result_cache_size(1024)
2076                    .build(),
2077            )))
2078            .with_files(vec![file])
2079    }
2080
2081    /// Helper to create a timestamp millisecond literal.
2082    fn ts_lit(val: i64) -> datafusion_expr::Expr {
2083        lit(ScalarValue::TimestampMillisecond(Some(val), None))
2084    }
2085
2086    fn metadata_with_time_index_unit(unit: TimeUnit) -> RegionMetadataRef {
2087        let mut builder = RegionMetadataBuilder::new(RegionId::new(123, 456));
2088        builder
2089            .push_column_metadata(ColumnMetadata {
2090                column_schema: ColumnSchema::new(
2091                    "k0".to_string(),
2092                    ConcreteDataType::string_datatype(),
2093                    false,
2094                ),
2095                semantic_type: SemanticType::Tag,
2096                column_id: 0,
2097            })
2098            .push_column_metadata(ColumnMetadata {
2099                column_schema: ColumnSchema::new(
2100                    "k1".to_string(),
2101                    ConcreteDataType::uint32_datatype(),
2102                    false,
2103                ),
2104                semantic_type: SemanticType::Tag,
2105                column_id: 1,
2106            })
2107            .push_column_metadata(ColumnMetadata {
2108                column_schema: ColumnSchema::new(
2109                    "ts".to_string(),
2110                    ConcreteDataType::timestamp_datatype(unit),
2111                    false,
2112                ),
2113                semantic_type: SemanticType::Timestamp,
2114                column_id: 2,
2115            })
2116            .push_column_metadata(ColumnMetadata {
2117                column_schema: ColumnSchema::new(
2118                    "v0".to_string(),
2119                    ConcreteDataType::int64_datatype(),
2120                    true,
2121                ),
2122                semantic_type: SemanticType::Field,
2123                column_id: 3,
2124            })
2125            .primary_key(vec![0, 1]);
2126
2127        Arc::new(builder.build().unwrap())
2128    }
2129
2130    fn file_handle_with_time_range(start: Timestamp, end: Timestamp) -> FileHandle {
2131        FileHandle::new(
2132            FileMeta {
2133                time_range: (start, end),
2134                ..Default::default()
2135            },
2136            Arc::new(crate::sst::file_purger::NoopFilePurger),
2137        )
2138    }
2139
2140    #[tokio::test]
2141    async fn test_scan_input_uses_explicit_batch_size() {
2142        let metadata = Arc::new(metadata_with_primary_key(vec![0, 1], false));
2143        let mapper = FlatProjectionMapper::new(&metadata, [0, 2, 3]).unwrap();
2144        let env = SchedulerEnv::new().await;
2145        let input = ScanInput::new(env.access_layer.clone(), mapper);
2146        assert_eq!(
2147            crate::sst::parquet::DEFAULT_READ_BATCH_SIZE,
2148            input.batch_size()
2149        );
2150
2151        let mapper = FlatProjectionMapper::new(&metadata, [0, 2, 3]).unwrap();
2152        let input = ScanInput::new(env.access_layer.clone(), mapper)
2153            .with_compaction(true)
2154            .with_batch_size(256);
2155        assert_eq!(256, input.batch_size());
2156
2157        let mapper = FlatProjectionMapper::new(&metadata, [0, 2, 3]).unwrap();
2158        let input = ScanInput::new(env.access_layer.clone(), mapper)
2159            .with_batch_size(256)
2160            .with_compaction(true)
2161            .with_compaction(false);
2162        assert_eq!(256, input.batch_size());
2163    }
2164
2165    #[test]
2166    fn test_fill_json_nested_paths_from_hint() -> Result<()> {
2167        fn json_projection_test_metadata() -> Result<RegionMetadataRef> {
2168            let mut builder = RegionMetadataBuilder::new(RegionId::new(1024, 0));
2169            builder
2170                .push_column_metadata(ColumnMetadata {
2171                    column_schema: ColumnSchema::new(
2172                        "tag".to_string(),
2173                        ConcreteDataType::string_datatype(),
2174                        true,
2175                    ),
2176                    semantic_type: SemanticType::Tag,
2177                    column_id: 0,
2178                })
2179                .push_column_metadata(ColumnMetadata {
2180                    column_schema: ColumnSchema::new(
2181                        "j".to_string(),
2182                        ConcreteDataType::json2(JsonNativeType::Object(JsonObjectType::new())),
2183                        true,
2184                    ),
2185                    semantic_type: SemanticType::Field,
2186                    column_id: 1,
2187                })
2188                .push_column_metadata(ColumnMetadata {
2189                    column_schema: ColumnSchema::new(
2190                        "ts".to_string(),
2191                        ConcreteDataType::timestamp_millisecond_datatype(),
2192                        false,
2193                    ),
2194                    semantic_type: SemanticType::Timestamp,
2195                    column_id: 2,
2196                });
2197            builder.primary_key(vec![0]);
2198            builder.build().context(InvalidMetadataSnafu).map(Arc::new)
2199        }
2200
2201        let metadata = json_projection_test_metadata()?;
2202        let hint = HashMap::from([(
2203            "j".to_string(),
2204            JsonNativeType::Object(JsonObjectType::from([
2205                ("a".to_string(), JsonNativeType::i64()),
2206                (
2207                    "b".to_string(),
2208                    JsonNativeType::Object(JsonObjectType::from([(
2209                        "c".to_string(),
2210                        JsonNativeType::String,
2211                    )])),
2212                ),
2213            ])),
2214        )]);
2215
2216        fn nested_path(parts: &[&str]) -> NestedPath {
2217            parts.iter().map(|part| part.to_string()).collect()
2218        }
2219
2220        let mut read_columns = ReadColumns {
2221            cols: vec![ReadColumn::new(1, vec![]), ReadColumn::new(0, vec![])],
2222        };
2223        narrow_read_columns_by_json_type_hint(&mut read_columns, &hint, metadata.as_ref());
2224        assert_eq!(
2225            read_columns,
2226            ReadColumns {
2227                cols: vec![
2228                    ReadColumn::new(
2229                        1,
2230                        vec![nested_path(&["j", "a"]), nested_path(&["j", "b", "c"])]
2231                    ),
2232                    ReadColumn::new(0, vec![])
2233                ]
2234            }
2235        );
2236
2237        let mut read_columns = ReadColumns {
2238            cols: vec![ReadColumn::new(0, vec![])],
2239        };
2240        narrow_read_columns_by_json_type_hint(&mut read_columns, &hint, metadata.as_ref());
2241        assert_eq!(
2242            read_columns,
2243            ReadColumns {
2244                cols: vec![ReadColumn::new(0, vec![])]
2245            }
2246        );
2247        Ok(())
2248    }
2249
2250    #[tokio::test]
2251    async fn test_build_scan_fingerprint_for_eligible_scan() {
2252        let metadata = Arc::new(metadata_with_primary_key(vec![0, 1], false));
2253        let input = new_scan_input(
2254            metadata.clone(),
2255            vec![
2256                col("ts").gt_eq(ts_lit(1000)),
2257                col("k0").eq(lit("foo")),
2258                col("v0").gt(lit(1)),
2259            ],
2260        )
2261        .await
2262        .with_distribution(Some(TimeSeriesDistribution::PerSeries))
2263        .with_series_row_selector(Some(TimeSeriesRowSelector::LastRow))
2264        .with_merge_mode(MergeMode::LastNonNull)
2265        .with_filter_deleted(false);
2266
2267        let fingerprint = build_scan_fingerprint(&input).unwrap();
2268
2269        let expected = ScanRequestFingerprintBuilder {
2270            read_columns: input.read_cols,
2271            read_column_types: vec![
2272                metadata
2273                    .column_by_id(0)
2274                    .map(|col| col.column_schema.data_type.clone()),
2275                metadata
2276                    .column_by_id(2)
2277                    .map(|col| col.column_schema.data_type.clone()),
2278                metadata
2279                    .column_by_id(3)
2280                    .map(|col| col.column_schema.data_type.clone()),
2281            ],
2282            filters: vec![
2283                col("k0").eq(lit("foo")).to_string(),
2284                col("v0").gt(lit(1)).to_string(),
2285            ],
2286            time_filters: vec![col("ts").gt_eq(ts_lit(1000)).to_string()],
2287            series_row_selector: Some(TimeSeriesRowSelector::LastRow),
2288            append_mode: false,
2289            filter_deleted: false,
2290            merge_mode: MergeMode::LastNonNull,
2291            partition_expr_version: 0,
2292        }
2293        .build();
2294        assert_eq!(expected, fingerprint.fingerprint);
2295    }
2296
2297    #[tokio::test]
2298    async fn test_build_scan_fingerprint_requires_tag_filter() {
2299        let metadata = Arc::new(metadata_with_primary_key(vec![0, 1], false));
2300        let input = new_scan_input(
2301            metadata,
2302            vec![col("ts").gt_eq(lit(1000)), col("v0").gt(lit(1))],
2303        )
2304        .await;
2305
2306        assert!(build_scan_fingerprint(&input).is_none());
2307    }
2308
2309    #[tokio::test]
2310    async fn test_build_scan_fingerprint_respects_scan_eligibility() {
2311        let metadata = Arc::new(metadata_with_primary_key(vec![0, 1], false));
2312        let filters = vec![col("k0").eq(lit("foo"))];
2313
2314        let disabled = ScanInput::new(
2315            SchedulerEnv::new().await.access_layer.clone(),
2316            FlatProjectionMapper::new(&metadata, [0, 2, 3].into_iter()).unwrap(),
2317        )
2318        .with_predicate(PredicateGroup::new(metadata.as_ref(), &filters).unwrap());
2319        assert!(build_scan_fingerprint(&disabled).is_none());
2320
2321        let compaction = new_scan_input(metadata.clone(), filters.clone())
2322            .await
2323            .with_compaction(true);
2324        assert!(build_scan_fingerprint(&compaction).is_none());
2325
2326        // No files to read.
2327        let no_files = new_scan_input(metadata, filters).await.with_files(vec![]);
2328        assert!(build_scan_fingerprint(&no_files).is_none());
2329    }
2330
2331    #[tokio::test]
2332    async fn test_build_scan_fingerprint_tracks_schema_and_partition_expr_changes() {
2333        let base = metadata_with_primary_key(vec![0, 1], false);
2334        let mut builder = RegionMetadataBuilder::from_existing(base);
2335        let partition_expr = partition_col("k0")
2336            .gt_eq(Value::String("foo".into()))
2337            .as_json_str()
2338            .unwrap();
2339        builder.partition_expr_json(Some(partition_expr));
2340        let metadata = Arc::new(builder.build_without_validation().unwrap());
2341
2342        let input = new_scan_input(metadata.clone(), vec![col("k0").eq(lit("foo"))]).await;
2343        let fingerprint = build_scan_fingerprint(&input).unwrap();
2344
2345        let expected = ScanRequestFingerprintBuilder {
2346            read_columns: input.read_cols,
2347            read_column_types: vec![
2348                metadata
2349                    .column_by_id(0)
2350                    .map(|col| col.column_schema.data_type.clone()),
2351                metadata
2352                    .column_by_id(2)
2353                    .map(|col| col.column_schema.data_type.clone()),
2354                metadata
2355                    .column_by_id(3)
2356                    .map(|col| col.column_schema.data_type.clone()),
2357            ],
2358            filters: vec![col("k0").eq(lit("foo")).to_string()],
2359            time_filters: vec![],
2360            series_row_selector: None,
2361            append_mode: false,
2362            filter_deleted: true,
2363            merge_mode: MergeMode::LastRow,
2364            partition_expr_version: metadata.partition_expr_version,
2365        }
2366        .build();
2367        assert_eq!(expected, fingerprint.fingerprint);
2368        assert_ne!(0, metadata.partition_expr_version);
2369    }
2370
2371    #[test]
2372    fn test_update_dyn_filters_with_empty_base_predicates() {
2373        let metadata = Arc::new(metadata_with_primary_key(vec![0, 1], false));
2374        let predicate_group = PredicateGroup::new(metadata.as_ref(), &[]).unwrap();
2375        assert!(predicate_group.predicate().is_none());
2376        assert!(predicate_group.predicate_without_region().is_none());
2377
2378        let dyn_filter = Arc::new(DynamicFilterPhysicalExpr::new(vec![], physical_lit(false)));
2379        predicate_group.add_dyn_filters(vec![dyn_filter]);
2380
2381        let predicate_all = predicate_group.predicate().unwrap();
2382        assert!(predicate_all.exprs().is_empty());
2383        assert_eq!(1, predicate_all.dyn_filters().len());
2384
2385        let predicate_without_region = predicate_group.predicate_without_region().unwrap();
2386        assert!(predicate_without_region.exprs().is_empty());
2387        assert_eq!(1, predicate_without_region.dyn_filters().len());
2388    }
2389
2390    #[test]
2391    fn test_file_level_pruning_stats_prunes_old_file() {
2392        let ts_col_name = "ts";
2393        let predicate = Predicate::new(vec![col(ts_col_name).gt(ts_lit(1000))]);
2394        let arrow_schema = Arc::new(ArrowSchema::new(vec![Field::new(
2395            ts_col_name,
2396            ArrowDataType::Timestamp(ArrowTimeUnit::Millisecond, None),
2397            false,
2398        )]));
2399
2400        // File with time range [0ms, 500ms] is completely before `ts > 1000ms`.
2401        let stats = FileLevelPruningStats {
2402            min_scalar: ScalarValue::TimestampMillisecond(Some(0), None),
2403            max_scalar: ScalarValue::TimestampMillisecond(Some(500), None),
2404            time_index_col_name: ts_col_name.to_string(),
2405        };
2406        assert_eq!(
2407            vec![false],
2408            predicate.prune_with_stats(&stats, &arrow_schema)
2409        );
2410
2411        // File with time range [0ms, 2000ms] overlaps `ts > 1000ms`, so keep it.
2412        let stats = FileLevelPruningStats {
2413            min_scalar: ScalarValue::TimestampMillisecond(Some(0), None),
2414            max_scalar: ScalarValue::TimestampMillisecond(Some(2000), None),
2415            time_index_col_name: ts_col_name.to_string(),
2416        };
2417        assert_eq!(
2418            vec![true],
2419            predicate.prune_with_stats(&stats, &arrow_schema)
2420        );
2421    }
2422
2423    #[test]
2424    fn test_file_level_pruning_stats_no_predicate_keeps_all() {
2425        let predicate = Predicate::new(vec![]);
2426        assert!(predicate.is_empty());
2427
2428        let stats = FileLevelPruningStats {
2429            min_scalar: ScalarValue::TimestampMillisecond(Some(0), None),
2430            max_scalar: ScalarValue::TimestampMillisecond(Some(500), None),
2431            time_index_col_name: "ts".to_string(),
2432        };
2433        let arrow_schema = Arc::new(ArrowSchema::new(Vec::<Field>::new()));
2434        assert_eq!(
2435            vec![true],
2436            predicate.prune_with_stats(&stats, &arrow_schema)
2437        );
2438    }
2439
2440    #[tokio::test]
2441    async fn test_file_level_pruning_stats_ceil_max_unit_conversion() {
2442        let metadata = metadata_with_time_index_unit(TimeUnit::Millisecond);
2443        let input = new_scan_input(metadata, vec![]).await;
2444        let file = file_handle_with_time_range(
2445            Timestamp::new(1_000_001, TimeUnit::Nanosecond),
2446            Timestamp::new(1_000_001, TimeUnit::Nanosecond),
2447        );
2448
2449        let stats = input.try_file_level_pruning_stats(&file).unwrap();
2450        assert_eq!(
2451            ScalarValue::TimestampMillisecond(Some(1), None),
2452            stats.min_scalar
2453        );
2454        assert_eq!(
2455            ScalarValue::TimestampMillisecond(Some(2), None),
2456            stats.max_scalar
2457        );
2458
2459        // The actual max timestamp is slightly greater than 1ms. It must be kept for `ts > 1ms`.
2460        let predicate = Predicate::new(vec![col("ts").gt(ts_lit(1))]);
2461        assert_eq!(
2462            vec![true],
2463            predicate.prune_with_stats(&stats, input.mapper.metadata().schema.arrow_schema())
2464        );
2465    }
2466
2467    #[tokio::test]
2468    async fn test_file_level_pruning_stats_overflow_keeps_file() {
2469        let metadata = metadata_with_time_index_unit(TimeUnit::Nanosecond);
2470        let input = new_scan_input(metadata, vec![]).await;
2471        let file = file_handle_with_time_range(
2472            Timestamp::new(0, TimeUnit::Second),
2473            Timestamp::new(i64::MAX, TimeUnit::Second),
2474        );
2475
2476        assert!(input.try_file_level_pruning_stats(&file).is_none());
2477    }
2478
2479    #[test]
2480    fn test_file_level_pruning_stats_keeps_inclusive_boundary() {
2481        let ts_col_name = "ts";
2482        let predicate = Predicate::new(vec![col(ts_col_name).gt_eq(ts_lit(1000))]);
2483        let arrow_schema = Arc::new(ArrowSchema::new(vec![Field::new(
2484            ts_col_name,
2485            ArrowDataType::Timestamp(ArrowTimeUnit::Millisecond, None),
2486            false,
2487        )]));
2488        let stats = FileLevelPruningStats {
2489            min_scalar: ScalarValue::TimestampMillisecond(Some(0), None),
2490            max_scalar: ScalarValue::TimestampMillisecond(Some(1000), None),
2491            time_index_col_name: ts_col_name.to_string(),
2492        };
2493
2494        assert_eq!(
2495            vec![true],
2496            predicate.prune_with_stats(&stats, &arrow_schema)
2497        );
2498    }
2499
2500    #[tokio::test]
2501    async fn test_file_level_pruning_with_dyn_filter_only_predicate() {
2502        let metadata = Arc::new(metadata_with_primary_key(vec![0, 1], false));
2503        let mapper = FlatProjectionMapper::new(&metadata, [0, 2, 3]).unwrap();
2504        let predicate_group = PredicateGroup::new(metadata.as_ref(), &[]).unwrap();
2505        predicate_group.add_dyn_filters(vec![Arc::new(DynamicFilterPhysicalExpr::new(
2506            vec![],
2507            physical_lit(false),
2508        ))]);
2509        let input = ScanInput::new(SchedulerEnv::new().await.access_layer.clone(), mapper)
2510            .with_predicate(predicate_group);
2511        let file = file_handle_with_time_range(
2512            Timestamp::new_millisecond(0),
2513            Timestamp::new_millisecond(1000),
2514        );
2515        let mut reader_metrics = ReaderMetrics::default();
2516
2517        let builder = input
2518            .prune_file(&file, PreFilterMode::SkipFields, &mut reader_metrics)
2519            .await
2520            .unwrap();
2521
2522        assert_eq!(1, reader_metrics.filter_metrics.files_time_range_pruned);
2523        let mut ranges = SmallVec::new();
2524        builder.build_ranges(-1, &mut ranges);
2525        assert!(ranges.is_empty());
2526    }
2527
2528    #[tokio::test]
2529    async fn test_manifest_pruning_observes_dynamic_filter_update() {
2530        let metadata = Arc::new(metadata_with_primary_key(vec![0, 1], false));
2531        let mapper = FlatProjectionMapper::new(&metadata, [0, 2, 3]).unwrap();
2532        let predicate_group = PredicateGroup::new(metadata.as_ref(), &[]).unwrap();
2533        let arrow_schema = metadata.schema.arrow_schema();
2534        let ts_expr = physical_col("ts", arrow_schema.as_ref()).unwrap();
2535        let dyn_filter = Arc::new(DynamicFilterPhysicalExpr::new(
2536            vec![ts_expr.clone()],
2537            physical_lit(true),
2538        ));
2539        predicate_group.add_dyn_filters(vec![dyn_filter.clone()]);
2540        let input = ScanInput::new(SchedulerEnv::new().await.access_layer.clone(), mapper)
2541            .with_predicate(predicate_group);
2542        let file = file_handle_with_time_range(
2543            Timestamp::new_millisecond(0),
2544            Timestamp::new_millisecond(1000),
2545        );
2546
2547        assert!(!input.can_manifest_prune_file(&file));
2548
2549        let updated = physical_binary(
2550            ts_expr,
2551            Operator::Gt,
2552            physical_lit(ScalarValue::TimestampMillisecond(Some(1000), None)),
2553            arrow_schema.as_ref(),
2554        )
2555        .unwrap();
2556        dyn_filter.update(updated).unwrap();
2557
2558        assert!(input.can_manifest_prune_file(&file));
2559    }
2560
2561    #[tokio::test]
2562    async fn test_range_pre_filter_mode() {
2563        let metadata = Arc::new(metadata_with_primary_key(vec![0, 1], false));
2564        let cases = [
2565            (true, MergeMode::LastRow, 1, PreFilterMode::All),
2566            (false, MergeMode::LastNonNull, 1, PreFilterMode::All),
2567            (false, MergeMode::LastRow, 2, PreFilterMode::SkipFields),
2568            (true, MergeMode::LastRow, 2, PreFilterMode::All),
2569        ];
2570
2571        for (append_mode, merge_mode, source_count, expected_mode) in cases {
2572            let input = new_scan_input(metadata.clone(), vec![])
2573                .await
2574                .with_append_mode(append_mode)
2575                .with_merge_mode(merge_mode);
2576
2577            assert_eq!(expected_mode, input.range_pre_filter_mode(source_count));
2578        }
2579    }
2580}