Skip to main content

datafusion_match_recognize/
config.rs

1// Licensed under the Apache License, Version 2.0 (the
2// "License"); you may not use this file except in compliance
3// with the License.  You may obtain a copy of the License at
4//
5//   http://www.apache.org/licenses/LICENSE-2.0
6//
7// Unless required by applicable law or agreed to in writing,
8// software distributed under the License is distributed on an
9// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
10// KIND, either express or implied.  See the License for the
11// specific language governing permissions and limitations
12// under the License.
13//
14// This product includes software developed at Datadog (https://www.datadoghq.com/) Copyright 2025-Present Datadog, Inc.
15
16//! Configuration options for MATCH_RECOGNIZE pattern matching.
17//!
18//! Session-scoped options can be set with SQL `SET` statements or through
19//! `SessionConfig`.
20//!
21//! User resource limits, advanced scheduler settings, and diagnostic algorithm
22//! overrides are separate records. SQL keys therefore make the distinction
23//! explicit, for example `match_recognize.limits.pattern_max_nfa_states` and
24//! `match_recognize.diagnostics.disable_pattern_optimizer`.
25
26use std::num::NonZeroUsize;
27use std::time::{Duration, Instant};
28
29use crate::nfa::PatternCompileLimits;
30use datafusion::common::{DataFusionError, config::ConfigExtension, extensions_options};
31
32/// Default maximum number of dynamic scalar/array pairs retained per scan.
33pub const DEFAULT_SINGLE_ROW_ARRAY_CACHE_MAX_ENTRIES: usize = 256;
34/// Default maximum live-entry bytes for dynamic scalar/array pairs per scan.
35pub const DEFAULT_SINGLE_ROW_ARRAY_CACHE_MAX_BYTES: usize = 1024 * 1024;
36/// Hard ceiling that bounds one cache eviction-planning pass.
37pub(crate) const MAX_SINGLE_ROW_ARRAY_CACHE_ENTRIES: usize = 4096;
38/// Hard ceiling for scan-local dynamic live-entry bytes.
39pub(crate) const MAX_SINGLE_ROW_ARRAY_CACHE_BYTES: usize = 64 * 1024 * 1024;
40
41/// One active poll's shared scheduling deadline, copied into resumable work.
42#[derive(Debug, Clone, Copy, PartialEq, Eq)]
43pub(crate) enum YieldPolicy {
44    /// Disable voluntary time slicing. Cancellation remains independent.
45    Disabled,
46    Deadline(Instant),
47    /// Deterministic safe-point selection for continuation tests only.
48    #[cfg(test)]
49    TestBudget(NonZeroUsize),
50}
51
52impl YieldPolicy {
53    #[cfg(test)]
54    pub(crate) const fn from_test_budget(budget: usize) -> Self {
55        match NonZeroUsize::new(budget) {
56            Some(budget) => Self::TestBudget(budget),
57            None => Self::Disabled,
58        }
59    }
60
61    pub(crate) fn is_expired(self) -> bool {
62        match self {
63            Self::Disabled => false,
64            Self::Deadline(deadline) => Instant::now() >= deadline,
65            #[cfg(test)]
66            Self::TestBudget(_) => false,
67        }
68    }
69}
70
71/// Default completed-work countdown interval between cancellation probes.
72pub const DEFAULT_CANCELLATION_POLL_INTERVAL: usize = 256;
73
74/// Bound cancellation settings installed into one persistent row-loop scan.
75#[derive(Debug, Clone, Copy, PartialEq, Eq)]
76pub(crate) struct CancellationPolicy {
77    poll_interval: NonZeroUsize,
78    deadline: Option<Duration>,
79}
80
81impl CancellationPolicy {
82    /// Validate configured cancellation settings before a scan starts work.
83    pub(crate) fn try_from_configured(
84        poll_interval: usize,
85        deadline_millis: usize,
86    ) -> datafusion::common::Result<Self> {
87        let poll_interval = NonZeroUsize::new(poll_interval).ok_or_else(|| {
88            DataFusionError::Configuration("match_recognize.limits.cancellation_poll_interval must be greater than 0".into())
89        })?;
90        let millis = u64::try_from(deadline_millis).map_err(|_| {
91            DataFusionError::Configuration("match_recognize.limits.execution_deadline_millis is too large to represent as a u64 number of milliseconds".into())
92        })?;
93        let deadline = (millis != 0).then(|| Duration::from_millis(millis));
94        Ok(Self {
95            poll_interval,
96            deadline,
97        })
98    }
99
100    pub(crate) const fn poll_interval(self) -> NonZeroUsize {
101        self.poll_interval
102    }
103
104    pub(crate) const fn deadline(self) -> Option<Duration> {
105        self.deadline
106    }
107}
108
109/// Default multiplier for parallel_no_partition_min_rows_per_task.
110/// The actual default is this value multiplied by batch_size.
111pub const DEFAULT_PARALLEL_MIN_ROWS_MULTIPLIER: usize = 8;
112
113/// Default batch size used when computing parallel_no_partition_min_rows_per_task.
114pub const DEFAULT_BATCH_SIZE: usize = 8192;
115
116extensions_options! {
117    /// Stable resource and safety limits for pattern matching.
118    pub struct MatchRecognizeLimits {
119        /// Soft active-work slice in microseconds, shared by matching and its
120        /// resumable preparation/output phases. Native calls stay atomic, so
121        /// this is not a latency bound. Zero disables voluntary slices, not
122        /// cancellation polling, the ready-input guard, or native scheduler cooperation.
123        pub yield_slice_micros: usize, default = 1000
124        /// Positive completed-work countdown interval for abort-signal and
125        /// execution-deadline probes. Polling occurs at completed-work call
126        /// boundaries, so one nonresumable charged batch may overshoot it. A
127        /// zero value is rejected before a scan begins.
128        pub cancellation_poll_interval: usize, default = DEFAULT_CANCELLATION_POLL_INTERVAL
129        /// Optional elapsed execution deadline in milliseconds, applied
130        /// independently to every row-loop scan governor and to the stream's
131        /// storage governor.
132        /// Zero disables the deadline; abort-signal polling remains enabled.
133        pub execution_deadline_millis: usize, default = 0
134        /// Maximum deduplicated `PERMUTE(...)` branches.
135        pub pattern_max_permute_branches: usize, default = PatternCompileLimits::DEFAULT.max_permute_branches
136        /// Maximum compiled NFA states.
137        pub pattern_max_nfa_states: usize, default = PatternCompileLimits::DEFAULT.max_nfa_states
138        /// Maximum retained epsilon-closure entries.
139        pub pattern_max_epsilon_closure_entries: usize, default = PatternCompileLimits::DEFAULT.max_epsilon_closure_entries
140        /// Maximum NFA transition-table entries (`states × symbol IDs`).
141        pub pattern_max_dense_transition_cells: usize, default = PatternCompileLimits::DEFAULT.max_dense_transition_cells
142        /// Maximum non-common entries retained by the scan-local one-row Arrow
143        /// array cache. Zero disables dynamic retention; fixed null, Boolean,
144        /// and small-integer slots remain available. Values above 4,096 are
145        /// rejected before fallback evaluation begins.
146        pub single_row_array_cache_max_entries: usize, default = DEFAULT_SINGLE_ROW_ARRAY_CACHE_MAX_ENTRIES
147        /// Maximum conservative live-entry bytes in the dynamic one-row Arrow
148        /// array cache. The memory pool also covers reusable LRU storage.
149        /// Zero disables dynamic retention. Values above 64 MiB are rejected
150        /// before fallback evaluation begins.
151        pub single_row_array_cache_max_bytes: usize, default = DEFAULT_SINGLE_ROW_ARRAY_CACHE_MAX_BYTES
152    }
153}
154
155impl MatchRecognizeLimits {
156    pub(crate) fn active_slice_duration(
157        &self,
158    ) -> datafusion::common::Result<Option<Duration>> {
159        let Some(micros) = NonZeroUsize::new(self.yield_slice_micros) else {
160            return Ok(None);
161        };
162        let micros = u64::try_from(micros.get()).map_err(|_| {
163            DataFusionError::Configuration(
164                "match_recognize.limits.yield_slice_micros is too large to represent as a u64 number of microseconds".into(),
165            )
166        })?;
167        Ok(Some(Duration::from_micros(micros)))
168    }
169
170    pub(crate) const fn pattern_compile_limits(&self) -> PatternCompileLimits {
171        PatternCompileLimits {
172            max_permute_branches: self.pattern_max_permute_branches,
173            max_nfa_states: self.pattern_max_nfa_states,
174            max_epsilon_closure_entries: self.pattern_max_epsilon_closure_entries,
175            max_dense_transition_cells: self.pattern_max_dense_transition_cells,
176        }
177    }
178}
179
180extensions_options! {
181    /// Advanced parallel scheduler settings.
182    pub struct MatchRecognizeSchedulerConfig {
183        /// Minimum core rows per parallel Halo task, with or without `PARTITION BY`.
184        /// Zero keeps keyed queries on ordinary matching and is rejected for
185        /// otherwise eligible queries without `PARTITION BY`.
186        pub parallel_no_partition_min_rows_per_task: usize, default = DEFAULT_PARALLEL_MIN_ROWS_MULTIPLIER * DEFAULT_BATCH_SIZE
187    }
188}
189
190extensions_options! {
191    /// Unstable diagnostic overrides used by differential tests and debugging.
192    ///
193    /// These switches select implementation fallbacks; they are not durable
194    /// application policy.
195    pub struct MatchRecognizeDiagnostics {
196        /// Disable runtime pruning of static symbols absent from a complete input
197        /// window. Construction-time normalization remains enabled.
198        pub disable_pattern_optimizer: bool, default = false
199        /// Keep DataFusion's input sort when planning a partitioned matcher.
200        pub disable_hash_grouped_ordering: bool, default = false
201        /// Keep every logical partition when hash-grouped ordering is selected.
202        pub disable_pre_sort_partition_pruning: bool, default = false
203        /// Disable construction-time pruning of static symbols proven absent by
204        /// exact overall input statistics. Structural normalization remains enabled.
205        pub disable_statistics_absence_pruning: bool, default = false
206        /// Force arena-backed path storage for patterns otherwise eligible for compact paths,
207        /// and disable direct-linear scan loops.
208        pub disable_compact_paths: bool, default = false
209        /// Disable bounded core-and-halo parallel planning and use ordinary
210        /// matching, distributing SQL partition keys across workers when present.
211        pub disable_parallel_no_partition: bool, default = false
212        /// Disable planning-time managed aggregate extraction and evaluate the
213        /// complete match-aware `DEFINE` expression against the bounded history slice.
214        pub disable_managed_aggregates: bool, default = false
215        /// Disable register-backed managed aggregates.
216        pub disable_register_aggregate_backend: bool, default = false
217        /// Disable planning-time static subexpression extraction.
218        ///
219        /// The full `DEFINE` predicates remain on their normal evaluators, no
220        /// generated `__mr_static_*` columns are projected, and runtime has no
221        /// static extraction prechecks. Match-independent Window inputs are
222        /// still planned and rebased normally.
223        pub disable_static_extraction: bool, default = false
224    }
225}
226
227extensions_options! {
228    /// Session-scoped `MATCH_RECOGNIZE` configuration.
229    ///
230    /// Insert the configuration before creating the session-state builder:
231    ///
232    /// ```rust
233    /// use datafusion::execution::SessionStateBuilder;
234    /// use datafusion::prelude::SessionConfig;
235    /// use datafusion_match_recognize::MatchRecognizeConfig;
236    ///
237    /// let mut session_config = SessionConfig::new();
238    /// let mut match_config = MatchRecognizeConfig::default();
239    /// match_config.limits.execution_deadline_millis = 30_000;
240    /// session_config.options_mut().extensions.insert(match_config);
241    ///
242    /// let _builder = SessionStateBuilder::new()
243    ///     .with_default_features()
244    ///     .with_config(session_config);
245    /// ```
246    pub struct MatchRecognizeConfig {
247        /// Stable resource and compiler limits.
248        pub limits: MatchRecognizeLimits, default = MatchRecognizeLimits::default()
249        /// Advanced scheduling settings.
250        pub scheduler: MatchRecognizeSchedulerConfig, default = MatchRecognizeSchedulerConfig::default()
251        /// Unstable diagnostic implementation overrides.
252        pub diagnostics: MatchRecognizeDiagnostics, default = MatchRecognizeDiagnostics::default()
253    }
254}
255
256impl ConfigExtension for MatchRecognizeConfig {
257    const PREFIX: &'static str = "match_recognize";
258}
259
260#[cfg(test)]
261mod tests {
262    use super::*;
263    use datafusion::common::config::ConfigOptions;
264
265    #[test]
266    fn public_defaults_bound_scheduling_and_compilation() {
267        let config = MatchRecognizeConfig::default();
268        assert_eq!(
269            (
270                config.diagnostics.disable_pattern_optimizer,
271                config.diagnostics.disable_statistics_absence_pruning,
272                config.diagnostics.disable_parallel_no_partition
273            ),
274            (false, false, false)
275        );
276        assert_eq!(
277            config.scheduler.parallel_no_partition_min_rows_per_task,
278            65_536
279        );
280        assert_eq!(config.limits.yield_slice_micros, 1000);
281        assert_eq!(config.limits.cancellation_poll_interval, 256);
282        assert_eq!(config.limits.execution_deadline_millis, 0);
283        assert_eq!(
284            (
285                config.limits.pattern_max_permute_branches,
286                config.limits.pattern_max_nfa_states,
287                config.limits.pattern_max_epsilon_closure_entries,
288                config.limits.pattern_max_dense_transition_cells,
289                config.limits.single_row_array_cache_max_entries,
290                config.limits.single_row_array_cache_max_bytes
291            ),
292            (5_040, 250_000, 3_000_000, 4_000_000, 256, 1_048_576)
293        );
294        assert_eq!(
295            (
296                config.diagnostics.disable_managed_aggregates,
297                config.diagnostics.disable_register_aggregate_backend,
298                config.diagnostics.disable_static_extraction
299            ),
300            (false, false, false)
301        );
302    }
303
304    #[test]
305    fn config_advertises_limits_and_diagnostics_controls() {
306        let mut options = ConfigOptions::default();
307        options.extensions.insert(MatchRecognizeConfig::default());
308        let entries = options.entries();
309        for key in [
310            "cancellation_poll_interval",
311            "disable_compact_paths",
312            "single_row_array_cache_max_entries",
313            "single_row_array_cache_max_bytes",
314            "disable_managed_aggregates",
315            "disable_register_aggregate_backend",
316            "disable_static_extraction",
317        ] {
318            assert!(entries.iter().any(|entry| entry.key == key), "{key}");
319        }
320    }
321
322    #[test]
323    fn diagnostic_keys_bind_only_their_named_control() {
324        for (leaf, expected) in [
325            (
326                "disable_pattern_optimizer",
327                (true, false, false, false, false, false),
328            ),
329            (
330                "disable_statistics_absence_pruning",
331                (false, true, false, false, false, false),
332            ),
333            (
334                "disable_parallel_no_partition",
335                (false, false, true, false, false, false),
336            ),
337            (
338                "disable_managed_aggregates",
339                (false, false, false, true, false, false),
340            ),
341            (
342                "disable_register_aggregate_backend",
343                (false, false, false, false, true, false),
344            ),
345            (
346                "disable_static_extraction",
347                (false, false, false, false, false, true),
348            ),
349        ] {
350            let mut options = ConfigOptions::default();
351            options.extensions.insert(MatchRecognizeConfig::default());
352            options
353                .set(&format!("match_recognize.diagnostics.{leaf}"), "true")
354                .unwrap();
355            let config = options.extensions.get::<MatchRecognizeConfig>().unwrap();
356            assert_eq!(
357                (
358                    config.diagnostics.disable_pattern_optimizer,
359                    config.diagnostics.disable_statistics_absence_pruning,
360                    config.diagnostics.disable_parallel_no_partition,
361                    config.diagnostics.disable_managed_aggregates,
362                    config.diagnostics.disable_register_aggregate_backend,
363                    config.diagnostics.disable_static_extraction,
364                ),
365                expected,
366                "{leaf}"
367            );
368        }
369    }
370
371    #[test]
372    fn numeric_keys_bind_distinct_compilation_cancellation_and_cache_limits() {
373        let mut options = ConfigOptions::default();
374        options.extensions.insert(MatchRecognizeConfig::default());
375        for (leaf, value) in [
376            ("pattern_max_permute_branches", "12"),
377            ("pattern_max_nfa_states", "34"),
378            ("pattern_max_epsilon_closure_entries", "56"),
379            ("pattern_max_dense_transition_cells", "78"),
380            ("cancellation_poll_interval", "17"),
381            ("execution_deadline_millis", "250"),
382            ("single_row_array_cache_max_entries", "17"),
383            ("single_row_array_cache_max_bytes", "4096"),
384        ] {
385            options
386                .set(&format!("match_recognize.limits.{leaf}"), value)
387                .unwrap();
388        }
389        let config = options.extensions.get::<MatchRecognizeConfig>().unwrap();
390        assert_eq!(
391            (
392                config.limits.pattern_max_permute_branches,
393                config.limits.pattern_max_nfa_states,
394                config.limits.pattern_max_epsilon_closure_entries,
395                config.limits.pattern_max_dense_transition_cells,
396                config.limits.cancellation_poll_interval,
397                config.limits.execution_deadline_millis,
398                config.limits.single_row_array_cache_max_entries,
399                config.limits.single_row_array_cache_max_bytes
400            ),
401            (12, 34, 56, 78, 17, 250, 17, 4096)
402        );
403    }
404
405    #[test]
406    fn yield_policy_observes_the_shared_deadline() {
407        assert!(!YieldPolicy::Disabled.is_expired());
408        assert!(YieldPolicy::Deadline(Instant::now()).is_expired());
409        assert!(
410            !YieldPolicy::Deadline(Instant::now() + Duration::from_secs(60)).is_expired()
411        );
412    }
413
414    #[test]
415    fn cancellation_policy_requires_a_nonzero_poll_interval() {
416        let error = CancellationPolicy::try_from_configured(0, 0).unwrap_err();
417        let DataFusionError::Configuration(message) = error else {
418            panic!("expected a configuration error, got {error}");
419        };
420        assert_eq!(
421            message,
422            "match_recognize.limits.cancellation_poll_interval must be greater than 0"
423        );
424
425        let without_deadline = CancellationPolicy::try_from_configured(7, 0).unwrap();
426        assert_eq!(without_deadline.poll_interval().get(), 7);
427        assert_eq!(without_deadline.deadline(), None);
428
429        let with_deadline = CancellationPolicy::try_from_configured(9, 25).unwrap();
430        assert_eq!(with_deadline.poll_interval().get(), 9);
431        assert_eq!(with_deadline.deadline(), Some(Duration::from_millis(25)));
432    }
433}