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_structured_json_field;
38use datatypes::types::json_type::JsonNativeType;
39use datatypes::value::timestamp_to_scalar_value;
40use futures::StreamExt;
41use itertools::Itertools;
42use partition::expr::PartitionExpr;
43use smallvec::SmallVec;
44use snafu::{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_structured_json_field);
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, 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        predicate: Option<Predicate>,
1288        reader_metrics: &mut ReaderMetrics,
1289    ) -> Result<FileRangeBuilder> {
1290        let may_build_selective_row_selection = predicate.is_some();
1291        let decode_pk_values = !self.compaction
1292            && self
1293                .mapper
1294                .read_columns()
1295                .column_ids_iter()
1296                .any(|column_id| self.mapper.metadata().primary_key.contains(&column_id));
1297        let reader = self
1298            .access_layer
1299            .read_sst(file.clone())
1300            .predicate(predicate)
1301            .projection(Some(self.read_cols.clone()))
1302            .cache(self.cache_strategy.clone())
1303            .inverted_index_appliers(self.inverted_index_appliers.clone())
1304            .bloom_filter_index_appliers(self.bloom_filter_index_appliers.clone())
1305            .fulltext_index_appliers(self.fulltext_index_appliers.clone());
1306        let reader = reader.batch_size(self.batch_size);
1307        let reader = if !self.compaction && may_build_selective_row_selection {
1308            reader.deferred_optional_page_index()
1309        } else {
1310            reader
1311        };
1312        #[cfg(feature = "vector_index")]
1313        let reader = {
1314            let mut reader = reader;
1315            reader =
1316                reader.vector_index_applier(self.vector_index_applier.clone(), self.vector_index_k);
1317            reader
1318        };
1319        let res = reader
1320            .expected_metadata(Some(self.mapper.metadata().clone()))
1321            .compaction(self.compaction)
1322            .pre_filter_mode(pre_filter_mode)
1323            .decode_primary_key_values(decode_pk_values)
1324            .build_reader_input(reader_metrics)
1325            .await;
1326        let read_input = match res {
1327            Ok(x) => x,
1328            Err(e) => {
1329                if e.is_object_not_found() && self.ignore_file_not_found {
1330                    error!(e; "File to scan does not exist, region_id: {}, file: {}", file.region_id(), file.file_id());
1331                    return Ok(FileRangeBuilder::default());
1332                } else {
1333                    return Err(e);
1334                }
1335            }
1336        };
1337
1338        let Some((mut file_range_ctx, selection)) = read_input else {
1339            return Ok(FileRangeBuilder::default());
1340        };
1341
1342        let need_compat = !compat::has_same_columns_and_pk_encoding(
1343            &self.mapper,
1344            file_range_ctx.read_format(),
1345            self.compaction,
1346        );
1347        if need_compat {
1348            // They have different schema. We need to adapt the batch first so the
1349            // mapper can convert it.
1350            let compat = FlatCompatBatch::try_new(
1351                &self.mapper,
1352                file_range_ctx.read_format(),
1353                self.compaction,
1354            )?;
1355            file_range_ctx.set_compat_batch(compat);
1356        }
1357        Ok(FileRangeBuilder::new(Arc::new(file_range_ctx), selection))
1358    }
1359
1360    /// Scans flat sources (RecordBatch streams) in parallel.
1361    ///
1362    /// # Panics if the input doesn't allow parallel scan.
1363    #[tracing::instrument(
1364        skip(self, sources, semaphore),
1365        fields(
1366            region_id = %self.region_metadata().region_id,
1367            source_count = sources.len()
1368        )
1369    )]
1370    pub(crate) fn create_parallel_flat_sources(
1371        &self,
1372        sources: Vec<BoxedRecordBatchStream>,
1373        semaphore: Arc<Semaphore>,
1374        channel_size: usize,
1375    ) -> Result<Vec<BoxedRecordBatchStream>> {
1376        if sources.len() <= 1 {
1377            return Ok(sources);
1378        }
1379
1380        // Spawn a task for each source.
1381        let sources = sources
1382            .into_iter()
1383            .map(|source| {
1384                let (sender, receiver) = mpsc::channel(channel_size);
1385                self.spawn_flat_scan_task(source, semaphore.clone(), sender);
1386                let stream = Box::pin(ReceiverStream::new(receiver));
1387                Box::pin(stream) as _
1388            })
1389            .collect();
1390        Ok(sources)
1391    }
1392
1393    /// Spawns a task to scan a flat source (RecordBatch stream) asynchronously.
1394    #[tracing::instrument(
1395        skip(self, input, semaphore, sender),
1396        fields(region_id = %self.region_metadata().region_id)
1397    )]
1398    pub(crate) fn spawn_flat_scan_task(
1399        &self,
1400        mut input: BoxedRecordBatchStream,
1401        semaphore: Arc<Semaphore>,
1402        sender: mpsc::Sender<Result<RecordBatch>>,
1403    ) {
1404        let region_id = self.region_metadata().region_id;
1405        let span = tracing::info_span!(
1406            "ScanInput::parallel_scan_task",
1407            region_id = %region_id,
1408            stream_kind = "flat"
1409        );
1410        common_runtime::spawn_query(
1411            async move {
1412                loop {
1413                    // We release the permit before sending result to avoid the task waiting on
1414                    // the channel with the permit held.
1415                    let maybe_batch = {
1416                        // Safety: We never close the semaphore.
1417                        let _permit = semaphore.acquire().await.unwrap();
1418                        input.next().await
1419                    };
1420                    match maybe_batch {
1421                        Some(Ok(batch)) => {
1422                            let _ = sender.send(Ok(batch)).await;
1423                        }
1424                        Some(Err(e)) => {
1425                            let _ = sender.send(Err(e)).await;
1426                            break;
1427                        }
1428                        None => break,
1429                    }
1430                }
1431            }
1432            .instrument(span),
1433        );
1434    }
1435
1436    pub(crate) fn total_rows(&self) -> usize {
1437        let rows_in_files: usize = self.files.iter().map(|f| f.num_rows()).sum();
1438        let rows_in_memtables: usize = self.memtables.iter().map(|m| m.stats().num_rows()).sum();
1439
1440        let rows = rows_in_files + rows_in_memtables;
1441        #[cfg(feature = "enterprise")]
1442        let rows = rows
1443            + self
1444                .extension_ranges
1445                .iter()
1446                .map(|x| x.num_rows())
1447                .sum::<u64>() as usize;
1448        rows
1449    }
1450
1451    pub(crate) fn predicate_group(&self) -> &PredicateGroup {
1452        &self.predicate
1453    }
1454
1455    /// Returns number of memtables to scan.
1456    pub(crate) fn num_memtables(&self) -> usize {
1457        self.memtables.len()
1458    }
1459
1460    /// Returns number of SST files to scan.
1461    pub(crate) fn num_files(&self) -> usize {
1462        self.files.len()
1463    }
1464
1465    /// Gets the file handle from a row group index.
1466    pub(crate) fn file_from_index(&self, index: RowGroupIndex) -> &FileHandle {
1467        let file_index = index.index - self.num_memtables();
1468        &self.files[file_index]
1469    }
1470
1471    pub fn region_metadata(&self) -> &RegionMetadataRef {
1472        self.mapper.metadata()
1473    }
1474
1475    fn range_pre_filter_mode(&self, source_count: usize) -> PreFilterMode {
1476        if source_count <= 1 {
1477            // Duplicated rows in the same source is not a normal case and we don't provide
1478            // strict dedup semantic (last_row/last_non_null) for it. We expect the duplicated rows
1479            // are exactly identical in the same source so we use PreFilterMode::All for
1480            // performance reason.
1481            return PreFilterMode::All;
1482        }
1483
1484        pre_filter_mode(self.append_mode, self.merge_mode)
1485    }
1486}
1487
1488#[cfg(feature = "enterprise")]
1489impl ScanInput {
1490    #[must_use]
1491    pub(crate) fn with_extension_ranges(self, extension_ranges: Vec<BoxedExtensionRange>) -> Self {
1492        Self {
1493            extension_ranges,
1494            ..self
1495        }
1496    }
1497
1498    #[cfg(feature = "enterprise")]
1499    pub(crate) fn extension_ranges(&self) -> &[BoxedExtensionRange] {
1500        &self.extension_ranges
1501    }
1502
1503    /// Get a boxed [ExtensionRange] by the index in all ranges.
1504    #[cfg(feature = "enterprise")]
1505    pub(crate) fn extension_range(&self, i: usize) -> &BoxedExtensionRange {
1506        &self.extension_ranges[i - self.num_memtables() - self.num_files()]
1507    }
1508}
1509
1510/// Lightweight [PruningStatistics] that only uses the file-level time range from manifest
1511/// metadata, avoiding any parquet metadata reads. Used for early file-level pruning before
1512/// accessing row-group-level statistics.
1513pub(crate) struct FileLevelPruningStats {
1514    /// Scalar value for the file's minimum timestamp in the time index column's unit.
1515    pub(crate) min_scalar: ScalarValue,
1516    /// Scalar value for the file's maximum timestamp in the time index column's unit.
1517    pub(crate) max_scalar: ScalarValue,
1518    /// Name of the time index column.
1519    pub(crate) time_index_col_name: String,
1520}
1521
1522impl PruningStatistics for FileLevelPruningStats {
1523    fn min_values(&self, column: &Column) -> Option<ArrayRef> {
1524        if column.name == self.time_index_col_name {
1525            ScalarValue::iter_to_array(std::iter::once(self.min_scalar.clone())).ok()
1526        } else {
1527            None
1528        }
1529    }
1530
1531    fn max_values(&self, column: &Column) -> Option<ArrayRef> {
1532        if column.name == self.time_index_col_name {
1533            ScalarValue::iter_to_array(std::iter::once(self.max_scalar.clone())).ok()
1534        } else {
1535            None
1536        }
1537    }
1538
1539    fn num_containers(&self) -> usize {
1540        1
1541    }
1542
1543    fn null_counts(&self, column: &Column) -> Option<ArrayRef> {
1544        if column.name == self.time_index_col_name {
1545            // The time index column is NOT NULL.
1546            Some(Arc::new(UInt64Array::from(vec![0u64])))
1547        } else {
1548            None
1549        }
1550    }
1551
1552    fn row_counts(&self, _column: &Column) -> Option<ArrayRef> {
1553        None
1554    }
1555
1556    fn contained(&self, _column: &Column, _values: &HashSet<ScalarValue>) -> Option<BooleanArray> {
1557        None
1558    }
1559}
1560
1561#[cfg(test)]
1562impl ScanInput {
1563    /// Returns SST file ids to scan.
1564    pub(crate) fn file_ids(&self) -> Vec<crate::sst::file::RegionFileId> {
1565        self.files.iter().map(|file| file.file_id()).collect()
1566    }
1567
1568    pub(crate) fn index_ids(&self) -> Vec<crate::sst::file::RegionIndexId> {
1569        self.files.iter().map(|file| file.index_id()).collect()
1570    }
1571}
1572
1573fn pre_filter_mode(append_mode: bool, merge_mode: MergeMode) -> PreFilterMode {
1574    if append_mode {
1575        return PreFilterMode::All;
1576    }
1577
1578    match merge_mode {
1579        MergeMode::LastRow => PreFilterMode::SkipFields,
1580        MergeMode::LastNonNull => PreFilterMode::SkipFields,
1581    }
1582}
1583
1584fn json_nested_paths(column_name: &str, json_type: &JsonNativeType) -> Vec<NestedPath> {
1585    let mut paths = Vec::new();
1586    let mut current = vec![column_name.to_string()];
1587    collect_json_nested_paths(json_type, &mut current, &mut paths);
1588    paths
1589}
1590
1591fn collect_json_nested_paths(
1592    json_type: &JsonNativeType,
1593    current: &mut NestedPath,
1594    paths: &mut Vec<NestedPath>,
1595) {
1596    match json_type {
1597        JsonNativeType::Object(fields) if !fields.is_empty() => {
1598            for (field, child) in fields {
1599                current.push(field.clone());
1600                collect_json_nested_paths(child, current, paths);
1601                current.pop();
1602            }
1603        }
1604        _ => paths.push(current.clone()),
1605    }
1606}
1607
1608/// Output of [build_scan_fingerprint]: the cache fingerprint plus the derived
1609/// implied time range used to decide whether the cache key can drop the time
1610/// predicates for a given partition (see `build_range_cache_key`).
1611pub(crate) struct ScanFingerprintBundle {
1612    pub(crate) fingerprint: ScanRequestFingerprint,
1613    /// `Some(r)` = all time-only predicates are guaranteed true on `r` (in the
1614    /// column's `TimeUnit`).
1615    /// `None`    = at least one time-only predicate could not be proven (e.g.
1616    /// `OR`), so the cache-key optimization is disabled for this scan.
1617    pub(crate) implied_time_range: Option<TimestampRange>,
1618}
1619
1620/// Builds a [ScanFingerprintBundle] from a [ScanInput] if the scan is eligible
1621/// for partition range caching.
1622pub(crate) fn build_scan_fingerprint(input: &ScanInput) -> Option<ScanFingerprintBundle> {
1623    let eligible = !input.compaction
1624        && !input.files.is_empty()
1625        && matches!(input.cache_strategy, CacheStrategy::EnableAll(_));
1626
1627    if !eligible {
1628        return None;
1629    }
1630
1631    let metadata = input.region_metadata();
1632    let tag_names: HashSet<&str> = metadata
1633        .column_metadatas
1634        .iter()
1635        .filter(|col| col.semantic_type == SemanticType::Tag)
1636        .map(|col| col.column_schema.name.as_str())
1637        .collect();
1638
1639    let time_index = metadata.time_index_column();
1640    let time_index_name = time_index.column_schema.name.clone();
1641    let ts_col_unit = time_index
1642        .column_schema
1643        .data_type
1644        .as_timestamp()
1645        .expect("Time index must have timestamp-compatible type")
1646        .unit();
1647
1648    let exprs = input
1649        .predicate_group()
1650        .predicate_without_region()
1651        .map(|predicate| predicate.exprs())
1652        .unwrap_or_default();
1653
1654    let mut filters = Vec::new();
1655    let mut time_only_exprs: Vec<&Expr> = Vec::new();
1656    let mut has_tag_filter = false;
1657    let mut columns = HashSet::new();
1658
1659    for expr in exprs {
1660        columns.clear();
1661        let is_time_only = match expr_to_columns(expr, &mut columns) {
1662            Ok(()) if !columns.is_empty() => {
1663                has_tag_filter |= columns
1664                    .iter()
1665                    .any(|col| tag_names.contains(col.name.as_str()));
1666                columns.iter().all(|col| col.name == time_index_name)
1667            }
1668            _ => false,
1669        };
1670
1671        // Route time-only exprs that the legacy extractor recognizes into
1672        // `time_only_exprs` so the implication walker
1673        // (`implied_time_range_from_exprs`, called below) can attempt to drop
1674        // them from the cache key when the partition's `FileTimeRange` is fully
1675        // covered, then stringify them into the fingerprint's `time_filters`
1676        // bucket. Time-only exprs that the extractor doesn't recognize stay in
1677        // `filters` and never get stripped — conservatively correct.
1678        if is_time_only
1679            && extract_time_range_from_expr(&time_index_name, ts_col_unit, expr).is_some()
1680        {
1681            time_only_exprs.push(expr);
1682        } else {
1683            filters.push(expr.to_string());
1684        }
1685    }
1686
1687    if !has_tag_filter {
1688        // We only cache requests that have tag filters to avoid caching all series.
1689        return None;
1690    }
1691
1692    let implied_time_range =
1693        implied_time_range_from_exprs(&time_index_name, ts_col_unit, &time_only_exprs);
1694    let mut time_filters: Vec<String> = time_only_exprs.iter().map(|e| e.to_string()).collect();
1695
1696    // Ensure the filters are sorted for consistent fingerprinting.
1697    filters.sort_unstable();
1698    time_filters.sort_unstable();
1699    let read_columns = input.read_cols.clone();
1700    let fingerprint = crate::read::range_cache::ScanRequestFingerprintBuilder {
1701        read_column_types: read_columns
1702            .column_ids_iter()
1703            .map(|id| {
1704                metadata
1705                    .column_by_id(id)
1706                    .map(|col| col.column_schema.data_type.clone())
1707            })
1708            .collect(),
1709        read_columns,
1710        filters,
1711        time_filters,
1712        series_row_selector: input.series_row_selector,
1713        append_mode: input.append_mode,
1714        filter_deleted: input.filter_deleted,
1715        merge_mode: input.merge_mode,
1716        partition_expr_version: metadata.partition_expr_version,
1717    }
1718    .build();
1719
1720    Some(ScanFingerprintBundle {
1721        fingerprint,
1722        implied_time_range,
1723    })
1724}
1725
1726/// Context shared by different streams from a scanner.
1727/// It contains the input and ranges to scan.
1728pub struct StreamContext {
1729    /// Input memtables and files.
1730    pub input: ScanInput,
1731    /// Metadata for partition ranges.
1732    pub(crate) ranges: Vec<RangeMeta>,
1733    /// Precomputed scan fingerprint for partition range caching.
1734    /// `None` when the scan is not eligible for caching.
1735    #[allow(dead_code)]
1736    pub(crate) scan_fingerprint: Option<ScanRequestFingerprint>,
1737    /// Implied range of every time-only predicate, in the time index column's
1738    /// `TimeUnit`. Used by `build_range_cache_key` to decide whether the
1739    /// partition's `FileTimeRange` is fully covered (allowing `time_filters`
1740    /// to be stripped from the cache key). `None` when caching is ineligible
1741    /// or when the implication walker bailed on an unsupported shape (e.g.
1742    /// `OR`).
1743    pub(crate) scan_implied_time_range: Option<TimestampRange>,
1744
1745    // Metrics:
1746    /// The start time of the query.
1747    pub(crate) query_start: Instant,
1748}
1749
1750impl StreamContext {
1751    /// Creates a new [StreamContext] for [SeqScan].
1752    pub(crate) fn seq_scan_ctx(input: ScanInput) -> Self {
1753        let query_start = input.query_start.unwrap_or_else(Instant::now);
1754        let ranges = RangeMeta::seq_scan_ranges(&input);
1755        READ_SST_COUNT.observe(input.num_files() as f64);
1756        let (scan_fingerprint, scan_implied_time_range) = match build_scan_fingerprint(&input) {
1757            Some(b) => (Some(b.fingerprint), b.implied_time_range),
1758            None => (None, None),
1759        };
1760
1761        Self {
1762            input,
1763            ranges,
1764            scan_fingerprint,
1765            scan_implied_time_range,
1766            query_start,
1767        }
1768    }
1769
1770    /// Creates a new [StreamContext] for [UnorderedScan].
1771    pub(crate) fn unordered_scan_ctx(input: ScanInput) -> Self {
1772        let query_start = input.query_start.unwrap_or_else(Instant::now);
1773        let ranges = RangeMeta::unordered_scan_ranges(&input);
1774        READ_SST_COUNT.observe(input.num_files() as f64);
1775        let (scan_fingerprint, scan_implied_time_range) = match build_scan_fingerprint(&input) {
1776            Some(b) => (Some(b.fingerprint), b.implied_time_range),
1777            None => (None, None),
1778        };
1779
1780        Self {
1781            input,
1782            ranges,
1783            scan_fingerprint,
1784            scan_implied_time_range,
1785            query_start,
1786        }
1787    }
1788
1789    /// Returns true if the index refers to a memtable.
1790    pub(crate) fn is_mem_range_index(&self, index: RowGroupIndex) -> bool {
1791        self.input.num_memtables() > index.index
1792    }
1793
1794    pub(crate) fn is_file_range_index(&self, index: RowGroupIndex) -> bool {
1795        !self.is_mem_range_index(index)
1796            && index.index < self.input.num_files() + self.input.num_memtables()
1797    }
1798
1799    pub(crate) fn range_pre_filter_mode(&self, part_range: &PartitionRange) -> PreFilterMode {
1800        let range_meta = &self.ranges[part_range.identifier];
1801        let source_count = range_meta.indices.len();
1802
1803        self.input.range_pre_filter_mode(source_count)
1804    }
1805
1806    /// Retrieves the partition ranges.
1807    pub(crate) fn partition_ranges(&self) -> Vec<PartitionRange> {
1808        self.ranges
1809            .iter()
1810            .enumerate()
1811            .map(|(idx, range_meta)| range_meta.new_partition_range(idx))
1812            .collect()
1813    }
1814
1815    /// Format the context for explain.
1816    pub(crate) fn format_for_explain(&self, verbose: bool, f: &mut fmt::Formatter) -> fmt::Result {
1817        let (mut num_mem_ranges, mut num_file_ranges, mut num_other_ranges) = (0, 0, 0);
1818        for range_meta in &self.ranges {
1819            for idx in &range_meta.row_group_indices {
1820                if self.is_mem_range_index(*idx) {
1821                    num_mem_ranges += 1;
1822                } else if self.is_file_range_index(*idx) {
1823                    num_file_ranges += 1;
1824                } else {
1825                    num_other_ranges += 1;
1826                }
1827            }
1828        }
1829        if verbose {
1830            write!(f, "{{")?;
1831        }
1832        write!(
1833            f,
1834            r#""partition_count":{{"count":{}, "mem_ranges":{}, "files":{}, "file_ranges":{}"#,
1835            self.ranges.len(),
1836            num_mem_ranges,
1837            self.input.num_files(),
1838            num_file_ranges,
1839        )?;
1840        if num_other_ranges > 0 {
1841            write!(f, r#", "other_ranges":{}"#, num_other_ranges)?;
1842        }
1843        write!(f, "}}")?;
1844
1845        if let Some(selector) = &self.input.series_row_selector {
1846            write!(f, ", \"selector\":\"{}\"", selector)?;
1847        }
1848        if let Some(distribution) = &self.input.distribution {
1849            write!(f, ", \"distribution\":\"{}\"", distribution)?;
1850        }
1851
1852        if verbose {
1853            self.format_verbose_content(f)?;
1854        }
1855
1856        Ok(())
1857    }
1858
1859    fn format_verbose_content(&self, f: &mut fmt::Formatter) -> fmt::Result {
1860        struct FileWrapper<'a> {
1861            file: &'a FileHandle,
1862        }
1863
1864        impl fmt::Debug for FileWrapper<'_> {
1865            fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1866                let (start, end) = self.file.time_range();
1867                write!(
1868                    f,
1869                    r#"{{"file_id":"{}","time_range_start":"{}::{}","time_range_end":"{}::{}","rows":{},"size":{},"index_size":{}}}"#,
1870                    self.file.file_id(),
1871                    start.value(),
1872                    start.unit(),
1873                    end.value(),
1874                    end.unit(),
1875                    self.file.num_rows(),
1876                    self.file.size(),
1877                    self.file.index_size()
1878                )
1879            }
1880        }
1881
1882        struct InputWrapper<'a> {
1883            input: &'a ScanInput,
1884        }
1885
1886        #[cfg(feature = "enterprise")]
1887        impl InputWrapper<'_> {
1888            fn format_extension_ranges(&self, f: &mut fmt::Formatter) -> fmt::Result {
1889                if self.input.extension_ranges.is_empty() {
1890                    return Ok(());
1891                }
1892
1893                let mut delimiter = "";
1894                write!(f, ", extension_ranges: [")?;
1895                for range in self.input.extension_ranges() {
1896                    write!(f, "{}{:?}", delimiter, range)?;
1897                    delimiter = ", ";
1898                }
1899                write!(f, "]")?;
1900                Ok(())
1901            }
1902        }
1903
1904        impl fmt::Debug for InputWrapper<'_> {
1905            fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1906                let output_schema = self.input.mapper.output_schema();
1907                if !output_schema.is_empty() {
1908                    let names: Vec<_> = output_schema
1909                        .column_schemas()
1910                        .iter()
1911                        .map(|col| &col.name)
1912                        .collect();
1913                    write!(f, ", \"projection\": {:?}", names)?;
1914                }
1915                if let Some(predicate) = &self.input.predicate.predicate() {
1916                    if !predicate.exprs().is_empty() {
1917                        let exprs: Vec<_> =
1918                            predicate.exprs().iter().map(|e| e.to_string()).collect();
1919                        write!(f, ", \"filters\": {:?}", exprs)?;
1920                    }
1921                    if !predicate.dyn_filters().is_empty() {
1922                        let dyn_filters: Vec<_> = predicate
1923                            .dyn_filters()
1924                            .iter()
1925                            .map(|f| format!("{}", f))
1926                            .collect();
1927                        write!(f, ", \"dyn_filters\": {:?}", dyn_filters)?;
1928                    }
1929                }
1930                #[cfg(feature = "vector_index")]
1931                if let Some(vector_index_k) = self.input.vector_index_k {
1932                    write!(f, ", \"vector_index_k\": {}", vector_index_k)?;
1933                }
1934                if !self.input.files.is_empty() {
1935                    write!(f, ", \"files\": ")?;
1936                    f.debug_list()
1937                        .entries(self.input.files.iter().map(|file| FileWrapper { file }))
1938                        .finish()?;
1939                }
1940                write!(f, ", \"flat_format\": {}", self.input.explain_flat_format)?;
1941                #[cfg(feature = "enterprise")]
1942                self.format_extension_ranges(f)?;
1943
1944                Ok(())
1945            }
1946        }
1947
1948        write!(f, "{:?}", InputWrapper { input: &self.input })
1949    }
1950
1951    /// Add new dynamic filters to the predicates.
1952    /// Safe after stream creation; in-flight reads may still observe an older snapshot.
1953    pub(crate) fn add_dyn_filter_to_predicate(
1954        self: &Arc<Self>,
1955        filter_exprs: Vec<Arc<dyn datafusion::physical_plan::PhysicalExpr>>,
1956    ) -> Vec<bool> {
1957        let mut supported = Vec::with_capacity(filter_exprs.len());
1958        let filter_expr = filter_exprs
1959            .into_iter()
1960            .filter_map(|expr| {
1961                if let Ok(dyn_filter) = (expr as Arc<dyn std::any::Any + Send + Sync + 'static>)
1962                .downcast::<datafusion::physical_plan::expressions::DynamicFilterPhysicalExpr>()
1963            {
1964                supported.push(true);
1965                Some(dyn_filter)
1966            } else {
1967                supported.push(false);
1968                None
1969            }
1970            })
1971            .collect();
1972        self.input.predicate.add_dyn_filters(filter_expr);
1973        supported
1974    }
1975}
1976
1977/// Predicates to evaluate.
1978/// It only keeps filters that [SimpleFilterEvaluator] supports.
1979#[derive(Clone, Default)]
1980pub struct PredicateGroup {
1981    time_filters: Option<Arc<Vec<SimpleFilterEvaluator>>>,
1982    /// Predicate that includes request filters and region partition expr (if any).
1983    predicate_all: Predicate,
1984    /// Predicate that only includes request filters.
1985    predicate_without_region: Predicate,
1986    /// Region partition expression restored from metadata.
1987    region_partition_expr: Option<PartitionExpr>,
1988}
1989
1990impl PredicateGroup {
1991    /// Creates a new `PredicateGroup` from exprs according to the metadata.
1992    pub fn new(metadata: &RegionMetadata, exprs: &[Expr]) -> Result<Self> {
1993        let mut combined_exprs = exprs.to_vec();
1994        let mut region_partition_expr = None;
1995
1996        if let Some(expr_json) = metadata.partition_expr.as_ref()
1997            && !expr_json.is_empty()
1998            && let Some(expr) = PartitionExpr::from_json_str(expr_json)
1999                .context(InvalidPartitionExprSnafu { expr: expr_json })?
2000        {
2001            let logical_expr = expr
2002                .try_as_logical_expr()
2003                .context(InvalidPartitionExprSnafu {
2004                    expr: expr_json.clone(),
2005                })?;
2006
2007            combined_exprs.push(logical_expr);
2008            region_partition_expr = Some(expr);
2009        }
2010
2011        let mut time_filters = Vec::with_capacity(combined_exprs.len());
2012        // Columns in the expr.
2013        let mut columns = HashSet::new();
2014        for expr in &combined_exprs {
2015            columns.clear();
2016            let Some(filter) = Self::expr_to_filter(expr, metadata, &mut columns) else {
2017                continue;
2018            };
2019            time_filters.push(filter);
2020        }
2021        let time_filters = if time_filters.is_empty() {
2022            None
2023        } else {
2024            Some(Arc::new(time_filters))
2025        };
2026
2027        let predicate_all = Predicate::new(combined_exprs);
2028        let predicate_without_region = Predicate::new(exprs.to_vec());
2029
2030        Ok(Self {
2031            time_filters,
2032            predicate_all,
2033            predicate_without_region,
2034            region_partition_expr,
2035        })
2036    }
2037
2038    /// Returns time filters.
2039    pub(crate) fn time_filters(&self) -> Option<Arc<Vec<SimpleFilterEvaluator>>> {
2040        self.time_filters.clone()
2041    }
2042
2043    /// Returns predicate of all exprs (including region partition expr if present).
2044    pub(crate) fn predicate(&self) -> Option<&Predicate> {
2045        if self.predicate_all.is_empty() {
2046            None
2047        } else {
2048            Some(&self.predicate_all)
2049        }
2050    }
2051
2052    /// Returns predicate that excludes region partition expr.
2053    pub(crate) fn predicate_without_region(&self) -> Option<&Predicate> {
2054        if self.predicate_without_region.is_empty() {
2055            None
2056        } else {
2057            Some(&self.predicate_without_region)
2058        }
2059    }
2060
2061    /// Add dynamic filters in the predicates.
2062    pub(crate) fn add_dyn_filters(&self, dyn_filters: Vec<Arc<DynamicFilterPhysicalExpr>>) {
2063        self.predicate_all.add_dyn_filters(dyn_filters.clone());
2064        self.predicate_without_region.add_dyn_filters(dyn_filters);
2065    }
2066
2067    /// Returns the region partition expr from metadata, if any.
2068    pub(crate) fn region_partition_expr(&self) -> Option<&PartitionExpr> {
2069        self.region_partition_expr.as_ref()
2070    }
2071
2072    fn expr_to_filter(
2073        expr: &Expr,
2074        metadata: &RegionMetadata,
2075        columns: &mut HashSet<Column>,
2076    ) -> Option<SimpleFilterEvaluator> {
2077        columns.clear();
2078        // `expr_to_columns` won't return error.
2079        // We still ignore these expressions for safety.
2080        expr_to_columns(expr, columns).ok()?;
2081        if columns.len() > 1 {
2082            // Simple filter doesn't support multiple columns.
2083            return None;
2084        }
2085        let column = columns.iter().next()?;
2086        let column_meta = metadata.column_by_name(&column.name)?;
2087        if column_meta.semantic_type == SemanticType::Timestamp {
2088            SimpleFilterEvaluator::try_new(expr)
2089        } else {
2090            None
2091        }
2092    }
2093}
2094
2095#[cfg(test)]
2096mod tests {
2097    use std::sync::Arc;
2098
2099    use common_time::timestamp::{TimeUnit, Timestamp};
2100    use datafusion::physical_plan::expressions::{
2101        binary as physical_binary, col as physical_col, lit as physical_lit,
2102    };
2103    use datafusion_common::ScalarValue;
2104    use datafusion_expr::{Operator, col, lit};
2105    use datatypes::arrow::datatypes::{
2106        DataType as ArrowDataType, Field, Schema as ArrowSchema, TimeUnit as ArrowTimeUnit,
2107    };
2108    use datatypes::prelude::ConcreteDataType;
2109    use datatypes::schema::ColumnSchema;
2110    use datatypes::types::json_type::JsonObjectType;
2111    use datatypes::value::Value;
2112    use partition::expr::col as partition_col;
2113    use store_api::metadata::{ColumnMetadata, RegionMetadataBuilder};
2114    use store_api::storage::{RegionId, TimeSeriesDistribution, TimeSeriesRowSelector};
2115
2116    use super::*;
2117    use crate::cache::CacheManager;
2118    use crate::read::range_cache::ScanRequestFingerprintBuilder;
2119    use crate::sst::file::FileMeta;
2120    use crate::test_util::memtable_util::metadata_with_primary_key;
2121    use crate::test_util::scheduler_util::SchedulerEnv;
2122
2123    async fn new_scan_input(metadata: RegionMetadataRef, filters: Vec<Expr>) -> ScanInput {
2124        let env = SchedulerEnv::new().await;
2125        let mapper = FlatProjectionMapper::new(&metadata, [0, 2, 3]).unwrap();
2126        let predicate = PredicateGroup::new(metadata.as_ref(), &filters).unwrap();
2127        let file = FileHandle::new(
2128            crate::sst::file::FileMeta::default(),
2129            Arc::new(crate::sst::file_purger::NoopFilePurger),
2130        );
2131
2132        ScanInput::new(env.access_layer.clone(), mapper)
2133            .with_predicate(predicate)
2134            .with_cache(CacheStrategy::EnableAll(Arc::new(
2135                CacheManager::builder()
2136                    .range_result_cache_size(1024)
2137                    .build(),
2138            )))
2139            .with_files(vec![file])
2140    }
2141
2142    /// Helper to create a timestamp millisecond literal.
2143    fn ts_lit(val: i64) -> datafusion_expr::Expr {
2144        lit(ScalarValue::TimestampMillisecond(Some(val), None))
2145    }
2146
2147    fn metadata_with_time_index_unit(unit: TimeUnit) -> RegionMetadataRef {
2148        let mut builder = RegionMetadataBuilder::new(RegionId::new(123, 456));
2149        builder
2150            .push_column_metadata(ColumnMetadata {
2151                column_schema: ColumnSchema::new(
2152                    "k0".to_string(),
2153                    ConcreteDataType::string_datatype(),
2154                    false,
2155                ),
2156                semantic_type: SemanticType::Tag,
2157                column_id: 0,
2158            })
2159            .push_column_metadata(ColumnMetadata {
2160                column_schema: ColumnSchema::new(
2161                    "k1".to_string(),
2162                    ConcreteDataType::uint32_datatype(),
2163                    false,
2164                ),
2165                semantic_type: SemanticType::Tag,
2166                column_id: 1,
2167            })
2168            .push_column_metadata(ColumnMetadata {
2169                column_schema: ColumnSchema::new(
2170                    "ts".to_string(),
2171                    ConcreteDataType::timestamp_datatype(unit),
2172                    false,
2173                ),
2174                semantic_type: SemanticType::Timestamp,
2175                column_id: 2,
2176            })
2177            .push_column_metadata(ColumnMetadata {
2178                column_schema: ColumnSchema::new(
2179                    "v0".to_string(),
2180                    ConcreteDataType::int64_datatype(),
2181                    true,
2182                ),
2183                semantic_type: SemanticType::Field,
2184                column_id: 3,
2185            })
2186            .primary_key(vec![0, 1]);
2187
2188        Arc::new(builder.build().unwrap())
2189    }
2190
2191    fn file_handle_with_time_range(start: Timestamp, end: Timestamp) -> FileHandle {
2192        FileHandle::new(
2193            FileMeta {
2194                time_range: (start, end),
2195                ..Default::default()
2196            },
2197            Arc::new(crate::sst::file_purger::NoopFilePurger),
2198        )
2199    }
2200
2201    #[tokio::test]
2202    async fn test_scan_input_uses_explicit_batch_size() {
2203        let metadata = Arc::new(metadata_with_primary_key(vec![0, 1], false));
2204        let mapper = FlatProjectionMapper::new(&metadata, [0, 2, 3]).unwrap();
2205        let env = SchedulerEnv::new().await;
2206        let input = ScanInput::new(env.access_layer.clone(), mapper);
2207        assert_eq!(
2208            crate::sst::parquet::DEFAULT_READ_BATCH_SIZE,
2209            input.batch_size()
2210        );
2211
2212        let mapper = FlatProjectionMapper::new(&metadata, [0, 2, 3]).unwrap();
2213        let input = ScanInput::new(env.access_layer.clone(), mapper)
2214            .with_compaction(true)
2215            .with_batch_size(256);
2216        assert_eq!(256, input.batch_size());
2217
2218        let mapper = FlatProjectionMapper::new(&metadata, [0, 2, 3]).unwrap();
2219        let input = ScanInput::new(env.access_layer.clone(), mapper)
2220            .with_batch_size(256)
2221            .with_compaction(true)
2222            .with_compaction(false);
2223        assert_eq!(256, input.batch_size());
2224    }
2225
2226    #[test]
2227    fn test_fill_json_nested_paths_from_hint() -> Result<()> {
2228        let hint = JsonNativeType::Object(JsonObjectType::from([
2229            ("a".to_string(), JsonNativeType::i64()),
2230            (
2231                "b".to_string(),
2232                JsonNativeType::Object(JsonObjectType::from([(
2233                    "c".to_string(),
2234                    JsonNativeType::String,
2235                )])),
2236            ),
2237        ]));
2238
2239        fn nested_path(parts: &[&str]) -> NestedPath {
2240            parts.iter().map(|part| part.to_string()).collect()
2241        }
2242
2243        assert_eq!(
2244            json_nested_paths("j", &hint),
2245            vec![nested_path(&["j", "a"]), nested_path(&["j", "b", "c"])]
2246        );
2247        Ok(())
2248    }
2249
2250    #[tokio::test]
2251    async fn test_build_scan_fingerprint_for_eligible_scan() {
2252        let metadata = Arc::new(metadata_with_primary_key(vec![0, 1], false));
2253        let input = new_scan_input(
2254            metadata.clone(),
2255            vec![
2256                col("ts").gt_eq(ts_lit(1000)),
2257                col("k0").eq(lit("foo")),
2258                col("v0").gt(lit(1)),
2259            ],
2260        )
2261        .await
2262        .with_distribution(Some(TimeSeriesDistribution::PerSeries))
2263        .with_series_row_selector(Some(TimeSeriesRowSelector::LastRow))
2264        .with_merge_mode(MergeMode::LastNonNull)
2265        .with_filter_deleted(false);
2266
2267        let fingerprint = build_scan_fingerprint(&input).unwrap();
2268
2269        let expected = ScanRequestFingerprintBuilder {
2270            read_columns: input.read_cols,
2271            read_column_types: vec![
2272                metadata
2273                    .column_by_id(0)
2274                    .map(|col| col.column_schema.data_type.clone()),
2275                metadata
2276                    .column_by_id(2)
2277                    .map(|col| col.column_schema.data_type.clone()),
2278                metadata
2279                    .column_by_id(3)
2280                    .map(|col| col.column_schema.data_type.clone()),
2281            ],
2282            filters: vec![
2283                col("k0").eq(lit("foo")).to_string(),
2284                col("v0").gt(lit(1)).to_string(),
2285            ],
2286            time_filters: vec![col("ts").gt_eq(ts_lit(1000)).to_string()],
2287            series_row_selector: Some(TimeSeriesRowSelector::LastRow),
2288            append_mode: false,
2289            filter_deleted: false,
2290            merge_mode: MergeMode::LastNonNull,
2291            partition_expr_version: 0,
2292        }
2293        .build();
2294        assert_eq!(expected, fingerprint.fingerprint);
2295    }
2296
2297    #[tokio::test]
2298    async fn test_build_scan_fingerprint_requires_tag_filter() {
2299        let metadata = Arc::new(metadata_with_primary_key(vec![0, 1], false));
2300        let input = new_scan_input(
2301            metadata,
2302            vec![col("ts").gt_eq(lit(1000)), col("v0").gt(lit(1))],
2303        )
2304        .await;
2305
2306        assert!(build_scan_fingerprint(&input).is_none());
2307    }
2308
2309    #[tokio::test]
2310    async fn test_build_scan_fingerprint_respects_scan_eligibility() {
2311        let metadata = Arc::new(metadata_with_primary_key(vec![0, 1], false));
2312        let filters = vec![col("k0").eq(lit("foo"))];
2313
2314        let disabled = ScanInput::new(
2315            SchedulerEnv::new().await.access_layer.clone(),
2316            FlatProjectionMapper::new(&metadata, [0, 2, 3].into_iter()).unwrap(),
2317        )
2318        .with_predicate(PredicateGroup::new(metadata.as_ref(), &filters).unwrap());
2319        assert!(build_scan_fingerprint(&disabled).is_none());
2320
2321        let compaction = new_scan_input(metadata.clone(), filters.clone())
2322            .await
2323            .with_compaction(true);
2324        assert!(build_scan_fingerprint(&compaction).is_none());
2325
2326        // No files to read.
2327        let no_files = new_scan_input(metadata, filters).await.with_files(vec![]);
2328        assert!(build_scan_fingerprint(&no_files).is_none());
2329    }
2330
2331    #[tokio::test]
2332    async fn test_build_scan_fingerprint_tracks_schema_and_partition_expr_changes() {
2333        let base = metadata_with_primary_key(vec![0, 1], false);
2334        let mut builder = RegionMetadataBuilder::from_existing(base);
2335        let partition_expr = partition_col("k0")
2336            .gt_eq(Value::String("foo".into()))
2337            .as_json_str()
2338            .unwrap();
2339        builder.partition_expr_json(Some(partition_expr));
2340        let metadata = Arc::new(builder.build_without_validation().unwrap());
2341
2342        let input = new_scan_input(metadata.clone(), vec![col("k0").eq(lit("foo"))]).await;
2343        let fingerprint = build_scan_fingerprint(&input).unwrap();
2344
2345        let expected = ScanRequestFingerprintBuilder {
2346            read_columns: input.read_cols,
2347            read_column_types: vec![
2348                metadata
2349                    .column_by_id(0)
2350                    .map(|col| col.column_schema.data_type.clone()),
2351                metadata
2352                    .column_by_id(2)
2353                    .map(|col| col.column_schema.data_type.clone()),
2354                metadata
2355                    .column_by_id(3)
2356                    .map(|col| col.column_schema.data_type.clone()),
2357            ],
2358            filters: vec![col("k0").eq(lit("foo")).to_string()],
2359            time_filters: vec![],
2360            series_row_selector: None,
2361            append_mode: false,
2362            filter_deleted: true,
2363            merge_mode: MergeMode::LastRow,
2364            partition_expr_version: metadata.partition_expr_version,
2365        }
2366        .build();
2367        assert_eq!(expected, fingerprint.fingerprint);
2368        assert_ne!(0, metadata.partition_expr_version);
2369    }
2370
2371    #[test]
2372    fn test_update_dyn_filters_with_empty_base_predicates() {
2373        let metadata = Arc::new(metadata_with_primary_key(vec![0, 1], false));
2374        let predicate_group = PredicateGroup::new(metadata.as_ref(), &[]).unwrap();
2375        assert!(predicate_group.predicate().is_none());
2376        assert!(predicate_group.predicate_without_region().is_none());
2377
2378        let dyn_filter = Arc::new(DynamicFilterPhysicalExpr::new(vec![], physical_lit(false)));
2379        predicate_group.add_dyn_filters(vec![dyn_filter]);
2380
2381        let predicate_all = predicate_group.predicate().unwrap();
2382        assert!(predicate_all.exprs().is_empty());
2383        assert_eq!(1, predicate_all.dyn_filters().len());
2384
2385        let predicate_without_region = predicate_group.predicate_without_region().unwrap();
2386        assert!(predicate_without_region.exprs().is_empty());
2387        assert_eq!(1, predicate_without_region.dyn_filters().len());
2388    }
2389
2390    #[test]
2391    fn test_file_level_pruning_stats_prunes_old_file() {
2392        let ts_col_name = "ts";
2393        let predicate = Predicate::new(vec![col(ts_col_name).gt(ts_lit(1000))]);
2394        let arrow_schema = Arc::new(ArrowSchema::new(vec![Field::new(
2395            ts_col_name,
2396            ArrowDataType::Timestamp(ArrowTimeUnit::Millisecond, None),
2397            false,
2398        )]));
2399
2400        // File with time range [0ms, 500ms] is completely before `ts > 1000ms`.
2401        let stats = FileLevelPruningStats {
2402            min_scalar: ScalarValue::TimestampMillisecond(Some(0), None),
2403            max_scalar: ScalarValue::TimestampMillisecond(Some(500), None),
2404            time_index_col_name: ts_col_name.to_string(),
2405        };
2406        assert_eq!(
2407            vec![false],
2408            predicate.prune_with_stats(&stats, &arrow_schema)
2409        );
2410
2411        // File with time range [0ms, 2000ms] overlaps `ts > 1000ms`, so keep it.
2412        let stats = FileLevelPruningStats {
2413            min_scalar: ScalarValue::TimestampMillisecond(Some(0), None),
2414            max_scalar: ScalarValue::TimestampMillisecond(Some(2000), None),
2415            time_index_col_name: ts_col_name.to_string(),
2416        };
2417        assert_eq!(
2418            vec![true],
2419            predicate.prune_with_stats(&stats, &arrow_schema)
2420        );
2421    }
2422
2423    #[test]
2424    fn test_file_level_pruning_stats_no_predicate_keeps_all() {
2425        let predicate = Predicate::new(vec![]);
2426        assert!(predicate.is_empty());
2427
2428        let stats = FileLevelPruningStats {
2429            min_scalar: ScalarValue::TimestampMillisecond(Some(0), None),
2430            max_scalar: ScalarValue::TimestampMillisecond(Some(500), None),
2431            time_index_col_name: "ts".to_string(),
2432        };
2433        let arrow_schema = Arc::new(ArrowSchema::new(Vec::<Field>::new()));
2434        assert_eq!(
2435            vec![true],
2436            predicate.prune_with_stats(&stats, &arrow_schema)
2437        );
2438    }
2439
2440    #[tokio::test]
2441    async fn test_file_level_pruning_stats_ceil_max_unit_conversion() {
2442        let metadata = metadata_with_time_index_unit(TimeUnit::Millisecond);
2443        let input = new_scan_input(metadata, vec![]).await;
2444        let file = file_handle_with_time_range(
2445            Timestamp::new(1_000_001, TimeUnit::Nanosecond),
2446            Timestamp::new(1_000_001, TimeUnit::Nanosecond),
2447        );
2448
2449        let stats = input.try_file_level_pruning_stats(&file).unwrap();
2450        assert_eq!(
2451            ScalarValue::TimestampMillisecond(Some(1), None),
2452            stats.min_scalar
2453        );
2454        assert_eq!(
2455            ScalarValue::TimestampMillisecond(Some(2), None),
2456            stats.max_scalar
2457        );
2458
2459        // The actual max timestamp is slightly greater than 1ms. It must be kept for `ts > 1ms`.
2460        let predicate = Predicate::new(vec![col("ts").gt(ts_lit(1))]);
2461        assert_eq!(
2462            vec![true],
2463            predicate.prune_with_stats(&stats, input.mapper.metadata().schema.arrow_schema())
2464        );
2465    }
2466
2467    #[tokio::test]
2468    async fn test_file_level_pruning_stats_overflow_keeps_file() {
2469        let metadata = metadata_with_time_index_unit(TimeUnit::Nanosecond);
2470        let input = new_scan_input(metadata, vec![]).await;
2471        let file = file_handle_with_time_range(
2472            Timestamp::new(0, TimeUnit::Second),
2473            Timestamp::new(i64::MAX, TimeUnit::Second),
2474        );
2475
2476        assert!(input.try_file_level_pruning_stats(&file).is_none());
2477    }
2478
2479    #[test]
2480    fn test_file_level_pruning_stats_keeps_inclusive_boundary() {
2481        let ts_col_name = "ts";
2482        let predicate = Predicate::new(vec![col(ts_col_name).gt_eq(ts_lit(1000))]);
2483        let arrow_schema = Arc::new(ArrowSchema::new(vec![Field::new(
2484            ts_col_name,
2485            ArrowDataType::Timestamp(ArrowTimeUnit::Millisecond, None),
2486            false,
2487        )]));
2488        let stats = FileLevelPruningStats {
2489            min_scalar: ScalarValue::TimestampMillisecond(Some(0), None),
2490            max_scalar: ScalarValue::TimestampMillisecond(Some(1000), None),
2491            time_index_col_name: ts_col_name.to_string(),
2492        };
2493
2494        assert_eq!(
2495            vec![true],
2496            predicate.prune_with_stats(&stats, &arrow_schema)
2497        );
2498    }
2499
2500    #[tokio::test]
2501    async fn test_file_level_pruning_with_dyn_filter_only_predicate() {
2502        let metadata = Arc::new(metadata_with_primary_key(vec![0, 1], false));
2503        let mapper = FlatProjectionMapper::new(&metadata, [0, 2, 3]).unwrap();
2504        let predicate_group = PredicateGroup::new(metadata.as_ref(), &[]).unwrap();
2505        predicate_group.add_dyn_filters(vec![Arc::new(DynamicFilterPhysicalExpr::new(
2506            vec![],
2507            physical_lit(false),
2508        ))]);
2509        let input = ScanInput::new(SchedulerEnv::new().await.access_layer.clone(), mapper)
2510            .with_predicate(predicate_group);
2511        let file = file_handle_with_time_range(
2512            Timestamp::new_millisecond(0),
2513            Timestamp::new_millisecond(1000),
2514        );
2515        let mut reader_metrics = ReaderMetrics::default();
2516
2517        let builder = input
2518            .prune_file(&file, PreFilterMode::SkipFields, &mut reader_metrics)
2519            .await
2520            .unwrap();
2521
2522        assert_eq!(1, reader_metrics.filter_metrics.files_time_range_pruned);
2523        let mut ranges = SmallVec::new();
2524        builder.build_ranges(-1, &mut ranges);
2525        assert!(ranges.is_empty());
2526    }
2527
2528    #[tokio::test]
2529    async fn test_manifest_pruning_observes_dynamic_filter_update() {
2530        let metadata = Arc::new(metadata_with_primary_key(vec![0, 1], false));
2531        let mapper = FlatProjectionMapper::new(&metadata, [0, 2, 3]).unwrap();
2532        let predicate_group = PredicateGroup::new(metadata.as_ref(), &[]).unwrap();
2533        let arrow_schema = metadata.schema.arrow_schema();
2534        let ts_expr = physical_col("ts", arrow_schema.as_ref()).unwrap();
2535        let dyn_filter = Arc::new(DynamicFilterPhysicalExpr::new(
2536            vec![ts_expr.clone()],
2537            physical_lit(true),
2538        ));
2539        predicate_group.add_dyn_filters(vec![dyn_filter.clone()]);
2540        let input = ScanInput::new(SchedulerEnv::new().await.access_layer.clone(), mapper)
2541            .with_predicate(predicate_group);
2542        let file = file_handle_with_time_range(
2543            Timestamp::new_millisecond(0),
2544            Timestamp::new_millisecond(1000),
2545        );
2546
2547        assert!(!input.can_manifest_prune_file(&file));
2548
2549        let updated = physical_binary(
2550            ts_expr,
2551            Operator::Gt,
2552            physical_lit(ScalarValue::TimestampMillisecond(Some(1000), None)),
2553            arrow_schema.as_ref(),
2554        )
2555        .unwrap();
2556        dyn_filter.update(updated).unwrap();
2557
2558        assert!(input.can_manifest_prune_file(&file));
2559    }
2560
2561    #[tokio::test]
2562    async fn test_range_pre_filter_mode() {
2563        let metadata = Arc::new(metadata_with_primary_key(vec![0, 1], false));
2564        let cases = [
2565            (true, MergeMode::LastRow, 1, PreFilterMode::All),
2566            (false, MergeMode::LastNonNull, 1, PreFilterMode::All),
2567            (false, MergeMode::LastRow, 2, PreFilterMode::SkipFields),
2568            (true, MergeMode::LastRow, 2, PreFilterMode::All),
2569        ];
2570
2571        for (append_mode, merge_mode, source_count, expected_mode) in cases {
2572            let input = new_scan_input(metadata.clone(), vec![])
2573                .await
2574                .with_append_mode(append_mode)
2575                .with_merge_mode(merge_mode);
2576
2577            assert_eq!(expected_mode, input.range_pre_filter_mode(source_count));
2578        }
2579    }
2580}