Skip to main content

table/
predicate.rs

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