Skip to main content

table/
predicate.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
15use std::fmt;
16use std::hash::{Hash, Hasher};
17use std::sync::Arc;
18
19use arc_swap::ArcSwap;
20use common_recordbatch::DfRecordBatch;
21use common_recordbatch::filter::SimpleFilterEvaluator;
22use common_telemetry::{debug, warn};
23use common_time::Timestamp;
24use common_time::range::TimestampRange;
25use common_time::timestamp::TimeUnit;
26use datafusion::common::ScalarValue;
27use datafusion::error::Result as DfResult;
28use datafusion::physical_optimizer::pruning::PruningPredicateBuilder;
29use datafusion_common::pruning::PruningStatistics;
30use datafusion_common::tree_node::TreeNode;
31use datafusion_common::{DFSchema, DataFusionError, ToDFSchema};
32use datafusion_expr::ColumnarValue;
33use datafusion_expr::expr::{Expr, InList, ScalarFunction};
34use datafusion_expr::physical_planning_context::PhysicalPlanningContext;
35use datafusion_expr::{Between, BinaryExpr, Operator};
36use datafusion_physical_expr::execution_props::ExecutionProps;
37use datafusion_physical_expr::expressions::{
38    BinaryExpr as PhysicalBinaryExpr, DynamicFilterPhysicalExpr,
39};
40use datafusion_physical_expr::{PhysicalExpr, create_physical_expr};
41use datatypes::arrow;
42use datatypes::arrow::array::{Array, BooleanArray};
43use datatypes::arrow::datatypes::{DataType as ArrowDataType, Schema as ArrowSchema};
44use datatypes::value::scalar_value_to_timestamp;
45use snafu::ResultExt;
46
47use crate::error;
48
49#[cfg(test)]
50mod stats;
51
52/// Assert the scalar value is not utf8. Returns `None` if it's utf8.
53/// In theory, it should be converted to a timestamp scalar value by `TypeConversionRule`.
54macro_rules! return_none_if_utf8 {
55    ($lit: ident) => {
56        if is_string_timestamp_literal($lit) {
57            warn!(
58                "Unexpected ScalarValue::Utf8 in time range predicate: {:?}. Maybe it's an implicit bug, please report it to https://github.com/GreptimeTeam/greptimedb/issues",
59                $lit
60            );
61
62            // Make the predicate ineffective.
63            return None;
64        }
65    };
66}
67
68pub fn is_string_timestamp_literal(scalar: &ScalarValue) -> bool {
69    matches!(
70        scalar,
71        ScalarValue::Utf8(_) | ScalarValue::LargeUtf8(_) | ScalarValue::Utf8View(_)
72    )
73}
74
75/// Reference-counted pointer to a list of logical exprs and a list of dynamic filter physical exprs.
76#[derive(Debug, Clone, Default)]
77pub struct Predicate {
78    /// logical exprs
79    exprs: Arc<Vec<Expr>>,
80    /// dynamic filter physical exprs, only useful if dynamic filtering is enabled
81    ///
82    /// They are usually from `TopK` or `Join` operators, and can dynamically filter data during query execution by using current runtime information to further reduce data scanning
83    dyn_filters: Arc<ArcSwap<Vec<Arc<DynamicFilterPhysicalExpr>>>>,
84}
85
86impl Predicate {
87    /// Creates a new `Predicate` by converting logical exprs to physical exprs that can be
88    /// evaluated against record batches.
89    /// Returns error when failed to convert exprs.
90    pub fn new(exprs: Vec<Expr>) -> Self {
91        Self {
92            exprs: Arc::new(exprs),
93            dyn_filters: Arc::new(ArcSwap::new(Arc::new(vec![]))),
94        }
95    }
96
97    pub fn with_dyn_filters(
98        exprs: Vec<Expr>,
99        dyn_filters: Vec<Arc<DynamicFilterPhysicalExpr>>,
100    ) -> Self {
101        Self {
102            exprs: Arc::new(exprs),
103            dyn_filters: Arc::new(ArcSwap::new(Arc::new(dyn_filters))),
104        }
105    }
106
107    pub fn is_empty(&self) -> bool {
108        self.exprs.is_empty() && self.dyn_filters.load().is_empty()
109    }
110
111    /// Adds dynamic filter physical exprs to the existing list.
112    pub fn add_dyn_filters(&self, dyn_filters: Vec<Arc<DynamicFilterPhysicalExpr>>) {
113        self.dyn_filters.rcu(|existing| {
114            let mut new_filters = existing.as_ref().clone();
115            new_filters.extend(dyn_filters.clone());
116            Arc::new(new_filters)
117        });
118    }
119
120    /// Removes dynamic filters while preserving the static logical expressions.
121    pub fn clear_dyn_filters(&self) {
122        self.dyn_filters.store(Arc::new(vec![]));
123    }
124
125    /// Returns the logical exprs.
126    pub fn exprs(&self) -> &[Expr] {
127        &self.exprs
128    }
129
130    /// Returns the dynamic filter physical exprs. Notice this return a live dynamic filters which
131    /// can change during query execution.
132    ///
133    /// # Precondition: pruning only, never row filtering
134    ///
135    /// A consumer may only use these expressions to *prune*: to skip a region, a file or a
136    /// row group whose statistics prove that no row can match, as
137    /// [`Self::prune_with_stats`] does. A remote dynamic filter is a bounded pruning hint,
138    /// not a copy of the producer's predicate — the coordinator ships the join's build-key
139    /// list as `IN`/`NOT IN` and drops the top-level conjuncts it cannot ship, so the
140    /// predicate can be *wider* than the one the producer evaluates (see
141    /// `DynFilterPayload::decode_datafusion_expr` in `common-query`). Over-approximating is
142    /// free for pruning but loses rows for filtering, so row filtering must not consume
143    /// these expressions unconditionally.
144    pub fn dyn_filters(&self) -> Arc<Vec<Arc<DynamicFilterPhysicalExpr>>> {
145        self.dyn_filters.load_full()
146    }
147
148    /// Returns snapshots of the dynamic filters as physical expressions.
149    ///
150    /// Pruning only: see [`Self::dyn_filters`] for why these expressions must not filter
151    /// rows. Producers must conservatively encode which NULL inputs can contribute.
152    pub fn dyn_filter_phy_exprs(&self) -> error::Result<Vec<Arc<dyn PhysicalExpr>>> {
153        self.dyn_filters
154            .load()
155            .iter()
156            .map(|e| e.current())
157            .collect::<Result<Vec<_>, _>>()
158            .context(error::DatafusionSnafu)
159    }
160
161    /// Builds a single physical expr for a caller that *evaluates* it against record batches.
162    ///
163    /// Regex comparisons are rewritten into [`PrecompiledRegexExpr`] because
164    /// `create_physical_expr` builds a comparison that recompiles its pattern on every evaluation,
165    /// while a scan evaluates one physical expr per batch.
166    ///
167    /// Pruning must not use this: it never evaluates the expression, only folds it into column
168    /// statistics, so [`Self::to_pruning_physical_exprs`] keeps the plain comparison.
169    pub fn to_physical_expr(
170        expr: &Expr,
171        schema: &arrow::datatypes::SchemaRef,
172    ) -> error::Result<Arc<dyn PhysicalExpr>> {
173        let df_schema = schema
174            .clone()
175            .to_dfschema_ref()
176            .context(error::DatafusionSnafu)?;
177
178        // TODO(hl): `execution_props` provides variables required by evaluation.
179        // we may reuse the `execution_props` from `SessionState` once we support
180        // registering variables.
181        let execution_props = &ExecutionProps::new();
182        let planning_context = &PhysicalPlanningContext::default();
183
184        if let Some(physical) = Self::to_regex_physical_expr(
185            expr,
186            schema,
187            df_schema.as_ref(),
188            execution_props,
189            planning_context,
190        ) {
191            return Ok(physical);
192        }
193
194        Self::to_plain_physical_expr(expr, df_schema.as_ref())
195    }
196
197    /// Builds the physical expr `create_physical_expr` produces, without the regex rewrite.
198    ///
199    /// This is what pruning consumes: it is a shape the pruning predicate builder recognizes.
200    fn to_plain_physical_expr(
201        expr: &Expr,
202        df_schema: &DFSchema,
203    ) -> error::Result<Arc<dyn PhysicalExpr>> {
204        let execution_props = &ExecutionProps::new();
205        let planning_context = &PhysicalPlanningContext::default();
206        create_physical_expr(expr, df_schema, execution_props, planning_context)
207            .context(error::DatafusionSnafu)
208    }
209
210    /// Rewrites the regex comparisons in `expr` into [`PrecompiledRegexExpr`], so each pattern is
211    /// compiled once per scan instead of once per batch.
212    ///
213    /// Returns `None` when nothing in `expr` can be precompiled, which leaves the caller with the
214    /// unmodified `create_physical_expr` path. `AND`/`OR` are rebuilt with only the rewritable
215    /// branch replaced because a label matcher accepting the empty string is planned as
216    /// `is_null(col) OR col =~ 'pattern'`: the rewrite has to reach the regex below the `OR` or a
217    /// nullable label column never benefits. Every other node — `NOT`, `CASE`, a cast around the
218    /// whole comparison — is left to the planner.
219    fn to_regex_physical_expr(
220        expr: &Expr,
221        schema: &arrow::datatypes::SchemaRef,
222        df_schema: &DFSchema,
223        execution_props: &ExecutionProps,
224        planning_context: &PhysicalPlanningContext,
225    ) -> Option<Arc<dyn PhysicalExpr>> {
226        let Expr::BinaryExpr(binary) = expr else {
227            return None;
228        };
229        let compile = |expr: &Expr| {
230            create_physical_expr(expr, df_schema, execution_props, planning_context).ok()
231        };
232        let rewrite = |expr: &Expr| {
233            Self::to_regex_physical_expr(expr, schema, df_schema, execution_props, planning_context)
234        };
235
236        if matches!(binary.op, Operator::And | Operator::Or) {
237            let left = rewrite(&binary.left);
238            let right = rewrite(&binary.right);
239            if left.is_none() && right.is_none() {
240                return None;
241            }
242            let left = left.or_else(|| compile(&binary.left))?;
243            let right = right.or_else(|| compile(&binary.right))?;
244            return Some(Arc::new(PhysicalBinaryExpr::new(left, binary.op, right)));
245        }
246
247        if !matches!(binary.op, Operator::RegexMatch | Operator::RegexNotMatch) {
248            return None;
249        }
250        // Precompile only what the precompiled kernel can evaluate exactly; other string layouts
251        // keep the arrow comparison instead of failing at scan time.
252        let column_type = regex_column_type(&binary.left, schema)?;
253        if !is_precompilable_regex_type(&column_type) {
254            return None;
255        }
256        let filter = SimpleFilterEvaluator::try_new_with_column_type(expr, &|name| {
257            schema
258                .field_with_name(name)
259                .ok()
260                .map(|field| field.data_type().clone())
261        })?;
262        let Expr::Literal(literal, _) = binary.right.as_ref() else {
263            return None;
264        };
265        let pattern = literal.try_as_str()?.map(str::to_string)?;
266        let column = compile(&binary.left)?;
267
268        Some(Arc::new(PrecompiledRegexExpr {
269            column,
270            filter,
271            pattern,
272            op: binary.op,
273        }))
274    }
275
276    /// Builds the physical exprs [`Self::prune_with_stats`] folds into column statistics.
277    ///
278    /// Pruning never evaluates a predicate, and the regex rewrite exists only to make evaluation
279    /// cheap, so this deliberately builds what `create_physical_expr` builds. Besides saving the
280    /// conversion on a per-file (manifest pruning) and per-batch (bulk memtable pruning) path,
281    /// [`PrecompiledRegexExpr`] is a node the pruning predicate builder does not know: it replaces
282    /// unknown nodes with `true`, while the plain comparison below is handled (or rejected) the
283    /// same way it was before the rewrite existed.
284    pub fn to_pruning_physical_exprs(
285        &self,
286        schema: &arrow::datatypes::SchemaRef,
287    ) -> error::Result<Vec<Arc<dyn PhysicalExpr>>> {
288        let df_schema = schema
289            .clone()
290            .to_dfschema_ref()
291            .context(error::DatafusionSnafu)?;
292        let dyn_filters = self.dyn_filter_phy_exprs()?;
293
294        Ok(self
295            .exprs
296            .iter()
297            .filter_map(|expr| Self::to_plain_physical_expr(expr, df_schema.as_ref()).ok())
298            .chain(dyn_filters)
299            .collect::<Vec<_>>())
300    }
301
302    /// Evaluates the predicate against the `stats`.
303    /// Returns a vector of boolean values, among which `false` means the row group can be skipped.
304    pub fn prune_with_stats<S: PruningStatistics>(
305        &self,
306        stats: &S,
307        schema: &arrow::datatypes::SchemaRef,
308    ) -> Vec<bool> {
309        let mut res = vec![true; stats.num_containers()];
310        let physical_exprs = match self.to_pruning_physical_exprs(schema) {
311            Ok(expr) => expr,
312            Err(e) => {
313                warn!(e; "Failed to build physical expr from predicates: {:?}", &self.exprs);
314                return res;
315            }
316        };
317
318        for expr in &physical_exprs {
319            match PruningPredicateBuilder::new()
320                .with_file_schema(schema.clone())
321                .try_build(expr.clone())
322            {
323                Ok(p) => match p.prune(stats) {
324                    Ok(r) => {
325                        for (curr_val, res) in r.into_iter().zip(res.iter_mut()) {
326                            *res &= curr_val
327                        }
328                    }
329                    Err(e) => {
330                        warn!(e; "Failed to prune row groups");
331                    }
332                },
333                Err(e) => {
334                    // since dynamic filter exprs could be complex, it's possible that the pruning predicate builder fails to prove anything from it. In that case, we just log it and skip pruning with this expr.
335                    debug!("Failed to create pruning predicate for expr: {e:?}");
336                }
337            }
338        }
339        res
340    }
341}
342
343/// Returns whether `data_type` is a string layout [`SimpleFilterEvaluator`] can evaluate.
344///
345/// Its regex kernels accept `Utf8` and `Dictionary(UInt32, Utf8)` only; `LargeUtf8`, `Utf8View`
346/// and other dictionary layouts keep the arrow comparison.
347fn is_precompilable_regex_type(data_type: &ArrowDataType) -> bool {
348    match data_type {
349        ArrowDataType::Utf8 => true,
350        ArrowDataType::Dictionary(key, value) => {
351            **key == ArrowDataType::UInt32 && **value == ArrowDataType::Utf8
352        }
353        _ => false,
354    }
355}
356
357/// Returns the arrow type the regex comparison in `expr` evaluates, `None` if `expr` is not a
358/// column (or a cast of one) this rewrite can reason about.
359fn regex_column_type(expr: &Expr, schema: &arrow::datatypes::SchemaRef) -> Option<ArrowDataType> {
360    match expr {
361        Expr::Column(column) => schema
362            .field_with_name(&column.name)
363            .ok()
364            .map(|field| field.data_type().clone()),
365        // A cast decides the compared type, whatever the column holds underneath.
366        Expr::Cast(cast) => match cast.expr.as_ref() {
367            Expr::Column(_) => Some(cast.field.data_type().clone()),
368            _ => None,
369        },
370        _ => None,
371    }
372}
373
374/// A regex comparison (`col =~ 'pattern'` / `col !~ 'pattern'`) compiled on first evaluation.
375///
376/// `create_physical_expr` turns the comparison into a binary expression that recompiles the pattern
377/// on every evaluation, because arrow's `regexp_is_match_scalar` compiles the pattern it is given.
378/// A scan evaluates its physical expr once per batch, so that costs one `Regex::new` per batch, and
379/// a series scan evaluates one batch per series. [`SimpleFilterEvaluator`] lazily compiles its
380/// pattern once on first evaluation, then borrows one cache per batch rather than one per row.
381///
382/// The result is bit-identical to the arrow expression it replaces: `evaluate_array` folds SQL
383/// `NULL` into `false`, so the column's logical nulls are restored afterwards — exactly the validity
384/// arrow's kernel produces for a regex, which never fails on `NULL`.
385///
386/// Only [`Predicate::to_physical_expr`] builds this node, for callers that evaluate the predicate.
387/// Pruning uses [`Predicate::to_pruning_physical_exprs`] and keeps the arrow comparison.
388#[derive(Debug)]
389struct PrecompiledRegexExpr {
390    /// The column the pattern is matched against.
391    column: Arc<dyn PhysicalExpr>,
392    /// The pattern, compiled on first evaluation and reused thereafter.
393    filter: SimpleFilterEvaluator,
394    /// The pattern text, kept for display and equality.
395    pattern: String,
396    /// `RegexMatch` or `RegexNotMatch`, kept for display and equality.
397    op: Operator,
398}
399
400impl fmt::Display for PrecompiledRegexExpr {
401    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
402        let op = if matches!(self.op, Operator::RegexMatch) {
403            "=~"
404        } else {
405            "!~"
406        };
407        write!(f, "{} {op} '{}'", self.column, self.pattern)
408    }
409}
410
411impl PartialEq for PrecompiledRegexExpr {
412    fn eq(&self, other: &Self) -> bool {
413        self.op == other.op && self.pattern == other.pattern && self.column.eq(&other.column)
414    }
415}
416
417impl Eq for PrecompiledRegexExpr {}
418
419impl Hash for PrecompiledRegexExpr {
420    fn hash<H: Hasher>(&self, state: &mut H) {
421        self.op.hash(state);
422        self.pattern.hash(state);
423        self.column.hash(state);
424    }
425}
426
427impl PhysicalExpr for PrecompiledRegexExpr {
428    fn data_type(&self, _input_schema: &ArrowSchema) -> DfResult<ArrowDataType> {
429        Ok(ArrowDataType::Boolean)
430    }
431
432    fn nullable(&self, input_schema: &ArrowSchema) -> DfResult<bool> {
433        self.column.nullable(input_schema)
434    }
435
436    fn evaluate(&self, batch: &DfRecordBatch) -> DfResult<ColumnarValue> {
437        let column = self.column.evaluate(batch)?.into_array(batch.num_rows())?;
438        let matched = self
439            .filter
440            .evaluate_array(&column)
441            .map_err(|e| DataFusionError::External(Box::new(e)))?;
442        Ok(ColumnarValue::Array(Arc::new(BooleanArray::new(
443            matched,
444            column.logical_nulls(),
445        ))))
446    }
447
448    fn children(&self) -> Vec<&Arc<dyn PhysicalExpr>> {
449        vec![&self.column]
450    }
451
452    fn with_new_children(
453        self: Arc<Self>,
454        children: Vec<Arc<dyn PhysicalExpr>>,
455    ) -> DfResult<Arc<dyn PhysicalExpr>> {
456        Ok(Arc::new(Self {
457            column: children[0].clone(),
458            filter: self.filter.clone(),
459            pattern: self.pattern.clone(),
460            op: self.op,
461        }))
462    }
463
464    fn fmt_sql(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
465        write!(f, "{self}")
466    }
467}
468
469// tests for `build_time_range_predicate` locates in src/query/tests/time_range_filter_test.rs
470// since it requires query engine to convert sql to filters.
471/// `build_time_range_predicate` extracts time range from logical exprs to facilitate fast
472/// time range pruning.
473pub fn build_time_range_predicate(
474    ts_col_name: &str,
475    ts_col_unit: TimeUnit,
476    filters: &[Expr],
477) -> TimestampRange {
478    let mut res = TimestampRange::min_to_max();
479    for expr in filters {
480        if let Some(range) = extract_time_range_from_expr(ts_col_name, ts_col_unit, expr) {
481            res = res.and(&range);
482        }
483    }
484    res
485}
486
487/// The outcome of strictly extracting the time range of `ts_col_name` from a
488/// scan's filters. Unlike [`build_time_range_predicate`], which quietly widens
489/// to `min_to_max` on anything it cannot parse (fine for pruning), this
490/// distinguishes "the column is not filtered at all" from "it is filtered in a
491/// way that cannot be safely turned into a range" — for callers whose contract
492/// forbids silently falling back to a default window.
493#[derive(Debug, Clone, PartialEq, Eq)]
494pub enum TimeRangeExtraction {
495    /// No filter references the column.
496    Absent,
497    /// Every filter referencing the column was folded into this range, which
498    /// over-approximates the filters' satisfying set.
499    Extracted(TimestampRange),
500    /// At least one filter references the column in a shape that cannot be
501    /// safely extracted (e.g. under `OR`/`NOT`, or compared to a non-literal).
502    Unsupported,
503}
504
505/// Strictly extracts the time range of `ts_col_name` from the (implicitly
506/// AND-ed) scan filters. See [`TimeRangeExtraction`].
507pub fn extract_time_range_strict(
508    ts_col_name: &str,
509    ts_col_unit: TimeUnit,
510    filters: &[Expr],
511) -> TimeRangeExtraction {
512    let mut range: Option<TimestampRange> = None;
513    for expr in filters {
514        if !expr
515            .column_refs()
516            .iter()
517            .any(|column| column.name == ts_col_name)
518        {
519            continue;
520        }
521        // Disjunctive shapes (`OR`, `IN`) collapse disjoint ranges into their
522        // convex hull, which is not exactly representable as one contiguous
523        // range; callers deriving synthetic timestamps from the bounds would
524        // emit points inside the gaps.
525        if contains_disjunction_over_column(expr, ts_col_name) {
526            return TimeRangeExtraction::Unsupported;
527        }
528        // `Some` from the lenient extractor over-approximates the expression's
529        // satisfying set (an `AND` side it cannot parse is dropped, which only
530        // widens), so intersecting extracted conjuncts stays an
531        // over-approximation.
532        // Ranges derived from `date_bin` are skipped: they can be a bucket wider than
533        // the filter, so a timestamp synthesized at their bounds may not satisfy it.
534        match extract_time_range(ts_col_name, ts_col_unit, expr, DateBinFilters::Skip) {
535            Some(extracted) => {
536                range = Some(match range {
537                    Some(acc) => acc.and(&extracted),
538                    None => extracted,
539                });
540            }
541            None => return TimeRangeExtraction::Unsupported,
542        }
543    }
544    match range {
545        Some(range) => TimeRangeExtraction::Extracted(range),
546        None => TimeRangeExtraction::Absent,
547    }
548}
549
550fn contains_disjunction_over_column(expr: &Expr, ts_col_name: &str) -> bool {
551    let is_disjunction = |expr: &Expr| {
552        matches!(
553            expr,
554            Expr::BinaryExpr(BinaryExpr {
555                op: Operator::Or,
556                ..
557            }) | Expr::InList(_)
558        ) && expr
559            .column_refs()
560            .iter()
561            .any(|column| column.name == ts_col_name)
562    };
563    expr.exists(|expr| Ok(is_disjunction(expr))).unwrap_or(true)
564}
565
566/// Extract time range filter from `WHERE`/`IN (...)`/`BETWEEN` clauses.
567/// Return None if no time range can be found in expr.
568pub fn extract_time_range_from_expr(
569    ts_col_name: &str,
570    ts_col_unit: TimeUnit,
571    expr: &Expr,
572) -> Option<TimestampRange> {
573    extract_time_range(ts_col_name, ts_col_unit, expr, DateBinFilters::Derive)
574}
575
576/// Whether a filter on `date_bin(stride, ts)` yields a range on `ts`.
577#[derive(Debug, Clone, Copy, PartialEq, Eq)]
578enum DateBinFilters {
579    /// Derive a range that covers every satisfying row (see [`date_bin_stride`]).
580    Derive,
581    /// Treat the filter as unparsable.
582    Skip,
583}
584
585fn extract_time_range(
586    ts_col_name: &str,
587    ts_col_unit: TimeUnit,
588    expr: &Expr,
589    date_bin: DateBinFilters,
590) -> Option<TimestampRange> {
591    match expr {
592        Expr::BinaryExpr(BinaryExpr { left, op, right }) => {
593            extract_from_binary_expr(ts_col_name, ts_col_unit, left, op, right, date_bin)
594        }
595        Expr::Between(Between {
596            expr,
597            negated,
598            low,
599            high,
600        }) => {
601            extract_from_between_expr(ts_col_name, ts_col_unit, expr, negated, low, high, date_bin)
602        }
603        Expr::InList(InList {
604            expr,
605            list,
606            negated,
607        }) => extract_from_in_list_expr(ts_col_name, expr, *negated, list),
608        _ => None,
609    }
610}
611
612fn extract_from_binary_expr(
613    ts_col_name: &str,
614    ts_col_unit: TimeUnit,
615    left: &Expr,
616    op: &Operator,
617    right: &Expr,
618    date_bin: DateBinFilters,
619) -> Option<TimestampRange> {
620    if date_bin == DateBinFilters::Derive
621        && let Some(range) =
622            extract_from_date_bin_comparison(ts_col_name, ts_col_unit, left, op, right)
623    {
624        return Some(range);
625    }
626    match op {
627        Operator::Eq => get_timestamp_filter(ts_col_name, left, right)
628            .and_then(|(ts, _)| ts.convert_to(ts_col_unit))
629            .map(TimestampRange::single),
630        Operator::Lt => {
631            let (ts, reverse) = get_timestamp_filter(ts_col_name, left, right)?;
632            if reverse {
633                // [lit] < ts_col
634                let ts_val = ts.convert_to(ts_col_unit)?.value();
635                Some(TimestampRange::from_start(Timestamp::new(
636                    ts_val + 1,
637                    ts_col_unit,
638                )))
639            } else {
640                // ts_col < [lit]
641                ts.convert_to_ceil(ts_col_unit)
642                    .map(|ts| TimestampRange::until_end(ts, false))
643            }
644        }
645        Operator::LtEq => {
646            let (ts, reverse) = get_timestamp_filter(ts_col_name, left, right)?;
647            if reverse {
648                // [lit] <= ts_col
649                ts.convert_to_ceil(ts_col_unit)
650                    .map(TimestampRange::from_start)
651            } else {
652                // ts_col <= [lit]
653                ts.convert_to(ts_col_unit)
654                    .map(|ts| TimestampRange::until_end(ts, true))
655            }
656        }
657        Operator::Gt => {
658            let (ts, reverse) = get_timestamp_filter(ts_col_name, left, right)?;
659            if reverse {
660                // [lit] > ts_col
661                ts.convert_to_ceil(ts_col_unit)
662                    .map(|t| TimestampRange::until_end(t, false))
663            } else {
664                // ts_col > [lit]
665                let ts_val = ts.convert_to(ts_col_unit)?.value();
666                Some(TimestampRange::from_start(Timestamp::new(
667                    ts_val + 1,
668                    ts_col_unit,
669                )))
670            }
671        }
672        Operator::GtEq => {
673            let (ts, reverse) = get_timestamp_filter(ts_col_name, left, right)?;
674            if reverse {
675                // [lit] >= ts_col
676                ts.convert_to(ts_col_unit)
677                    .map(|t| TimestampRange::until_end(t, true))
678            } else {
679                // ts_col >= [lit]
680                ts.convert_to_ceil(ts_col_unit)
681                    .map(TimestampRange::from_start)
682            }
683        }
684        Operator::And => {
685            // instead of return none when failed to extract time range from left/right, we unwrap the none into
686            // `TimestampRange::min_to_max`.
687            let left = extract_time_range(ts_col_name, ts_col_unit, left, date_bin)
688                .unwrap_or_else(TimestampRange::min_to_max);
689            let right = extract_time_range(ts_col_name, ts_col_unit, right, date_bin)
690                .unwrap_or_else(TimestampRange::min_to_max);
691            Some(left.and(&right))
692        }
693        Operator::Or => {
694            let left = extract_time_range(ts_col_name, ts_col_unit, left, date_bin)?;
695            let right = extract_time_range(ts_col_name, ts_col_unit, right, date_bin)?;
696            Some(left.or(&right))
697        }
698        _ => None,
699    }
700}
701
702/// Returns the stride of `date_bin(stride, ts_col[, origin])`, converted to `unit`
703/// and rounded up, if `expr` is that call with a literal, fixed-width stride.
704///
705/// `date_bin` floors a timestamp to the start of its bucket, so for every row
706/// `bucket_start <= ts < bucket_start + stride`, whatever the origin. That lets a
707/// filter on the bucket start bound the time index itself, which is what a
708/// filter on a view's `date_bin(...) AS time` column becomes once it is pushed
709/// below the view's aggregate.
710///
711/// This holds in nanoseconds. DataFusion computes the bucket start in
712/// nanoseconds and truncates it to the column unit, so on a coarser column the
713/// returned value can be up to one unit below the true start; see
714/// [`date_bin_range`].
715fn date_bin_stride(ts_col_name: &str, unit: TimeUnit, expr: &Expr) -> Option<i64> {
716    let Expr::ScalarFunction(ScalarFunction { func, args }) = expr else {
717        return None;
718    };
719    if func.name() != "date_bin" || !(2..=3).contains(&args.len()) {
720        return None;
721    }
722    let Expr::Column(col) = &args[1] else {
723        return None;
724    };
725    if col.name != ts_col_name {
726        return None;
727    }
728    let stride_ns: i128 = match &args[0] {
729        // Months have no fixed width.
730        Expr::Literal(ScalarValue::IntervalMonthDayNano(Some(v)), _) if v.months == 0 => {
731            v.days as i128 * 86_400_000_000_000 + v.nanoseconds as i128
732        }
733        Expr::Literal(ScalarValue::IntervalDayTime(Some(v)), _) => {
734            v.days as i128 * 86_400_000_000_000 + v.milliseconds as i128 * 1_000_000
735        }
736        _ => return None,
737    };
738    if stride_ns <= 0 {
739        return None;
740    }
741    let ns_per_unit = match unit {
742        TimeUnit::Second => 1_000_000_000,
743        TimeUnit::Millisecond => 1_000_000,
744        TimeUnit::Microsecond => 1_000,
745        TimeUnit::Nanosecond => 1,
746    };
747    i64::try_from((stride_ns + ns_per_unit - 1) / ns_per_unit).ok()
748}
749
750/// Extracts a time range from `date_bin(stride, ts_col) <op> literal`. The range
751/// over-approximates the rows that satisfy the comparison (see [`date_bin_stride`]).
752fn extract_from_date_bin_comparison(
753    ts_col_name: &str,
754    ts_col_unit: TimeUnit,
755    left: &Expr,
756    op: &Operator,
757    right: &Expr,
758) -> Option<TimestampRange> {
759    // Normalize to `date_bin(...) <op> literal`.
760    let (bin, op, lit) = match (left, right) {
761        (bin, Expr::Literal(lit, _)) => (bin, *op, lit),
762        (Expr::Literal(lit, _), bin) => (bin, op.swap()?, lit),
763        _ => return None,
764    };
765    let stride = date_bin_stride(ts_col_name, ts_col_unit, bin)?;
766    return_none_if_utf8!(lit);
767    let bound = scalar_value_to_timestamp(lit, None)?;
768    date_bin_range(op, &bound, stride, ts_col_unit)
769}
770
771/// The range of `ts` for which `date_bin(stride, ts) <op> bound` can hold.
772fn date_bin_range(
773    op: Operator,
774    bound: &Timestamp,
775    stride: i64,
776    unit: TimeUnit,
777) -> Option<TimestampRange> {
778    // `bin >= bound` and `bin > bound` imply `ts >= bound`, because `ts >= bin`.
779    let lower = || bound.convert_to_ceil(unit).map(TimestampRange::from_start);
780    // `bin <= bound` and `bin < bound` imply `ts < bound + stride`, because `ts < bin + stride`.
781    // On a column coarser than nanoseconds, the returned `bin` is truncated from the true
782    // bucket start and can be up to one unit below it, so widen the end by one unit.
783    let slack = if unit == TimeUnit::Nanosecond { 0 } else { 1 };
784    let upper = || {
785        let end = bound
786            .convert_to_ceil(unit)?
787            .value()
788            .checked_add(stride)?
789            .checked_add(slack)?;
790        Some(TimestampRange::until_end(Timestamp::new(end, unit), false))
791    };
792    match op {
793        Operator::Gt | Operator::GtEq => lower(),
794        Operator::Lt | Operator::LtEq => upper(),
795        Operator::Eq => Some(lower()?.and(&upper()?)),
796        _ => None,
797    }
798}
799
800fn get_timestamp_filter(ts_col_name: &str, left: &Expr, right: &Expr) -> Option<(Timestamp, bool)> {
801    let (col, lit, reverse) = match (left, right) {
802        (Expr::Column(column), Expr::Literal(scalar, _)) => (column, scalar, false),
803        (Expr::Literal(scalar, _), Expr::Column(column)) => (column, scalar, true),
804        _ => {
805            return None;
806        }
807    };
808    if col.name != ts_col_name {
809        return None;
810    }
811
812    return_none_if_utf8!(lit);
813    scalar_value_to_timestamp(lit, None).map(|t| (t, reverse))
814}
815
816fn extract_from_between_expr(
817    ts_col_name: &str,
818    ts_col_unit: TimeUnit,
819    expr: &Expr,
820    negated: &bool,
821    low: &Expr,
822    high: &Expr,
823    date_bin: DateBinFilters,
824) -> Option<TimestampRange> {
825    if *negated {
826        return None;
827    }
828
829    if date_bin == DateBinFilters::Derive
830        && let Some(stride) = date_bin_stride(ts_col_name, ts_col_unit, expr)
831    {
832        // `low <= date_bin(...) <= high`
833        let (Expr::Literal(low, _), Expr::Literal(high, _)) = (low, high) else {
834            return None;
835        };
836        return_none_if_utf8!(low);
837        return_none_if_utf8!(high);
838        let low = date_bin_range(
839            Operator::GtEq,
840            &scalar_value_to_timestamp(low, None)?,
841            stride,
842            ts_col_unit,
843        );
844        let high = date_bin_range(
845            Operator::LtEq,
846            &scalar_value_to_timestamp(high, None)?,
847            stride,
848            ts_col_unit,
849        );
850        return Some(
851            low.unwrap_or_else(TimestampRange::min_to_max)
852                .and(&high.unwrap_or_else(TimestampRange::min_to_max)),
853        );
854    }
855
856    let Expr::Column(col) = expr else {
857        return None;
858    };
859    if col.name != ts_col_name {
860        return None;
861    }
862
863    match (low, high) {
864        (Expr::Literal(low, _), Expr::Literal(high, _)) => {
865            return_none_if_utf8!(low);
866            return_none_if_utf8!(high);
867
868            let low_opt =
869                scalar_value_to_timestamp(low, None).and_then(|ts| ts.convert_to(ts_col_unit));
870            let high_opt = scalar_value_to_timestamp(high, None)
871                .and_then(|ts| ts.convert_to_ceil(ts_col_unit));
872            Some(TimestampRange::new_inclusive(low_opt, high_opt))
873        }
874        _ => None,
875    }
876}
877
878/// Extract time range filter from `IN (...)` expr.
879fn extract_from_in_list_expr(
880    ts_col_name: &str,
881    expr: &Expr,
882    negated: bool,
883    list: &[Expr],
884) -> Option<TimestampRange> {
885    if negated {
886        return None;
887    }
888    let Expr::Column(col) = expr else {
889        return None;
890    };
891    if col.name != ts_col_name {
892        return None;
893    }
894
895    if list.is_empty() {
896        return Some(TimestampRange::empty());
897    }
898    let mut init_range = TimestampRange::empty();
899    for expr in list {
900        if let Expr::Literal(scalar, _) = expr {
901            return_none_if_utf8!(scalar);
902            // TODO(hl): maybe we should raise an error here since cannot parse
903            // timestamp value from in list expr
904            let timestamp = scalar_value_to_timestamp(scalar, None)?;
905            init_range = init_range.or(&TimestampRange::single(timestamp));
906        }
907    }
908    Some(init_range)
909}
910
911#[cfg(test)]
912mod tests {
913    use std::sync::Arc;
914
915    use common_test_util::temp_dir::{TempDir, create_temp_dir};
916    use datafusion::parquet::arrow::ArrowWriter;
917    use datafusion_common::tree_node::TreeNodeRecursion;
918    use datafusion_common::{Column, ScalarValue};
919    use datafusion_expr::{BinaryExpr, Literal, Operator, col, lit};
920    use datatypes::arrow::array::{
921        ArrayRef, DictionaryArray, Int32Array, LargeStringArray, StringViewArray, UInt8Array,
922        UInt32Array,
923    };
924    use datatypes::arrow::datatypes::{DataType, Field, Schema};
925    use datatypes::arrow::record_batch::RecordBatch;
926    use datatypes::arrow_array::StringArray;
927    use parquet::arrow::ParquetRecordBatchStreamBuilder;
928    use parquet::file::properties::WriterProperties;
929
930    use super::*;
931    use crate::predicate::stats::RowGroupPruningStatistics;
932
933    fn check_build_predicate(expr: Expr, expect: TimestampRange) {
934        assert_eq!(
935            expect,
936            build_time_range_predicate("ts", TimeUnit::Millisecond, &[expr])
937        );
938    }
939
940    fn date_bin(stride: Expr) -> Expr {
941        datafusion::functions::datetime::date_bin().call(vec![stride, col("ts")])
942    }
943
944    fn ms(v: i64) -> Expr {
945        lit(ScalarValue::TimestampMillisecond(Some(v), None))
946    }
947
948    fn minute() -> Expr {
949        lit(ScalarValue::new_interval_mdn(0, 0, 60_000_000_000))
950    }
951
952    #[test]
953    fn test_date_bin() {
954        // Upper bounds on a coarser-than-ns column are widened by one unit, because
955        // `date_bin` truncates its nanosecond bucket start to the column unit.
956        let t = Timestamp::new_millisecond;
957        // date_bin(1m, ts) >= 120_000ms  =>  ts >= 120_000ms
958        check_build_predicate(
959            date_bin(minute()).gt_eq(ms(120_000)),
960            TimestampRange::from_start(t(120_000)),
961        );
962        // date_bin(1m, ts) > 120_000ms  =>  ts > 120_000ms, widened to ts >= 120_000ms
963        check_build_predicate(
964            date_bin(minute()).gt(ms(120_000)),
965            TimestampRange::from_start(t(120_000)),
966        );
967        // date_bin(1m, ts) < 120_000ms  =>  ts < 180_001ms
968        check_build_predicate(
969            date_bin(minute()).lt(ms(120_000)),
970            TimestampRange::until_end(t(180_001), false),
971        );
972        // date_bin(1m, ts) <= 120_000ms  =>  ts < 180_001ms
973        check_build_predicate(
974            date_bin(minute()).lt_eq(ms(120_000)),
975            TimestampRange::until_end(t(180_001), false),
976        );
977        // 120_000ms <= date_bin(1m, ts)  =>  ts >= 120_000ms
978        check_build_predicate(
979            ms(120_000).lt_eq(date_bin(minute())),
980            TimestampRange::from_start(t(120_000)),
981        );
982        // date_bin(1m, ts) = 120_000ms  =>  120_000ms <= ts < 180_001ms
983        check_build_predicate(
984            date_bin(minute()).eq(ms(120_000)),
985            TimestampRange::new(t(120_000), t(180_001)).unwrap(),
986        );
987        // date_bin(1m, ts) BETWEEN 60_000ms AND 120_000ms  =>  60_000ms <= ts < 180_001ms
988        check_build_predicate(
989            date_bin(minute()).between(ms(60_000), ms(120_000)),
990            TimestampRange::new(t(60_000), t(180_001)).unwrap(),
991        );
992        // Combined with other conjuncts.
993        check_build_predicate(
994            date_bin(minute())
995                .gt_eq(ms(60_000))
996                .and(date_bin(minute()).lt(ms(120_000)))
997                .and(col("v").gt(lit(1))),
998            TimestampRange::new(t(60_000), t(180_001)).unwrap(),
999        );
1000        // An origin argument doesn't change the bounds.
1001        check_build_predicate(
1002            datafusion::functions::datetime::date_bin()
1003                .call(vec![minute(), col("ts"), ms(17)])
1004                .gt_eq(ms(120_000)),
1005            TimestampRange::from_start(t(120_000)),
1006        );
1007        // A month stride has no fixed width: no range for the upper bound.
1008        check_build_predicate(
1009            date_bin(lit(ScalarValue::new_interval_mdn(1, 0, 0))).lt(ms(120_000)),
1010            TimestampRange::min_to_max(),
1011        );
1012        // Other columns are ignored.
1013        check_build_predicate(
1014            datafusion::functions::datetime::date_bin()
1015                .call(vec![minute(), col("other")])
1016                .gt_eq(ms(120_000)),
1017            TimestampRange::min_to_max(),
1018        );
1019        // An upper bound that overflows leaves the range unbounded.
1020        check_build_predicate(
1021            date_bin(minute()).lt_eq(ms(i64::MAX - 1)),
1022            TimestampRange::min_to_max(),
1023        );
1024    }
1025
1026    /// Evaluates `date_bin` with DataFusion over a grid of timestamps, then checks
1027    /// that every row satisfying a comparison on its result lies in the extracted
1028    /// range. Covers coarse column units, strides and origins that are not a whole
1029    /// number of column units, and negative timestamps.
1030    #[tokio::test]
1031    async fn test_date_bin_range_keeps_satisfying_rows() {
1032        /// Whether the comparison holds for a `date_bin` result.
1033        type BinHolds = Box<dyn Fn(i64) -> bool>;
1034
1035        use datafusion::prelude::SessionContext;
1036        use datafusion_expr::cast;
1037        use datatypes::arrow::array::{AsArray, Int64Array};
1038        use datatypes::arrow::datatypes::{Int64Type, TimeUnit as ArrowTimeUnit};
1039
1040        let units = [
1041            (TimeUnit::Second, ArrowTimeUnit::Second, 1_000_000_000i64),
1042            (TimeUnit::Millisecond, ArrowTimeUnit::Millisecond, 1_000_000),
1043            (TimeUnit::Microsecond, ArrowTimeUnit::Microsecond, 1_000),
1044        ];
1045        let ctx = SessionContext::new();
1046
1047        for (unit, arrow_unit, ns_per_unit) in units {
1048            let ts_lit = |v: i64| {
1049                lit(match unit {
1050                    TimeUnit::Second => ScalarValue::TimestampSecond(Some(v), None),
1051                    TimeUnit::Millisecond => ScalarValue::TimestampMillisecond(Some(v), None),
1052                    TimeUnit::Microsecond => ScalarValue::TimestampMicrosecond(Some(v), None),
1053                    TimeUnit::Nanosecond => ScalarValue::TimestampNanosecond(Some(v), None),
1054                })
1055            };
1056            let ts_type = DataType::Timestamp(arrow_unit, None);
1057            let ts_array = datatypes::arrow::compute::cast(
1058                &Int64Array::from((-30..=30).collect::<Vec<i64>>()),
1059                &ts_type,
1060            )
1061            .unwrap();
1062            let schema = Arc::new(Schema::new(vec![Field::new("ts", ts_type, false)]));
1063            let batch = RecordBatch::try_new(schema, vec![ts_array]).unwrap();
1064
1065            let strides_ns = [
1066                ns_per_unit,
1067                ns_per_unit * 3,
1068                ns_per_unit / 2,
1069                ns_per_unit * 13 / 10,
1070                ns_per_unit * 26 / 10,
1071            ];
1072            let origins_ns = [
1073                None,
1074                Some(0),
1075                Some(ns_per_unit / 2),
1076                Some(-ns_per_unit * 7 / 3),
1077            ];
1078            for stride_ns in strides_ns {
1079                for origin_ns in origins_ns {
1080                    let mut args = vec![
1081                        lit(ScalarValue::new_interval_mdn(0, 0, stride_ns)),
1082                        col("ts"),
1083                    ];
1084                    if let Some(origin) = origin_ns {
1085                        args.push(lit(ScalarValue::TimestampNanosecond(Some(origin), None)));
1086                    }
1087                    let bin = datafusion::functions::datetime::date_bin().call(args);
1088
1089                    // (ts, date_bin(ts)), both in the column unit.
1090                    let rows: Vec<(i64, i64)> = ctx
1091                        .read_batch(batch.clone())
1092                        .unwrap()
1093                        .select(vec![
1094                            cast(col("ts"), DataType::Int64),
1095                            cast(bin.clone(), DataType::Int64),
1096                        ])
1097                        .unwrap()
1098                        .collect()
1099                        .await
1100                        .unwrap()
1101                        .iter()
1102                        .flat_map(|b| {
1103                            let ts = b.column(0).as_primitive::<Int64Type>();
1104                            let bins = b.column(1).as_primitive::<Int64Type>();
1105                            ts.values()
1106                                .iter()
1107                                .copied()
1108                                .zip(bins.values().iter().copied())
1109                                .collect::<Vec<_>>()
1110                        })
1111                        .collect();
1112                    assert_eq!(rows.len(), 61);
1113
1114                    for c in -35..=35 {
1115                        let cases: Vec<(Expr, BinHolds)> = vec![
1116                            (bin.clone().eq(ts_lit(c)), Box::new(move |b| b == c)),
1117                            (bin.clone().lt(ts_lit(c)), Box::new(move |b| b < c)),
1118                            (bin.clone().lt_eq(ts_lit(c)), Box::new(move |b| b <= c)),
1119                            (bin.clone().gt(ts_lit(c)), Box::new(move |b| b > c)),
1120                            (bin.clone().gt_eq(ts_lit(c)), Box::new(move |b| b >= c)),
1121                            (ts_lit(c).gt_eq(bin.clone()), Box::new(move |b| c >= b)),
1122                            (
1123                                bin.clone().between(ts_lit(c), ts_lit(c + 2)),
1124                                Box::new(move |b| c <= b && b <= c + 2),
1125                            ),
1126                        ];
1127                        for (expr, holds) in cases {
1128                            let range =
1129                                build_time_range_predicate("ts", unit, std::slice::from_ref(&expr));
1130                            for &(ts, b) in &rows {
1131                                assert!(
1132                                    !holds(b) || range.contains(&Timestamp::new(ts, unit)),
1133                                    "{expr} holds for ts={ts} (bin={b}, {unit:?}, stride={stride_ns}ns, origin={origin_ns:?}ns) but {range:?} excludes it",
1134                                );
1135                            }
1136                        }
1137                    }
1138                }
1139            }
1140        }
1141    }
1142
1143    #[test]
1144    fn test_gt() {
1145        // ts > 1ms
1146        check_build_predicate(
1147            col("ts").gt(lit(ScalarValue::TimestampMillisecond(Some(1), None))),
1148            TimestampRange::from_start(Timestamp::new_millisecond(2)),
1149        );
1150
1151        // 1ms > ts
1152        check_build_predicate(
1153            lit(ScalarValue::TimestampMillisecond(Some(1), None)).gt(col("ts")),
1154            TimestampRange::until_end(Timestamp::new_millisecond(1), false),
1155        );
1156
1157        // 1001us > ts
1158        check_build_predicate(
1159            lit(ScalarValue::TimestampMicrosecond(Some(1001), None)).gt(col("ts")),
1160            TimestampRange::until_end(Timestamp::new_millisecond(1), true),
1161        );
1162
1163        // ts > 1001us
1164        check_build_predicate(
1165            col("ts").gt(lit(ScalarValue::TimestampMicrosecond(Some(1001), None))),
1166            TimestampRange::from_start(Timestamp::new_millisecond(2)),
1167        );
1168
1169        // 1s > ts
1170        check_build_predicate(
1171            lit(ScalarValue::TimestampSecond(Some(1), None)).gt(col("ts")),
1172            TimestampRange::until_end(Timestamp::new_millisecond(1000), false),
1173        );
1174
1175        // ts > 1s
1176        check_build_predicate(
1177            col("ts").gt(lit(ScalarValue::TimestampSecond(Some(1), None))),
1178            TimestampRange::from_start(Timestamp::new_millisecond(1001)),
1179        );
1180    }
1181
1182    #[test]
1183    fn test_gt_eq() {
1184        // ts >= 1ms
1185        check_build_predicate(
1186            col("ts").gt_eq(lit(ScalarValue::TimestampMillisecond(Some(1), None))),
1187            TimestampRange::from_start(Timestamp::new_millisecond(1)),
1188        );
1189
1190        // 1ms >= ts
1191        check_build_predicate(
1192            lit(ScalarValue::TimestampMillisecond(Some(1), None)).gt_eq(col("ts")),
1193            TimestampRange::until_end(Timestamp::new_millisecond(1), true),
1194        );
1195
1196        // 1001us >= ts
1197        check_build_predicate(
1198            lit(ScalarValue::TimestampMicrosecond(Some(1001), None)).gt_eq(col("ts")),
1199            TimestampRange::until_end(Timestamp::new_millisecond(1), true),
1200        );
1201
1202        // ts >= 1001us
1203        check_build_predicate(
1204            col("ts").gt_eq(lit(ScalarValue::TimestampMicrosecond(Some(1001), None))),
1205            TimestampRange::from_start(Timestamp::new_millisecond(2)),
1206        );
1207
1208        // 1s >= ts
1209        check_build_predicate(
1210            lit(ScalarValue::TimestampSecond(Some(1), None)).gt_eq(col("ts")),
1211            TimestampRange::until_end(Timestamp::new_millisecond(1000), true),
1212        );
1213
1214        // ts >= 1s
1215        check_build_predicate(
1216            col("ts").gt_eq(lit(ScalarValue::TimestampSecond(Some(1), None))),
1217            TimestampRange::from_start(Timestamp::new_millisecond(1000)),
1218        );
1219    }
1220
1221    #[test]
1222    fn test_lt() {
1223        // ts < 1ms
1224        check_build_predicate(
1225            col("ts").lt(lit(ScalarValue::TimestampMillisecond(Some(1), None))),
1226            TimestampRange::until_end(Timestamp::new_millisecond(1), false),
1227        );
1228
1229        // 1ms < ts
1230        check_build_predicate(
1231            lit(ScalarValue::TimestampMillisecond(Some(1), None)).lt(col("ts")),
1232            TimestampRange::from_start(Timestamp::new_millisecond(2)),
1233        );
1234
1235        // 1001us < ts
1236        check_build_predicate(
1237            lit(ScalarValue::TimestampMicrosecond(Some(1001), None)).lt(col("ts")),
1238            TimestampRange::from_start(Timestamp::new_millisecond(2)),
1239        );
1240
1241        // ts < 1001us
1242        check_build_predicate(
1243            col("ts").lt(lit(ScalarValue::TimestampMicrosecond(Some(1001), None))),
1244            TimestampRange::until_end(Timestamp::new_millisecond(1), true),
1245        );
1246
1247        // 1s < ts
1248        check_build_predicate(
1249            lit(ScalarValue::TimestampSecond(Some(1), None)).lt(col("ts")),
1250            TimestampRange::from_start(Timestamp::new_millisecond(1001)),
1251        );
1252
1253        // ts < 1s
1254        check_build_predicate(
1255            col("ts").lt(lit(ScalarValue::TimestampSecond(Some(1), None))),
1256            TimestampRange::until_end(Timestamp::new_millisecond(1000), false),
1257        );
1258    }
1259
1260    #[test]
1261    fn test_lt_eq() {
1262        // ts <= 1ms
1263        check_build_predicate(
1264            col("ts").lt_eq(lit(ScalarValue::TimestampMillisecond(Some(1), None))),
1265            TimestampRange::until_end(Timestamp::new_millisecond(1), true),
1266        );
1267
1268        // 1ms <= ts
1269        check_build_predicate(
1270            lit(ScalarValue::TimestampMillisecond(Some(1), None)).lt_eq(col("ts")),
1271            TimestampRange::from_start(Timestamp::new_millisecond(1)),
1272        );
1273
1274        // 1001us <= ts
1275        check_build_predicate(
1276            lit(ScalarValue::TimestampMicrosecond(Some(1001), None)).lt_eq(col("ts")),
1277            TimestampRange::from_start(Timestamp::new_millisecond(2)),
1278        );
1279
1280        // ts <= 1001us
1281        check_build_predicate(
1282            col("ts").lt_eq(lit(ScalarValue::TimestampMicrosecond(Some(1001), None))),
1283            TimestampRange::until_end(Timestamp::new_millisecond(1), true),
1284        );
1285
1286        // 1s <= ts
1287        check_build_predicate(
1288            lit(ScalarValue::TimestampSecond(Some(1), None)).lt_eq(col("ts")),
1289            TimestampRange::from_start(Timestamp::new_millisecond(1000)),
1290        );
1291
1292        // ts <= 1s
1293        check_build_predicate(
1294            col("ts").lt_eq(lit(ScalarValue::TimestampSecond(Some(1), None))),
1295            TimestampRange::until_end(Timestamp::new_millisecond(1000), true),
1296        );
1297    }
1298
1299    #[test]
1300    fn test_extract_time_range_strict() {
1301        fn ts_lit(ms: i64) -> Expr {
1302            lit(ScalarValue::TimestampMillisecond(Some(ms), None))
1303        }
1304        let extract =
1305            |filters: &[Expr]| extract_time_range_strict("ts", TimeUnit::Millisecond, filters);
1306        let range = |start: i64, end: i64| {
1307            TimestampRange::new(
1308                Timestamp::new_millisecond(start),
1309                Timestamp::new_millisecond(end),
1310            )
1311            .unwrap()
1312        };
1313
1314        // No filter references the column.
1315        assert_eq!(extract(&[]), TimeRangeExtraction::Absent);
1316        assert_eq!(
1317            extract(&[col("host").eq(lit("a"))]),
1318            TimeRangeExtraction::Absent
1319        );
1320
1321        // Both bounds across conjuncts; unrelated filters are ignored.
1322        assert_eq!(
1323            extract(&[
1324                col("ts").gt_eq(ts_lit(1000)),
1325                col("ts").lt(ts_lit(2000)),
1326                col("host").eq(lit("a")),
1327            ]),
1328            TimeRangeExtraction::Extracted(range(1000, 2000))
1329        );
1330
1331        // Lower bound only / upper bound only.
1332        assert_eq!(
1333            extract(&[col("ts").gt_eq(ts_lit(1000))]),
1334            TimeRangeExtraction::Extracted(TimestampRange::from_start(Timestamp::new_millisecond(
1335                1000
1336            )))
1337        );
1338        assert_eq!(
1339            extract(&[col("ts").lt(ts_lit(2000))]),
1340            TimeRangeExtraction::Extracted(TimestampRange::until_end(
1341                Timestamp::new_millisecond(2000),
1342                false
1343            ))
1344        );
1345
1346        // BETWEEN is inclusive on both ends.
1347        assert_eq!(
1348            extract(&[col("ts").between(ts_lit(1000), ts_lit(2000))]),
1349            TimeRangeExtraction::Extracted(range(1000, 2001))
1350        );
1351
1352        // Equality pins a single point.
1353        assert_eq!(
1354            extract(&[col("ts").eq(ts_lit(1500))]),
1355            TimeRangeExtraction::Extracted(TimestampRange::single(Timestamp::new_millisecond(
1356                1500
1357            )))
1358        );
1359
1360        // An unparsable side under AND only widens; the extraction stays safe.
1361        assert_eq!(
1362            extract(&[col("ts").gt_eq(ts_lit(1000)).and(col("ts").lt(col("t2")))]),
1363            TimeRangeExtraction::Extracted(TimestampRange::from_start(Timestamp::new_millisecond(
1364                1000
1365            )))
1366        );
1367
1368        // Contradictory bounds collapse to the empty range, not an error.
1369        let TimeRangeExtraction::Extracted(empty) =
1370            extract(&[col("ts").gt_eq(ts_lit(2000)), col("ts").lt(ts_lit(1000))])
1371        else {
1372            panic!("expected an extraction");
1373        };
1374        assert!(empty.is_empty());
1375
1376        // Shapes that could widen the satisfying set beyond what is extractable
1377        // must be refused: OR with an unparsable side, NOT, non-literal bounds.
1378        assert_eq!(
1379            extract(&[col("ts").gt(ts_lit(1000)).or(col("host").eq(lit("a")))]),
1380            TimeRangeExtraction::Unsupported
1381        );
1382        assert_eq!(
1383            extract(&[!col("ts").gt(ts_lit(1000))]),
1384            TimeRangeExtraction::Unsupported
1385        );
1386        assert_eq!(
1387            extract(&[col("ts").gt_eq(col("t2"))]),
1388            TimeRangeExtraction::Unsupported
1389        );
1390
1391        // A range derived from `date_bin` over-approximates by up to a bucket, so a
1392        // timestamp synthesized from its bounds may fail the filter: refuse it.
1393        assert_eq!(
1394            extract(&[date_bin(minute()).gt(ts_lit(60_000))]),
1395            TimeRangeExtraction::Unsupported
1396        );
1397        assert_eq!(
1398            extract(&[date_bin(minute()).between(ts_lit(0), ts_lit(60_000))]),
1399            TimeRangeExtraction::Unsupported
1400        );
1401        // Under AND it is dropped like any other unparsable side.
1402        assert_eq!(
1403            extract(&[col("ts")
1404                .lt(ts_lit(2000))
1405                .and(date_bin(minute()).gt_eq(ts_lit(60_000)))]),
1406            TimeRangeExtraction::Extracted(TimestampRange::until_end(
1407                Timestamp::new_millisecond(2000),
1408                false
1409            ))
1410        );
1411    }
1412
1413    async fn gen_test_parquet_file(dir: &TempDir, cnt: usize) -> (String, Arc<Schema>) {
1414        let path = dir
1415            .path()
1416            .join("test-prune.parquet")
1417            .to_string_lossy()
1418            .to_string();
1419
1420        let name_field = Field::new("name", DataType::Utf8, true);
1421        let count_field = Field::new("cnt", DataType::Int32, true);
1422        let schema = Arc::new(Schema::new(vec![name_field, count_field]));
1423
1424        let file = std::fs::OpenOptions::new()
1425            .write(true)
1426            .create(true)
1427            .truncate(true)
1428            .open(path.clone())
1429            .unwrap();
1430
1431        let write_props = WriterProperties::builder()
1432            .set_max_row_group_row_count(Some(10))
1433            .build();
1434        let mut writer = ArrowWriter::try_new(file, schema.clone(), Some(write_props)).unwrap();
1435
1436        for i in (0..cnt).step_by(10) {
1437            let name_array = Arc::new(StringArray::from(
1438                (i..(i + 10).min(cnt))
1439                    .map(|i| i.to_string())
1440                    .collect::<Vec<_>>(),
1441            )) as Arc<_>;
1442            let count_array = Arc::new(Int32Array::from(
1443                (i..(i + 10).min(cnt)).map(|i| i as i32).collect::<Vec<_>>(),
1444            )) as Arc<_>;
1445            let rb = RecordBatch::try_new(schema.clone(), vec![name_array, count_array]).unwrap();
1446            writer.write(&rb).unwrap();
1447        }
1448        let _ = writer.close().unwrap();
1449        (path, schema)
1450    }
1451
1452    async fn assert_prune(array_cnt: usize, filters: Vec<Expr>, expect: Vec<bool>) {
1453        let dir = create_temp_dir("prune_parquet");
1454        let (path, arrow_schema) = gen_test_parquet_file(&dir, array_cnt).await;
1455        let schema = Arc::new(datatypes::schema::Schema::try_from(arrow_schema.clone()).unwrap());
1456        let arrow_predicate = Predicate::new(filters);
1457        let builder = ParquetRecordBatchStreamBuilder::new(
1458            tokio::fs::OpenOptions::new()
1459                .read(true)
1460                .open(path)
1461                .await
1462                .unwrap(),
1463        )
1464        .await
1465        .unwrap();
1466        let metadata = builder.metadata().clone();
1467        let row_groups = metadata.row_groups();
1468
1469        let stats = RowGroupPruningStatistics::new(row_groups, &schema);
1470        let res = arrow_predicate.prune_with_stats(&stats, &arrow_schema);
1471        assert_eq!(expect, res);
1472    }
1473
1474    #[test]
1475    fn test_clear_dyn_filters_preserves_static_predicates() {
1476        use datafusion_physical_expr::expressions::lit as physical_lit;
1477
1478        let static_exprs = vec![col("a").eq(lit(1_i32))];
1479        let dynamic_filter = Arc::new(DynamicFilterPhysicalExpr::new(vec![], physical_lit(true)));
1480        let predicate =
1481            Predicate::with_dyn_filters(static_exprs.clone(), vec![dynamic_filter.clone()]);
1482
1483        predicate.clear_dyn_filters();
1484        // An update from the old producer must not put its wrapper back into this execution.
1485        dynamic_filter.update(physical_lit(false)).unwrap();
1486
1487        assert_eq!(predicate.exprs(), static_exprs);
1488        assert!(predicate.dyn_filters().is_empty());
1489        assert!(predicate.dyn_filter_phy_exprs().unwrap().is_empty());
1490    }
1491
1492    #[tokio::test]
1493    async fn test_dynamic_topk_pruning_nullable_lexicographic_keys() {
1494        use std::cmp::Ordering;
1495
1496        use datafusion::datasource::memory::MemorySourceConfig;
1497        use datafusion::execution::context::TaskContext;
1498        use datafusion::physical_plan::sorts::sort::SortExec;
1499        use datafusion::physical_plan::{ExecutionPlan, collect};
1500        use datafusion_physical_expr::PhysicalSortExpr;
1501        use datafusion_physical_expr::expressions::Column as PhysicalColumn;
1502        use datatypes::arrow::compute::SortOptions;
1503
1504        type Row = (Option<i32>, Option<i32>);
1505
1506        fn compare(left: Option<i32>, right: Option<i32>, options: SortOptions) -> Ordering {
1507            match (left, right) {
1508                (None, None) => Ordering::Equal,
1509                (None, Some(_)) => {
1510                    if options.nulls_first {
1511                        Ordering::Less
1512                    } else {
1513                        Ordering::Greater
1514                    }
1515                }
1516                (Some(_), None) => {
1517                    if options.nulls_first {
1518                        Ordering::Greater
1519                    } else {
1520                        Ordering::Less
1521                    }
1522                }
1523                (Some(left), Some(right)) => {
1524                    let ordering = left.cmp(&right);
1525                    if options.descending {
1526                        ordering.reverse()
1527                    } else {
1528                        ordering
1529                    }
1530                }
1531            }
1532        }
1533
1534        let groups: [[Row; 2]; 6] = [
1535            [(Some(11), None), (Some(12), Some(1))],
1536            [(Some(10), Some(4)), (Some(10), Some(5))],
1537            [(Some(9), None), (Some(10), Some(6))],
1538            [(None, Some(1)), (None, Some(2))],
1539            [(Some(10), None), (Some(10), Some(1))],
1540            [(Some(10), Some(5)), (Some(10), Some(5))],
1541        ];
1542        let dir = create_temp_dir("dynamic_topk_pruning");
1543        let path = dir.path().join("nullable.parquet");
1544        let arrow_schema = Arc::new(Schema::new(vec![
1545            Field::new("a", DataType::Int32, true),
1546            Field::new("b", DataType::Int32, true),
1547        ]));
1548        let batch = |rows: &[Row]| {
1549            RecordBatch::try_new(
1550                arrow_schema.clone(),
1551                vec![
1552                    Arc::new(Int32Array::from(
1553                        rows.iter().map(|r| r.0).collect::<Vec<_>>(),
1554                    )),
1555                    Arc::new(Int32Array::from(
1556                        rows.iter().map(|r| r.1).collect::<Vec<_>>(),
1557                    )),
1558                ],
1559            )
1560            .unwrap()
1561        };
1562        let mut writer = ArrowWriter::try_new(
1563            std::fs::File::create(&path).unwrap(),
1564            arrow_schema.clone(),
1565            None,
1566        )
1567        .unwrap();
1568        for group in &groups {
1569            writer.write(&batch(group)).unwrap();
1570            writer.flush().unwrap();
1571        }
1572        writer.close().unwrap();
1573        let builder =
1574            ParquetRecordBatchStreamBuilder::new(tokio::fs::File::open(path).await.unwrap())
1575                .await
1576                .unwrap();
1577        let schema = Arc::new(datatypes::schema::Schema::try_from(arrow_schema.clone()).unwrap());
1578        let stats = RowGroupPruningStatistics::new(builder.metadata().row_groups(), &schema);
1579
1580        for (options, boundary, expected, must_prune_first) in [
1581            (
1582                SortOptions {
1583                    descending: false,
1584                    nulls_first: false,
1585                },
1586                (Some(10), Some(5)),
1587                [(Some(9), None), (Some(10), Some(1))],
1588                true,
1589            ),
1590            (
1591                SortOptions {
1592                    descending: false,
1593                    nulls_first: true,
1594                },
1595                (Some(10), Some(5)),
1596                [(None, Some(1)), (None, Some(2))],
1597                false,
1598            ),
1599            (
1600                SortOptions {
1601                    descending: true,
1602                    nulls_first: false,
1603                },
1604                (Some(10), Some(5)),
1605                [(Some(12), Some(1)), (Some(11), None)],
1606                false,
1607            ),
1608            (
1609                SortOptions {
1610                    descending: false,
1611                    nulls_first: true,
1612                },
1613                (None, Some(5)),
1614                [(None, Some(1)), (None, Some(2))],
1615                false,
1616            ),
1617            (
1618                SortOptions {
1619                    descending: false,
1620                    nulls_first: false,
1621                },
1622                (None, Some(5)),
1623                [(Some(9), None), (Some(10), Some(1))],
1624                false,
1625            ),
1626            (
1627                SortOptions {
1628                    descending: false,
1629                    nulls_first: false,
1630                },
1631                (Some(10), None),
1632                [(Some(9), None), (Some(10), Some(1))],
1633                true,
1634            ),
1635        ] {
1636            // Let the real SortExec/TopK producer publish its boundary predicate.
1637            // Two boundary rows also make dropping later full-key ties safe.
1638            let seed = [boundary, boundary];
1639            let input =
1640                MemorySourceConfig::try_new_exec(&[vec![batch(&seed)]], arrow_schema.clone(), None)
1641                    .unwrap();
1642            let ordering = [
1643                PhysicalSortExpr {
1644                    expr: Arc::new(PhysicalColumn::new("a", 0)),
1645                    options,
1646                },
1647                PhysicalSortExpr {
1648                    expr: Arc::new(PhysicalColumn::new("b", 1)),
1649                    options,
1650                },
1651            ];
1652            let sort = SortExec::new(ordering.into(), input).with_fetch(Some(2));
1653            let filter = sort
1654                .dynamic_expressions_produced()
1655                .into_iter()
1656                .next()
1657                .unwrap();
1658            let filter = (filter as Arc<dyn std::any::Any + Send + Sync>)
1659                .downcast::<DynamicFilterPhysicalExpr>()
1660                .unwrap();
1661            collect(Arc::new(sort), Arc::new(TaskContext::default()))
1662                .await
1663                .unwrap();
1664            let predicate = Predicate::with_dyn_filters(vec![], vec![filter]);
1665            let keep = predicate.prune_with_stats(&stats, &arrow_schema);
1666            if must_prune_first {
1667                assert!(
1668                    !keep[0],
1669                    "disjoint first row group must be pruned: {options:?}, {boundary:?}"
1670                );
1671            }
1672            if boundary == (Some(10), Some(5)) && !options.nulls_first && !options.descending {
1673                assert!(
1674                    !keep[5],
1675                    "duplicate full-key ties may be pruned after the heap is full"
1676                );
1677            }
1678
1679            let top_two = |mut rows: Vec<Row>| {
1680                rows.sort_by(|left, right| {
1681                    compare(left.0, right.0, options)
1682                        .then_with(|| compare(left.1, right.1, options))
1683                });
1684                rows.truncate(2);
1685                rows
1686            };
1687            let all = seed
1688                .into_iter()
1689                .chain(groups.into_iter().flatten())
1690                .collect();
1691            let retained = seed
1692                .into_iter()
1693                .chain(
1694                    groups
1695                        .into_iter()
1696                        .zip(keep)
1697                        .filter(|(_, keep)| *keep)
1698                        .flat_map(|(rows, _)| rows),
1699                )
1700                .collect();
1701            assert_eq!(
1702                top_two(all),
1703                expected,
1704                "explicit sort oracle: {options:?}, {boundary:?}"
1705            );
1706            assert_eq!(
1707                top_two(retained),
1708                expected,
1709                "pruned result: {options:?}, {boundary:?}"
1710            );
1711            // Seed duplicates must remain available when every candidate ties
1712            // the full boundary, even if all tied SST rows are pruned.
1713            assert_eq!(top_two(seed.to_vec()), vec![boundary, boundary]);
1714        }
1715    }
1716
1717    #[tokio::test]
1718    async fn test_dynamic_aggregate_unknown_to_known_pruning() {
1719        use std::sync::Mutex;
1720
1721        use datafusion::execution::context::TaskContext;
1722        use datafusion::functions_aggregate::min_max::min_udaf;
1723        use datafusion::physical_expr::aggregate::AggregateExprBuilder;
1724        use datafusion::physical_plan::aggregates::{
1725            AggregateExec, AggregateMode, PhysicalGroupBy,
1726        };
1727        use datafusion::physical_plan::common::collect;
1728        use datafusion::physical_plan::stream::RecordBatchStreamAdapter;
1729        use datafusion::physical_plan::streaming::{PartitionStream, StreamingTableExec};
1730        use datafusion::physical_plan::{ExecutionPlan, SendableRecordBatchStream};
1731        use datafusion_physical_expr::expressions::col as physical_col;
1732        use datatypes::arrow::array::Int64Array;
1733        use futures::{StreamExt, channel::mpsc};
1734
1735        #[derive(Debug)]
1736        struct TestInput {
1737            schema: Arc<Schema>,
1738            receiver:
1739                Mutex<Option<mpsc::UnboundedReceiver<datafusion_common::Result<RecordBatch>>>>,
1740        }
1741        impl PartitionStream for TestInput {
1742            fn schema(&self) -> &Arc<Schema> {
1743                &self.schema
1744            }
1745
1746            fn execute(&self, _: Arc<TaskContext>) -> SendableRecordBatchStream {
1747                let stream = self.receiver.lock().unwrap().take().unwrap();
1748                Box::pin(RecordBatchStreamAdapter::new(self.schema.clone(), stream))
1749            }
1750        }
1751
1752        let arrow_schema = Arc::new(Schema::new(vec![
1753            Field::new("a", DataType::Int64, true),
1754            Field::new("b", DataType::Int64, true),
1755        ]));
1756        let dir = create_temp_dir("dynamic_aggregate_pruning");
1757        let path = dir.path().join("nullable.parquet");
1758        let make_batch = |a: Vec<Option<i64>>, b: Vec<Option<i64>>| {
1759            RecordBatch::try_new(
1760                arrow_schema.clone(),
1761                vec![Arc::new(Int64Array::from(a)), Arc::new(Int64Array::from(b))],
1762            )
1763            .unwrap()
1764        };
1765        let mut writer = ArrowWriter::try_new(
1766            std::fs::File::create(&path).unwrap(),
1767            arrow_schema.clone(),
1768            None,
1769        )
1770        .unwrap();
1771        for batch in [
1772            make_batch(vec![Some(101)], vec![Some(5)]),
1773            make_batch(vec![Some(101)], vec![Some(1)]),
1774        ] {
1775            writer.write(&batch).unwrap();
1776            writer.flush().unwrap();
1777        }
1778        writer.close().unwrap();
1779        let builder =
1780            ParquetRecordBatchStreamBuilder::new(tokio::fs::File::open(path).await.unwrap())
1781                .await
1782                .unwrap();
1783        let schema = Arc::new(datatypes::schema::Schema::try_from(arrow_schema.clone()).unwrap());
1784        let stats = RowGroupPruningStatistics::new(builder.metadata().row_groups(), &schema);
1785        let (sender, receiver) = mpsc::unbounded();
1786        let input = Arc::new(
1787            StreamingTableExec::try_new(
1788                arrow_schema.clone(),
1789                vec![Arc::new(TestInput {
1790                    schema: arrow_schema.clone(),
1791                    receiver: Mutex::new(Some(receiver)),
1792                })],
1793                None,
1794                [],
1795                false,
1796                None,
1797            )
1798            .unwrap(),
1799        );
1800        let aggregates = ["a", "b"]
1801            .into_iter()
1802            .map(|name| {
1803                Arc::new(
1804                    AggregateExprBuilder::new(
1805                        min_udaf(),
1806                        vec![physical_col(name, &arrow_schema).unwrap()],
1807                    )
1808                    .schema(arrow_schema.clone())
1809                    .alias(name)
1810                    .build()
1811                    .unwrap(),
1812                )
1813            })
1814            .collect();
1815        let aggregate = Arc::new(
1816            AggregateExec::try_new(
1817                AggregateMode::Partial,
1818                PhysicalGroupBy::default(),
1819                aggregates,
1820                vec![None; 2],
1821                input,
1822                arrow_schema.clone(),
1823            )
1824            .unwrap(),
1825        );
1826        let expr = aggregate.dynamic_expressions_produced().pop().unwrap();
1827        let dynamic_filter = (expr as Arc<dyn std::any::Any + Send + Sync>)
1828            .downcast::<DynamicFilterPhysicalExpr>()
1829            .unwrap();
1830        let predicate = Predicate::with_dyn_filters(vec![], vec![dynamic_filter]);
1831        let mut stream = aggregate
1832            .execute(0, Arc::new(TaskContext::default()))
1833            .unwrap();
1834
1835        sender
1836            .unbounded_send(Ok(make_batch(vec![Some(100)], vec![None])))
1837            .unwrap();
1838        // Poll until the input channel becomes pending, after processing this batch.
1839        assert!(futures::poll!(stream.next()).is_pending());
1840        assert_eq!(
1841            predicate.prune_with_stats(&stats, &arrow_schema),
1842            vec![true, true],
1843            "unknown min(b) must keep a possible first non-NULL value"
1844        );
1845        sender
1846            .unbounded_send(Ok(make_batch(vec![Some(99)], vec![Some(2)])))
1847            .unwrap();
1848        assert!(futures::poll!(stream.next()).is_pending());
1849        assert_eq!(
1850            predicate.prune_with_stats(&stats, &arrow_schema),
1851            vec![false, true],
1852            "known bounds prune only the non-improving group"
1853        );
1854        sender
1855            .unbounded_send(Ok(make_batch(vec![Some(101)], vec![Some(1)])))
1856            .unwrap();
1857        drop(sender);
1858        let results = collect(stream).await.unwrap();
1859        assert_eq!(results.len(), 1);
1860        assert_eq!(
1861            ScalarValue::try_from_array(results[0].column(0), 0).unwrap(),
1862            ScalarValue::Int64(Some(99))
1863        );
1864        assert_eq!(
1865            ScalarValue::try_from_array(results[0].column(1), 0).unwrap(),
1866            ScalarValue::Int64(Some(1))
1867        );
1868    }
1869
1870    #[tokio::test]
1871    async fn test_clear_dyn_filters_restores_static_row_group_pruning() {
1872        use datafusion_physical_expr::expressions::{
1873            Column as PhysicalColumn, lit as physical_lit,
1874        };
1875
1876        let dir = create_temp_dir("dynamic_pruning_reset");
1877        let (path, arrow_schema) = gen_test_parquet_file(&dir, 30).await;
1878        let schema = Arc::new(datatypes::schema::Schema::try_from(arrow_schema.clone()).unwrap());
1879        let builder =
1880            ParquetRecordBatchStreamBuilder::new(tokio::fs::File::open(path).await.unwrap())
1881                .await
1882                .unwrap();
1883        let stats = RowGroupPruningStatistics::new(builder.metadata().row_groups(), &schema);
1884        let dynamic_filter = Arc::new(DynamicFilterPhysicalExpr::new(
1885            vec![Arc::new(PhysicalColumn::new("cnt", 1))],
1886            physical_lit(true),
1887        ));
1888        let predicate = Predicate::with_dyn_filters(
1889            vec![col("cnt").gt_eq(lit(10_i32))],
1890            vec![dynamic_filter.clone()],
1891        );
1892
1893        dynamic_filter
1894            .update(
1895                Predicate::to_physical_expr(&col("cnt").gt(lit(100_i32)), &arrow_schema).unwrap(),
1896            )
1897            .unwrap();
1898        assert_eq!(
1899            predicate.prune_with_stats(&stats, &arrow_schema),
1900            vec![false; 3]
1901        );
1902
1903        // Reset after the prior stream is dropped: no dynamic filter remains, while the
1904        // static predicate still excludes only the first row group.
1905        predicate.clear_dyn_filters();
1906        assert_eq!(
1907            predicate.prune_with_stats(&stats, &arrow_schema),
1908            vec![false, true, true]
1909        );
1910    }
1911
1912    fn gen_predicate(max_val: i32, op: Operator) -> Vec<Expr> {
1913        vec![datafusion_expr::Expr::BinaryExpr(BinaryExpr {
1914            left: Box::new(datafusion_expr::Expr::Column(Column::from_name("cnt"))),
1915            op,
1916            right: Box::new(max_val.lit()),
1917        })]
1918    }
1919
1920    #[tokio::test]
1921    async fn test_prune_empty() {
1922        assert_prune(3, vec![], vec![true]).await;
1923    }
1924
1925    #[tokio::test]
1926    async fn test_prune_all_match() {
1927        let p = gen_predicate(3, Operator::Gt);
1928        assert_prune(2, p, vec![false]).await;
1929    }
1930
1931    #[tokio::test]
1932    async fn test_prune_gt() {
1933        let p = gen_predicate(29, Operator::Gt);
1934        assert_prune(
1935            100,
1936            p,
1937            vec![
1938                false, false, false, true, true, true, true, true, true, true,
1939            ],
1940        )
1941        .await;
1942    }
1943
1944    #[tokio::test]
1945    async fn test_prune_eq_expr() {
1946        let p = gen_predicate(30, Operator::Eq);
1947        assert_prune(40, p, vec![false, false, false, true]).await;
1948    }
1949
1950    #[tokio::test]
1951    async fn test_prune_neq_expr() {
1952        let p = gen_predicate(30, Operator::NotEq);
1953        assert_prune(40, p, vec![true, true, true, true]).await;
1954    }
1955
1956    #[tokio::test]
1957    async fn test_prune_gteq_expr() {
1958        let p = gen_predicate(29, Operator::GtEq);
1959        assert_prune(40, p, vec![false, false, true, true]).await;
1960    }
1961
1962    #[tokio::test]
1963    async fn test_prune_lt_expr() {
1964        let p = gen_predicate(30, Operator::Lt);
1965        assert_prune(40, p, vec![true, true, true, false]).await;
1966    }
1967
1968    #[tokio::test]
1969    async fn test_prune_lteq_expr() {
1970        let p = gen_predicate(30, Operator::LtEq);
1971        assert_prune(40, p, vec![true, true, true, true]).await;
1972    }
1973
1974    #[tokio::test]
1975    async fn test_prune_between_expr() {
1976        let p = gen_predicate(30, Operator::LtEq);
1977        assert_prune(40, p, vec![true, true, true, true]).await;
1978    }
1979
1980    #[tokio::test]
1981    async fn test_or() {
1982        // cnt > 30 or cnt < 20
1983        let e = datafusion_expr::Expr::Column(Column::from_name("cnt"))
1984            .gt(30.lit())
1985            .or(datafusion_expr::Expr::Column(Column::from_name("cnt")).lt(20.lit()));
1986        assert_prune(40, vec![e], vec![true, true, false, true]).await;
1987    }
1988
1989    #[tokio::test]
1990    async fn test_to_physical_expr() {
1991        let predicate = Predicate::new(vec![
1992            col("host").eq(lit("host_a")),
1993            col("ts").gt(lit(ScalarValue::TimestampMicrosecond(Some(123), None))),
1994        ]);
1995
1996        let schema = Arc::new(arrow::datatypes::Schema::new(vec![Field::new(
1997            "host",
1998            arrow::datatypes::DataType::Utf8,
1999            false,
2000        )]));
2001
2002        let predicates = predicate.to_pruning_physical_exprs(&schema).unwrap();
2003        assert!(!predicates.is_empty());
2004
2005        let physical_expr = Predicate::to_physical_expr(&col("host").eq(lit("host_a")), &schema);
2006        assert!(physical_expr.is_ok());
2007    }
2008
2009    fn regex_expr(column: &str, op: Operator, pattern: &str) -> Expr {
2010        Expr::BinaryExpr(BinaryExpr {
2011            left: Box::new(col(column)),
2012            op,
2013            right: Box::new(lit(pattern)),
2014        })
2015    }
2016
2017    /// The expression `create_physical_expr` builds on its own, i.e. the implementation before
2018    /// regex patterns were precompiled. It recompiles the pattern on every evaluation.
2019    fn arrow_regex_expr(expr: &Expr, schema: &Arc<Schema>) -> Arc<dyn PhysicalExpr> {
2020        let df_schema = schema.clone().to_dfschema_ref().unwrap();
2021        create_physical_expr(
2022            expr,
2023            df_schema.as_ref(),
2024            &ExecutionProps::new(),
2025            &PhysicalPlanningContext::default(),
2026        )
2027        .unwrap()
2028    }
2029
2030    fn regex_batch(
2031        data_type: DataType,
2032        array: ArrayRef,
2033        nullable: bool,
2034    ) -> (Arc<Schema>, RecordBatch) {
2035        let schema = Arc::new(Schema::new(vec![Field::new("host", data_type, nullable)]));
2036        let batch = RecordBatch::try_new(schema.clone(), vec![array]).unwrap();
2037        (schema, batch)
2038    }
2039
2040    /// Returns the value of `physical` per row, `None` standing for SQL `NULL`.
2041    fn evaluate_rows(physical: &Arc<dyn PhysicalExpr>, batch: &RecordBatch) -> Vec<Option<bool>> {
2042        let array = physical
2043            .evaluate(batch)
2044            .unwrap()
2045            .into_array(batch.num_rows())
2046            .unwrap();
2047        let array = array.as_any().downcast_ref::<BooleanArray>().unwrap();
2048        (0..array.len())
2049            .map(|index| array.is_valid(index).then(|| array.value(index)))
2050            .collect()
2051    }
2052
2053    /// Asserts both implementations agree row by row, as predicate values and as the filter mask a
2054    /// scan derives from them.
2055    fn assert_same_regex_result(expr: &Expr, schema: &Arc<Schema>, batch: &RecordBatch) {
2056        let arrow = arrow_regex_expr(expr, schema);
2057        let precompiled = Predicate::to_physical_expr(expr, schema).unwrap();
2058
2059        assert_eq!(
2060            evaluate_rows(&arrow, batch),
2061            evaluate_rows(&precompiled, batch),
2062            "values differ for {expr:?}"
2063        );
2064        assert_eq!(
2065            common_recordbatch::filter::batch_filter(batch, &arrow).unwrap(),
2066            common_recordbatch::filter::batch_filter(batch, &precompiled).unwrap(),
2067            "filtered rows differ for {expr:?}"
2068        );
2069    }
2070
2071    /// Differential test: the precompiled predicate must produce exactly what arrow's own regex
2072    /// kernel produces, for every string layout, with and without `NULL`s, for `=~` and `!~`.
2073    #[test]
2074    fn test_precompiled_regex_matches_arrow() {
2075        let plain_nulls = vec![
2076            Some("host-a"),
2077            None,
2078            Some(""),
2079            Some("db"),
2080            Some("日本語"),
2081            Some("HOST-B"),
2082        ];
2083        // A dictionary with a `NULL` key and a `NULL` dictionary value: both are SQL `NULL`, and
2084        // the dictionary value's `NULL` is what a naive kernel loses.
2085        let dict_values = Arc::new(StringArray::from(vec![
2086            Some("host-a"),
2087            Some("HOST-B"),
2088            Some(""),
2089            None,
2090            Some("日本語"),
2091        ])) as ArrayRef;
2092        let cases: Vec<(&str, DataType, ArrayRef, bool, bool)> = vec![
2093            (
2094                "utf8",
2095                DataType::Utf8,
2096                Arc::new(StringArray::from(vec!["host-a", "db", ""])) as ArrayRef,
2097                false,
2098                true,
2099            ),
2100            (
2101                "utf8 with nulls",
2102                DataType::Utf8,
2103                Arc::new(StringArray::from(plain_nulls.clone())) as ArrayRef,
2104                true,
2105                true,
2106            ),
2107            (
2108                "dictionary(UInt32, utf8) with nulls",
2109                DataType::Dictionary(Box::new(DataType::UInt32), Box::new(DataType::Utf8)),
2110                Arc::new(DictionaryArray::new(
2111                    UInt32Array::from(vec![Some(0), Some(1), Some(2), None, Some(3), Some(4)]),
2112                    dict_values.clone(),
2113                )) as ArrayRef,
2114                true,
2115                true,
2116            ),
2117            (
2118                "large utf8 with nulls",
2119                DataType::LargeUtf8,
2120                Arc::new(LargeStringArray::from(plain_nulls.clone())) as ArrayRef,
2121                true,
2122                false,
2123            ),
2124            (
2125                "utf8 view with nulls",
2126                DataType::Utf8View,
2127                Arc::new(StringViewArray::from(plain_nulls.clone())) as ArrayRef,
2128                true,
2129                false,
2130            ),
2131            (
2132                "dictionary(UInt8, utf8) with nulls",
2133                DataType::Dictionary(Box::new(DataType::UInt8), Box::new(DataType::Utf8)),
2134                Arc::new(DictionaryArray::new(
2135                    UInt8Array::from(vec![Some(0u8), Some(1), Some(2), None, Some(3), Some(4)]),
2136                    dict_values.clone(),
2137                )) as ArrayRef,
2138                true,
2139                false,
2140            ),
2141        ];
2142
2143        for (name, data_type, array, nullable, expect_precompiled) in cases {
2144            let (schema, batch) = regex_batch(data_type.clone(), array, nullable);
2145            for op in [Operator::RegexMatch, Operator::RegexNotMatch] {
2146                for pattern in [
2147                    "host.*", "^host-a$", "^(?:.*)$", "", "(?i)host", "日本", "^$",
2148                ] {
2149                    let expr = regex_expr("host", op, pattern);
2150                    let physical = Predicate::to_physical_expr(&expr, &schema).unwrap();
2151                    assert_eq!(
2152                        expect_precompiled,
2153                        physical.downcast_ref::<PrecompiledRegexExpr>().is_some(),
2154                        "{name}: {op:?} {pattern:?}"
2155                    );
2156                    assert_same_regex_result(&expr, &schema, &batch);
2157                    let slice = batch.slice(1, batch.num_rows() - 1);
2158                    assert_same_regex_result(&expr, &schema, &slice);
2159                }
2160            }
2161        }
2162
2163        // A cast decides the compared type: a dictionary column cast to `Utf8` is precompilable
2164        // even though the column itself is not `Utf8`.
2165        let (schema, batch) = regex_batch(
2166            DataType::Dictionary(Box::new(DataType::UInt32), Box::new(DataType::Utf8)),
2167            Arc::new(DictionaryArray::new(
2168                UInt32Array::from(vec![Some(0), Some(1), Some(2), None, Some(3), Some(4)]),
2169                dict_values.clone(),
2170            )) as ArrayRef,
2171            true,
2172        );
2173        let cast = Expr::Cast(datafusion_expr::expr::Cast {
2174            expr: Box::new(col("host")),
2175            field: Arc::new(Field::new("host", DataType::Utf8, true)),
2176        });
2177        let expr = Expr::BinaryExpr(BinaryExpr {
2178            left: Box::new(cast),
2179            op: Operator::RegexMatch,
2180            right: Box::new(lit("host.*")),
2181        });
2182        let physical = Predicate::to_physical_expr(&expr, &schema).unwrap();
2183        assert!(physical.downcast_ref::<PrecompiledRegexExpr>().is_some());
2184        assert_same_regex_result(&expr, &schema, &batch);
2185    }
2186
2187    /// Pruning never evaluates the predicate, so its entry point must keep the plain comparison
2188    /// instead of the evaluation-only [`PrecompiledRegexExpr`]: pruning runs once per file
2189    /// (manifest pruning) and once per batch (bulk memtable pruning), and a node the pruning
2190    /// predicate builder does not recognize would only be replaced by `true`.
2191    #[test]
2192    fn test_pruning_keeps_the_plain_regex_expr() {
2193        let (schema, _) = regex_batch(
2194            DataType::Utf8,
2195            Arc::new(StringArray::from(vec![Some("host-a"), None, Some("db")])) as ArrayRef,
2196            true,
2197        );
2198        let expr = regex_expr("host", Operator::RegexMatch, "host.*");
2199
2200        let pruning = Predicate::new(vec![expr.clone()])
2201            .to_pruning_physical_exprs(&schema)
2202            .unwrap();
2203        assert_eq!(1, pruning.len());
2204        let physical = &pruning[0];
2205        let mut rewritten = false;
2206        physical
2207            .apply(|node| {
2208                rewritten |= node.downcast_ref::<PrecompiledRegexExpr>().is_some();
2209                Ok(TreeNodeRecursion::Continue)
2210            })
2211            .unwrap();
2212        assert!(
2213            !rewritten,
2214            "pruning must not build the evaluation-only rewrite: {physical}"
2215        );
2216        // It is exactly what `create_physical_expr` plans, i.e. what pruning saw before the
2217        // rewrite existed.
2218        assert_eq!(
2219            arrow_regex_expr(&expr, &schema).to_string(),
2220            physical.to_string()
2221        );
2222
2223        // Evaluation keeps the rewrite.
2224        let evaluated = Predicate::to_physical_expr(&expr, &schema).unwrap();
2225        assert!(
2226            evaluated.downcast_ref::<PrecompiledRegexExpr>().is_some(),
2227            "evaluation must precompile the pattern: {evaluated}"
2228        );
2229    }
2230
2231    /// Pruning still applies the numeric conjunct of a predicate that also holds a regex, so
2232    /// keeping the plain comparison does not weaken pruning.
2233    #[tokio::test]
2234    async fn test_prune_with_regex_conjunct() {
2235        let e = regex_expr("name", Operator::RegexMatch, "^1.*").and(col("cnt").gt_eq(lit(10_i32)));
2236        assert_prune(40, vec![e], vec![false, true, true, true]).await;
2237    }
2238
2239    /// The precompiled pattern stays uninitialized until the first evaluation and is then reused.
2240    /// The per-regex compile counter is tested in common-recordbatch.
2241    #[test]
2242    #[allow(clippy::print_stdout)]
2243    fn test_precompiled_regex_defers_compilation_until_evaluation() {
2244        let (schema, batch) = regex_batch(
2245            DataType::Utf8,
2246            Arc::new(StringArray::from(vec![Some("host-a"), None, Some("db")])) as ArrayRef,
2247            true,
2248        );
2249        let expr = regex_expr("host", Operator::RegexMatch, "host.*");
2250        let physical = Predicate::to_physical_expr(&expr, &schema).unwrap();
2251        let regex = physical.downcast_ref::<PrecompiledRegexExpr>().unwrap();
2252        let initialized = || format!("{:?}", regex.filter);
2253        assert!(
2254            initialized().contains("initialized: false"),
2255            "{}",
2256            initialized()
2257        );
2258        println!("after to_physical_expr: regex initializations = 0");
2259
2260        assert_eq!(
2261            vec![Some(true), None, Some(false)],
2262            evaluate_rows(&physical, &batch)
2263        );
2264        assert!(
2265            initialized().contains("initialized: true"),
2266            "{}",
2267            initialized()
2268        );
2269        println!("after first evaluate: regex initialized = true");
2270        for _ in 0..100 {
2271            assert_eq!(
2272                vec![Some(true), None, Some(false)],
2273                evaluate_rows(&physical, &batch)
2274            );
2275        }
2276        assert!(
2277            initialized().contains("initialized: true"),
2278            "{}",
2279            initialized()
2280        );
2281        println!("after 100 further evaluations: same OnceLock remains initialized");
2282    }
2283
2284    /// A malformed regex must be deferred too, but row evaluation still reports an error instead
2285    /// of silently accepting the predicate as an exact match.
2286    #[test]
2287    #[allow(clippy::print_stdout)]
2288    fn test_invalid_regex_fails_at_evaluation_not_construction() {
2289        let (schema, batch) = regex_batch(
2290            DataType::Utf8,
2291            Arc::new(StringArray::from(vec![Some("host-a")])) as ArrayRef,
2292            true,
2293        );
2294        let expr = regex_expr("host", Operator::RegexMatch, "host(");
2295        // The old rewrite fell back to DataFusion on eager compilation failure. That physical
2296        // planner does not compile the pattern, so it too reports this error on evaluation.
2297        let old_fallback = arrow_regex_expr(&expr, &schema);
2298        assert!(old_fallback.evaluate(&batch).is_err());
2299        let physical = Predicate::to_physical_expr(&expr, &schema)
2300            .expect("construction must retain the invalid regex");
2301        let regex = physical.downcast_ref::<PrecompiledRegexExpr>().unwrap();
2302        assert!(format!("{:?}", regex.filter).contains("initialized: false"));
2303        let error = physical
2304            .evaluate(&batch)
2305            .expect_err("invalid regex must fail on evaluate, not construction");
2306        let DataFusionError::External(source) = &error else {
2307            panic!("expected a common-recordbatch error, got: {error}");
2308        };
2309        assert!(
2310            matches!(
2311                source.downcast_ref::<common_recordbatch::error::Error>(),
2312                Some(common_recordbatch::error::Error::ArrowCompute { .. })
2313            ),
2314            "expected ArrowCompute, got: {error}"
2315        );
2316        assert!(physical.evaluate(&batch).is_err());
2317        assert!(format!("{:?}", regex.filter).contains("initialized: true"));
2318        println!(
2319            "invalid regex: 0 initializations after to_physical_expr; first evaluate returned an error"
2320        );
2321    }
2322
2323    /// A scan can repeatedly evaluate the same regex expression without changing its results.
2324    #[test]
2325    fn test_regex_pattern_reused_across_batches() {
2326        let (schema, batch) = regex_batch(
2327            DataType::Utf8,
2328            Arc::new(StringArray::from(vec![
2329                Some("host-a"),
2330                None,
2331                Some(""),
2332                Some("db"),
2333                Some("host-b"),
2334            ])) as ArrayRef,
2335            true,
2336        );
2337        let expr = regex_expr("host", Operator::RegexMatch, "host.*");
2338
2339        let physical = Predicate::to_physical_expr(&expr, &schema).unwrap();
2340        assert!(
2341            physical.downcast_ref::<PrecompiledRegexExpr>().is_some(),
2342            "the scan-side predicate holds the lazy pattern: {physical}"
2343        );
2344        assert_eq!("host@0 =~ 'host.*'", physical.to_string());
2345
2346        for _ in 0..100 {
2347            assert_eq!(
2348                vec![Some(true), None, Some(false), Some(false), Some(true)],
2349                evaluate_rows(&physical, &batch)
2350            );
2351        }
2352    }
2353
2354    /// The predicate a native `rate(x{host=~'host.*'}[1m])` builds when the label column is
2355    /// nullable, as [`PromPlanner::matchers_to_expr`] plans it: `is_null(host) OR host =~ '...'`.
2356    ///
2357    /// `matchers_to_expr` lives in the query crate; this reproduces the expression it emits so the
2358    /// rewrite is covered for the shape the series scan actually sees. The logical plan is not
2359    /// touched by the precompiled path, and the rows are unchanged.
2360    #[test]
2361    fn test_nullable_label_matcher_keeps_shape_and_rows() {
2362        let (schema, batch) = regex_batch(
2363            DataType::Utf8,
2364            Arc::new(StringArray::from(vec![
2365                Some("host-a"),
2366                None,
2367                Some(""),
2368                Some("db"),
2369                Some("host-b"),
2370            ])) as ArrayRef,
2371            true,
2372        );
2373        let expr =
2374            col("host")
2375                .is_null()
2376                .or(regex_expr("host", Operator::RegexMatch, "^(?:host.*)$"));
2377
2378        let physical = Predicate::to_physical_expr(&expr, &schema).unwrap();
2379        // Shape: the `OR` survives, its null test is untouched, and only the comparison below it
2380        // is replaced by the precompiled form.
2381        let or = physical
2382            .downcast_ref::<PhysicalBinaryExpr>()
2383            .unwrap_or_else(|| panic!("the OR was rewritten into {physical}"));
2384        assert_eq!(&Operator::Or, or.op());
2385        assert!(
2386            or.left()
2387                .downcast_ref::<datafusion_physical_expr::expressions::IsNullExpr>()
2388                .is_some(),
2389            "the null test is unchanged: {}",
2390            or.left()
2391        );
2392        assert!(
2393            or.right().downcast_ref::<PrecompiledRegexExpr>().is_some(),
2394            "the regex below the OR is precompiled: {}",
2395            or.right()
2396        );
2397
2398        // The explicit OR makes a missing label match independently of the regex result.
2399        assert_eq!(
2400            vec![Some(true), Some(true), Some(false), Some(false), Some(true)],
2401            evaluate_rows(&physical, &batch)
2402        );
2403        assert_same_regex_result(&expr, &schema, &batch);
2404    }
2405
2406    /// A scan hands one physical expr to every thread that evaluates it, and the precompiled
2407    /// expression provides separate caches to concurrent searches. Sharing it must neither panic
2408    /// nor change an answer.
2409    #[test]
2410    fn test_precompiled_regex_is_shared_between_threads() {
2411        let (schema, batch) = regex_batch(
2412            DataType::Utf8,
2413            Arc::new(StringArray::from(vec![
2414                Some("host-a"),
2415                None,
2416                Some(""),
2417                Some("db"),
2418                Some("host-b"),
2419            ])) as ArrayRef,
2420            true,
2421        );
2422        let expr = regex_expr("host", Operator::RegexMatch, "host.*");
2423        let physical = Predicate::to_physical_expr(&expr, &schema).unwrap();
2424        assert!(physical.downcast_ref::<PrecompiledRegexExpr>().is_some());
2425        let expected = vec![Some(true), None, Some(false), Some(false), Some(true)];
2426        assert_eq!(expected, evaluate_rows(&physical, &batch));
2427
2428        std::thread::scope(|scope| {
2429            for _ in 0..8 {
2430                let physical = Arc::clone(&physical);
2431                let batch = batch.clone();
2432                let expected = expected.clone();
2433                scope.spawn(move || {
2434                    for _ in 0..50 {
2435                        assert_eq!(expected, evaluate_rows(&physical, &batch));
2436                    }
2437                });
2438            }
2439        });
2440
2441        // The concurrent evaluations neither compiled nor changed the expression.
2442        assert_eq!(expected, evaluate_rows(&physical, &batch));
2443    }
2444}