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

//! Sealed stateful matching program and its checked predicate bindings.

pub(crate) mod contracts;
pub(crate) mod validated_vm;

use std::sync::Arc;

use crate::core::{
    MatchRecognizeOutputSpec, NavigationOffset, NormalizedPattern, RowsPerMatch,
    SymbolEvalMode, SymbolId,
};
use crate::nfa::CompiledAutomaton;
use crate::planning::SymbolRelationships;
use datafusion::arrow::datatypes::SchemaRef;
use datafusion::physical_plan::PhysicalExpr;
use datafusion_common::Result;

pub(super) mod build;
use super::row_loop::lane_scan::LaneRejection;
use super::{
    AggregateHotTables, ExecutableOutputPlan, ExecutablePatternVariant,
    ExecutableSymbolProgram, ExecutableUserSymbolProgram, ResolvedAfterMatchSkip,
    SymbolTable,
};
use crate::execution::classification::OffsetColumns;
use crate::execution::classification::{MatchAwareClassification, PackedAnchors};
use crate::execution::deferred::DeferredEvaluatorFactory;
use crate::execution::deferred::DeferredHistoryProjection;
use crate::execution::identity::MatchProgramId;
use crate::execution::physical::virtual_input::VirtualInputMapping;
use build::ProgramBuilder;
use contracts::{
    AggregateProgram, ExecutableMatchProgramInput, ResolvedStaticExtraction,
};
use validated_vm::{RuntimeVmLayout, ValidatedVmProgram};

/// Immutable, validated program shared by the physical node and every stream.
///
/// Physical planning seals the base [`ExecutablePatternVariant`] once. Each
/// stream applies its execution-time configuration to the shared graph tables
/// and creates mutable matcher services.
#[derive(Clone)]
pub(crate) struct ExecutableMatchProgram {
    pub(crate) virtual_input: Option<Arc<VirtualInputMapping>>,
    pub(crate) offset_columns: Option<Arc<OffsetColumns>>,
    pub(crate) pre_sort_filter:
        Option<Arc<dyn datafusion_hash_grouped_order::PartitionMaskExtractor>>,
    pub(crate) classification: Option<Arc<MatchAwareClassification>>,
    pub(crate) packed_anchors: Option<Arc<PackedAnchors>>,
    pub(crate) can_skip_candidate_evaluation: bool,
    pub(crate) non_overlapping_starts: bool,
    program_id: MatchProgramId,
    pub(crate) input_schema: SchemaRef,
    pub(super) aggregate_programs: Arc<[AggregateProgram]>,
    pub(super) deferred_evaluator_factory: Option<Arc<DeferredEvaluatorFactory>>,
    pub(super) base_variant: Arc<ExecutablePatternVariant>,
    pub(super) prepared: Arc<PreparedMatcherProgram>,
}

impl std::fmt::Debug for ExecutableMatchProgram {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ExecutableMatchProgram")
            .field("symbols", &self.prepared.vm_program.symbol_programs().len())
            .field("aggregates", &self.aggregate_programs.len())
            .field("output_schema", self.output_plan().schema())
            .finish()
    }
}

impl ExecutableMatchProgram {
    pub(crate) fn rows_per_match(&self) -> &RowsPerMatch {
        self.output_plan().rows_per_match()
    }

    pub(crate) fn with_synthetic_row_filter(
        &self,
        rows: RowsPerMatch,
        suppress_terminal_empty: bool,
    ) -> Result<Self> {
        self.with_filtered_output(
            Arc::clone(self.output_plan())
                .with_synthetic_row_filter(rows, suppress_terminal_empty)?,
        )
    }

    pub(crate) fn with_extended_input_schema(&self, schema: &SchemaRef) -> Result<Self> {
        let mut cloned = self.clone_with_fresh_identity()?;
        cloned.input_schema = Arc::clone(schema);
        Ok(cloned)
    }

    pub(crate) fn is_infallible_never(&self) -> bool {
        matches!(self.normalized_pattern(), NormalizedPattern::Never)
            && self.can_skip_candidate_evaluation
            && self.offset_columns.is_none()
            && self
                .classification
                .as_ref()
                .is_none_or(|c| !c.needs_neighbors())
    }

    pub(crate) fn emits_ordered_unmatched(&self) -> bool {
        matches!(
            self.rows_per_match(),
            RowsPerMatch::AllRows(crate::core::EmptyMatchesMode::WithUnmatched)
        ) && matches!(self.after_match_skip(), ResolvedAfterMatchSkip::PastLastRow)
            && !self.output_plan().stream().emits_navigation_buffer_rows()
            && self.compiled_automaton().min_match_rows() > 0
            && !self.stream_requirements().interleaves_logical_partitions
    }

    /// Grouped input can avoid gathering unused columns. Derived fields are
    /// supplied after ordering; their raw operands must remain available.
    pub(crate) fn referenced_input_columns(&self, width: usize) -> Vec<bool> {
        // Candidate evaluators and offsets can read private working-schema slots.
        // Keep their transport conservative until all such uses are represented.
        if !self.can_skip_candidate_evaluation
            || self.offset_columns.is_some()
            || self
                .user_symbol_programs()
                .any(|s| s.evaluator().mode() != SymbolEvalMode::Static)
            || !self.aggregate_programs.is_empty()
        {
            return vec![true; width];
        }
        let mut needed = vec![false; width];
        self.output_plan()
            .mark_referenced_input_columns(&mut needed);
        if self.is_infallible_never() {
            return needed;
        }
        let absorbed = self
            .classification
            .as_ref()
            .map(|c| {
                c.classifier.mark_referenced_input_columns(&mut needed);
                c.predicates
                    .iter()
                    .map(|p| p.output)
                    .collect::<std::collections::HashSet<_>>()
            })
            .unwrap_or_default();
        for symbol in self.base_variant().active_symbol_columns().columns() {
            if !absorbed.contains(&symbol.column.index())
                && let Some(slot) = needed.get_mut(symbol.column.index())
            {
                *slot = true;
            }
        }
        needed
    }

    /// Validate every input and schema reference, then build the immutable
    /// program used by matcher execution.
    pub(crate) fn try_new(input: ExecutableMatchProgramInput) -> Result<Self> {
        let ExecutableMatchProgramInput {
            input_schema,
            normalized_pattern,
            max_define_lookahead_rows,
            has_deferred_history_operations,
            symbols,
            aggregate_programs,
            output,
            after_match_skip,
            deferred_evaluator_factory,
        } = input;
        let aggregate_programs: Arc<[AggregateProgram]> = aggregate_programs.into();

        let prepared = ProgramBuilder::build(
            input_schema.as_ref(),
            aggregate_programs.as_ref(),
            normalized_pattern,
            max_define_lookahead_rows,
            has_deferred_history_operations,
            Arc::clone(&output),
            symbols,
            after_match_skip,
        )?;
        let base_variant = ExecutablePatternVariant::try_new(
            &prepared,
            prepared.normalized_pattern(),
            Arc::clone(&prepared.automaton),
            Arc::clone(&prepared.symbol_table),
            false,
        )?;

        let can_skip_candidate_evaluation = aggregate_programs.is_empty()
            && deferred_evaluator_factory.is_none()
            && !prepared.has_deferred_history_operations
            && prepared
                .vm_program
                .symbol_programs()
                .iter()
                .filter_map(ExecutableSymbolProgram::user)
                .all(|program| program.evaluator().mode() == SymbolEvalMode::Static);

        let non_overlapping_starts = can_skip_candidate_evaluation
            && matches!(
                prepared.after_match_skip(),
                ResolvedAfterMatchSkip::PastLastRow
            )
            && prepared
                .automaton
                .max_match_rows()
                .is_some_and(|rows| rows > 1)
            && super::graph::non_overlap::proves_non_overlapping_starts(
                &prepared.automaton,
                &prepared.relationships,
            )?;
        Ok(Self {
            non_overlapping_starts,
            virtual_input: None,
            offset_columns: None,
            pre_sort_filter: None,
            classification: None,
            packed_anchors: None,
            can_skip_candidate_evaluation,
            program_id: MatchProgramId::try_allocate()?,
            input_schema,
            aggregate_programs,
            deferred_evaluator_factory,
            base_variant,
            prepared: Arc::new(prepared),
        })
    }

    pub(crate) fn compiled_automaton(&self) -> &Arc<CompiledAutomaton> {
        &self.prepared.automaton
    }

    pub(crate) fn normalized_pattern(&self) -> &NormalizedPattern {
        self.prepared.normalized_pattern()
    }

    pub(crate) fn after_match_skip(&self) -> &ResolvedAfterMatchSkip {
        self.prepared.after_match_skip()
    }

    pub(crate) fn match_aware_symbols(&self) -> &[SymbolId] {
        self.prepared.match_aware_symbols()
    }

    #[cfg(test)]
    pub(crate) fn has_lookahead_defines(&self) -> bool {
        self.prepared.has_lookahead_defines()
    }

    #[cfg(test)]
    pub(crate) fn max_define_lookahead_rows(&self) -> NavigationOffset {
        self.prepared.max_define_lookahead_rows
    }

    pub(crate) fn has_deferred_history_operations(&self) -> bool {
        self.prepared.has_deferred_history_operations
    }

    pub(crate) fn has_global_match_number_predicate(&self) -> bool {
        self.prepared.has_global_match_number_predicate
    }

    pub(crate) const fn program_id(&self) -> MatchProgramId {
        self.program_id
    }

    pub(crate) fn output_schema(&self) -> &SchemaRef {
        self.output_plan().schema()
    }

    pub(crate) fn output_spec(&self) -> &MatchRecognizeOutputSpec {
        self.output_plan().spec()
    }

    pub(crate) fn output_plan(&self) -> &Arc<ExecutableOutputPlan> {
        self.prepared.output_plan()
    }

    /// Give a physical input owner its own identity while sharing sealed bindings.
    pub(crate) fn clone_with_fresh_identity(&self) -> Result<Self> {
        let mut cloned = self.clone();
        cloned.program_id = MatchProgramId::try_allocate()?;
        Ok(cloned)
    }

    pub(crate) fn with_filtered_output(
        &self,
        output: Arc<ExecutableOutputPlan>,
    ) -> Result<Self> {
        let mut cloned = self.clone_with_fresh_identity()?;
        Arc::make_mut(&mut cloned.prepared).output = output;
        Ok(cloned)
    }

    /// Clone this sealed program with one planner-owned input column carried
    /// through the match output.
    ///
    /// Physical halo partitioning uses this to retain its private chunk key
    /// across the ordinary partitioned matcher. All existing input bindings
    /// keep their indices because the private column is appended to the input.
    pub(crate) fn with_appended_passthrough(
        &self,
        input_schema: &SchemaRef,
        input_index: usize,
    ) -> Result<Self> {
        let output = self.output_plan().with_appended_passthrough(
            input_schema.as_ref(),
            input_index,
            self.compiled_automaton().as_ref(),
        )?;

        let mut cloned = self.with_filtered_output(output)?;
        cloned.input_schema = Arc::clone(input_schema);
        Ok(cloned)
    }

    pub(crate) fn aggregate_programs(&self) -> &[AggregateProgram] {
        &self.aggregate_programs
    }

    pub(crate) fn base_variant(&self) -> &Arc<ExecutablePatternVariant> {
        &self.base_variant
    }

    pub(crate) fn static_extractions(&self) -> &[ResolvedStaticExtraction] {
        &self.prepared.static_extractions
    }

    pub(crate) fn history_input_ordinals(&self) -> &[usize] {
        self.deferred_evaluator_factory
            .as_ref()
            .map_or(&[], |f| f.input_ordinals())
    }

    pub(crate) fn has_deferred_evaluator_factory(&self) -> bool {
        self.deferred_evaluator_factory.is_some()
    }

    /// Return every physical-expression root evaluated by the matcher runtime.
    ///
    /// Runtime partition-key expressions belong to the physical-plan layout
    /// and are appended by `MatchRecognizePatternExec`.
    pub(crate) fn physical_expr_roots(&self) -> Vec<Arc<dyn PhysicalExpr>> {
        let mut roots = Vec::new();
        for program in self.user_symbol_programs() {
            program.evaluator().append_physical_expr_roots(&mut roots);
        }
        for aggregate in self.aggregate_programs() {
            roots.extend_from_slice(aggregate.input_expressions());
        }
        if let Some(factory) = &self.deferred_evaluator_factory {
            roots.extend(factory.physical_expr_roots());
        }
        roots
    }

    #[cfg(test)]
    pub(crate) fn symbol_eval_modes(&self) -> Vec<SymbolEvalMode> {
        self.prepared
            .vm_program
            .symbol_programs()
            .iter()
            .map(ExecutableSymbolProgram::mode)
            .collect()
    }

    pub(crate) fn user_symbol_programs(
        &self,
    ) -> impl Iterator<Item = &ExecutableUserSymbolProgram> {
        self.prepared
            .vm_program
            .symbol_programs()
            .iter()
            .filter_map(ExecutableSymbolProgram::user)
    }

    pub(crate) fn runtime_vm_layout(&self) -> &RuntimeVmLayout {
        self.prepared.vm_program.runtime_layout()
    }

    pub(crate) fn vm_program(&self) -> &ValidatedVmProgram {
        &self.prepared.vm_program
    }

    pub(crate) fn explain_lane_rejection(&self) -> Option<LaneRejection> {
        self.base_variant.lane_outcome().rejection()
    }
}

/// Stable, validated inputs for sealing base and runtime-pruned executable variants.
#[derive(Clone)]
pub(crate) struct PreparedMatcherProgram {
    pub(crate) automaton: Arc<CompiledAutomaton>,
    pub(crate) normalized_pattern: Arc<NormalizedPattern>,
    pub(crate) output: Arc<ExecutableOutputPlan>,
    pub(crate) after_match_skip: ResolvedAfterMatchSkip,
    pub(crate) match_aware_symbols: Arc<[SymbolId]>,
    pub(crate) match_aware_bitmap: u64,
    pub(crate) max_define_lookahead_rows: NavigationOffset,
    pub(crate) has_deferred_history_operations: bool,
    pub(crate) has_symbol_qualified_aggregates: bool,
    pub(crate) has_classifier_aggregates: bool,
    pub(crate) has_unqualified_aggregates: bool,
    pub(crate) has_volatile_managed_accumulators: bool,
    pub(crate) symbol_table: Arc<SymbolTable>,
    pub(crate) symbol_name_arrays: Arc<[Option<datafusion::arrow::array::ArrayRef>]>,
    pub(crate) vm_program: ValidatedVmProgram,
    pub(crate) has_global_match_number_predicate: bool,
    pub(crate) aggregate_symbols_bitmap: u64,
    // None means no Deferred evaluator reads path labels or exclusions. Wide
    // symbol domains retain conservative reachability for IDs outside the bitmap.
    pub(crate) path_sensitive_deferred_symbols: Option<u64>,
    pub(crate) deferred_history: DeferredHistoryProjection,
    pub(crate) aggregate_hot_tables: AggregateHotTables,
    pub(crate) relationships: SymbolRelationships,
    pub(crate) static_extractions: Vec<ResolvedStaticExtraction>,
}

impl PreparedMatcherProgram {
    #[inline]
    pub(crate) fn normalized_pattern(&self) -> &NormalizedPattern {
        self.normalized_pattern.as_ref()
    }

    #[inline]
    pub(crate) fn output_plan(&self) -> &Arc<ExecutableOutputPlan> {
        &self.output
    }

    #[inline]
    pub(crate) fn rows_per_match(&self) -> &RowsPerMatch {
        self.output.rows_per_match()
    }

    #[inline]
    pub(crate) fn after_match_skip(&self) -> &ResolvedAfterMatchSkip {
        &self.after_match_skip
    }

    #[inline]
    pub(crate) fn match_aware_symbols(&self) -> &[SymbolId] {
        &self.match_aware_symbols
    }

    #[inline]
    pub(crate) const fn has_lookahead_defines(&self) -> bool {
        !self.max_define_lookahead_rows.is_zero()
    }

    #[inline]
    pub(crate) const fn has_path_dependent_aggregates(&self) -> bool {
        self.has_symbol_qualified_aggregates || self.has_classifier_aggregates
    }
}

/// Execution facts consumed by buffering, ordering, and Halo policy.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct StreamRequirements {
    pub(crate) independent_candidate_starts: bool,
    pub(crate) needs_complete_partition: bool,
    pub(crate) interleaves_logical_partitions: bool,
}