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