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
// 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.

//! Share Lane failure searches without selecting a match path.
//!
//! At a fixed row and automaton state, the earliest start dominates every later
//! start: static predicates give them identical possible continuations. Once a
//! start accepts, only earlier live starts can improve it. The ordinary scanner
//! still resolves the returned start's preferences, captures, and output.

use super::LaneScanProgram;
use crate::config::YieldPolicy;
use crate::execution::common::progress::COARSE_WORK_BATCH_SIZE;
use crate::execution::common::{memory::try_reserve_accounted, work::WorkGovernor};
use crate::execution::matching::row_loop::compiled_program::ExecutablePatternVariant;
use crate::execution::matching::symbols::BoolColumnProvider;
use crate::execution::storage::collection::BatchCollection;
use crate::nfa::AutomatonStateId;
use datafusion::arrow::{array::AsArray, datatypes::UInt64Type};
use datafusion::common::{DataFusionError, Result};
use datafusion::execution::memory_pool::MemoryReservation;
use std::sync::Arc;

const UNSEEN: usize = usize::MAX;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum StaticSearchStep {
    Yield,
    /// Earliest accepted start, or the earliest still-live start at an open
    /// input boundary. The ordinary scanner resolves its match or input need.
    Found(usize),
    Exhausted,
}

#[derive(Clone, Copy, PartialEq, Eq)]
enum PackedFrontier {
    Ordinary,
    Comparing,
    Fixed,
}

/// Setup cost used by the caller to avoid sharing short, inexpensive failures.
pub(crate) fn graph_work_threshold(graph: &LaneScanProgram) -> Option<usize> {
    if graph.requires_partition_start() || graph.requires_partition_end() {
        return None;
    }
    graph
        .closure_accepting
        .len()
        .checked_add(graph.transitions.edge_count())
}

/// A search over one fixed readable input window.
///
/// An admitted Lane graph supplies the complete consuming edges and acceptance
/// table. General scans share starts natively and do not use this guard. State
/// tables retain only minimum starts; sparse lists avoid touching the entire
/// graph per row. No provider or borrowed input survives `advance`.
pub(crate) struct StaticStartSearch {
    graph: Arc<LaneScanProgram>,
    current: Vec<usize>,
    next: Vec<usize>,
    active: Vec<AutomatonStateId>,
    next_active: Vec<AutomatonStateId>,
    row: usize,
    // Exclusive bounds on eligible starts and readable rows, respectively.
    start_end: usize,
    end: usize,
    final_input: bool,
    best: Option<usize>,
    source: usize,
    known: u64,
    physical_mask: u64,
    eager: u64,
    eligible: u64,
    previous_word: Option<u64>,
    packed_frontier: PackedFrontier,
    // Drop graph and scratch owners before their accounting leases.
    _memory: MemoryReservation,
    _variant: Arc<ExecutablePatternVariant>,
}

impl StaticStartSearch {
    /// Admit optional search scratch. A declined allocation leaves the caller's
    /// retained candidate scanner available to advance from its current start.
    pub(crate) fn try_new(
        variant: &Arc<ExecutablePatternVariant>,
        start: usize,
        start_end: usize,
        end: usize,
        final_input: bool,
        memory: &MemoryReservation,
    ) -> Result<Option<Self>> {
        if start > start_end || start_end > end {
            return Err(invalid("starts beyond its input window"));
        }
        let Some(graph) = variant.lane_scan_program() else {
            return Ok(None);
        };
        if variant.automaton().min_match_rows() == 0
            || graph.payload_symbols != 0
            || (graph.requires_partition_start() || graph.requires_partition_end())
        {
            return Ok(None);
        }
        let states = graph.closure_accepting.len();
        let reservation = memory.new_empty();
        let mut current = Vec::new();
        let mut next = Vec::new();
        let mut active = Vec::new();
        let mut next_active = Vec::new();
        let admission = (|| -> Result<()> {
            try_reserve_accounted(
                &mut current,
                &reservation,
                states,
                "static search starts",
            )?;
            try_reserve_accounted(
                &mut next,
                &reservation,
                states,
                "static search successors",
            )?;
            try_reserve_accounted(
                &mut active,
                &reservation,
                states,
                "static search states",
            )?;
            try_reserve_accounted(
                &mut next_active,
                &reservation,
                states,
                "static search successor states",
            )?;
            Ok(())
        })();
        match admission {
            Ok(()) => {}
            Err(DataFusionError::ResourcesExhausted(_)) => return Ok(None),
            Err(error) => return Err(error),
        }

        current.resize(states, UNSEEN);
        next.resize(states, UNSEEN);
        if start < start_end {
            let initial = graph.transitions.start_state();
            current[initial.index()] = start;
            active.push(initial);
        }
        let physical_mask = variant
            .symbol_execution_plan()
            .physical_symbols()
            .iter()
            .fold(0, |mask, s| mask | (1u64 << s.id.index()));
        Ok(Some(Self {
            graph: Arc::clone(graph),
            current,
            next,
            active,
            next_active,
            row: start,
            start_end,
            end,
            final_input,
            best: None,
            source: 0,
            known: !physical_mask,
            physical_mask,
            eager: variant.symbol_execution_plan().eager_bitmap,
            eligible: variant.symbol_execution_plan().eager_bitmap,
            previous_word: None,
            packed_frontier: PackedFrontier::Ordinary,
            _memory: reservation,
            _variant: Arc::clone(variant),
        }))
    }

    /// Either admit the mask for one exact transition, or use a previously
    /// verified fixed frontier across equal packed words. Never skip the row
    /// before start_end, where fresh-start injection stops, or the final input
    /// row. Reverify the non-injecting frontier after crossing start_end.
    fn packed_row(
        &mut self,
        words: &[u64],
        governor: &mut WorkGovernor,
        is_aborted: &impl Fn() -> bool,
    ) -> Result<bool> {
        let word = words[0];
        let repeated = self.previous_word.replace(word) == Some(word);
        let boundary = if self.row < self.start_end {
            self.start_end
        } else {
            self.end
        };
        let interior = boundary - self.row - 1;
        if repeated && self.packed_frontier == PackedFrontier::Fixed && interior > 0 {
            let limit = interior.min(words.len()).min(COARSE_WORK_BATCH_SIZE);
            let same = words[1..limit]
                .iter()
                .take_while(|&&next| next == word)
                .count()
                + 1;
            governor.record_completed(same + usize::from(same < limit), is_aborted)?;
            let seed = self.graph.transitions.start_state().index();
            if self.current[seed] == self.row {
                self.current[seed] += same;
            }
            self.row += same;
            debug_assert_eq!(self.source, 0);
            return Ok(true);
        }
        self.packed_frontier = if repeated
            && interior > 0
            && self.best.is_none()
            && self.active.len() <= COARSE_WORK_BATCH_SIZE
        {
            PackedFrontier::Comparing
        } else {
            PackedFrontier::Ordinary
        };
        // The prepared Lane column reserves bit zero and indexes SymbolId directly.
        self.known = u64::MAX;
        self.eligible = word;
        governor.record_completed(1, is_aborted)?;
        Ok(false)
    }

    /// The same mask gives the same transitions. If every non-seed minimum
    /// survives unchanged, future seeds (which only get later) cannot improve
    /// those minima. The sole changing entry may be the injected initial state.
    fn compare_frontiers(
        &mut self,
        governor: &mut WorkGovernor,
        is_aborted: &impl Fn() -> bool,
    ) -> Result<()> {
        let initial = self.graph.transitions.start_state();
        let mut fixed = self.active.len() == self.next_active.len();
        for &state in &self.active {
            let start = std::mem::replace(&mut self.current[state.index()], UNSEEN);
            let expected = if state == initial && start == self.row {
                self.row + 1
            } else {
                start
            };
            fixed &= self.next[state.index()] == expected;
        }
        self.packed_frontier = if fixed {
            PackedFrontier::Fixed
        } else {
            PackedFrontier::Ordinary
        };
        governor.record_completed(self.active.len(), is_aborted)
    }

    #[expect(clippy::too_many_arguments)]
    pub(crate) fn advance(
        &mut self,
        provider: &impl BoolColumnProvider,
        provider_origin: usize,
        start_end: usize,
        packed_input: Option<(&BatchCollection, usize, usize)>,
        governor: &mut WorkGovernor,
        policy: YieldPolicy,
        is_aborted: impl Fn() -> bool,
    ) -> Result<StaticSearchStep> {
        let provider_end = provider_origin
            .checked_add(provider.num_rows())
            .ok_or_else(|| invalid("provider extent overflowed"))?;
        if provider_origin > self.row
            || provider_end != self.end
            || start_end != self.start_end
        {
            return Err(invalid("input window changed across suspension"));
        }
        // Providers may be rebuilt across calls and keep private location
        // caches, so a RowLocation is borrowed only within this call.
        let mut location = None;
        let mut packed: Option<&[u64]> = Some(&[]);
        loop {
            if self.source == 0 {
                let mut minimum_live = UNSEEN;
                for &state in &self.active {
                    let start = self.current[state.index()];
                    if self.graph.closure_accepting[state.index()].is_some() {
                        self.best = Some(self.best.map_or(start, |best| best.min(start)));
                    }
                    if !self.graph.transitions.sealed_range(state).is_empty() {
                        minimum_live = minimum_live.min(start);
                    }
                    governor.record_completed(1, &is_aborted)?;
                }
                // Same-start continuations affect path preference, which
                // the ordinary scanner will resolve, but cannot beat best.
                if self.best.is_some_and(|best| best <= minimum_live) {
                    return Ok(self
                        .best
                        .map_or(StaticSearchStep::Exhausted, StaticSearchStep::Found));
                }
                if self.row >= self.start_end && minimum_live == UNSEEN {
                    return Ok(StaticSearchStep::Exhausted);
                }
                if self.row == self.end {
                    // An open boundary cannot disprove a live start. Return
                    // it to the exact scanner, which owns input suspension.
                    if !self.final_input && minimum_live != UNSEEN {
                        self.best = Some(
                            self.best
                                .map_or(minimum_live, |best| best.min(minimum_live)),
                        );
                    }
                    return Ok(self
                        .best
                        .map_or(StaticSearchStep::Exhausted, StaticSearchStep::Found));
                }
                if packed.is_some_and(<[u64]>::is_empty) {
                    packed = packed_input.map(|(input, origin, column)| {
                        let (batch, local) = input.locate(self.row - origin);
                        let words = input
                            .batch(batch)
                            .column(column)
                            .as_primitive::<UInt64Type>()
                            .values();
                        &words[local..]
                    });
                }
                if let Some(words) = packed.filter(|s| !s.is_empty()) {
                    let before = self.row;
                    let skipped = self.packed_row(words, governor, &is_aborted)?;
                    packed = Some(&words[(self.row - before).max(1)..]);
                    if skipped {
                        if governor.take_yield_if_due_hot(policy) {
                            return Ok(StaticSearchStep::Yield);
                        }
                        continue;
                    }
                } else {
                    self.previous_word = None;
                    self.packed_frontier = PackedFrontier::Ordinary;
                }
            }
            while self.source < self.active.len() {
                let state = self.active[self.source];
                let start = self.current[state.index()];
                let range = self.graph.transitions.sealed_range(state);
                if self.best.is_none_or(|best| start < best) {
                    for edge_id in range {
                        let edge = self.graph.transitions.sealed_edge(edge_id);
                        let bit = 1u64 << edge.symbol_id.index();
                        if self.known & bit == 0 {
                            let located = if let Some(location) = location {
                                location
                            } else {
                                let found = provider
                                    .locate_with_work(
                                        self.row - provider_origin,
                                        &mut |units| {
                                            governor.record_completed(units, &is_aborted)
                                        },
                                    )?
                                    .ok_or_else(|| invalid("provider omitted a row"))?;
                                location = Some(found);
                                found
                            };
                            if provider.get_bool_with_loc(edge.symbol_id, located) {
                                self.eligible |= bit;
                            }
                            self.known |= bit;
                            governor.record_completed(1, &is_aborted)?;
                        }
                        if self.eligible & bit != 0 {
                            let target = edge.next_state_id;
                            let previous = &mut self.next[target.index()];
                            if *previous == UNSEEN {
                                self.next_active.push(target);
                            }
                            *previous = (*previous).min(start);
                        }
                        governor.record_completed(1, &is_aborted)?;
                    }
                }
                if self.packed_frontier != PackedFrontier::Comparing {
                    self.current[state.index()] = UNSEEN;
                }
                self.source += 1;
                governor.record_completed(1, &is_aborted)?;
                if self.source < self.active.len()
                    && governor.take_yield_if_due_hot(policy)
                {
                    return Ok(StaticSearchStep::Yield);
                }
            }
            // Inject starts only inside the eligible candidate window.
            let next_row = self.row + 1;
            if self.best.is_none() && next_row < self.start_end {
                let initial = self.graph.transitions.start_state();
                if self.next[initial.index()] == UNSEEN {
                    self.next[initial.index()] = next_row;
                    self.next_active.push(initial);
                }
            }
            if self.packed_frontier == PackedFrontier::Comparing {
                self.compare_frontiers(governor, &is_aborted)?;
            }
            std::mem::swap(&mut self.current, &mut self.next);
            std::mem::swap(&mut self.active, &mut self.next_active);
            self.next_active.clear();
            self.row = next_row;
            self.source = 0;
            self.known = !self.physical_mask;
            self.eligible = self.eager;
            location = None;
            governor.record_completed(1, &is_aborted)?;
            if governor.take_yield_if_due_hot(policy) {
                return Ok(StaticSearchStep::Yield);
            }
        }
    }
}

fn invalid(detail: &str) -> DataFusionError {
    DataFusionError::Internal(format!("MATCH_RECOGNIZE static start search {detail}"))
}