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
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
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
// 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 super::RowLoopSession;
use super::transition::{
    TransitionContext, TransitionOutputs, TransitionScratch, run as run_transition_loop,
};
use crate::core::PositionOffset;
use crate::execution::common::coordinates::absolute_row_to_usize;
use crate::execution::common::progress::ComputeStep;
use crate::execution::matching::PatternMatcher;
use crate::execution::matching::dedup::DedupArena;
use crate::execution::matching::row_loop::aggregate_engine::AggregateEngine;
use crate::execution::matching::row_loop::policies::AnchorPolicy;
use crate::execution::matching::row_loop::state::{
    ResumeFrame, ScanContext, try_advance_generation,
};
use crate::execution::matching::row_loop::symbol_evaluator::SymbolEvaluator;
use crate::execution::matching::row_loop::thread_store::ThreadBuffers;
use datafusion_common::Result;
use std::mem::size_of;

pub(super) struct ScanLoopDriver<'a, 'ctx, 'session, 'active, AP> {
    matcher: &'a PatternMatcher,
    session: &'session mut RowLoopSession<'a, 'ctx>,
    buffers: &'active mut ThreadBuffers,
    anchor_policy: &'active mut AP,
}

/// Scalar row-loop state that must cross every driver return boundary.
#[derive(Debug)]
pub(super) struct ScanResumeFrame {
    current_row: usize,
    resume: ResumeFrame,
    cur_gen: u32,
}

impl ScanResumeFrame {
    pub(super) fn take_from_context(ctx: &mut ScanContext) -> Self {
        Self {
            current_row: ctx.scan_state.current_row,
            resume: std::mem::take(&mut ctx.scan_state.resume),
            cur_gen: ctx.thread_store.cur_gen,
        }
    }

    fn restore_outcome(
        self,
        ctx: &mut ScanContext,
        outcome: Result<ComputeStep>,
    ) -> Result<ComputeStep> {
        ctx.scan_state.current_row = self.current_row;
        ctx.scan_state.resume = self.resume;
        ctx.thread_store.cur_gen = self.cur_gen;
        outcome
    }
}

impl<'a, 'ctx, 'session, 'active, AP> ScanLoopDriver<'a, 'ctx, 'session, 'active, AP>
where
    AP: AnchorPolicy,
{
    pub(super) fn new(
        matcher: &'a PatternMatcher,
        session: &'session mut RowLoopSession<'a, 'ctx>,
        buffers: &'active mut ThreadBuffers,
        anchor_policy: &'active mut AP,
    ) -> Self {
        Self {
            matcher,
            session,
            buffers,
            anchor_policy,
        }
    }

    fn reconcile_position_history_memory(&mut self, absolute_row: usize) -> Result<()> {
        let exhausted = || {
            datafusion_common::DataFusionError::ResourcesExhausted(
                "MATCH_RECOGNIZE position-history accounting exceeds usize".into(),
            )
        };
        let checked = |value: Option<usize>| value.ok_or_else(exhausted);
        let program = self.session.program;
        let unlabeled = program
            .empty_position_tracking()
            .map_or(0, |set| set.iter().len());
        let labeled = program
            .empty_labeled_tracking()
            .map_or(0, |set| set.iter().len());
        let states = checked(
            self.buffers
                .active
                .len()
                .checked_add(self.buffers.next_active.len())
                .and_then(|count| {
                    count.checked_add(usize::from(
                        self.buffers.pending_transition.is_some(),
                    ))
                }),
        )?;
        if states == 0 || checked(unlabeled.checked_add(labeled))? == 0 {
            return Ok(());
        }

        // Every history belongs to this candidate and can record one position
        // per row. Use its absolute start so a provider rebind cannot change
        // the bound. Arc::make_mut and SmallVec can still allocate during a
        // transition segment before this coarse reconciliation.
        let frontiers = self
            .session
            .ctx
            .scan_frontiers(self.matcher.program.config().max_prev_offset)?
            .ok_or_else(|| {
                datafusion_common::internal_datafusion_err!(
                    "MATCH_RECOGNIZE position-history accounting requires a live candidate"
                )
            })?;
        let candidate_start =
            absolute_row_to_usize(frontiers.candidate_start_abs(), "candidate start")?;
        let candidate_offset = absolute_row.checked_sub(candidate_start).ok_or_else(|| {
            datafusion_common::internal_datafusion_err!(
                "MATCH_RECOGNIZE position-history row {absolute_row} precedes candidate start {candidate_start}"
            )
        })?;
        let row_cap = checked(
            checked(candidate_offset.checked_add(1))?
                .max(16)
                .checked_next_power_of_two(),
        )?;
        let state_cap = checked(states.checked_next_power_of_two())?;
        let weighted =
            checked(unlabeled.checked_mul(size_of::<PositionOffset>()).and_then(
                |bytes| {
                    labeled
                        .checked_mul(size_of::<(PositionOffset, u16)>())
                        .and_then(|labeled_bytes| bytes.checked_add(labeled_bytes))
                },
            ))?;
        // Factor two covers the inline SmallVec body plus capacity-rounded
        // spill storage and Arc/table overhead.
        let target = checked(
            2usize
                .checked_mul(state_cap)
                .and_then(|bytes| bytes.checked_mul(row_cap))
                .and_then(|bytes| bytes.checked_mul(weighted)),
        )?;
        self.session
            .ctx
            .thread_store
            .grow_position_history_memory(target)?;
        Ok(())
    }

    /// Phase 1: evaluate symbol booleans and refresh matched-symbol metadata.
    fn phase_evaluate_symbols(&mut self, cur_row: usize) -> Result<u64> {
        let evaluator = SymbolEvaluator {
            symbol_programs: self.session.program.symbol_programs(),
        };
        let matcher = self.matcher;
        let resources = self.session.ctx.resources_mut();
        let symbols = &mut resources.symbols;
        let governor = &mut resources.scan_state.governor;

        evaluator.evaluate_row(
            self.session.program.symbol_execution_plan(),
            self.session.source.provider,
            cur_row,
            self.session.range.total_rows,
            self.session.range.has_virtual_row,
            symbols,
            &mut |units| governor.record_completed(units, || matcher.is_aborted()),
        )
    }

    fn execute_transition_row(
        &mut self,
        frame: &mut ScanResumeFrame,
        partition_len: usize,
    ) -> Result<ComputeStep> {
        let current_row = frame.current_row;
        let (prepare_row, define_cache_generation, matched_bitmap) = match &frame.resume {
            ResumeFrame::StartRow => {
                let matcher = self.matcher;
                {
                    let resources = self.session.ctx.resources_mut();
                    let governor = &mut resources.scan_state.governor;
                    try_advance_generation(
                        &mut frame.cur_gen,
                        &mut resources.thread_store.next_gen_flags,
                        &mut |units| {
                            governor.record_completed(units, || matcher.is_aborted())
                        },
                    )?;
                }
                let matched_bitmap = self.phase_evaluate_symbols(current_row)?;
                let define_cache_generation = self
                    .session
                    .ctx
                    .aggregation
                    .define_cache_state
                    .proposed_generation();
                (true, define_cache_generation, matched_bitmap)
            }
            ResumeFrame::Transitions(transitions) => {
                let active_generation = self.session.ctx.thread_store.active_generation;
                transitions.validate_active_generation(active_generation)?;
                let cached_generation = self
                    .session
                    .ctx
                    .aggregation
                    .define_cache_state
                    .define_cache_gen;
                transitions.validate_define_cache_generation(cached_generation)?;
                let symbols = transitions.symbols();
                (
                    false,
                    symbols.define_cache_generation(),
                    symbols.matched_bitmap(),
                )
            }
        };
        let session = &mut self.session;
        let ctx = &mut *session.ctx;
        let active_generation = ctx.thread_store.active_generation;
        if active_generation.get() == 0 {
            return datafusion_common::internal_err!(
                "MATCH_RECOGNIZE cannot execute transitions without an active container generation"
            );
        }
        let partition_end_row = ctx.partition.partition_end_row;
        let partition_start_row = ctx.partition.partition_start_row;
        let next_match_number = ctx.partition.next_match_number;
        let resources = ctx.resources_mut();
        let mut agg_engine = AggregateEngine::new(
            self.matcher,
            session.program,
            session.source.input_buffer,
            &self.matcher.program.aggregate_hot_tables().columns,
            &mut resources.aggregation,
            define_cache_generation,
            partition_start_row,
            session.range.global_row_offset,
            next_match_number,
        );
        agg_engine.prepare_or_resume_transition_row(
            current_row,
            partition_len,
            prepare_row,
            &mut |units| {
                resources
                    .scan_state
                    .governor
                    .record_completed(units, || self.matcher.is_aborted())
            },
        )?;
        if prepare_row {
            // Publish transition cursors only after all fallible row preparation
            // succeeds, so a resumable transition frame always names valid cache
            // and active-container generations.
            frame.resume.begin_transitions(
                define_cache_generation,
                matched_bitmap,
                active_generation,
            )?;
            if resources
                .scan_state
                .governor
                .take_yield_if_due_hot(session.yield_policy)
            {
                return Ok(ComputeStep::Yield);
            }
        }

        let scratch = TransitionScratch {
            traversal: &mut resources.traversal,
            arena: DedupArena {
                next_active: &mut self.buffers.next_active,
                next_primary_slot: &mut self.buffers.next_primary_slot,
                next_gen_flags: &mut resources.thread_store.next_gen_flags,
                cur_row_gen: frame.cur_gen,
                memory: &mut self.buffers.memory,
                overflow_index: &mut self.buffers.overflow_index,
            },
            node_arena: &mut resources.thread_store.node_arena,
            loops: frame
                .resume
                .transition_mut()
                .expect("transition phase was published before traversal")
                .loops_mut(),
            governor: &mut resources.scan_state.governor,
            pending_transition: &mut self.buffers.pending_transition,
            yield_policy: session.yield_policy,
        };
        let outputs = TransitionOutputs {
            history: &mut resources.candidate_history,
            partition_end_row,
            incumbent: &mut resources.scan_state.incumbent,
        };

        let mut row_ctx = TransitionContext {
            matcher: self.matcher,
            program: session.program,
            partition_len,
            pre_checks: resources.symbols.pre_checks.as_slice(),
            or_passes: resources.symbols.or_passes.as_slice(),
            matched_symbols: resources.symbols.matched_ids.as_slice(),
            scratch,
            outputs,
            agg_engine,
            matched_bitmap,
        };
        let progress = run_transition_loop(
            &mut row_ctx,
            &mut self.buffers.active,
            active_generation,
            self.anchor_policy,
        )?;
        Ok(progress)
    }

    fn finalize_row(&mut self, frame: &mut ScanResumeFrame) -> Result<()> {
        if self.buffers.pending_transition.is_some() {
            return datafusion_common::internal_err!(
                "MATCH_RECOGNIZE cannot publish a row with a pending successor"
            );
        }
        if !frame.resume.is_row_in_progress() {
            return datafusion_common::internal_err!(
                "MATCH_RECOGNIZE cannot finish a row from resume phase {}",
                frame.resume.name()
            );
        }
        let resources = self.session.ctx.resources_mut();
        let thread_store = &mut resources.thread_store;
        let governor = &mut resources.scan_state.governor;
        let active_len = self.buffers.active.len();

        // Successors were checked when staged. Cancellation remains restart-safe
        // because no active or staged ownership moves until accounting succeeds.
        let matcher = self.matcher;

        let overflow_reset_work = self.buffers.overflow_index.reset_work_units();
        let finalization_work = active_len
            .saturating_add(overflow_reset_work)
            .saturating_add(1);
        governor.record_completed(finalization_work, || matcher.is_aborted())?;

        self.buffers.active.clear();
        // Preserve lexical emission order, retaining accounted seed capacity
        // when a candidate fails without producing successors.
        if !self.buffers.next_active.is_empty() {
            std::mem::swap(&mut self.buffers.active, &mut self.buffers.next_active);
        }
        thread_store.active_generation = thread_store.active_generation.next();
        self.buffers.overflow_index.reset();
        frame.current_row += 1;
        frame.resume.finish_row()?;
        Ok(())
    }

    /// Run until the next externally visible outcome, retaining its resume frame.
    pub(super) fn step(mut self) -> Result<ComputeStep> {
        let mut frame = ScanResumeFrame::take_from_context(self.session.ctx);
        let outcome = self.run_inner(&mut frame);
        frame.restore_outcome(self.session.ctx, outcome)
    }

    fn run_inner(&mut self, frame: &mut ScanResumeFrame) -> Result<ComputeStep> {
        let coordinates = self.session.coordinates()?;
        let (provider_origin, partition_len, total_proc_rows) = (
            coordinates.provider_origin,
            coordinates.partition_len,
            coordinates.work_len,
        );

        if frame.resume.is_row_in_progress() && frame.current_row >= total_proc_rows {
            return datafusion_common::internal_err!(
                "MATCH_RECOGNIZE resume phase {} has no processable active row",
                frame.resume.name()
            );
        }

        while frame.current_row < total_proc_rows
            && (!self.buffers.active.is_empty() || frame.resume.is_row_in_progress())
        {
            let absolute_row = provider_origin
                .checked_add(frame.current_row)
                .ok_or_else(|| {
                    datafusion_common::DataFusionError::ResourcesExhausted(
                        "MATCH_RECOGNIZE scan row exceeds usize".to_string(),
                    )
                })?;
            self.anchor_policy.update_row(absolute_row);

            let progress = self.execute_transition_row(frame, partition_len)?;
            // Virtual EOF cannot append positions to candidate history.
            if frame.current_row < partition_len {
                self.reconcile_position_history_memory(absolute_row)?;
            }
            if matches!(progress, ComputeStep::Yield) {
                return Ok(ComputeStep::Yield);
            }

            self.finalize_row(frame)?;
            if self
                .session
                .ctx
                .scan_state
                .governor
                .take_yield_if_due_hot(self.session.yield_policy)
            {
                return Ok(ComputeStep::Yield);
            }
        }

        if !frame.resume.is_start_row() {
            return datafusion_common::internal_err!(
                "MATCH_RECOGNIZE cannot finish scan from resume phase {}",
                frame.resume.name()
            );
        }

        Ok(ComputeStep::Complete)
    }
}

#[cfg(test)]
mod tests {
    use super::ScanResumeFrame;
    use crate::execution::common::progress::ComputeStep;
    use crate::execution::matching::row_loop::state::{
        ActiveContainerGeneration, ResumeFrame, ScanContext,
    };
    use datafusion_common::{DataFusionError, Result};

    fn restore_sentinel_frame(outcome: Result<ComputeStep>) -> Result<ComputeStep> {
        let mut context = ScanContext::new(3, 2, 1);
        let mut resume = ResumeFrame::StartRow;
        resume
            .begin_transitions(29, 0xa5a5, ActiveContainerGeneration::new(31))
            .unwrap();
        resume
            .transition_mut()
            .expect("the sentinel should be in transition traversal")
            .loops_mut()
            .active_idx = 7;
        let frame = ScanResumeFrame {
            current_row: 17,
            resume,
            cur_gen: 23,
        };
        let outcome = frame.restore_outcome(&mut context, outcome);
        assert_eq!(context.scan_state.current_row, 17);
        assert!(context.scan_state.resume.is_transitions());
        assert_eq!(context.thread_store.cur_gen, 23);
        let transition = context
            .scan_state
            .resume
            .transition()
            .expect("the full transition payload should be restored");
        assert_eq!(transition.symbols().define_cache_generation(), 29);
        assert_eq!(transition.symbols().matched_bitmap(), 0xa5a5);
        assert_eq!(transition.active_generation().get(), 31);
        assert_eq!(transition.loops().active_idx, 7);
        outcome
    }

    #[test]
    fn scan_step_restores_the_full_resume_frame_before_exposing_outcome() {
        assert!(matches!(
            restore_sentinel_frame(Ok(ComputeStep::Complete)).unwrap(),
            ComputeStep::Complete
        ));
        assert!(matches!(
            restore_sentinel_frame(Ok(ComputeStep::Yield)).unwrap(),
            ComputeStep::Yield
        ));

        let error = restore_sentinel_frame(Err(DataFusionError::Internal(
            "injected driver failure".to_string(),
        )))
        .expect_err("the injected failure should remain the outcome");
        assert!(error.to_string().contains("injected driver failure"));
    }
}