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
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
// 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.

//! Immutable physical output layout and finalization choices.

use std::collections::BTreeSet;
use std::sync::Arc;

use crate::core::{
    EmptyMatchesMode, MatchMetadataColumn, MatchRecognizeOutputSpec, MatchSummaryField,
    NavigationOffsets, RowsPerMatch, SymbolId,
};
use crate::nfa::CompiledAutomaton;
use crate::planning::logical::MAX_DIRECT_EDGE_OFFSET;
use crate::planning::logical::MetadataEndpoint;
pub(crate) use crate::planning::logical::SelectedReductionOp;
use datafusion::arrow::datatypes::{DataType, Schema, SchemaRef};
use datafusion::physical_plan::PhysicalExpr;
use datafusion_common::{DataFusionError, Result, internal_err};
use datafusion_physical_expr::expressions::Column;
use datafusion_physical_expr::projection::{ProjectionExpr, ProjectionExprs};

/// Passthrough output slots that retain their partition values on virtual rows.
#[derive(Debug, Clone, Default)]
pub(crate) struct PartitionPassthrough(Option<Arc<[bool]>>);

impl PartitionPassthrough {
    fn try_new(
        stream: &ExecutableRowStreamPlan,
        partition_input_indices: &[usize],
    ) -> Result<Self> {
        if partition_input_indices.is_empty() {
            return Ok(Self::default());
        }
        let passthrough = stream.spec().passthrough_input_indices();
        let mut flags = Vec::new();
        flags.try_reserve_exact(passthrough.len()).map_err(|error| {
            DataFusionError::ResourcesExhausted(format!(
                "MATCH_RECOGNIZE partition passthrough bindings could not reserve {} entries: {error}",
                passthrough.len()
            ))
        })?;
        flags.extend(
            passthrough
                .iter()
                .map(|index| partition_input_indices.binary_search(index).is_ok()),
        );
        Ok(Self(flags.iter().any(|flag| *flag).then(|| flags.into())))
    }

    pub(crate) fn has_keys(&self) -> bool {
        self.0.is_some()
    }

    pub(crate) fn retains(&self, output_index: usize) -> bool {
        self.0.as_ref().is_some_and(|flags| flags[output_index])
    }
}

/// Physical partition dependencies bound to each matcher output stream.
#[derive(Debug, Clone, Default)]
pub(crate) struct OutputPartitionBindings {
    visible: PartitionPassthrough,
}

impl OutputPartitionBindings {
    pub(crate) fn try_new(
        input_schema: &Schema,
        output: &ExecutableOutputPlan,
        partition_exprs: impl IntoIterator<Item = Arc<dyn PhysicalExpr>>,
    ) -> Result<Self> {
        let mut direct_partition_indices: BTreeSet<_> =
            output.prepared_partition_inputs.iter().copied().collect();
        let partition_input_indices =
            ProjectionExprs::new(partition_exprs.into_iter().map(|expr| {
                if let Some(column) = expr.downcast_ref::<Column>() {
                    direct_partition_indices.insert(column.index());
                }
                ProjectionExpr::new(expr, "")
            }))
            .column_indices();
        if let Some(index) = partition_input_indices
            .iter()
            .find(|index| **index >= input_schema.fields().len())
        {
            return internal_err!(
                "MATCH_RECOGNIZE partition passthrough index {index} is out of bounds for input schema with {} columns",
                input_schema.fields().len()
            );
        }
        let direct_partition_indices =
            direct_partition_indices.into_iter().collect::<Vec<_>>();
        // ONE ROW grouping still evaluates partition expressions, including
        // when an upper Aggregate finalizes a row stream. Public ALL ROWS
        // exposes input fields, so expression arguments are not partition keys.
        let visible_indices = if output.spec().retains_partition_expr_inputs()
            || matches!(output.rows_per_match(), RowsPerMatch::OneRow)
        {
            &partition_input_indices
        } else {
            &direct_partition_indices
        };
        Ok(Self {
            visible: PartitionPassthrough::try_new(output.stream(), visible_indices)?,
        })
    }

    pub(crate) fn visible(&self) -> PartitionPassthrough {
        self.visible.clone()
    }
}

/// MATCH_NUMBER output column whose position and Int64 Arrow type were checked
/// while the executable layout was constructed.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct ResolvedMatchNumberColumn(usize);

impl ResolvedMatchNumberColumn {
    const fn new_validated(index: usize) -> Self {
        Self(index)
    }

    pub(crate) const fn index(self) -> usize {
        self.0
    }
}

/// Arrow layout and checked bindings shared by every output finalizer.
#[derive(Debug, Clone)]
pub(crate) struct ExecutableRowStreamPlan {
    schema: SchemaRef,
    passthrough_schema: SchemaRef,
    spec: MatchRecognizeOutputSpec,
    classifier_bitset_symbol_ids: Arc<[SymbolId]>,
    match_number_column: Option<ResolvedMatchNumberColumn>,
    has_classifier: bool,
    has_sequence_number: bool,
    has_excluded: bool,
    rows_per_match: RowsPerMatch,
    original_rows_per_match: RowsPerMatch,
    suppress_terminal_empty: bool,
    suppress_navigation_buffer_rows: bool,
}

impl ExecutableRowStreamPlan {
    fn try_new(
        input_schema: &Schema,
        spec: MatchRecognizeOutputSpec,
        classifier_bitset_symbol_ids: Arc<[SymbolId]>,
        summary_fields: &[MatchSummaryField],
        rows_per_match: RowsPerMatch,
        automaton: &CompiledAutomaton,
    ) -> Result<Arc<Self>> {
        validate_metadata_columns(&spec)?;
        validate_passthrough_indices(input_schema, &spec)?;
        validate_classifier_ids(&spec, &classifier_bitset_symbol_ids, automaton)?;

        let schema = spec.build_arrow_schema_with_summaries(input_schema, summary_fields);
        let passthrough_len = spec.passthrough_input_indices().len();
        let passthrough_schema = Arc::new(Schema::new_with_metadata(
            schema.fields()[..passthrough_len].to_vec(),
            schema.metadata().clone(),
        ));
        let match_number_column = spec
            .metadata_columns()
            .iter()
            .position(|column| *column == MatchMetadataColumn::MatchNumber)
            .map(|metadata_index| {
                passthrough_len
                    .checked_add(metadata_index)
                    .map(ResolvedMatchNumberColumn::new_validated)
                    .ok_or_else(|| {
                        DataFusionError::Internal(
                            "MATCH_RECOGNIZE MATCH_NUMBER output index overflow"
                                .to_string(),
                        )
                    })
            })
            .transpose()?;

        Ok(Arc::new(Self {
            original_rows_per_match: rows_per_match.clone(),
            rows_per_match,
            suppress_terminal_empty: false,
            suppress_navigation_buffer_rows: false,
            has_classifier: spec
                .metadata_columns()
                .contains(&MatchMetadataColumn::Classifier),
            has_sequence_number: spec
                .metadata_columns()
                .contains(&MatchMetadataColumn::MatchSequenceNumber),
            has_excluded: spec
                .metadata_columns()
                .contains(&MatchMetadataColumn::Excluded),
            schema,
            passthrough_schema,
            spec,
            classifier_bitset_symbol_ids,
            match_number_column,
        }))
    }

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

    pub(crate) fn passthrough_schema(&self) -> &SchemaRef {
        &self.passthrough_schema
    }

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

    pub(crate) fn classifier_bitset_symbol_ids(&self) -> &Arc<[SymbolId]> {
        &self.classifier_bitset_symbol_ids
    }

    pub(crate) const fn match_number_column(&self) -> Option<ResolvedMatchNumberColumn> {
        self.match_number_column
    }

    pub(crate) const fn has_classifier(&self) -> bool {
        self.has_classifier
    }

    pub(crate) const fn has_sequence_number(&self) -> bool {
        self.has_sequence_number
    }

    pub(crate) const fn has_excluded(&self) -> bool {
        self.has_excluded
    }

    pub(crate) const fn navigation_offsets(&self) -> NavigationOffsets {
        self.spec.navigation_offsets()
    }

    pub(crate) const fn rows_per_match(&self) -> &RowsPerMatch {
        &self.rows_per_match
    }

    pub(crate) const fn original_rows_per_match(&self) -> &RowsPerMatch {
        &self.original_rows_per_match
    }

    pub(crate) const fn suppresses_terminal_empty(&self) -> bool {
        self.suppress_terminal_empty
    }

    pub(crate) fn emits_navigation_buffer_rows(&self) -> bool {
        !self.navigation_offsets().is_zero() && !self.suppress_navigation_buffer_rows
    }

    pub(crate) fn emits_terminal_empty_match(&self) -> bool {
        self.emits_virtual_empty_match() && !self.suppress_terminal_empty
    }

    pub(crate) fn empty_matches_mode(&self) -> &EmptyMatchesMode {
        static SHOW: EmptyMatchesMode = EmptyMatchesMode::Show;
        match &self.rows_per_match {
            RowsPerMatch::OneRow => &SHOW,
            RowsPerMatch::AllRows(mode) => mode,
        }
    }

    pub(crate) fn emits_virtual_empty_match(&self) -> bool {
        !matches!(self.empty_matches_mode(), EmptyMatchesMode::Omit)
    }
}

/// A winner's native result, already decoded using its bound aggregate type.
/// The enclosing Option on a register read distinguishes an unsupported source from SQL NULL.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) enum WinningValue {
    Int32(Option<i32>),
    Int64(Option<i64>),
    Float64(Option<f64>),
    Decimal128(Option<i128>),
}

/// A primitive input reduction with an optional matching DEFINE register.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct ExecutableReduction {
    pub(crate) op: SelectedReductionOp,
    pub(crate) input_column: usize,
    pub(crate) input_type: DataType,
    pub(crate) output_type: DataType,
    pub(crate) managed_aggregate: Option<usize>,
}

/// A direct edge navigation measure for `ONE ROW PER MATCH`: resolves
/// `FIRST(S.x, logical_offset)` or `LAST(S.x, logical_offset)` within the
/// selected match, applies `physical_shift` (negative for `PREV`, positive for
/// `NEXT`, zero for pure `FIRST`/`LAST`), and emits `default_value` (or SQL
/// `NULL` when `None`) if the anchor is absent or the shifted coordinate falls
/// outside the SQL partition.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct ExecutableEdge {
    pub(crate) input_column: usize,
    pub(crate) last: bool,
    pub(crate) logical_offset: usize,
    pub(crate) physical_shift: i64,
    pub(crate) default_value: Option<datafusion_common::ScalarValue>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
enum SelectedValue {
    Count,
    Edge(ExecutableEdge),
    Reduction(ExecutableReduction),
    Metadata(MetadataEndpoint),
}

/// A value computed directly from the elected match and its input.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct ExecutableDirectCountSummary {
    field: MatchSummaryField,
    symbol_id: Option<SymbolId>,
    value: SelectedValue,
}

impl ExecutableDirectCountSummary {
    pub(crate) fn new(field: MatchSummaryField, symbol_id: Option<SymbolId>) -> Self {
        Self {
            field,
            symbol_id,
            value: SelectedValue::Count,
        }
    }

    #[cfg(test)]
    pub(crate) fn new_edge(
        field: MatchSummaryField,
        symbol_id: Option<SymbolId>,
        input_column: usize,
        last: bool,
    ) -> Self {
        Self::new_edge_spec(
            field,
            symbol_id,
            ExecutableEdge {
                input_column,
                last,
                logical_offset: 0,
                physical_shift: 0,
                default_value: None,
            },
        )
    }

    pub(crate) fn new_edge_spec(
        field: MatchSummaryField,
        symbol_id: Option<SymbolId>,
        edge: ExecutableEdge,
    ) -> Self {
        Self {
            field,
            symbol_id,
            value: SelectedValue::Edge(edge),
        }
    }

    pub(crate) fn format_selected_value(&self, prefix: &str, input: &Schema) -> String {
        let name = self.field().column_name();
        match &self.value {
            SelectedValue::Reduction(reduction) => {
                let column = input.field(reduction.input_column).name();
                let function = format!("{:?}", reduction.op).to_uppercase();
                let route = if reduction.managed_aggregate.is_some() {
                    "DirectRegister"
                } else {
                    "DirectSliceAgg"
                };
                format!("{name}={function}({prefix}{column}):{route}")
            }
            SelectedValue::Metadata(endpoint) => {
                let function = if endpoint.last() { "LAST" } else { "FIRST" };
                let column = endpoint.column().measure_function_name().to_uppercase();
                format!("{name}={function}({prefix}{column}()):DirectEdge")
            }
            SelectedValue::Edge(edge) => {
                let column = input.field(edge.input_column).name();
                let function = if edge.last { "LAST" } else { "FIRST" };
                let inner = if edge.logical_offset == 0 {
                    format!("{function}({prefix}{column})")
                } else {
                    format!("{function}({prefix}{column}, {})", edge.logical_offset)
                };
                let expr = if edge.physical_shift < 0 {
                    format!("PREV({inner}, {})", edge.physical_shift.unsigned_abs())
                } else if edge.physical_shift > 0 {
                    format!("NEXT({inner}, {})", edge.physical_shift)
                } else {
                    inner
                };
                format!("{name}={expr}:DirectEdge")
            }
            SelectedValue::Count => format!("{name}=COUNT({prefix}*):DirectCount"),
        }
    }

    /// Original physical input edge specification if this summary gathers an edge.
    pub(crate) const fn edge(&self) -> Option<&ExecutableEdge> {
        match &self.value {
            SelectedValue::Edge(edge) => Some(edge),
            _ => None,
        }
    }

    pub(crate) fn new_metadata(
        field: MatchSummaryField,
        symbol_id: Option<SymbolId>,
        endpoint: MetadataEndpoint,
    ) -> Self {
        Self {
            field,
            symbol_id,
            value: SelectedValue::Metadata(endpoint),
        }
    }

    pub(crate) const fn metadata(&self) -> Option<MetadataEndpoint> {
        match self.value {
            SelectedValue::Metadata(endpoint) => Some(endpoint),
            _ => None,
        }
    }

    pub(crate) fn new_reduction(
        field: MatchSummaryField,
        symbol_id: Option<SymbolId>,
        reduction: ExecutableReduction,
    ) -> Self {
        Self {
            field,
            symbol_id,
            value: SelectedValue::Reduction(reduction),
        }
    }

    pub(crate) const fn reduction(&self) -> Option<&ExecutableReduction> {
        match &self.value {
            SelectedValue::Reduction(reduction) => Some(reduction),
            _ => None,
        }
    }

    pub(crate) const fn input_column(&self) -> Option<usize> {
        match &self.value {
            SelectedValue::Count | SelectedValue::Metadata(_) => None,
            SelectedValue::Edge(edge) => Some(edge.input_column),
            SelectedValue::Reduction(reduction) => Some(reduction.input_column),
        }
    }

    pub(crate) fn field(&self) -> &MatchSummaryField {
        &self.field
    }

    pub(crate) const fn symbol_id(&self) -> Option<SymbolId> {
        self.symbol_id
    }
}

/// Complete executable matcher output, including its one finalization route.
#[derive(Debug, Clone)]
pub(crate) struct ExecutableOutputPlan {
    /// Direct source columns whose normalized keys are materialized on the input.
    pub(crate) prepared_partition_inputs: Box<[usize]>,
    stream: Arc<ExecutableRowStreamPlan>,
    finalizer: ExecutableOutputFinalizer,
}

/// The finalizer selected for an output plan.
///
/// Exactly one route is active. Direct summaries emit one visible row per match.
#[derive(Debug, Clone)]
pub(crate) enum ExecutableOutputFinalizer {
    /// Emit the configured row stream without matcher-owned reduction.
    Rows,
    /// Derive counts from path facts without a private row stream. An empty
    /// summary list still preserves one-row-per-match cardinality.
    DirectCounts {
        summaries: Arc<[ExecutableDirectCountSummary]>,
    },
}

impl ExecutableOutputPlan {
    pub(crate) fn with_synthetic_row_filter(
        mut self: Arc<Self>,
        rows_per_match: RowsPerMatch,
        suppress_terminal_empty: bool,
    ) -> Result<Arc<Self>> {
        use EmptyMatchesMode::{Omit, Show, WithUnmatched};
        use RowsPerMatch::AllRows;
        if !matches!(self.finalizer, ExecutableOutputFinalizer::Rows)
            || self.stream.emits_navigation_buffer_rows()
            || (!self.stream.classifier_bitset_symbol_ids().is_empty()
                && !(suppress_terminal_empty && self.rows_per_match() == &rows_per_match))
            || !matches!(
                (self.rows_per_match(), &rows_per_match),
                (AllRows(WithUnmatched), AllRows(_))
                    | (AllRows(Show), AllRows(Show | Omit))
                    | (AllRows(Omit), AllRows(Omit))
            )
        {
            return internal_err!("invalid MATCH_RECOGNIZE synthetic row filter");
        }
        let stream = Arc::make_mut(&mut Arc::make_mut(&mut self).stream);
        stream.rows_per_match = rows_per_match;
        stream.suppress_terminal_empty |= suppress_terminal_empty;
        Ok(self)
    }

    pub(crate) fn try_rows(
        input_schema: &Schema,
        spec: MatchRecognizeOutputSpec,
        classifier_bitset_symbol_ids: Arc<[SymbolId]>,
        rows_per_match: RowsPerMatch,
        automaton: &CompiledAutomaton,
    ) -> Result<Arc<Self>> {
        Ok(Arc::new(Self {
            prepared_partition_inputs: Box::default(),
            stream: ExecutableRowStreamPlan::try_new(
                input_schema,
                spec,
                classifier_bitset_symbol_ids,
                &[],
                rows_per_match,
                automaton,
            )?,
            finalizer: ExecutableOutputFinalizer::Rows,
        }))
    }

    pub(crate) fn try_direct_counts(
        input_schema: &Schema,
        spec: MatchRecognizeOutputSpec,
        classifier_bitset_symbol_ids: Arc<[SymbolId]>,
        summaries: Vec<ExecutableDirectCountSummary>,
        automaton: &CompiledAutomaton,
    ) -> Result<Arc<Self>> {
        validate_direct_counts(
            &summaries,
            input_schema,
            spec.navigation_offsets(),
            automaton,
        )?;
        let fields = summaries
            .iter()
            .map(|summary| summary.field.clone())
            .collect::<Vec<_>>();
        let mut stream = ExecutableRowStreamPlan::try_new(
            input_schema,
            spec,
            classifier_bitset_symbol_ids,
            &fields,
            RowsPerMatch::OneRow,
            automaton,
        )?;
        // Direct summaries evaluate shifted PREV/NEXT edges directly against
        // retained history and lookahead windows without emitting halo rows.
        Arc::make_mut(&mut stream).suppress_navigation_buffer_rows = true;
        Ok(Arc::new(Self {
            prepared_partition_inputs: Box::default(),
            stream,
            finalizer: ExecutableOutputFinalizer::DirectCounts {
                summaries: summaries.into(),
            },
        }))
    }

    pub(crate) fn stream(&self) -> &Arc<ExecutableRowStreamPlan> {
        &self.stream
    }

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

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

    pub(crate) fn classifier_bitset_symbol_ids(&self) -> &Arc<[SymbolId]> {
        self.stream().classifier_bitset_symbol_ids()
    }

    pub(crate) fn match_number_column(&self) -> Option<ResolvedMatchNumberColumn> {
        self.stream().match_number_column()
    }

    pub(crate) fn rows_per_match(&self) -> &RowsPerMatch {
        self.stream.rows_per_match()
    }

    pub(crate) const fn finalizer(&self) -> &ExecutableOutputFinalizer {
        &self.finalizer
    }

    pub(crate) fn summary_count(&self) -> usize {
        match &self.finalizer {
            ExecutableOutputFinalizer::Rows => 0,
            ExecutableOutputFinalizer::DirectCounts { summaries } => summaries.len(),
        }
    }

    pub(crate) fn mark_referenced_input_columns(&self, needed: &mut [bool]) {
        for &idx in self.spec().passthrough_input_indices() {
            if let Some(slot) = needed.get_mut(idx) {
                *slot = true;
            }
        }
        for &idx in self.prepared_partition_inputs.iter() {
            if let Some(slot) = needed.get_mut(idx) {
                *slot = true;
            }
        }

        if let ExecutableOutputFinalizer::DirectCounts { summaries } = &self.finalizer {
            for summary in summaries.iter() {
                if let Some(idx) = summary.input_column()
                    && let Some(slot) = needed.get_mut(idx)
                {
                    *slot = true;
                }
            }
        }
    }

    pub(crate) fn with_appended_passthrough(
        &self,
        input_schema: &Schema,
        input_index: usize,
        automaton: &CompiledAutomaton,
    ) -> Result<Arc<Self>> {
        if input_schema.fields().len() != input_index.saturating_add(1) {
            return internal_err!(
                "MATCH_RECOGNIZE private passthrough must be the final input column"
            );
        }
        let mut passthrough = self.spec().passthrough_input_indices().to_vec();
        passthrough.push(input_index);
        let spec = self
            .spec()
            .clone()
            .with_passthrough_input_indices(passthrough);
        let fields = match &self.finalizer {
            ExecutableOutputFinalizer::Rows => Vec::new(),
            ExecutableOutputFinalizer::DirectCounts { summaries } => summaries
                .iter()
                .map(|summary| summary.field.clone())
                .collect(),
        };
        let mut stream = ExecutableRowStreamPlan::try_new(
            input_schema,
            spec,
            Arc::clone(self.classifier_bitset_symbol_ids()),
            &fields,
            self.rows_per_match().clone(),
            automaton,
        )?;
        let updated = Arc::make_mut(&mut stream);
        updated.original_rows_per_match = self.stream.original_rows_per_match.clone();
        updated.suppress_terminal_empty = self.stream.suppress_terminal_empty;
        updated.suppress_navigation_buffer_rows =
            self.stream.suppress_navigation_buffer_rows;
        Ok(Arc::new(Self {
            stream,
            ..self.clone()
        }))
    }
}

fn validate_metadata_columns(spec: &MatchRecognizeOutputSpec) -> Result<()> {
    for (index, column) in spec.metadata_columns().iter().enumerate() {
        if *column == MatchMetadataColumn::PathId {
            return internal_err!(
                "MATCH_RECOGNIZE internal path ID cannot be selected for final output"
            );
        }
        if spec.metadata_columns()[..index].contains(column) {
            return internal_err!(
                "MATCH_RECOGNIZE output metadata column '{}' is selected more than once",
                column.as_ref()
            );
        }
    }
    Ok(())
}

fn validate_passthrough_indices(
    input_schema: &Schema,
    spec: &MatchRecognizeOutputSpec,
) -> Result<()> {
    if let Some(index) = spec
        .passthrough_input_indices()
        .iter()
        .copied()
        .find(|index| *index >= input_schema.fields().len())
    {
        return internal_err!(
            "MATCH_RECOGNIZE output passthrough index {index} is out of bounds for the validated input schema with {} columns",
            input_schema.fields().len()
        );
    }
    Ok(())
}

fn validate_classifier_ids(
    spec: &MatchRecognizeOutputSpec,
    ids: &[SymbolId],
    automaton: &CompiledAutomaton,
) -> Result<()> {
    if ids.len() != spec.classifier_bitset_symbols().len() {
        return internal_err!(
            "MATCH_RECOGNIZE classifier output has {} IDs, expected {}",
            ids.len(),
            spec.classifier_bitset_symbols().len()
        );
    }
    let mut seen = BTreeSet::new();
    for (position, (id, name)) in
        ids.iter().zip(spec.classifier_bitset_symbols()).enumerate()
    {
        if !seen.insert(*id) {
            return internal_err!(
                "MATCH_RECOGNIZE classifier output position {position} duplicates symbol ID {id}"
            );
        }
        let Some(Some(compiled_name)) = automaton.id_to_symbol().get(id.index()) else {
            return internal_err!(
                "MATCH_RECOGNIZE classifier output position {position} has invalid symbol ID {id}"
            );
        };
        if compiled_name != name {
            return internal_err!(
                "MATCH_RECOGNIZE classifier output position {position} binds '{name}' to compiled symbol {:?}",
                Some(compiled_name)
            );
        }
    }
    Ok(())
}

fn validate_direct_counts(
    summaries: &[ExecutableDirectCountSummary],
    input_schema: &Schema,
    navigation_offsets: NavigationOffsets,
    automaton: &CompiledAutomaton,
) -> Result<()> {
    let mut output_ids = BTreeSet::new();
    for (position, summary) in summaries.iter().enumerate() {
        let id = summary.field.output_id();
        if !output_ids.insert(id) {
            return internal_err!(
                "MATCH_RECOGNIZE summary output ID {id} is selected more than once"
            );
        }
        let field = summary.field.arrow_field();
        match &summary.value {
            SelectedValue::Reduction(reduction)
                if !input_schema
                    .fields()
                    .get(reduction.input_column)
                    .is_some_and(|input| input.data_type() == &reduction.input_type)
                    || field.data_type() != &reduction.output_type
                    || !reduction
                        .op
                        .accepts(&reduction.input_type, &reduction.output_type)
                    || field.is_nullable()
                        != (reduction.op != SelectedReductionOp::Count) =>
            {
                return internal_err!(
                    "MATCH_RECOGNIZE reduction {position} has incompatible input or result type"
                );
            }
            SelectedValue::Metadata(endpoint)
                if field.data_type() != &endpoint.column().data_type()
                    || !field.is_nullable() =>
            {
                return internal_err!(
                    "MATCH_RECOGNIZE metadata endpoint {position} has incompatible field {field:?}"
                );
            }
            SelectedValue::Edge(edge) => {
                let Some(input) = input_schema.fields().get(edge.input_column) else {
                    return internal_err!(
                        "MATCH_RECOGNIZE edge input {} is out of bounds",
                        edge.input_column
                    );
                };
                if input.data_type() != field.data_type()
                    || input.metadata() != field.metadata()
                    || !field.is_nullable()
                {
                    return internal_err!(
                        "MATCH_RECOGNIZE edge summary {position} field {field:?} cannot gather input {input:?}"
                    );
                }
                if edge.logical_offset > MAX_DIRECT_EDGE_OFFSET {
                    return internal_err!(
                        "MATCH_RECOGNIZE edge summary {position} logical offset {} exceeds limit {MAX_DIRECT_EDGE_OFFSET}",
                        edge.logical_offset
                    );
                }
                let shift_ok = if edge.physical_shift < 0 {
                    edge.physical_shift.unsigned_abs()
                        <= navigation_offsets.previous().as_u64()
                } else {
                    (edge.physical_shift as u64) <= navigation_offsets.next().as_u64()
                };
                if !shift_ok {
                    return internal_err!(
                        "MATCH_RECOGNIZE edge summary {position} shift {} exceeds navigation offsets {:?}",
                        edge.physical_shift,
                        navigation_offsets
                    );
                }
                if let Some(default) = &edge.default_value
                    && (default.is_null() || default.data_type() != *field.data_type())
                {
                    return internal_err!(
                        "MATCH_RECOGNIZE edge summary {position} default {default:?} does not match field {field:?}"
                    );
                }
            }
            SelectedValue::Count
                if field.data_type() != &DataType::Int64 || field.is_nullable() =>
            {
                return internal_err!(
                    "MATCH_RECOGNIZE direct count summary {position} requires a non-null Int64 field, got {field:?}"
                );
            }
            SelectedValue::Count
            | SelectedValue::Reduction(_)
            | SelectedValue::Metadata(_) => {}
        }
        if let Some(symbol_id) = summary.symbol_id
            && !matches!(
                automaton.id_to_symbol().get(symbol_id.index()),
                Some(Some(_))
            )
        {
            return internal_err!(
                "MATCH_RECOGNIZE direct count summary {position} has invalid symbol ID {symbol_id}"
            );
        }
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::{NormalizedPattern, Pattern, Symbol};
    use datafusion::arrow::datatypes::Field;

    fn automaton() -> CompiledAutomaton {
        CompiledAutomaton::compile(
            &NormalizedPattern::Ast(Pattern::Symbol(Symbol::Named("A".into()))),
            &["A".into()],
        )
        .unwrap()
    }

    #[test]
    fn synthetic_row_filters_only_tighten_and_survive_private_projection() -> Result<()> {
        use EmptyMatchesMode::{Omit, Show, WithUnmatched};
        use RowsPerMatch::AllRows;

        let graph = automaton();
        let key = Field::new("k", DataType::Int64, false);
        let base = ExecutableOutputPlan::try_rows(
            &Schema::new(vec![key.clone()]),
            MatchRecognizeOutputSpec::new(vec![0], vec![], vec![]),
            Arc::from([]),
            AllRows(WithUnmatched),
            &graph,
        )?;
        let show = Arc::clone(&base).with_synthetic_row_filter(AllRows(Show), true)?;
        assert_eq!(base.rows_per_match(), &AllRows(WithUnmatched));
        assert!(base.stream().emits_terminal_empty_match());
        assert!(show.stream().emits_virtual_empty_match());
        assert!(!show.stream().emits_terminal_empty_match());
        assert!(Arc::ptr_eq(base.schema(), show.schema()));
        assert!(
            Arc::clone(&show)
                .with_synthetic_row_filter(AllRows(WithUnmatched), false)
                .is_err()
        );

        let projected = show
            .with_synthetic_row_filter(AllRows(Omit), false)?
            .with_appended_passthrough(
                &Schema::new(vec![key, Field::new("private", DataType::Int64, true)]),
                1,
                &graph,
            )?;
        assert_eq!(projected.rows_per_match(), &AllRows(Omit));
        assert_eq!(
            projected.stream().original_rows_per_match(),
            &AllRows(WithUnmatched)
        );
        assert!(projected.stream().suppresses_terminal_empty());
        Ok(())
    }

    #[test]
    fn direct_counts_keep_one_row_cardinality_without_private_rows() {
        for with_count in [false, true] {
            let summaries = if with_count {
                vec![ExecutableDirectCountSummary::new(
                    MatchSummaryField::new(
                        0,
                        Arc::new(Field::new("count", DataType::Int64, false)),
                    ),
                    None,
                )]
            } else {
                vec![]
            };
            let plan = ExecutableOutputPlan::try_direct_counts(
                &Schema::empty(),
                MatchRecognizeOutputSpec::new(vec![], vec![], vec![]),
                Arc::from([]),
                summaries,
                &automaton(),
            )
            .unwrap();
            let ExecutableOutputFinalizer::DirectCounts { summaries } = plan.finalizer()
            else {
                panic!("expected native counts");
            };
            assert_eq!(summaries.len(), usize::from(with_count));
            assert_eq!(plan.rows_per_match(), &RowsPerMatch::OneRow);
        }
    }

    #[test]
    fn direct_edges_bind_nullable_values_to_original_input_types() {
        let input = Schema::new(vec![
            Field::new("z", DataType::Utf8, false),
            Field::new("value", DataType::Int32, true),
        ]);
        let automaton = automaton();
        let field = MatchSummaryField::new(
            0,
            Arc::new(Field::new("endpoint", DataType::Int32, true)),
        );
        for (index, valid) in [(0, false), (1, true), (2, false)] {
            let edge =
                ExecutableDirectCountSummary::new_edge(field.clone(), None, index, true);
            assert_eq!(
                validate_direct_counts(
                    &[edge],
                    &input,
                    NavigationOffsets::ZERO,
                    &automaton
                )
                .is_ok(),
                valid
            );
        }
    }

    #[test]
    fn direct_count_sealing_validates_ids_fields_and_symbol_targets() {
        for (ids, data_type, nullable, symbol, error) in [
            (vec![4, 5], DataType::Int64, false, None, None),
            (
                vec![4, 4],
                DataType::Int64,
                false,
                None,
                Some("output ID 4 is selected more than once"),
            ),
            (
                vec![4],
                DataType::Int32,
                false,
                None,
                Some("requires a non-null Int64 field"),
            ),
            (
                vec![4],
                DataType::Int64,
                true,
                None,
                Some("requires a non-null Int64 field"),
            ),
            (
                vec![4],
                DataType::Int64,
                false,
                Some(SymbolId::try_new(2, 3).unwrap()),
                Some("invalid symbol ID 2"),
            ),
        ] {
            let summaries = ids
                .into_iter()
                .map(|id| {
                    ExecutableDirectCountSummary::new(
                        MatchSummaryField::new(
                            id,
                            Arc::new(Field::new("count", data_type.clone(), nullable)),
                        ),
                        symbol,
                    )
                })
                .collect();
            let result = ExecutableOutputPlan::try_direct_counts(
                &Schema::empty(),
                MatchRecognizeOutputSpec::new(vec![], vec![], vec![]),
                Arc::from([]),
                summaries,
                &automaton(),
            );
            if let Some(expected) = error {
                let error = result.unwrap_err();
                assert!(error.to_string().contains(expected), "{error}");
            } else {
                assert!(result.is_ok());
            }
        }
    }
}