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                strictly_after(ts, ts_col_unit)
635            } else {
636                // ts_col < [lit]
637                ts.convert_to_ceil(ts_col_unit)
638                    .map(|ts| TimestampRange::until_end(ts, false))
639            }
640        }
641        Operator::LtEq => {
642            let (ts, reverse) = get_timestamp_filter(ts_col_name, left, right)?;
643            if reverse {
644                // [lit] <= ts_col
645                ts.convert_to_ceil(ts_col_unit)
646                    .map(TimestampRange::from_start)
647            } else {
648                // ts_col <= [lit]
649                ts.convert_to(ts_col_unit)
650                    .map(|ts| TimestampRange::until_end(ts, true))
651            }
652        }
653        Operator::Gt => {
654            let (ts, reverse) = get_timestamp_filter(ts_col_name, left, right)?;
655            if reverse {
656                // [lit] > ts_col
657                ts.convert_to_ceil(ts_col_unit)
658                    .map(|t| TimestampRange::until_end(t, false))
659            } else {
660                // ts_col > [lit]
661                strictly_after(ts, ts_col_unit)
662            }
663        }
664        Operator::GtEq => {
665            let (ts, reverse) = get_timestamp_filter(ts_col_name, left, right)?;
666            if reverse {
667                // [lit] >= ts_col
668                ts.convert_to(ts_col_unit)
669                    .map(|t| TimestampRange::until_end(t, true))
670            } else {
671                // ts_col >= [lit]
672                ts.convert_to_ceil(ts_col_unit)
673                    .map(TimestampRange::from_start)
674            }
675        }
676        Operator::And => {
677            // instead of return none when failed to extract time range from left/right, we unwrap the none into
678            // `TimestampRange::min_to_max`.
679            let left = extract_time_range(ts_col_name, ts_col_unit, left, date_bin)
680                .unwrap_or_else(TimestampRange::min_to_max);
681            let right = extract_time_range(ts_col_name, ts_col_unit, right, date_bin)
682                .unwrap_or_else(TimestampRange::min_to_max);
683            Some(left.and(&right))
684        }
685        Operator::Or => {
686            let left = extract_time_range(ts_col_name, ts_col_unit, left, date_bin)?;
687            let right = extract_time_range(ts_col_name, ts_col_unit, right, date_bin)?;
688            Some(left.or(&right))
689        }
690        _ => None,
691    }
692}
693
694/// Returns the stride of `date_bin(stride, ts_col[, origin])`, converted to `unit`
695/// and rounded up, if `expr` is that call with a literal, fixed-width stride.
696///
697/// `date_bin` floors a timestamp to the start of its bucket, so for every row
698/// `bucket_start <= ts < bucket_start + stride`, whatever the origin. That lets a
699/// filter on the bucket start bound the time index itself, which is what a
700/// filter on a view's `date_bin(...) AS time` column becomes once it is pushed
701/// below the view's aggregate.
702///
703/// This holds in nanoseconds. DataFusion computes the bucket start in
704/// nanoseconds and truncates it to the column unit, so on a coarser column the
705/// returned value can be up to one unit below the true start; see
706/// [`date_bin_range`].
707fn date_bin_stride(ts_col_name: &str, unit: TimeUnit, expr: &Expr) -> Option<i64> {
708    let Expr::ScalarFunction(ScalarFunction { func, args }) = expr else {
709        return None;
710    };
711    if func.name() != "date_bin" || !(2..=3).contains(&args.len()) {
712        return None;
713    }
714    let Expr::Column(col) = &args[1] else {
715        return None;
716    };
717    if col.name != ts_col_name {
718        return None;
719    }
720    let stride_ns: i128 = match &args[0] {
721        // Months have no fixed width.
722        Expr::Literal(ScalarValue::IntervalMonthDayNano(Some(v)), _) if v.months == 0 => {
723            v.days as i128 * 86_400_000_000_000 + v.nanoseconds as i128
724        }
725        Expr::Literal(ScalarValue::IntervalDayTime(Some(v)), _) => {
726            v.days as i128 * 86_400_000_000_000 + v.milliseconds as i128 * 1_000_000
727        }
728        _ => return None,
729    };
730    if stride_ns <= 0 {
731        return None;
732    }
733    let ns_per_unit = match unit {
734        TimeUnit::Second => 1_000_000_000,
735        TimeUnit::Millisecond => 1_000_000,
736        TimeUnit::Microsecond => 1_000,
737        TimeUnit::Nanosecond => 1,
738    };
739    i64::try_from((stride_ns + ns_per_unit - 1) / ns_per_unit).ok()
740}
741
742/// Extracts a time range from `date_bin(stride, ts_col) <op> literal`. The range
743/// over-approximates the rows that satisfy the comparison (see [`date_bin_stride`]).
744fn extract_from_date_bin_comparison(
745    ts_col_name: &str,
746    ts_col_unit: TimeUnit,
747    left: &Expr,
748    op: &Operator,
749    right: &Expr,
750) -> Option<TimestampRange> {
751    // Normalize to `date_bin(...) <op> literal`.
752    let (bin, op, lit) = match (left, right) {
753        (bin, Expr::Literal(lit, _)) => (bin, *op, lit),
754        (Expr::Literal(lit, _), bin) => (bin, op.swap()?, lit),
755        _ => return None,
756    };
757    let stride = date_bin_stride(ts_col_name, ts_col_unit, bin)?;
758    return_none_if_utf8!(lit);
759    let bound = scalar_value_to_timestamp(lit, None)?;
760    date_bin_range(op, &bound, stride, ts_col_unit)
761}
762
763/// The range of `ts` for which `date_bin(stride, ts) <op> bound` can hold.
764fn date_bin_range(
765    op: Operator,
766    bound: &Timestamp,
767    stride: i64,
768    unit: TimeUnit,
769) -> Option<TimestampRange> {
770    // `bin >= bound` and `bin > bound` imply `ts >= bound`, because `ts >= bin`.
771    let lower = || bound.convert_to_ceil(unit).map(TimestampRange::from_start);
772    // `bin <= bound` and `bin < bound` imply `ts < bound + stride`, because `ts < bin + stride`.
773    // On a column coarser than nanoseconds, the returned `bin` is truncated from the true
774    // bucket start and can be up to one unit below it, so widen the end by one unit.
775    let slack = if unit == TimeUnit::Nanosecond { 0 } else { 1 };
776    let upper = || {
777        let end = bound
778            .convert_to_ceil(unit)?
779            .value()
780            .checked_add(stride)?
781            .checked_add(slack)?;
782        Some(TimestampRange::until_end(Timestamp::new(end, unit), false))
783    };
784    match op {
785        Operator::Gt | Operator::GtEq => lower(),
786        Operator::Lt | Operator::LtEq => upper(),
787        Operator::Eq => Some(lower()?.and(&upper()?)),
788        _ => None,
789    }
790}
791
792/// Returns the timestamps after `ts` in `unit`. The range is empty when `ts`
793/// is the largest representable timestamp, rather than wrapping around.
794fn strictly_after(ts: Timestamp, unit: TimeUnit) -> Option<TimestampRange> {
795    let ts_val = ts.convert_to(unit)?.value();
796    Some(match ts_val.checked_add(1) {
797        Some(next) => TimestampRange::from_start(Timestamp::new(next, unit)),
798        None => TimestampRange::empty(),
799    })
800}
801
802fn get_timestamp_filter(ts_col_name: &str, left: &Expr, right: &Expr) -> Option<(Timestamp, bool)> {
803    let (col, lit, reverse) = match (left, right) {
804        (Expr::Column(column), Expr::Literal(scalar, _)) => (column, scalar, false),
805        (Expr::Literal(scalar, _), Expr::Column(column)) => (column, scalar, true),
806        _ => {
807            return None;
808        }
809    };
810    if col.name != ts_col_name {
811        return None;
812    }
813
814    return_none_if_utf8!(lit);
815    scalar_value_to_timestamp(lit, None).map(|t| (t, reverse))
816}
817
818fn extract_from_between_expr(
819    ts_col_name: &str,
820    ts_col_unit: TimeUnit,
821    expr: &Expr,
822    negated: &bool,
823    low: &Expr,
824    high: &Expr,
825    date_bin: DateBinFilters,
826) -> Option<TimestampRange> {
827    if *negated {
828        return None;
829    }
830
831    if date_bin == DateBinFilters::Derive
832        && let Some(stride) = date_bin_stride(ts_col_name, ts_col_unit, expr)
833    {
834        // `low <= date_bin(...) <= high`
835        let (Expr::Literal(low, _), Expr::Literal(high, _)) = (low, high) else {
836            return None;
837        };
838        return_none_if_utf8!(low);
839        return_none_if_utf8!(high);
840        let low = date_bin_range(
841            Operator::GtEq,
842            &scalar_value_to_timestamp(low, None)?,
843            stride,
844            ts_col_unit,
845        );
846        let high = date_bin_range(
847            Operator::LtEq,
848            &scalar_value_to_timestamp(high, None)?,
849            stride,
850            ts_col_unit,
851        );
852        return Some(
853            low.unwrap_or_else(TimestampRange::min_to_max)
854                .and(&high.unwrap_or_else(TimestampRange::min_to_max)),
855        );
856    }
857
858    let Expr::Column(col) = expr else {
859        return None;
860    };
861    if col.name != ts_col_name {
862        return None;
863    }
864
865    match (low, high) {
866        (Expr::Literal(low, _), Expr::Literal(high, _)) => {
867            return_none_if_utf8!(low);
868            return_none_if_utf8!(high);
869
870            let low_opt =
871                scalar_value_to_timestamp(low, None).and_then(|ts| ts.convert_to(ts_col_unit));
872            let high_opt = scalar_value_to_timestamp(high, None)
873                .and_then(|ts| ts.convert_to_ceil(ts_col_unit));
874            Some(TimestampRange::new_inclusive(low_opt, high_opt))
875        }
876        _ => None,
877    }
878}
879
880/// Extract time range filter from `IN (...)` expr.
881fn extract_from_in_list_expr(
882    ts_col_name: &str,
883    expr: &Expr,
884    negated: bool,
885    list: &[Expr],
886) -> Option<TimestampRange> {
887    if negated {
888        return None;
889    }
890    let Expr::Column(col) = expr else {
891        return None;
892    };
893    if col.name != ts_col_name {
894        return None;
895    }
896
897    if list.is_empty() {
898        return Some(TimestampRange::empty());
899    }
900    // A list with any non-literal item (e.g. `ts IN (1, 2, 3, 4, other_ts)`) makes the
901    // literal-only envelope unsound: the non-literal item may match any timestamp, so a
902    // range built from the literals alone can be narrower than the filter's satisfying set
903    // and the scan would prune rows that satisfy the predicate. `InList` survives above
904    // DataFusion's inline threshold, so abandon the whole `IN` instead of narrowing.
905    if !list.iter().all(|expr| matches!(expr, Expr::Literal(_, _))) {
906        return None;
907    }
908    let mut init_range = TimestampRange::empty();
909    for expr in list {
910        if let Expr::Literal(scalar, _) = expr {
911            return_none_if_utf8!(scalar);
912            // TODO(hl): maybe we should raise an error here since cannot parse
913            // timestamp value from in list expr
914            let timestamp = scalar_value_to_timestamp(scalar, None)?;
915            init_range = init_range.or(&TimestampRange::single(timestamp));
916        }
917    }
918    Some(init_range)
919}
920
921#[cfg(test)]
922mod tests {
923    use std::sync::Arc;
924
925    use common_test_util::temp_dir::{TempDir, create_temp_dir};
926    use datafusion::parquet::arrow::ArrowWriter;
927    use datafusion_common::tree_node::TreeNodeRecursion;
928    use datafusion_common::{Column, ScalarValue};
929    use datafusion_expr::{BinaryExpr, Literal, Operator, col, lit};
930    use datatypes::arrow::array::{
931        ArrayRef, DictionaryArray, Int32Array, LargeStringArray, StringViewArray, UInt8Array,
932        UInt32Array,
933    };
934    use datatypes::arrow::datatypes::{DataType, Field, Schema};
935    use datatypes::arrow::record_batch::RecordBatch;
936    use datatypes::arrow_array::StringArray;
937    use parquet::arrow::ParquetRecordBatchStreamBuilder;
938    use parquet::file::properties::WriterProperties;
939
940    use super::*;
941    use crate::predicate::stats::RowGroupPruningStatistics;
942
943    fn check_build_predicate(expr: Expr, expect: TimestampRange) {
944        assert_eq!(
945            expect,
946            build_time_range_predicate("ts", TimeUnit::Millisecond, &[expr])
947        );
948    }
949
950    fn date_bin(stride: Expr) -> Expr {
951        datafusion::functions::datetime::date_bin().call(vec![stride, col("ts")])
952    }
953
954    fn ms(v: i64) -> Expr {
955        lit(ScalarValue::TimestampMillisecond(Some(v), None))
956    }
957
958    fn minute() -> Expr {
959        lit(ScalarValue::new_interval_mdn(0, 0, 60_000_000_000))
960    }
961
962    #[test]
963    fn test_date_bin() {
964        // Upper bounds on a coarser-than-ns column are widened by one unit, because
965        // `date_bin` truncates its nanosecond bucket start to the column unit.
966        let t = Timestamp::new_millisecond;
967        // date_bin(1m, ts) >= 120_000ms  =>  ts >= 120_000ms
968        check_build_predicate(
969            date_bin(minute()).gt_eq(ms(120_000)),
970            TimestampRange::from_start(t(120_000)),
971        );
972        // date_bin(1m, ts) > 120_000ms  =>  ts > 120_000ms, widened to ts >= 120_000ms
973        check_build_predicate(
974            date_bin(minute()).gt(ms(120_000)),
975            TimestampRange::from_start(t(120_000)),
976        );
977        // date_bin(1m, ts) < 120_000ms  =>  ts < 180_001ms
978        check_build_predicate(
979            date_bin(minute()).lt(ms(120_000)),
980            TimestampRange::until_end(t(180_001), false),
981        );
982        // date_bin(1m, ts) <= 120_000ms  =>  ts < 180_001ms
983        check_build_predicate(
984            date_bin(minute()).lt_eq(ms(120_000)),
985            TimestampRange::until_end(t(180_001), false),
986        );
987        // 120_000ms <= date_bin(1m, ts)  =>  ts >= 120_000ms
988        check_build_predicate(
989            ms(120_000).lt_eq(date_bin(minute())),
990            TimestampRange::from_start(t(120_000)),
991        );
992        // date_bin(1m, ts) = 120_000ms  =>  120_000ms <= ts < 180_001ms
993        check_build_predicate(
994            date_bin(minute()).eq(ms(120_000)),
995            TimestampRange::new(t(120_000), t(180_001)).unwrap(),
996        );
997        // date_bin(1m, ts) BETWEEN 60_000ms AND 120_000ms  =>  60_000ms <= ts < 180_001ms
998        check_build_predicate(
999            date_bin(minute()).between(ms(60_000), ms(120_000)),
1000            TimestampRange::new(t(60_000), t(180_001)).unwrap(),
1001        );
1002        // Combined with other conjuncts.
1003        check_build_predicate(
1004            date_bin(minute())
1005                .gt_eq(ms(60_000))
1006                .and(date_bin(minute()).lt(ms(120_000)))
1007                .and(col("v").gt(lit(1))),
1008            TimestampRange::new(t(60_000), t(180_001)).unwrap(),
1009        );
1010        // An origin argument doesn't change the bounds.
1011        check_build_predicate(
1012            datafusion::functions::datetime::date_bin()
1013                .call(vec![minute(), col("ts"), ms(17)])
1014                .gt_eq(ms(120_000)),
1015            TimestampRange::from_start(t(120_000)),
1016        );
1017        // A month stride has no fixed width: no range for the upper bound.
1018        check_build_predicate(
1019            date_bin(lit(ScalarValue::new_interval_mdn(1, 0, 0))).lt(ms(120_000)),
1020            TimestampRange::min_to_max(),
1021        );
1022        // Other columns are ignored.
1023        check_build_predicate(
1024            datafusion::functions::datetime::date_bin()
1025                .call(vec![minute(), col("other")])
1026                .gt_eq(ms(120_000)),
1027            TimestampRange::min_to_max(),
1028        );
1029        // An upper bound that overflows leaves the range unbounded.
1030        check_build_predicate(
1031            date_bin(minute()).lt_eq(ms(i64::MAX - 1)),
1032            TimestampRange::min_to_max(),
1033        );
1034    }
1035
1036    /// Evaluates `date_bin` with DataFusion over a grid of timestamps, then checks
1037    /// that every row satisfying a comparison on its result lies in the extracted
1038    /// range. Covers coarse column units, strides and origins that are not a whole
1039    /// number of column units, and negative timestamps.
1040    #[tokio::test]
1041    async fn test_date_bin_range_keeps_satisfying_rows() {
1042        /// Whether the comparison holds for a `date_bin` result.
1043        type BinHolds = Box<dyn Fn(i64) -> bool>;
1044
1045        use datafusion::prelude::SessionContext;
1046        use datafusion_expr::cast;
1047        use datatypes::arrow::array::{AsArray, Int64Array};
1048        use datatypes::arrow::datatypes::{Int64Type, TimeUnit as ArrowTimeUnit};
1049
1050        let units = [
1051            (TimeUnit::Second, ArrowTimeUnit::Second, 1_000_000_000i64),
1052            (TimeUnit::Millisecond, ArrowTimeUnit::Millisecond, 1_000_000),
1053            (TimeUnit::Microsecond, ArrowTimeUnit::Microsecond, 1_000),
1054        ];
1055        let ctx = SessionContext::new();
1056
1057        for (unit, arrow_unit, ns_per_unit) in units {
1058            let ts_lit = |v: i64| {
1059                lit(match unit {
1060                    TimeUnit::Second => ScalarValue::TimestampSecond(Some(v), None),
1061                    TimeUnit::Millisecond => ScalarValue::TimestampMillisecond(Some(v), None),
1062                    TimeUnit::Microsecond => ScalarValue::TimestampMicrosecond(Some(v), None),
1063                    TimeUnit::Nanosecond => ScalarValue::TimestampNanosecond(Some(v), None),
1064                })
1065            };
1066            let ts_type = DataType::Timestamp(arrow_unit, None);
1067            let ts_array = datatypes::arrow::compute::cast(
1068                &Int64Array::from((-30..=30).collect::<Vec<i64>>()),
1069                &ts_type,
1070            )
1071            .unwrap();
1072            let schema = Arc::new(Schema::new(vec![Field::new("ts", ts_type, false)]));
1073            let batch = RecordBatch::try_new(schema, vec![ts_array]).unwrap();
1074
1075            let strides_ns = [
1076                ns_per_unit,
1077                ns_per_unit * 3,
1078                ns_per_unit / 2,
1079                ns_per_unit * 13 / 10,
1080                ns_per_unit * 26 / 10,
1081            ];
1082            let origins_ns = [
1083                None,
1084                Some(0),
1085                Some(ns_per_unit / 2),
1086                Some(-ns_per_unit * 7 / 3),
1087            ];
1088            for stride_ns in strides_ns {
1089                for origin_ns in origins_ns {
1090                    let mut args = vec![
1091                        lit(ScalarValue::new_interval_mdn(0, 0, stride_ns)),
1092                        col("ts"),
1093                    ];
1094                    if let Some(origin) = origin_ns {
1095                        args.push(lit(ScalarValue::TimestampNanosecond(Some(origin), None)));
1096                    }
1097                    let bin = datafusion::functions::datetime::date_bin().call(args);
1098
1099                    // (ts, date_bin(ts)), both in the column unit.
1100                    let rows: Vec<(i64, i64)> = ctx
1101                        .read_batch(batch.clone())
1102                        .unwrap()
1103                        .select(vec![
1104                            cast(col("ts"), DataType::Int64),
1105                            cast(bin.clone(), DataType::Int64),
1106                        ])
1107                        .unwrap()
1108                        .collect()
1109                        .await
1110                        .unwrap()
1111                        .iter()
1112                        .flat_map(|b| {
1113                            let ts = b.column(0).as_primitive::<Int64Type>();
1114                            let bins = b.column(1).as_primitive::<Int64Type>();
1115                            ts.values()
1116                                .iter()
1117                                .copied()
1118                                .zip(bins.values().iter().copied())
1119                                .collect::<Vec<_>>()
1120                        })
1121                        .collect();
1122                    assert_eq!(rows.len(), 61);
1123
1124                    for c in -35..=35 {
1125                        let cases: Vec<(Expr, BinHolds)> = vec![
1126                            (bin.clone().eq(ts_lit(c)), Box::new(move |b| b == c)),
1127                            (bin.clone().lt(ts_lit(c)), Box::new(move |b| b < c)),
1128                            (bin.clone().lt_eq(ts_lit(c)), Box::new(move |b| b <= c)),
1129                            (bin.clone().gt(ts_lit(c)), Box::new(move |b| b > c)),
1130                            (bin.clone().gt_eq(ts_lit(c)), Box::new(move |b| b >= c)),
1131                            (ts_lit(c).gt_eq(bin.clone()), Box::new(move |b| c >= b)),
1132                            (
1133                                bin.clone().between(ts_lit(c), ts_lit(c + 2)),
1134                                Box::new(move |b| c <= b && b <= c + 2),
1135                            ),
1136                        ];
1137                        for (expr, holds) in cases {
1138                            let range =
1139                                build_time_range_predicate("ts", unit, std::slice::from_ref(&expr));
1140                            for &(ts, b) in &rows {
1141                                assert!(
1142                                    !holds(b) || range.contains(&Timestamp::new(ts, unit)),
1143                                    "{expr} holds for ts={ts} (bin={b}, {unit:?}, stride={stride_ns}ns, origin={origin_ns:?}ns) but {range:?} excludes it",
1144                                );
1145                            }
1146                        }
1147                    }
1148                }
1149            }
1150        }
1151    }
1152
1153    #[test]
1154    fn test_gt() {
1155        // ts > 1ms
1156        check_build_predicate(
1157            col("ts").gt(lit(ScalarValue::TimestampMillisecond(Some(1), None))),
1158            TimestampRange::from_start(Timestamp::new_millisecond(2)),
1159        );
1160
1161        // 1ms > ts
1162        check_build_predicate(
1163            lit(ScalarValue::TimestampMillisecond(Some(1), None)).gt(col("ts")),
1164            TimestampRange::until_end(Timestamp::new_millisecond(1), false),
1165        );
1166
1167        // 1001us > ts
1168        check_build_predicate(
1169            lit(ScalarValue::TimestampMicrosecond(Some(1001), None)).gt(col("ts")),
1170            TimestampRange::until_end(Timestamp::new_millisecond(1), true),
1171        );
1172
1173        // ts > 1001us
1174        check_build_predicate(
1175            col("ts").gt(lit(ScalarValue::TimestampMicrosecond(Some(1001), None))),
1176            TimestampRange::from_start(Timestamp::new_millisecond(2)),
1177        );
1178
1179        // 1s > ts
1180        check_build_predicate(
1181            lit(ScalarValue::TimestampSecond(Some(1), None)).gt(col("ts")),
1182            TimestampRange::until_end(Timestamp::new_millisecond(1000), false),
1183        );
1184
1185        // ts > 1s
1186        check_build_predicate(
1187            col("ts").gt(lit(ScalarValue::TimestampSecond(Some(1), None))),
1188            TimestampRange::from_start(Timestamp::new_millisecond(1001)),
1189        );
1190
1191        // No timestamp is after the maximum, in either operand order. The
1192        // successor must not wrap around to the minimum.
1193        let max = || lit(ScalarValue::TimestampMillisecond(Some(i64::MAX), None));
1194        for expr in [col("ts").gt(max()), max().lt(col("ts"))] {
1195            let range = build_time_range_predicate("ts", TimeUnit::Millisecond, &[expr]);
1196            assert!(range.is_empty(), "{range:?}");
1197        }
1198        for (literal, successor) in [
1199            (
1200                ScalarValue::TimestampMillisecond(Some(i64::MIN), None),
1201                i64::MIN + 1,
1202            ),
1203            (ScalarValue::TimestampMicrosecond(Some(-1001), None), -1),
1204            (ScalarValue::TimestampMicrosecond(Some(-1), None), 0),
1205            (ScalarValue::TimestampSecond(Some(0), None), 1),
1206        ] {
1207            let literal = lit(literal);
1208            for expr in [col("ts").gt(literal.clone()), literal.lt(col("ts"))] {
1209                check_build_predicate(
1210                    expr,
1211                    TimestampRange::from_start(Timestamp::new_millisecond(successor)),
1212                );
1213            }
1214        }
1215    }
1216
1217    #[test]
1218    fn test_gt_eq() {
1219        // ts >= 1ms
1220        check_build_predicate(
1221            col("ts").gt_eq(lit(ScalarValue::TimestampMillisecond(Some(1), None))),
1222            TimestampRange::from_start(Timestamp::new_millisecond(1)),
1223        );
1224
1225        // 1ms >= ts
1226        check_build_predicate(
1227            lit(ScalarValue::TimestampMillisecond(Some(1), None)).gt_eq(col("ts")),
1228            TimestampRange::until_end(Timestamp::new_millisecond(1), true),
1229        );
1230
1231        // 1001us >= ts
1232        check_build_predicate(
1233            lit(ScalarValue::TimestampMicrosecond(Some(1001), None)).gt_eq(col("ts")),
1234            TimestampRange::until_end(Timestamp::new_millisecond(1), true),
1235        );
1236
1237        // ts >= 1001us
1238        check_build_predicate(
1239            col("ts").gt_eq(lit(ScalarValue::TimestampMicrosecond(Some(1001), None))),
1240            TimestampRange::from_start(Timestamp::new_millisecond(2)),
1241        );
1242
1243        // 1s >= ts
1244        check_build_predicate(
1245            lit(ScalarValue::TimestampSecond(Some(1), None)).gt_eq(col("ts")),
1246            TimestampRange::until_end(Timestamp::new_millisecond(1000), true),
1247        );
1248
1249        // ts >= 1s
1250        check_build_predicate(
1251            col("ts").gt_eq(lit(ScalarValue::TimestampSecond(Some(1), None))),
1252            TimestampRange::from_start(Timestamp::new_millisecond(1000)),
1253        );
1254    }
1255
1256    #[test]
1257    fn test_lt() {
1258        // ts < 1ms
1259        check_build_predicate(
1260            col("ts").lt(lit(ScalarValue::TimestampMillisecond(Some(1), None))),
1261            TimestampRange::until_end(Timestamp::new_millisecond(1), false),
1262        );
1263
1264        // 1ms < ts
1265        check_build_predicate(
1266            lit(ScalarValue::TimestampMillisecond(Some(1), None)).lt(col("ts")),
1267            TimestampRange::from_start(Timestamp::new_millisecond(2)),
1268        );
1269
1270        // 1001us < ts
1271        check_build_predicate(
1272            lit(ScalarValue::TimestampMicrosecond(Some(1001), None)).lt(col("ts")),
1273            TimestampRange::from_start(Timestamp::new_millisecond(2)),
1274        );
1275
1276        // ts < 1001us
1277        check_build_predicate(
1278            col("ts").lt(lit(ScalarValue::TimestampMicrosecond(Some(1001), None))),
1279            TimestampRange::until_end(Timestamp::new_millisecond(1), true),
1280        );
1281
1282        // 1s < ts
1283        check_build_predicate(
1284            lit(ScalarValue::TimestampSecond(Some(1), None)).lt(col("ts")),
1285            TimestampRange::from_start(Timestamp::new_millisecond(1001)),
1286        );
1287
1288        // ts < 1s
1289        check_build_predicate(
1290            col("ts").lt(lit(ScalarValue::TimestampSecond(Some(1), None))),
1291            TimestampRange::until_end(Timestamp::new_millisecond(1000), false),
1292        );
1293    }
1294
1295    #[test]
1296    fn test_lt_eq() {
1297        // ts <= 1ms
1298        check_build_predicate(
1299            col("ts").lt_eq(lit(ScalarValue::TimestampMillisecond(Some(1), None))),
1300            TimestampRange::until_end(Timestamp::new_millisecond(1), true),
1301        );
1302
1303        // 1ms <= ts
1304        check_build_predicate(
1305            lit(ScalarValue::TimestampMillisecond(Some(1), None)).lt_eq(col("ts")),
1306            TimestampRange::from_start(Timestamp::new_millisecond(1)),
1307        );
1308
1309        // 1001us <= ts
1310        check_build_predicate(
1311            lit(ScalarValue::TimestampMicrosecond(Some(1001), None)).lt_eq(col("ts")),
1312            TimestampRange::from_start(Timestamp::new_millisecond(2)),
1313        );
1314
1315        // ts <= 1001us
1316        check_build_predicate(
1317            col("ts").lt_eq(lit(ScalarValue::TimestampMicrosecond(Some(1001), None))),
1318            TimestampRange::until_end(Timestamp::new_millisecond(1), true),
1319        );
1320
1321        // 1s <= ts
1322        check_build_predicate(
1323            lit(ScalarValue::TimestampSecond(Some(1), None)).lt_eq(col("ts")),
1324            TimestampRange::from_start(Timestamp::new_millisecond(1000)),
1325        );
1326
1327        // ts <= 1s
1328        check_build_predicate(
1329            col("ts").lt_eq(lit(ScalarValue::TimestampSecond(Some(1), None))),
1330            TimestampRange::until_end(Timestamp::new_millisecond(1000), true),
1331        );
1332    }
1333
1334    #[test]
1335    fn test_in_list_with_non_literal_item_is_not_extracted() {
1336        // `ts IN (10ms, v)`: the non-literal item can match any timestamp, so the whole
1337        // list must be abandoned instead of being narrowed to the literal's range.
1338        check_build_predicate(
1339            col("ts").in_list(
1340                vec![
1341                    lit(ScalarValue::TimestampMillisecond(Some(10), None)),
1342                    col("v"),
1343                ],
1344                false,
1345            ),
1346            TimestampRange::min_to_max(),
1347        );
1348
1349        // A lone non-literal item is just as unsound.
1350        check_build_predicate(
1351            col("ts").in_list(vec![col("v")], false),
1352            TimestampRange::min_to_max(),
1353        );
1354
1355        // All-literal lists still extract the envelope covering every listed value.
1356        check_build_predicate(
1357            col("ts").in_list(
1358                vec![
1359                    lit(ScalarValue::TimestampMillisecond(Some(10), None)),
1360                    lit(ScalarValue::TimestampMillisecond(Some(20), None)),
1361                ],
1362                false,
1363            ),
1364            TimestampRange::new(
1365                Timestamp::new_millisecond(10),
1366                Timestamp::new_millisecond(21),
1367            )
1368            .unwrap(),
1369        );
1370    }
1371
1372    #[test]
1373    fn test_extract_time_range_strict() {
1374        fn ts_lit(ms: i64) -> Expr {
1375            lit(ScalarValue::TimestampMillisecond(Some(ms), None))
1376        }
1377        let extract =
1378            |filters: &[Expr]| extract_time_range_strict("ts", TimeUnit::Millisecond, filters);
1379        let range = |start: i64, end: i64| {
1380            TimestampRange::new(
1381                Timestamp::new_millisecond(start),
1382                Timestamp::new_millisecond(end),
1383            )
1384            .unwrap()
1385        };
1386
1387        // No filter references the column.
1388        assert_eq!(extract(&[]), TimeRangeExtraction::Absent);
1389        assert_eq!(
1390            extract(&[col("host").eq(lit("a"))]),
1391            TimeRangeExtraction::Absent
1392        );
1393
1394        // Both bounds across conjuncts; unrelated filters are ignored.
1395        assert_eq!(
1396            extract(&[
1397                col("ts").gt_eq(ts_lit(1000)),
1398                col("ts").lt(ts_lit(2000)),
1399                col("host").eq(lit("a")),
1400            ]),
1401            TimeRangeExtraction::Extracted(range(1000, 2000))
1402        );
1403
1404        // Lower bound only / upper bound only.
1405        assert_eq!(
1406            extract(&[col("ts").gt_eq(ts_lit(1000))]),
1407            TimeRangeExtraction::Extracted(TimestampRange::from_start(Timestamp::new_millisecond(
1408                1000
1409            )))
1410        );
1411        assert_eq!(
1412            extract(&[col("ts").lt(ts_lit(2000))]),
1413            TimeRangeExtraction::Extracted(TimestampRange::until_end(
1414                Timestamp::new_millisecond(2000),
1415                false
1416            ))
1417        );
1418
1419        // BETWEEN is inclusive on both ends.
1420        assert_eq!(
1421            extract(&[col("ts").between(ts_lit(1000), ts_lit(2000))]),
1422            TimeRangeExtraction::Extracted(range(1000, 2001))
1423        );
1424
1425        // Equality pins a single point.
1426        assert_eq!(
1427            extract(&[col("ts").eq(ts_lit(1500))]),
1428            TimeRangeExtraction::Extracted(TimestampRange::single(Timestamp::new_millisecond(
1429                1500
1430            )))
1431        );
1432
1433        // An unparsable side under AND only widens; the extraction stays safe.
1434        assert_eq!(
1435            extract(&[col("ts").gt_eq(ts_lit(1000)).and(col("ts").lt(col("t2")))]),
1436            TimeRangeExtraction::Extracted(TimestampRange::from_start(Timestamp::new_millisecond(
1437                1000
1438            )))
1439        );
1440
1441        // Contradictory bounds collapse to the empty range, not an error.
1442        let TimeRangeExtraction::Extracted(empty) =
1443            extract(&[col("ts").gt_eq(ts_lit(2000)), col("ts").lt(ts_lit(1000))])
1444        else {
1445            panic!("expected an extraction");
1446        };
1447        assert!(empty.is_empty());
1448
1449        // Shapes that could widen the satisfying set beyond what is extractable
1450        // must be refused: OR with an unparsable side, NOT, non-literal bounds.
1451        assert_eq!(
1452            extract(&[col("ts").gt(ts_lit(1000)).or(col("host").eq(lit("a")))]),
1453            TimeRangeExtraction::Unsupported
1454        );
1455        assert_eq!(
1456            extract(&[!col("ts").gt(ts_lit(1000))]),
1457            TimeRangeExtraction::Unsupported
1458        );
1459        assert_eq!(
1460            extract(&[col("ts").gt_eq(col("t2"))]),
1461            TimeRangeExtraction::Unsupported
1462        );
1463
1464        // A range derived from `date_bin` over-approximates by up to a bucket, so a
1465        // timestamp synthesized from its bounds may fail the filter: refuse it.
1466        assert_eq!(
1467            extract(&[date_bin(minute()).gt(ts_lit(60_000))]),
1468            TimeRangeExtraction::Unsupported
1469        );
1470        assert_eq!(
1471            extract(&[date_bin(minute()).between(ts_lit(0), ts_lit(60_000))]),
1472            TimeRangeExtraction::Unsupported
1473        );
1474        // Under AND it is dropped like any other unparsable side.
1475        assert_eq!(
1476            extract(&[col("ts")
1477                .lt(ts_lit(2000))
1478                .and(date_bin(minute()).gt_eq(ts_lit(60_000)))]),
1479            TimeRangeExtraction::Extracted(TimestampRange::until_end(
1480                Timestamp::new_millisecond(2000),
1481                false
1482            ))
1483        );
1484    }
1485
1486    async fn gen_test_parquet_file(dir: &TempDir, cnt: usize) -> (String, Arc<Schema>) {
1487        let path = dir
1488            .path()
1489            .join("test-prune.parquet")
1490            .to_string_lossy()
1491            .to_string();
1492
1493        let name_field = Field::new("name", DataType::Utf8, true);
1494        let count_field = Field::new("cnt", DataType::Int32, true);
1495        let schema = Arc::new(Schema::new(vec![name_field, count_field]));
1496
1497        let file = std::fs::OpenOptions::new()
1498            .write(true)
1499            .create(true)
1500            .truncate(true)
1501            .open(path.clone())
1502            .unwrap();
1503
1504        let write_props = WriterProperties::builder()
1505            .set_max_row_group_row_count(Some(10))
1506            .build();
1507        let mut writer = ArrowWriter::try_new(file, schema.clone(), Some(write_props)).unwrap();
1508
1509        for i in (0..cnt).step_by(10) {
1510            let name_array = Arc::new(StringArray::from(
1511                (i..(i + 10).min(cnt))
1512                    .map(|i| i.to_string())
1513                    .collect::<Vec<_>>(),
1514            )) as Arc<_>;
1515            let count_array = Arc::new(Int32Array::from(
1516                (i..(i + 10).min(cnt)).map(|i| i as i32).collect::<Vec<_>>(),
1517            )) as Arc<_>;
1518            let rb = RecordBatch::try_new(schema.clone(), vec![name_array, count_array]).unwrap();
1519            writer.write(&rb).unwrap();
1520        }
1521        let _ = writer.close().unwrap();
1522        (path, schema)
1523    }
1524
1525    async fn assert_prune(array_cnt: usize, filters: Vec<Expr>, expect: Vec<bool>) {
1526        let dir = create_temp_dir("prune_parquet");
1527        let (path, arrow_schema) = gen_test_parquet_file(&dir, array_cnt).await;
1528        let schema = Arc::new(datatypes::schema::Schema::try_from(arrow_schema.clone()).unwrap());
1529        let arrow_predicate = Predicate::new(filters);
1530        let builder = ParquetRecordBatchStreamBuilder::new(
1531            tokio::fs::OpenOptions::new()
1532                .read(true)
1533                .open(path)
1534                .await
1535                .unwrap(),
1536        )
1537        .await
1538        .unwrap();
1539        let metadata = builder.metadata().clone();
1540        let row_groups = metadata.row_groups();
1541
1542        let stats = RowGroupPruningStatistics::new(row_groups, &schema);
1543        let res = arrow_predicate.prune_with_stats(&stats, &arrow_schema);
1544        assert_eq!(expect, res);
1545    }
1546
1547    #[test]
1548    fn test_clear_dyn_filters_preserves_static_predicates() {
1549        use datafusion_physical_expr::expressions::lit as physical_lit;
1550
1551        let static_exprs = vec![col("a").eq(lit(1_i32))];
1552        let dynamic_filter = Arc::new(DynamicFilterPhysicalExpr::new(vec![], physical_lit(true)));
1553        let predicate =
1554            Predicate::with_dyn_filters(static_exprs.clone(), vec![dynamic_filter.clone()]);
1555
1556        predicate.clear_dyn_filters();
1557        // An update from the old producer must not put its wrapper back into this execution.
1558        dynamic_filter.update(physical_lit(false)).unwrap();
1559
1560        assert_eq!(predicate.exprs(), static_exprs);
1561        assert!(predicate.dyn_filters().is_empty());
1562        assert!(predicate.dyn_filter_phy_exprs().unwrap().is_empty());
1563    }
1564
1565    #[tokio::test]
1566    async fn test_dynamic_topk_pruning_nullable_lexicographic_keys() {
1567        use std::cmp::Ordering;
1568
1569        use datafusion::datasource::memory::MemorySourceConfig;
1570        use datafusion::execution::context::TaskContext;
1571        use datafusion::physical_plan::sorts::sort::SortExec;
1572        use datafusion::physical_plan::{ExecutionPlan, collect};
1573        use datafusion_physical_expr::PhysicalSortExpr;
1574        use datafusion_physical_expr::expressions::Column as PhysicalColumn;
1575        use datatypes::arrow::compute::SortOptions;
1576
1577        type Row = (Option<i32>, Option<i32>);
1578
1579        fn compare(left: Option<i32>, right: Option<i32>, options: SortOptions) -> Ordering {
1580            match (left, right) {
1581                (None, None) => Ordering::Equal,
1582                (None, Some(_)) => {
1583                    if options.nulls_first {
1584                        Ordering::Less
1585                    } else {
1586                        Ordering::Greater
1587                    }
1588                }
1589                (Some(_), None) => {
1590                    if options.nulls_first {
1591                        Ordering::Greater
1592                    } else {
1593                        Ordering::Less
1594                    }
1595                }
1596                (Some(left), Some(right)) => {
1597                    let ordering = left.cmp(&right);
1598                    if options.descending {
1599                        ordering.reverse()
1600                    } else {
1601                        ordering
1602                    }
1603                }
1604            }
1605        }
1606
1607        let groups: [[Row; 2]; 6] = [
1608            [(Some(11), None), (Some(12), Some(1))],
1609            [(Some(10), Some(4)), (Some(10), Some(5))],
1610            [(Some(9), None), (Some(10), Some(6))],
1611            [(None, Some(1)), (None, Some(2))],
1612            [(Some(10), None), (Some(10), Some(1))],
1613            [(Some(10), Some(5)), (Some(10), Some(5))],
1614        ];
1615        let dir = create_temp_dir("dynamic_topk_pruning");
1616        let path = dir.path().join("nullable.parquet");
1617        let arrow_schema = Arc::new(Schema::new(vec![
1618            Field::new("a", DataType::Int32, true),
1619            Field::new("b", DataType::Int32, true),
1620        ]));
1621        let batch = |rows: &[Row]| {
1622            RecordBatch::try_new(
1623                arrow_schema.clone(),
1624                vec![
1625                    Arc::new(Int32Array::from(
1626                        rows.iter().map(|r| r.0).collect::<Vec<_>>(),
1627                    )),
1628                    Arc::new(Int32Array::from(
1629                        rows.iter().map(|r| r.1).collect::<Vec<_>>(),
1630                    )),
1631                ],
1632            )
1633            .unwrap()
1634        };
1635        let mut writer = ArrowWriter::try_new(
1636            std::fs::File::create(&path).unwrap(),
1637            arrow_schema.clone(),
1638            None,
1639        )
1640        .unwrap();
1641        for group in &groups {
1642            writer.write(&batch(group)).unwrap();
1643            writer.flush().unwrap();
1644        }
1645        writer.close().unwrap();
1646        let builder =
1647            ParquetRecordBatchStreamBuilder::new(tokio::fs::File::open(path).await.unwrap())
1648                .await
1649                .unwrap();
1650        let schema = Arc::new(datatypes::schema::Schema::try_from(arrow_schema.clone()).unwrap());
1651        let stats = RowGroupPruningStatistics::new(builder.metadata().row_groups(), &schema);
1652
1653        for (options, boundary, expected, must_prune_first) in [
1654            (
1655                SortOptions {
1656                    descending: false,
1657                    nulls_first: false,
1658                },
1659                (Some(10), Some(5)),
1660                [(Some(9), None), (Some(10), Some(1))],
1661                true,
1662            ),
1663            (
1664                SortOptions {
1665                    descending: false,
1666                    nulls_first: true,
1667                },
1668                (Some(10), Some(5)),
1669                [(None, Some(1)), (None, Some(2))],
1670                false,
1671            ),
1672            (
1673                SortOptions {
1674                    descending: true,
1675                    nulls_first: false,
1676                },
1677                (Some(10), Some(5)),
1678                [(Some(12), Some(1)), (Some(11), None)],
1679                false,
1680            ),
1681            (
1682                SortOptions {
1683                    descending: false,
1684                    nulls_first: true,
1685                },
1686                (None, Some(5)),
1687                [(None, Some(1)), (None, Some(2))],
1688                false,
1689            ),
1690            (
1691                SortOptions {
1692                    descending: false,
1693                    nulls_first: false,
1694                },
1695                (None, Some(5)),
1696                [(Some(9), None), (Some(10), Some(1))],
1697                false,
1698            ),
1699            (
1700                SortOptions {
1701                    descending: false,
1702                    nulls_first: false,
1703                },
1704                (Some(10), None),
1705                [(Some(9), None), (Some(10), Some(1))],
1706                true,
1707            ),
1708        ] {
1709            // Let the real SortExec/TopK producer publish its boundary predicate.
1710            // Two boundary rows also make dropping later full-key ties safe.
1711            let seed = [boundary, boundary];
1712            let input =
1713                MemorySourceConfig::try_new_exec(&[vec![batch(&seed)]], arrow_schema.clone(), None)
1714                    .unwrap();
1715            let ordering = [
1716                PhysicalSortExpr {
1717                    expr: Arc::new(PhysicalColumn::new("a", 0)),
1718                    options,
1719                },
1720                PhysicalSortExpr {
1721                    expr: Arc::new(PhysicalColumn::new("b", 1)),
1722                    options,
1723                },
1724            ];
1725            let sort = SortExec::new(ordering.into(), input).with_fetch(Some(2));
1726            let filter = sort
1727                .dynamic_expressions_produced()
1728                .into_iter()
1729                .next()
1730                .unwrap();
1731            let filter = (filter as Arc<dyn std::any::Any + Send + Sync>)
1732                .downcast::<DynamicFilterPhysicalExpr>()
1733                .unwrap();
1734            collect(Arc::new(sort), Arc::new(TaskContext::default()))
1735                .await
1736                .unwrap();
1737            let predicate = Predicate::with_dyn_filters(vec![], vec![filter]);
1738            let keep = predicate.prune_with_stats(&stats, &arrow_schema);
1739            if must_prune_first {
1740                assert!(
1741                    !keep[0],
1742                    "disjoint first row group must be pruned: {options:?}, {boundary:?}"
1743                );
1744            }
1745            if boundary == (Some(10), Some(5)) && !options.nulls_first && !options.descending {
1746                assert!(
1747                    !keep[5],
1748                    "duplicate full-key ties may be pruned after the heap is full"
1749                );
1750            }
1751
1752            let top_two = |mut rows: Vec<Row>| {
1753                rows.sort_by(|left, right| {
1754                    compare(left.0, right.0, options)
1755                        .then_with(|| compare(left.1, right.1, options))
1756                });
1757                rows.truncate(2);
1758                rows
1759            };
1760            let all = seed
1761                .into_iter()
1762                .chain(groups.into_iter().flatten())
1763                .collect();
1764            let retained = seed
1765                .into_iter()
1766                .chain(
1767                    groups
1768                        .into_iter()
1769                        .zip(keep)
1770                        .filter(|(_, keep)| *keep)
1771                        .flat_map(|(rows, _)| rows),
1772                )
1773                .collect();
1774            assert_eq!(
1775                top_two(all),
1776                expected,
1777                "explicit sort oracle: {options:?}, {boundary:?}"
1778            );
1779            assert_eq!(
1780                top_two(retained),
1781                expected,
1782                "pruned result: {options:?}, {boundary:?}"
1783            );
1784            // Seed duplicates must remain available when every candidate ties
1785            // the full boundary, even if all tied SST rows are pruned.
1786            assert_eq!(top_two(seed.to_vec()), vec![boundary, boundary]);
1787        }
1788    }
1789
1790    #[tokio::test]
1791    async fn test_dynamic_aggregate_unknown_to_known_pruning() {
1792        use std::sync::Mutex;
1793
1794        use datafusion::execution::context::TaskContext;
1795        use datafusion::functions_aggregate::min_max::min_udaf;
1796        use datafusion::physical_expr::aggregate::AggregateExprBuilder;
1797        use datafusion::physical_plan::aggregates::{
1798            AggregateExec, AggregateMode, PhysicalGroupBy,
1799        };
1800        use datafusion::physical_plan::common::collect;
1801        use datafusion::physical_plan::stream::RecordBatchStreamAdapter;
1802        use datafusion::physical_plan::streaming::{PartitionStream, StreamingTableExec};
1803        use datafusion::physical_plan::{ExecutionPlan, SendableRecordBatchStream};
1804        use datafusion_physical_expr::expressions::col as physical_col;
1805        use datatypes::arrow::array::Int64Array;
1806        use futures::{StreamExt, channel::mpsc};
1807
1808        #[derive(Debug)]
1809        struct TestInput {
1810            schema: Arc<Schema>,
1811            receiver:
1812                Mutex<Option<mpsc::UnboundedReceiver<datafusion_common::Result<RecordBatch>>>>,
1813        }
1814        impl PartitionStream for TestInput {
1815            fn schema(&self) -> &Arc<Schema> {
1816                &self.schema
1817            }
1818
1819            fn execute(&self, _: Arc<TaskContext>) -> SendableRecordBatchStream {
1820                let stream = self.receiver.lock().unwrap().take().unwrap();
1821                Box::pin(RecordBatchStreamAdapter::new(self.schema.clone(), stream))
1822            }
1823        }
1824
1825        let arrow_schema = Arc::new(Schema::new(vec![
1826            Field::new("a", DataType::Int64, true),
1827            Field::new("b", DataType::Int64, true),
1828        ]));
1829        let dir = create_temp_dir("dynamic_aggregate_pruning");
1830        let path = dir.path().join("nullable.parquet");
1831        let make_batch = |a: Vec<Option<i64>>, b: Vec<Option<i64>>| {
1832            RecordBatch::try_new(
1833                arrow_schema.clone(),
1834                vec![Arc::new(Int64Array::from(a)), Arc::new(Int64Array::from(b))],
1835            )
1836            .unwrap()
1837        };
1838        let mut writer = ArrowWriter::try_new(
1839            std::fs::File::create(&path).unwrap(),
1840            arrow_schema.clone(),
1841            None,
1842        )
1843        .unwrap();
1844        for batch in [
1845            make_batch(vec![Some(101)], vec![Some(5)]),
1846            make_batch(vec![Some(101)], vec![Some(1)]),
1847        ] {
1848            writer.write(&batch).unwrap();
1849            writer.flush().unwrap();
1850        }
1851        writer.close().unwrap();
1852        let builder =
1853            ParquetRecordBatchStreamBuilder::new(tokio::fs::File::open(path).await.unwrap())
1854                .await
1855                .unwrap();
1856        let schema = Arc::new(datatypes::schema::Schema::try_from(arrow_schema.clone()).unwrap());
1857        let stats = RowGroupPruningStatistics::new(builder.metadata().row_groups(), &schema);
1858        let (sender, receiver) = mpsc::unbounded();
1859        let input = Arc::new(
1860            StreamingTableExec::try_new(
1861                arrow_schema.clone(),
1862                vec![Arc::new(TestInput {
1863                    schema: arrow_schema.clone(),
1864                    receiver: Mutex::new(Some(receiver)),
1865                })],
1866                None,
1867                [],
1868                false,
1869                None,
1870            )
1871            .unwrap(),
1872        );
1873        let aggregates = ["a", "b"]
1874            .into_iter()
1875            .map(|name| {
1876                Arc::new(
1877                    AggregateExprBuilder::new(
1878                        min_udaf(),
1879                        vec![physical_col(name, &arrow_schema).unwrap()],
1880                    )
1881                    .schema(arrow_schema.clone())
1882                    .alias(name)
1883                    .build()
1884                    .unwrap(),
1885                )
1886            })
1887            .collect();
1888        let aggregate = Arc::new(
1889            AggregateExec::try_new(
1890                AggregateMode::Partial,
1891                PhysicalGroupBy::default(),
1892                aggregates,
1893                vec![None; 2],
1894                input,
1895                arrow_schema.clone(),
1896            )
1897            .unwrap(),
1898        );
1899        let expr = aggregate.dynamic_expressions_produced().pop().unwrap();
1900        let dynamic_filter = (expr as Arc<dyn std::any::Any + Send + Sync>)
1901            .downcast::<DynamicFilterPhysicalExpr>()
1902            .unwrap();
1903        let predicate = Predicate::with_dyn_filters(vec![], vec![dynamic_filter]);
1904        let mut stream = aggregate
1905            .execute(0, Arc::new(TaskContext::default()))
1906            .unwrap();
1907
1908        sender
1909            .unbounded_send(Ok(make_batch(vec![Some(100)], vec![None])))
1910            .unwrap();
1911        // Poll until the input channel becomes pending, after processing this batch.
1912        assert!(futures::poll!(stream.next()).is_pending());
1913        assert_eq!(
1914            predicate.prune_with_stats(&stats, &arrow_schema),
1915            vec![true, true],
1916            "unknown min(b) must keep a possible first non-NULL value"
1917        );
1918        sender
1919            .unbounded_send(Ok(make_batch(vec![Some(99)], vec![Some(2)])))
1920            .unwrap();
1921        assert!(futures::poll!(stream.next()).is_pending());
1922        assert_eq!(
1923            predicate.prune_with_stats(&stats, &arrow_schema),
1924            vec![false, true],
1925            "known bounds prune only the non-improving group"
1926        );
1927        sender
1928            .unbounded_send(Ok(make_batch(vec![Some(101)], vec![Some(1)])))
1929            .unwrap();
1930        drop(sender);
1931        let results = collect(stream).await.unwrap();
1932        assert_eq!(results.len(), 1);
1933        assert_eq!(
1934            ScalarValue::try_from_array(results[0].column(0), 0).unwrap(),
1935            ScalarValue::Int64(Some(99))
1936        );
1937        assert_eq!(
1938            ScalarValue::try_from_array(results[0].column(1), 0).unwrap(),
1939            ScalarValue::Int64(Some(1))
1940        );
1941    }
1942
1943    #[tokio::test]
1944    async fn test_clear_dyn_filters_restores_static_row_group_pruning() {
1945        use datafusion_physical_expr::expressions::{
1946            Column as PhysicalColumn, lit as physical_lit,
1947        };
1948
1949        let dir = create_temp_dir("dynamic_pruning_reset");
1950        let (path, arrow_schema) = gen_test_parquet_file(&dir, 30).await;
1951        let schema = Arc::new(datatypes::schema::Schema::try_from(arrow_schema.clone()).unwrap());
1952        let builder =
1953            ParquetRecordBatchStreamBuilder::new(tokio::fs::File::open(path).await.unwrap())
1954                .await
1955                .unwrap();
1956        let stats = RowGroupPruningStatistics::new(builder.metadata().row_groups(), &schema);
1957        let dynamic_filter = Arc::new(DynamicFilterPhysicalExpr::new(
1958            vec![Arc::new(PhysicalColumn::new("cnt", 1))],
1959            physical_lit(true),
1960        ));
1961        let predicate = Predicate::with_dyn_filters(
1962            vec![col("cnt").gt_eq(lit(10_i32))],
1963            vec![dynamic_filter.clone()],
1964        );
1965
1966        dynamic_filter
1967            .update(
1968                Predicate::to_physical_expr(&col("cnt").gt(lit(100_i32)), &arrow_schema).unwrap(),
1969            )
1970            .unwrap();
1971        assert_eq!(
1972            predicate.prune_with_stats(&stats, &arrow_schema),
1973            vec![false; 3]
1974        );
1975
1976        // Reset after the prior stream is dropped: no dynamic filter remains, while the
1977        // static predicate still excludes only the first row group.
1978        predicate.clear_dyn_filters();
1979        assert_eq!(
1980            predicate.prune_with_stats(&stats, &arrow_schema),
1981            vec![false, true, true]
1982        );
1983    }
1984
1985    fn gen_predicate(max_val: i32, op: Operator) -> Vec<Expr> {
1986        vec![datafusion_expr::Expr::BinaryExpr(BinaryExpr {
1987            left: Box::new(datafusion_expr::Expr::Column(Column::from_name("cnt"))),
1988            op,
1989            right: Box::new(max_val.lit()),
1990        })]
1991    }
1992
1993    #[tokio::test]
1994    async fn test_prune_empty() {
1995        assert_prune(3, vec![], vec![true]).await;
1996    }
1997
1998    #[tokio::test]
1999    async fn test_prune_all_match() {
2000        let p = gen_predicate(3, Operator::Gt);
2001        assert_prune(2, p, vec![false]).await;
2002    }
2003
2004    #[tokio::test]
2005    async fn test_prune_gt() {
2006        let p = gen_predicate(29, Operator::Gt);
2007        assert_prune(
2008            100,
2009            p,
2010            vec![
2011                false, false, false, true, true, true, true, true, true, true,
2012            ],
2013        )
2014        .await;
2015    }
2016
2017    #[tokio::test]
2018    async fn test_prune_eq_expr() {
2019        let p = gen_predicate(30, Operator::Eq);
2020        assert_prune(40, p, vec![false, false, false, true]).await;
2021    }
2022
2023    #[tokio::test]
2024    async fn test_prune_neq_expr() {
2025        let p = gen_predicate(30, Operator::NotEq);
2026        assert_prune(40, p, vec![true, true, true, true]).await;
2027    }
2028
2029    #[tokio::test]
2030    async fn test_prune_gteq_expr() {
2031        let p = gen_predicate(29, Operator::GtEq);
2032        assert_prune(40, p, vec![false, false, true, true]).await;
2033    }
2034
2035    #[tokio::test]
2036    async fn test_prune_lt_expr() {
2037        let p = gen_predicate(30, Operator::Lt);
2038        assert_prune(40, p, vec![true, true, true, false]).await;
2039    }
2040
2041    #[tokio::test]
2042    async fn test_prune_lteq_expr() {
2043        let p = gen_predicate(30, Operator::LtEq);
2044        assert_prune(40, p, vec![true, true, true, true]).await;
2045    }
2046
2047    #[tokio::test]
2048    async fn test_prune_between_expr() {
2049        let p = gen_predicate(30, Operator::LtEq);
2050        assert_prune(40, p, vec![true, true, true, true]).await;
2051    }
2052
2053    #[tokio::test]
2054    async fn test_or() {
2055        // cnt > 30 or cnt < 20
2056        let e = datafusion_expr::Expr::Column(Column::from_name("cnt"))
2057            .gt(30.lit())
2058            .or(datafusion_expr::Expr::Column(Column::from_name("cnt")).lt(20.lit()));
2059        assert_prune(40, vec![e], vec![true, true, false, true]).await;
2060    }
2061
2062    #[tokio::test]
2063    async fn test_to_physical_expr() {
2064        let predicate = Predicate::new(vec![
2065            col("host").eq(lit("host_a")),
2066            col("ts").gt(lit(ScalarValue::TimestampMicrosecond(Some(123), None))),
2067        ]);
2068
2069        let schema = Arc::new(arrow::datatypes::Schema::new(vec![Field::new(
2070            "host",
2071            arrow::datatypes::DataType::Utf8,
2072            false,
2073        )]));
2074
2075        let predicates = predicate.to_pruning_physical_exprs(&schema).unwrap();
2076        assert!(!predicates.is_empty());
2077
2078        let physical_expr = Predicate::to_physical_expr(&col("host").eq(lit("host_a")), &schema);
2079        assert!(physical_expr.is_ok());
2080    }
2081
2082    fn regex_expr(column: &str, op: Operator, pattern: &str) -> Expr {
2083        Expr::BinaryExpr(BinaryExpr {
2084            left: Box::new(col(column)),
2085            op,
2086            right: Box::new(lit(pattern)),
2087        })
2088    }
2089
2090    /// The expression `create_physical_expr` builds on its own, i.e. the implementation before
2091    /// regex patterns were precompiled. It recompiles the pattern on every evaluation.
2092    fn arrow_regex_expr(expr: &Expr, schema: &Arc<Schema>) -> Arc<dyn PhysicalExpr> {
2093        let df_schema = schema.clone().to_dfschema_ref().unwrap();
2094        create_physical_expr(
2095            expr,
2096            df_schema.as_ref(),
2097            &ExecutionProps::new(),
2098            &PhysicalPlanningContext::default(),
2099        )
2100        .unwrap()
2101    }
2102
2103    fn regex_batch(
2104        data_type: DataType,
2105        array: ArrayRef,
2106        nullable: bool,
2107    ) -> (Arc<Schema>, RecordBatch) {
2108        let schema = Arc::new(Schema::new(vec![Field::new("host", data_type, nullable)]));
2109        let batch = RecordBatch::try_new(schema.clone(), vec![array]).unwrap();
2110        (schema, batch)
2111    }
2112
2113    /// Returns the value of `physical` per row, `None` standing for SQL `NULL`.
2114    fn evaluate_rows(physical: &Arc<dyn PhysicalExpr>, batch: &RecordBatch) -> Vec<Option<bool>> {
2115        let array = physical
2116            .evaluate(batch)
2117            .unwrap()
2118            .into_array(batch.num_rows())
2119            .unwrap();
2120        let array = array.as_any().downcast_ref::<BooleanArray>().unwrap();
2121        (0..array.len())
2122            .map(|index| array.is_valid(index).then(|| array.value(index)))
2123            .collect()
2124    }
2125
2126    /// Asserts both implementations agree row by row, as predicate values and as the filter mask a
2127    /// scan derives from them.
2128    fn assert_same_regex_result(expr: &Expr, schema: &Arc<Schema>, batch: &RecordBatch) {
2129        let arrow = arrow_regex_expr(expr, schema);
2130        let precompiled = Predicate::to_physical_expr(expr, schema).unwrap();
2131
2132        assert_eq!(
2133            evaluate_rows(&arrow, batch),
2134            evaluate_rows(&precompiled, batch),
2135            "values differ for {expr:?}"
2136        );
2137        assert_eq!(
2138            common_recordbatch::filter::batch_filter(batch, &arrow).unwrap(),
2139            common_recordbatch::filter::batch_filter(batch, &precompiled).unwrap(),
2140            "filtered rows differ for {expr:?}"
2141        );
2142    }
2143
2144    /// Differential test: the precompiled predicate must produce exactly what arrow's own regex
2145    /// kernel produces, for every string layout, with and without `NULL`s, for `=~` and `!~`.
2146    #[test]
2147    fn test_precompiled_regex_matches_arrow() {
2148        let plain_nulls = vec![
2149            Some("host-a"),
2150            None,
2151            Some(""),
2152            Some("db"),
2153            Some("日本語"),
2154            Some("HOST-B"),
2155        ];
2156        // A dictionary with a `NULL` key and a `NULL` dictionary value: both are SQL `NULL`, and
2157        // the dictionary value's `NULL` is what a naive kernel loses.
2158        let dict_values = Arc::new(StringArray::from(vec![
2159            Some("host-a"),
2160            Some("HOST-B"),
2161            Some(""),
2162            None,
2163            Some("日本語"),
2164        ])) as ArrayRef;
2165        let cases: Vec<(&str, DataType, ArrayRef, bool, bool)> = vec![
2166            (
2167                "utf8",
2168                DataType::Utf8,
2169                Arc::new(StringArray::from(vec!["host-a", "db", ""])) as ArrayRef,
2170                false,
2171                true,
2172            ),
2173            (
2174                "utf8 with nulls",
2175                DataType::Utf8,
2176                Arc::new(StringArray::from(plain_nulls.clone())) as ArrayRef,
2177                true,
2178                true,
2179            ),
2180            (
2181                "dictionary(UInt32, utf8) with nulls",
2182                DataType::Dictionary(Box::new(DataType::UInt32), Box::new(DataType::Utf8)),
2183                Arc::new(DictionaryArray::new(
2184                    UInt32Array::from(vec![Some(0), Some(1), Some(2), None, Some(3), Some(4)]),
2185                    dict_values.clone(),
2186                )) as ArrayRef,
2187                true,
2188                true,
2189            ),
2190            (
2191                "large utf8 with nulls",
2192                DataType::LargeUtf8,
2193                Arc::new(LargeStringArray::from(plain_nulls.clone())) as ArrayRef,
2194                true,
2195                false,
2196            ),
2197            (
2198                "utf8 view with nulls",
2199                DataType::Utf8View,
2200                Arc::new(StringViewArray::from(plain_nulls.clone())) as ArrayRef,
2201                true,
2202                false,
2203            ),
2204            (
2205                "dictionary(UInt8, utf8) with nulls",
2206                DataType::Dictionary(Box::new(DataType::UInt8), Box::new(DataType::Utf8)),
2207                Arc::new(DictionaryArray::new(
2208                    UInt8Array::from(vec![Some(0u8), Some(1), Some(2), None, Some(3), Some(4)]),
2209                    dict_values.clone(),
2210                )) as ArrayRef,
2211                true,
2212                false,
2213            ),
2214        ];
2215
2216        for (name, data_type, array, nullable, expect_precompiled) in cases {
2217            let (schema, batch) = regex_batch(data_type.clone(), array, nullable);
2218            for op in [Operator::RegexMatch, Operator::RegexNotMatch] {
2219                for pattern in [
2220                    "host.*", "^host-a$", "^(?:.*)$", "", "(?i)host", "日本", "^$",
2221                ] {
2222                    let expr = regex_expr("host", op, pattern);
2223                    let physical = Predicate::to_physical_expr(&expr, &schema).unwrap();
2224                    assert_eq!(
2225                        expect_precompiled,
2226                        physical.downcast_ref::<PrecompiledRegexExpr>().is_some(),
2227                        "{name}: {op:?} {pattern:?}"
2228                    );
2229                    assert_same_regex_result(&expr, &schema, &batch);
2230                    let slice = batch.slice(1, batch.num_rows() - 1);
2231                    assert_same_regex_result(&expr, &schema, &slice);
2232                }
2233            }
2234        }
2235
2236        // A cast decides the compared type: a dictionary column cast to `Utf8` is precompilable
2237        // even though the column itself is not `Utf8`.
2238        let (schema, batch) = regex_batch(
2239            DataType::Dictionary(Box::new(DataType::UInt32), Box::new(DataType::Utf8)),
2240            Arc::new(DictionaryArray::new(
2241                UInt32Array::from(vec![Some(0), Some(1), Some(2), None, Some(3), Some(4)]),
2242                dict_values.clone(),
2243            )) as ArrayRef,
2244            true,
2245        );
2246        let cast = Expr::Cast(datafusion_expr::expr::Cast {
2247            expr: Box::new(col("host")),
2248            field: Arc::new(Field::new("host", DataType::Utf8, true)),
2249        });
2250        let expr = Expr::BinaryExpr(BinaryExpr {
2251            left: Box::new(cast),
2252            op: Operator::RegexMatch,
2253            right: Box::new(lit("host.*")),
2254        });
2255        let physical = Predicate::to_physical_expr(&expr, &schema).unwrap();
2256        assert!(physical.downcast_ref::<PrecompiledRegexExpr>().is_some());
2257        assert_same_regex_result(&expr, &schema, &batch);
2258    }
2259
2260    /// Pruning never evaluates the predicate, so its entry point must keep the plain comparison
2261    /// instead of the evaluation-only [`PrecompiledRegexExpr`]: pruning runs once per file
2262    /// (manifest pruning) and once per batch (bulk memtable pruning), and a node the pruning
2263    /// predicate builder does not recognize would only be replaced by `true`.
2264    #[test]
2265    fn test_pruning_keeps_the_plain_regex_expr() {
2266        let (schema, _) = regex_batch(
2267            DataType::Utf8,
2268            Arc::new(StringArray::from(vec![Some("host-a"), None, Some("db")])) as ArrayRef,
2269            true,
2270        );
2271        let expr = regex_expr("host", Operator::RegexMatch, "host.*");
2272
2273        let pruning = Predicate::new(vec![expr.clone()])
2274            .to_pruning_physical_exprs(&schema)
2275            .unwrap();
2276        assert_eq!(1, pruning.len());
2277        let physical = &pruning[0];
2278        let mut rewritten = false;
2279        physical
2280            .apply(|node| {
2281                rewritten |= node.downcast_ref::<PrecompiledRegexExpr>().is_some();
2282                Ok(TreeNodeRecursion::Continue)
2283            })
2284            .unwrap();
2285        assert!(
2286            !rewritten,
2287            "pruning must not build the evaluation-only rewrite: {physical}"
2288        );
2289        // It is exactly what `create_physical_expr` plans, i.e. what pruning saw before the
2290        // rewrite existed.
2291        assert_eq!(
2292            arrow_regex_expr(&expr, &schema).to_string(),
2293            physical.to_string()
2294        );
2295
2296        // Evaluation keeps the rewrite.
2297        let evaluated = Predicate::to_physical_expr(&expr, &schema).unwrap();
2298        assert!(
2299            evaluated.downcast_ref::<PrecompiledRegexExpr>().is_some(),
2300            "evaluation must precompile the pattern: {evaluated}"
2301        );
2302    }
2303
2304    /// Pruning still applies the numeric conjunct of a predicate that also holds a regex, so
2305    /// keeping the plain comparison does not weaken pruning.
2306    #[tokio::test]
2307    async fn test_prune_with_regex_conjunct() {
2308        let e = regex_expr("name", Operator::RegexMatch, "^1.*").and(col("cnt").gt_eq(lit(10_i32)));
2309        assert_prune(40, vec![e], vec![false, true, true, true]).await;
2310    }
2311
2312    /// The precompiled pattern stays uninitialized until the first evaluation and is then reused.
2313    /// The per-regex compile counter is tested in common-recordbatch.
2314    #[test]
2315    #[allow(clippy::print_stdout)]
2316    fn test_precompiled_regex_defers_compilation_until_evaluation() {
2317        let (schema, batch) = regex_batch(
2318            DataType::Utf8,
2319            Arc::new(StringArray::from(vec![Some("host-a"), None, Some("db")])) as ArrayRef,
2320            true,
2321        );
2322        let expr = regex_expr("host", Operator::RegexMatch, "host.*");
2323        let physical = Predicate::to_physical_expr(&expr, &schema).unwrap();
2324        let regex = physical.downcast_ref::<PrecompiledRegexExpr>().unwrap();
2325        let initialized = || format!("{:?}", regex.filter);
2326        assert!(
2327            initialized().contains("initialized: false"),
2328            "{}",
2329            initialized()
2330        );
2331        println!("after to_physical_expr: regex initializations = 0");
2332
2333        assert_eq!(
2334            vec![Some(true), None, Some(false)],
2335            evaluate_rows(&physical, &batch)
2336        );
2337        assert!(
2338            initialized().contains("initialized: true"),
2339            "{}",
2340            initialized()
2341        );
2342        println!("after first evaluate: regex initialized = true");
2343        for _ in 0..100 {
2344            assert_eq!(
2345                vec![Some(true), None, Some(false)],
2346                evaluate_rows(&physical, &batch)
2347            );
2348        }
2349        assert!(
2350            initialized().contains("initialized: true"),
2351            "{}",
2352            initialized()
2353        );
2354        println!("after 100 further evaluations: same OnceLock remains initialized");
2355    }
2356
2357    /// A malformed regex must be deferred too, but row evaluation still reports an error instead
2358    /// of silently accepting the predicate as an exact match.
2359    #[test]
2360    #[allow(clippy::print_stdout)]
2361    fn test_invalid_regex_fails_at_evaluation_not_construction() {
2362        let (schema, batch) = regex_batch(
2363            DataType::Utf8,
2364            Arc::new(StringArray::from(vec![Some("host-a")])) as ArrayRef,
2365            true,
2366        );
2367        let expr = regex_expr("host", Operator::RegexMatch, "host(");
2368        // The old rewrite fell back to DataFusion on eager compilation failure. That physical
2369        // planner does not compile the pattern, so it too reports this error on evaluation.
2370        let old_fallback = arrow_regex_expr(&expr, &schema);
2371        assert!(old_fallback.evaluate(&batch).is_err());
2372        let physical = Predicate::to_physical_expr(&expr, &schema)
2373            .expect("construction must retain the invalid regex");
2374        let regex = physical.downcast_ref::<PrecompiledRegexExpr>().unwrap();
2375        assert!(format!("{:?}", regex.filter).contains("initialized: false"));
2376        let error = physical
2377            .evaluate(&batch)
2378            .expect_err("invalid regex must fail on evaluate, not construction");
2379        let DataFusionError::External(source) = &error else {
2380            panic!("expected a common-recordbatch error, got: {error}");
2381        };
2382        assert!(
2383            matches!(
2384                source.downcast_ref::<common_recordbatch::error::Error>(),
2385                Some(common_recordbatch::error::Error::ArrowCompute { .. })
2386            ),
2387            "expected ArrowCompute, got: {error}"
2388        );
2389        assert!(physical.evaluate(&batch).is_err());
2390        assert!(format!("{:?}", regex.filter).contains("initialized: true"));
2391        println!(
2392            "invalid regex: 0 initializations after to_physical_expr; first evaluate returned an error"
2393        );
2394    }
2395
2396    /// A scan can repeatedly evaluate the same regex expression without changing its results.
2397    #[test]
2398    fn test_regex_pattern_reused_across_batches() {
2399        let (schema, batch) = regex_batch(
2400            DataType::Utf8,
2401            Arc::new(StringArray::from(vec![
2402                Some("host-a"),
2403                None,
2404                Some(""),
2405                Some("db"),
2406                Some("host-b"),
2407            ])) as ArrayRef,
2408            true,
2409        );
2410        let expr = regex_expr("host", Operator::RegexMatch, "host.*");
2411
2412        let physical = Predicate::to_physical_expr(&expr, &schema).unwrap();
2413        assert!(
2414            physical.downcast_ref::<PrecompiledRegexExpr>().is_some(),
2415            "the scan-side predicate holds the lazy pattern: {physical}"
2416        );
2417        assert_eq!("host@0 =~ 'host.*'", physical.to_string());
2418
2419        for _ in 0..100 {
2420            assert_eq!(
2421                vec![Some(true), None, Some(false), Some(false), Some(true)],
2422                evaluate_rows(&physical, &batch)
2423            );
2424        }
2425    }
2426
2427    /// The predicate a native `rate(x{host=~'host.*'}[1m])` builds when the label column is
2428    /// nullable, as [`PromPlanner::matchers_to_expr`] plans it: `is_null(host) OR host =~ '...'`.
2429    ///
2430    /// `matchers_to_expr` lives in the query crate; this reproduces the expression it emits so the
2431    /// rewrite is covered for the shape the series scan actually sees. The logical plan is not
2432    /// touched by the precompiled path, and the rows are unchanged.
2433    #[test]
2434    fn test_nullable_label_matcher_keeps_shape_and_rows() {
2435        let (schema, batch) = regex_batch(
2436            DataType::Utf8,
2437            Arc::new(StringArray::from(vec![
2438                Some("host-a"),
2439                None,
2440                Some(""),
2441                Some("db"),
2442                Some("host-b"),
2443            ])) as ArrayRef,
2444            true,
2445        );
2446        let expr =
2447            col("host")
2448                .is_null()
2449                .or(regex_expr("host", Operator::RegexMatch, "^(?:host.*)$"));
2450
2451        let physical = Predicate::to_physical_expr(&expr, &schema).unwrap();
2452        // Shape: the `OR` survives, its null test is untouched, and only the comparison below it
2453        // is replaced by the precompiled form.
2454        let or = physical
2455            .downcast_ref::<PhysicalBinaryExpr>()
2456            .unwrap_or_else(|| panic!("the OR was rewritten into {physical}"));
2457        assert_eq!(&Operator::Or, or.op());
2458        assert!(
2459            or.left()
2460                .downcast_ref::<datafusion_physical_expr::expressions::IsNullExpr>()
2461                .is_some(),
2462            "the null test is unchanged: {}",
2463            or.left()
2464        );
2465        assert!(
2466            or.right().downcast_ref::<PrecompiledRegexExpr>().is_some(),
2467            "the regex below the OR is precompiled: {}",
2468            or.right()
2469        );
2470
2471        // The explicit OR makes a missing label match independently of the regex result.
2472        assert_eq!(
2473            vec![Some(true), Some(true), Some(false), Some(false), Some(true)],
2474            evaluate_rows(&physical, &batch)
2475        );
2476        assert_same_regex_result(&expr, &schema, &batch);
2477    }
2478
2479    /// A scan hands one physical expr to every thread that evaluates it, and the precompiled
2480    /// expression provides separate caches to concurrent searches. Sharing it must neither panic
2481    /// nor change an answer.
2482    #[test]
2483    fn test_precompiled_regex_is_shared_between_threads() {
2484        let (schema, batch) = regex_batch(
2485            DataType::Utf8,
2486            Arc::new(StringArray::from(vec![
2487                Some("host-a"),
2488                None,
2489                Some(""),
2490                Some("db"),
2491                Some("host-b"),
2492            ])) as ArrayRef,
2493            true,
2494        );
2495        let expr = regex_expr("host", Operator::RegexMatch, "host.*");
2496        let physical = Predicate::to_physical_expr(&expr, &schema).unwrap();
2497        assert!(physical.downcast_ref::<PrecompiledRegexExpr>().is_some());
2498        let expected = vec![Some(true), None, Some(false), Some(false), Some(true)];
2499        assert_eq!(expected, evaluate_rows(&physical, &batch));
2500
2501        std::thread::scope(|scope| {
2502            for _ in 0..8 {
2503                let physical = Arc::clone(&physical);
2504                let batch = batch.clone();
2505                let expected = expected.clone();
2506                scope.spawn(move || {
2507                    for _ in 0..50 {
2508                        assert_eq!(expected, evaluate_rows(&physical, &batch));
2509                    }
2510                });
2511            }
2512        });
2513
2514        // The concurrent evaluations neither compiled nor changed the expression.
2515        assert_eq!(expected, evaluate_rows(&physical, &batch));
2516    }
2517}