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

//! Outer row-scanning loop that drives the pattern matcher.

mod driver;
pub(crate) mod transition;

use self::driver::ScanLoopDriver;
use super::policies::{AnchorPolicy, CheckAnchors, IgnoreAnchors};
use super::state::{ActiveTier, ScanContext};
use crate::core::AbsoluteRow;
use crate::execution::common::coordinates::absolute_row_from_usize;
use crate::execution::common::progress::ComputeStep;
use crate::execution::matching::PatternMatcher;
use crate::execution::matching::row_loop::compiled_program::ExecutablePatternVariant;
use crate::execution::matching::row_loop::types::ActiveNFAState;
use crate::execution::matching::symbol_columns::MultiBatchBoolColumns;
use crate::execution::storage::collection::BatchCollection;
use crate::nfa::AutomatonStateId;
use datafusion_common::{DataFusionError, Result};

/// Data sources for the scan.
pub(crate) struct ScanSource<'a> {
    pub(crate) provider: &'a MultiBatchBoolColumns,
    pub(crate) input_buffer: &'a BatchCollection,
}

/// Provider-local `row_idx` and physical-plus-optional-virtual `total_rows` bound.
#[derive(Clone, Copy)]
pub(crate) struct ScanRange {
    pub(crate) row_idx: usize,
    pub(crate) total_rows: usize,
    /// Absolute exclusive end of rows the scan may read while extending an
    /// in-range match start.
    pub(crate) read_end_row: usize,
    pub(crate) global_row_offset: usize,
    pub(crate) absolute_partition_start: usize,
    pub(crate) has_virtual_row: bool,
}

/// Consolidated session data for a single row-loop invocation.
pub(crate) struct RowLoopSession<'a, 'ctx> {
    pub(crate) program: &'a ExecutablePatternVariant,
    pub(crate) source: ScanSource<'a>,
    pub(crate) range: ScanRange,
    pub(crate) ctx: &'ctx mut ScanContext,
    pub(crate) yield_policy: crate::config::YieldPolicy,
}

#[derive(Clone, Copy)]
pub(super) struct ScanCoordinates {
    pub(super) provider_origin: usize,
    pub(super) partition_len: usize,
    pub(super) work_len: usize,
    pub(super) match_start: AbsoluteRow,
    pub(super) provider_origin_abs: AbsoluteRow,
    pub(super) provider_end: AbsoluteRow,
}

impl RowLoopSession<'_, '_> {
    pub(super) fn coordinates(&self) -> Result<ScanCoordinates> {
        let provider_origin = self
            .ctx
            .partition
            .partition_start_row
            .checked_add(self.range.global_row_offset)
            .ok_or_else(|| {
                DataFusionError::ResourcesExhausted(
                    "MATCH_RECOGNIZE provider origin exceeds usize".into(),
                )
            })?;
        let partition_len = self.range.read_end_row.checked_sub(provider_origin).ok_or_else(
            || {
                DataFusionError::Internal(format!(
                    "MATCH_RECOGNIZE read end {} precedes provider origin {provider_origin}",
                    self.range.read_end_row
                ))
            },
        )?;
        let work_len = partition_len.checked_add(usize::from(self.range.has_virtual_row)).ok_or_else(|| {
            DataFusionError::ResourcesExhausted(format!(
                "MATCH_RECOGNIZE scan extent cannot represent {partition_len} physical rows plus a virtual end in usize"
            ))
        })?;
        let match_start =
            self.range
                .row_idx
                .checked_add(provider_origin)
                .ok_or_else(|| {
                    DataFusionError::ResourcesExhausted(
                        "MATCH_RECOGNIZE match start exceeds usize".into(),
                    )
                })?;
        Ok(ScanCoordinates {
            provider_origin,
            partition_len,
            work_len,
            match_start: absolute_row_from_usize(match_start, "match start")?,
            provider_origin_abs: absolute_row_from_usize(
                provider_origin,
                "provider origin",
            )?,
            provider_end: absolute_row_from_usize(
                self.range.read_end_row,
                "provider end",
            )?,
        })
    }
}

type ScanOutcome = Result<ComputeStep>;

#[derive(Clone, Copy)]
enum CandidateScanEntry {
    Start,
    Resume,
}

impl PatternMatcher {
    pub(crate) fn start_candidate_scan<'a, 'ctx>(
        &self,
        session: RowLoopSession<'a, 'ctx>,
    ) -> ScanOutcome {
        session.ctx.prepare_next_start()?;
        self.scan_candidate(session, CandidateScanEntry::Start)
    }

    pub(crate) fn resume_candidate_scan<'a, 'ctx>(
        &self,
        session: RowLoopSession<'a, 'ctx>,
    ) -> ScanOutcome {
        if !session.ctx.has_live_continuation() {
            return datafusion_common::internal_err!(
                "MATCH_RECOGNIZE cannot resume an idle candidate scan"
            );
        }
        if session.ctx.lane_continuation_is_live() {
            let program =
                session
                    .program
                    .enabled_lane_scan_program(self)
                    .ok_or_else(|| {
                        DataFusionError::Internal(
                            "MATCH_RECOGNIZE live lane continuation became ineligible"
                                .into(),
                        )
                    })?;
            let variant = session.program;
            let mut lane = super::lane_scan::LaneCollection::new();
            let result = super::lane_scan::resume_candidate_scan(
                self, program, session, &mut lane,
            );
            lane.record_routes(self, variant);
            return result;
        }
        self.scan_candidate(session, CandidateScanEntry::Resume)
    }

    fn scan_candidate<'a, 'ctx>(
        &self,
        session: RowLoopSession<'a, 'ctx>,
        entry: CandidateScanEntry,
    ) -> ScanOutcome {
        if session.program.automaton().has_anchors() {
            let provider_origin = session
                .ctx
                .partition
                .partition_start_row
                .checked_add(session.range.global_row_offset)
                .ok_or_else(|| {
                    DataFusionError::ResourcesExhausted(
                        "MATCH_RECOGNIZE anchor provider origin cannot be represented as usize"
                            .to_string(),
                    )
                })?;
            let virt_row = session
                .range
                .row_idx
                .checked_add(provider_origin)
                .ok_or_else(|| {
                    DataFusionError::ResourcesExhausted(
                        "MATCH_RECOGNIZE anchor row cannot be represented as usize"
                            .to_string(),
                    )
                })?;
            let total_virt_rows = session
                .range
                .total_rows
                .checked_add(provider_origin)
                .ok_or_else(|| {
                DataFusionError::ResourcesExhausted(
                    "MATCH_RECOGNIZE anchor input end cannot be represented as usize"
                        .to_string(),
                )
            })?;
            let anchor_policy = CheckAnchors {
                virt_row,
                total_virt_rows,
                absolute_partition_start: session.range.absolute_partition_start,
                has_virtual_end: session.range.has_virtual_row,
            };
            self.scan_candidate_impl(session, entry, anchor_policy)
        } else {
            self.scan_candidate_impl(session, entry, IgnoreAnchors)
        }
    }

    fn scan_candidate_impl<'a, 'ctx, AP: AnchorPolicy>(
        &'a self,
        mut session: RowLoopSession<'a, 'ctx>,
        entry: CandidateScanEntry,
        anchor_policy: AP,
    ) -> ScanOutcome {
        if matches!(entry, CandidateScanEntry::Start) {
            let active_tier = self.resolve_active_tier();
            session.ctx.thread_store.select_tier(
                active_tier,
                session.program.automaton().nfa().state_count(),
            )?;
            if let Some(metrics) = &self.services.metrics {
                metrics.route_scan_generic.add(1);
                let tier = match active_tier {
                    ActiveTier::Compact => &metrics.route_tier_compact,
                    ActiveTier::Standard => &metrics.route_tier_standard,
                    ActiveTier::Accumulator => &metrics.route_tier_accumulator,
                };
                tier.add(1);
                let path = if session.program.path_representation().uses_compact_paths() {
                    &metrics.route_path_compact
                } else {
                    &metrics.route_path_ordinary
                };
                path.add(1);
                session
                    .program
                    .symbol_execution_plan()
                    .record_evaluator_routes(
                        metrics,
                        !self.aggregate_backend_set().supports_lifted_state(),
                        1,
                    );
            }
        }
        session.ctx.ensure_capacity(
            session.program.automaton().nfa().state_count(),
            session.program.automaton().id_to_symbol().len(),
        )?;

        if matches!(entry, CandidateScanEntry::Start)
            && let Err(error) = self.initialize_partition_start_state(&mut session)
        {
            session.ctx.discard_candidate_scan();
            return Err(error);
        }

        self.run_scan_driver_for_active_tier(session, anchor_policy)
    }

    #[inline]
    fn resolve_active_tier(&self) -> ActiveTier {
        // Preserve backend route reporting and navigation initialization.
        if !self.aggregate_backend_set().supports_lifted_state() {
            return ActiveTier::Accumulator;
        }
        use crate::core::vm::VmTier;
        match self.runtime_vm_layout().tier() {
            VmTier::Compact => ActiveTier::Compact,
            VmTier::Standard => ActiveTier::Standard,
        }
    }

    fn initial_active_thread(
        &self,
        variant: &ExecutablePatternVariant,
        start_state: AutomatonStateId,
        match_start: AbsoluteRow,
        state_memory: &datafusion_execution::memory_pool::MemoryReservation,
    ) -> Result<super::types::ActiveThread> {
        let layout = self.runtime_vm_layout();
        let register_spill = if layout.needs_register_spill() {
            Some(super::types::SharedRegisterFrame(
                super::types::AccountedCowSlice::try_from_slice(
                    layout.initial_registers_slice(),
                    state_memory,
                )?,
            ))
        } else {
            None
        };
        Ok(super::types::ActiveThread::new(
            ActiveNFAState {
                state_id: start_state,
                path: None,
                match_start_row: match_start,
                registers: layout.initial_inline_registers(),
                deferred_history_fingerprint: 0,
            },
            None,
            variant.empty_position_tracking().cloned(),
            variant.empty_labeled_tracking().cloned(),
            None,
        )
        .with_register_spill(register_spill))
    }

    fn initialize_partition_start_state<'a, 'ctx>(
        &self,
        session: &mut RowLoopSession<'a, 'ctx>,
    ) -> Result<()> {
        let coordinates = session.coordinates()?;
        let match_start = coordinates.match_start;
        let start_state = session.program.automaton().nfa().start_state();
        session.ctx.scan_state.reset(session.range.row_idx);
        let next_generation = session.ctx.thread_store.active_generation.next();

        let factories = &self.program.aggregate_hot_tables().factories;
        let initial_accumulators = if session.ctx.thread_store.selected_tier()
            == Some(ActiveTier::Accumulator)
            && !factories.is_empty()
        {
            Some(super::types::AccumulatorSet::try_new(
                std::iter::repeat_with(|| None)
                    .take(factories.len())
                    .collect(),
                session.ctx.thread_store.state_memory(),
            )?)
        } else {
            None
        };

        let mut state = self.initial_active_thread(
            session.program,
            start_state,
            match_start,
            session.ctx.thread_store.state_memory(),
        )?;
        state.put_accumulators(initial_accumulators);
        let buffers = session.ctx.thread_store.buffers.as_mut().ok_or_else(|| {
            datafusion_common::internal_datafusion_err!(
                "MATCH_RECOGNIZE thread buffers were not selected before initialization"
            )
        })?;
        debug_assert!(
            buffers.active.is_empty(),
            "fresh scan retained active states"
        );
        crate::execution::common::memory::try_reserve_accounted(
            &mut buffers.active,
            &buffers.memory,
            1,
            "active",
        )?;
        buffers.active.push(state);
        session.ctx.thread_store.active_generation = next_generation;

        debug_assert!(
            session.ctx.thread_store.node_arena.is_empty(),
            "fresh scan retained path nodes"
        );
        session.ctx.symbols.pre_checks.fill(true);
        session.ctx.symbols.or_passes.fill(false);
        session.ctx.begin_continuation(
            match_start,
            coordinates.provider_origin_abs,
            coordinates.provider_end,
            self.program.config().max_prev_offset,
            session.range.has_virtual_row,
        )
    }

    /// Run the shared scan driver using the selected thread buffers.
    fn run_scan_driver_for_active_tier<'a, 'ctx, AP: AnchorPolicy>(
        &'a self,
        mut session: RowLoopSession<'a, 'ctx>,
        mut anchor_policy: AP,
    ) -> ScanOutcome {
        // The driver borrows the whole selected tier and the common scan context
        // independently. Return the tier, including every lease, on every outcome.
        let mut buffers = session.ctx.thread_store.buffers.take();
        let outcome = match buffers.as_mut() {
            Some(buffers) => {
                ScanLoopDriver::new(self, &mut session, buffers, &mut anchor_policy)
                    .step()
            }
            None => datafusion_common::internal_err!(
                "MATCH_RECOGNIZE scan has no active thread tier"
            ),
        };
        session.ctx.thread_store.buffers = buffers;
        outcome
    }
}

#[cfg(test)]
mod tests;