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
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
// 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.

//! Checked pattern, DEFINE predicates, matcher input slots, and output contracts.

use super::ExtractionKind;
pub use super::output::{LogicalMatchOutput, LogicalSelectedMatchSummary};
#[cfg(test)]
use crate::core::SymbolEvalMode;
use crate::core::{
    AfterMatchSkip, AggregateId, MatchMetadataColumn, MatchRecognizeOutputSpec,
    MatchRecognizeSpec, Pattern, RowsPerMatch, classifier_bits_col_name,
    managed_aggregate_col_name, static_predicate_and_col_name,
    static_predicate_or_col_name, static_scalar_col_name, symbol_col_name,
};
use crate::planning::hybrid_guard::{LogicalHybridGuardExpr, build_logical_hybrid_guard};
use crate::planning::semantic_metadata::{
    aggregate_references_semantic_metadata, is_managed_classifier_navigation_aggregate,
};
use crate::planning::{NamedExpr, SymbolRelationships};
use datafusion::arrow::datatypes::DataType;
use datafusion::common::float_semantics::has_float_leaf;
use datafusion::common::{DFSchema, Result, ScalarValue, plan_err};
use datafusion::logical_expr::expr::AggregateFunction;
use datafusion::logical_expr::{Expr, ExprSchemable, SortExpr, lit};
use std::collections::{BTreeMap, BTreeSet};

/// Constructor input for a prepared symbol predicate.
#[derive(Clone, Debug)]
pub struct LogicalSymbolInput {
    pub(crate) name: String,
    predicate: LogicalSymbolInputPredicate,
}
#[derive(Clone, Debug)]
enum LogicalSymbolInputPredicate {
    Static { expr: Expr, demanded: bool },
    MatchAware(MatchAwareSymbolInput),
}
impl LogicalSymbolInput {
    /// Describe a complete static predicate. Node construction checks both its
    /// dependency proof and its materialized Boolean input binding.
    pub fn static_(name: impl Into<String>, expr: Expr) -> Self {
        Self {
            name: name.into(),
            predicate: LogicalSymbolInputPredicate::Static {
                expr,
                demanded: false,
            },
        }
    }
}

impl LogicalSymbolInput {
    pub(crate) fn demanded(name: impl Into<String>, expr: Expr) -> Self {
        Self {
            name: name.into(),
            predicate: LogicalSymbolInputPredicate::Static {
                expr,
                demanded: true,
            },
        }
    }
}

/// Checked predicate for static membership or candidate-state evaluation.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum LogicalSymbolPredicate {
    /// Static membership predicate.
    Static {
        /// Normalized predicate retained for diagnostics, export or matcher evaluation.
        expr: Expr,
    },
    /// Predicate evaluated against a candidate's local state or history.
    MatchAware(Box<MatchAwareSymbolPredicate>),
}
impl LogicalSymbolPredicate {
    /// Return the complete static predicate.
    pub fn static_expr(&self) -> Option<&Expr> {
        match self {
            Self::Static { expr } => Some(expr),
            Self::MatchAware(_) => None,
        }
    }

    fn precomputed_expr(&self) -> Option<Expr> {
        match self {
            Self::Static { expr } => Some(expr.clone()),
            Self::MatchAware(predicate) => predicate.precomputed_expr(),
        }
    }
}

/// One symbol and the identity of its Boolean result slot.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct LogicalSymbol {
    pub(super) id: LogicalSymbolId,
    pub(super) name: String,
    pub(super) predicate: LogicalSymbolPredicate,
    demanded: bool,
}
impl LogicalSymbol {
    /// Row predicate whose errors or volatile calls belong to a reached transition.
    pub fn demanded_expr(&self) -> Option<&Expr> {
        if self.demanded {
            self.predicate.static_expr()
        } else {
            None
        }
    }
    /// Dense symbol identity.
    pub const fn id(&self) -> LogicalSymbolId {
        self.id
    }
    /// Canonical symbol name.
    pub fn name(&self) -> &str {
        &self.name
    }
    /// Checked predicate retained with its identity.
    pub fn predicate(&self) -> &LogicalSymbolPredicate {
        &self.predicate
    }
    /// Boolean result field.
    pub fn result_column_name(&self) -> String {
        symbol_col_name(self.name())
    }
}

/// Common input to a checked logical program.
#[derive(Clone, Debug)]
pub struct LogicalMatchProgramInput {
    /// Partitioning expressions.
    pub partition_by: Vec<Expr>,
    /// Within-partition ordering.
    pub order_by: Vec<SortExpr>,
    /// Resume position after selection.
    pub after_skip: AfterMatchSkip,
    /// Pattern syntax tree.
    pub pattern: Pattern,
    /// Predicates in symbol identity order.
    pub symbols: Vec<LogicalSymbolInput>,
    /// Static extractions and aggregates used by candidate predicates.
    pub match_aware: Option<ExecutableMatchProgramInput>,
    /// Output cardinality and selected-row expressions.
    pub output: LogicalMatchOutput,
    /// Proven symbol relationships.
    pub symbol_relationships: SymbolRelationships,
}

/// Authoritative checked pattern, input, and selected-match output program.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct LogicalMatchProgram {
    partition_by: Vec<Expr>,
    order_by: Vec<SortExpr>,
    after_skip: AfterMatchSkip,
    pattern: Pattern,
    pub(super) symbols: Vec<LogicalSymbol>,
    after_skip_target: Option<LogicalSymbolId>,
    matcher_input_slots: Vec<InternalSlotRequirement>,
    output: LogicalMatchOutput,
    symbol_relationships: SymbolRelationships,
    match_aware: Option<Box<ExecutableMatchProgram>>,
}
impl LogicalMatchProgram {
    pub(crate) fn try_new(input: LogicalMatchProgramInput) -> Result<Self> {
        let names = input
            .symbols
            .iter()
            .map(|symbol| symbol.name.clone())
            .collect::<Vec<_>>();
        let after_skip_target = validate_structure(
            &names,
            &input.pattern,
            &input.after_skip,
            &input.output,
            &input.symbol_relationships,
        )?;
        let pattern_vars = names.iter().cloned().collect::<BTreeSet<_>>();
        let admission =
            MatchAwareAdmission::try_new(names, &input.symbols, input.match_aware)?;
        let symbols = input
            .symbols
            .into_iter()
            .enumerate()
            .map(|(index, symbol)| {
                let id = LogicalSymbolId(index);
                let (predicate, demanded) = match symbol.predicate {
                    LogicalSymbolInputPredicate::Static { expr, demanded } => {
                        crate::planning::define::validate_static_predicate(
                            &symbol.name,
                            &expr,
                            &pattern_vars,
                        )?;
                        (LogicalSymbolPredicate::Static { expr }, demanded)
                    }
                    LogicalSymbolInputPredicate::MatchAware(predicate) => (
                        LogicalSymbolPredicate::MatchAware(Box::new(
                            admission.build_predicate(id, &symbol.name, predicate)?,
                        )),
                        false,
                    ),
                };
                Ok(LogicalSymbol {
                    id,
                    name: symbol.name,
                    predicate,
                    demanded,
                })
            })
            .collect::<Result<Vec<_>>>()?;
        Ok(Self {
            partition_by: input.partition_by,
            order_by: input.order_by,
            after_skip: input.after_skip,
            pattern: input.pattern,
            symbols,
            after_skip_target,
            matcher_input_slots: Vec::new(),
            output: input.output,
            symbol_relationships: input.symbol_relationships,
            match_aware: admission.into_payload(),
        })
    }
    /// Whether DEFINE execution uses candidate predicates, extractions, or aggregates.
    #[cfg(test)]
    pub fn requires_match_aware_defines(&self) -> bool {
        self.match_aware.is_some()
    }
    /// Partitioning expressions.
    pub fn partition_by(&self) -> &[Expr] {
        &self.partition_by
    }
    /// Whether partition equality can differ from the physical key's floating representation.
    pub fn has_float_partition_keys(&self, schema: &DFSchema) -> Result<bool> {
        for key in &self.partition_by {
            if has_float_leaf(&key.get_type(schema)?) {
                return Ok(true);
            }
        }
        Ok(false)
    }

    /// Within-partition ordering.
    pub fn order_by(&self) -> &[SortExpr] {
        &self.order_by
    }
    /// Resume strategy.
    pub fn after_skip(&self) -> &AfterMatchSkip {
        &self.after_skip
    }
    /// Resolved symbol-targeted resume identity.
    pub fn after_skip_target(&self) -> Option<LogicalSymbolId> {
        self.after_skip_target
    }
    /// Requested output cardinality.
    pub fn rows_per_match(&self) -> &RowsPerMatch {
        self.output.rows_per_match()
    }
    /// Pattern syntax tree.
    pub fn pattern(&self) -> &Pattern {
        &self.pattern
    }
    /// Checked symbol table.
    pub fn symbols(&self) -> &[LogicalSymbol] {
        &self.symbols
    }
    /// Canonical symbol names in identity order.
    pub fn symbol_names(&self) -> impl ExactSizeIterator<Item = &str> {
        self.symbols.iter().map(LogicalSymbol::name)
    }
    /// Typed fields crossing the matcher input boundary.
    pub fn matcher_input_slots(&self) -> &[InternalSlotRequirement] {
        &self.matcher_input_slots
    }
    /// Generated name of one owned input field.
    pub fn internal_slot_name(&self, owner: InternalSlotOwner) -> Option<String> {
        match owner {
            InternalSlotOwner::SymbolResult(id) => self
                .symbols
                .get(id.index())
                .map(LogicalSymbol::result_column_name),
            other => self
                .match_aware
                .as_deref()
                .and_then(|payload| payload.internal_slot_name(other)),
        }
    }
    pub(crate) fn with_matcher_input_slots(mut self, schema: &DFSchema) -> Result<Self> {
        let mut slots = Vec::new();
        if let Some(payload) = &self.match_aware {
            payload.append_matcher_input_slots(schema, &mut slots)?;
        }
        for symbol in &self.symbols {
            let name = symbol.result_column_name();
            let Some(field) = exact_internal_field(schema, &name)? else {
                if symbol.predicate.static_expr().is_some() {
                    return plan_err!(
                        "MATCH_RECOGNIZE static symbol result '{name}' must bind exactly one non-null Boolean input field"
                    );
                }
                // Candidate-evaluated symbols have no input membership column.
                continue;
            };
            if field.data_type() != &DataType::Boolean || field.is_nullable() {
                return plan_err!(
                    "MATCH_RECOGNIZE symbol result '{name}' must be non-null Boolean"
                );
            }
            slots.push(InternalSlotRequirement::new(
                InternalSlotOwner::SymbolResult(symbol.id),
                DataType::Boolean,
                false,
            ));
        }
        self.matcher_input_slots = slots;
        Ok(self)
    }
    pub(crate) fn with_pruned_selected_summary_input(
        mut self,
        schema: &DFSchema,
    ) -> Result<Self> {
        self.output.prune_selected_summary_input(schema)?;
        Ok(self)
    }
    /// Selected visible row fields.
    pub fn output_spec(&self) -> &MatchRecognizeOutputSpec {
        self.output.spec()
    }
    /// Complete output cardinality and summary contract.
    pub fn output(&self) -> &LogicalMatchOutput {
        &self.output
    }
    /// Exact selected-match aggregates.
    pub fn selected_match_summaries(&self) -> &[LogicalSelectedMatchSummary] {
        self.output.selected_match_summaries()
    }
    /// Private selected-row stream consumed by summaries.
    pub fn selected_match_summary_input_spec(&self) -> Option<&MatchRecognizeOutputSpec> {
        self.output.selected_match_summary_input_spec()
    }
    /// Planner-proven symbol relationships.
    pub fn symbol_relationships(&self) -> &SymbolRelationships {
        &self.symbol_relationships
    }
    pub(crate) fn static_defines(&self) -> impl Iterator<Item = NamedExpr> + '_ {
        self.symbols.iter().filter_map(|symbol| {
            symbol.predicate.precomputed_expr().map(|expr| NamedExpr {
                name: symbol.name.clone(),
                expr,
            })
        })
    }
}

fn exact_internal_field<'a>(
    schema: &'a DFSchema,
    name: &str,
) -> Result<Option<&'a datafusion::arrow::datatypes::Field>> {
    let mut fields = schema.fields().iter().filter(|field| field.name() == name);
    let Some(field) = fields.next() else {
        return Ok(None);
    };
    if fields.next().is_some() {
        return plan_err!("MATCH_RECOGNIZE internal field '{name}' is ambiguous");
    }
    Ok(Some(field.as_ref()))
}

#[derive(Clone, Debug)]
pub(super) enum MatchAwareSymbolInput {
    Local(Expr),
    History { expr: Expr, local: Option<Expr> },
}
impl LogicalSymbolInputPredicate {
    fn requires_history(&self) -> bool {
        matches!(
            self,
            Self::MatchAware(MatchAwareSymbolInput::History { .. })
        )
    }
}

impl LogicalSymbolInput {
    fn match_aware(name: impl Into<String>, predicate: MatchAwareSymbolInput) -> Self {
        Self {
            name: name.into(),
            predicate: LogicalSymbolInputPredicate::MatchAware(predicate),
        }
    }

    /// Describe a local candidate predicate.
    pub fn incremental(name: impl Into<String>, expr: Expr) -> Self {
        Self::match_aware(name, MatchAwareSymbolInput::Local(expr))
    }

    /// Describe a candidate predicate evaluated over its selected history.
    pub fn deferred(name: impl Into<String>, expr: Expr) -> Self {
        Self::history(name, expr, None)
    }

    /// Describe a history predicate with a local guard.
    pub fn hybrid(name: impl Into<String>, local: Expr, deferred: Expr) -> Self {
        Self::history(name, deferred, Some(local))
    }

    pub(in crate::planning::logical) fn history(
        name: impl Into<String>,
        expr: Expr,
        local: Option<Expr>,
    ) -> Self {
        Self::match_aware(name, MatchAwareSymbolInput::History { expr, local })
    }
}

/// Candidate-specific meaning of a checked symbol predicate.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum MatchAwareSymbolPredicate {
    /// Locally evaluated candidate expression.
    Incremental {
        /// Candidate expression.
        expr: Expr,
    },
    /// Deferred candidate expression.
    Deferred {
        /// History expression.
        expr: Expr,
    },
    /// Local expression with a checked three-valued Deferred guard.
    Hybrid {
        /// Local candidate expression.
        local: Expr,
        /// Equivalent history expression.
        deferred: Expr,
        /// Three-valued guard.
        guard: Box<LogicalHybridGuardExpr>,
    },
}
impl MatchAwareSymbolPredicate {
    /// Candidate evaluation mode.
    #[cfg(test)]
    pub const fn mode(&self) -> SymbolEvalMode {
        match self {
            Self::Incremental { .. } => SymbolEvalMode::Incremental,
            Self::Deferred { .. } => SymbolEvalMode::Deferred,
            Self::Hybrid { .. } => SymbolEvalMode::Hybrid,
        }
    }
    /// Locally evaluated candidate expression.
    pub fn local_expr(&self) -> Option<&Expr> {
        match self {
            Self::Incremental { expr } | Self::Hybrid { local: expr, .. } => Some(expr),
            Self::Deferred { .. } => None,
        }
    }
    /// Deferred history expression.
    pub fn deferred_expr(&self) -> Option<&Expr> {
        match self {
            Self::Deferred { expr } | Self::Hybrid { deferred: expr, .. } => Some(expr),
            Self::Incremental { .. } => None,
        }
    }
    /// Checked Hybrid guard.
    pub fn hybrid_guard(&self) -> Option<&LogicalHybridGuardExpr> {
        match self {
            Self::Hybrid { guard, .. } => Some(guard),
            _ => None,
        }
    }
    pub(super) fn precomputed_expr(&self) -> Option<Expr> {
        matches!(self, Self::Deferred { .. }).then(|| lit(true))
    }
}
impl LogicalSymbolPredicate {
    /// Runtime evaluation mode; static programs retain the common Static case.
    #[cfg(test)]
    pub const fn mode(&self) -> SymbolEvalMode {
        match self {
            Self::Static { .. } => SymbolEvalMode::Static,
            Self::MatchAware(predicate) => predicate.mode(),
        }
    }
    /// Locally evaluated candidate expression.
    pub fn local_expr(&self) -> Option<&Expr> {
        match self {
            Self::MatchAware(predicate) => predicate.local_expr(),
            Self::Static { .. } => None,
        }
    }
    /// Deferred history expression.
    pub fn deferred_expr(&self) -> Option<&Expr> {
        match self {
            Self::MatchAware(predicate) => predicate.deferred_expr(),
            Self::Static { .. } => None,
        }
    }
    /// Stored Hybrid guard.
    pub fn hybrid_guard(&self) -> Option<&LogicalHybridGuardExpr> {
        match self {
            Self::MatchAware(predicate) => predicate.hybrid_guard(),
            Self::Static { .. } => None,
        }
    }
}

/// Zero-based identity of a reusable row-level expression.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct StaticExtractionId(usize);

impl StaticExtractionId {
    /// Return this extraction's position in the program's dense table.
    pub const fn index(self) -> usize {
        self.0
    }
}

/// One checked reusable row-level expression.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct LogicalStaticExtraction {
    id: StaticExtractionId,
    ordinal: usize,
    expr: Expr,
    kind: ExtractionKind,
    symbols: Vec<LogicalSymbolId>,
}

impl LogicalStaticExtraction {
    /// Return this extraction's dense logical identity.
    pub const fn id(&self) -> StaticExtractionId {
        self.id
    }

    /// Return the generated boundary column name.
    pub fn column_name(&self) -> String {
        static_extraction_column_name(self.kind, self.ordinal)
    }

    /// Return the expression computed once per input row.
    pub fn expr(&self) -> &Expr {
        &self.expr
    }

    /// Return the extraction's value kind.
    pub const fn kind(&self) -> ExtractionKind {
        self.kind
    }

    /// Return the symbols that may consume this extraction.
    pub fn symbols(&self) -> &[LogicalSymbolId] {
        &self.symbols
    }

    pub(crate) fn to_input(&self, symbols: &[LogicalSymbol]) -> StaticExtractionInput {
        StaticExtractionInput {
            expr: self.expr.clone(),
            kind: self.kind,
            symbols: self
                .symbols
                .iter()
                .map(|id| symbols[id.index()].name.clone())
                .collect(),
        }
    }
}

/// Constructor input for one reusable row-level expression.
#[derive(Clone, Debug)]
pub struct StaticExtractionInput {
    expr: Expr,
    kind: ExtractionKind,
    symbols: Vec<String>,
}

impl StaticExtractionInput {
    /// Describe an extraction; program validation assigns its identity and name.
    pub fn new(expr: Expr, kind: ExtractionKind, symbols: Vec<String>) -> Self {
        Self {
            expr,
            kind,
            symbols,
        }
    }
}

/// One checked aggregate maintained while a candidate match grows.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct LogicalManagedAggregate {
    id: AggregateId,
    func: AggregateFunction,
    symbol: Option<LogicalSymbolId>,
}

impl LogicalManagedAggregate {
    #[cfg(test)]
    pub(crate) fn for_test(
        id: usize,
        func: AggregateFunction,
        symbol: Option<LogicalSymbolId>,
    ) -> Self {
        Self {
            id: AggregateId::try_new(id, id + 1).expect("test aggregate ID is valid"),
            func,
            symbol,
        }
    }

    /// Return this aggregate's dense identity.
    pub const fn id(&self) -> AggregateId {
        self.id
    }

    /// Return the aggregate expression.
    pub fn func(&self) -> &AggregateFunction {
        &self.func
    }

    /// Return the symbol controlling updates, if any.
    pub const fn symbol(&self) -> Option<LogicalSymbolId> {
        self.symbol
    }

    /// Return the generated boundary column name.
    pub fn column_name(&self) -> String {
        managed_aggregate_col_name(self.id.index())
    }

    pub(crate) fn to_input(&self, symbols: &[LogicalSymbol]) -> ManagedAggregateInput {
        ManagedAggregateInput {
            func: self.func.clone(),
            symbol: self.symbol.map(|id| symbols[id.index()].name.clone()),
        }
    }
}

/// Aggregate constructor input; program validation assigns its dense identity.
#[derive(Clone, Debug)]
pub struct ManagedAggregateInput {
    func: AggregateFunction,
    symbol: Option<String>,
}

impl ManagedAggregateInput {
    /// Describe an aggregate and its optional update-controlling symbol.
    /// Program validation requires FILTER to have been normalized away.
    pub fn new(func: AggregateFunction, symbol: Option<String>) -> Self {
        Self { func, symbol }
    }

    pub(crate) fn replace_func(&mut self, func: AggregateFunction) {
        self.func = func;
    }
}

/// Extracted row expressions and managed aggregates supplied by DEFINE planning.
#[derive(Clone, Debug)]
pub struct ExecutableMatchProgramInput {
    /// Reusable row expressions consumed by candidate evaluators.
    pub static_extractions: Vec<StaticExtractionInput>,
    /// Aggregates updated while a candidate grows.
    pub managed_aggregates: Vec<ManagedAggregateInput>,
}
impl ExecutableMatchProgramInput {
    /// Group the extraction and aggregate definitions if either collection is nonempty.
    pub fn new(
        static_extractions: Vec<StaticExtractionInput>,
        managed_aggregates: Vec<ManagedAggregateInput>,
    ) -> Option<Self> {
        (!static_extractions.is_empty() || !managed_aggregates.is_empty()).then_some(
            Self {
                static_extractions,
                managed_aggregates,
            },
        )
    }
}
/// Checked extraction and aggregate definitions for candidate DEFINE evaluation.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct ExecutableMatchProgram {
    static_extractions: Vec<LogicalStaticExtraction>,
    managed_aggregates: Vec<LogicalManagedAggregate>,
}
impl ExecutableMatchProgram {
    /// Reusable row expressions consumed by candidate evaluators.
    pub fn static_extractions(&self) -> &[LogicalStaticExtraction] {
        &self.static_extractions
    }
    /// Aggregates updated while a candidate grows.
    pub fn managed_aggregates(&self) -> &[LogicalManagedAggregate] {
        &self.managed_aggregates
    }
    pub(super) fn internal_slot_name(&self, owner: InternalSlotOwner) -> Option<String> {
        match owner {
            InternalSlotOwner::ManagedAggregate(id) => self
                .managed_aggregates
                .get(id.index())
                .map(|_| managed_aggregate_col_name(id.index())),
            InternalSlotOwner::StaticExtraction(id) => self
                .static_extractions
                .get(id.index())
                .map(LogicalStaticExtraction::column_name),
            InternalSlotOwner::SymbolResult(_) => None,
        }
    }
    pub(super) fn append_matcher_input_slots(
        &self,
        schema: &DFSchema,
        slots: &mut Vec<InternalSlotRequirement>,
    ) -> Result<()> {
        for extraction in &self.static_extractions {
            let name = extraction.column_name();
            let field = required_internal_field(schema, &name)?;
            if extraction.kind() != ExtractionKind::Scalar
                && field.data_type() != &DataType::Boolean
            {
                return plan_err!(
                    "MATCH_RECOGNIZE static extraction '{}' must be Boolean, got {}",
                    field.name(),
                    field.data_type()
                );
            }
            slots.push(InternalSlotRequirement::new(
                InternalSlotOwner::StaticExtraction(extraction.id()),
                field.data_type().clone(),
                field.is_nullable(),
            ));
        }
        for aggregate in &self.managed_aggregates {
            let name = aggregate.column_name();
            let field = required_internal_field(schema, &name)?;
            slots.push(InternalSlotRequirement::new(
                InternalSlotOwner::ManagedAggregate(aggregate.id()),
                field.data_type().clone(),
                field.is_nullable(),
            ));
        }
        Ok(())
    }
}
impl LogicalMatchProgram {
    /// Whether skipping candidate evaluation in a proven match-free partition
    /// preserves errors and volatile calls. Static symbols are already evaluated
    /// by the input projection. Residual predicates and aggregate updates would
    /// otherwise execute only on candidates, potentially before a match fails.
    pub fn can_skip_candidate_evaluation(&self, input_schema: &DFSchema) -> bool {
        use crate::planning::expr_safety::can_discard_scalar;

        let safe = |expr: &Expr| can_discard_scalar(expr, Some(input_schema));
        self.symbols()
            .iter()
            .all(|symbol| match symbol.predicate() {
                LogicalSymbolPredicate::Static { .. } => symbol.demanded_expr().is_none(),
                LogicalSymbolPredicate::MatchAware(predicate) => {
                    predicate.deferred_expr().is_none()
                        && predicate.local_expr().is_some_and(safe)
                }
            })
            && self.managed_aggregates().iter().all(|aggregate| {
                managed_aggregate_is_infallible(aggregate.func(), input_schema, &safe)
            })
    }

    /// Candidate DEFINE metadata, available for programs with candidate predicates or state.
    pub fn match_aware(&self) -> Option<&ExecutableMatchProgram> {
        self.match_aware.as_deref()
    }
    /// Reusable candidate row expressions, empty for static programs.
    pub fn static_extractions(&self) -> &[LogicalStaticExtraction] {
        self.match_aware()
            .map(ExecutableMatchProgram::static_extractions)
            .unwrap_or_default()
    }
    /// Candidate aggregate definitions, empty for static programs.
    pub fn managed_aggregates(&self) -> &[LogicalManagedAggregate] {
        self.match_aware()
            .map(ExecutableMatchProgram::managed_aggregates)
            .unwrap_or_default()
    }
}

struct SymbolCatalog {
    names: Vec<String>,
    requires_history: Vec<bool>,
}

impl SymbolCatalog {
    fn new(names: Vec<String>, symbols: &[LogicalSymbolInput]) -> Self {
        // Common structure validation has already admitted unique canonical
        // names and assigned their order. This table adds only route facts.
        let requires_history = symbols
            .iter()
            .map(|symbol| symbol.predicate.requires_history())
            .collect();
        Self {
            names,
            requires_history,
        }
    }

    fn id(&self, context: &str, name: &str) -> Result<LogicalSymbolId> {
        resolve_symbol(&self.names, context, name)
    }
}

/// Temporary candidate validation state; no copy of common program data is retained.
pub(super) struct MatchAwareAdmission {
    catalog: SymbolCatalog,
    payload: Option<Box<ExecutableMatchProgram>>,
}
impl MatchAwareAdmission {
    pub(super) fn try_new(
        names: Vec<String>,
        symbols: &[LogicalSymbolInput],
        input: Option<ExecutableMatchProgramInput>,
    ) -> Result<Self> {
        let catalog = SymbolCatalog::new(names, symbols);
        let input = input.unwrap_or_else(|| ExecutableMatchProgramInput {
            static_extractions: vec![],
            managed_aggregates: vec![],
        });
        let managed_aggregates =
            build_managed_aggregates(input.managed_aggregates, &catalog)?;
        let mut ordinals = [0; 3];
        let static_extractions = input
            .static_extractions
            .into_iter()
            .enumerate()
            .map(|(index, extraction)| {
                let kind_index = match extraction.kind {
                    ExtractionKind::BooleanAnd => 0,
                    ExtractionKind::BooleanOr => 1,
                    ExtractionKind::Scalar => 2,
                };
                let ordinal = ordinals[kind_index];
                ordinals[kind_index] += 1;
                Ok(LogicalStaticExtraction {
                    id: StaticExtractionId(index),
                    ordinal,
                    expr: extraction.expr,
                    kind: extraction.kind,
                    symbols: extraction
                        .symbols
                        .iter()
                        .map(|name| catalog.id("static extraction", name))
                        .collect::<Result<Vec<_>>>()?,
                })
            })
            .collect::<Result<Vec<_>>>()?;
        let candidate_predicates = symbols.iter().any(|symbol| {
            matches!(symbol.predicate, LogicalSymbolInputPredicate::MatchAware(_))
        });
        let payload = (candidate_predicates
            || !static_extractions.is_empty()
            || !managed_aggregates.is_empty())
        .then(|| {
            Box::new(ExecutableMatchProgram {
                static_extractions,
                managed_aggregates,
            })
        });
        Ok(Self { catalog, payload })
    }
    pub(super) fn build_predicate(
        &self,
        id: LogicalSymbolId,
        name: &str,
        input: MatchAwareSymbolInput,
    ) -> Result<MatchAwareSymbolPredicate> {
        Ok(match input {
            MatchAwareSymbolInput::Local(expr) => {
                MatchAwareSymbolPredicate::Incremental { expr }
            }
            MatchAwareSymbolInput::History { expr, local: None } => {
                MatchAwareSymbolPredicate::Deferred { expr }
            }
            MatchAwareSymbolInput::History {
                expr: deferred,
                local: Some(local),
            } => {
                let aggregates = self
                    .payload
                    .as_deref()
                    .map(ExecutableMatchProgram::managed_aggregates)
                    .unwrap_or_default();
                let columns = effective_deferred_columns(id, aggregates, &self.catalog);
                let guard = build_logical_hybrid_guard(&local, &columns);
                if !guard.contains_unknown() {
                    return plan_err!(
                        "MATCH_RECOGNIZE Hybrid symbol '{}' has no Deferred dependency",
                        name
                    );
                }
                MatchAwareSymbolPredicate::Hybrid {
                    local,
                    deferred,
                    guard: Box::new(guard),
                }
            }
        })
    }
    pub(super) fn into_payload(self) -> Option<Box<ExecutableMatchProgram>> {
        self.payload
    }
}

fn static_extraction_column_name(kind: ExtractionKind, ordinal: usize) -> String {
    match kind {
        ExtractionKind::BooleanAnd => static_predicate_and_col_name(ordinal),
        ExtractionKind::BooleanOr => static_predicate_or_col_name(ordinal),
        ExtractionKind::Scalar => static_scalar_col_name(ordinal),
    }
}

fn build_managed_aggregates(
    inputs: Vec<ManagedAggregateInput>,
    catalog: &SymbolCatalog,
) -> Result<Vec<LogicalManagedAggregate>> {
    let count = inputs.len();
    inputs
        .into_iter()
        .enumerate()
        .map(|(index, aggregate)| {
            if aggregate_references_semantic_metadata(&aggregate.func)
                && !is_managed_classifier_navigation_aggregate(&aggregate.func)
            {
                return plan_err!(
                    "MATCH_RECOGNIZE managed aggregate {index} cannot read match metadata in a semantic argument, filter, or ordering expression"
                );
            }
            // Updates already carry row/symbol membership. Physical managed
            // accumulator programs do not evaluate a retained SQL FILTER.
            if aggregate.func.params.filter.is_some() {
                return plan_err!(
                    "MATCH_RECOGNIZE managed aggregate {index} cannot retain FILTER; normalize it before constructing managed state"
                );
            }
            Ok(LogicalManagedAggregate {
                id: AggregateId::try_new(index, count)
                    .expect("validated aggregate position is in bounds"),
                func: aggregate.func,
                symbol: aggregate
                    .symbol
                    .as_deref()
                    .map(|symbol| catalog.id("managed aggregate", symbol))
                    .transpose()?,
            })
        })
        .collect()
}

fn required_internal_field<'a>(
    schema: &'a DFSchema,
    name: &str,
) -> Result<&'a datafusion::arrow::datatypes::Field> {
    exact_internal_field(schema, name)?.ok_or_else(|| {
        datafusion::common::DataFusionError::Plan(format!(
            "MATCH_RECOGNIZE internal field '{name}' is missing"
        ))
    })
}

pub(in crate::planning::logical) fn effective_deferred_columns_for_program(
    program: &LogicalMatchProgram,
    define_id: LogicalSymbolId,
) -> BTreeSet<String> {
    collect_effective_deferred_columns(
        define_id,
        program.managed_aggregates(),
        program.symbol_names(),
        |source| {
            program.symbols()[source.index()]
                .predicate()
                .deferred_expr()
                .is_some()
        },
    )
}

fn effective_deferred_columns(
    define_id: LogicalSymbolId,
    aggregates: &[LogicalManagedAggregate],
    catalog: &SymbolCatalog,
) -> BTreeSet<String> {
    collect_effective_deferred_columns(
        define_id,
        aggregates,
        catalog.names.iter().map(String::as_str),
        |source| catalog.requires_history[source.index()],
    )
}

fn collect_effective_deferred_columns<'a>(
    define_id: LogicalSymbolId,
    aggregates: &[LogicalManagedAggregate],
    symbol_names: impl IntoIterator<Item = &'a str>,
    requires_history: impl Fn(LogicalSymbolId) -> bool,
) -> BTreeSet<String> {
    symbol_names
        .into_iter()
        .map(classifier_bits_col_name)
        .chain(aggregates.iter().filter_map(|aggregate| {
            let source = aggregate.symbol()?;
            (source != define_id && requires_history(source))
                .then(|| aggregate.column_name())
        }))
        .collect()
}

/// Whether updating and evaluating a plain managed aggregate cannot fail or
/// observe side effects when candidate evaluation is skipped on a match-free
/// partition or impossible tail.
pub(crate) fn managed_aggregate_is_infallible(
    func: &AggregateFunction,
    input_schema: &DFSchema,
    safe: &impl Fn(&Expr) -> bool,
) -> bool {
    use crate::planning::expr_safety::{
        scalar_ordering_type_is_safe, scalar_value_type_is_safe,
    };
    use datafusion::functions_aggregate::{
        average::avg_udaf,
        bool_and_or::{bool_and_udaf, bool_or_udaf},
        count::count_udaf,
        first_last::{first_value_udaf, last_value_udaf},
        min_max::{max_udaf, min_udaf},
        stddev::{stddev_pop_udaf, stddev_udaf},
        sum::sum_udaf,
        variance::{var_pop_udaf, var_samp_udaf},
    };
    use datafusion::logical_expr::type_coercion::functions::fields_with_udf;
    use datafusion::logical_expr::{ExprSchemable, Volatility};

    if !crate::planning::extract::is_plain_aggregate(func)
        || func.func.signature().volatility != Volatility::Immutable
        || !func.params.args.iter().all(safe)
    {
        return false;
    }
    let udaf = func.func.as_ref();
    if udaf == count_udaf().as_ref() {
        return func.params.args.len() <= 1;
    }
    if udaf == crate::functions::udaf::mr_prev_udaf().as_ref() {
        // Localized NEXT uses PREV with offset zero to capture a shifted input
        // value. This exact form copies one scalar and cannot fail at runtime.
        let [
            value,
            Expr::Literal(ScalarValue::UInt64(Some(0)), _),
            Expr::Literal(default, _),
            matched,
            classifier,
        ] = func.params.args.as_slice()
        else {
            return false;
        };
        return value.get_type(input_schema).is_ok_and(|ty| {
            scalar_ordering_type_is_safe(&ty) && default.data_type() == ty
        }) && matched
            .get_type(input_schema)
            .is_ok_and(|ty| ty == DataType::Boolean)
            && classifier
                .get_type(input_schema)
                .is_ok_and(|ty| ty == DataType::Boolean);
    }
    let [arg] = func.params.args.as_slice() else {
        return false;
    };
    let Ok((_, arg_field)) = arg.to_field(input_schema) else {
        return false;
    };
    let Ok(coerced_fields) = fields_with_udf(std::slice::from_ref(&arg_field), udaf)
    else {
        return false;
    };
    let [coerced_field] = coerced_fields.as_slice() else {
        return false;
    };
    // Physical managed aggregate execution (`build_aggregate_programs`) does not
    // coerce aggregate arguments, so the input must already match its coerced
    // UDF type.
    if arg_field.data_type() != coerced_field.data_type() {
        return false;
    }
    let Ok(return_field) = func.func.return_field(&coerced_fields) else {
        return false;
    };
    let coerced_type = coerced_field.data_type();
    let return_type = return_field.data_type();
    if udaf == first_value_udaf().as_ref() || udaf == last_value_udaf().as_ref() {
        return scalar_value_type_is_safe(coerced_type) && return_type == coerced_type;
    }
    if udaf == min_udaf().as_ref() || udaf == max_udaf().as_ref() {
        return !coerced_type.is_null()
            && scalar_ordering_type_is_safe(coerced_type)
            && return_type == coerced_type;
    }
    if udaf == bool_and_udaf().as_ref() || udaf == bool_or_udaf().as_ref() {
        return *coerced_type == DataType::Boolean && *return_type == DataType::Boolean;
    }
    if udaf == sum_udaf().as_ref() {
        return match (coerced_type, return_type) {
            (DataType::Int64 | DataType::UInt64 | DataType::Float64, _) => {
                return_type == coerced_type
            }
            // DataFusion's SumAccumulator<Decimal128Type> uses wrapping i128
            // addition without precision-value overflow validation.
            (DataType::Decimal128(_, s), DataType::Decimal128(_, rs)) => {
                s == rs
                    && scalar_value_type_is_safe(coerced_type)
                    && scalar_value_type_is_safe(return_type)
            }
            _ => false,
        };
    }
    if udaf == avg_udaf().as_ref()
        || udaf == stddev_udaf().as_ref()
        || udaf == stddev_pop_udaf().as_ref()
        || udaf == var_samp_udaf().as_ref()
        || udaf == var_pop_udaf().as_ref()
    {
        return *coerced_type == DataType::Float64 && *return_type == DataType::Float64;
    }
    false
}

/// Zero-based identity of a user-defined symbol in a logical match program.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct LogicalSymbolId(pub(crate) usize);

impl LogicalSymbolId {
    /// Return this symbol's position in the program's dense symbol table.
    pub const fn index(self) -> usize {
        self.0
    }

    #[cfg(test)]
    pub(crate) const fn for_test(index: usize) -> Self {
        Self(index)
    }
}

/// Semantic producer of one generated schema slot.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum InternalSlotOwner {
    /// Row-level result of one symbol predicate.
    SymbolResult(LogicalSymbolId),
    /// Placeholder for one managed aggregate value.
    ManagedAggregate(AggregateId),
    /// One reusable static row expression.
    StaticExtraction(StaticExtractionId),
}

/// Arrow field requirements for one internally generated slot.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct InternalSlotRequirement {
    owner: InternalSlotOwner,
    data_type: DataType,
    nullable: bool,
}

impl InternalSlotRequirement {
    pub(crate) fn new(
        owner: InternalSlotOwner,
        data_type: DataType,
        nullable: bool,
    ) -> Self {
        Self {
            owner,
            data_type,
            nullable,
        }
    }

    /// Return the typed producer of this slot.
    pub const fn owner(&self) -> InternalSlotOwner {
        self.owner
    }

    /// Return the required Arrow data type.
    pub const fn data_type(&self) -> &DataType {
        &self.data_type
    }

    /// Return whether the field may contain nulls.
    pub const fn nullable(&self) -> bool {
        self.nullable
    }
}

pub(crate) fn resolve_symbol(
    symbols: &[String],
    context: &str,
    name: &str,
) -> Result<LogicalSymbolId> {
    let Some(index) = symbols
        .iter()
        .position(|symbol| symbol.eq_ignore_ascii_case(name))
    else {
        return plan_err!("MATCH_RECOGNIZE {context} references unknown symbol '{name}'");
    };
    if symbols[index] != name {
        return plan_err!(
            "MATCH_RECOGNIZE {context} must use canonical symbol '{}', not '{name}'",
            symbols[index]
        );
    }
    Ok(LogicalSymbolId(index))
}

pub(crate) fn validate_structure(
    symbols: &[String],
    pattern: &Pattern,
    after_skip: &AfterMatchSkip,
    output: &LogicalMatchOutput,
    relationships: &SymbolRelationships,
) -> Result<Option<LogicalSymbolId>> {
    let mut seen = BTreeMap::new();
    for name in symbols {
        if let Some(previous) = seen.insert(name.to_ascii_lowercase(), name) {
            return plan_err!(
                "MATCH_RECOGNIZE logical symbol '{name}' duplicates symbol '{previous}'"
            );
        }
    }
    if symbols.iter().cloned().collect::<BTreeSet<_>>() != pattern.symbol_names() {
        return plan_err!(
            "MATCH_RECOGNIZE logical program symbols do not match pattern symbols"
        );
    }
    let target = match after_skip {
        AfterMatchSkip::ToFirst(name) | AfterMatchSkip::ToLast(name) => {
            Some(resolve_symbol(symbols, "AFTER MATCH SKIP", name)?)
        }
        _ => None,
    };
    for (left, right) in relationships.disjoint.iter().chain(&relationships.implies) {
        resolve_symbol(symbols, "symbol relationship", left)?;
        resolve_symbol(symbols, "symbol relationship", right)?;
    }
    let classifier_symbols = output.spec().classifier_bitset_symbols();
    let classifiers = classifier_symbols
        .iter()
        .map(|name| resolve_symbol(symbols, "classifier output", name))
        .collect::<Result<BTreeSet<_>>>()?;
    if classifiers.len() != classifier_symbols.len() {
        return plan_err!(
            "MATCH_RECOGNIZE classifier output contains a duplicate symbol"
        );
    }
    validate_match_output(output, symbols)?;
    Ok(target)
}

pub(crate) fn validate_match_output(
    output: &LogicalMatchOutput,
    symbols: &[String],
) -> Result<()> {
    let LogicalMatchOutput::SelectedSummaries {
        spec,
        input_spec,
        summaries,
    } = output
    else {
        return Ok(());
    };
    if input_spec.navigation_offsets() != spec.navigation_offsets() {
        return plan_err!(
            "MATCH_RECOGNIZE selected-match summary row selections must use the same navigation offsets"
        );
    }
    if input_spec
        .metadata_columns()
        .contains(&MatchMetadataColumn::PathId)
    {
        return plan_err!(
            "MATCH_RECOGNIZE selected-match summary input cannot select the internal path ID"
        );
    }
    let classifier_ids = input_spec
        .classifier_bitset_symbols()
        .iter()
        .map(|symbol| {
            resolve_symbol(symbols, "selected-match summary input classifier", symbol)
        })
        .collect::<Result<BTreeSet<_>>>()?;
    if classifier_ids.len() != input_spec.classifier_bitset_symbols().len() {
        return plan_err!(
            "MATCH_RECOGNIZE selected-match summary input classifier contract contains a duplicate symbol"
        );
    }
    let mut output_ids = BTreeSet::new();
    for summary in summaries {
        if !output_ids.insert(summary.field().output_id()) {
            return plan_err!(
                "MATCH_RECOGNIZE summary output ID {} is selected more than once",
                summary.field().output_id()
            );
        }
    }
    Ok(())
}

/// The lowered request consumed immediately when the logical node is built.
/// It is not stored in the finished plan or exposed outside this crate.
pub(crate) type LoweredMatchSpec = MatchRecognizeSpec<Expr>;

#[cfg(test)]
mod stateful_tests {
    use super::*;
    use datafusion::arrow::datatypes::{Field, Schema};
    use datafusion::functions_aggregate::{
        average::avg_udaf,
        bool_and_or::{bool_and_udaf, bool_or_udaf},
        count::count_udaf,
        first_last::{first_value_udaf, last_value_udaf},
        min_max::{max_udaf, min_udaf},
        stddev::{stddev_pop_udaf, stddev_udaf},
        sum::sum_udaf,
        variance::{var_pop_udaf, var_samp_udaf},
    };
    use datafusion::logical_expr::expr::AggregateFunctionParams;
    use datafusion::logical_expr::{Operator, binary_expr, col};
    use std::sync::Arc;

    fn test_schema() -> DFSchema {
        let ree = DataType::RunEndEncoded(
            Arc::new(Field::new("run_ends", DataType::Int32, false)),
            Arc::new(Field::new("values", DataType::Int64, true)),
        );
        DFSchema::try_from(Arc::new(Schema::new(vec![
            Field::new("i32_col", DataType::Int32, true),
            Field::new("i64_col", DataType::Int64, true),
            Field::new("u64_col", DataType::UInt64, true),
            Field::new("f64_col", DataType::Float64, true),
            Field::new("dec_col", DataType::Decimal128(10, 2), true),
            Field::new("str_col", DataType::Utf8, true),
            Field::new("bool_col", DataType::Boolean, true),
            Field::new("null_col", DataType::Null, true),
            Field::new("ree_col", ree.clone(), true),
            Field::new(
                "list_ree_col",
                DataType::List(Arc::new(Field::new("item", ree, true))),
                true,
            ),
            Field::new(
                "list_i64_col",
                DataType::List(Arc::new(Field::new("item", DataType::Int64, true))),
                true,
            ),
        ])))
        .unwrap()
    }

    fn plain_agg(
        udaf: Arc<datafusion::logical_expr::AggregateUDF>,
        args: Vec<Expr>,
    ) -> AggregateFunction {
        AggregateFunction::new_udf(udaf, args, false, None, vec![], None)
    }

    #[test]
    fn managed_aggregate_infallibility_admits_safe_builtins_and_rejects_fallible() {
        let schema = test_schema();
        let safe = |expr: &Expr| {
            crate::planning::expr_safety::can_discard_scalar(expr, Some(&schema))
        };

        for (label, agg) in [
            (
                "first_value",
                plain_agg(first_value_udaf(), vec![col("f64_col")]),
            ),
            (
                "last_value",
                plain_agg(last_value_udaf(), vec![col("dec_col")]),
            ),
            (
                "first_value(list<i64>)",
                plain_agg(first_value_udaf(), vec![col("list_i64_col")]),
            ),
            ("count(*)", plain_agg(count_udaf(), vec![lit(1_i64)])),
            ("count(col)", plain_agg(count_udaf(), vec![col("str_col")])),
            ("min(f64)", plain_agg(min_udaf(), vec![col("f64_col")])),
            ("max(str)", plain_agg(max_udaf(), vec![col("str_col")])),
            ("max(dec)", plain_agg(max_udaf(), vec![col("dec_col")])),
            ("sum(i64)", plain_agg(sum_udaf(), vec![col("i64_col")])),
            ("sum(u64)", plain_agg(sum_udaf(), vec![col("u64_col")])),
            ("sum(f64)", plain_agg(sum_udaf(), vec![col("f64_col")])),
            ("sum(dec)", plain_agg(sum_udaf(), vec![col("dec_col")])),
            ("avg(f64)", plain_agg(avg_udaf(), vec![col("f64_col")])),
            (
                "bool_and",
                plain_agg(bool_and_udaf(), vec![col("bool_col")]),
            ),
            ("bool_or", plain_agg(bool_or_udaf(), vec![col("bool_col")])),
            (
                "stddev(f64)",
                plain_agg(stddev_udaf(), vec![col("f64_col")]),
            ),
            (
                "stddev_pop(f64)",
                plain_agg(stddev_pop_udaf(), vec![col("f64_col")]),
            ),
            (
                "var_samp(f64)",
                plain_agg(var_samp_udaf(), vec![col("f64_col")]),
            ),
            (
                "var_pop(f64)",
                plain_agg(var_pop_udaf(), vec![col("f64_col")]),
            ),
        ] {
            assert!(
                managed_aggregate_is_infallible(&agg, &schema, &safe),
                "expected infallible: {label}"
            );
        }

        let distinct_count = AggregateFunction {
            func: count_udaf(),
            params: AggregateFunctionParams {
                args: vec![col("i64_col")],
                distinct: true,
                filter: None,
                order_by: vec![],
                null_treatment: None,
            },
        };
        let fallible_arg = plain_agg(
            sum_udaf(),
            vec![binary_expr(lit(1_i64), Operator::Divide, col("i64_col"))],
        );

        for (label, agg) in [
            (
                "uncoerced sum(i32)",
                plain_agg(sum_udaf(), vec![col("i32_col")]),
            ),
            (
                "uncoerced avg(i64)",
                plain_agg(avg_udaf(), vec![col("i64_col")]),
            ),
            (
                "uncoerced stddev(i64)",
                plain_agg(stddev_udaf(), vec![col("i64_col")]),
            ),
            (
                "uncoerced bool_and(null)",
                plain_agg(bool_and_udaf(), vec![col("null_col")]),
            ),
            (
                "first_value(ree)",
                plain_agg(first_value_udaf(), vec![col("ree_col")]),
            ),
            (
                "last_value(ree)",
                plain_agg(last_value_udaf(), vec![col("ree_col")]),
            ),
            (
                "first_value(list<ree>)",
                plain_agg(first_value_udaf(), vec![col("list_ree_col")]),
            ),
            ("min(null)", plain_agg(min_udaf(), vec![col("null_col")])),
            ("max(null)", plain_agg(max_udaf(), vec![col("null_col")])),
            ("avg(dec)", plain_agg(avg_udaf(), vec![col("dec_col")])),
            ("sum(str)", plain_agg(sum_udaf(), vec![col("str_col")])),
            ("avg(str)", plain_agg(avg_udaf(), vec![col("str_col")])),
            ("count(distinct)", distinct_count),
            ("sum(1/i64)", fallible_arg),
        ] {
            assert!(
                !managed_aggregate_is_infallible(&agg, &schema, &safe),
                "expected fallible/rejected: {label}"
            );
        }
    }
}