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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
// 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.

//! Resumable row, transition-loop, scan, and collection progress markers.

use crate::execution::matching::path::PathNodeIndex;
use crate::nfa::{AnchorEnvironment, AutomatonStateId};
use datafusion::common::{DataFusionError, Result};

pub(crate) use crate::execution::common::work::WorkGovernor;
pub(crate) use crate::execution::matching::selection::{AcceptingCandidate, BestMatch};

/// Version of the dense active-state container.
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub(crate) struct ActiveContainerGeneration(u64);

impl ActiveContainerGeneration {
    #[cfg(test)]
    pub(crate) const fn new(value: u64) -> Self {
        Self(value)
    }

    pub(crate) const fn get(self) -> u64 {
        self.0
    }

    pub(crate) const fn next(self) -> Self {
        let next = self.0.wrapping_add(1);
        Self(if next == 0 { 1 } else { next })
    }
}

/// Stable identity bound to an outer transition-loop cursor.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct ActiveResumeIdentity {
    pub(crate) active_idx: usize,
    pub(crate) container_generation: ActiveContainerGeneration,
    pub(crate) state_id: AutomatonStateId,
    pub(crate) path: Option<PathNodeIndex>,
}

impl ActiveResumeIdentity {
    pub(crate) const fn new(
        active_idx: usize,
        container_generation: ActiveContainerGeneration,
        state_id: AutomatonStateId,
        path: Option<PathNodeIndex>,
    ) -> Self {
        Self {
            active_idx,
            container_generation,
            state_id,
            path,
        }
    }
}

/// An active cursor identity and its row-local match sequence, once resolved.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct ActiveCursorBinding {
    identity: ActiveResumeIdentity,
    match_sequence: Option<i64>,
}

impl ActiveCursorBinding {
    fn new(identity: ActiveResumeIdentity) -> Self {
        Self {
            identity,
            match_sequence: None,
        }
    }
}

/// Backing storage used by the current active state's epsilon traversal.
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum EpsilonSource {
    #[default]
    Unbound,
    Precomputed,
    Anchored(AnchorEnvironment),
    Scratch {
        generation: u32,
    },
}

/// State for resumable NFA transition processing within a single row.
///
/// Tracks five cursors; both symbol loops share the innermost `next_idx`:
/// ```text
/// for active_state in active_states {           // active_idx
///     for eps_state in epsilon_closure {        // eps_idx
///         for symbol in matched_symbols {       // sym_idx
///             for next in transitions[symbol] { // next_idx
///                 // process transition
///             }
///         }
///         for symbol in match_aware_symbols {   // match_aware_sym_idx
///             for next in transitions[symbol] { // next_idx
///                 // process transition
///             }
///         }
///     }
/// }
/// ```
///
/// Its `advance_*` methods own retained cursor mutation; the common graph
/// traversal owns loop boundaries and last-edge decisions.
#[derive(Default, Debug, Clone, PartialEq, Eq)]
pub(crate) struct TransitionLoopState {
    /// Index into `active_states` slice (outermost loop)
    pub active_idx: usize,
    /// Index into epsilon closure results (2nd loop)
    pub eps_idx: usize,
    /// Index into matched symbols (3rd loop)
    pub sym_idx: usize,
    /// Index into transition targets (innermost loop)
    pub next_idx: usize,
    /// Exact source addressed by `eps_idx` for the current active state.
    pub(crate) epsilon_source: EpsilonSource,
    /// Index into match-aware symbols, retained across yields.
    pub match_aware_sym_idx: usize,
    /// Active element addressed by the nested cursors.
    pub(crate) active_cursor: Option<ActiveCursorBinding>,
}

/// Stable row-local values published after symbol evaluation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct SymbolsReadyFrame {
    define_cache_generation: u32,
    matched_bitmap: u64,
}

impl SymbolsReadyFrame {
    pub(crate) const fn define_cache_generation(&self) -> u32 {
        self.define_cache_generation
    }

    pub(crate) const fn matched_bitmap(&self) -> u64 {
        self.matched_bitmap
    }
}

/// Exact transition traversal state retained across cooperative returns.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct TransitionFrame {
    symbols: SymbolsReadyFrame,
    active_generation: ActiveContainerGeneration,
    loops: TransitionLoopState,
}

impl TransitionFrame {
    pub(crate) const fn symbols(&self) -> SymbolsReadyFrame {
        self.symbols
    }

    #[cfg(test)]
    pub(crate) const fn active_generation(&self) -> ActiveContainerGeneration {
        self.active_generation
    }

    #[cfg(test)]
    pub(crate) const fn loops(&self) -> &TransitionLoopState {
        &self.loops
    }

    pub(crate) fn loops_mut(&mut self) -> &mut TransitionLoopState {
        &mut self.loops
    }

    pub(crate) fn validate_active_generation(
        &self,
        current: ActiveContainerGeneration,
    ) -> Result<()> {
        if self.active_generation.get() == 0 {
            return datafusion::common::internal_err!(
                "MATCH_RECOGNIZE transition frame has an unbound active generation"
            );
        }
        if self.active_generation != current {
            return datafusion::common::internal_err!(
                "MATCH_RECOGNIZE transition frame generation {:?} does not match active container {:?}",
                self.active_generation,
                current
            );
        }
        Ok(())
    }

    pub(crate) fn validate_define_cache_generation(&self, current: u32) -> Result<()> {
        if self.symbols.define_cache_generation != current {
            return datafusion::common::internal_err!(
                "MATCH_RECOGNIZE transition frame cache generation {} does not match prepared cache generation {current}",
                self.symbols.define_cache_generation
            );
        }
        Ok(())
    }
}

/// The current phase of a resumable candidate scan.
///
/// The frame and its cursors distinguish work already committed from the next
/// unfinished unit. The driver advances them before a cooperative yield,
/// so resumption cannot repeat row preparation, a state update, predicate
/// evaluation, edge finalization, history verification, or row publication.
#[derive(Debug, Default)]
pub(crate) enum ResumeFrame {
    #[default]
    StartRow,
    Transitions(TransitionFrame),
}

impl ResumeFrame {
    pub(crate) const fn name(&self) -> &'static str {
        match self {
            Self::StartRow => "StartRow",
            Self::Transitions(_) => "Transitions",
        }
    }

    pub(crate) const fn is_start_row(&self) -> bool {
        matches!(self, Self::StartRow)
    }

    #[cfg(test)]
    pub(crate) const fn is_transitions(&self) -> bool {
        matches!(self, Self::Transitions(_))
    }

    /// Whether the frame owns an unfinished physical input row.
    pub(crate) const fn is_row_in_progress(&self) -> bool {
        matches!(self, Self::Transitions(_))
    }

    #[cfg(test)]
    pub(crate) const fn transition(&self) -> Option<&TransitionFrame> {
        match self {
            Self::Transitions(frame) => Some(frame),
            Self::StartRow => None,
        }
    }

    pub(crate) fn transition_mut(&mut self) -> Option<&mut TransitionFrame> {
        match self {
            Self::Transitions(frame) => Some(frame),
            Self::StartRow => None,
        }
    }

    pub(crate) fn begin_transitions(
        &mut self,
        define_cache_generation: u32,
        matched_bitmap: u64,
        active_generation: ActiveContainerGeneration,
    ) -> Result<()> {
        if define_cache_generation == 0 {
            return datafusion::common::internal_err!(
                "MATCH_RECOGNIZE cannot publish transitions with an unbound cache generation"
            );
        }
        if active_generation.get() == 0 {
            return datafusion::common::internal_err!(
                "MATCH_RECOGNIZE cannot begin transitions with an unbound active generation"
            );
        }
        if !matches!(self, Self::StartRow) {
            return datafusion::common::internal_err!(
                "MATCH_RECOGNIZE cannot begin transitions from resume phase {}",
                self.name()
            );
        }
        *self = Self::Transitions(TransitionFrame {
            symbols: SymbolsReadyFrame {
                define_cache_generation,
                matched_bitmap,
            },
            active_generation,
            loops: TransitionLoopState::default(),
        });
        Ok(())
    }

    pub(crate) fn finish_row(&mut self) -> Result<()> {
        if !matches!(self, Self::Transitions(_)) {
            return datafusion::common::internal_err!(
                "MATCH_RECOGNIZE cannot finish a row from resume phase {}",
                self.name()
            );
        }
        *self = Self::StartRow;
        Ok(())
    }
}

impl TransitionLoopState {
    /// Bind the current state's epsilon source and restart its index.
    #[inline]
    pub(crate) fn mark_epsilon_ready(&mut self, source: EpsilonSource) {
        debug_assert!(!matches!(source, EpsilonSource::Unbound));
        debug_assert!(!matches!(source, EpsilonSource::Scratch { generation: 0 }));
        self.epsilon_source = source;
        self.eps_idx = 0;
    }

    pub(crate) const fn epsilon_source(&self) -> EpsilonSource {
        self.epsilon_source
    }

    pub(crate) fn validate_epsilon_scratch_generation(&self, current: u32) -> Result<()> {
        let EpsilonSource::Scratch { generation } = self.epsilon_source else {
            return Ok(());
        };
        if generation == 0 {
            return datafusion::common::internal_err!(
                "MATCH_RECOGNIZE epsilon scratch source has an unbound generation"
            );
        }
        if generation != current {
            return datafusion::common::internal_err!(
                "MATCH_RECOGNIZE epsilon scratch generation {generation} does not match current generation {current}"
            );
        }
        Ok(())
    }

    /// Advance next-state index in the innermost transition loop.
    #[inline]
    pub fn advance_next_idx(&mut self) {
        self.next_idx += 1;
    }

    /// Advance regular symbol loop and reset inner next-state traversal.
    #[inline]
    pub fn advance_regular_symbol(&mut self) {
        self.sym_idx += 1;
        self.next_idx = 0;
    }

    /// Advance match-aware-symbol traversal and reset inner target traversal.
    #[inline]
    pub fn advance_match_aware_symbol(&mut self) {
        self.match_aware_sym_idx += 1;
        self.next_idx = 0;
    }

    /// Move to next epsilon state and reset symbol-level traversal.
    #[inline]
    pub fn advance_epsilon_state(&mut self) {
        self.reset_inner_transition_cursors();
        self.eps_idx += 1;
    }

    /// Move to the next active state and mark its epsilon closure as not yet computed.
    #[inline]
    pub fn advance_active_state(&mut self) {
        self.reset_inner_transition_cursors();
        self.eps_idx = 0;
        self.epsilon_source = EpsilonSource::Unbound;
        self.active_idx += 1;
        self.active_cursor = None;
    }

    #[inline]
    fn reset_inner_transition_cursors(&mut self) {
        self.sym_idx = 0;
        self.next_idx = 0;
        self.match_aware_sym_idx = 0;
    }

    /// Bind a fresh outer cursor or validate the identity retained across a resume.
    pub(crate) fn bind_or_validate_active_identity(
        &mut self,
        expected: ActiveResumeIdentity,
    ) -> Result<()> {
        match self.active_identity() {
            None => {
                self.active_cursor = Some(ActiveCursorBinding::new(expected));
                Ok(())
            }
            Some(bound) if bound == expected => Ok(()),
            Some(bound) => datafusion::common::internal_err!(
                "MATCH_RECOGNIZE active cursor identity mismatch: bound {:?}, current {:?}",
                bound,
                expected
            ),
        }
    }

    pub(crate) const fn active_identity(&self) -> Option<ActiveResumeIdentity> {
        match self.active_cursor {
            Some(cursor) => Some(cursor.identity),
            None => None,
        }
    }

    /// Return the metadata value correlated with the bound active cursor.
    pub(crate) fn cached_active_match_sequence(&self) -> Result<Option<i64>> {
        let cursor = self.active_cursor.as_ref().ok_or_else(|| {
            DataFusionError::Internal(
                "MATCH_RECOGNIZE cannot read match-sequence metadata for an unbound active cursor"
                    .to_string(),
            )
        })?;
        Ok(cursor.match_sequence)
    }

    /// Publish a successfully resolved value for the exact bound identity.
    pub(crate) fn publish_active_match_sequence(&mut self, value: i64) -> Result<()> {
        let cursor = self.active_cursor.as_mut().ok_or_else(|| {
            DataFusionError::Internal(
                "MATCH_RECOGNIZE cannot publish match-sequence metadata for an unbound active cursor"
                    .to_string(),
            )
        })?;
        match cursor.match_sequence {
            None => {
                cursor.match_sequence = Some(value);
                Ok(())
            }
            Some(cached) if cached == value => Ok(()),
            Some(cached) => datafusion::common::internal_err!(
                "MATCH_RECOGNIZE active match-sequence cache conflict for {:?}: cached value {}, new value {}",
                cursor.identity,
                cached,
                value
            ),
        }
    }

    /// Whether an unbound outer cursor is at a safe between-state boundary.
    pub(crate) const fn is_clean_unbound_active_cursor(&self) -> bool {
        self.active_cursor.is_none()
            && self.eps_idx == 0
            && self.sym_idx == 0
            && self.next_idx == 0
            && matches!(self.epsilon_source, EpsilonSource::Unbound)
            && self.match_aware_sym_idx == 0
    }
}

/// State for one resumable candidate scan.
///
/// This state persists across yields, allowing the NFA simulation to be suspended
/// and resumed without losing progress.
#[derive(Default, Debug)]
pub(crate) struct ScanState {
    /// Current row being processed in the NFA simulation
    pub current_row: usize,
    /// Typed row-loop continuation and the invariants required to resume it.
    pub(crate) resume: ResumeFrame,
    /// Best resolved accepting path found so far.
    pub(crate) incumbent: Option<AcceptingCandidate>,
    /// Unified completed-work, voluntary-yield, and cancellation accounting.
    pub governor: WorkGovernor,
}

impl ScanState {
    /// Reset for a new scan starting at `start_row`
    pub fn reset(&mut self, start_row: usize) {
        self.current_row = start_row;
        self.resume = ResumeFrame::StartRow;
        self.incumbent = None;
        // Sampling, cancellation, and the progress epoch survive candidate resets.
    }
}