Skip to main content

common_recordbatch/filter/
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
15//! Predicate recognition, execution, and lazily compiled regular expressions.
16
17use std::fmt;
18#[cfg(test)]
19use std::sync::atomic::{AtomicUsize, Ordering};
20use std::sync::{Arc, OnceLock};
21
22use datafusion::logical_expr::{Expr, Operator};
23use datafusion_common::ScalarValue;
24use datafusion_common::arrow::array::{ArrayRef, Datum, Scalar};
25use datafusion_common::arrow::buffer::BooleanBuffer;
26use datafusion_common::arrow::compute::kernels::cmp;
27use datafusion_common::cast::as_string_array;
28use datatypes::arrow::array::{
29    Array, ArrayAccessor, ArrayData, BooleanArray, BooleanBufferBuilder, DictionaryArray,
30    StringArrayType,
31};
32use datatypes::arrow::datatypes::{DataType, UInt32Type};
33use datatypes::arrow::error::ArrowError;
34use datatypes::compute::or_kleene;
35use regex_automata::Input;
36use regex_automata::meta;
37use regex_automata::util::pool::{Pool, PoolGuard};
38use snafu::ResultExt;
39
40use crate::error::{ArrowComputeSnafu, Result, UnsupportedOperationSnafu};
41
42#[derive(Debug, Clone)]
43pub(crate) enum SimplePredicate {
44    Comparison {
45        literal: Scalar<ArrayRef>,
46        op: Operator,
47        regex: Option<Arc<CompiledRegex>>,
48        regex_negative: bool,
49    },
50    OrEqChain {
51        literals: Vec<Scalar<ArrayRef>>,
52    },
53    IsNull {
54        negated: bool,
55    },
56    Constant(Option<bool>),
57    And(Box<Self>, Box<Self>),
58    Or(Box<Self>, Box<Self>),
59}
60
61impl SimplePredicate {
62    pub(crate) fn try_new(expr: &Expr, column_type: Option<&DataType>) -> Option<Self> {
63        match expr {
64            Expr::BinaryExpr(binary) if matches!(binary.op, Operator::And | Operator::Or) => {
65                let left = Self::try_new(&binary.left, column_type)?;
66                let right = Self::try_new(&binary.right, column_type)?;
67                if binary.op == Operator::And {
68                    return Some(Self::And(Box::new(left), Box::new(right)));
69                }
70                // Preserve the encoded-key IN-list fast path for pure equality disjunctions.
71                if let (Some(mut lhs), Some(rhs)) =
72                    (left.equality_literals(), right.equality_literals())
73                {
74                    lhs.extend(rhs);
75                    return Some(Self::OrEqChain { literals: lhs });
76                }
77                Some(Self::Or(Box::new(left), Box::new(right)))
78            }
79            Expr::BinaryExpr(binary) => {
80                let mut op = binary.op;
81                if !matches!(
82                    op,
83                    Operator::Eq
84                        | Operator::NotEq
85                        | Operator::Lt
86                        | Operator::LtEq
87                        | Operator::Gt
88                        | Operator::GtEq
89                        | Operator::RegexMatch
90                        | Operator::RegexIMatch
91                        | Operator::RegexNotMatch
92                        | Operator::RegexNotIMatch
93                ) {
94                    return None;
95                }
96                let literal = if let Expr::Literal(literal, _) = &*binary.right {
97                    Self::check_column(&binary.left, column_type)?;
98                    literal
99                } else if let Expr::Literal(literal, _) = &*binary.left {
100                    Self::check_column(&binary.right, column_type)?;
101                    op = op.swap()?;
102                    literal
103                } else {
104                    return None;
105                };
106                let (regex, regex_negative) = Self::maybe_build_regex(op, literal).ok()?;
107                Some(Self::Comparison {
108                    literal: datafusion_common::utils::normalize_float_zero_scalar(literal.clone())
109                        .to_scalar()
110                        .ok()?,
111                    op,
112                    regex,
113                    regex_negative,
114                })
115            }
116            Expr::IsNull(column) | Expr::IsNotNull(column) => {
117                Self::check_column(column, column_type)?;
118                Some(Self::IsNull {
119                    negated: matches!(expr, Expr::IsNotNull(_)),
120                })
121            }
122            Expr::Literal(ScalarValue::Boolean(value), _) => Some(Self::Constant(*value)),
123            _ => None,
124        }
125    }
126
127    fn check_column(expr: &Expr, column_type: Option<&DataType>) -> Option<()> {
128        match expr {
129            Expr::Column(_) => Some(()),
130            Expr::Cast(cast) if cast.field.data_type() == &DataType::Utf8 => {
131                let Expr::Column(_) = &*cast.expr else {
132                    return None;
133                };
134                match column_type? {
135                    DataType::Utf8 => Some(()),
136                    DataType::Dictionary(key, value)
137                        if **key == DataType::UInt32 && **value == DataType::Utf8 =>
138                    {
139                        Some(())
140                    }
141                    _ => None,
142                }
143            }
144            _ => None,
145        }
146    }
147
148    fn equality_literals(&self) -> Option<Vec<Scalar<ArrayRef>>> {
149        match self {
150            Self::Comparison {
151                literal,
152                op: Operator::Eq,
153                ..
154            } => Some(vec![literal.clone()]),
155            Self::OrEqChain { literals } => Some(literals.clone()),
156            _ => None,
157        }
158    }
159
160    pub(crate) fn evaluate(&self, input: &impl Datum, len: usize) -> Result<BooleanArray> {
161        match self {
162            Self::Comparison {
163                literal,
164                op,
165                regex,
166                regex_negative,
167            } => match op {
168                Operator::Eq => cmp::eq(input, literal),
169                Operator::NotEq => cmp::neq(input, literal),
170                Operator::Lt => cmp::lt(input, literal),
171                Operator::LtEq => cmp::lt_eq(input, literal),
172                Operator::Gt => cmp::gt(input, literal),
173                Operator::GtEq => cmp::gt_eq(input, literal),
174                Operator::RegexMatch
175                | Operator::RegexIMatch
176                | Operator::RegexNotMatch
177                | Operator::RegexNotIMatch => {
178                    Self::regex_match(input, regex.as_deref(), *regex_negative)
179                }
180                _ => {
181                    return UnsupportedOperationSnafu {
182                        reason: format!("{op:?}"),
183                    }
184                    .fail();
185                }
186            }
187            .context(ArrowComputeSnafu),
188            Self::OrEqChain { literals } => {
189                let mut result = BooleanArray::from(vec![false; len]);
190                for literal in literals {
191                    let rhs = cmp::eq(input, literal).context(ArrowComputeSnafu)?;
192                    result = or_kleene(&result, &rhs).context(ArrowComputeSnafu)?;
193                }
194                Ok(result)
195            }
196            Self::IsNull { negated } => {
197                let values = match input.get().0.logical_nulls() {
198                    Some(nulls) if *negated => nulls.inner().clone(),
199                    Some(nulls) => !nulls.inner(),
200                    None if *negated => BooleanBuffer::new_set(len),
201                    None => BooleanBuffer::new_unset(len),
202                };
203                Ok(BooleanArray::new(values, None))
204            }
205            Self::Constant(value) => Ok(BooleanArray::from(vec![*value; len])),
206            Self::And(left, right) => datatypes::compute::and_kleene(
207                &left.evaluate(input, len)?,
208                &right.evaluate(input, len)?,
209            )
210            .context(ArrowComputeSnafu),
211            Self::Or(left, right) => {
212                or_kleene(&left.evaluate(input, len)?, &right.evaluate(input, len)?)
213                    .context(ArrowComputeSnafu)
214            }
215        }
216    }
217
218    /// Builds a regex pattern from a scalar value and operator.
219    /// Returns the `(regex, negative)` and if successful.
220    ///
221    /// Returns `Err` if
222    /// - the value is not a string
223    ///
224    /// The regex is `None` if
225    /// - the operator is not a regex operator
226    /// - the pattern is empty
227    ///
228    /// A non-empty pattern is stored without compiling. The first evaluation compiles it and
229    /// initializes its cache pool; pruning can construct the evaluator without paying that cost.
230    fn maybe_build_regex(
231        operator: Operator,
232        value: &ScalarValue,
233    ) -> Result<(Option<Arc<CompiledRegex>>, bool), ArrowError> {
234        let (ignore_case, negative) = match operator {
235            Operator::RegexMatch => (false, false),
236            Operator::RegexIMatch => (true, false),
237            Operator::RegexNotMatch => (false, true),
238            Operator::RegexNotIMatch => (true, true),
239            _ => return Ok((None, false)),
240        };
241        let flag = if ignore_case { Some("i") } else { None };
242        let regex = value
243            .try_as_str()
244            .ok_or_else(|| ArrowError::CastError(format!("Cannot cast {:?} to str", value)))?
245            .ok_or_else(|| ArrowError::CastError("Regex should not be null".to_string()))?;
246        let pattern = match flag {
247            Some(flag) => format!("(?{flag}){regex}"),
248            None => regex.to_string(),
249        };
250        if pattern.is_empty() {
251            Ok((None, negative))
252        } else {
253            CompiledRegex::new(&pattern).map(|regex| (Some(Arc::new(regex)), negative))
254        }
255    }
256
257    fn regex_match(
258        input: &impl Datum,
259        regex: Option<&CompiledRegex>,
260        negative: bool,
261    ) -> std::result::Result<BooleanArray, ArrowError> {
262        let array = input.get().0;
263
264        // Try to cast to StringArray first
265        if let Ok(string_array) = as_string_array(array) {
266            let mut result = regexp_is_match_scalar(string_array, regex)?;
267            if negative {
268                result = datatypes::compute::not(&result)?;
269            }
270            return Ok(result);
271        }
272
273        // Try to cast to StringDictionaryArray
274        if let Some(dict_array) = array.as_any().downcast_ref::<DictionaryArray<UInt32Type>>() {
275            let mut result = regexp_is_match_dictionary(dict_array, regex)?;
276            if negative {
277                result = datatypes::compute::not(&result)?;
278            }
279            return Ok(result);
280        }
281
282        Err(ArrowError::CastError(format!(
283            "Cannot cast {:?} to StringArray or StringDictionaryArray",
284            array.data_type()
285        )))
286    }
287}
288
289/// A regular expression compiled on first use with a pool of per-array scratch spaces.
290///
291/// `search_half_with` bypasses the regex's internal per-search cache pool. Each array borrows one
292/// cache from our pool and uses it for all its rows; different arrays can search concurrently.
293/// The compilation uses the same `meta::Regex` defaults as [`regex::Regex`].
294pub struct CompiledRegex {
295    pattern: String,
296    // Cache compilation errors as well: a malformed pattern must not be rebuilt per batch.
297    compiled: OnceLock<std::result::Result<RegexProgram, String>>,
298    #[cfg(test)]
299    compilations: AtomicUsize,
300    #[cfg(test)]
301    cache_acquisitions: AtomicUsize,
302    // The hook runs after checkout and before entering the array loop, without holding a pool lock.
303    #[cfg(test)]
304    after_cache_acquired: OnceLock<Arc<dyn Fn() + Send + Sync>>,
305}
306
307type CacheFactory = Box<dyn Fn() -> meta::Cache + Send + Sync>;
308type CachePool = Pool<meta::Cache, CacheFactory>;
309
310struct RegexProgram {
311    regex: Arc<meta::Regex>,
312    caches: CachePool,
313}
314
315impl CompiledRegex {
316    /// Stores `pattern`. Compilation and syntax errors are deferred until first evaluation.
317    ///
318    /// Returns `Ok` for compatibility with the prior eager constructor.
319    pub fn new(pattern: &str) -> Result<Self, ArrowError> {
320        Ok(Self {
321            pattern: pattern.to_string(),
322            compiled: OnceLock::new(),
323            #[cfg(test)]
324            compilations: AtomicUsize::new(0),
325            #[cfg(test)]
326            cache_acquisitions: AtomicUsize::new(0),
327            #[cfg(test)]
328            after_cache_acquired: OnceLock::new(),
329        })
330    }
331
332    /// Compiles the pattern at most once, even if several arrays first evaluate it concurrently.
333    fn program(&self) -> Result<&RegexProgram, ArrowError> {
334        self.compiled
335            .get_or_init(|| {
336                #[cfg(test)]
337                self.compilations.fetch_add(1, Ordering::Relaxed);
338                let regex = Arc::new(
339                    meta::Regex::new(&self.pattern)
340                        .map_err(|e| format!("Regular expression did not compile: {e:?}"))?,
341                );
342                let pooled_regex = Arc::clone(&regex);
343                let factory: CacheFactory = Box::new(move || pooled_regex.create_cache());
344                Ok(RegexProgram {
345                    regex,
346                    caches: Pool::new(factory),
347                })
348            })
349            .as_ref()
350            .map_err(|message| ArrowError::ComputeError(message.clone()))
351    }
352
353    /// Returns whether `value` matches, or a compilation error for an invalid pattern.
354    pub fn is_match(&self, value: &str) -> Result<bool, ArrowError> {
355        let program = self.program()?;
356        let mut cache = self.get_cache(program);
357        Ok(program.is_match_with(&mut cache, value))
358    }
359
360    /// Checks out one cache; its guard returns it to the pool when the array loop exits.
361    fn get_cache<'a>(&self, program: &'a RegexProgram) -> PoolGuard<'a, meta::Cache, CacheFactory> {
362        let cache = program.caches.get();
363        #[cfg(test)]
364        {
365            self.cache_acquisitions.fetch_add(1, Ordering::Relaxed);
366            if let Some(hook) = self.after_cache_acquired.get() {
367                hook();
368            }
369        }
370        cache
371    }
372
373    #[cfg(test)]
374    fn cache_acquisitions(&self) -> usize {
375        self.cache_acquisitions.load(Ordering::Relaxed)
376    }
377
378    #[cfg(test)]
379    fn compilations(&self) -> usize {
380        self.compilations.load(Ordering::Relaxed)
381    }
382}
383
384impl RegexProgram {
385    fn is_match_with(&self, cache: &mut meta::Cache, value: &str) -> bool {
386        self.regex
387            .search_half_with(cache, &Input::new(value).earliest(true))
388            .is_some()
389    }
390}
391
392impl fmt::Debug for CompiledRegex {
393    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
394        // Expose initialization state, not the (potentially large) program or cache pool.
395        f.debug_struct("CompiledRegex")
396            .field("pattern", &self.pattern)
397            .field("initialized", &self.compiled.get().is_some())
398            .finish_non_exhaustive()
399    }
400}
401
402/// The same as arrow [regexp_is_match_scalar()](datatypes::compute::kernels::regexp::regexp_is_match_scalar())
403/// with a reusable, lazily compiled regex.
404/// See <https://github.com/apache/arrow-rs/blob/54.2.0/arrow-string/src/regexp.rs#L204-L246> for the implementation details.
405pub fn regexp_is_match_scalar<'a, S>(
406    array: &'a S,
407    regex: Option<&CompiledRegex>,
408) -> Result<BooleanArray, ArrowError>
409where
410    &'a S: StringArrayType<'a>,
411{
412    let null_bit_buffer = array.nulls().map(|x| x.inner().sliced());
413    let mut result = BooleanBufferBuilder::new(array.len());
414
415    if let Some(re) = regex {
416        let program = re.program()?;
417        // One checkout for the entire array. The guard returns the cache on drop.
418        let mut cache = re.get_cache(program);
419        for i in 0..array.len() {
420            result.append(program.is_match_with(&mut cache, array.value(i)));
421        }
422    } else {
423        result.append_n(array.len(), true);
424    }
425
426    let buffer = result.into();
427    let data = unsafe {
428        ArrayData::new_unchecked(
429            DataType::Boolean,
430            array.len(),
431            None,
432            null_bit_buffer,
433            0,
434            vec![buffer],
435            vec![],
436        )
437    };
438
439    Ok(BooleanArray::from(data))
440}
441
442/// Similar to [regexp_is_match_scalar] but for StringDictionaryArray.
443/// Iterates through dictionary keys to get string values and applies regex matching.
444pub fn regexp_is_match_dictionary(
445    dict_array: &DictionaryArray<UInt32Type>,
446    regex: Option<&CompiledRegex>,
447) -> Result<BooleanArray, ArrowError> {
448    // Get the string values from the dictionary
449    let string_values = dict_array
450        .values()
451        .as_any()
452        .downcast_ref::<datatypes::arrow::array::StringArray>()
453        .ok_or_else(|| {
454            ArrowError::CastError("Dictionary values must be StringArray".to_string())
455        })?;
456
457    // Dictionary logical nulls include both null keys and keys whose dictionary value is null.
458    let logical_nulls = dict_array.logical_nulls();
459    let null_bit_buffer = logical_nulls.as_ref().map(|x| x.inner().sliced());
460    let mut result = BooleanBufferBuilder::new(dict_array.len());
461
462    if let Some(re) = regex {
463        let program = re.program()?;
464        // One checkout for the entire array, as in `regexp_is_match_scalar`.
465        let mut cache = re.get_cache(program);
466        let keys = dict_array.keys().values();
467        for i in 0..dict_array.len() {
468            if logical_nulls.as_ref().is_some_and(|nulls| nulls.is_null(i)) {
469                result.append(false);
470            } else {
471                let key = keys[i] as usize;
472                let string_value = string_values.value(key);
473                result.append(program.is_match_with(&mut cache, string_value));
474            }
475        }
476    } else {
477        result.append_n(dict_array.len(), true);
478    }
479
480    let buffer = result.into();
481    let data = unsafe {
482        ArrayData::new_unchecked(
483            DataType::Boolean,
484            dict_array.len(),
485            None,
486            null_bit_buffer,
487            0,
488            vec![buffer],
489            vec![],
490        )
491    };
492
493    Ok(BooleanArray::from(data))
494}
495
496#[cfg(test)]
497mod tests {
498    use std::sync::Arc;
499
500    use datafusion::execution::context::ExecutionProps;
501    use datafusion::logical_expr::physical_planning_context::PhysicalPlanningContext;
502    use datafusion::logical_expr::{BinaryExpr, Expr, Literal, Operator, col, lit};
503    use datafusion::physical_expr::create_physical_expr;
504    use datafusion_common::arrow::array::ArrayRef;
505    use datafusion_common::arrow::buffer::BooleanBuffer;
506    use datafusion_common::{Column, DFSchema, ScalarValue};
507    use datatypes::arrow::array::{
508        Array, BooleanArray, DictionaryArray, LargeStringArray, RecordBatch, StringArray,
509        StringArrayType, StringViewArray, UInt32Array,
510    };
511    use datatypes::arrow::datatypes::{DataType, Field, Schema, TimeUnit, UInt32Type};
512    use datatypes::value::Value;
513    use regex::Regex;
514
515    use crate::filter::predicate::{
516        CompiledRegex, SimplePredicate, regexp_is_match_dictionary, regexp_is_match_scalar,
517    };
518    use crate::filter::{SimpleFilterEvaluator, batch_filter};
519
520    #[test]
521    fn unsupported_filter_op() {
522        // `+` is not supported
523        let expr = Expr::BinaryExpr(BinaryExpr {
524            left: Box::new(Expr::Column(Column::from_name("foo"))),
525            op: Operator::Plus,
526            right: Box::new(1.lit()),
527        });
528        assert!(SimpleFilterEvaluator::try_new(&expr).is_none());
529
530        // two literal is not supported
531        let expr = Expr::BinaryExpr(BinaryExpr {
532            left: Box::new(1.lit()),
533            op: Operator::Eq,
534            right: Box::new(1.lit()),
535        });
536        assert!(SimpleFilterEvaluator::try_new(&expr).is_none());
537
538        // two column is not supported
539        let expr = Expr::BinaryExpr(BinaryExpr {
540            left: Box::new(Expr::Column(Column::from_name("foo"))),
541            op: Operator::Eq,
542            right: Box::new(Expr::Column(Column::from_name("bar"))),
543        });
544        assert!(SimpleFilterEvaluator::try_new(&expr).is_none());
545
546        // compound expr is not supported
547        let expr = Expr::BinaryExpr(BinaryExpr {
548            left: Box::new(Expr::BinaryExpr(BinaryExpr {
549                left: Box::new(Expr::Column(Column::from_name("foo"))),
550                op: Operator::Eq,
551                right: Box::new(1.lit()),
552            })),
553            op: Operator::Eq,
554            right: Box::new(1.lit()),
555        });
556        assert!(SimpleFilterEvaluator::try_new(&expr).is_none());
557        for negated in [false, true] {
558            let membership = col("label").in_list(vec![lit(""), lit("lo")], negated);
559            assert!(SimpleFilterEvaluator::try_new(&membership).is_none());
560            assert!(
561                SimpleFilterEvaluator::try_new(&col("label").is_null().or(membership)).is_none()
562            );
563        }
564        for expr in [
565            col("other").is_null().or(col("label").not_eq(lit("lo"))),
566            col("a.label")
567                .is_null()
568                .or(col("b.label").not_eq(lit("lo"))),
569            col("label").is_null().or(col("label").eq(col("other"))),
570            col("label")
571                .is_null()
572                .or(Expr::Cast(datafusion::logical_expr::Cast::new(
573                    Box::new(col("label")),
574                    DataType::Int64,
575                ))
576                .eq(lit("lo"))),
577        ] {
578            assert!(SimpleFilterEvaluator::try_new(&expr).is_none(), "{expr}");
579        }
580    }
581
582    #[test]
583    fn string_cast_requires_matching_column_type() {
584        let cast = Expr::Cast(datafusion::logical_expr::Cast::new(
585            Box::new(col("label")),
586            DataType::Utf8,
587        ));
588        let expr = col("label").is_null().or(cast.not_eq(lit("lo")));
589        for data_type in [
590            DataType::Int64,
591            DataType::Timestamp(TimeUnit::Millisecond, None),
592            DataType::Binary,
593        ] {
594            assert!(
595                SimpleFilterEvaluator::try_new_with_column_type(&expr, &|_| Some(
596                    data_type.clone()
597                ))
598                .is_none()
599            );
600        }
601        assert!(SimpleFilterEvaluator::try_new(&expr).is_none());
602    }
603
604    #[tokio::test]
605    async fn single_column_predicates_match_datafusion() {
606        use datafusion::prelude::SessionContext;
607        use datafusion_common::tree_node::{TreeNode, TreeNodeRecursion};
608        use datatypes::arrow::array::{Int32Array, StringArray, UInt32Array};
609
610        let values = vec![
611            None,
612            Some(""),
613            Some("lo"),
614            Some("eth0"),
615            Some("a\nb"),
616            Some("服务"),
617            None,
618        ];
619        let strings: ArrayRef = Arc::new(StringArray::from(values));
620        let dictionary: ArrayRef = Arc::new(DictionaryArray::<UInt32Type>::new(
621            UInt32Array::from(vec![
622                None,
623                Some(0),
624                Some(1),
625                Some(2),
626                Some(3),
627                Some(4),
628                Some(5),
629            ]),
630            Arc::new(StringArray::from(vec![
631                Some(""),
632                Some("lo"),
633                Some("eth0"),
634                Some("a\nb"),
635                Some("服务"),
636                None,
637            ])),
638        ));
639        let null = || lit(ScalarValue::Utf8(None));
640        let mut predicates = vec![
641            col("label").is_null(),
642            col("label").is_not_null(),
643            col("label")
644                .is_null()
645                .or(col("label").eq(lit("")))
646                .and(col("label").is_not_null()),
647            col("label")
648                .not_eq(lit("lo"))
649                .and(col("label").not_eq(lit("eth0"))),
650            col("label")
651                .eq(lit("lo"))
652                .or(col("label").eq(lit("eth0")))
653                .or(col("label").eq(lit(""))),
654            col("label").eq(null()).or(col("label").eq(lit("eth0"))),
655            col("label").gt(lit("a")).and(col("label").lt(lit("z"))),
656            lit("lo").not_eq(col("label")),
657        ];
658        for (op, literal) in [
659            (Operator::Eq, ""),
660            (Operator::NotEq, "lo"),
661            (Operator::RegexNotMatch, "^(?:lo|vfat)$"),
662            (Operator::RegexMatch, "^(?:|eth0)$"),
663        ] {
664            let comparison = Expr::BinaryExpr(BinaryExpr::new(
665                Box::new(col("label")),
666                op,
667                Box::new(lit(literal)),
668            ));
669            predicates.extend([
670                col("label").is_null().or(comparison.clone()),
671                comparison.or(col("label").is_null()),
672            ]);
673        }
674        for input in [strings, dictionary] {
675            let ctx = SessionContext::new();
676            let schema = Arc::new(Schema::new(vec![
677                Field::new("label", input.data_type().clone(), true),
678                Field::new("id", DataType::Int32, false),
679            ]));
680            ctx.register_batch(
681                "labels",
682                RecordBatch::try_new(
683                    schema,
684                    vec![
685                        input.clone(),
686                        Arc::new(Int32Array::from_iter_values(0..input.len() as i32)),
687                    ],
688                )
689                .unwrap(),
690            )
691            .unwrap();
692            for expr in &predicates {
693                let df = ctx
694                    .table("labels")
695                    .await
696                    .unwrap()
697                    .filter(expr.clone())
698                    .unwrap();
699                let plan = df.clone().into_optimized_plan().unwrap();
700                let expected = df
701                    .collect()
702                    .await
703                    .unwrap()
704                    .iter()
705                    .flat_map(|batch| {
706                        batch
707                            .column_by_name("id")
708                            .unwrap()
709                            .as_any()
710                            .downcast_ref::<Int32Array>()
711                            .unwrap()
712                            .values()
713                            .to_vec()
714                    })
715                    .collect::<Vec<_>>();
716                let evaluate = |expr: &Expr| {
717                    let evaluator =
718                        SimpleFilterEvaluator::try_new_with_column_type(expr, &|name| {
719                            (name == "label").then(|| input.data_type().clone())
720                        })
721                        .unwrap_or_else(|| panic!("unsupported: {expr}"));
722                    let mask = evaluator.evaluate_array(&input).unwrap();
723                    for (i, matched) in mask.iter().enumerate() {
724                        let scalar = ScalarValue::try_from_array(&input, i).unwrap();
725                        assert_eq!(
726                            evaluator.evaluate_scalar(&scalar).unwrap(),
727                            matched,
728                            "{expr}, row={i}"
729                        );
730                    }
731                    mask
732                };
733                let selected = |mask: BooleanBuffer| {
734                    mask.iter()
735                        .enumerate()
736                        .filter_map(|(i, matched)| matched.then_some(i as i32))
737                        .collect::<Vec<_>>()
738                };
739                assert_eq!(selected(evaluate(expr)), expected, "{expr}");
740                let mut filters = Vec::new();
741                plan.apply(|plan| {
742                    if let datafusion::logical_expr::LogicalPlan::Filter(filter) = plan {
743                        filters.push(filter.predicate.clone());
744                    }
745                    Ok(TreeNodeRecursion::Continue)
746                })
747                .unwrap();
748                if !filters.is_empty() {
749                    let mut mask = BooleanBuffer::new_set(input.len());
750                    for filter in filters {
751                        mask = &mask & &evaluate(&filter);
752                    }
753                    assert_eq!(selected(mask), expected, "optimized: {plan}");
754                }
755            }
756        }
757    }
758
759    #[tokio::test]
760    async fn float_zero_predicates_match_datafusion() {
761        use datafusion::prelude::SessionContext;
762        use datatypes::arrow::array::{Float32Array, Float64Array, Int32Array};
763
764        let float64: ArrayRef = Arc::new(Float64Array::from(vec![
765            Some(-0.0),
766            Some(0.0),
767            Some(1.0),
768            Some(f64::NAN),
769            None,
770        ]));
771        let float32: ArrayRef = Arc::new(Float32Array::from(vec![
772            Some(-0.0),
773            Some(0.0),
774            Some(1.0),
775            Some(f32::NAN),
776            None,
777        ]));
778        for input in [float64, float32] {
779            let literal = |v: f64| {
780                if input.data_type() == &DataType::Float32 {
781                    lit(v as f32)
782                } else {
783                    lit(v)
784                }
785            };
786            let ctx = SessionContext::new();
787            let schema = Arc::new(Schema::new(vec![
788                Field::new("v", input.data_type().clone(), true),
789                Field::new("id", DataType::Int32, false),
790            ]));
791            ctx.register_batch(
792                "floats",
793                RecordBatch::try_new(
794                    schema,
795                    vec![
796                        input.clone(),
797                        Arc::new(Int32Array::from_iter_values(0..input.len() as i32)),
798                    ],
799                )
800                .unwrap(),
801            )
802            .unwrap();
803            for expr in [
804                col("v").eq(literal(0.0)),
805                col("v").eq(literal(-0.0)),
806                col("v").not_eq(literal(-0.0)),
807                col("v").lt(literal(0.0)),
808                col("v").lt_eq(literal(-0.0)),
809                col("v").gt(literal(-0.0)),
810                col("v").gt_eq(literal(0.0)),
811                literal(0.0).lt_eq(col("v")),
812                col("v").eq(literal(0.0)).or(col("v").eq(literal(1.0))),
813                col("v").eq(literal(f64::NAN)),
814            ] {
815                let expected = ctx
816                    .table("floats")
817                    .await
818                    .unwrap()
819                    .filter(expr.clone())
820                    .unwrap()
821                    .collect()
822                    .await
823                    .unwrap()
824                    .iter()
825                    .flat_map(|batch| {
826                        batch
827                            .column_by_name("id")
828                            .unwrap()
829                            .as_any()
830                            .downcast_ref::<Int32Array>()
831                            .unwrap()
832                            .values()
833                            .to_vec()
834                    })
835                    .collect::<Vec<_>>();
836                let evaluator = SimpleFilterEvaluator::try_new(&expr).unwrap();
837                let mask = evaluator.evaluate_array(&input).unwrap();
838                let selected = mask
839                    .iter()
840                    .enumerate()
841                    .filter_map(|(i, matched)| matched.then_some(i as i32))
842                    .collect::<Vec<_>>();
843                assert_eq!(selected, expected, "{expr}");
844                for (i, matched) in mask.iter().enumerate() {
845                    let scalar = ScalarValue::try_from_array(&input, i).unwrap();
846                    assert_eq!(
847                        evaluator.evaluate_scalar(&scalar).unwrap(),
848                        matched,
849                        "{expr}, row={i}"
850                    );
851                }
852            }
853        }
854    }
855
856    #[test]
857    fn supported_filter_op() {
858        // equal
859        let expr = Expr::BinaryExpr(BinaryExpr {
860            left: Box::new(Expr::Column(Column::from_name("foo"))),
861            op: Operator::Eq,
862            right: Box::new(1.lit()),
863        });
864        let _ = SimpleFilterEvaluator::try_new(&expr).unwrap();
865
866        // swap operands
867        let expr = Expr::BinaryExpr(BinaryExpr {
868            left: Box::new(1.lit()),
869            op: Operator::Lt,
870            right: Box::new(Expr::Column(Column::from_name("foo"))),
871        });
872        let evaluator = SimpleFilterEvaluator::try_new(&expr).unwrap();
873        assert!(evaluator.is_gt());
874        assert_eq!(evaluator.column_name, "foo".to_string());
875    }
876
877    #[test]
878    fn run_on_array() {
879        let expr = Expr::BinaryExpr(BinaryExpr {
880            left: Box::new(Expr::Column(Column::from_name("foo"))),
881            op: Operator::Eq,
882            right: Box::new(1i64.lit()),
883        });
884        let evaluator = SimpleFilterEvaluator::try_new(&expr).unwrap();
885
886        let input_1 = Arc::new(datatypes::arrow::array::Int64Array::from(vec![1, 2, 3])) as _;
887        let result = evaluator.evaluate_array(&input_1).unwrap();
888        assert_eq!(result, BooleanBuffer::from(vec![true, false, false]));
889
890        let input_2 = Arc::new(datatypes::arrow::array::Int64Array::from(vec![1, 1, 1])) as _;
891        let result = evaluator.evaluate_array(&input_2).unwrap();
892        assert_eq!(result, BooleanBuffer::from(vec![true, true, true]));
893
894        let input_3 = Arc::new(datatypes::arrow::array::Int64Array::new_null(0)) as _;
895        let result = evaluator.evaluate_array(&input_3).unwrap();
896        assert_eq!(result, BooleanBuffer::from(vec![]));
897    }
898
899    #[test]
900    fn run_on_scalar() {
901        let expr = Expr::BinaryExpr(BinaryExpr {
902            left: Box::new(Expr::Column(Column::from_name("foo"))),
903            op: Operator::Lt,
904            right: Box::new(1i64.lit()),
905        });
906        let evaluator = SimpleFilterEvaluator::try_new(&expr).unwrap();
907
908        let input_1 = ScalarValue::Int64(Some(1));
909        let result = evaluator.evaluate_scalar(&input_1).unwrap();
910        assert!(!result);
911
912        let input_2 = ScalarValue::Int64(Some(0));
913        let result = evaluator.evaluate_scalar(&input_2).unwrap();
914        assert!(result);
915
916        let input_3 = ScalarValue::Int64(None);
917        let result = evaluator.evaluate_scalar(&input_3).unwrap();
918        assert!(!result);
919    }
920
921    #[test]
922    fn test_complex_filter_expression() {
923        // Create an expression tree for: col = 'B' OR col = 'C' OR col = 'D'
924        let col_eq_b = col("col").eq(lit("B"));
925        let col_eq_c = col("col").eq(lit("C"));
926        let col_eq_d = col("col").eq(lit("D"));
927
928        // Build the OR chain
929        let col_or_expr = col_eq_b.or(col_eq_c).or(col_eq_d);
930
931        // Check that SimpleFilterEvaluator can handle OR chain
932        let or_evaluator = SimpleFilterEvaluator::try_new(&col_or_expr).unwrap();
933        assert_eq!(or_evaluator.column_name, "col");
934        assert!(or_evaluator.is_or_eq_chain());
935        assert_eq!(
936            or_evaluator.literal_list_values().unwrap(),
937            vec![Value::from("B"), Value::from("C"), Value::from("D")]
938        );
939
940        // Create a schema and batch for testing
941        let schema = Schema::new(vec![Field::new("col", DataType::Utf8, false)]);
942        let df_schema = DFSchema::try_from(schema.clone()).unwrap();
943        let props = ExecutionProps::new();
944        let physical_expr = create_physical_expr(
945            &col_or_expr,
946            &df_schema,
947            &props,
948            &PhysicalPlanningContext::default(),
949        )
950        .unwrap();
951
952        // Create test data
953        let col_data = Arc::new(datatypes::arrow::array::StringArray::from(vec![
954            "B", "C", "E", "B", "C", "D", "F",
955        ]));
956        let batch = RecordBatch::try_new(Arc::new(schema), vec![col_data]).unwrap();
957        let expected = datatypes::arrow::array::StringArray::from(vec!["B", "C", "B", "C", "D"]);
958
959        // Filter the batch
960        let filtered_batch = batch_filter(&batch, &physical_expr).unwrap();
961
962        // Expected: rows with col in ("B", "C", "D")
963        // That would be rows 0, 1, 3, 4, 5
964        assert_eq!(filtered_batch.num_rows(), 5);
965
966        let col_filtered = filtered_batch
967            .column(0)
968            .as_any()
969            .downcast_ref::<datatypes::arrow::array::StringArray>()
970            .unwrap();
971        assert_eq!(col_filtered, &expected);
972    }
973
974    #[test]
975    fn test_maybe_build_regex() {
976        // Test case for RegexMatch (case sensitive, non-negative)
977        let (regex, negative) = SimplePredicate::maybe_build_regex(
978            Operator::RegexMatch,
979            &ScalarValue::Utf8(Some("a.*b".to_string())),
980        )
981        .unwrap();
982        assert!(regex.is_some());
983        assert!(!negative);
984        assert!(regex.unwrap().is_match("axxb").unwrap());
985
986        // Test case for RegexIMatch (case insensitive, non-negative)
987        let (regex, negative) = SimplePredicate::maybe_build_regex(
988            Operator::RegexIMatch,
989            &ScalarValue::Utf8(Some("a.*b".to_string())),
990        )
991        .unwrap();
992        assert!(regex.is_some());
993        assert!(!negative);
994        assert!(regex.unwrap().is_match("AxxB").unwrap());
995
996        // Test case for RegexNotMatch (case sensitive, negative)
997        let (regex, negative) = SimplePredicate::maybe_build_regex(
998            Operator::RegexNotMatch,
999            &ScalarValue::Utf8(Some("a.*b".to_string())),
1000        )
1001        .unwrap();
1002        assert!(regex.is_some());
1003        assert!(negative);
1004
1005        // Test case for RegexNotIMatch (case insensitive, negative)
1006        let (regex, negative) = SimplePredicate::maybe_build_regex(
1007            Operator::RegexNotIMatch,
1008            &ScalarValue::Utf8(Some("a.*b".to_string())),
1009        )
1010        .unwrap();
1011        assert!(regex.is_some());
1012        assert!(negative);
1013
1014        // Test with empty regex pattern
1015        let (regex, negative) = SimplePredicate::maybe_build_regex(
1016            Operator::RegexMatch,
1017            &ScalarValue::Utf8(Some("".to_string())),
1018        )
1019        .unwrap();
1020        assert!(regex.is_none());
1021        assert!(!negative);
1022
1023        // Test with non-regex operator
1024        let (regex, negative) = SimplePredicate::maybe_build_regex(
1025            Operator::Eq,
1026            &ScalarValue::Utf8(Some("a.*b".to_string())),
1027        )
1028        .unwrap();
1029        assert!(regex.is_none());
1030        assert!(!negative);
1031
1032        // Invalid regex patterns are rejected on first evaluation, not at construction.
1033        let result = SimplePredicate::maybe_build_regex(
1034            Operator::RegexMatch,
1035            &ScalarValue::Utf8(Some("a(b".to_string())),
1036        );
1037        let invalid = result.unwrap().0.unwrap();
1038        assert_eq!(0, invalid.compilations());
1039        assert!(invalid.is_match("anything").is_err());
1040        assert!(invalid.is_match("anything").is_err());
1041        assert_eq!(
1042            1,
1043            invalid.compilations(),
1044            "invalid patterns are compiled only once"
1045        );
1046
1047        // Test with non-string value
1048        let result = SimplePredicate::maybe_build_regex(
1049            Operator::RegexMatch,
1050            &ScalarValue::Int64(Some(123)),
1051        );
1052        assert!(result.is_err());
1053
1054        // Test with null value
1055        let result =
1056            SimplePredicate::maybe_build_regex(Operator::RegexMatch, &ScalarValue::Utf8(None));
1057        assert!(result.is_err());
1058    }
1059
1060    #[test]
1061    fn test_regex_match_dictionary_array() {
1062        use datatypes::arrow::array::StringDictionaryBuilder;
1063
1064        // Create a StringDictionaryArray
1065        let mut builder = StringDictionaryBuilder::<UInt32Type>::new();
1066        builder.append("apple").unwrap();
1067        builder.append("banana").unwrap();
1068        builder.append("apple").unwrap();
1069        builder.append("cherry").unwrap();
1070        let dict_array = builder.finish();
1071
1072        // Test regex that matches "apple"
1073        let regex = CompiledRegex::new(r"app.*").unwrap();
1074        let result = regexp_is_match_dictionary(&dict_array, Some(&regex)).unwrap();
1075
1076        // Should match indices 0 and 2 (both "apple")
1077        assert_eq!(result.len(), 4);
1078        assert!(result.value(0)); // "apple"
1079        assert!(!result.value(1)); // "banana"
1080        assert!(result.value(2)); // "apple"
1081        assert!(!result.value(3)); // "cherry"
1082
1083        // Test regex that matches "banana"
1084        let regex2 = CompiledRegex::new(r"ban.*").unwrap();
1085        let result2 = regexp_is_match_dictionary(&dict_array, Some(&regex2)).unwrap();
1086
1087        assert!(!result2.value(0)); // "apple"
1088        assert!(result2.value(1)); // "banana"
1089        assert!(!result2.value(2)); // "apple"
1090        assert!(!result2.value(3)); // "cherry"
1091
1092        // Test with no regex (should match all)
1093        let result3 = regexp_is_match_dictionary(&dict_array, None).unwrap();
1094        assert!(result3.value(0));
1095        assert!(result3.value(1));
1096        assert!(result3.value(2));
1097        assert!(result3.value(3));
1098    }
1099
1100    #[test]
1101    fn test_regex_scan_masks_preserve_sql_null_semantics() {
1102        let plain = Arc::new(datatypes::arrow::array::StringArray::from(vec![
1103            Some("api"),
1104            Some("API"),
1105            Some("db"),
1106            None,
1107        ])) as ArrayRef;
1108        assert_regex_scan_masks(
1109            &plain,
1110            [
1111                vec![true, false, false, false],
1112                vec![true, true, false, false],
1113                vec![false, true, true, false],
1114                vec![false, false, true, false],
1115            ],
1116        );
1117
1118        let dictionary = DictionaryArray::new(
1119            datatypes::arrow::array::UInt32Array::from(vec![
1120                Some(0),
1121                Some(1),
1122                Some(2),
1123                None,
1124                Some(3),
1125            ]),
1126            Arc::new(datatypes::arrow::array::StringArray::from(vec![
1127                Some("api"),
1128                Some("API"),
1129                Some("db"),
1130                None,
1131            ])),
1132        );
1133        let raw =
1134            regexp_is_match_dictionary(&dictionary, Some(&CompiledRegex::new("^api$").unwrap()))
1135                .unwrap();
1136        assert!(raw.is_null(3)); // null dictionary key
1137        assert!(raw.is_null(4)); // non-null key referencing a null dictionary value
1138
1139        let dictionary = Arc::new(dictionary) as ArrayRef;
1140        assert_regex_scan_masks(
1141            &dictionary,
1142            [
1143                vec![true, false, false, false, false],
1144                vec![true, true, false, false, false],
1145                vec![false, true, true, false, false],
1146                vec![false, false, true, false, false],
1147            ],
1148        );
1149
1150        let negative = regex_evaluator(Operator::RegexNotMatch);
1151        assert!(!negative.evaluate_scalar(&ScalarValue::Utf8(None)).unwrap());
1152    }
1153
1154    fn assert_regex_scan_masks(input: &ArrayRef, expected: [Vec<bool>; 4]) {
1155        for (op, expected) in [
1156            Operator::RegexMatch,
1157            Operator::RegexIMatch,
1158            Operator::RegexNotMatch,
1159            Operator::RegexNotIMatch,
1160        ]
1161        .into_iter()
1162        .zip(expected)
1163        {
1164            assert_eq!(
1165                BooleanBuffer::from(expected),
1166                regex_evaluator(op).evaluate_array(input).unwrap(),
1167                "{op:?}"
1168            );
1169        }
1170    }
1171
1172    fn regex_evaluator(op: Operator) -> SimpleFilterEvaluator {
1173        let expr = Expr::BinaryExpr(BinaryExpr {
1174            left: Box::new(Expr::Column(Column::from_name("host"))),
1175            op,
1176            right: Box::new("^api$".lit()),
1177        });
1178        SimpleFilterEvaluator::try_new(&expr).unwrap()
1179    }
1180
1181    /// The sql expr `col =~ pattern` as the scan sees it, so the kernels run through the same
1182    /// predicate an evaluator builds.
1183    fn regex_column_evaluator(pattern: &str, op: Operator) -> SimpleFilterEvaluator {
1184        let expr = Expr::BinaryExpr(BinaryExpr {
1185            left: Box::new(Expr::Column(Column::from_name("host"))),
1186            op,
1187            right: Box::new(pattern.lit()),
1188        });
1189        SimpleFilterEvaluator::try_new(&expr).unwrap()
1190    }
1191
1192    /// Reusing one cache must not change an answer: compare with `regex::Regex::is_match` over
1193    /// anchors, flags, empty matches, alternations and multi-byte UTF-8.
1194    #[test]
1195    fn test_compiled_regex_agrees_with_regex_crate() {
1196        let patterns = [
1197            "^",
1198            "$",
1199            "^$",
1200            ".*",
1201            "host.*",
1202            "(?i)host",
1203            "(?i)HOST-?A",
1204            "a|ab",
1205            "(?:ab)+",
1206            "a{2,3}",
1207            "\\bdb\\b",
1208            "[[:alpha:]]+",
1209            "\\p{Greek}",
1210            "日",
1211            "^.$",
1212            "(?s).",
1213            "(?m)^db$",
1214            "x?",
1215            "[^a-z]",
1216            "\\d+",
1217            "^\\s*$",
1218        ];
1219        let values = [
1220            "",
1221            "host-a",
1222            "HOST-A",
1223            "Host-a",
1224            "db",
1225            "a",
1226            "aa",
1227            "aaa",
1228            "ab",
1229            "abab",
1230            " ",
1231            "\t",
1232            "42",
1233            "host-42",
1234            "日",
1235            "日本語",
1236            "αβ",
1237            "x",
1238            "\n",
1239            "a\ndb\n",
1240            "-",
1241            "A",
1242        ];
1243
1244        for pattern in patterns {
1245            let compiled = CompiledRegex::new(pattern).unwrap();
1246            let reference = Regex::new(pattern).unwrap();
1247            for value in values {
1248                assert_eq!(
1249                    reference.is_match(value),
1250                    compiled.is_match(value).unwrap(),
1251                    "{pattern:?} on {value:?}"
1252                );
1253            }
1254        }
1255    }
1256
1257    /// A compiled regex and the evaluator holding it are shared by the threads evaluating one
1258    /// plan: both have to be `Send + Sync` without `unsafe`.
1259    #[test]
1260    fn test_compiled_regex_is_send_and_sync() {
1261        fn assert_send_sync<T: Send + Sync>() {}
1262
1263        assert_send_sync::<CompiledRegex>();
1264        assert_send_sync::<SimpleFilterEvaluator>();
1265    }
1266
1267    /// Asserts the kernel answers exactly what arrow's own kernel answers for `array`.
1268    fn assert_kernel_agrees_with_arrow<'a, S>(array: &'a S, pattern: &str)
1269    where
1270        &'a S: StringArrayType<'a>,
1271    {
1272        let expected =
1273            datatypes::compute::kernels::regexp::regexp_is_match_scalar(array, pattern, None)
1274                .unwrap();
1275        let compiled = compiled_or_match_all(pattern);
1276        let actual = regexp_is_match_scalar(array, compiled.as_ref()).unwrap();
1277
1278        assert_eq!(expected, actual, "{pattern:?}");
1279    }
1280
1281    /// Returns the compiled pattern, or `None` for the empty pattern, which matches every row and
1282    /// is how [`SimplePredicate::maybe_build_regex`] represents it.
1283    fn compiled_or_match_all(pattern: &str) -> Option<CompiledRegex> {
1284        (!pattern.is_empty()).then(|| CompiledRegex::new(pattern).unwrap())
1285    }
1286
1287    /// The array kernels agree with arrow's kernel row by row, including for `NULL`s and for
1288    /// sliced arrays whose values do not start at offset 0.
1289    #[test]
1290    fn test_regex_array_kernels_agree_with_arrow() {
1291        let values = vec![Some("host-a"), None, Some(""), Some("db"), Some("host-b")];
1292        let patterns = ["host.*", "^host-a$", "(?i)HOST.*", "^$", "日", ""];
1293
1294        let plain = StringArray::from(values.clone());
1295        let large = LargeStringArray::from(values.clone());
1296        let view = StringViewArray::from(values.clone());
1297        for pattern in patterns {
1298            assert_kernel_agrees_with_arrow(&plain, pattern);
1299            assert_kernel_agrees_with_arrow(&large, pattern);
1300            assert_kernel_agrees_with_arrow(&view, pattern);
1301
1302            // A slice: row 0 is `NULL` and the first value starts at a non-zero offset in the
1303            // values buffer, which the kernel must honour instead of assuming row 0 is offset 0.
1304            let sliced = plain.slice(1, 3);
1305            assert!(sliced.value_offsets()[0] > 0);
1306            assert!(sliced.is_null(0));
1307            assert_kernel_agrees_with_arrow(&sliced, pattern);
1308        }
1309    }
1310
1311    /// The dictionary kernel sees the same values as the scalar kernel, and therefore as arrow:
1312    /// a `NULL` key, a key pointing at a `NULL` dictionary value, and a sliced dictionary array.
1313    #[test]
1314    fn test_dictionary_kernel_agrees_with_the_scalar_kernel() {
1315        let values = Arc::new(StringArray::from(vec![
1316            Some("api"),
1317            Some("API"),
1318            Some("db"),
1319            None,
1320        ]));
1321        let keys = UInt32Array::from(vec![Some(0), Some(1), Some(3), None, Some(2)]);
1322        let dictionary = DictionaryArray::new(keys, values);
1323        let patterns = ["^api$", "(?i)^api$", "db", "日", ""];
1324
1325        for pattern in patterns {
1326            assert_dictionary_kernel_agrees_with_the_scalar_kernel(&dictionary, pattern);
1327            // A slice whose rows are a key pointing at a `NULL` dictionary value and then a
1328            // `NULL` key. Both are SQL `NULL`, which only the logical nulls of a dictionary show.
1329            let sliced = dictionary.slice(1, 3);
1330            let logical_nulls = sliced.logical_nulls().unwrap();
1331            assert!(!sliced.is_null(1));
1332            assert!(logical_nulls.is_null(1));
1333            assert!(logical_nulls.is_null(2));
1334            assert_dictionary_kernel_agrees_with_the_scalar_kernel(&sliced, pattern);
1335        }
1336    }
1337
1338    /// Asserts the dictionary kernel answers what the scalar kernel answers on the values the
1339    /// dictionary stands for. Arrow's own kernel takes no dictionary, but
1340    /// [`test_regex_array_kernels_agree_with_arrow`] pins the scalar kernel to it.
1341    fn assert_dictionary_kernel_agrees_with_the_scalar_kernel(
1342        dictionary: &DictionaryArray<UInt32Type>,
1343        pattern: &str,
1344    ) {
1345        let values = dictionary
1346            .values()
1347            .as_any()
1348            .downcast_ref::<StringArray>()
1349            .unwrap();
1350        let nulls = dictionary.logical_nulls();
1351        let materialized: StringArray = (0..dictionary.len())
1352            .map(|i: usize| {
1353                let is_null = nulls.as_ref().is_some_and(|nulls| nulls.is_null(i));
1354                (!is_null).then(|| {
1355                    values
1356                        .value(dictionary.keys().values()[i] as usize)
1357                        .to_string()
1358                })
1359            })
1360            .collect();
1361
1362        let compiled = compiled_or_match_all(pattern);
1363        let expected = regexp_is_match_scalar(&materialized, compiled.as_ref()).unwrap();
1364        let actual = regexp_is_match_dictionary(dictionary, compiled.as_ref()).unwrap();
1365
1366        assert_same_boolean_rows(&expected, &actual, pattern);
1367    }
1368
1369    /// Asserts two boolean arrays hold the same value in every row, `NULL` included.
1370    fn assert_same_boolean_rows(expected: &BooleanArray, actual: &BooleanArray, pattern: &str) {
1371        assert_eq!(expected.len(), actual.len(), "{pattern:?}");
1372        for i in 0..expected.len() {
1373            assert_eq!(
1374                (expected.is_valid(i), expected.value(i)),
1375                (actual.is_valid(i), actual.value(i)),
1376                "{pattern:?} row {i}"
1377            );
1378        }
1379    }
1380
1381    /// A scan evaluates one expression per array, so the cache is acquired once per array and not
1382    /// once per row: 100 arrays of 3 rows cost 100 acquisitions, each searching 3 values.
1383    #[test]
1384    #[allow(clippy::print_stdout)]
1385    fn test_evaluator_borrows_the_cache_once_per_array() {
1386        let evaluator = regex_column_evaluator("api|db", Operator::RegexMatch);
1387        let SimplePredicate::Comparison {
1388            regex: Some(compiled),
1389            ..
1390        } = &evaluator.predicate
1391        else {
1392            panic!("the evaluator holds a regex");
1393        };
1394        assert_eq!(0, compiled.cache_acquisitions());
1395        assert_eq!(0, compiled.compilations());
1396
1397        let array = Arc::new(StringArray::from(vec![Some("api"), None, Some("db")])) as ArrayRef;
1398        let cloned = evaluator.clone();
1399        for arrays in 1..=100 {
1400            let current = if arrays % 2 == 0 { &cloned } else { &evaluator };
1401            assert_eq!(
1402                BooleanBuffer::from(vec![true, false, true]),
1403                current.evaluate_array(&array).unwrap()
1404            );
1405            assert_eq!(
1406                arrays,
1407                compiled.cache_acquisitions(),
1408                "{arrays} arrays must cost {arrays} cache acquisitions, not one per row"
1409            );
1410            assert_eq!(1, compiled.compilations());
1411        }
1412        println!(
1413            "arrays: 100; cache acquisitions: {}; compilations: {}",
1414            compiled.cache_acquisitions(),
1415            compiled.compilations()
1416        );
1417    }
1418
1419    /// Invalid patterns are errors at evaluation, not silently rejected during construction.
1420    #[test]
1421    fn test_invalid_regex_is_reported_on_first_evaluation() {
1422        let evaluator = regex_column_evaluator("a(b", Operator::RegexMatch);
1423        let SimplePredicate::Comparison {
1424            regex: Some(compiled),
1425            ..
1426        } = &evaluator.predicate
1427        else {
1428            panic!("missing regex");
1429        };
1430        let array = Arc::new(StringArray::from(vec!["abc"])) as ArrayRef;
1431        assert_eq!(0, compiled.compilations());
1432        for _ in 0..2 {
1433            assert!(evaluator.evaluate_array(&array).is_err());
1434        }
1435        assert_eq!(1, compiled.compilations());
1436        assert_eq!(0, compiled.cache_acquisitions());
1437    }
1438
1439    /// Empty patterns use the match-all branch without compiling or checking out a cache.
1440    #[test]
1441    fn test_empty_regex_does_not_initialize_a_cache() {
1442        let evaluator = regex_column_evaluator("", Operator::RegexMatch);
1443        let SimplePredicate::Comparison { regex, .. } = &evaluator.predicate else {
1444            panic!("missing comparison");
1445        };
1446        assert!(regex.is_none());
1447        let array = Arc::new(StringArray::from(vec![Some(""), None, Some("日本")])) as ArrayRef;
1448        for _ in 0..100 {
1449            assert_eq!(
1450                BooleanBuffer::from(vec![true, false, true]),
1451                evaluator.evaluate_array(&array).unwrap()
1452            );
1453        }
1454    }
1455
1456    /// Dictionary arrays also check out exactly one cache, including for null keys and values.
1457    #[test]
1458    #[allow(clippy::print_stdout)]
1459    fn test_dictionary_evaluator_borrows_cache_once_per_array() {
1460        let evaluator = regex_column_evaluator("api|db", Operator::RegexNotMatch);
1461        let SimplePredicate::Comparison {
1462            regex: Some(compiled),
1463            ..
1464        } = &evaluator.predicate
1465        else {
1466            panic!("missing regex");
1467        };
1468        let array = Arc::new(DictionaryArray::new(
1469            UInt32Array::from(vec![Some(0), None, Some(1), Some(2)]),
1470            Arc::new(StringArray::from(vec![Some("api"), None, Some("other")])),
1471        )) as ArrayRef;
1472        for _ in 0..100 {
1473            assert_eq!(
1474                BooleanBuffer::from(vec![false, false, false, true]),
1475                evaluator.evaluate_array(&array).unwrap()
1476            );
1477        }
1478        assert_eq!(1, compiled.compilations());
1479        assert_eq!(100, compiled.cache_acquisitions());
1480        println!(
1481            "dictionary arrays: 100; cache acquisitions: {}; compilations: {}",
1482            compiled.cache_acquisitions(),
1483            compiled.compilations()
1484        );
1485    }
1486
1487    /// Several arrays can be in flight at once because a pool hands out one independent cache per
1488    /// checkout. A single `Mutex<meta::Cache>` held for the array loop could not hand out a second
1489    /// cache before the first array finished, so this test needs no timing.
1490    #[test]
1491    fn test_cache_pool_hands_out_independent_caches() {
1492        let compiled = CompiledRegex::new("^api$").unwrap();
1493        let program = compiled.program().unwrap();
1494        let mut caches: Vec<_> = (0..8).map(|_| compiled.get_cache(program)).collect();
1495
1496        // Every cache is usable while all the others are still checked out.
1497        for cache in &mut caches {
1498            assert!(program.is_match_with(cache, "api"));
1499            assert!(!program.is_match_with(cache, "db"));
1500        }
1501        assert_eq!(8, compiled.cache_acquisitions());
1502        assert_eq!(1, compiled.compilations());
1503    }
1504
1505    /// Prove eight evaluations reach the array kernel with their own checked-out cache at the
1506    /// same time. A shared mutex held over the loop cannot pass the barrier and times out.
1507    #[test]
1508    #[allow(clippy::print_stdout)]
1509    fn test_evaluator_cache_pool_allows_parallel_arrays() {
1510        use std::sync::{Condvar, Mutex};
1511        use std::time::Duration;
1512
1513        const THREADS: usize = 8;
1514        const ARRAYS_PER_THREAD: usize = 5;
1515        let evaluator = Arc::new(regex_column_evaluator("^api$", Operator::RegexMatch));
1516        let SimplePredicate::Comparison {
1517            regex: Some(compiled),
1518            ..
1519        } = &evaluator.predicate
1520        else {
1521            panic!("missing regex");
1522        };
1523        let rendezvous = Arc::new((Mutex::new((0usize, 0usize, false)), Condvar::new()));
1524        let in_kernel = Arc::clone(&rendezvous);
1525        assert!(
1526            compiled
1527                .after_cache_acquired
1528                .set(Arc::new(move || {
1529                    let (lock, wake) = &*in_kernel;
1530                    let mut state = lock.lock().unwrap();
1531                    if state.2 {
1532                        return;
1533                    }
1534                    state.0 += 1;
1535                    state.1 = state.1.max(state.0);
1536                    if state.0 == THREADS {
1537                        state.2 = true;
1538                        wake.notify_all();
1539                    } else {
1540                        let (guard, _) = wake
1541                            .wait_timeout_while(state, Duration::from_secs(5), |state| !state.2)
1542                            .unwrap();
1543                        state = guard;
1544                    }
1545                    state.0 -= 1;
1546                }))
1547                .is_ok()
1548        );
1549        let array = Arc::new(StringArray::from(vec![Some("api"), None, Some("db")])) as ArrayRef;
1550        std::thread::scope(|scope| {
1551            for _ in 0..THREADS {
1552                let evaluator = Arc::clone(&evaluator);
1553                let array = Arc::clone(&array);
1554                scope.spawn(move || {
1555                    for _ in 0..ARRAYS_PER_THREAD {
1556                        assert_eq!(
1557                            BooleanBuffer::from(vec![true, false, false]),
1558                            evaluator.evaluate_array(&array).unwrap()
1559                        );
1560                    }
1561                });
1562            }
1563        });
1564        let state = rendezvous.0.lock().unwrap();
1565        assert_eq!(
1566            THREADS, state.1,
1567            "all threads must hold a cache concurrently"
1568        );
1569        assert_eq!(1, compiled.compilations());
1570        assert_eq!(THREADS * ARRAYS_PER_THREAD, compiled.cache_acquisitions());
1571        println!(
1572            "peak concurrent kernels: {}; compilations: {}; cache acquisitions: {}",
1573            state.1,
1574            compiled.compilations(),
1575            compiled.cache_acquisitions()
1576        );
1577    }
1578
1579    /// One evaluator is evaluated by several threads at once during a scan, each borrowing its own
1580    /// cache.
1581    #[test]
1582    fn test_evaluator_matches_from_several_threads() {
1583        let evaluator = Arc::new(regex_column_evaluator("^api$", Operator::RegexMatch));
1584        let array = Arc::new(StringArray::from(vec![
1585            Some("api"),
1586            Some("API"),
1587            None,
1588            Some("db"),
1589        ])) as ArrayRef;
1590        let expected = BooleanBuffer::from(vec![true, false, false, false]);
1591
1592        std::thread::scope(|scope| {
1593            for _ in 0..8 {
1594                let evaluator = Arc::clone(&evaluator);
1595                let array = Arc::clone(&array);
1596                let expected = expected.clone();
1597                scope.spawn(move || {
1598                    for _ in 0..100 {
1599                        assert_eq!(expected, evaluator.evaluate_array(&array).unwrap());
1600                    }
1601                });
1602            }
1603        });
1604    }
1605}