datafusion-match-recognize 0.56.0

MATCH_RECOGNIZE extension for 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
// 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.

use crate::core::{AbsoluteRow, PhysicalRowCount};
use crate::execution::matching::path::{PathStep, Sym};
use datafusion_common::{DataFusionError, Result};

use super::LaneScanProgram;
use crate::execution::matching::graph::ordered_transitions::OrderedTransitionEdge;

fn invalid(message: &'static str) -> DataFusionError {
    DataFusionError::Internal(format!("MATCH_RECOGNIZE {message}"))
}

fn exhausted(message: &'static str) -> DataFusionError {
    DataFusionError::ResourcesExhausted(format!("MATCH_RECOGNIZE {message}"))
}

pub(crate) fn periodic_phase(start: u32, offset: u64, len: u32) -> Result<usize> {
    if len == 0 || start >= len {
        return Err(DataFusionError::Internal(format!(
            "MATCH_RECOGNIZE lane cycle phase {start} is outside length {len}"
        )));
    }
    if len == 1 {
        return Ok(0);
    }
    let len = u64::from(len);
    // Both terms are below len, so at most one wrap is needed. Their sum
    // fits u64 even when the offset itself is u64::MAX.
    let phase = u64::from(start) + offset % len;
    let phase = if phase >= len { phase - len } else { phase };
    Ok(phase as usize)
}

/// Repeated applications of one edge or one compiler-owned periodic cycle word.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum LanePathBlock {
    Edge(u32),
    Cycle(u32),
}

/// One checked compressed-history run in a fixed-stride lane history.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct LanePathRun {
    block: LanePathBlock,
    start_phase: u32,
    steps: PhysicalRowCount,
    first_row: AbsoluteRow,
}

impl LanePathRun {
    pub(crate) const EMPTY: Self = Self {
        block: LanePathBlock::Edge(0),
        start_phase: 0,
        steps: PhysicalRowCount::ZERO,
        first_row: AbsoluteRow::ZERO,
    };

    pub(crate) const fn steps(self) -> PhysicalRowCount {
        self.steps
    }

    pub(crate) const fn first_row(self) -> AbsoluteRow {
        self.first_row
    }

    /// Decode the run once. Selection and precedence use the same shape checks.
    pub(super) fn edge_and_period(
        &self,
        graph: &LaneScanProgram,
        offset: u64,
    ) -> Result<(OrderedTransitionEdge, u64)> {
        if offset >= self.steps.as_u64() {
            return Err(invalid("lane cursor outside run"));
        }
        let (id, period) = match self.block {
            LanePathBlock::Edge(id) => (id, 1),
            LanePathBlock::Cycle(cycle) => {
                let word = &graph.cycles[cycle as usize];
                let phase = periodic_phase(self.start_phase, offset, word.len() as u32)?;
                (word[phase], word.len() as u64)
            }
        };
        Ok((graph.transitions.sealed_edge(id as usize), period))
    }

    pub(crate) fn repeated_edge(
        edge_id: usize,
        row: AbsoluteRow,
        steps: PhysicalRowCount,
    ) -> Self {
        debug_assert!(u32::try_from(edge_id).is_ok() && steps.as_u64() != 0);
        Self {
            block: LanePathBlock::Edge(edge_id as u32),
            start_phase: 0,
            steps,
            first_row: row,
        }
    }

    pub(crate) fn extend_repeated_edge(
        &mut self,
        edge_id: usize,
        first: AbsoluteRow,
        steps: PhysicalRowCount,
    ) -> Result<bool> {
        if self.steps.as_u64() == 0 || self.block != LanePathBlock::Edge(edge_id as u32) {
            return Ok(false);
        }
        let next = self
            .first_row
            .checked_add(self.steps)
            .ok_or_else(|| exhausted("direct run exceeds row coordinates"))?;
        if first != next || steps.as_u64() == 0 {
            return Err(invalid("non-contiguous direct run"));
        }
        let total = self
            .steps
            .checked_add(steps)
            .ok_or_else(|| exhausted("direct run exceeds u64"))?;
        self.first_row
            .checked_add(total)
            .ok_or_else(|| exhausted("direct run exceeds row coordinates"))?;
        self.steps = total;
        Ok(true)
    }

    pub(crate) fn edge(edge_id: usize, row: AbsoluteRow) -> Self {
        debug_assert!(u32::try_from(edge_id).is_ok());
        Self {
            block: LanePathBlock::Edge(edge_id as u32),
            start_phase: 0,
            steps: PhysicalRowCount::new(1),
            first_row: row,
        }
    }

    pub(crate) const fn cycle(cycle_id: u32, start_phase: u32, row: AbsoluteRow) -> Self {
        Self::cycle_steps(cycle_id, start_phase, row, PhysicalRowCount::new(1))
    }

    pub(crate) const fn cycle_steps(
        cycle_id: u32,
        start_phase: u32,
        row: AbsoluteRow,
        steps: PhysicalRowCount,
    ) -> Self {
        Self {
            block: LanePathBlock::Cycle(cycle_id),
            start_phase,
            steps,
            first_row: row,
        }
    }

    /// Extend only after every checked coordinate and cycle fact is established.
    pub(crate) fn try_extend_cycle(
        &mut self,
        program: &LaneScanProgram,
        edge_id: usize,
        row: AbsoluteRow,
        steps: PhysicalRowCount,
    ) -> Result<bool> {
        let LanePathBlock::Cycle(cycle_id) = self.block else {
            return Ok(false);
        };
        let word = &program.cycles[cycle_id as usize];
        if steps.as_u64() != 1 && word.len() != 1 {
            return Ok(false);
        }
        let phase =
            periodic_phase(self.start_phase, self.steps.as_u64(), word.len() as u32)?;
        if word[phase] as usize != edge_id {
            return Ok(false);
        }
        let expected_row = self
            .first_row
            .checked_add(self.steps)
            .ok_or_else(|| exhausted("lane history row exceeds u64"))?;
        if expected_row != row {
            return Err(invalid("non-contiguous lane cycle"));
        }
        self.steps = self
            .steps
            .checked_add(steps)
            .ok_or_else(|| exhausted("lane run exceeds u64"))?;
        Ok(true)
    }
}

/// Lossless forward cursor over a fixed slice of compressed lane runs.
pub(crate) struct LanePathCursor<'a> {
    program: &'a LaneScanProgram,
    runs: &'a [LanePathRun],
    run_index: usize,
    step_offset: u64,
}

/// Scalar checkpoint into an immutable lane history.
#[derive(Clone, Copy, Default)]
pub(crate) struct LanePathPosition {
    run_index: usize,
    step_offset: u64,
}

impl<'a> LanePathCursor<'a> {
    pub(crate) fn resume_at(&mut self, position: LanePathPosition) {
        self.run_index = position.run_index;
        self.step_offset = position.step_offset;
    }

    pub(crate) const fn position(&self) -> LanePathPosition {
        LanePathPosition {
            run_index: self.run_index,
            step_offset: self.step_offset,
        }
    }
    pub(crate) const fn new(
        program: &'a LaneScanProgram,
        runs: &'a [LanePathRun],
    ) -> Self {
        Self {
            program,
            runs,
            run_index: 0,
            step_offset: 0,
        }
    }

    /// Produce one step, advancing only after its coordinates are checked.
    pub(crate) fn try_next(&mut self) -> Result<Option<PathStep>> {
        let Some(run) = self.runs.get(self.run_index) else {
            return Ok(None);
        };
        let (edge, _) = run.edge_and_period(self.program, self.step_offset)?;
        let row = run
            .first_row
            .checked_add(PhysicalRowCount::new(self.step_offset))
            .ok_or_else(|| exhausted("lane path row exceeds u64"))?;
        let step = PathStep {
            row,
            sym: Sym::from_index(edge.symbol_id.index()),
            excluded: edge.excluded,
        };
        self.step_offset += 1;
        if self.step_offset == run.steps.as_u64() {
            self.run_index += 1;
            self.step_offset = 0;
        }
        Ok(Some(step))
    }
}

#[cfg(test)]
pub(crate) mod tests {
    use super::*;
    use crate::core::{
        NormalizedPattern, Pattern, RepetitionQuantifier, Symbol, SymbolId,
    };
    use crate::execution::matching::graph::ordered_transitions::OrderedTransitionTable;
    use crate::execution::matching::row_loop::lane_scan::{LaneCapacity, graph};
    use crate::nfa::CompiledAutomaton;
    use std::sync::Arc;

    pub(crate) fn repeated_pair_graph() -> LaneScanProgram {
        let compiled = CompiledAutomaton::compile(
            &NormalizedPattern::Ast(Pattern::Repetition(
                Box::new(Pattern::Concat(vec![
                    Pattern::Symbol(Symbol::Named("A".into())),
                    Pattern::Symbol(Symbol::Named("B".into())),
                ])),
                RepetitionQuantifier::OneOrMore,
            )),
            &["A".into(), "B".into()],
        )
        .unwrap();
        let transitions = Arc::new(
            OrderedTransitionTable::try_new(
                &compiled,
                &[
                    SymbolId::try_new(1, compiled.num_symbols()).unwrap(),
                    SymbolId::try_new(2, compiled.num_symbols()).unwrap(),
                ],
            )
            .unwrap(),
        );
        let layout = graph::analyze_graph(&compiled, &transitions)
            .unwrap()
            .unwrap();
        assert_eq!(layout.cycle_words.len(), 1);
        LaneScanProgram {
            initial_registers: [0; crate::core::vm::MAX_REGISTERS],
            register_words: 0,
            navigation_layout: None,
            navigation_words: 0,
            payload_symbols: 0,
            idempotent_last_symbols: 0,
            suffix_reuse: None,
            direct_linear: false,
            state_meta: Box::new([]),
            direct_edges: Box::new([]),
            direct_payload_work: 0,
            transitions,
            closure_accepting: Arc::clone(compiled.unconditional_first_accepting_state()),
            boundary_anchors: super::super::LaneBoundaryAnchors::None,
            cycle_positions: layout.cycle_positions.into(),
            cycles: layout.cycle_words.into(),
            optimistic_history: false,
            // Cursor tests do not allocate a scan slab.
            capacity: LaneCapacity {
                live_lanes: 0,
                path_runs_per_lane: 0,
                encoded_program_bytes: 0,
                source_payload_floor_bytes: 0,
                scan_resource_bytes: 0,
            },
        }
    }

    #[test]
    fn edge_runs_reject_empty_and_out_of_range_offsets() -> Result<()> {
        let graph = repeated_pair_graph();
        let edge = graph
            .transitions
            .sealed_range(graph.transitions.start_state())
            .next()
            .unwrap();
        let mut empty = LanePathRun::EMPTY;
        assert!(!empty.extend_repeated_edge(
            0,
            AbsoluteRow::ZERO,
            PhysicalRowCount::new(1)
        )?);
        assert!(empty.edge_and_period(&graph, 0).is_err());
        let mut run = LanePathRun::edge(edge, AbsoluteRow::new(7));
        assert!(run.extend_repeated_edge(
            edge,
            AbsoluteRow::new(8),
            PhysicalRowCount::new(2)
        )?);
        let runs = [run];
        let mut cursor = LanePathCursor::new(&graph, &runs);
        for row in 7..10 {
            assert_eq!(cursor.try_next()?.unwrap().row, AbsoluteRow::new(row));
        }
        assert!(cursor.try_next()?.is_none());
        assert!(run.edge_and_period(&graph, 3).is_err());
        assert!(run.edge_and_period(&graph, u64::MAX).is_err());
        Ok(())
    }

    #[test]
    fn lane_history_rejects_gaps_before_selected_publication() {
        use crate::execution::common::memory::new_unbounded_state_memory;
        use crate::execution::matching::row_loop::lane_scan::{
            CompactSelection, LaneState, state::LaneScanState,
        };

        let origin = AbsoluteRow::new(7);
        let next = AbsoluteRow::new(8);
        let gap = AbsoluteRow::new(9);
        for disable_cycles in [false, true] {
            let mut graph = repeated_pair_graph();
            if disable_cycles {
                graph.cycle_positions.fill(u64::MAX);
            }
            graph.capacity.live_lanes = 1;
            graph.capacity.path_runs_per_lane = 3;
            graph.capacity.scan_resource_bytes =
                4 * (size_of::<LaneState>() + 3 * size_of::<LanePathRun>());
            let graph = Arc::new(graph);
            let start = graph.transitions.start_state();
            let first = graph.transitions.sealed_range(start).next().unwrap();
            let second_state = graph.transitions.sealed_edge(first).next_state_id;
            let second = graph.transitions.sealed_range(second_state).next().unwrap();
            let mut lane =
                LaneScanState::try_new(Arc::clone(&graph), &new_unbounded_state_memory())
                    .unwrap();
            lane.start_candidate(origin);
            lane.prepare_transition(0, false).unwrap();
            assert!(lane.apply_scratch_transition(start, first, next).is_err());
            lane.apply_scratch_transition(start, first, origin).unwrap();
            assert!(
                lane.apply_scratch_transition(second_state, second, gap)
                    .is_err()
            );
            lane.apply_scratch_transition(second_state, second, next)
                .unwrap();

            let runs = [
                LanePathRun::edge(first, origin),
                LanePathRun::edge(second, next),
            ];
            assert!(CompactSelection::try_new(&graph, &runs, origin, next, gap).is_ok());
            assert!(CompactSelection::try_new(&graph, &runs, next, next, gap).is_err());
            assert!(CompactSelection::try_new(&graph, &runs, origin, gap, gap).is_err());
            assert!(
                CompactSelection::try_new(&graph, &runs, origin, next, origin).is_err()
            );
        }
    }

    #[test]
    fn cycle_phase_wraps_without_narrowing_large_offsets() {
        for len in [1, 2, 3, 17, u32::MAX] {
            for start in [0, len - 1] {
                for offset in [
                    0,
                    1,
                    u64::from(len) - 1,
                    u64::from(len),
                    u64::from(len) + 1,
                    u64::MAX - 1,
                    u64::MAX,
                ] {
                    let expected =
                        (u128::from(start) + u128::from(offset)) % u128::from(len);
                    assert_eq!(
                        periodic_phase(start, offset, len).unwrap(),
                        expected as usize,
                        "start={start}, offset={offset}, len={len}"
                    );
                }
            }
        }
        for (start, len) in [(0, 0), (1, 1), (2, 2), (u32::MAX, u32::MAX)] {
            assert!(periodic_phase(start, u64::MAX, len).is_err());
        }
    }
}