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
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
// 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.

//! Output projection specification for MATCH_RECOGNIZE results.
//!
//! The planner and optimizer use this model to select passthrough input
//! columns, metadata columns, classifier bitsets, and navigation padding.
//! Planning owns output cardinality and selected-match summaries.

use std::fmt::{self, Display, Formatter};
use std::sync::Arc;

use datafusion::arrow::datatypes::{
    Field, Schema as ArrowSchema, SchemaRef as ArrowSchemaRef,
};
use datafusion::common::{DFSchema, DFSchemaRef};

use crate::core::metadata::{MatchMetadataColumn, classifier_bits_arrow_fields};

// The count-named prefix is part of the semantic Substrait one-row wire
// contract. It identifies any admitted selected-match summary.
const MATCH_SUMMARY_COL_PREFIX: &str = "__mr_count_summary_";

/// One typed value emitted while finalizing a selected match.
///
/// The stable output identity survives logical output pruning without
/// renumbering downstream column references. The field retains DataFusion's
/// inferred type, nullability, and metadata while using an internal generated
/// name at the matcher boundary.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct MatchSummaryField {
    output_id: usize,
    field: Arc<Field>,
}

impl MatchSummaryField {
    /// Construct a summary field with its stable matcher-boundary name.
    pub fn new(output_id: usize, field: Arc<Field>) -> Self {
        let field = Arc::new(
            field
                .as_ref()
                .clone()
                .with_name(format!("{MATCH_SUMMARY_COL_PREFIX}{output_id}")),
        );
        Self { output_id, field }
    }

    /// Return the stable identity used when summary fields are pruned.
    pub const fn output_id(&self) -> usize {
        self.output_id
    }

    /// Return the stable matcher-boundary column name.
    pub fn column_name(&self) -> String {
        self.field.name().clone()
    }

    /// Return the exact Arrow field exposed at the matcher boundary.
    pub fn arrow_field(&self) -> Arc<Field> {
        Arc::clone(&self.field)
    }
}

/// Largest navigation offset whose buffer-row sequence numbers remain outside
/// the valid matched-row sequence-number range.
pub const MAX_NAVIGATION_OFFSET: u64 = (1_u64 << 62) - 1;

/// A checked `PREV` or `NEXT` row offset.
///
/// The bound is part of the output metadata contract: `NEXT` buffer rows use
/// sequence numbers above `MAX_VALID_MATCH_SEQUENCE_NUMBER`,
/// so a larger offset would make buffer and matched-row categories overlap.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(transparent)]
pub struct NavigationOffset(usize);

impl NavigationOffset {
    /// Zero rows of navigation.
    pub const ZERO: Self = Self(0);
    /// One row of navigation.
    pub const ONE: Self = Self(1);

    /// Validate a platform-sized offset against the metadata representation.
    pub fn try_new(value: usize) -> Option<Self> {
        let value_u64 = u64::try_from(value).ok()?;
        (value_u64 <= MAX_NAVIGATION_OFFSET).then_some(Self(value))
    }

    /// Validate a portable literal and its conversion to this platform.
    pub fn try_from_u64(value: u64) -> Option<Self> {
        usize::try_from(value).ok().and_then(Self::try_new)
    }

    /// Return the checked offset in platform-sized form.
    pub const fn as_usize(self) -> usize {
        self.0
    }

    /// Return the checked offset in its portable metadata representation.
    pub fn as_u64(self) -> u64 {
        u64::try_from(self.0)
            .expect("validated navigation offsets always fit the u64 metadata domain")
    }

    /// Return whether this offset selects the current row.
    pub const fn is_zero(self) -> bool {
        self.0 == 0
    }
}

/// Checked navigation padding retained by planning and execution.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct NavigationOffsets {
    previous: NavigationOffset,
    next: NavigationOffset,
}

impl NavigationOffsets {
    /// No padding before or after a match.
    #[cfg(any(test, feature = "substrait", feature = "internal-bench"))]
    pub const ZERO: Self = Self {
        previous: NavigationOffset::ZERO,
        next: NavigationOffset::ZERO,
    };

    /// Construct padding from offsets that have already been checked.
    pub const fn new(previous: NavigationOffset, next: NavigationOffset) -> Self {
        Self { previous, next }
    }

    /// Validate raw `PREV` and `NEXT` padding together.
    #[cfg(test)]
    pub fn try_from_raw(previous: usize, next: usize) -> Option<Self> {
        Some(Self::new(
            NavigationOffset::try_new(previous)?,
            NavigationOffset::try_new(next)?,
        ))
    }

    /// Return the maximum retained offset before a match.
    pub const fn previous(self) -> NavigationOffset {
        self.previous
    }

    /// Return the maximum retained offset after a match.
    pub const fn next(self) -> NavigationOffset {
        self.next
    }

    /// Return whether neither side requires navigation padding.
    pub const fn is_zero(self) -> bool {
        self.previous.is_zero() && self.next.is_zero()
    }
}

/// Selects the columns emitted by `MATCH_RECOGNIZE`.
///
/// It records which input columns pass through, their order, which metadata
/// columns are produced, which classifier bitsets are appended, and the
/// checked navigation padding required by those columns. Planning supplies
/// selected-match summary fields separately when it owns one-row
/// finalization.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct MatchRecognizeOutputSpec {
    passthrough_input_indices: Vec<usize>,
    metadata_columns: Vec<MatchMetadataColumn>,
    classifier_bitset_symbols: Vec<String>,
    navigation_offsets: NavigationOffsets,
    retain_partition_expr_inputs: bool,
}

impl MatchRecognizeOutputSpec {
    /// Pass through every input column, emit all public metadata, and append a
    /// classifier bitset for every declared symbol.
    #[cfg(any(test, feature = "substrait"))]
    pub fn full_from(input_schema: &DFSchemaRef, symbols: &[String]) -> Self {
        Self::new(
            (0..input_schema.fields().len()).collect(),
            MatchMetadataColumn::public_output().to_vec(),
            symbols.to_vec(),
        )
    }

    /// Construct an output selection from explicit components.
    #[cfg(any(test, feature = "substrait", feature = "internal-bench"))]
    pub fn new(
        passthrough_input_indices: Vec<usize>,
        metadata_columns: Vec<MatchMetadataColumn>,
        classifier_bitset_symbols: Vec<String>,
    ) -> Self {
        Self::with_validated_navigation_offsets(
            passthrough_input_indices,
            metadata_columns,
            classifier_bitset_symbols,
            NavigationOffsets::ZERO,
        )
    }

    /// Construct an output selection from offsets already checked while
    /// lowering the source expression.
    pub fn with_validated_navigation_offsets(
        passthrough_input_indices: Vec<usize>,
        metadata_columns: Vec<MatchMetadataColumn>,
        classifier_bitset_symbols: Vec<String>,
        navigation_offsets: NavigationOffsets,
    ) -> Self {
        Self {
            passthrough_input_indices,
            metadata_columns,
            classifier_bitset_symbols,
            navigation_offsets,
            retain_partition_expr_inputs: false,
        }
    }

    /// Return input-column indices in output order.
    pub fn passthrough_input_indices(&self) -> &[usize] {
        &self.passthrough_input_indices
    }

    /// Return metadata columns emitted after passthrough columns.
    pub fn metadata_columns(&self) -> &[MatchMetadataColumn] {
        &self.metadata_columns
    }

    /// Return symbols whose classifier bitsets follow the metadata columns.
    pub fn classifier_bitset_symbols(&self) -> &[String] {
        &self.classifier_bitset_symbols
    }

    /// Return the checked navigation padding retained around each match.
    pub const fn navigation_offsets(&self) -> NavigationOffsets {
        self.navigation_offsets
    }

    /// Whether empty rows preserve computed-key inputs for downstream ONE ROW grouping.
    pub const fn retains_partition_expr_inputs(&self) -> bool {
        self.retain_partition_expr_inputs
    }

    /// Retain computed-key inputs when downstream ONE ROW grouping needs them.
    pub fn with_partition_expr_inputs(mut self, retain: bool) -> Self {
        self.retain_partition_expr_inputs = retain;
        self
    }

    /// Replace navigation padding with checked offsets.
    #[cfg(test)]
    pub fn with_navigation_offsets(
        mut self,
        navigation_offsets: NavigationOffsets,
    ) -> Self {
        self.navigation_offsets = navigation_offsets;
        self
    }

    /// Replace passthrough columns without changing generated columns or
    /// navigation padding.
    pub fn with_passthrough_input_indices(
        mut self,
        passthrough_input_indices: Vec<usize>,
    ) -> Self {
        self.passthrough_input_indices = passthrough_input_indices;
        self
    }

    /// Build the logical DataFusion schema for the selected columns.
    pub fn build_df_schema(
        &self,
        input: &DFSchema,
    ) -> datafusion::common::Result<DFSchemaRef> {
        self.build_df_schema_with_summaries(input, std::iter::empty())
    }

    /// Build the logical DataFusion schema with selected-match summaries
    /// appended after the row-stream columns.
    pub fn build_df_schema_with_summaries<'a>(
        &self,
        input: &DFSchema,
        summary_fields: impl IntoIterator<Item = &'a MatchSummaryField>,
    ) -> datafusion::common::Result<DFSchemaRef> {
        let mut fields = Vec::with_capacity(self.passthrough_input_indices.len());
        for &i in &self.passthrough_input_indices {
            if i >= input.fields().len() {
                return datafusion::common::plan_err!(
                    "passthrough_input_indices contains out-of-bounds index"
                );
            }
            let (qualifier, field) = input.qualified_field(i);
            let mut field = field.as_ref().clone();
            field.set_nullable(true);
            fields.push((qualifier.cloned(), Arc::new(field)));
        }

        fields.extend(
            self.generated_fields(summary_fields)
                .map(|field| (None, field)),
        );

        Ok(Arc::new(DFSchema::new_with_metadata(
            fields,
            input.metadata().clone(),
        )?))
    }

    /// Build the physical Arrow schema for the selected columns.
    ///
    /// # Panics
    ///
    /// Panics if a passthrough index is outside `input`. Checked planning paths
    /// validate the same specification against the logical schema first.
    #[cfg(test)]
    pub fn build_arrow_schema(&self, input: &ArrowSchema) -> ArrowSchemaRef {
        self.build_arrow_schema_with_summaries(input, std::iter::empty())
    }

    /// Build the physical Arrow schema with selected-match summaries appended
    /// after the row-stream columns.
    ///
    /// # Panics
    ///
    /// Panics if a passthrough index is outside `input`. Checked planning paths
    /// validate the same specification against the logical schema first.
    pub fn build_arrow_schema_with_summaries<'a>(
        &self,
        input: &ArrowSchema,
        summary_fields: impl IntoIterator<Item = &'a MatchSummaryField>,
    ) -> ArrowSchemaRef {
        let fields: Vec<_> = self
            .passthrough_input_indices
            .iter()
            .map(|&i| {
                let mut field = input.fields()[i].as_ref().clone();
                field.set_nullable(true);
                Arc::new(field)
            })
            .chain(self.generated_fields(summary_fields))
            .collect();

        Arc::new(ArrowSchema::new_with_metadata(
            fields,
            input.metadata().clone(),
        ))
    }

    fn generated_fields<'a>(
        &self,
        summary_fields: impl IntoIterator<Item = &'a MatchSummaryField>,
    ) -> impl Iterator<Item = Arc<Field>> {
        self.metadata_columns
            .iter()
            .copied()
            .map(MatchMetadataColumn::arrow_field)
            .chain(classifier_bits_arrow_fields(
                &self.classifier_bitset_symbols,
            ))
            .chain(
                summary_fields
                    .into_iter()
                    .map(MatchSummaryField::arrow_field),
            )
    }

    /// Return whether the row stream selects no columns.
    pub fn is_empty(&self) -> bool {
        self.metadata_columns.is_empty()
            && self.classifier_bitset_symbols.is_empty()
            && self.passthrough_input_indices.is_empty()
    }
}

/// Formats a `MatchRecognizeOutputSpec` using column names from a `DFSchema`.
pub type OutputSpecWithDFSchema<'a> = OutputSpecDisplay<'a, DFSchemaRef>;

/// Formats a `MatchRecognizeOutputSpec` using column names from an Arrow schema.
pub type OutputSpecWithArrowSchema<'a> = OutputSpecDisplay<'a, ArrowSchemaRef>;

trait SchemaColumnName {
    fn column_name(&self, index: usize) -> String;
}

impl SchemaColumnName for DFSchemaRef {
    fn column_name(&self, index: usize) -> String {
        let (qualifier, field) = self.qualified_field(index);
        match qualifier {
            Some(qualifier) => format!("{}.{}", qualifier, field.name()),
            None => field.name().to_string(),
        }
    }
}

impl SchemaColumnName for ArrowSchemaRef {
    fn column_name(&self, index: usize) -> String {
        self.fields()[index].name().to_string()
    }
}

/// Formats an output specification against its input schema.
pub struct OutputSpecDisplay<'a, S> {
    spec: &'a MatchRecognizeOutputSpec,
    schema: &'a S,
    summary_fields: Option<Vec<&'a MatchSummaryField>>,
}

impl<'a, S> OutputSpecDisplay<'a, S> {
    /// Construct a schema-aware display wrapper.
    ///
    /// Formatting the wrapper panics if a passthrough index is outside `schema`.
    pub fn new(spec: &'a MatchRecognizeOutputSpec, schema: &'a S) -> Self {
        Self {
            spec,
            schema,
            summary_fields: None,
        }
    }

    /// Include matcher-native selected summaries in the formatted output.
    ///
    /// An empty iterator still displays the selected-summary output mode.
    pub fn with_summary_fields(
        mut self,
        summary_fields: impl IntoIterator<Item = &'a MatchSummaryField>,
    ) -> Self {
        self.summary_fields = Some(summary_fields.into_iter().collect());
        self
    }
}

impl<S: SchemaColumnName> Display for OutputSpecDisplay<'_, S> {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        let spec = self.spec;
        let mut parts: Vec<String> = Vec::new();

        if !spec.passthrough_input_indices.is_empty() {
            let passthrough = spec
                .passthrough_input_indices
                .iter()
                .map(|&i| self.schema.column_name(i))
                .collect::<Vec<_>>()
                .join(",");
            parts.push(format!("passthrough_columns=[{passthrough}]"));
        }

        if !spec.metadata_columns.is_empty() {
            let meta = spec
                .metadata_columns
                .iter()
                .map(|c| c.as_ref())
                .collect::<Vec<_>>()
                .join(",");
            parts.push(format!("metadata=[{meta}]"));
        }

        if !spec.classifier_bitset_symbols.is_empty() {
            let bits = spec.classifier_bitset_symbols.join(",");
            parts.push(format!("classifier_flags=[{bits}]"));
        }

        if let Some(summary_fields) = self.summary_fields.as_deref() {
            let summaries = summary_fields
                .iter()
                .map(|summary| {
                    let field = summary.field.as_ref();
                    format!(
                        "{}:{}{}",
                        field.name(),
                        field.data_type(),
                        if field.is_nullable() { "?" } else { "" }
                    )
                })
                .collect::<Vec<_>>()
                .join(",");
            parts.push(format!("native_one_row=[summaries=[{summaries}]]"));
        }

        if parts.is_empty() {
            return Ok(());
        }

        write!(f, "output={{")?;
        write!(f, "{}", parts.join(", "))?;
        write!(f, "}}")
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use datafusion::arrow::datatypes::DataType;

    #[test]
    fn navigation_offsets_check_metadata_and_direction_boundaries() {
        let raw = u64::from(u32::MAX);
        assert_eq!(NavigationOffset::try_from_u64(raw).unwrap().as_u64(), raw);
        assert!(NavigationOffset::try_from_u64(MAX_NAVIGATION_OFFSET + 1).is_none());
        if usize::try_from(MAX_NAVIGATION_OFFSET).is_ok() {
            let maximum = NavigationOffset::try_from_u64(MAX_NAVIGATION_OFFSET).unwrap();
            assert_eq!(maximum.as_u64(), MAX_NAVIGATION_OFFSET);
            assert_eq!(
                i64::try_from(maximum.as_u64()).unwrap(),
                crate::core::metadata::MAX_VALID_MATCH_SEQUENCE_NUMBER
            );
        }
        if let Ok(invalid) = usize::try_from(MAX_NAVIGATION_OFFSET + 1) {
            assert!(NavigationOffsets::try_from_raw(invalid, 0).is_none());
            assert!(NavigationOffsets::try_from_raw(0, invalid).is_none());
        }
    }

    #[test]
    fn summary_field_preserves_inferred_contract_and_uses_stable_name() {
        let source = Arc::new(
            Field::new("aggregate_result", DataType::Decimal256(38, 6), true)
                .with_metadata(std::collections::HashMap::from([(
                    "owner".to_string(),
                    "datafusion".to_string(),
                )])),
        );

        let summary = MatchSummaryField::new(7, source);

        assert_eq!(summary.output_id(), 7);
        assert_eq!(summary.column_name(), "__mr_count_summary_7");
        assert_eq!(summary.arrow_field().name(), "__mr_count_summary_7");
        assert_eq!(
            summary.arrow_field().data_type(),
            &DataType::Decimal256(38, 6)
        );
        assert!(summary.arrow_field().is_nullable());
        assert_eq!(
            summary
                .arrow_field()
                .metadata()
                .get("owner")
                .map(String::as_str),
            Some("datafusion")
        );
    }
}