datafusion-match-recognize 0.56.1

SQL MATCH_RECOGNIZE row-pattern matching for Apache DataFusion
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
// Licensed under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.
//
// This product includes software developed at Datadog (https://www.datadoghq.com/) Copyright 2025-Present Datadog, Inc.

//! Configuration options for MATCH_RECOGNIZE pattern matching.
//!
//! Session-scoped options can be set with SQL `SET` statements or through
//! `SessionConfig`.
//!
//! User resource limits, advanced scheduler settings, and diagnostic algorithm
//! overrides are separate records. SQL keys therefore make the distinction
//! explicit, for example `match_recognize.limits.pattern_max_nfa_states` and
//! `match_recognize.diagnostics.disable_pattern_optimizer`.

use std::num::NonZeroUsize;
use std::time::{Duration, Instant};

use crate::nfa::PatternCompileLimits;
use datafusion::common::{DataFusionError, config::ConfigExtension, extensions_options};

/// Default maximum number of dynamic scalar/array pairs retained per scan.
pub const DEFAULT_SINGLE_ROW_ARRAY_CACHE_MAX_ENTRIES: usize = 256;
/// Default maximum live-entry bytes for dynamic scalar/array pairs per scan.
pub const DEFAULT_SINGLE_ROW_ARRAY_CACHE_MAX_BYTES: usize = 1024 * 1024;
/// Hard ceiling that bounds one cache eviction-planning pass.
pub(crate) const MAX_SINGLE_ROW_ARRAY_CACHE_ENTRIES: usize = 4096;
/// Hard ceiling for scan-local dynamic live-entry bytes.
pub(crate) const MAX_SINGLE_ROW_ARRAY_CACHE_BYTES: usize = 64 * 1024 * 1024;

/// One active poll's shared scheduling deadline, copied into resumable work.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum YieldPolicy {
    /// Disable voluntary time slicing. Cancellation remains independent.
    Disabled,
    Deadline(Instant),
    /// Deterministic safe-point selection for continuation tests only.
    #[cfg(test)]
    TestBudget(NonZeroUsize),
}

impl YieldPolicy {
    #[cfg(test)]
    pub(crate) const fn from_test_budget(budget: usize) -> Self {
        match NonZeroUsize::new(budget) {
            Some(budget) => Self::TestBudget(budget),
            None => Self::Disabled,
        }
    }

    pub(crate) fn is_expired(self) -> bool {
        match self {
            Self::Disabled => false,
            Self::Deadline(deadline) => Instant::now() >= deadline,
            #[cfg(test)]
            Self::TestBudget(_) => false,
        }
    }
}

/// Default completed-work countdown interval between cancellation probes.
pub const DEFAULT_CANCELLATION_POLL_INTERVAL: usize = 256;

/// Bound cancellation settings installed into one persistent row-loop scan.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct CancellationPolicy {
    poll_interval: NonZeroUsize,
    deadline: Option<Duration>,
}

impl CancellationPolicy {
    /// Validate configured cancellation settings before a scan starts work.
    pub(crate) fn try_from_configured(
        poll_interval: usize,
        deadline_millis: usize,
    ) -> datafusion::common::Result<Self> {
        let poll_interval = NonZeroUsize::new(poll_interval).ok_or_else(|| {
            DataFusionError::Configuration("match_recognize.limits.cancellation_poll_interval must be greater than 0".into())
        })?;
        let millis = u64::try_from(deadline_millis).map_err(|_| {
            DataFusionError::Configuration("match_recognize.limits.execution_deadline_millis is too large to represent as a u64 number of milliseconds".into())
        })?;
        let deadline = (millis != 0).then(|| Duration::from_millis(millis));
        Ok(Self {
            poll_interval,
            deadline,
        })
    }

    pub(crate) const fn poll_interval(self) -> NonZeroUsize {
        self.poll_interval
    }

    pub(crate) const fn deadline(self) -> Option<Duration> {
        self.deadline
    }
}

/// Default multiplier for parallel_no_partition_min_rows_per_task.
/// The actual default is this value multiplied by batch_size.
pub const DEFAULT_PARALLEL_MIN_ROWS_MULTIPLIER: usize = 8;

/// Default batch size used when computing parallel_no_partition_min_rows_per_task.
pub const DEFAULT_BATCH_SIZE: usize = 8192;

extensions_options! {
    /// Stable resource and safety limits for pattern matching.
    pub struct MatchRecognizeLimits {
        /// Soft active-work slice in microseconds, shared by matching and its
        /// resumable preparation/output phases. Native calls stay atomic, so
        /// this is not a latency bound. Zero disables voluntary slices, not
        /// cancellation polling, the ready-input guard, or native scheduler cooperation.
        pub yield_slice_micros: usize, default = 1000
        /// Positive completed-work countdown interval for abort-signal and
        /// execution-deadline probes. Polling occurs at completed-work call
        /// boundaries, so one nonresumable charged batch may overshoot it. A
        /// zero value is rejected before a scan begins.
        pub cancellation_poll_interval: usize, default = DEFAULT_CANCELLATION_POLL_INTERVAL
        /// Optional elapsed execution deadline in milliseconds, applied
        /// independently to every row-loop scan governor and to the stream's
        /// storage governor.
        /// Zero disables the deadline; abort-signal polling remains enabled.
        pub execution_deadline_millis: usize, default = 0
        /// Maximum deduplicated `PERMUTE(...)` branches.
        pub pattern_max_permute_branches: usize, default = PatternCompileLimits::DEFAULT.max_permute_branches
        /// Maximum compiled NFA states.
        pub pattern_max_nfa_states: usize, default = PatternCompileLimits::DEFAULT.max_nfa_states
        /// Maximum retained epsilon-closure entries.
        pub pattern_max_epsilon_closure_entries: usize, default = PatternCompileLimits::DEFAULT.max_epsilon_closure_entries
        /// Maximum NFA transition-table entries (`states × symbol IDs`).
        pub pattern_max_dense_transition_cells: usize, default = PatternCompileLimits::DEFAULT.max_dense_transition_cells
        /// Maximum non-common entries retained by the scan-local one-row Arrow
        /// array cache. Zero disables dynamic retention; fixed null, Boolean,
        /// and small-integer slots remain available. Values above 4,096 are
        /// rejected before fallback evaluation begins.
        pub single_row_array_cache_max_entries: usize, default = DEFAULT_SINGLE_ROW_ARRAY_CACHE_MAX_ENTRIES
        /// Maximum conservative live-entry bytes in the dynamic one-row Arrow
        /// array cache. The memory pool also covers reusable LRU storage.
        /// Zero disables dynamic retention. Values above 64 MiB are rejected
        /// before fallback evaluation begins.
        pub single_row_array_cache_max_bytes: usize, default = DEFAULT_SINGLE_ROW_ARRAY_CACHE_MAX_BYTES
    }
}

impl MatchRecognizeLimits {
    pub(crate) fn active_slice_duration(
        &self,
    ) -> datafusion::common::Result<Option<Duration>> {
        let Some(micros) = NonZeroUsize::new(self.yield_slice_micros) else {
            return Ok(None);
        };
        let micros = u64::try_from(micros.get()).map_err(|_| {
            DataFusionError::Configuration(
                "match_recognize.limits.yield_slice_micros is too large to represent as a u64 number of microseconds".into(),
            )
        })?;
        Ok(Some(Duration::from_micros(micros)))
    }

    pub(crate) const fn pattern_compile_limits(&self) -> PatternCompileLimits {
        PatternCompileLimits {
            max_permute_branches: self.pattern_max_permute_branches,
            max_nfa_states: self.pattern_max_nfa_states,
            max_epsilon_closure_entries: self.pattern_max_epsilon_closure_entries,
            max_dense_transition_cells: self.pattern_max_dense_transition_cells,
        }
    }
}

extensions_options! {
    /// Advanced parallel scheduler settings.
    pub struct MatchRecognizeSchedulerConfig {
        /// Minimum core rows per parallel Halo task, with or without `PARTITION BY`.
        /// Zero keeps keyed queries on ordinary matching and is rejected for
        /// otherwise eligible queries without `PARTITION BY`.
        pub parallel_no_partition_min_rows_per_task: usize, default = DEFAULT_PARALLEL_MIN_ROWS_MULTIPLIER * DEFAULT_BATCH_SIZE
    }
}

extensions_options! {
    /// Unstable diagnostic overrides used by differential tests and debugging.
    ///
    /// These switches select implementation fallbacks; they are not durable
    /// application policy.
    pub struct MatchRecognizeDiagnostics {
        /// Disable runtime pruning of static symbols absent from a complete input
        /// window. Construction-time normalization remains enabled.
        pub disable_pattern_optimizer: bool, default = false
        /// Keep DataFusion's input sort when planning a partitioned matcher.
        pub disable_hash_grouped_ordering: bool, default = false
        /// Keep every logical partition when hash-grouped ordering is selected.
        pub disable_pre_sort_partition_pruning: bool, default = false
        /// Disable construction-time pruning of static symbols proven absent by
        /// exact overall input statistics. Structural normalization remains enabled.
        pub disable_statistics_absence_pruning: bool, default = false
        /// Force arena-backed path storage for patterns otherwise eligible for compact paths,
        /// and disable direct-linear scan loops.
        pub disable_compact_paths: bool, default = false
        /// Disable bounded core-and-halo parallel planning and use ordinary
        /// matching, distributing SQL partition keys across workers when present.
        pub disable_parallel_no_partition: bool, default = false
        /// Disable planning-time managed aggregate extraction and evaluate the
        /// complete match-aware `DEFINE` expression against the bounded history slice.
        pub disable_managed_aggregates: bool, default = false
        /// Disable register-backed managed aggregates.
        pub disable_register_aggregate_backend: bool, default = false
        /// Disable planning-time static subexpression extraction.
        ///
        /// The full `DEFINE` predicates remain on their normal evaluators, no
        /// generated `__mr_static_*` columns are projected, and runtime has no
        /// static extraction prechecks. Match-independent Window inputs are
        /// still planned and rebased normally.
        pub disable_static_extraction: bool, default = false
    }
}

extensions_options! {
    /// Session-scoped `MATCH_RECOGNIZE` configuration.
    ///
    /// Insert the configuration before creating the session-state builder:
    ///
    /// ```rust
    /// use datafusion::execution::SessionStateBuilder;
    /// use datafusion::prelude::SessionConfig;
    /// use datafusion_match_recognize::MatchRecognizeConfig;
    ///
    /// let mut session_config = SessionConfig::new();
    /// let mut match_config = MatchRecognizeConfig::default();
    /// match_config.limits.execution_deadline_millis = 30_000;
    /// session_config.options_mut().extensions.insert(match_config);
    ///
    /// let _builder = SessionStateBuilder::new()
    ///     .with_default_features()
    ///     .with_config(session_config);
    /// ```
    pub struct MatchRecognizeConfig {
        /// Stable resource and compiler limits.
        pub limits: MatchRecognizeLimits, default = MatchRecognizeLimits::default()
        /// Advanced scheduling settings.
        pub scheduler: MatchRecognizeSchedulerConfig, default = MatchRecognizeSchedulerConfig::default()
        /// Unstable diagnostic implementation overrides.
        pub diagnostics: MatchRecognizeDiagnostics, default = MatchRecognizeDiagnostics::default()
    }
}

impl ConfigExtension for MatchRecognizeConfig {
    const PREFIX: &'static str = "match_recognize";
}

#[cfg(test)]
mod tests {
    use super::*;
    use datafusion::common::config::ConfigOptions;

    #[test]
    fn public_defaults_bound_scheduling_and_compilation() {
        let config = MatchRecognizeConfig::default();
        assert_eq!(
            (
                config.diagnostics.disable_pattern_optimizer,
                config.diagnostics.disable_statistics_absence_pruning,
                config.diagnostics.disable_parallel_no_partition
            ),
            (false, false, false)
        );
        assert_eq!(
            config.scheduler.parallel_no_partition_min_rows_per_task,
            65_536
        );
        assert_eq!(config.limits.yield_slice_micros, 1000);
        assert_eq!(config.limits.cancellation_poll_interval, 256);
        assert_eq!(config.limits.execution_deadline_millis, 0);
        assert_eq!(
            (
                config.limits.pattern_max_permute_branches,
                config.limits.pattern_max_nfa_states,
                config.limits.pattern_max_epsilon_closure_entries,
                config.limits.pattern_max_dense_transition_cells,
                config.limits.single_row_array_cache_max_entries,
                config.limits.single_row_array_cache_max_bytes
            ),
            (5_040, 250_000, 3_000_000, 4_000_000, 256, 1_048_576)
        );
        assert_eq!(
            (
                config.diagnostics.disable_managed_aggregates,
                config.diagnostics.disable_register_aggregate_backend,
                config.diagnostics.disable_static_extraction
            ),
            (false, false, false)
        );
    }

    #[test]
    fn config_advertises_limits_and_diagnostics_controls() {
        let mut options = ConfigOptions::default();
        options.extensions.insert(MatchRecognizeConfig::default());
        let entries = options.entries();
        for key in [
            "cancellation_poll_interval",
            "disable_compact_paths",
            "single_row_array_cache_max_entries",
            "single_row_array_cache_max_bytes",
            "disable_managed_aggregates",
            "disable_register_aggregate_backend",
            "disable_static_extraction",
        ] {
            assert!(entries.iter().any(|entry| entry.key == key), "{key}");
        }
    }

    #[test]
    fn diagnostic_keys_bind_only_their_named_control() {
        for (leaf, expected) in [
            (
                "disable_pattern_optimizer",
                (true, false, false, false, false, false),
            ),
            (
                "disable_statistics_absence_pruning",
                (false, true, false, false, false, false),
            ),
            (
                "disable_parallel_no_partition",
                (false, false, true, false, false, false),
            ),
            (
                "disable_managed_aggregates",
                (false, false, false, true, false, false),
            ),
            (
                "disable_register_aggregate_backend",
                (false, false, false, false, true, false),
            ),
            (
                "disable_static_extraction",
                (false, false, false, false, false, true),
            ),
        ] {
            let mut options = ConfigOptions::default();
            options.extensions.insert(MatchRecognizeConfig::default());
            options
                .set(&format!("match_recognize.diagnostics.{leaf}"), "true")
                .unwrap();
            let config = options.extensions.get::<MatchRecognizeConfig>().unwrap();
            assert_eq!(
                (
                    config.diagnostics.disable_pattern_optimizer,
                    config.diagnostics.disable_statistics_absence_pruning,
                    config.diagnostics.disable_parallel_no_partition,
                    config.diagnostics.disable_managed_aggregates,
                    config.diagnostics.disable_register_aggregate_backend,
                    config.diagnostics.disable_static_extraction,
                ),
                expected,
                "{leaf}"
            );
        }
    }

    #[test]
    fn numeric_keys_bind_distinct_compilation_cancellation_and_cache_limits() {
        let mut options = ConfigOptions::default();
        options.extensions.insert(MatchRecognizeConfig::default());
        for (leaf, value) in [
            ("pattern_max_permute_branches", "12"),
            ("pattern_max_nfa_states", "34"),
            ("pattern_max_epsilon_closure_entries", "56"),
            ("pattern_max_dense_transition_cells", "78"),
            ("cancellation_poll_interval", "17"),
            ("execution_deadline_millis", "250"),
            ("single_row_array_cache_max_entries", "17"),
            ("single_row_array_cache_max_bytes", "4096"),
        ] {
            options
                .set(&format!("match_recognize.limits.{leaf}"), value)
                .unwrap();
        }
        let config = options.extensions.get::<MatchRecognizeConfig>().unwrap();
        assert_eq!(
            (
                config.limits.pattern_max_permute_branches,
                config.limits.pattern_max_nfa_states,
                config.limits.pattern_max_epsilon_closure_entries,
                config.limits.pattern_max_dense_transition_cells,
                config.limits.cancellation_poll_interval,
                config.limits.execution_deadline_millis,
                config.limits.single_row_array_cache_max_entries,
                config.limits.single_row_array_cache_max_bytes
            ),
            (12, 34, 56, 78, 17, 250, 17, 4096)
        );
    }

    #[test]
    fn yield_policy_observes_the_shared_deadline() {
        assert!(!YieldPolicy::Disabled.is_expired());
        assert!(YieldPolicy::Deadline(Instant::now()).is_expired());
        assert!(
            !YieldPolicy::Deadline(Instant::now() + Duration::from_secs(60)).is_expired()
        );
    }

    #[test]
    fn cancellation_policy_requires_a_nonzero_poll_interval() {
        let error = CancellationPolicy::try_from_configured(0, 0).unwrap_err();
        let DataFusionError::Configuration(message) = error else {
            panic!("expected a configuration error, got {error}");
        };
        assert_eq!(
            message,
            "match_recognize.limits.cancellation_poll_interval must be greater than 0"
        );

        let without_deadline = CancellationPolicy::try_from_configured(7, 0).unwrap();
        assert_eq!(without_deadline.poll_interval().get(), 7);
        assert_eq!(without_deadline.deadline(), None);

        let with_deadline = CancellationPolicy::try_from_configured(9, 25).unwrap();
        assert_eq!(with_deadline.poll_interval().get(), 9);
        assert_eq!(with_deadline.deadline(), Some(Duration::from_millis(25)));
    }
}