diff --git a/Cargo.lock b/Cargo.lock index 8b0881a67f4..a1759e00ab6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2857,6 +2857,7 @@ dependencies = [ "jsonb", "pin-project", "regex", + "regex-automata", "serde", "serde_json", "snafu 0.8.6", diff --git a/src/common/recordbatch/Cargo.toml b/src/common/recordbatch/Cargo.toml index 59929ba3477..63ef9c5d9ef 100644 --- a/src/common/recordbatch/Cargo.toml +++ b/src/common/recordbatch/Cargo.toml @@ -22,6 +22,7 @@ futures.workspace = true jsonb.workspace = true pin-project.workspace = true regex.workspace = true +regex-automata.workspace = true serde.workspace = true serde_json.workspace = true snafu.workspace = true diff --git a/src/common/recordbatch/src/filter.rs b/src/common/recordbatch/src/filter.rs index 3d8d7da7051..9f1bcb48131 100644 --- a/src/common/recordbatch/src/filter.rs +++ b/src/common/recordbatch/src/filter.rs @@ -37,7 +37,7 @@ use datatypes::value::Value; use datatypes::vectors::VectorRef; use snafu::ResultExt; -pub use self::predicate::{regexp_is_match_dictionary, regexp_is_match_scalar}; +pub use self::predicate::{CompiledRegex, regexp_is_match_dictionary, regexp_is_match_scalar}; pub use self::timestamp::timestamp_scalar_value; use crate::error::{Result, ToArrowScalarSnafu}; use crate::filter::predicate::SimplePredicate; @@ -51,8 +51,8 @@ pub struct MetadataFilter { } impl MetadataFilter { - /// Compiles supported conjuncts once for reuse across scan stages. OR is - /// never split: an unknown alternative might match the candidate. + /// Builds supported conjuncts once for reuse across scan stages; regex patterns compile on + /// first evaluation. OR is never split: an unknown alternative might match the candidate. pub fn new(expressions: &[Expr]) -> Self { Self { filters: expressions @@ -77,7 +77,7 @@ impl MetadataFilter { } } -/// Evaluates supported single-column predicates with precompiled regular expressions. +/// Evaluates supported single-column predicates with lazily compiled regular expressions. /// Compound predicates preserve SQL null semantics until conversion to a scan mask. /// Float comparisons treat `-0.0` and `+0.0` as equal, as DataFusion does. #[derive(Debug, Clone)] diff --git a/src/common/recordbatch/src/filter/predicate.rs b/src/common/recordbatch/src/filter/predicate.rs index d9827004b53..ac1b4ed7362 100644 --- a/src/common/recordbatch/src/filter/predicate.rs +++ b/src/common/recordbatch/src/filter/predicate.rs @@ -12,7 +12,12 @@ // See the License for the specific language governing permissions and // limitations under the License. -//! Predicate recognition, execution, and precompiled regular expressions. +//! Predicate recognition, execution, and lazily compiled regular expressions. + +use std::fmt; +#[cfg(test)] +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Arc, OnceLock}; use datafusion::logical_expr::{Expr, Operator}; use datafusion_common::ScalarValue; @@ -27,7 +32,9 @@ use datatypes::arrow::array::{ use datatypes::arrow::datatypes::{DataType, UInt32Type}; use datatypes::arrow::error::ArrowError; use datatypes::compute::or_kleene; -use regex::Regex; +use regex_automata::Input; +use regex_automata::meta; +use regex_automata::util::pool::{Pool, PoolGuard}; use snafu::ResultExt; use crate::error::{ArrowComputeSnafu, Result, UnsupportedOperationSnafu}; @@ -37,7 +44,7 @@ pub(crate) enum SimplePredicate { Comparison { literal: Scalar, op: Operator, - regex: Option, + regex: Option>, regex_negative: bool, }, OrEqChain { @@ -168,7 +175,7 @@ impl SimplePredicate { | Operator::RegexIMatch | Operator::RegexNotMatch | Operator::RegexNotIMatch => { - Self::regex_match(input, regex.as_ref(), *regex_negative) + Self::regex_match(input, regex.as_deref(), *regex_negative) } _ => { return UnsupportedOperationSnafu { @@ -213,15 +220,17 @@ impl SimplePredicate { /// /// Returns `Err` if /// - the value is not a string - /// - the regex pattern is invalid /// /// The regex is `None` if /// - the operator is not a regex operator /// - the pattern is empty + /// + /// A non-empty pattern is stored without compiling. The first evaluation compiles it and + /// initializes its cache pool; pruning can construct the evaluator without paying that cost. fn maybe_build_regex( operator: Operator, value: &ScalarValue, - ) -> Result<(Option, bool), ArrowError> { + ) -> Result<(Option>, bool), ArrowError> { let (ignore_case, negative) = match operator { Operator::RegexMatch => (false, false), Operator::RegexIMatch => (true, false), @@ -241,17 +250,13 @@ impl SimplePredicate { if pattern.is_empty() { Ok((None, negative)) } else { - Regex::new(pattern.as_str()) - .map_err(|e| { - ArrowError::ComputeError(format!("Regular expression did not compile: {e:?}")) - }) - .map(|regex| (Some(regex), negative)) + CompiledRegex::new(&pattern).map(|regex| (Some(Arc::new(regex)), negative)) } } fn regex_match( input: &impl Datum, - regex: Option<&Regex>, + regex: Option<&CompiledRegex>, negative: bool, ) -> std::result::Result { let array = input.get().0; @@ -281,12 +286,125 @@ impl SimplePredicate { } } +/// A regular expression compiled on first use with a pool of per-array scratch spaces. +/// +/// `search_half_with` bypasses the regex's internal per-search cache pool. Each array borrows one +/// cache from our pool and uses it for all its rows; different arrays can search concurrently. +/// The compilation uses the same `meta::Regex` defaults as [`regex::Regex`]. +pub struct CompiledRegex { + pattern: String, + // Cache compilation errors as well: a malformed pattern must not be rebuilt per batch. + compiled: OnceLock>, + #[cfg(test)] + compilations: AtomicUsize, + #[cfg(test)] + cache_acquisitions: AtomicUsize, + // The hook runs after checkout and before entering the array loop, without holding a pool lock. + #[cfg(test)] + after_cache_acquired: OnceLock>, +} + +type CacheFactory = Box meta::Cache + Send + Sync>; +type CachePool = Pool; + +struct RegexProgram { + regex: Arc, + caches: CachePool, +} + +impl CompiledRegex { + /// Stores `pattern`. Compilation and syntax errors are deferred until first evaluation. + /// + /// Returns `Ok` for compatibility with the prior eager constructor. + pub fn new(pattern: &str) -> Result { + Ok(Self { + pattern: pattern.to_string(), + compiled: OnceLock::new(), + #[cfg(test)] + compilations: AtomicUsize::new(0), + #[cfg(test)] + cache_acquisitions: AtomicUsize::new(0), + #[cfg(test)] + after_cache_acquired: OnceLock::new(), + }) + } + + /// Compiles the pattern at most once, even if several arrays first evaluate it concurrently. + fn program(&self) -> Result<&RegexProgram, ArrowError> { + self.compiled + .get_or_init(|| { + #[cfg(test)] + self.compilations.fetch_add(1, Ordering::Relaxed); + let regex = Arc::new( + meta::Regex::new(&self.pattern) + .map_err(|e| format!("Regular expression did not compile: {e:?}"))?, + ); + let pooled_regex = Arc::clone(®ex); + let factory: CacheFactory = Box::new(move || pooled_regex.create_cache()); + Ok(RegexProgram { + regex, + caches: Pool::new(factory), + }) + }) + .as_ref() + .map_err(|message| ArrowError::ComputeError(message.clone())) + } + + /// Returns whether `value` matches, or a compilation error for an invalid pattern. + pub fn is_match(&self, value: &str) -> Result { + let program = self.program()?; + let mut cache = self.get_cache(program); + Ok(program.is_match_with(&mut cache, value)) + } + + /// Checks out one cache; its guard returns it to the pool when the array loop exits. + fn get_cache<'a>(&self, program: &'a RegexProgram) -> PoolGuard<'a, meta::Cache, CacheFactory> { + let cache = program.caches.get(); + #[cfg(test)] + { + self.cache_acquisitions.fetch_add(1, Ordering::Relaxed); + if let Some(hook) = self.after_cache_acquired.get() { + hook(); + } + } + cache + } + + #[cfg(test)] + fn cache_acquisitions(&self) -> usize { + self.cache_acquisitions.load(Ordering::Relaxed) + } + + #[cfg(test)] + fn compilations(&self) -> usize { + self.compilations.load(Ordering::Relaxed) + } +} + +impl RegexProgram { + fn is_match_with(&self, cache: &mut meta::Cache, value: &str) -> bool { + self.regex + .search_half_with(cache, &Input::new(value).earliest(true)) + .is_some() + } +} + +impl fmt::Debug for CompiledRegex { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + // Expose initialization state, not the (potentially large) program or cache pool. + f.debug_struct("CompiledRegex") + .field("pattern", &self.pattern) + .field("initialized", &self.compiled.get().is_some()) + .finish_non_exhaustive() + } +} + /// The same as arrow [regexp_is_match_scalar()](datatypes::compute::kernels::regexp::regexp_is_match_scalar()) -/// with pre-compiled regex. +/// with a reusable, lazily compiled regex. /// See for the implementation details. pub fn regexp_is_match_scalar<'a, S>( array: &'a S, - regex: Option<&Regex>, + regex: Option<&CompiledRegex>, ) -> Result where &'a S: StringArrayType<'a>, @@ -295,9 +413,11 @@ where let mut result = BooleanBufferBuilder::new(array.len()); if let Some(re) = regex { + let program = re.program()?; + // One checkout for the entire array. The guard returns the cache on drop. + let mut cache = re.get_cache(program); for i in 0..array.len() { - let value = array.value(i); - result.append(re.is_match(value)); + result.append(program.is_match_with(&mut cache, array.value(i))); } } else { result.append_n(array.len(), true); @@ -323,7 +443,7 @@ where /// Iterates through dictionary keys to get string values and applies regex matching. pub fn regexp_is_match_dictionary( dict_array: &DictionaryArray, - regex: Option<&Regex>, + regex: Option<&CompiledRegex>, ) -> Result { // Get the string values from the dictionary let string_values = dict_array @@ -340,6 +460,9 @@ pub fn regexp_is_match_dictionary( let mut result = BooleanBufferBuilder::new(dict_array.len()); if let Some(re) = regex { + let program = re.program()?; + // One checkout for the entire array, as in `regexp_is_match_scalar`. + let mut cache = re.get_cache(program); let keys = dict_array.keys().values(); for i in 0..dict_array.len() { if logical_nulls.as_ref().is_some_and(|nulls| nulls.is_null(i)) { @@ -347,7 +470,7 @@ pub fn regexp_is_match_dictionary( } else { let key = keys[i] as usize; let string_value = string_values.value(key); - result.append(re.is_match(string_value)); + result.append(program.is_match_with(&mut cache, string_value)); } } } else { @@ -381,12 +504,17 @@ mod tests { use datafusion_common::arrow::array::ArrayRef; use datafusion_common::arrow::buffer::BooleanBuffer; use datafusion_common::{Column, DFSchema, ScalarValue}; - use datatypes::arrow::array::{Array, DictionaryArray, RecordBatch}; + use datatypes::arrow::array::{ + Array, BooleanArray, DictionaryArray, LargeStringArray, RecordBatch, StringArray, + StringArrayType, StringViewArray, UInt32Array, + }; use datatypes::arrow::datatypes::{DataType, Field, Schema, TimeUnit, UInt32Type}; use datatypes::value::Value; use regex::Regex; - use crate::filter::predicate::{SimplePredicate, regexp_is_match_dictionary}; + use crate::filter::predicate::{ + CompiledRegex, SimplePredicate, regexp_is_match_dictionary, regexp_is_match_scalar, + }; use crate::filter::{SimpleFilterEvaluator, batch_filter}; #[test] @@ -853,7 +981,7 @@ mod tests { .unwrap(); assert!(regex.is_some()); assert!(!negative); - assert!(regex.unwrap().is_match("axxb")); + assert!(regex.unwrap().is_match("axxb").unwrap()); // Test case for RegexIMatch (case insensitive, non-negative) let (regex, negative) = SimplePredicate::maybe_build_regex( @@ -863,7 +991,7 @@ mod tests { .unwrap(); assert!(regex.is_some()); assert!(!negative); - assert!(regex.unwrap().is_match("AxxB")); + assert!(regex.unwrap().is_match("AxxB").unwrap()); // Test case for RegexNotMatch (case sensitive, negative) let (regex, negative) = SimplePredicate::maybe_build_regex( @@ -901,12 +1029,20 @@ mod tests { assert!(regex.is_none()); assert!(!negative); - // Test with invalid regex pattern + // Invalid regex patterns are rejected on first evaluation, not at construction. let result = SimplePredicate::maybe_build_regex( Operator::RegexMatch, &ScalarValue::Utf8(Some("a(b".to_string())), ); - assert!(result.is_err()); + let invalid = result.unwrap().0.unwrap(); + assert_eq!(0, invalid.compilations()); + assert!(invalid.is_match("anything").is_err()); + assert!(invalid.is_match("anything").is_err()); + assert_eq!( + 1, + invalid.compilations(), + "invalid patterns are compiled only once" + ); // Test with non-string value let result = SimplePredicate::maybe_build_regex( @@ -934,7 +1070,7 @@ mod tests { let dict_array = builder.finish(); // Test regex that matches "apple" - let regex = regex::Regex::new(r"app.*").unwrap(); + let regex = CompiledRegex::new(r"app.*").unwrap(); let result = regexp_is_match_dictionary(&dict_array, Some(®ex)).unwrap(); // Should match indices 0 and 2 (both "apple") @@ -945,7 +1081,7 @@ mod tests { assert!(!result.value(3)); // "cherry" // Test regex that matches "banana" - let regex2 = regex::Regex::new(r"ban.*").unwrap(); + let regex2 = CompiledRegex::new(r"ban.*").unwrap(); let result2 = regexp_is_match_dictionary(&dict_array, Some(®ex2)).unwrap(); assert!(!result2.value(0)); // "apple" @@ -995,7 +1131,8 @@ mod tests { ])), ); let raw = - regexp_is_match_dictionary(&dictionary, Some(&Regex::new("^api$").unwrap())).unwrap(); + regexp_is_match_dictionary(&dictionary, Some(&CompiledRegex::new("^api$").unwrap())) + .unwrap(); assert!(raw.is_null(3)); // null dictionary key assert!(raw.is_null(4)); // non-null key referencing a null dictionary value @@ -1040,4 +1177,429 @@ mod tests { }); SimpleFilterEvaluator::try_new(&expr).unwrap() } + + /// The sql expr `col =~ pattern` as the scan sees it, so the kernels run through the same + /// predicate an evaluator builds. + fn regex_column_evaluator(pattern: &str, op: Operator) -> SimpleFilterEvaluator { + let expr = Expr::BinaryExpr(BinaryExpr { + left: Box::new(Expr::Column(Column::from_name("host"))), + op, + right: Box::new(pattern.lit()), + }); + SimpleFilterEvaluator::try_new(&expr).unwrap() + } + + /// Reusing one cache must not change an answer: compare with `regex::Regex::is_match` over + /// anchors, flags, empty matches, alternations and multi-byte UTF-8. + #[test] + fn test_compiled_regex_agrees_with_regex_crate() { + let patterns = [ + "^", + "$", + "^$", + ".*", + "host.*", + "(?i)host", + "(?i)HOST-?A", + "a|ab", + "(?:ab)+", + "a{2,3}", + "\\bdb\\b", + "[[:alpha:]]+", + "\\p{Greek}", + "日", + "^.$", + "(?s).", + "(?m)^db$", + "x?", + "[^a-z]", + "\\d+", + "^\\s*$", + ]; + let values = [ + "", + "host-a", + "HOST-A", + "Host-a", + "db", + "a", + "aa", + "aaa", + "ab", + "abab", + " ", + "\t", + "42", + "host-42", + "日", + "日本語", + "αβ", + "x", + "\n", + "a\ndb\n", + "-", + "A", + ]; + + for pattern in patterns { + let compiled = CompiledRegex::new(pattern).unwrap(); + let reference = Regex::new(pattern).unwrap(); + for value in values { + assert_eq!( + reference.is_match(value), + compiled.is_match(value).unwrap(), + "{pattern:?} on {value:?}" + ); + } + } + } + + /// A compiled regex and the evaluator holding it are shared by the threads evaluating one + /// plan: both have to be `Send + Sync` without `unsafe`. + #[test] + fn test_compiled_regex_is_send_and_sync() { + fn assert_send_sync() {} + + assert_send_sync::(); + assert_send_sync::(); + } + + /// Asserts the kernel answers exactly what arrow's own kernel answers for `array`. + fn assert_kernel_agrees_with_arrow<'a, S>(array: &'a S, pattern: &str) + where + &'a S: StringArrayType<'a>, + { + let expected = + datatypes::compute::kernels::regexp::regexp_is_match_scalar(array, pattern, None) + .unwrap(); + let compiled = compiled_or_match_all(pattern); + let actual = regexp_is_match_scalar(array, compiled.as_ref()).unwrap(); + + assert_eq!(expected, actual, "{pattern:?}"); + } + + /// Returns the compiled pattern, or `None` for the empty pattern, which matches every row and + /// is how [`SimplePredicate::maybe_build_regex`] represents it. + fn compiled_or_match_all(pattern: &str) -> Option { + (!pattern.is_empty()).then(|| CompiledRegex::new(pattern).unwrap()) + } + + /// The array kernels agree with arrow's kernel row by row, including for `NULL`s and for + /// sliced arrays whose values do not start at offset 0. + #[test] + fn test_regex_array_kernels_agree_with_arrow() { + let values = vec![Some("host-a"), None, Some(""), Some("db"), Some("host-b")]; + let patterns = ["host.*", "^host-a$", "(?i)HOST.*", "^$", "日", ""]; + + let plain = StringArray::from(values.clone()); + let large = LargeStringArray::from(values.clone()); + let view = StringViewArray::from(values.clone()); + for pattern in patterns { + assert_kernel_agrees_with_arrow(&plain, pattern); + assert_kernel_agrees_with_arrow(&large, pattern); + assert_kernel_agrees_with_arrow(&view, pattern); + + // A slice: row 0 is `NULL` and the first value starts at a non-zero offset in the + // values buffer, which the kernel must honour instead of assuming row 0 is offset 0. + let sliced = plain.slice(1, 3); + assert!(sliced.value_offsets()[0] > 0); + assert!(sliced.is_null(0)); + assert_kernel_agrees_with_arrow(&sliced, pattern); + } + } + + /// The dictionary kernel sees the same values as the scalar kernel, and therefore as arrow: + /// a `NULL` key, a key pointing at a `NULL` dictionary value, and a sliced dictionary array. + #[test] + fn test_dictionary_kernel_agrees_with_the_scalar_kernel() { + let values = Arc::new(StringArray::from(vec![ + Some("api"), + Some("API"), + Some("db"), + None, + ])); + let keys = UInt32Array::from(vec![Some(0), Some(1), Some(3), None, Some(2)]); + let dictionary = DictionaryArray::new(keys, values); + let patterns = ["^api$", "(?i)^api$", "db", "日", ""]; + + for pattern in patterns { + assert_dictionary_kernel_agrees_with_the_scalar_kernel(&dictionary, pattern); + // A slice whose rows are a key pointing at a `NULL` dictionary value and then a + // `NULL` key. Both are SQL `NULL`, which only the logical nulls of a dictionary show. + let sliced = dictionary.slice(1, 3); + let logical_nulls = sliced.logical_nulls().unwrap(); + assert!(!sliced.is_null(1)); + assert!(logical_nulls.is_null(1)); + assert!(logical_nulls.is_null(2)); + assert_dictionary_kernel_agrees_with_the_scalar_kernel(&sliced, pattern); + } + } + + /// Asserts the dictionary kernel answers what the scalar kernel answers on the values the + /// dictionary stands for. Arrow's own kernel takes no dictionary, but + /// [`test_regex_array_kernels_agree_with_arrow`] pins the scalar kernel to it. + fn assert_dictionary_kernel_agrees_with_the_scalar_kernel( + dictionary: &DictionaryArray, + pattern: &str, + ) { + let values = dictionary + .values() + .as_any() + .downcast_ref::() + .unwrap(); + let nulls = dictionary.logical_nulls(); + let materialized: StringArray = (0..dictionary.len()) + .map(|i: usize| { + let is_null = nulls.as_ref().is_some_and(|nulls| nulls.is_null(i)); + (!is_null).then(|| { + values + .value(dictionary.keys().values()[i] as usize) + .to_string() + }) + }) + .collect(); + + let compiled = compiled_or_match_all(pattern); + let expected = regexp_is_match_scalar(&materialized, compiled.as_ref()).unwrap(); + let actual = regexp_is_match_dictionary(dictionary, compiled.as_ref()).unwrap(); + + assert_same_boolean_rows(&expected, &actual, pattern); + } + + /// Asserts two boolean arrays hold the same value in every row, `NULL` included. + fn assert_same_boolean_rows(expected: &BooleanArray, actual: &BooleanArray, pattern: &str) { + assert_eq!(expected.len(), actual.len(), "{pattern:?}"); + for i in 0..expected.len() { + assert_eq!( + (expected.is_valid(i), expected.value(i)), + (actual.is_valid(i), actual.value(i)), + "{pattern:?} row {i}" + ); + } + } + + /// A scan evaluates one expression per array, so the cache is acquired once per array and not + /// once per row: 100 arrays of 3 rows cost 100 acquisitions, each searching 3 values. + #[test] + #[allow(clippy::print_stdout)] + fn test_evaluator_borrows_the_cache_once_per_array() { + let evaluator = regex_column_evaluator("api|db", Operator::RegexMatch); + let SimplePredicate::Comparison { + regex: Some(compiled), + .. + } = &evaluator.predicate + else { + panic!("the evaluator holds a regex"); + }; + assert_eq!(0, compiled.cache_acquisitions()); + assert_eq!(0, compiled.compilations()); + + let array = Arc::new(StringArray::from(vec![Some("api"), None, Some("db")])) as ArrayRef; + let cloned = evaluator.clone(); + for arrays in 1..=100 { + let current = if arrays % 2 == 0 { &cloned } else { &evaluator }; + assert_eq!( + BooleanBuffer::from(vec![true, false, true]), + current.evaluate_array(&array).unwrap() + ); + assert_eq!( + arrays, + compiled.cache_acquisitions(), + "{arrays} arrays must cost {arrays} cache acquisitions, not one per row" + ); + assert_eq!(1, compiled.compilations()); + } + println!( + "arrays: 100; cache acquisitions: {}; compilations: {}", + compiled.cache_acquisitions(), + compiled.compilations() + ); + } + + /// Invalid patterns are errors at evaluation, not silently rejected during construction. + #[test] + fn test_invalid_regex_is_reported_on_first_evaluation() { + let evaluator = regex_column_evaluator("a(b", Operator::RegexMatch); + let SimplePredicate::Comparison { + regex: Some(compiled), + .. + } = &evaluator.predicate + else { + panic!("missing regex"); + }; + let array = Arc::new(StringArray::from(vec!["abc"])) as ArrayRef; + assert_eq!(0, compiled.compilations()); + for _ in 0..2 { + assert!(evaluator.evaluate_array(&array).is_err()); + } + assert_eq!(1, compiled.compilations()); + assert_eq!(0, compiled.cache_acquisitions()); + } + + /// Empty patterns use the match-all branch without compiling or checking out a cache. + #[test] + fn test_empty_regex_does_not_initialize_a_cache() { + let evaluator = regex_column_evaluator("", Operator::RegexMatch); + let SimplePredicate::Comparison { regex, .. } = &evaluator.predicate else { + panic!("missing comparison"); + }; + assert!(regex.is_none()); + let array = Arc::new(StringArray::from(vec![Some(""), None, Some("日本")])) as ArrayRef; + for _ in 0..100 { + assert_eq!( + BooleanBuffer::from(vec![true, false, true]), + evaluator.evaluate_array(&array).unwrap() + ); + } + } + + /// Dictionary arrays also check out exactly one cache, including for null keys and values. + #[test] + #[allow(clippy::print_stdout)] + fn test_dictionary_evaluator_borrows_cache_once_per_array() { + let evaluator = regex_column_evaluator("api|db", Operator::RegexNotMatch); + let SimplePredicate::Comparison { + regex: Some(compiled), + .. + } = &evaluator.predicate + else { + panic!("missing regex"); + }; + let array = Arc::new(DictionaryArray::new( + UInt32Array::from(vec![Some(0), None, Some(1), Some(2)]), + Arc::new(StringArray::from(vec![Some("api"), None, Some("other")])), + )) as ArrayRef; + for _ in 0..100 { + assert_eq!( + BooleanBuffer::from(vec![false, false, false, true]), + evaluator.evaluate_array(&array).unwrap() + ); + } + assert_eq!(1, compiled.compilations()); + assert_eq!(100, compiled.cache_acquisitions()); + println!( + "dictionary arrays: 100; cache acquisitions: {}; compilations: {}", + compiled.cache_acquisitions(), + compiled.compilations() + ); + } + + /// Several arrays can be in flight at once because a pool hands out one independent cache per + /// checkout. A single `Mutex` held for the array loop could not hand out a second + /// cache before the first array finished, so this test needs no timing. + #[test] + fn test_cache_pool_hands_out_independent_caches() { + let compiled = CompiledRegex::new("^api$").unwrap(); + let program = compiled.program().unwrap(); + let mut caches: Vec<_> = (0..8).map(|_| compiled.get_cache(program)).collect(); + + // Every cache is usable while all the others are still checked out. + for cache in &mut caches { + assert!(program.is_match_with(cache, "api")); + assert!(!program.is_match_with(cache, "db")); + } + assert_eq!(8, compiled.cache_acquisitions()); + assert_eq!(1, compiled.compilations()); + } + + /// Prove eight evaluations reach the array kernel with their own checked-out cache at the + /// same time. A shared mutex held over the loop cannot pass the barrier and times out. + #[test] + #[allow(clippy::print_stdout)] + fn test_evaluator_cache_pool_allows_parallel_arrays() { + use std::sync::{Condvar, Mutex}; + use std::time::Duration; + + const THREADS: usize = 8; + const ARRAYS_PER_THREAD: usize = 5; + let evaluator = Arc::new(regex_column_evaluator("^api$", Operator::RegexMatch)); + let SimplePredicate::Comparison { + regex: Some(compiled), + .. + } = &evaluator.predicate + else { + panic!("missing regex"); + }; + let rendezvous = Arc::new((Mutex::new((0usize, 0usize, false)), Condvar::new())); + let in_kernel = Arc::clone(&rendezvous); + assert!( + compiled + .after_cache_acquired + .set(Arc::new(move || { + let (lock, wake) = &*in_kernel; + let mut state = lock.lock().unwrap(); + if state.2 { + return; + } + state.0 += 1; + state.1 = state.1.max(state.0); + if state.0 == THREADS { + state.2 = true; + wake.notify_all(); + } else { + let (guard, _) = wake + .wait_timeout_while(state, Duration::from_secs(5), |state| !state.2) + .unwrap(); + state = guard; + } + state.0 -= 1; + })) + .is_ok() + ); + let array = Arc::new(StringArray::from(vec![Some("api"), None, Some("db")])) as ArrayRef; + std::thread::scope(|scope| { + for _ in 0..THREADS { + let evaluator = Arc::clone(&evaluator); + let array = Arc::clone(&array); + scope.spawn(move || { + for _ in 0..ARRAYS_PER_THREAD { + assert_eq!( + BooleanBuffer::from(vec![true, false, false]), + evaluator.evaluate_array(&array).unwrap() + ); + } + }); + } + }); + let state = rendezvous.0.lock().unwrap(); + assert_eq!( + THREADS, state.1, + "all threads must hold a cache concurrently" + ); + assert_eq!(1, compiled.compilations()); + assert_eq!(THREADS * ARRAYS_PER_THREAD, compiled.cache_acquisitions()); + println!( + "peak concurrent kernels: {}; compilations: {}; cache acquisitions: {}", + state.1, + compiled.compilations(), + compiled.cache_acquisitions() + ); + } + + /// One evaluator is evaluated by several threads at once during a scan, each borrowing its own + /// cache. + #[test] + fn test_evaluator_matches_from_several_threads() { + let evaluator = Arc::new(regex_column_evaluator("^api$", Operator::RegexMatch)); + let array = Arc::new(StringArray::from(vec![ + Some("api"), + Some("API"), + None, + Some("db"), + ])) as ArrayRef; + let expected = BooleanBuffer::from(vec![true, false, false, false]); + + std::thread::scope(|scope| { + for _ in 0..8 { + let evaluator = Arc::clone(&evaluator); + let array = Arc::clone(&array); + let expected = expected.clone(); + scope.spawn(move || { + for _ in 0..100 { + assert_eq!(expected, evaluator.evaluate_array(&array).unwrap()); + } + }); + } + }); + } } diff --git a/src/table/src/predicate.rs b/src/table/src/predicate.rs index b3cbf54e9a1..5e61b93a3dd 100644 --- a/src/table/src/predicate.rs +++ b/src/table/src/predicate.rs @@ -12,18 +12,24 @@ // See the License for the specific language governing permissions and // limitations under the License. +use std::fmt; +use std::hash::{Hash, Hasher}; use std::sync::Arc; use arc_swap::ArcSwap; +use common_recordbatch::DfRecordBatch; +use common_recordbatch::filter::SimpleFilterEvaluator; use common_telemetry::{debug, warn}; use common_time::Timestamp; use common_time::range::TimestampRange; use common_time::timestamp::TimeUnit; use datafusion::common::ScalarValue; +use datafusion::error::Result as DfResult; use datafusion::physical_optimizer::pruning::PruningPredicateBuilder; -use datafusion_common::ToDFSchema; use datafusion_common::pruning::PruningStatistics; use datafusion_common::tree_node::TreeNode; +use datafusion_common::{DFSchema, DataFusionError, ToDFSchema}; +use datafusion_expr::ColumnarValue; use datafusion_expr::expr::{Expr, InList, ScalarFunction}; use datafusion_expr::physical_planning_context::PhysicalPlanningContext; use datafusion_expr::{Between, BinaryExpr, Operator}; @@ -33,6 +39,8 @@ use datafusion_physical_expr::expressions::{ }; use datafusion_physical_expr::{PhysicalExpr, create_physical_expr}; use datatypes::arrow; +use datatypes::arrow::array::{Array, BooleanArray}; +use datatypes::arrow::datatypes::{DataType as ArrowDataType, Schema as ArrowSchema}; use datatypes::value::scalar_value_to_timestamp; use snafu::ResultExt; @@ -162,7 +170,14 @@ impl Predicate { .context(error::DatafusionSnafu) } - /// Builds a single physical expr according to provided schema. + /// Builds a single physical expr for a caller that *evaluates* it against record batches. + /// + /// Regex comparisons are rewritten into [`PrecompiledRegexExpr`] because + /// `create_physical_expr` builds a comparison that recompiles its pattern on every evaluation, + /// while a scan evaluates one physical expr per batch. + /// + /// Pruning must not use this: it never evaluates the expression, only folds it into column + /// statistics, so [`Self::to_pruning_physical_exprs`] keeps the plain comparison. pub fn to_physical_expr( expr: &Expr, schema: &arrow::datatypes::SchemaRef, @@ -176,27 +191,122 @@ impl Predicate { // we may reuse the `execution_props` from `SessionState` once we support // registering variables. let execution_props = &ExecutionProps::new(); + let planning_context = &PhysicalPlanningContext::default(); - create_physical_expr( + if let Some(physical) = Self::to_regex_physical_expr( expr, + schema, df_schema.as_ref(), execution_props, - &PhysicalPlanningContext::default(), - ) - .context(error::DatafusionSnafu) + planning_context, + ) { + return Ok(physical); + } + + Self::to_plain_physical_expr(expr, df_schema.as_ref()) } - /// Builds physical exprs according to provided schema. - pub fn to_physical_exprs( + /// Builds the physical expr `create_physical_expr` produces, without the regex rewrite. + /// + /// This is what pruning consumes: it is a shape the pruning predicate builder recognizes. + fn to_plain_physical_expr( + expr: &Expr, + df_schema: &DFSchema, + ) -> error::Result> { + let execution_props = &ExecutionProps::new(); + let planning_context = &PhysicalPlanningContext::default(); + create_physical_expr(expr, df_schema, execution_props, planning_context) + .context(error::DatafusionSnafu) + } + + /// Rewrites the regex comparisons in `expr` into [`PrecompiledRegexExpr`], so each pattern is + /// compiled once per scan instead of once per batch. + /// + /// Returns `None` when nothing in `expr` can be precompiled, which leaves the caller with the + /// unmodified `create_physical_expr` path. `AND`/`OR` are rebuilt with only the rewritable + /// branch replaced because a label matcher accepting the empty string is planned as + /// `is_null(col) OR col =~ 'pattern'`: the rewrite has to reach the regex below the `OR` or a + /// nullable label column never benefits. Every other node — `NOT`, `CASE`, a cast around the + /// whole comparison — is left to the planner. + fn to_regex_physical_expr( + expr: &Expr, + schema: &arrow::datatypes::SchemaRef, + df_schema: &DFSchema, + execution_props: &ExecutionProps, + planning_context: &PhysicalPlanningContext, + ) -> Option> { + let Expr::BinaryExpr(binary) = expr else { + return None; + }; + let compile = |expr: &Expr| { + create_physical_expr(expr, df_schema, execution_props, planning_context).ok() + }; + let rewrite = |expr: &Expr| { + Self::to_regex_physical_expr(expr, schema, df_schema, execution_props, planning_context) + }; + + if matches!(binary.op, Operator::And | Operator::Or) { + let left = rewrite(&binary.left); + let right = rewrite(&binary.right); + if left.is_none() && right.is_none() { + return None; + } + let left = left.or_else(|| compile(&binary.left))?; + let right = right.or_else(|| compile(&binary.right))?; + return Some(Arc::new(PhysicalBinaryExpr::new(left, binary.op, right))); + } + + if !matches!(binary.op, Operator::RegexMatch | Operator::RegexNotMatch) { + return None; + } + // Precompile only what the precompiled kernel can evaluate exactly; other string layouts + // keep the arrow comparison instead of failing at scan time. + let column_type = regex_column_type(&binary.left, schema)?; + if !is_precompilable_regex_type(&column_type) { + return None; + } + let filter = SimpleFilterEvaluator::try_new_with_column_type(expr, &|name| { + schema + .field_with_name(name) + .ok() + .map(|field| field.data_type().clone()) + })?; + let Expr::Literal(literal, _) = binary.right.as_ref() else { + return None; + }; + let pattern = literal.try_as_str()?.map(str::to_string)?; + let column = compile(&binary.left)?; + + Some(Arc::new(PrecompiledRegexExpr { + column, + filter, + pattern, + op: binary.op, + })) + } + + /// Builds the physical exprs [`Self::prune_with_stats`] folds into column statistics. + /// + /// Pruning never evaluates a predicate, and the regex rewrite exists only to make evaluation + /// cheap, so this deliberately builds what `create_physical_expr` builds. Besides saving the + /// conversion on a per-file (manifest pruning) and per-batch (bulk memtable pruning) path, + /// [`PrecompiledRegexExpr`] is a node the pruning predicate builder does not know: it replaces + /// unknown nodes with `true`, while the plain comparison below is handled (or rejected) the + /// same way it was before the rewrite existed. + pub fn to_pruning_physical_exprs( &self, schema: &arrow::datatypes::SchemaRef, ) -> error::Result>> { + let df_schema = schema + .clone() + .to_dfschema_ref() + .context(error::DatafusionSnafu)?; let dyn_filters = self.dyn_filter_phy_exprs()?; Ok(self .exprs .iter() - .filter_map(|expr| Self::to_physical_expr(expr, schema).ok()) + .filter_map(|expr| Self::to_plain_physical_expr(expr, df_schema.as_ref()).ok()) .chain(dyn_filters) .collect::>()) } @@ -209,7 +319,7 @@ impl Predicate { schema: &arrow::datatypes::SchemaRef, ) -> Vec { let mut res = vec![true; stats.num_containers()]; - let physical_exprs = match self.to_physical_exprs(schema) { + let physical_exprs = match self.to_pruning_physical_exprs(schema) { Ok(expr) => expr, Err(e) => { warn!(e; "Failed to build physical expr from predicates: {:?}", &self.exprs); @@ -242,6 +352,132 @@ impl Predicate { } } +/// Returns whether `data_type` is a string layout [`SimpleFilterEvaluator`] can evaluate. +/// +/// Its regex kernels accept `Utf8` and `Dictionary(UInt32, Utf8)` only; `LargeUtf8`, `Utf8View` +/// and other dictionary layouts keep the arrow comparison. +fn is_precompilable_regex_type(data_type: &ArrowDataType) -> bool { + match data_type { + ArrowDataType::Utf8 => true, + ArrowDataType::Dictionary(key, value) => { + **key == ArrowDataType::UInt32 && **value == ArrowDataType::Utf8 + } + _ => false, + } +} + +/// Returns the arrow type the regex comparison in `expr` evaluates, `None` if `expr` is not a +/// column (or a cast of one) this rewrite can reason about. +fn regex_column_type(expr: &Expr, schema: &arrow::datatypes::SchemaRef) -> Option { + match expr { + Expr::Column(column) => schema + .field_with_name(&column.name) + .ok() + .map(|field| field.data_type().clone()), + // A cast decides the compared type, whatever the column holds underneath. + Expr::Cast(cast) => match cast.expr.as_ref() { + Expr::Column(_) => Some(cast.field.data_type().clone()), + _ => None, + }, + _ => None, + } +} + +/// A regex comparison (`col =~ 'pattern'` / `col !~ 'pattern'`) compiled on first evaluation. +/// +/// `create_physical_expr` turns the comparison into a binary expression that recompiles the pattern +/// on every evaluation, because arrow's `regexp_is_match_scalar` compiles the pattern it is given. +/// A scan evaluates its physical expr once per batch, so that costs one `Regex::new` per batch, and +/// a series scan evaluates one batch per series. [`SimpleFilterEvaluator`] lazily compiles its +/// pattern once on first evaluation, then borrows one cache per batch rather than one per row. +/// +/// The result is bit-identical to the arrow expression it replaces: `evaluate_array` folds SQL +/// `NULL` into `false`, so the column's logical nulls are restored afterwards — exactly the validity +/// arrow's kernel produces for a regex, which never fails on `NULL`. +/// +/// Only [`Predicate::to_physical_expr`] builds this node, for callers that evaluate the predicate. +/// Pruning uses [`Predicate::to_pruning_physical_exprs`] and keeps the arrow comparison. +#[derive(Debug)] +struct PrecompiledRegexExpr { + /// The column the pattern is matched against. + column: Arc, + /// The pattern, compiled on first evaluation and reused thereafter. + filter: SimpleFilterEvaluator, + /// The pattern text, kept for display and equality. + pattern: String, + /// `RegexMatch` or `RegexNotMatch`, kept for display and equality. + op: Operator, +} + +impl fmt::Display for PrecompiledRegexExpr { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let op = if matches!(self.op, Operator::RegexMatch) { + "=~" + } else { + "!~" + }; + write!(f, "{} {op} '{}'", self.column, self.pattern) + } +} + +impl PartialEq for PrecompiledRegexExpr { + fn eq(&self, other: &Self) -> bool { + self.op == other.op && self.pattern == other.pattern && self.column.eq(&other.column) + } +} + +impl Eq for PrecompiledRegexExpr {} + +impl Hash for PrecompiledRegexExpr { + fn hash(&self, state: &mut H) { + self.op.hash(state); + self.pattern.hash(state); + self.column.hash(state); + } +} + +impl PhysicalExpr for PrecompiledRegexExpr { + fn data_type(&self, _input_schema: &ArrowSchema) -> DfResult { + Ok(ArrowDataType::Boolean) + } + + fn nullable(&self, input_schema: &ArrowSchema) -> DfResult { + self.column.nullable(input_schema) + } + + fn evaluate(&self, batch: &DfRecordBatch) -> DfResult { + let column = self.column.evaluate(batch)?.into_array(batch.num_rows())?; + let matched = self + .filter + .evaluate_array(&column) + .map_err(|e| DataFusionError::External(Box::new(e)))?; + Ok(ColumnarValue::Array(Arc::new(BooleanArray::new( + matched, + column.logical_nulls(), + )))) + } + + fn children(&self) -> Vec<&Arc> { + vec![&self.column] + } + + fn with_new_children( + self: Arc, + children: Vec>, + ) -> DfResult> { + Ok(Arc::new(Self { + column: children[0].clone(), + filter: self.filter.clone(), + pattern: self.pattern.clone(), + op: self.op, + })) + } + + fn fmt_sql(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{self}") + } +} + // tests for `build_time_range_predicate` locates in src/query/tests/time_range_filter_test.rs // since it requires query engine to convert sql to filters. /// `build_time_range_predicate` extracts time range from logical exprs to facilitate fast @@ -690,9 +926,13 @@ mod tests { use common_test_util::temp_dir::{TempDir, create_temp_dir}; use datafusion::parquet::arrow::ArrowWriter; + use datafusion_common::tree_node::TreeNodeRecursion; use datafusion_common::{Column, ScalarValue}; use datafusion_expr::{BinaryExpr, Literal, Operator, col, lit}; - use datatypes::arrow::array::Int32Array; + use datatypes::arrow::array::{ + ArrayRef, DictionaryArray, Int32Array, LargeStringArray, StringViewArray, UInt8Array, + UInt32Array, + }; use datatypes::arrow::datatypes::{DataType, Field, Schema}; use datatypes::arrow::record_batch::RecordBatch; use datatypes::arrow_array::StringArray; @@ -1445,10 +1685,446 @@ mod tests { false, )])); - let predicates = predicate.to_physical_exprs(&schema).unwrap(); + let predicates = predicate.to_pruning_physical_exprs(&schema).unwrap(); assert!(!predicates.is_empty()); let physical_expr = Predicate::to_physical_expr(&col("host").eq(lit("host_a")), &schema); assert!(physical_expr.is_ok()); } + + fn regex_expr(column: &str, op: Operator, pattern: &str) -> Expr { + Expr::BinaryExpr(BinaryExpr { + left: Box::new(col(column)), + op, + right: Box::new(lit(pattern)), + }) + } + + /// The expression `create_physical_expr` builds on its own, i.e. the implementation before + /// regex patterns were precompiled. It recompiles the pattern on every evaluation. + fn arrow_regex_expr(expr: &Expr, schema: &Arc) -> Arc { + let df_schema = schema.clone().to_dfschema_ref().unwrap(); + create_physical_expr( + expr, + df_schema.as_ref(), + &ExecutionProps::new(), + &PhysicalPlanningContext::default(), + ) + .unwrap() + } + + fn regex_batch( + data_type: DataType, + array: ArrayRef, + nullable: bool, + ) -> (Arc, RecordBatch) { + let schema = Arc::new(Schema::new(vec![Field::new("host", data_type, nullable)])); + let batch = RecordBatch::try_new(schema.clone(), vec![array]).unwrap(); + (schema, batch) + } + + /// Returns the value of `physical` per row, `None` standing for SQL `NULL`. + fn evaluate_rows(physical: &Arc, batch: &RecordBatch) -> Vec> { + let array = physical + .evaluate(batch) + .unwrap() + .into_array(batch.num_rows()) + .unwrap(); + let array = array.as_any().downcast_ref::().unwrap(); + (0..array.len()) + .map(|index| array.is_valid(index).then(|| array.value(index))) + .collect() + } + + /// Asserts both implementations agree row by row, as predicate values and as the filter mask a + /// scan derives from them. + fn assert_same_regex_result(expr: &Expr, schema: &Arc, batch: &RecordBatch) { + let arrow = arrow_regex_expr(expr, schema); + let precompiled = Predicate::to_physical_expr(expr, schema).unwrap(); + + assert_eq!( + evaluate_rows(&arrow, batch), + evaluate_rows(&precompiled, batch), + "values differ for {expr:?}" + ); + assert_eq!( + common_recordbatch::filter::batch_filter(batch, &arrow).unwrap(), + common_recordbatch::filter::batch_filter(batch, &precompiled).unwrap(), + "filtered rows differ for {expr:?}" + ); + } + + /// Differential test: the precompiled predicate must produce exactly what arrow's own regex + /// kernel produces, for every string layout, with and without `NULL`s, for `=~` and `!~`. + #[test] + fn test_precompiled_regex_matches_arrow() { + let plain_nulls = vec![ + Some("host-a"), + None, + Some(""), + Some("db"), + Some("日本語"), + Some("HOST-B"), + ]; + // A dictionary with a `NULL` key and a `NULL` dictionary value: both are SQL `NULL`, and + // the dictionary value's `NULL` is what a naive kernel loses. + let dict_values = Arc::new(StringArray::from(vec![ + Some("host-a"), + Some("HOST-B"), + Some(""), + None, + Some("日本語"), + ])) as ArrayRef; + let cases: Vec<(&str, DataType, ArrayRef, bool, bool)> = vec![ + ( + "utf8", + DataType::Utf8, + Arc::new(StringArray::from(vec!["host-a", "db", ""])) as ArrayRef, + false, + true, + ), + ( + "utf8 with nulls", + DataType::Utf8, + Arc::new(StringArray::from(plain_nulls.clone())) as ArrayRef, + true, + true, + ), + ( + "dictionary(UInt32, utf8) with nulls", + DataType::Dictionary(Box::new(DataType::UInt32), Box::new(DataType::Utf8)), + Arc::new(DictionaryArray::new( + UInt32Array::from(vec![Some(0), Some(1), Some(2), None, Some(3), Some(4)]), + dict_values.clone(), + )) as ArrayRef, + true, + true, + ), + ( + "large utf8 with nulls", + DataType::LargeUtf8, + Arc::new(LargeStringArray::from(plain_nulls.clone())) as ArrayRef, + true, + false, + ), + ( + "utf8 view with nulls", + DataType::Utf8View, + Arc::new(StringViewArray::from(plain_nulls.clone())) as ArrayRef, + true, + false, + ), + ( + "dictionary(UInt8, utf8) with nulls", + DataType::Dictionary(Box::new(DataType::UInt8), Box::new(DataType::Utf8)), + Arc::new(DictionaryArray::new( + UInt8Array::from(vec![Some(0u8), Some(1), Some(2), None, Some(3), Some(4)]), + dict_values.clone(), + )) as ArrayRef, + true, + false, + ), + ]; + + for (name, data_type, array, nullable, expect_precompiled) in cases { + let (schema, batch) = regex_batch(data_type.clone(), array, nullable); + for op in [Operator::RegexMatch, Operator::RegexNotMatch] { + for pattern in [ + "host.*", "^host-a$", "^(?:.*)$", "", "(?i)host", "日本", "^$", + ] { + let expr = regex_expr("host", op, pattern); + let physical = Predicate::to_physical_expr(&expr, &schema).unwrap(); + assert_eq!( + expect_precompiled, + physical.downcast_ref::().is_some(), + "{name}: {op:?} {pattern:?}" + ); + assert_same_regex_result(&expr, &schema, &batch); + let slice = batch.slice(1, batch.num_rows() - 1); + assert_same_regex_result(&expr, &schema, &slice); + } + } + } + + // A cast decides the compared type: a dictionary column cast to `Utf8` is precompilable + // even though the column itself is not `Utf8`. + let (schema, batch) = regex_batch( + DataType::Dictionary(Box::new(DataType::UInt32), Box::new(DataType::Utf8)), + Arc::new(DictionaryArray::new( + UInt32Array::from(vec![Some(0), Some(1), Some(2), None, Some(3), Some(4)]), + dict_values.clone(), + )) as ArrayRef, + true, + ); + let cast = Expr::Cast(datafusion_expr::expr::Cast { + expr: Box::new(col("host")), + field: Arc::new(Field::new("host", DataType::Utf8, true)), + }); + let expr = Expr::BinaryExpr(BinaryExpr { + left: Box::new(cast), + op: Operator::RegexMatch, + right: Box::new(lit("host.*")), + }); + let physical = Predicate::to_physical_expr(&expr, &schema).unwrap(); + assert!(physical.downcast_ref::().is_some()); + assert_same_regex_result(&expr, &schema, &batch); + } + + /// Pruning never evaluates the predicate, so its entry point must keep the plain comparison + /// instead of the evaluation-only [`PrecompiledRegexExpr`]: pruning runs once per file + /// (manifest pruning) and once per batch (bulk memtable pruning), and a node the pruning + /// predicate builder does not recognize would only be replaced by `true`. + #[test] + fn test_pruning_keeps_the_plain_regex_expr() { + let (schema, _) = regex_batch( + DataType::Utf8, + Arc::new(StringArray::from(vec![Some("host-a"), None, Some("db")])) as ArrayRef, + true, + ); + let expr = regex_expr("host", Operator::RegexMatch, "host.*"); + + let pruning = Predicate::new(vec![expr.clone()]) + .to_pruning_physical_exprs(&schema) + .unwrap(); + assert_eq!(1, pruning.len()); + let physical = &pruning[0]; + let mut rewritten = false; + physical + .apply(|node| { + rewritten |= node.downcast_ref::().is_some(); + Ok(TreeNodeRecursion::Continue) + }) + .unwrap(); + assert!( + !rewritten, + "pruning must not build the evaluation-only rewrite: {physical}" + ); + // It is exactly what `create_physical_expr` plans, i.e. what pruning saw before the + // rewrite existed. + assert_eq!( + arrow_regex_expr(&expr, &schema).to_string(), + physical.to_string() + ); + + // Evaluation keeps the rewrite. + let evaluated = Predicate::to_physical_expr(&expr, &schema).unwrap(); + assert!( + evaluated.downcast_ref::().is_some(), + "evaluation must precompile the pattern: {evaluated}" + ); + } + + /// Pruning still applies the numeric conjunct of a predicate that also holds a regex, so + /// keeping the plain comparison does not weaken pruning. + #[tokio::test] + async fn test_prune_with_regex_conjunct() { + let e = regex_expr("name", Operator::RegexMatch, "^1.*").and(col("cnt").gt_eq(lit(10_i32))); + assert_prune(40, vec![e], vec![false, true, true, true]).await; + } + + /// The precompiled pattern stays uninitialized until the first evaluation and is then reused. + /// The per-regex compile counter is tested in common-recordbatch. + #[test] + #[allow(clippy::print_stdout)] + fn test_precompiled_regex_defers_compilation_until_evaluation() { + let (schema, batch) = regex_batch( + DataType::Utf8, + Arc::new(StringArray::from(vec![Some("host-a"), None, Some("db")])) as ArrayRef, + true, + ); + let expr = regex_expr("host", Operator::RegexMatch, "host.*"); + let physical = Predicate::to_physical_expr(&expr, &schema).unwrap(); + let regex = physical.downcast_ref::().unwrap(); + let initialized = || format!("{:?}", regex.filter); + assert!( + initialized().contains("initialized: false"), + "{}", + initialized() + ); + println!("after to_physical_expr: regex initializations = 0"); + + assert_eq!( + vec![Some(true), None, Some(false)], + evaluate_rows(&physical, &batch) + ); + assert!( + initialized().contains("initialized: true"), + "{}", + initialized() + ); + println!("after first evaluate: regex initialized = true"); + for _ in 0..100 { + assert_eq!( + vec![Some(true), None, Some(false)], + evaluate_rows(&physical, &batch) + ); + } + assert!( + initialized().contains("initialized: true"), + "{}", + initialized() + ); + println!("after 100 further evaluations: same OnceLock remains initialized"); + } + + /// A malformed regex must be deferred too, but row evaluation still reports an error instead + /// of silently accepting the predicate as an exact match. + #[test] + #[allow(clippy::print_stdout)] + fn test_invalid_regex_fails_at_evaluation_not_construction() { + let (schema, batch) = regex_batch( + DataType::Utf8, + Arc::new(StringArray::from(vec![Some("host-a")])) as ArrayRef, + true, + ); + let expr = regex_expr("host", Operator::RegexMatch, "host("); + // The old rewrite fell back to DataFusion on eager compilation failure. That physical + // planner does not compile the pattern, so it too reports this error on evaluation. + let old_fallback = arrow_regex_expr(&expr, &schema); + assert!(old_fallback.evaluate(&batch).is_err()); + let physical = Predicate::to_physical_expr(&expr, &schema) + .expect("construction must retain the invalid regex"); + let regex = physical.downcast_ref::().unwrap(); + assert!(format!("{:?}", regex.filter).contains("initialized: false")); + let error = physical + .evaluate(&batch) + .expect_err("invalid regex must fail on evaluate, not construction"); + let DataFusionError::External(source) = &error else { + panic!("expected a common-recordbatch error, got: {error}"); + }; + assert!( + matches!( + source.downcast_ref::(), + Some(common_recordbatch::error::Error::ArrowCompute { .. }) + ), + "expected ArrowCompute, got: {error}" + ); + assert!(physical.evaluate(&batch).is_err()); + assert!(format!("{:?}", regex.filter).contains("initialized: true")); + println!( + "invalid regex: 0 initializations after to_physical_expr; first evaluate returned an error" + ); + } + + /// A scan can repeatedly evaluate the same regex expression without changing its results. + #[test] + fn test_regex_pattern_reused_across_batches() { + let (schema, batch) = regex_batch( + DataType::Utf8, + Arc::new(StringArray::from(vec![ + Some("host-a"), + None, + Some(""), + Some("db"), + Some("host-b"), + ])) as ArrayRef, + true, + ); + let expr = regex_expr("host", Operator::RegexMatch, "host.*"); + + let physical = Predicate::to_physical_expr(&expr, &schema).unwrap(); + assert!( + physical.downcast_ref::().is_some(), + "the scan-side predicate holds the lazy pattern: {physical}" + ); + assert_eq!("host@0 =~ 'host.*'", physical.to_string()); + + for _ in 0..100 { + assert_eq!( + vec![Some(true), None, Some(false), Some(false), Some(true)], + evaluate_rows(&physical, &batch) + ); + } + } + + /// The predicate a native `rate(x{host=~'host.*'}[1m])` builds when the label column is + /// nullable, as [`PromPlanner::matchers_to_expr`] plans it: `is_null(host) OR host =~ '...'`. + /// + /// `matchers_to_expr` lives in the query crate; this reproduces the expression it emits so the + /// rewrite is covered for the shape the series scan actually sees. The logical plan is not + /// touched by the precompiled path, and the rows are unchanged. + #[test] + fn test_nullable_label_matcher_keeps_shape_and_rows() { + let (schema, batch) = regex_batch( + DataType::Utf8, + Arc::new(StringArray::from(vec![ + Some("host-a"), + None, + Some(""), + Some("db"), + Some("host-b"), + ])) as ArrayRef, + true, + ); + let expr = + col("host") + .is_null() + .or(regex_expr("host", Operator::RegexMatch, "^(?:host.*)$")); + + let physical = Predicate::to_physical_expr(&expr, &schema).unwrap(); + // Shape: the `OR` survives, its null test is untouched, and only the comparison below it + // is replaced by the precompiled form. + let or = physical + .downcast_ref::() + .unwrap_or_else(|| panic!("the OR was rewritten into {physical}")); + assert_eq!(&Operator::Or, or.op()); + assert!( + or.left() + .downcast_ref::() + .is_some(), + "the null test is unchanged: {}", + or.left() + ); + assert!( + or.right().downcast_ref::().is_some(), + "the regex below the OR is precompiled: {}", + or.right() + ); + + // The explicit OR makes a missing label match independently of the regex result. + assert_eq!( + vec![Some(true), Some(true), Some(false), Some(false), Some(true)], + evaluate_rows(&physical, &batch) + ); + assert_same_regex_result(&expr, &schema, &batch); + } + + /// A scan hands one physical expr to every thread that evaluates it, and the precompiled + /// expression provides separate caches to concurrent searches. Sharing it must neither panic + /// nor change an answer. + #[test] + fn test_precompiled_regex_is_shared_between_threads() { + let (schema, batch) = regex_batch( + DataType::Utf8, + Arc::new(StringArray::from(vec![ + Some("host-a"), + None, + Some(""), + Some("db"), + Some("host-b"), + ])) as ArrayRef, + true, + ); + let expr = regex_expr("host", Operator::RegexMatch, "host.*"); + let physical = Predicate::to_physical_expr(&expr, &schema).unwrap(); + assert!(physical.downcast_ref::().is_some()); + let expected = vec![Some(true), None, Some(false), Some(false), Some(true)]; + assert_eq!(expected, evaluate_rows(&physical, &batch)); + + std::thread::scope(|scope| { + for _ in 0..8 { + let physical = Arc::clone(&physical); + let batch = batch.clone(); + let expected = expected.clone(); + scope.spawn(move || { + for _ in 0..50 { + assert_eq!(expected, evaluate_rows(&physical, &batch)); + } + }); + } + }); + + // The concurrent evaluations neither compiled nor changed the expression. + assert_eq!(expected, evaluate_rows(&physical, &batch)); + } }