datafusion-match-recognize 0.55.0

SQL MATCH_RECOGNIZE row-pattern matching for Apache 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
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
// 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.

//! Imports a Substrait `MATCH_RECOGNIZE` relation into DataFusion planning.

use super::decode::*;
use super::schema::{output_type_matches, validate_output_schema};
use super::*;
use crate::core::{
    MatchMetadataColumn, MatchRecognizeOutputSpec, MatchSummaryField,
    classifier_bits_col_name, is_reserved_internal_column_name,
};
use crate::planning::can_have_nulls_outside_bitmap;
use crate::planning::logical::{LogicalMatchOutput, LogicalSelectedMatchSummary};
use datafusion::common::ScalarValue;
use datafusion::common::tree_node::{Transformed, TreeNode};
use datafusion::functions_aggregate::count::count_udaf;
use datafusion::logical_expr::{
    ExprSchemable, Projection, SortExpr, TableType, WindowFrameBound,
};
use datafusion_substrait::logical_plan::consumer::{
    DefaultSubstraitLambdaConsumer, from_scalar_function, from_substrait_func_args,
};
use std::collections::BTreeMap;
use std::ops::Range;

/// Converts a complete Substrait plan containing this package's
/// `MATCH_RECOGNIZE` extension relation into a DataFusion logical plan.
///
/// Ordinary relations are delegated to DataFusion's Substrait consumer. The
/// supplied session state resolves tables and registered functions while this
/// package decodes, validates, and plans matcher relations.
///
/// # Errors
///
/// Returns an error when extension declarations cannot be decoded, type
/// variation extensions are present, ordinary plan traversal cannot resolve an
/// input, or a matcher relation is malformed, unsupported, or cannot be
/// planned with `state`.
pub async fn from_substrait_plan_with_match_recognize(
    state: &SessionState,
    plan: &Plan,
) -> Result<LogicalPlan> {
    let extensions = Extensions::try_from(&plan.extensions)?;
    if !extensions.type_variations.is_empty() {
        return not_impl_err!("Type variation extensions are not supported");
    }

    let consumer = MatchRecognizeSubstraitConsumer::new(&extensions, state);
    from_substrait_plan_with_consumer(&consumer, plan).await
}

/// Substrait consumer that recognizes this package's extension relation and
/// delegates ordinary relations to DataFusion.
///
/// Most callers should use [`from_substrait_plan_with_match_recognize`]. This
/// type supports integrations that need to drive or customize the surrounding
/// Substrait traversal.
pub struct MatchRecognizeSubstraitConsumer<'a> {
    extensions: &'a Extensions,
    state: &'a SessionState,
    outer_schemas: RwLock<Vec<Arc<DFSchema>>>,
    lambda_consumer: DefaultSubstraitLambdaConsumer,
}

impl<'a> MatchRecognizeSubstraitConsumer<'a> {
    /// Create a consumer using the plan's decoded `extensions` and the
    /// registries and catalog in `state`.
    pub fn new(extensions: &'a Extensions, state: &'a SessionState) -> Self {
        Self {
            extensions,
            state,
            outer_schemas: RwLock::new(Vec::new()),
            lambda_consumer: DefaultSubstraitLambdaConsumer::new(),
        }
    }
}

#[async_trait]
impl SubstraitConsumer for MatchRecognizeSubstraitConsumer<'_> {
    async fn resolve_table_ref(
        &self,
        table_ref: &TableReference,
    ) -> Result<Option<Arc<dyn TableProvider>>> {
        let table = table_ref.table().to_string();
        let schema = self.state.schema_for_ref(table_ref.clone())?;
        let table_provider = schema.table(&table).await?;
        Ok(table_provider)
    }

    fn get_extensions(&self) -> &Extensions {
        self.extensions
    }

    fn get_function_registry(&self) -> &impl FunctionRegistry {
        self.state
    }

    fn push_outer_schema(&self, schema: Arc<DFSchema>) {
        self.outer_schemas.write().unwrap().push(schema);
    }

    fn pop_outer_schema(&self) {
        self.outer_schemas.write().unwrap().pop();
    }

    fn get_outer_schema(&self, steps_out: usize) -> Option<Arc<DFSchema>> {
        let schemas = self.outer_schemas.read().unwrap();
        schemas
            .len()
            .checked_sub(steps_out)
            .and_then(|idx| schemas.get(idx).cloned())
    }

    fn push_lambda_parameters(
        &self,
        parameters: &[proto::Type],
        input_schema: &DFSchema,
    ) -> Result<Vec<String>> {
        self.lambda_consumer
            .push_lambda_parameters(self, parameters, input_schema)
    }

    fn pop_lambda_parameters(&self) {
        self.lambda_consumer.pop_lambda_parameters();
    }

    fn lambda_variable(&self, steps_out: usize, field_idx: usize) -> Result<Expr> {
        self.lambda_consumer.lambda_variable(steps_out, field_idx)
    }

    async fn consume_scalar_function(
        &self,
        function: &proto::expression::ScalarFunction,
        input_schema: &DFSchema,
    ) -> Result<Expr> {
        if self
            .extensions
            .functions
            .get(&function.function_reference)
            .is_some_and(|name| name == BUILTIN_SUBSTRING_NAME)
        {
            if !matches!(function.arguments.len(), 2 | 3) {
                return plan_err!(
                    "MATCH_RECOGNIZE SUBSTRING expects two or three arguments"
                );
            }
            let args =
                from_substrait_func_args(self, &function.arguments, input_schema).await?;
            return Ok(datafusion::functions::unicode::substr().call(args));
        }
        from_scalar_function(self, function, input_schema).await
    }

    async fn consume_window_function(
        &self,
        expr: &proto::expression::WindowFunction,
        input_schema: &DFSchema,
    ) -> Result<Expr> {
        window::decode_window_function(self, expr, input_schema).await
    }

    async fn consume_extension_single(
        &self,
        rel: &ExtensionSingleRel,
    ) -> Result<LogicalPlan> {
        let detail = rel.detail.as_ref().ok_or_else(|| {
            datafusion::common::DataFusionError::Plan(
                "ExtensionSingleRel missing detail".to_string(),
            )
        })?;
        if detail.type_url != MATCH_RECOGNIZE_TYPE_URL {
            return plan_err!(
                "MATCH_RECOGNIZE Substrait adapter rejected unknown ExtensionSingleRel type URL '{}'",
                detail.type_url
            );
        }

        if matches!(
            rel.common
                .as_ref()
                .and_then(|common| common.emit_kind.as_ref()),
            Some(EmitKind::Emit(_))
        ) {
            return plan_err!(
                "MATCH_RECOGNIZE Substrait extension does not support ExtensionSingleRel.common.emit"
            );
        }

        let input_rel = rel.input.as_ref().ok_or_else(|| {
            datafusion::common::DataFusionError::Plan(
                "MATCH_RECOGNIZE ExtensionSingleRel missing input".to_string(),
            )
        })?;
        let input = self.consume_rel(input_rel).await?;
        let (payload, capabilities, boundary) = decode_match_recognize_payload(detail)?;
        let input = if boundary == MatchRecognizeBoundary::CompletePlan {
            input
        } else {
            sanitize_semantic_node_input(input)?
        };
        let decoded = decode_match_recognize_detail_from_payload(
            self,
            payload,
            capabilities,
            boundary,
            input.schema(),
        )
        .await?;

        let mut planning_context = SubstraitPlanningContext { state: self.state };
        validate_define_declaration(&mut planning_context, &input, &decoded)?;
        let boundary = decoded.boundary;
        let planned = match boundary {
            MatchRecognizeBoundary::CompletePlan => {
                plan_match_recognize_from_source_with_capabilities(
                    &mut planning_context,
                    input,
                    decoded.spec,
                    decoded.capabilities,
                )?
            }
            MatchRecognizeBoundary::RowStreamNode => {
                plan_match_recognize_node_from_source_with_capabilities(
                    &mut planning_context,
                    input,
                    decoded.spec,
                    decoded.capabilities,
                )?
            }
            MatchRecognizeBoundary::OneRowNode => {
                plan_match_recognize_native_one_row_node_from_source_with_capabilities(
                    &mut planning_context,
                    input,
                    decoded.spec,
                    decoded.capabilities,
                )?
            }
        };
        let expected = from_substrait_named_struct(self, &decoded.output_schema)?;
        let expected_types = decoded
            .output_schema
            .r#struct
            .as_ref()
            .ok_or_else(|| {
                datafusion::common::DataFusionError::Plan(
                    "MATCH_RECOGNIZE output schema missing struct".to_string(),
                )
            })?
            .types
            .as_slice();
        let planned = if boundary == MatchRecognizeBoundary::CompletePlan {
            planned
        } else {
            align_semantic_output(
                planned,
                &expected,
                expected_types,
                &decoded.retained_passthrough_input_fields,
                &decoded.prepared_output_fields,
                &decoded.summary_output_fields,
            )?
        };
        validate_output_schema(&planned, &expected, expected_types, boundary)?;
        Ok(planned)
    }

    async fn consume_extension_leaf(
        &self,
        rel: &ExtensionLeafRel,
    ) -> Result<LogicalPlan> {
        let Some(detail) = rel.detail.as_ref() else {
            return substrait_err!("Unexpected empty detail in ExtensionLeafRel");
        };
        plan_err!(
            "MATCH_RECOGNIZE Substrait adapter rejected unsupported ExtensionLeafRel type URL '{}'",
            detail.type_url
        )
    }

    async fn consume_extension_multi(
        &self,
        rel: &ExtensionMultiRel,
    ) -> Result<LogicalPlan> {
        let Some(detail) = rel.detail.as_ref() else {
            return substrait_err!("Unexpected empty detail in ExtensionMultiRel");
        };
        plan_err!(
            "MATCH_RECOGNIZE Substrait adapter rejected unsupported ExtensionMultiRel type URL '{}'",
            detail.type_url
        )
    }
}

struct PlannedSummary {
    exact: DecodedSummaryAggregate,
    folded: Option<DecodedSummaryAggregate>,
    is_builtin_count: bool,
    is_volatile: bool,
}

fn align_semantic_output(
    plan: LogicalPlan,
    expected: &DFSchema,
    expected_types: &[proto::Type],
    retained_input_fields: &[Column],
    prepared_output_fields: &[(usize, Expr)],
    summary_output_fields: &[(usize, DecodedSummaryAggregate)],
) -> Result<LogicalPlan> {
    let LogicalPlan::Extension(extension) = &plan else {
        return plan_err!(
            "MATCH_RECOGNIZE native semantic-node planning did not return an extension node"
        );
    };
    let Some(node) = extension.node.as_any().downcast_ref::<MatchRecognize>() else {
        return plan_err!(
            "MATCH_RECOGNIZE native semantic-node planning returned an unexpected extension node"
        );
    };
    let source_input = node
        .bound_source()
        .ok_or_else(|| {
            datafusion::common::DataFusionError::Plan(
                "MATCH_RECOGNIZE native semantic-node planning did not retain bound source"
                    .to_string(),
            )
        })?
        .input();
    let source_schema = source_input.schema();

    let full = node.program().output();
    let spec = full.spec();
    let passthrough = spec.passthrough_input_indices();
    let actual = node.schema();
    let metadata_start = passthrough.len();
    let classifier_start = metadata_start + spec.metadata_columns().len();
    let summary_start = classifier_start + spec.classifier_bitset_symbols().len();
    let ordinary_source_positions = passthrough
        .iter()
        .enumerate()
        .filter_map(|(position, &index)| {
            let (qualifier, field) = node.input().schema().qualified_field(index);
            source_schema
                .qualified_field_from_column(&Column::new(
                    qualifier.cloned(),
                    field.name(),
                ))
                .is_ok()
                .then_some(position)
        })
        .collect::<BTreeSet<_>>();
    let mut retained = Vec::with_capacity(expected.fields().len());
    let mut used = BTreeSet::new();
    for column in retained_input_fields {
        let input_index = node.input().schema().index_of_column(column)?;
        let positions = passthrough
            .iter()
            .enumerate()
            .filter(|(_, index)| **index == input_index)
            .map(|(position, _)| position)
            .collect::<Vec<_>>();
        let [position] = positions.as_slice() else {
            return plan_err!(
                "MATCH_RECOGNIZE retained input column '{}' does not identify one passthrough output",
                column
            );
        };
        used.insert(*position);
        retained.push(*position);
    }
    let mut prepared_windows = BTreeMap::new();
    for (position, &index) in passthrough.iter().enumerate() {
        if !ordinary_source_positions.contains(&position)
            && let Some(expression) =
                producer::prepared_window_expr(node, index, source_schema)?
        {
            prepared_windows
                .insert(position, normalize_wire_expr(expression, source_schema)?);
        }
    }
    let prepared_output_fields = prepared_output_fields
        .iter()
        .map(|(position, expression)| {
            Ok((
                *position,
                normalize_wire_expr(expression.clone(), source_schema)?,
            ))
        })
        .collect::<Result<BTreeMap<_, _>>>()?;
    let symbols = node
        .program()
        .symbols()
        .iter()
        .map(|symbol| symbol.name().to_string())
        .collect::<Vec<_>>();
    let builtin_count = count_udaf();
    let (planned_summaries, expected_summaries) = if !full
        .selected_match_summaries()
        .is_empty()
        || !summary_output_fields.is_empty()
    {
        let summary_schema = summary_wire_decode_schema(source_schema, &symbols)?;
        let planned_summaries = full
            .selected_match_summaries()
            .iter()
            .map(|summary| {
                let exact = planned_summary_identity(
                    summary,
                    node,
                    source_schema,
                    &summary_schema,
                )?;
                let is_builtin_count =
                    Arc::ptr_eq(summary.aggregate().func.inner(), builtin_count.inner());
                let folded = is_builtin_count
                    .then(|| {
                        folded_required_count_identity(&exact, source_input, &symbols)
                    })
                    .flatten();
                let is_volatile =
                    Expr::AggregateFunction(summary.aggregate().clone()).is_volatile();
                Ok(PlannedSummary {
                    exact,
                    folded,
                    is_builtin_count,
                    is_volatile,
                })
            })
            .collect::<Result<Vec<_>>>()?;
        let expected_summaries = summary_output_fields
            .iter()
            .map(|(position, summary)| {
                Ok((
                    *position,
                    normalize_decoded_summary(summary, &summary_schema)?,
                ))
            })
            .collect::<Result<BTreeMap<_, _>>>()?;
        (planned_summaries, expected_summaries)
    } else {
        (Vec::new(), BTreeMap::new())
    };
    let mut seen_non_volatile_summaries = Vec::new();
    for (output_index, expected_field) in
        expected.fields().iter().enumerate().skip(retained.len())
    {
        if let Some(expected_summary) = expected_summaries.get(&output_index) {
            let mut exact_matches = Vec::new();
            for (offset, planned) in planned_summaries.iter().enumerate() {
                let position = summary_start + offset;
                let field = actual.field(position);
                if !used.contains(&position)
                    && planned.exact == *expected_summary
                    && field.is_nullable() == expected_field.is_nullable()
                    && output_type_matches(
                        field.data_type(),
                        expected_field.data_type(),
                        &expected_types[output_index],
                    )?
                {
                    exact_matches.push(offset);
                }
            }
            if exact_matches.len() > 1 {
                let by_name = exact_matches
                    .iter()
                    .copied()
                    .filter(|&offset| {
                        actual.field(summary_start + offset).name()
                            == expected_field.name()
                    })
                    .collect::<Vec<_>>();
                exact_matches = if by_name.is_empty() {
                    vec![exact_matches[0]]
                } else {
                    by_name
                };
            }
            let (matched_offset, matched_exact) = match exact_matches.as_slice() {
                [offset] => (*offset, true),
                [] => {
                    if seen_non_volatile_summaries.contains(&expected_summary) {
                        return plan_err!(
                            "MATCH_RECOGNIZE native semantic-node generated output field '{}' does not identify one unambiguous retained field",
                            expected_field.name()
                        );
                    }
                    let expected_folded = folded_required_count_identity(
                        expected_summary,
                        source_input,
                        &symbols,
                    );
                    let mut folded_matches = Vec::new();
                    for (offset, planned) in planned_summaries.iter().enumerate() {
                        let position = summary_start + offset;
                        let field = actual.field(position);
                        if !planned.is_volatile
                            && planned.is_builtin_count
                            && field.is_nullable() == expected_field.is_nullable()
                            && output_type_matches(
                                field.data_type(),
                                expected_field.data_type(),
                                &expected_types[output_index],
                            )?
                            && (expected_folded.as_ref() == Some(&planned.exact)
                                || planned.folded.as_ref() == Some(expected_summary))
                        {
                            folded_matches.push(offset);
                        }
                    }
                    let Some(&offset) = folded_matches.first() else {
                        return plan_err!(
                            "MATCH_RECOGNIZE native semantic-node generated output field '{}' does not identify one unambiguous retained field",
                            expected_field.name()
                        );
                    };
                    (offset, false)
                }
                _ => {
                    return plan_err!(
                        "MATCH_RECOGNIZE native semantic-node generated output field '{}' does not identify one unambiguous retained field",
                        expected_field.name()
                    );
                }
            };
            let position = summary_start + matched_offset;
            if matched_exact {
                used.insert(position);
            }
            if !planned_summaries[matched_offset].is_volatile
                && !seen_non_volatile_summaries.contains(&expected_summary)
            {
                seen_non_volatile_summaries.push(expected_summary);
            }
            retained.push(position);
            continue;
        }
        // Prepared placeholders and LAG/LEAD outputs are not source ordinals.
        // Window display names change with consumed aliases, so match the full
        // defining expression. Other generated non-summary outputs retain unique names.
        let prepared = prepared_output_fields.get(&output_index);
        let mut positions = Vec::new();
        for (position, field) in actual.fields().iter().enumerate().take(summary_start) {
            if !ordinary_source_positions.contains(&position)
                && !used.contains(&position)
                && match prepared {
                    Some(expression) => {
                        prepared_windows.get(&position) == Some(expression)
                    }
                    None => {
                        !prepared_windows.contains_key(&position)
                            && field.name() == expected_field.name()
                    }
                }
                && field.is_nullable() == expected_field.is_nullable()
                && output_type_matches(
                    field.data_type(),
                    expected_field.data_type(),
                    &expected_types[output_index],
                )?
            {
                positions.push(position);
            }
        }
        if positions.len() > 1
            && let Some(expression) = prepared
        {
            if expression.is_volatile() {
                // Equal volatile windows have separate, source-ordered aliases.
                positions.retain(|&position| {
                    actual.field(position).name() == expected_field.name()
                });
            } else {
                // Distinct non-volatile ASTs that normalize to the same wire
                // expression are semantically equivalent; prefer an exact alias
                // match and otherwise consume the first unused slot.
                let by_name = positions
                    .iter()
                    .copied()
                    .filter(|&position| {
                        actual.field(position).name() == expected_field.name()
                    })
                    .collect::<Vec<_>>();
                positions = if by_name.is_empty() {
                    vec![positions[0]]
                } else {
                    by_name
                };
            }
        }
        let [position] = positions.as_slice() else {
            return plan_err!(
                "MATCH_RECOGNIZE native semantic-node generated output field '{}' does not identify one unambiguous retained field",
                expected_field.name()
            );
        };
        used.insert(*position);
        retained.push(*position);
    }

    let mut selected_passthrough = Vec::new();
    let mut selected_metadata = Vec::new();
    let mut selected_classifiers = Vec::new();
    let mut selected_summaries = Vec::new();
    let mut previous_group = 0;
    for index in retained {
        let group = if index < metadata_start {
            selected_passthrough.push(passthrough[index]);
            0
        } else if index < classifier_start {
            selected_metadata.push(spec.metadata_columns()[index - metadata_start]);
            1
        } else if index < summary_start {
            selected_classifiers
                .push(spec.classifier_bitset_symbols()[index - classifier_start].clone());
            2
        } else {
            let summary = &full.selected_match_summaries()[index - summary_start];
            let field = MatchSummaryField::new(
                selected_summaries.len(),
                summary.field().arrow_field(),
            );
            selected_summaries.push(LogicalSelectedMatchSummary::new(
                field,
                summary.aggregate().clone(),
            ));
            3
        };
        if group < previous_group {
            return plan_err!(
                "MATCH_RECOGNIZE native semantic-node output fields are not in matcher output order"
            );
        }
        previous_group = group;
    }
    let selected_spec = MatchRecognizeOutputSpec::with_validated_navigation_offsets(
        selected_passthrough,
        selected_metadata,
        selected_classifiers,
        spec.navigation_offsets(),
    );
    let output = match full {
        LogicalMatchOutput::SelectedSummaries { input_spec, .. } => {
            LogicalMatchOutput::selected_summaries(
                selected_spec,
                input_spec.clone(),
                selected_summaries,
            )
        }
        LogicalMatchOutput::Rows { rows_per_match, .. } => {
            LogicalMatchOutput::rows(rows_per_match.clone(), selected_spec)
        }
    };
    let aligned = node.rebuild_with_output(output)?;
    if let Some(grouped) = aligned.grouped_output_plan()? {
        return Ok(grouped);
    }
    Ok(LogicalPlan::Extension(Extension {
        node: Arc::new(aligned),
    }))
}

struct SubstraitPlanningContext<'a> {
    state: &'a SessionState,
}

impl MatchRecognizePlanningContext for SubstraitPlanningContext<'_> {
    fn options(&self) -> &datafusion::common::config::ConfigOptions {
        self.state.config_options()
    }

    fn scalar_udf(&self, name: &str) -> Option<Arc<ScalarUDF>> {
        self.state.udf(name).ok()
    }

    fn aggregate_udf(&self, name: &str) -> Option<Arc<AggregateUDF>> {
        self.state
            .udaf(name)
            .ok()
            .or_else(|| self.options().aggregate_udf(name))
    }
}

/// Output contract represented by one decoded `MATCH_RECOGNIZE` relation.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum MatchRecognizeBoundary {
    /// Complete output plan, including its projections or final aggregation.
    CompletePlan,
    /// Semantic matcher node that emits rows for downstream output operators.
    RowStreamNode,
    /// Semantic matcher node that finalizes one row per selected match.
    OneRowNode,
}

/// Decoded identity for one retained selected-match summary output.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DecodedSummaryAggregate {
    /// Registered DataFusion aggregate function name.
    pub function_name: String,
    /// Aggregate arguments decoded against `[source_input, public_metadata, pattern_classifiers]`.
    pub args: Vec<Expr>,
    /// Whether the aggregate uses `DISTINCT`.
    pub distinct: bool,
    /// Optional aggregate `FILTER` predicate.
    pub filter: Option<Expr>,
    /// Aggregate `ORDER BY` expressions.
    pub order_by: Vec<SortExpr>,
    /// Optional aggregate null treatment.
    pub null_treatment: Option<expr::NullTreatment>,
}

/// Validated source request decoded from one extension detail message.
#[derive(Clone, Debug)]
pub struct DecodedMatchRecognizeDetail {
    /// Bound source request encoded by the payload.
    pub spec: BoundMatchSpec,
    /// Planning capabilities declared by the payload's required features.
    pub capabilities: MatchRecognizePlanningCapabilities,
    /// Whether the payload declares match-aware DEFINE requirements.
    ///
    /// This is wire metadata, not proof that executable admission has succeeded.
    pub declares_match_aware_defines: bool,
    /// Exact output schema declared at the extension boundary.
    pub output_schema: NamedStruct,
    /// Checked output contract of the decoded extension relation.
    pub boundary: MatchRecognizeBoundary,
    /// Ordinary-source passthrough outputs in payload order, resolved against
    /// the consumed input. Required positional identity accompanies both
    /// row-stream and selected-summary semantic boundaries.
    pub retained_passthrough_input_fields: Vec<Column>,
    /// Prepared window outputs identified by absolute output position and the
    /// complete defining expression decoded against the consumed source input.
    pub prepared_output_fields: Vec<(usize, Expr)>,
    /// Selected-match summary outputs identified by absolute output position
    /// and canonical aggregate identity decoded against the consumed source
    /// input, public metadata, and pattern classifiers.
    pub summary_output_fields: Vec<(usize, DecodedSummaryAggregate)>,
}

/// Decodes and validates one `MATCH_RECOGNIZE` Protobuf detail message against
/// its input schema.
///
/// # Errors
///
/// Returns an error when the type URL is not [`MATCH_RECOGNIZE_TYPE_URL`], the
/// Protobuf message is malformed, its schema version or required features are
/// unsupported, an expression cannot be decoded against `input_schema`, or the
/// resulting source specification is invalid.
pub async fn decode_match_recognize_detail(
    consumer: &impl SubstraitConsumer,
    detail: &Any,
    input_schema: &DFSchema,
) -> Result<DecodedMatchRecognizeDetail> {
    let (payload, capabilities, boundary) = decode_match_recognize_payload(detail)?;
    decode_match_recognize_detail_from_payload(
        consumer,
        payload,
        capabilities,
        boundary,
        input_schema,
    )
    .await
}

fn decode_match_recognize_payload(
    detail: &Any,
) -> Result<(
    payload::MatchRecognizeRel,
    MatchRecognizePlanningCapabilities,
    MatchRecognizeBoundary,
)> {
    if detail.type_url != MATCH_RECOGNIZE_TYPE_URL {
        return plan_err!(
            "unknown MATCH_RECOGNIZE detail type URL: {}",
            detail.type_url
        );
    }

    let payload = wire::decode_detail(detail.value.as_ref())?;
    validate_schema_version(payload.schema_version)?;
    let capabilities = decode_capabilities(&payload.required_features)?;
    let boundary = decode_boundary(&payload)?;
    Ok((payload, capabilities, boundary))
}

/// Re-alias positional semantic-node input fields whose names or qualifiers lost
/// SQL aliases across upstream Substrait relations.
///
/// Substrait `ProjectRel` strips column aliases and drops `SubqueryAlias` table
/// qualifiers. A valid SQL query — such as chained `MATCH_RECOGNIZE` nodes where
/// an inner semantic node exposes `__mr_*` outputs or a projection aliasing a
/// `__mr_*` base column — can therefore arrive at an outer semantic node with
/// reserved `__mr_*` field names or qualifiers. Because semantic-node inputs and
/// outputs are strictly positional, introducing fresh unqualified names for only
/// those offending columns preserves exact field ordinals, types, nullability,
/// and metadata without weakening SQL validation.
fn sanitize_semantic_node_input(input: LogicalPlan) -> Result<LogicalPlan> {
    let needs_sanitizing = input
        .schema()
        .iter()
        .any(|(qualifier, field)| field_needs_sanitizing(qualifier, field));
    if !needs_sanitizing {
        return Ok(input);
    }

    let mut used_names = input
        .schema()
        .fields()
        .iter()
        .map(|field| field.name().to_ascii_lowercase())
        .collect::<BTreeSet<_>>();
    let mut exprs = Vec::with_capacity(input.schema().fields().len());
    for (index, (qualifier, field)) in input.schema().iter().enumerate() {
        let column = Expr::Column(Column::new(qualifier.cloned(), field.name()));
        if field_needs_sanitizing(qualifier, field) {
            let mut candidate = format!("substrait_input_{index}");
            let mut suffix = 0usize;
            while !used_names.insert(candidate.to_ascii_lowercase()) {
                candidate = format!("substrait_input_{index}_{suffix}");
                suffix += 1;
            }
            exprs.push(column.alias(candidate));
        } else {
            exprs.push(column);
        }
    }

    Ok(LogicalPlan::Projection(Projection::try_new(
        exprs,
        Arc::new(input),
    )?))
}

fn field_needs_sanitizing(qualifier: Option<&TableReference>, field: &Field) -> bool {
    is_reserved_internal_column_name(field.name())
        || qualifier.is_some_and(has_reserved_relation)
}

fn has_reserved_relation(relation: &TableReference) -> bool {
    [
        relation.catalog(),
        relation.schema(),
        Some(relation.table()),
    ]
    .into_iter()
    .flatten()
    .any(is_reserved_internal_column_name)
}

async fn decode_match_recognize_detail_from_payload(
    consumer: &impl SubstraitConsumer,
    payload: payload::MatchRecognizeRel,
    capabilities: MatchRecognizePlanningCapabilities,
    boundary: MatchRecognizeBoundary,
    input_schema: &DFSchema,
) -> Result<DecodedMatchRecognizeDetail> {
    if boundary != MatchRecognizeBoundary::CompletePlan
        && !payload
            .required_features
            .iter()
            .any(|feature| feature == DATAFUSION_WINDOW_MODIFIERS_FEATURE)
    {
        return plan_err!(
            "semantic MATCH_RECOGNIZE Substrait payload missing required feature {}",
            DATAFUSION_WINDOW_MODIFIERS_FEATURE
        );
    }
    let declares_match_aware_defines = payload
        .required_features
        .iter()
        .any(|feature| feature == MATCH_RECOGNIZE_MATCH_AWARE_DEFINES_FEATURE);
    let mut seen = BTreeSet::new();
    let retained_passthrough_input_fields = payload
        .retained_passthrough_input_fields
        .iter()
        .map(|&index| {
            if !seen.insert(index) {
                return plan_err!(
                    "MATCH_RECOGNIZE retained_passthrough_input_fields contains duplicate input_field {}",
                    index
                );
            }
            decode_input_field(input_schema, index)
        })
        .collect::<Result<Vec<_>>>()?;
    let output_schema = payload.output_schema.ok_or_else(|| {
        datafusion::common::DataFusionError::Plan(
            "MATCH_RECOGNIZE Substrait payload missing output_schema".to_string(),
        )
    })?;
    let output_count = output_schema
        .r#struct
        .as_ref()
        .map_or(0, |schema| schema.types.len());
    let retained_prefix_len = retained_passthrough_input_fields.len();
    if retained_prefix_len > output_count {
        return plan_err!(
            "MATCH_RECOGNIZE retained_passthrough_input_fields exceeds the output field count"
        );
    }
    let prepared_output_fields = decode_prepared_output_fields(
        consumer,
        input_schema,
        output_count,
        retained_prefix_len,
        &payload.prepared_output_fields,
    )
    .await?;
    let pattern = decode_pattern(payload.pattern)?;
    if has_reluctant_quantifier(&pattern)
        && !payload
            .required_features
            .iter()
            .any(|feature| feature == MATCH_RECOGNIZE_RELUCTANT_QUANTIFIERS_FEATURE)
    {
        return plan_err!(
            "MATCH_RECOGNIZE Substrait reluctant quantifier requires feature {}",
            MATCH_RECOGNIZE_RELUCTANT_QUANTIFIERS_FEATURE
        );
    }

    let pattern_symbols = payload
        .symbols
        .iter()
        .map(|symbol| symbol.to_ascii_lowercase())
        .collect::<BTreeSet<_>>();
    let spec = MatchRecognizeSpec {
        partition_by: decode_exprs(
            consumer,
            input_schema,
            &pattern_symbols,
            payload.partition_expressions,
        )
        .await?,
        order_by: decode_source_sorts(
            consumer,
            input_schema,
            &pattern_symbols,
            payload.sorts,
        )
        .await?,
        source_rows_per_match: decode_rows_per_match(payload.rows_per_match)?,
        after_match_skip: decode_after_match_skip(payload.after_match_skip)?,
        pattern,
        symbols: payload.symbols,
        definitions: decode_definitions(
            consumer,
            input_schema,
            &pattern_symbols,
            payload.definitions,
        )
        .await?,
        measures: decode_measures(
            consumer,
            input_schema,
            &pattern_symbols,
            payload.measures,
        )
        .await?,
        output: decode_output_contract(
            consumer,
            input_schema,
            &pattern_symbols,
            payload.output_contract,
        )
        .await?,
    }
    .try_new()
    .map_err(|err| datafusion::common::DataFusionError::Plan(err.to_string()))?;
    let expr_features = spec_expr_features(&spec)?;
    if expr_features.has_logical_offset
        && !payload
            .required_features
            .iter()
            .any(|feature| feature == MATCH_RECOGNIZE_LOGICAL_NAVIGATION_OFFSET_FEATURE)
    {
        return plan_err!(
            "MATCH_RECOGNIZE Substrait logical navigation offset requires feature {}",
            MATCH_RECOGNIZE_LOGICAL_NAVIGATION_OFFSET_FEATURE
        );
    }
    if expr_features.has_compound_navigation
        && !payload
            .required_features
            .iter()
            .any(|feature| feature == MATCH_RECOGNIZE_COMPOUND_NAVIGATION_FEATURE)
    {
        return plan_err!(
            "MATCH_RECOGNIZE Substrait compound navigation requires feature {}",
            MATCH_RECOGNIZE_COMPOUND_NAVIGATION_FEATURE
        );
    }
    if expr_features.has_distinct_from
        && !payload
            .required_features
            .iter()
            .any(|feature| feature == MATCH_RECOGNIZE_DISTINCT_FROM_FEATURE)
    {
        return plan_err!(
            "MATCH_RECOGNIZE Substrait IS [NOT] DISTINCT FROM requires feature {}",
            MATCH_RECOGNIZE_DISTINCT_FROM_FEATURE
        );
    }
    let summary_output_fields = decode_summary_output_fields(
        consumer,
        input_schema,
        &spec.symbols,
        retained_prefix_len..output_count,
        &prepared_output_fields,
        &payload.summary_output_fields,
    )
    .await?;

    Ok(DecodedMatchRecognizeDetail {
        spec,
        capabilities,
        declares_match_aware_defines,
        output_schema,
        boundary,
        retained_passthrough_input_fields,
        prepared_output_fields,
        summary_output_fields,
    })
}

/// Check the wire declaration against the normalized DEFINE requirements before executable import.
fn validate_define_declaration(
    context: &mut impl MatchRecognizePlanningContext,
    input: &LogicalPlan,
    decoded: &DecodedMatchRecognizeDetail,
) -> Result<()> {
    let requirements = analyze_match_recognize_requirements(
        context,
        input,
        &decoded.spec,
        decoded.capabilities,
    )?;
    if requirements.requires_match_aware_defines()
        && !decoded.declares_match_aware_defines
    {
        return plan_err!(
            "MATCH_RECOGNIZE Substrait payload with match-aware DEFINEs is missing required feature {}",
            MATCH_RECOGNIZE_MATCH_AWARE_DEFINES_FEATURE
        );
    }
    Ok(())
}

async fn decode_prepared_output_fields(
    consumer: &impl SubstraitConsumer,
    input_schema: &DFSchema,
    output_count: usize,
    retained_prefix_len: usize,
    fields: &[payload::PreparedOutputField],
) -> Result<Vec<(usize, Expr)>> {
    let mut seen = BTreeSet::new();
    let mut decoded = Vec::with_capacity(fields.len());
    for field in fields {
        let index = usize::try_from(field.output_field).map_err(|_| {
            datafusion::common::DataFusionError::Plan(
                "MATCH_RECOGNIZE prepared output_field exceeds the addressable output"
                    .into(),
            )
        })?;
        if index >= output_count {
            return plan_err!(
                "MATCH_RECOGNIZE prepared output_field {} is out of bounds for {} output fields",
                index,
                output_count
            );
        }
        if index < retained_prefix_len {
            return plan_err!(
                "MATCH_RECOGNIZE prepared output_field {} overlaps the ordinary-source output prefix",
                index
            );
        }
        if !seen.insert(index) {
            return plan_err!(
                "MATCH_RECOGNIZE prepared_output_fields contains duplicate output_field {}",
                index
            );
        }
        let expression = field.expression.as_ref().ok_or_else(|| {
            datafusion::common::DataFusionError::Plan(
                "MATCH_RECOGNIZE prepared output_field is missing expression".into(),
            )
        })?;
        let expression = consumer
            .consume_expression(expression, input_schema)
            .await?;
        if !matches!(expression, Expr::WindowFunction(_)) {
            return plan_err!(
                "MATCH_RECOGNIZE prepared output_field expression must be a window expression"
            );
        }
        decoded.push((index, expression));
    }
    Ok(decoded)
}

async fn decode_summary_output_fields(
    consumer: &impl SubstraitConsumer,
    input_schema: &DFSchema,
    symbols: &[String],
    valid_outputs: Range<usize>,
    prepared_output_fields: &[(usize, Expr)],
    fields: &[payload::SummaryOutputField],
) -> Result<Vec<(usize, DecodedSummaryAggregate)>> {
    if fields.is_empty() {
        return Ok(Vec::new());
    }
    let summary_schema = summary_wire_decode_schema(input_schema, symbols)?;
    let prepared_positions = prepared_output_fields
        .iter()
        .map(|(index, _)| *index)
        .collect::<BTreeSet<_>>();
    let mut seen = BTreeSet::new();
    let mut decoded = Vec::with_capacity(fields.len());
    for field in fields {
        let index = usize::try_from(field.output_field).map_err(|_| {
            datafusion::common::DataFusionError::Plan(
                "MATCH_RECOGNIZE summary output_field exceeds the addressable output"
                    .into(),
            )
        })?;
        if index >= valid_outputs.end {
            return plan_err!(
                "MATCH_RECOGNIZE summary output_field {} is out of bounds for {} output fields",
                index,
                valid_outputs.end
            );
        }
        if index < valid_outputs.start {
            return plan_err!(
                "MATCH_RECOGNIZE summary output_field {} overlaps the ordinary-source output prefix",
                index
            );
        }
        if prepared_positions.contains(&index) {
            return plan_err!(
                "MATCH_RECOGNIZE summary output_field {} overlaps prepared_output_fields",
                index
            );
        }
        if !seen.insert(index) {
            return plan_err!(
                "MATCH_RECOGNIZE summary_output_fields contains duplicate output_field {}",
                index
            );
        }
        if field.function_name.trim().is_empty() {
            return plan_err!(
                "MATCH_RECOGNIZE summary output_field {} is missing function_name",
                index
            );
        }
        let mut args = Vec::with_capacity(field.args.len());
        for arg in &field.args {
            args.push(consumer.consume_expression(arg, &summary_schema).await?);
        }
        let filter = match &field.filter {
            Some(filter) => {
                Some(consumer.consume_expression(filter, &summary_schema).await?)
            }
            None => None,
        };
        let mut order_by = Vec::with_capacity(field.order_by.len());
        for sort in &field.order_by {
            let expr = sort.expr.as_ref().ok_or_else(|| {
                datafusion::common::DataFusionError::Plan(
                    "MATCH_RECOGNIZE summary ORDER BY sort expression missing expr"
                        .into(),
                )
            })?;
            let expr = consumer.consume_expression(expr, &summary_schema).await?;
            let asc = matches!(
                decode_sort_direction(sort.direction, "summary ORDER BY")?,
                MatchRecognizeSortDirection::Asc
            );
            let nulls_first = matches!(
                decode_null_ordering(sort.null_ordering, "summary ORDER BY")?,
                MatchRecognizeNullOrdering::First
            );
            order_by.push(SortExpr::new(expr, asc, nulls_first));
        }
        let null_treatment = decode_null_treatment(field.null_treatment)?;
        decoded.push((
            index,
            DecodedSummaryAggregate {
                function_name: field.function_name.clone(),
                args,
                distinct: field.distinct,
                filter,
                order_by,
                null_treatment,
            },
        ));
    }
    Ok(decoded)
}

fn summary_wire_decode_schema(
    input_schema: &DFSchema,
    symbols: &[String],
) -> Result<DFSchemaRef> {
    let input_schema_ref = Arc::new(input_schema.clone());
    MatchRecognizeOutputSpec::full_from(&input_schema_ref, symbols)
        .build_df_schema(input_schema)
}

fn normalize_decoded_summary(
    summary: &DecodedSummaryAggregate,
    summary_schema: &DFSchema,
) -> Result<DecodedSummaryAggregate> {
    let normalize = |expr: &Expr| normalize_wire_expr(expr.clone(), summary_schema);
    Ok(DecodedSummaryAggregate {
        function_name: summary.function_name.clone(),
        args: summary
            .args
            .iter()
            .map(normalize)
            .collect::<Result<Vec<_>>>()?,
        distinct: summary.distinct,
        filter: summary.filter.as_ref().map(normalize).transpose()?,
        order_by: summary
            .order_by
            .iter()
            .map(|sort| {
                Ok(SortExpr::new(
                    normalize(&sort.expr)?,
                    sort.asc,
                    sort.nulls_first,
                ))
            })
            .collect::<Result<Vec<_>>>()?,
        null_treatment: summary.null_treatment,
    })
}

fn planned_summary_identity(
    summary: &LogicalSelectedMatchSummary,
    node: &MatchRecognize,
    source_schema: &DFSchema,
    summary_schema: &DFSchema,
) -> Result<DecodedSummaryAggregate> {
    let normalize = |expr: &Expr| -> Result<Expr> {
        let expanded =
            producer::expand_prepared_source_exprs(expr.clone(), node, source_schema)?;
        normalize_wire_expr(expanded, summary_schema)
    };
    let aggregate = summary.aggregate();
    let params = &aggregate.params;
    Ok(DecodedSummaryAggregate {
        function_name: aggregate.func.name().to_string(),
        args: params
            .args
            .iter()
            .map(normalize)
            .collect::<Result<Vec<_>>>()?,
        distinct: params.distinct,
        filter: params.filter.as_deref().map(normalize).transpose()?,
        order_by: params
            .order_by
            .iter()
            .map(|sort| {
                Ok(SortExpr::new(
                    normalize(&sort.expr)?,
                    sort.asc,
                    sort.nulls_first,
                ))
            })
            .collect::<Result<Vec<_>>>()?,
        null_treatment: params.null_treatment,
    })
}

fn typed_null_identity(data_type: &DataType) -> Result<Expr> {
    let wire_type = schema::bare_decoded_type(data_type);
    match ScalarValue::try_from(&wire_type)? {
        ScalarValue::Date64(value) => Ok(Expr::Cast(expr::Cast::new(
            Box::new(Expr::Literal(ScalarValue::Int64(value), None)),
            DataType::Date64,
        ))),
        value => Ok(Expr::Literal(value, None)),
    }
}

fn normalize_wire_scalar(value: &ScalarValue) -> Result<Option<ScalarValue>> {
    use datafusion::arrow::array::{Array, AsArray, MapArray, new_empty_array};
    use datafusion::arrow::buffer::OffsetBuffer;
    use datafusion::common::scalar::ScalarStructBuilder;

    match value {
        v if v.is_null() && !v.data_type().is_null() => {
            let dt = v.data_type();
            let bare = schema::bare_decoded_type(&dt);
            if bare != dt {
                Ok(Some(ScalarValue::try_from(&bare)?))
            } else {
                Ok(None)
            }
        }
        ScalarValue::TimestampSecond(v, Some(tz)) if tz.as_ref() != "UTC" => {
            Ok(Some(ScalarValue::TimestampSecond(*v, Some("UTC".into()))))
        }
        ScalarValue::TimestampMillisecond(v, Some(tz)) if tz.as_ref() != "UTC" => Ok(
            Some(ScalarValue::TimestampMillisecond(*v, Some("UTC".into()))),
        ),
        ScalarValue::TimestampMicrosecond(v, Some(tz)) if tz.as_ref() != "UTC" => Ok(
            Some(ScalarValue::TimestampMicrosecond(*v, Some("UTC".into()))),
        ),
        ScalarValue::TimestampNanosecond(v, Some(tz)) if tz.as_ref() != "UTC" => Ok(
            Some(ScalarValue::TimestampNanosecond(*v, Some("UTC".into()))),
        ),
        ScalarValue::Struct(s) => {
            let mut builder = ScalarStructBuilder::new();
            for (index, col) in s.columns().iter().enumerate() {
                let child = ScalarValue::try_from_array(col.as_ref(), 0)?;
                let child = normalize_wire_scalar(&child)?.unwrap_or(child);
                builder = builder.with_scalar(
                    Field::new(format!("c{index}"), child.data_type(), true),
                    child,
                );
            }
            let normalized = builder.build()?;
            Ok((normalized != *value).then_some(normalized))
        }
        ScalarValue::List(l) => {
            let DataType::List(item_field) = l.data_type() else {
                return Ok(None);
            };
            let values = l.value(0);
            let normalized = if values.is_empty() {
                let elem_type = schema::bare_decoded_type(item_field.data_type());
                ScalarValue::List(ScalarValue::new_list_nullable(&[], &elem_type))
            } else {
                let mut elements = Vec::with_capacity(values.len());
                for i in 0..values.len() {
                    let elem = ScalarValue::try_from_array(values.as_ref(), i)?;
                    elements.push(normalize_wire_scalar(&elem)?.unwrap_or(elem));
                }
                let elem_type = elements[0].data_type();
                ScalarValue::List(ScalarValue::new_list_nullable(&elements, &elem_type))
            };
            Ok((normalized != *value).then_some(normalized))
        }
        ScalarValue::LargeList(l) => {
            let DataType::LargeList(item_field) = l.data_type() else {
                return Ok(None);
            };
            let values = l.value(0);
            let normalized = if values.is_empty() {
                let elem_type = schema::bare_decoded_type(item_field.data_type());
                ScalarValue::LargeList(ScalarValue::new_large_list(&[], &elem_type))
            } else {
                let mut elements = Vec::with_capacity(values.len());
                for i in 0..values.len() {
                    let elem = ScalarValue::try_from_array(values.as_ref(), i)?;
                    elements.push(normalize_wire_scalar(&elem)?.unwrap_or(elem));
                }
                let elem_type = elements[0].data_type();
                ScalarValue::LargeList(ScalarValue::new_large_list(&elements, &elem_type))
            };
            Ok((normalized != *value).then_some(normalized))
        }
        ScalarValue::Map(m) => {
            let DataType::Map(entries_field, _) = m.data_type() else {
                return Ok(None);
            };
            let DataType::Struct(kv_fields) = entries_field.data_type() else {
                return Ok(None);
            };
            if kv_fields.len() != 2 {
                return Ok(None);
            }
            let entries = m.value(0);
            let normalized = if entries.is_empty() {
                let key_field = Field::new(
                    "key",
                    schema::bare_decoded_type(kv_fields[0].data_type()),
                    false,
                );
                let value_field = Field::new(
                    "value",
                    schema::bare_decoded_type(kv_fields[1].data_type()),
                    kv_fields[1].is_nullable(),
                );
                let entries_type =
                    Field::new_struct("entries", vec![key_field, value_field], false);
                let struct_array = new_empty_array(entries_type.data_type())
                    .as_struct()
                    .to_owned();
                ScalarValue::Map(Arc::new(MapArray::new(
                    Arc::new(entries_type),
                    OffsetBuffer::new(vec![0, 0].into()),
                    struct_array,
                    None,
                    false,
                )))
            } else {
                let mut rows = Vec::with_capacity(entries.len());
                for i in 0..entries.len() {
                    let key_sv =
                        ScalarValue::try_from_array(entries.column(0).as_ref(), i)?;
                    let key_sv = normalize_wire_scalar(&key_sv)?.unwrap_or(key_sv);
                    let val_sv =
                        ScalarValue::try_from_array(entries.column(1).as_ref(), i)?;
                    let val_sv = normalize_wire_scalar(&val_sv)?.unwrap_or(val_sv);
                    rows.push(
                        ScalarStructBuilder::new()
                            .with_scalar(
                                Field::new("key", key_sv.data_type(), false),
                                key_sv,
                            )
                            .with_scalar(
                                Field::new("value", val_sv.data_type(), true),
                                val_sv,
                            )
                            .build()?,
                    );
                }
                ScalarValue::Map(Arc::new(MapArray::new(
                    Arc::new(Field::new("entries", rows[0].data_type(), false)),
                    OffsetBuffer::new(vec![0, rows.len() as i32].into()),
                    ScalarValue::iter_to_array(rows)?.as_struct().to_owned(),
                    None,
                    false,
                )))
            };
            Ok((normalized != *value).then_some(normalized))
        }
        _ => Ok(None),
    }
}

fn normalize_wire_literal(value: &ScalarValue) -> Result<Option<Expr>> {
    match value {
        ScalarValue::Date64(v) => Ok(Some(Expr::Cast(expr::Cast::new(
            Box::new(Expr::Literal(ScalarValue::Int64(*v), None)),
            DataType::Date64,
        )))),
        other => Ok(normalize_wire_scalar(other)?.map(|v| Expr::Literal(v, None))),
    }
}

fn is_date64_millis_cast(expr: &Expr) -> bool {
    matches!(
        expr,
        Expr::Cast(cast)
            if matches!(cast.expr.as_ref(), Expr::Literal(ScalarValue::Int64(_), _))
                && cast.field.as_ref() == &Field::new("", DataType::Date64, true)
    )
}

fn is_wire_rewritten_inert_when(expr: &Expr) -> bool {
    matches!(expr, Expr::Literal(value, _) if value.is_null())
        || is_date64_millis_cast(expr)
}

fn strip_wire_ambiguous_null_base_guard(
    mut case: expr::Case,
    schema: &DFSchema,
) -> Result<(expr::Case, bool)> {
    if case.expr.is_some() || case.when_then_expr.len() < 2 {
        return Ok((case, false));
    }
    let (Expr::IsNull(base), guard_then) = (
        case.when_then_expr[0].0.as_ref(),
        case.when_then_expr[0].1.as_ref(),
    ) else {
        return Ok((case, false));
    };
    if base.is_volatile() || !base.nullable(schema)? {
        return Ok((case, false));
    }
    let expected_guard_then = match &case.else_expr {
        Some(else_expr) => else_expr.as_ref().clone(),
        None => {
            let result_type = case.when_then_expr[1].1.get_type(schema)?;
            typed_null_identity(&result_type)?
        }
    };
    if guard_then != &expected_guard_then {
        return Ok((case, false));
    }
    let mut has_wire_rewritten = false;
    for (when, _) in &case.when_then_expr[1..] {
        let Expr::BinaryExpr(binary) = when.as_ref() else {
            return Ok((case, false));
        };
        if binary.op != Operator::Eq || binary.left.as_ref() != base.as_ref() {
            return Ok((case, false));
        }
        let right = binary.right.as_ref();
        if is_wire_rewritten_inert_when(right) {
            has_wire_rewritten = true;
        } else if !matches!(right, Expr::Literal(..) | Expr::Column(_)) {
            return Ok((case, false));
        }
    }
    if !has_wire_rewritten {
        return Ok((case, false));
    }
    case.when_then_expr.remove(0);
    Ok((case, true))
}

pub(crate) fn normalize_wire_expr(expression: Expr, schema: &DFSchema) -> Result<Expr> {
    // Desugar simple CASE top-down before child literal/cast/alias rewrites so
    // `when_operand_is_inert` and `base.nullable` inspect the same unrewritten
    // operands that DataFusion's Substrait `from_case` sees on export.
    let expression = expression
        .transform_down(|expr| {
            let Expr::Case(case) = expr else {
                return Ok(Transformed::no(expr));
            };
            if !case.expr.as_deref().is_some_and(|base| !base.is_volatile()) {
                return Ok(Transformed::no(Expr::Case(case)));
            }
            let base = case.expr.expect("checked Some above");
            let when_operand_is_inert = |(when, _): &(Box<Expr>, Box<Expr>)| {
                matches!(when.as_ref(), Expr::Literal(..) | Expr::Column(_))
            };
            let null_base_guard = !case.when_then_expr.iter().all(when_operand_is_inert)
                && base.nullable(schema)?;
            let mut when_then_expr = Vec::with_capacity(
                case.when_then_expr.len() + usize::from(null_base_guard),
            );
            if null_base_guard {
                let then = match &case.else_expr {
                    Some(else_expr) => else_expr.as_ref().clone(),
                    None => match case.when_then_expr.first() {
                        Some((_, then)) => {
                            let result_type = then.get_type(schema)?;
                            typed_null_identity(&result_type)?
                        }
                        None => {
                            return Ok(Transformed::no(Expr::Case(expr::Case {
                                expr: Some(base),
                                when_then_expr: case.when_then_expr,
                                else_expr: case.else_expr,
                            })));
                        }
                    },
                };
                when_then_expr
                    .push((Box::new(base.as_ref().clone().is_null()), Box::new(then)));
            }
            for (when, then) in case.when_then_expr {
                when_then_expr
                    .push((Box::new(Expr::eq(base.as_ref().clone(), *when)), then));
            }
            Ok(Transformed::yes(Expr::Case(expr::Case {
                expr: None,
                when_then_expr,
                else_expr: case.else_expr,
            })))
        })?
        .data;
    Ok(expression
        .transform_up(|expr| {
            let mut changed = false;
            let expr = match expr {
                Expr::Alias(alias) => {
                    changed = true;
                    *alias.expr
                }
                Expr::Literal(value, Some(_)) => {
                    changed = true;
                    Expr::Literal(value, None)
                }
                other => other,
            };
            match expr {
                Expr::WindowFunction(mut window) => {
                    // Substrait represents unbounded endpoints without a type.
                    // Their original NULL type does not affect frame identity.
                    for bound in [
                        &mut window.params.window_frame.start_bound,
                        &mut window.params.window_frame.end_bound,
                    ] {
                        if let WindowFrameBound::Preceding(value)
                        | WindowFrameBound::Following(value) = bound
                            && value.is_null()
                            && *value != ScalarValue::Null
                        {
                            *value = ScalarValue::Null;
                            changed = true;
                        }
                    }
                    Ok(if changed {
                        Transformed::yes(Expr::WindowFunction(window))
                    } else {
                        Transformed::no(Expr::WindowFunction(window))
                    })
                }
                Expr::Column(column) => {
                    let resolved = if let Ok(index) = schema.index_of_column(&column) {
                        let (qualifier, field) = schema.qualified_field(index);
                        Column::new(qualifier.cloned(), field.name())
                    } else {
                        column.clone()
                    };
                    Ok(if resolved != column {
                        Transformed::yes(Expr::Column(resolved))
                    } else if changed {
                        Transformed::yes(Expr::Column(column))
                    } else {
                        Transformed::no(Expr::Column(column))
                    })
                }
                Expr::Cast(cast)
                    if matches!(
                        cast.expr.as_ref(),
                        Expr::Literal(ScalarValue::Null, _)
                    ) && cast.field.as_ref()
                        == &Field::new("", cast.field.data_type().clone(), true) =>
                {
                    Ok(Transformed::yes(typed_null_identity(
                        cast.field.data_type(),
                    )?))
                }
                Expr::Cast(mut cast)
                    if cast.field.as_ref()
                        == &Field::new("", cast.field.data_type().clone(), true) =>
                {
                    let bare = schema::bare_decoded_type(cast.field.data_type());
                    if bare != *cast.field.data_type() {
                        cast.field = Arc::new(Field::new("", bare, true));
                        Ok(Transformed::yes(Expr::Cast(cast)))
                    } else if changed {
                        Ok(Transformed::yes(Expr::Cast(cast)))
                    } else {
                        Ok(Transformed::no(Expr::Cast(cast)))
                    }
                }
                Expr::TryCast(mut try_cast)
                    if try_cast.field.as_ref()
                        == &Field::new("", try_cast.field.data_type().clone(), true) =>
                {
                    let bare = schema::bare_decoded_type(try_cast.field.data_type());
                    if bare != *try_cast.field.data_type() {
                        try_cast.field = Arc::new(Field::new("", bare, true));
                        Ok(Transformed::yes(Expr::TryCast(try_cast)))
                    } else if changed {
                        Ok(Transformed::yes(Expr::TryCast(try_cast)))
                    } else {
                        Ok(Transformed::no(Expr::TryCast(try_cast)))
                    }
                }
                Expr::Literal(value, meta) => {
                    if let Some(normalized) = normalize_wire_literal(&value)? {
                        Ok(Transformed::yes(normalized))
                    } else if changed {
                        Ok(Transformed::yes(Expr::Literal(value, meta)))
                    } else {
                        Ok(Transformed::no(Expr::Literal(value, meta)))
                    }
                }
                Expr::Between(between) => {
                    let expr = *between.expr;
                    let desugared = if between.negated {
                        Expr::or(
                            Expr::lt(expr.clone(), *between.low),
                            Expr::lt(*between.high, expr),
                        )
                    } else {
                        Expr::and(
                            Expr::lt_eq(*between.low, expr.clone()),
                            Expr::lt_eq(expr, *between.high),
                        )
                    };
                    Ok(Transformed::yes(desugared))
                }
                Expr::InList(mut in_list) if in_list.negated => {
                    in_list.negated = false;
                    Ok(Transformed::yes(Expr::Not(Box::new(Expr::InList(in_list)))))
                }
                Expr::Like(mut like) if like.negated => {
                    like.negated = false;
                    Ok(Transformed::yes(Expr::Not(Box::new(Expr::Like(like)))))
                }
                Expr::Case(case) if case.expr.is_none() => {
                    // Canonicalize a leading NULL-base guard when every WHEN
                    // operand is inert after wire normalization and at least one
                    // is a wire-rewritten typed NULL or Date64 millisecond cast.
                    // Separate encoding of structured expressions vs wire output
                    // fields can flip `when_operand_is_inert` on those two literal forms.
                    let (case, stripped) =
                        strip_wire_ambiguous_null_base_guard(case, schema)?;
                    Ok(if stripped || changed {
                        Transformed::yes(Expr::Case(case))
                    } else {
                        Transformed::no(Expr::Case(case))
                    })
                }
                other => Ok(if changed {
                    Transformed::yes(other)
                } else {
                    Transformed::no(other)
                }),
            }
        })?
        .data)
}

fn folded_required_count_identity(
    identity: &DecodedSummaryAggregate,
    source_input: &LogicalPlan,
    symbols: &[String],
) -> Option<DecodedSummaryAggregate> {
    if identity.function_name != count_udaf().name()
        || identity.distinct
        || identity.null_treatment.is_some()
        || !identity.order_by.is_empty()
    {
        return None;
    }
    let [Expr::Column(column)] = identity.args.as_slice() else {
        return None;
    };
    let source_schema = source_input.schema();
    let index = source_schema.maybe_index_of_column(column)?;
    let field = source_schema.field(index);
    if is_reserved_internal_column_name(field.name())
        || field.is_nullable()
        || can_have_nulls_outside_bitmap(field.data_type())
        || !is_stored_source_column(source_input, index)
    {
        return None;
    }
    let filter = identity.filter.as_ref()?;
    if !is_assigned_classifier_filter(filter, symbols) {
        return None;
    }
    Some(DecodedSummaryAggregate {
        function_name: identity.function_name.clone(),
        args: vec![Expr::Literal(ScalarValue::Int64(Some(1)), None)],
        distinct: false,
        filter: Some(filter.clone()),
        order_by: Vec::new(),
        null_treatment: None,
    })
}

fn is_assigned_classifier_filter(filter: &Expr, symbols: &[String]) -> bool {
    match filter {
        Expr::IsNotNull(inner) => matches!(
            inner.as_ref(),
            Expr::Column(column)
                if column.relation.is_none()
                    && column.name == MatchMetadataColumn::Classifier.as_ref()
        ),
        Expr::Column(column) => {
            column.relation.is_none()
                && symbols
                    .iter()
                    .any(|symbol| classifier_bits_col_name(symbol) == column.name)
        }
        _ => false,
    }
}

fn is_stored_source_column(mut input: &LogicalPlan, mut col_index: usize) -> bool {
    loop {
        match input {
            LogicalPlan::SubqueryAlias(alias) => input = &alias.input,
            LogicalPlan::Filter(filter) => input = &filter.input,
            LogicalPlan::Projection(projection) => {
                let Some(mut expr) = projection.expr.get(col_index) else {
                    return false;
                };
                while let Expr::Alias(alias) = expr {
                    expr = alias.expr.as_ref();
                }
                let Expr::Column(column) = expr else {
                    return false;
                };
                let Some(next_index) =
                    projection.input.schema().maybe_index_of_column(column)
                else {
                    return false;
                };
                input = &projection.input;
                col_index = next_index;
            }
            LogicalPlan::TableScan(scan) => {
                return scan.source.table_type() == TableType::Base
                    && scan.source.get_logical_plan().is_none();
            }
            _ => return false,
        }
    }
}

fn decode_boundary(
    payload: &payload::MatchRecognizeRel,
) -> Result<MatchRecognizeBoundary> {
    if !payload.retained_passthrough_input_fields.is_empty() && !payload.semantic_node {
        return plan_err!(
            "MATCH_RECOGNIZE retained_passthrough_input_fields requires positional semantic-node output"
        );
    }
    if !payload.prepared_output_fields.is_empty() && !payload.semantic_node {
        return plan_err!(
            "MATCH_RECOGNIZE prepared_output_fields requires positional semantic-node output"
        );
    }
    if !payload.summary_output_fields.is_empty()
        && (!payload.semantic_node || !payload.semantic_node_finalizes_one_row)
    {
        return plan_err!(
            "MATCH_RECOGNIZE summary_output_fields requires one-row semantic-node output"
        );
    }
    let finalizes_one_row = payload
        .required_features
        .iter()
        .any(|feature| feature == DATAFUSION_SEMANTIC_ONE_ROW_FEATURE);
    if payload.semantic_node_finalizes_one_row != finalizes_one_row {
        return plan_err!(
            "MATCH_RECOGNIZE Substrait semantic_node_finalizes_one_row must agree with required feature {}",
            DATAFUSION_SEMANTIC_ONE_ROW_FEATURE
        );
    }
    match (
        payload.semantic_node,
        payload.semantic_node_finalizes_one_row,
    ) {
        (false, false) => Ok(MatchRecognizeBoundary::CompletePlan),
        (true, false) => Ok(MatchRecognizeBoundary::RowStreamNode),
        (true, true) => Ok(MatchRecognizeBoundary::OneRowNode),
        (false, true) => plan_err!(
            "MATCH_RECOGNIZE Substrait native ONE ROW finalization requires semantic_node=true"
        ),
    }
}

pub(super) fn validate_schema_version(schema_version: Option<u32>) -> Result<()> {
    let Some(schema_version) = schema_version else {
        return plan_err!("MATCH_RECOGNIZE Substrait payload missing schema_version");
    };
    if schema_version == MATCH_RECOGNIZE_SCHEMA_VERSION {
        return Ok(());
    }
    plan_err!(
        "unsupported MATCH_RECOGNIZE Substrait payload schema_version {}; expected {}",
        schema_version,
        MATCH_RECOGNIZE_SCHEMA_VERSION
    )
}

pub(super) fn decode_capabilities(
    features: &[String],
) -> Result<MatchRecognizePlanningCapabilities> {
    let features = features.iter().map(String::as_str).collect::<BTreeSet<_>>();
    if !features.contains(MATCH_RECOGNIZE_EXTENSION_FEATURE) {
        return plan_err!(
            "MATCH_RECOGNIZE Substrait payload missing required feature {}",
            MATCH_RECOGNIZE_EXTENSION_FEATURE
        );
    }

    if !features.contains(MATCH_RECOGNIZE_POSITIONAL_FIELD_REFS_FEATURE) {
        return plan_err!(
            "MATCH_RECOGNIZE Substrait payload missing required feature {}",
            MATCH_RECOGNIZE_POSITIONAL_FIELD_REFS_FEATURE
        );
    }

    for &feature in &features {
        match feature {
            MATCH_RECOGNIZE_EXTENSION_FEATURE
            | MATCH_RECOGNIZE_POSITIONAL_FIELD_REFS_FEATURE
            | MATCH_RECOGNIZE_RELUCTANT_QUANTIFIERS_FEATURE
            | MATCH_RECOGNIZE_LOGICAL_NAVIGATION_OFFSET_FEATURE
            | MATCH_RECOGNIZE_COMPOUND_NAVIGATION_FEATURE
            | MATCH_RECOGNIZE_DISTINCT_FROM_FEATURE
            | MATCH_RECOGNIZE_MATCH_AWARE_DEFINES_FEATURE
            | DATAFUSION_MATCH_SEQUENCE_NUMBER_FEATURE
            | DATAFUSION_EXCLUDED_FEATURE
            | DATAFUSION_WINDOW_MODIFIERS_FEATURE
            | DATAFUSION_SEMANTIC_ONE_ROW_FEATURE => {}
            _ => {
                return plan_err!(
                    "unknown MATCH_RECOGNIZE Substrait required feature {}",
                    feature
                );
            }
        }
    }

    Ok(MatchRecognizePlanningCapabilities::restricted(
        features.contains(DATAFUSION_MATCH_SEQUENCE_NUMBER_FEATURE),
        features.contains(DATAFUSION_EXCLUDED_FEATURE),
    ))
}

pub(super) fn decode_input_field(input_schema: &DFSchema, index: u32) -> Result<Column> {
    let index = usize::try_from(index).map_err(|_| {
        datafusion::common::DataFusionError::Plan(
            "MATCH_RECOGNIZE Substrait input_field exceeds the addressable input".into(),
        )
    })?;
    if index >= input_schema.fields().len() {
        return plan_err!(
            "MATCH_RECOGNIZE Substrait input_field {} is out of bounds for {} input fields",
            index,
            input_schema.fields().len()
        );
    }
    let (qualifier, field) = input_schema.qualified_field(index);
    let column = Column::new(qualifier.cloned(), field.name());
    let identities = input_schema
        .iter()
        .filter(|(candidate_qualifier, candidate)| {
            *candidate_qualifier == qualifier && candidate.name() == field.name()
        })
        .count();
    if identities != 1 || input_schema.index_of_column(&column)? != index {
        return plan_err!(
            "MATCH_RECOGNIZE Substrait input_field {} does not identify an unambiguous input column",
            index
        );
    }
    Ok(column)
}