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

//! Small helpers shared by several logical-planning steps.
//!
//! They replace calculated expressions with plan columns, build the final
//! `ROWS PER MATCH` projection, and create canonical window frames for source
//! expressions and conditions for match-aware DEFINEs.

use crate::core::pattern::{EmptyMatchesMode, RowsPerMatch};
use crate::core::{
    MatchMetadataColumn, MatchRecognizeOutputSpec, classifier_bits_col_name,
};
use crate::planning::NamedExpr;
use datafusion::arrow::datatypes::{DataType, Field};
use datafusion::common::ScalarValue;
use datafusion::common::tree_node::{
    Transformed, TransformedResult, TreeNode, TreeNodeRecursion,
};
use datafusion::common::{Column, DFSchema, DFSchemaRef, Result, TableReference};
#[cfg(test)]
use datafusion::logical_expr::LogicalPlanBuilder;
use datafusion::logical_expr::expr::Case;
use datafusion::logical_expr::{
    Expr, ExprSchemable, LogicalPlan, SortExpr, WindowFrame, WindowFrameBound,
    WindowFrameUnits, WindowFunctionDefinition,
};
use std::collections::{BTreeSet, HashMap, HashSet};
use std::sync::Arc;

/// Create `ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW`.
///
/// Navigation and causal aggregate windows share this frame in selected-match
/// output and conditions for match-aware DEFINEs.
pub fn causal_window_frame() -> WindowFrame {
    WindowFrame::new_bounds(
        WindowFrameUnits::Rows,
        WindowFrameBound::Preceding(ScalarValue::UInt64(None)),
        WindowFrameBound::CurrentRow,
    )
}

/// Build the final `MATCH_RECOGNIZE` output projection.
///
/// - `OneRow`: project only `partition_by_exprs` plus `MEASURES`.
/// - `AllRows`: project partition columns, order columns, `MEASURES`,
///   then remaining input columns. Input columns are de-duplicated.
/// - With `UNMATCHED`: wrap measures with
///   `CASE WHEN __mr_match_number IS NOT NULL THEN <measure> END`
///   unless a direct metadata column (or a RunEndEncoded FIRST/LAST window
///   column whose mask is already false on unmatched rows) supplies the NULL.
pub(crate) fn rows_projection_expr(
    rows_per_match: &RowsPerMatch,
    plan: &LogicalPlan,
    table_schema: &DFSchemaRef,
    partition_by_exprs: &[Expr],
    order_by_exprs: &[SortExpr],
    measures_exprs: &[NamedExpr],
) -> Vec<Expr> {
    let one_row = matches!(rows_per_match, RowsPerMatch::OneRow);
    let (mut exprs, mut seen_input_indices) = if one_row {
        (partition_by_exprs.to_vec(), HashSet::new())
    } else {
        all_rows_leading_input_exprs(table_schema, partition_by_exprs, order_by_exprs)
    };

    let with_unmatched = matches!(
        rows_per_match,
        RowsPerMatch::AllRows(EmptyMatchesMode::WithUnmatched)
    );

    exprs.extend(measures_exprs.iter().map(|named| {
        // Remove nested aliases before assigning the one user-visible name.
        let unaliased = named.expr.clone().unalias_nested().data;

        let mut metadata = None;
        let projected = if with_unmatched && !is_null_on_unmatched_row(&unaliased, plan) {
            metadata = unaliased
                .metadata(plan.schema())
                .ok()
                .filter(|m| !m.is_empty());
            let match_number_not_null = Expr::Column(Column::from_name(
                MatchMetadataColumn::MatchNumber.as_ref(),
            ))
            .is_not_null();
            Expr::Case(Case::new(
                None,
                vec![(Box::new(match_number_not_null), Box::new(unaliased))],
                None,
            ))
        } else {
            unaliased
        };
        match metadata {
            Some(metadata) => projected.alias_with_metadata(&named.name, Some(metadata)),
            None => projected.alias(&named.name),
        }
    }));

    if !one_row {
        for idx in 0..table_schema.fields().len() {
            push_input_column_by_index(
                table_schema,
                idx,
                &mut seen_input_indices,
                &mut exprs,
            );
        }
    }

    exprs
}

fn is_null_on_unmatched_row(expr: &Expr, plan: &LogicalPlan) -> bool {
    let Expr::Column(c) = expr else {
        return false;
    };
    if c.relation.is_some() {
        return false;
    }
    if matches!(
        c.name.parse::<MatchMetadataColumn>(),
        Ok(MatchMetadataColumn::Classifier
            | MatchMetadataColumn::MatchNumber
            | MatchMetadataColumn::MatchSequenceNumber)
    ) {
        return true;
    }
    // `mr_first`/`mr_last` windows already mask on `__mr_classifier` (false on
    // every unmatched row) and preserve custom REE field names/metadata, whereas
    // `CASE WHEN __mr_match_number IS NOT NULL THEN col END` invokes Arrow
    // `nullif`, which resets REE child fields to canonical names.
    if !plan
        .schema()
        .field_with_unqualified_name(&c.name)
        .is_ok_and(|f| crate::execution::storage::contains_run_end_encoded(f.data_type()))
    {
        return false;
    }
    let first = crate::functions::udwf::mr_first_udwf();
    let last = crate::functions::udwf::mr_last_udwf();
    let mut cursor = plan;
    loop {
        match cursor {
            LogicalPlan::Filter(filter) => cursor = &filter.input,
            LogicalPlan::Window(window) => {
                if window.window_expr.iter().any(|expr| {
                    expr.qualified_name().1 == c.name
                        && matches!(
                            expr.clone().unalias(),
                            Expr::WindowFunction(wf)
                                if matches!(
                                    &wf.fun,
                                    WindowFunctionDefinition::WindowUDF(u)
                                        if u.as_ref() == first.as_ref() || u.as_ref() == last.as_ref()
                                )
                        )
                }) {
                    return true;
                }
                cursor = &window.input;
            }
            _ => return false,
        }
    }
}

fn all_rows_leading_input_exprs(
    table_schema: &DFSchemaRef,
    partition_by_exprs: &[Expr],
    order_by_exprs: &[SortExpr],
) -> (Vec<Expr>, HashSet<usize>) {
    let mut exprs = Vec::new();
    let mut seen = HashSet::new();

    for expr in partition_by_exprs {
        push_input_columns_from_expr(table_schema, expr, &mut seen, &mut exprs);
    }
    for sort_expr in order_by_exprs {
        push_input_columns_from_expr(
            table_schema,
            &sort_expr.expr,
            &mut seen,
            &mut exprs,
        );
    }

    (exprs, seen)
}

fn push_input_columns_from_expr(
    table_schema: &DFSchemaRef,
    expr: &Expr,
    seen: &mut HashSet<usize>,
    exprs: &mut Vec<Expr>,
) {
    let mut indices = expr
        .column_refs()
        .iter()
        .filter_map(|col| schema_index_of_column(table_schema, col))
        .collect::<Vec<_>>();
    indices.sort_unstable();

    for idx in indices {
        push_input_column_by_index(table_schema, idx, seen, exprs);
    }
}

fn push_input_column_by_index(
    table_schema: &DFSchemaRef,
    idx: usize,
    seen: &mut HashSet<usize>,
    exprs: &mut Vec<Expr>,
) {
    if !seen.insert(idx) {
        return;
    }

    let (qualifier, field) = table_schema.qualified_field(idx);
    let col_expr = Expr::Column(Column::new(qualifier.cloned(), field.name()));
    // Strip the input table qualifier on the anonymous MATCH_RECOGNIZE output
    // table whenever the bare field name is unique in the input schema.
    if qualifier.is_some()
        && table_schema
            .fields()
            .iter()
            .filter(|candidate| candidate.name() == field.name())
            .count()
            == 1
    {
        exprs.push(col_expr.alias(field.name()));
    } else {
        exprs.push(col_expr);
    }
}

/// Resolve a column against a schema, falling back to name-only matching when
/// qualifier-preserving lookup does not succeed.
pub fn schema_index_of_column(schema: &DFSchemaRef, col: &Column) -> Option<usize> {
    schema
        .maybe_index_of_column(col)
        .or_else(|| schema_index_of_name(schema, &col.name))
}

/// Resolve an unqualified field name against a schema.
pub fn schema_index_of_name(schema: &DFSchemaRef, name: &str) -> Option<usize> {
    schema
        .fields()
        .iter()
        .position(|field| field.name() == name)
}

/// Extend a set of required column indices from expression column references.
pub fn extend_required_indices_from_exprs<'a>(
    required: &mut HashSet<usize>,
    schema: &DFSchemaRef,
    exprs: impl IntoIterator<Item = &'a Expr>,
) {
    for expr in exprs {
        for col in expr.column_refs() {
            if let Some(idx) = schema_index_of_column(schema, col) {
                required.insert(idx);
            }
        }
    }
}

/// Extend a set of required column indices from unqualified column names.
pub fn extend_required_indices_from_names(
    required: &mut HashSet<usize>,
    schema: &DFSchemaRef,
    names: impl IntoIterator<Item = String>,
) {
    for name in names {
        if let Some(idx) = schema_index_of_name(schema, &name) {
            required.insert(idx);
        }
    }
}

/// Remap a passthrough field by its qualified identity. Projection can
/// remove one field while keeping a field of the same name from another relation.
pub fn remap_field_index(
    source_schema: &DFSchemaRef,
    source_idx: usize,
    target_schema: &DFSchemaRef,
) -> Option<usize> {
    let (qualifier, field) = source_schema.qualified_field(source_idx);
    match qualifier {
        Some(relation) => {
            target_schema.index_of_column_by_name(Some(relation), field.name())
        }
        None => target_schema.iter().position(|(qualifier, target)| {
            qualifier.is_none() && target.name() == field.name()
        }),
    }
}

/// Collect distinct output-column indices, including declared subquery correlations.
pub fn required_output_indices(schema: &DFSchemaRef, exprs: &[Expr]) -> Vec<usize> {
    use datafusion::common::tree_node::{TreeNode, TreeNodeRecursion};

    let mut required = Vec::new();
    let mut pending = exprs.iter().collect::<Vec<_>>();
    while let Some(expr) = pending.pop() {
        match expr {
            Expr::Column(column) | Expr::OuterReferenceColumn(_, column) => {
                // A same-named field from another relation is not interchangeable.
                if let Some(idx) = schema.maybe_index_of_column(column) {
                    required.push(idx);
                }
            }
            // Subquery-local columns belong to a different schema. Visit only
            // the declared outer dependencies, plus ordinary expression children.
            Expr::ScalarSubquery(subquery) => pending.extend(&subquery.outer_ref_columns),
            Expr::Exists(expr) => pending.extend(&expr.subquery.outer_ref_columns),
            Expr::InSubquery(expr) => pending.extend(&expr.subquery.outer_ref_columns),
            Expr::SetComparison(expr) => pending.extend(&expr.subquery.outer_ref_columns),
            _ => {}
        }
        expr.apply_children(|child| {
            pending.push(child);
            Ok(TreeNodeRecursion::Continue)
        })
        .expect("expression child traversal is infallible");
    }
    required.sort_unstable();
    required.dedup();
    required
}

/// Remap passthrough output columns to a new child schema after projection
/// pushdown or other child-schema rewrites.
pub(in crate::planning::logical) fn remap_output_spec(
    output_spec: &MatchRecognizeOutputSpec,
    old_input_schema: &DFSchemaRef,
    new_child_schema: &DFSchemaRef,
) -> MatchRecognizeOutputSpec {
    let remapped_passthrough = output_spec
        .passthrough_input_indices()
        .iter()
        .filter_map(|&old_idx| {
            remap_field_index(old_input_schema, old_idx, new_child_schema)
        })
        .collect();

    MatchRecognizeOutputSpec::with_validated_navigation_offsets(
        remapped_passthrough,
        output_spec.metadata_columns().to_vec(),
        output_spec.classifier_bitset_symbols().to_vec(),
        output_spec.navigation_offsets(),
    )
}

/// A pruned row selection and the retained summary positions owned by its
/// logical output mode.
pub(in crate::planning::logical) struct PrunedOutputSpec {
    pub(in crate::planning::logical) spec: MatchRecognizeOutputSpec,
    pub(in crate::planning::logical) summary_positions: Vec<usize>,
}

/// Prune a row selection and its trailing summary positions down to the
/// required output indices.
///
/// Returns `None` when the required indices keep the existing spec intact.
pub(in crate::planning::logical) fn prune_output_spec(
    output_spec: &MatchRecognizeOutputSpec,
    summary_count: usize,
    required_indices: &[usize],
) -> Option<PrunedOutputSpec> {
    let passthrough_count = output_spec.passthrough_input_indices().len();
    let metadata_count = output_spec.metadata_columns().len();
    let classifier_count = output_spec.classifier_bitset_symbols().len();

    let mut required_passthrough_positions = Vec::new();
    let mut required_metadata = Vec::new();
    let mut required_classifiers = Vec::new();
    let mut required_summary_positions = Vec::new();

    for &idx in required_indices {
        if idx < passthrough_count {
            required_passthrough_positions.push(idx);
            continue;
        }

        let generated_idx = idx - passthrough_count;
        if generated_idx < metadata_count {
            if let Some(&metadata_col) = output_spec.metadata_columns().get(generated_idx)
                && !required_metadata.contains(&metadata_col)
            {
                required_metadata.push(metadata_col);
            }
            continue;
        }

        let classifier_idx = generated_idx - metadata_count;
        if classifier_idx < classifier_count {
            let symbol = &output_spec.classifier_bitset_symbols()[classifier_idx];
            if !required_classifiers
                .iter()
                .any(|existing| existing == symbol)
            {
                required_classifiers.push(symbol.clone());
            }
            continue;
        }

        let summary_idx = classifier_idx - classifier_count;
        if summary_idx < summary_count
            && !required_summary_positions.contains(&summary_idx)
        {
            required_summary_positions.push(summary_idx);
        }
    }

    if required_passthrough_positions.len() == passthrough_count
        && required_metadata.len() == metadata_count
        && required_classifiers.len() == output_spec.classifier_bitset_symbols().len()
        && required_summary_positions.len() == summary_count
    {
        return None;
    }

    let required_passthrough_input_indices = required_passthrough_positions
        .into_iter()
        .map(|pos| output_spec.passthrough_input_indices()[pos])
        .collect();

    Some(PrunedOutputSpec {
        spec: MatchRecognizeOutputSpec::with_validated_navigation_offsets(
            required_passthrough_input_indices,
            required_metadata,
            required_classifiers,
            output_spec.navigation_offsets(),
        ),
        summary_positions: required_summary_positions,
    })
}

fn push_generated_field(
    qualified_fields: &mut Vec<(Option<TableReference>, Arc<Field>)>,
    table_schema: &DFSchemaRef,
    field: Arc<Field>,
) {
    // Prepared matcher inputs may already carry this generated field.
    if table_schema.has_column_with_unqualified_name(field.name()) {
        return;
    }
    qualified_fields.push((None, field));
}

/// Describe columns whose values depend on candidate state during semantic source inspection.
///
/// The schema includes input columns, internal match metadata, and one
/// `__mr_classifier_<symbol>` column per pattern variable. Planning uses it
/// to identify candidate dependencies and bind candidate predicates.
pub fn build_match_aware_schema(
    table_schema: &DFSchemaRef,
    define_symbol_names: &BTreeSet<String>,
) -> Result<DFSchemaRef> {
    // Preserve qualifiers on input columns.
    let mut qualified_fields = table_schema
        .iter()
        .map(|(qualifier, field)| (qualifier.cloned(), Arc::clone(field)))
        .collect::<Vec<_>>();

    // Internal metadata columns are unqualified.
    for col in MatchMetadataColumn::all() {
        push_generated_field(&mut qualified_fields, table_schema, col.arrow_field());
    }

    // Each pattern variable gets an unqualified classifier column.
    for symbol_name in define_symbol_names {
        let name = classifier_bits_col_name(symbol_name);
        let field = Arc::new(Field::new(name, DataType::Boolean, true));
        push_generated_field(&mut qualified_fields, table_schema, field);
    }

    // Keep the qualifiers collected above when constructing the schema.
    Ok(Arc::new(DFSchema::new_with_metadata(
        qualified_fields,
        HashMap::new(),
    )?))
}

/// Bind full expressions to columns without deriving identity from display names.
///
/// Direct columns retain their qualifiers. Calculated outputs receive names
/// distinct from every input field and every output reserved by the caller.
pub(crate) struct ExprBindings {
    entries: Vec<(Expr, Column)>,
    by_expr: HashMap<Expr, usize>,
    names: HashSet<String>,
}

impl ExprBindings {
    pub(crate) fn new<'a>(
        schema: &DFSchema,
        reserved: impl IntoIterator<Item = &'a str>,
    ) -> Self {
        Self {
            entries: Vec::new(),
            by_expr: HashMap::new(),
            names: schema
                .fields()
                .iter()
                .map(|field| field.name().clone())
                .chain(reserved.into_iter().map(str::to_owned))
                .collect(),
        }
    }

    /// Return the expression to calculate, reusing an existing exact binding.
    pub(crate) fn bind(&mut self, expr: Expr) -> Expr {
        let column = self.register(expr.clone());
        if matches!(expr, Expr::Column(_)) {
            expr
        } else {
            expr.alias(column.name)
        }
    }

    /// Give an expression one output identity, retaining direct column qualifiers.
    pub(crate) fn register(&mut self, expr: Expr) -> Column {
        if let Some(index) = self.by_expr.get(&expr) {
            return self.entries[*index].1.clone();
        }
        let column = if let Expr::Column(column) = &expr {
            self.names.insert(column.name.clone());
            column.clone()
        } else {
            self.fresh_column()
        };
        self.by_expr.insert(expr.clone(), self.entries.len());
        self.entries.push((expr, column.clone()));
        column
    }

    fn fresh_column(&mut self) -> Column {
        let mut name = format!("__mr_expr_{}", self.entries.len());
        while !self.names.insert(name.clone()) {
            name.push('_');
        }
        Column::from_name(name)
    }

    /// Bind one occurrence, sharing only expressions with stable values.
    pub(crate) fn register_occurrence(&mut self, expr: Expr) -> Column {
        if expr.is_volatile() {
            let column = self.fresh_column();
            self.entries.push((expr, column.clone()));
            column
        } else {
            self.register(expr)
        }
    }

    pub(crate) fn column(&self, expr: &Expr) -> Result<Column> {
        self.by_expr
            .get(expr)
            .map(|index| self.entries[*index].1.clone())
            .ok_or_else(|| {
                datafusion::common::internal_datafusion_err!(
                    "MATCH_RECOGNIZE expression has no prepared output binding: {expr}"
                )
            })
    }

    pub(crate) fn rebase(&self, expr: &Expr) -> Result<Expr> {
        expr.clone()
            .transform_down(|nested| {
                if let Some(index) = self.by_expr.get(&nested) {
                    Ok(Transformed::yes(Expr::Column(
                        self.entries[*index].1.clone(),
                    )))
                } else {
                    Ok(Transformed::no(nested))
                }
            })
            .data()
    }

    /// Rebase matching non-literal expressions onto their bound output columns.
    ///
    /// Literals remain valid after aggregation and may be required as constant
    /// arguments by scalar functions such as `get_field`.
    pub(crate) fn rebase_non_literal(&self, expr: &Expr) -> Result<Expr> {
        expr.clone()
            .transform_down(|nested| {
                if !matches!(nested, Expr::Literal(..))
                    && let Some(index) = self.by_expr.get(&nested)
                {
                    Ok(Transformed::yes(Expr::Column(
                        self.entries[*index].1.clone(),
                    )))
                } else {
                    Ok(Transformed::no(nested))
                }
            })
            .data()
    }

    pub(crate) fn binding_count(&self) -> usize {
        self.entries.len()
    }

    pub(crate) fn aliased_expressions_from(
        &self,
        first: usize,
    ) -> impl Iterator<Item = Expr> + '_ {
        self.entries[first..]
            .iter()
            .map(|(expr, column)| expr.clone().alias(&column.name))
    }

    pub(crate) fn into_named_exprs(self) -> Vec<NamedExpr> {
        self.entries
            .into_iter()
            .filter_map(|(expr, column)| {
                (!matches!(expr, Expr::Column(_))).then_some(NamedExpr {
                    name: column.name,
                    expr,
                })
            })
            .collect()
    }
}

/// Materialize eligible window occurrences and replace them with their columns.
pub(crate) fn prepare_windows<'a, 'expr>(
    plan: LogicalPlan,
    expressions: impl IntoIterator<Item = &'expr mut Expr>,
    reserved: impl IntoIterator<Item = &'a str>,
    eligible: impl Fn(&Expr) -> bool,
) -> Result<(LogicalPlan, Vec<NamedExpr>)> {
    let mut bindings = None;
    let mut reserved = Some(reserved);
    for expression in expressions {
        let original =
            std::mem::replace(expression, datafusion::logical_expr::lit(false));
        *expression = original
            .transform_down(|node| {
                if !matches!(node, Expr::WindowFunction(_)) {
                    return Ok(Transformed::no(node));
                }
                if !eligible(&node) {
                    return Ok(Transformed::new(node, false, TreeNodeRecursion::Jump));
                }
                let bindings = bindings.get_or_insert_with(|| {
                    ExprBindings::new(
                        plan.schema(),
                        reserved.take().expect("window bindings initialize once"),
                    )
                });
                let column = bindings.register_occurrence(node);
                Ok(Transformed::yes(Expr::Column(column)))
            })
            .data()?;
    }
    let Some(bindings) = bindings else {
        return Ok((plan, Vec::new()));
    };
    let plan = materialize_bound_windows(plan, &bindings)?;
    Ok((plan, bindings.into_named_exprs()))
}

/// Add explicitly named, already identified windows in native sort-key order.
pub(crate) fn materialize_windows<'a>(
    plan: LogicalPlan,
    window_exprs: &[Expr],
    reserved: impl IntoIterator<Item = &'a str>,
) -> Result<(LogicalPlan, ExprBindings)> {
    let mut bindings = ExprBindings::new(plan.schema(), reserved);
    for expr in window_exprs {
        bindings.register(expr.clone());
    }
    let plan = materialize_bound_windows(plan, &bindings)?;
    Ok((plan, bindings))
}

/// Guard only the value input: filtering rows would change physical offsets.
/// Callers supply the mask position for the window or aggregate signature.
pub(crate) fn guard_navigation_value(
    args: &mut [Expr],
    mask_index: Option<usize>,
    previous: bool,
    schema: &DFSchema,
) -> Result<()> {
    use crate::core::MAX_VALID_MATCH_SEQUENCE_NUMBER;
    use crate::planning::logical::is_matched_expr;
    use datafusion::logical_expr::{col, lit};

    if crate::planning::expr_safety::can_discard_scalar(&args[0], Some(schema)) {
        return Ok(());
    }
    let guard = if matches!(&args[1], Expr::Literal(ScalarValue::UInt64(Some(0)), _)) {
        // At offset zero the target is the symbol's logical anchor itself.
        mask_index.map_or_else(is_matched_expr, |index| args[index].clone())
    } else {
        // Empty markers have sequence 1 but no classifier. Halo rows also lack
        // classifiers, but belong to a match and use directional sentinels.
        // A positive shift can read any symbol, including the relevant halo.
        let sequence = col(MatchMetadataColumn::MatchSequenceNumber.as_ref());
        let halo = if previous {
            sequence.lt(lit(1_i64))
        } else {
            sequence.gt(lit(MAX_VALID_MATCH_SEQUENCE_NUMBER))
        };
        is_matched_expr().or(col(MatchMetadataColumn::MatchNumber.as_ref())
            .is_not_null()
            .and(halo))
    };
    let value = &mut args[0];
    let selected = Expr::Case(Case::new(
        None,
        vec![(Box::new(guard), Box::new(value.clone()))],
        None,
    ));
    // CASE does not inherit field metadata from its value branch.
    let metadata = value.metadata(schema)?;
    *value = if metadata.is_empty() {
        selected
    } else {
        selected.alias_with_metadata(value.schema_name().to_string(), Some(metadata))
    };
    Ok(())
}

fn materialize_bound_windows(
    plan: LogicalPlan,
    bindings: &ExprBindings,
) -> Result<LogicalPlan> {
    let mut windows = bindings.aliased_expressions_from(0).collect::<Vec<_>>();
    for expr in &mut windows {
        let expr = match expr {
            Expr::Alias(alias) => alias.expr.as_mut(),
            other => other,
        };
        let Expr::WindowFunction(window) = expr else {
            continue;
        };
        let WindowFunctionDefinition::WindowUDF(function) = &window.fun else {
            continue;
        };
        use crate::functions::udwf::{
            mr_first_udwf, mr_last_udwf, mr_next_udwf, mr_prev_udwf,
        };
        if !window
            .params
            .partition_by
            .contains(&Expr::Column(Column::from_name(
                MatchMetadataColumn::MatchNumber.as_ref(),
            )))
        {
            continue;
        }
        if function.as_ref() == mr_prev_udwf().as_ref()
            || function.as_ref() == mr_next_udwf().as_ref()
        {
            // Plain windows have 3 args, qualified windows 4, compound ones 6.
            let mask_index = match window.params.args.len() {
                3 => None,
                4 => Some(3),
                6 => Some(5),
                _ => continue,
            };
            guard_navigation_value(
                &mut window.params.args,
                mask_index,
                function.as_ref() == mr_prev_udwf().as_ref(),
                plan.schema(),
            )?;
            continue;
        }
        if function.as_ref() != mr_first_udwf().as_ref()
            && function.as_ref() != mr_last_udwf().as_ref()
        {
            continue;
        }
        let (value, mask) = match window.params.args.as_mut_slice() {
            [value, mask] | [value, _, mask] => (value, mask),
            _ => continue,
        };
        if crate::planning::expr_safety::can_discard_scalar(value, Some(plan.schema())) {
            continue;
        }
        // FIRST/LAST use a mask argument rather than FILTER. Window executors
        // evaluate values eagerly, so rejected and marker rows must skip any
        // fallible or volatile work before the navigation evaluator sees it.
        let selected = Expr::Case(Case::new(
            None,
            vec![(Box::new(mask.clone()), Box::new(value.clone()))],
            None,
        ));
        // CASE does not inherit field metadata from its value branch.
        let metadata = value.metadata(plan.schema().as_ref())?;
        *value = if metadata.is_empty() {
            selected
        } else {
            selected.alias_with_metadata(value.schema_name().to_string(), Some(metadata))
        };
    }
    // Windows retain their input fields, so temporary columns must not take
    // any of the already allocated window output names.
    let reserved = bindings
        .entries
        .iter()
        .map(|(_, column)| column.name.clone())
        .collect::<Vec<_>>();
    // ALL ROWS aggregate windows evaluate args before FILTER too. Prepare
    // guards here, where a volatile filter can be materialized once and shared
    // with its arguments without changing DEFINE or navigation evaluation.
    let plan =
        crate::planning::measures::prepare_filtered_inputs(
            plan,
            windows.iter_mut().filter_map(|expr| {
                let expr = match expr {
                    Expr::Alias(alias) => alias.expr.as_mut(),
                    other => other,
                };
                let Expr::WindowFunction(window) = expr else {
                    return None;
                };
                if !matches!(window.fun, WindowFunctionDefinition::AggregateUDF(_))
                    || !window.params.partition_by.contains(&Expr::Column(
                        Column::from_name(MatchMetadataColumn::MatchNumber.as_ref()),
                    ))
                {
                    return None;
                }
                Some((
                    &mut window.params.filter,
                    &mut window.params.args,
                    &mut window.params.order_by,
                ))
            }),
            &reserved,
        )?;
    let plan = crate::compat::window_plan(plan, windows)?;
    // Native window planning checks nesting and field types under aliases, but
    // its FILTER check still needs bare expressions. Aliased ROW_NUMBER also
    // omits uniqueness metadata; no matcher decision depends on that FD.
    if let Some((expr, _)) = bindings.entries.iter().find(|(expr, _)| {
        matches!(expr,
            Expr::WindowFunction(window)
                if !matches!(window.fun, WindowFunctionDefinition::AggregateUDF(_))
                    && window.params.filter.is_some()
        )
    }) {
        return datafusion::common::plan_err!(
            "FILTER clause can only be used with aggregate window functions. Found in '{expr}'"
        );
    }
    Ok(plan)
}

#[cfg(test)]
mod schema_utils_tests {
    use super::{build_match_aware_schema, prune_output_spec, remap_output_spec};
    use crate::core::MatchRecognizeOutputSpec;
    use datafusion::arrow::datatypes::{DataType, Field, Schema};
    use datafusion::common::DFSchema;
    use std::collections::BTreeSet;
    use std::sync::Arc;

    #[test]
    fn match_aware_schema_uses_current_metadata_and_classifier_nullability() {
        let table_schema = Arc::new(
            DFSchema::try_from(Schema::new(vec![
                Field::new("x", DataType::Int32, true),
                Field::new("__mr_path_id", DataType::Int64, false),
            ]))
            .expect("schema"),
        );
        let symbols = BTreeSet::from(["A".into(), "B".into(), "İA".into()]);
        let extended = build_match_aware_schema(&table_schema, &symbols).expect("schema");
        let expected = vec![
            Field::new("x", DataType::Int32, true),
            Field::new("__mr_path_id", DataType::Int64, false),
            Field::new("__mr_classifier", DataType::Utf8, true),
            Field::new("__mr_match_number", DataType::Int64, true),
            Field::new("__mr_match_sequence_number", DataType::Int64, true),
            Field::new("__mr_excluded", DataType::Boolean, true),
            Field::new("__mr_classifier_a", DataType::Boolean, true),
            Field::new("__mr_classifier_b", DataType::Boolean, true),
            Field::new("__mr_classifier_İa", DataType::Boolean, true),
        ];
        assert_eq!(extended.as_arrow(), &Schema::new(expected));
    }

    #[test]
    fn pruning_and_remapping_preserve_row_selection() {
        let schema = Arc::new(
            DFSchema::try_from(Schema::new(vec![Field::new(
                "x",
                DataType::Int32,
                false,
            )]))
            .expect("schema"),
        );
        let output = MatchRecognizeOutputSpec::new(vec![0], vec![], vec![]);

        let pruned = prune_output_spec(&output, 0, &[])
            .expect("the passthrough column should be removed")
            .spec;
        let remapped = remap_output_spec(&output, &schema, &schema);

        assert!(pruned.is_empty());
        assert_eq!(remapped.passthrough_input_indices(), [0]);
    }

    #[test]
    fn output_requirements_follow_declared_correlations_without_local_columns()
    -> datafusion::common::Result<()> {
        use datafusion::common::{Column, TableReference};
        use datafusion::logical_expr::expr::{SetComparison, SetQuantifier};
        use datafusion::logical_expr::expr_fn::{
            exists, in_subquery, out_ref_col, scalar_subquery,
        };
        use datafusion::logical_expr::{Expr, LogicalPlanBuilder, Operator, col, lit};

        let schema = Arc::new(DFSchema::new_with_metadata(
            [
                ("left", "id"),
                ("right", "id"),
                ("left", "Price"),
                ("left", "price"),
            ]
            .into_iter()
            .map(|(relation, name)| {
                (
                    Some(TableReference::bare(relation)),
                    Arc::new(Field::new(name, DataType::Int64, false)),
                )
            })
            .collect(),
            crate::compat::Metadata::new(),
        )?);
        let inner = Arc::new(
            LogicalPlanBuilder::empty(true)
                .project(vec![lit(7_i64).alias("id")])?
                .alias("left")?
                .filter(col("left.id").gt(out_ref_col(DataType::Int64, "right.id")))?
                .project(vec![col("left.id")])?
                .build()?,
        );
        let scalar = scalar_subquery(Arc::clone(&inner));
        let Expr::ScalarSubquery(subquery) = scalar.clone() else {
            unreachable!()
        };
        for (expr, expected) in [
            (scalar, vec![1]),
            (exists(Arc::clone(&inner)), vec![1]),
            (in_subquery(col("left.id"), inner), vec![0, 1]),
            (
                Expr::SetComparison(SetComparison::new(
                    Box::new(col("left.id")),
                    subquery,
                    Operator::Eq,
                    SetQuantifier::Any,
                )),
                vec![0, 1],
            ),
        ] {
            assert_eq!(super::required_output_indices(&schema, &[expr]), expected);
        }
        assert_eq!(
            super::required_output_indices(
                &schema,
                &[
                    out_ref_col(DataType::Int64, Column::new(Some("left"), "Price")),
                    out_ref_col(DataType::Int64, Column::new(Some("missing"), "id")),
                ]
            ),
            vec![2]
        );
        let uncorrelated = Arc::new(
            LogicalPlanBuilder::empty(true)
                .project(vec![lit(1_i64).alias("id")])?
                .alias("left")?
                .build()?,
        );
        assert!(
            super::required_output_indices(&schema, &[scalar_subquery(uncorrelated)])
                .is_empty()
        );
        Ok(())
    }
}

#[cfg(test)]
mod expr_rebasing_tests {
    use super::*;
    use datafusion::arrow::datatypes::{DataType, Field, Schema};
    use datafusion::common::{ExprSchema, ScalarValue};
    use datafusion::functions_window::lead_lag::lag_udwf;
    use datafusion::logical_expr::{ExprSchemable, col, lit};

    #[test]
    fn bindings_distinguish_nan_payloads() {
        let first = col("qty") + lit(f64::from_bits(0x7ff8_0000_0000_0001));
        let second = col("qty") + lit(f64::from_bits(0x7ff8_0000_0000_0002));
        assert_eq!(format!("{first:?}"), format!("{second:?}"));
        let mut bindings = ExprBindings::new(&DFSchema::empty(), []);
        let column = bindings.register(first.clone());
        assert_eq!(bindings.register(first), column);
        assert_ne!(bindings.register(second), column);
        assert_eq!(bindings.into_named_exprs().len(), 2);
    }

    #[test]
    fn bindings_preserve_types_qualifiers_and_first_seen_order() -> Result<()> {
        let schema = DFSchema::try_from(Schema::new(vec![Field::new(
            "__mr_expr_0",
            DataType::Int64,
            false,
        )]))?;
        let expressions = [
            col("right.qty") + lit(2_i64),
            col("left.qty") + lit(2_i64),
            col("right.qty") + lit(2_i32),
            col("right.qty") - lit(2_i64),
        ];
        let names = ["__mr_expr_0__", "__mr_expr_1", "__mr_expr_2", "__mr_expr_3"];
        let mut bindings = ExprBindings::new(&schema, ["__mr_expr_0_"]);
        for (expr, name) in expressions.iter().zip(names) {
            assert_eq!(bindings.register(expr.clone()), Column::from_name(name));
        }
        let first = Column::from_name(names[0]);
        assert_eq!(bindings.register(expressions[0].clone()), first);
        assert_eq!(bindings.column(&expressions[0])?, first);
        assert_eq!(bindings.rebase(&expressions[0])?, Expr::Column(first));
        assert_eq!(
            bindings.into_named_exprs(),
            expressions
                .into_iter()
                .zip(names)
                .map(|(expr, name)| NamedExpr {
                    name: name.into(),
                    expr
                })
                .collect::<Vec<_>>()
        );
        Ok(())
    }

    #[test]
    fn bindings_distinguish_equal_display_names_and_preserve_columns() -> Result<()> {
        let input = LogicalPlanBuilder::values(vec![vec![lit(7_i64), lit(9_i64)]])?
            .project(vec![
                col("column1").alias("x"),
                col("column2").alias("__mr_expr_0"),
            ])?
            .alias("t")?
            .build()?;
        let plain = lag_udwf().call(vec![col("t.x"), lit(1_u64), lit(ScalarValue::Null)]);
        let cast = lag_udwf().call(vec![
            col("t.x").cast_to(&DataType::Float64, input.schema())?,
            lit(1_u64),
            lit(ScalarValue::Null),
        ]);
        assert_eq!(
            plain.schema_name().to_string(),
            cast.schema_name().to_string()
        );
        let (plan, mut bindings) = materialize_windows(
            input,
            &[plain.clone(), cast.clone(), plain.clone()],
            ["__mr_expr_0_"],
        )?;
        let plain_column = bindings.column(&plain)?;
        let cast_column = bindings.column(&cast)?;
        assert_ne!(plain_column, cast_column);
        for column in [&plain_column, &cast_column] {
            assert!(!["__mr_expr_0", "__mr_expr_0_"].contains(&column.name.as_str()));
        }
        assert_eq!(
            plan.schema().field_from_column(&plain_column)?.data_type(),
            &DataType::Int64
        );
        assert_eq!(
            plan.schema().field_from_column(&cast_column)?.data_type(),
            &DataType::Float64
        );
        let LogicalPlan::Window(window) = &plan else {
            panic!("expected window")
        };
        assert_eq!(
            window.window_expr.len(),
            2,
            "repeated expressions share one output"
        );
        let direct = col("t.x");
        assert_eq!(bindings.bind(direct.clone()), direct);
        assert_eq!(bindings.rebase(&direct)?, direct);
        assert_eq!(
            bindings.rebase(&(plain + cast))?,
            Expr::Column(plain_column) + Expr::Column(cast_column)
        );
        assert_eq!(bindings.into_named_exprs().len(), 2);
        Ok(())
    }

    #[test]
    fn masked_match_navigation_guards_values_and_preserves_metadata() -> Result<()> {
        use crate::compat::{Metadata, MetadataExt};
        use crate::core::MAX_VALID_MATCH_SEQUENCE_NUMBER;
        use crate::functions::udwf::{
            mr_first_udwf, mr_last_udwf, mr_next_udwf, mr_prev_udwf,
        };
        use crate::planning::logical::is_matched_expr;
        use datafusion::logical_expr::{EmptyRelation, expr::Cast};

        let schema = Arc::new(DFSchema::try_from(Schema::new(vec![
            Field::new("denom", DataType::Int64, false),
            Field::new("mask", DataType::Boolean, true),
            Field::new(
                MatchMetadataColumn::Classifier.as_ref(),
                DataType::Utf8,
                true,
            ),
            Field::new(
                MatchMetadataColumn::MatchSequenceNumber.as_ref(),
                DataType::Int64,
                true,
            ),
            Field::new(
                MatchMetadataColumn::MatchNumber.as_ref(),
                DataType::Int64,
                true,
            ),
        ]))?);
        let input = LogicalPlan::EmptyRelation(EmptyRelation {
            produce_one_row: false,
            schema,
        });
        let metadata = Metadata::new().with("unit", "widgets");
        let fallible = Expr::Cast(Cast::new_from_field(
            Box::new(lit(1_i64) / col("denom")),
            Arc::new(Field::new("value", DataType::Int64, true).with_metadata(metadata)),
        ));
        for function in [
            mr_first_udwf(),
            mr_last_udwf(),
            mr_prev_udwf(),
            mr_next_udwf(),
        ] {
            let shift = function == mr_prev_udwf() || function == mr_next_udwf();
            for with_offset in [false, true] {
                for (value, needs_guard) in [
                    (fallible.clone(), true),
                    (datafusion::functions::math::random().call(vec![]), true),
                    (col("denom"), false),
                    (lit(42_i64), false),
                ] {
                    let mut args = vec![value.clone()];
                    if shift {
                        args.extend([lit(u64::from(with_offset)), lit(99_i64)]);
                        if with_offset {
                            args.extend([lit(true), lit(0_u64)]);
                        }
                    } else if with_offset {
                        args.push(lit(1_u64));
                    }
                    args.push(col("mask"));
                    let expected_args = args.clone();
                    let Expr::WindowFunction(mut window) = function.call(args) else {
                        unreachable!()
                    };
                    window.params.partition_by = vec![Expr::Column(Column::from_name(
                        MatchMetadataColumn::MatchNumber.as_ref(),
                    ))];
                    window.params.window_frame = causal_window_frame();
                    let original = Expr::WindowFunction(window);
                    let expected_field = original.to_field(input.schema().as_ref())?.1;
                    let (plan, bindings) = materialize_windows(
                        input.clone(),
                        std::slice::from_ref(&original),
                        [],
                    )?;
                    let actual_field = plan
                        .schema()
                        .field_from_column(&bindings.column(&original)?)?;
                    assert_eq!(actual_field.data_type(), expected_field.data_type());
                    assert_eq!(actual_field.is_nullable(), expected_field.is_nullable());
                    assert_eq!(actual_field.metadata(), expected_field.metadata());
                    let LogicalPlan::Window(window) = &plan else {
                        panic!("window plan")
                    };
                    let Expr::Alias(alias) = &window.window_expr[0] else {
                        panic!("window alias")
                    };
                    let Expr::WindowFunction(actual) = alias.expr.as_ref() else {
                        panic!("window expression")
                    };
                    assert_eq!(actual.params.args[1..], expected_args[1..]);
                    assert!(actual.params.filter.is_none());
                    if needs_guard {
                        let guarded = &actual.params.args[0];
                        assert_eq!(
                            guarded.metadata(input.schema())?,
                            value.metadata(input.schema())?
                        );
                        let guarded = match guarded {
                            Expr::Alias(alias) => alias.expr.as_ref(),
                            other => other,
                        };
                        let guard = if shift && with_offset {
                            let sequence =
                                col(MatchMetadataColumn::MatchSequenceNumber.as_ref());
                            let halo = if function == mr_prev_udwf() {
                                sequence.lt(lit(1_i64))
                            } else {
                                sequence.gt(lit(MAX_VALID_MATCH_SEQUENCE_NUMBER))
                            };
                            is_matched_expr().or(col(
                                MatchMetadataColumn::MatchNumber.as_ref()
                            )
                            .is_not_null()
                            .and(halo))
                        } else {
                            col("mask")
                        };
                        assert_eq!(
                            guarded,
                            &Expr::Case(Case::new(
                                None,
                                vec![(Box::new(guard), Box::new(value))],
                                None,
                            ))
                        );
                    } else {
                        let expected = crate::compat::window_plan(
                            input.clone(),
                            bindings.aliased_expressions_from(0),
                        )?;
                        assert_eq!(
                            plan, expected,
                            "discardable values keep the original plan"
                        );
                    }
                }
            }
        }
        Ok(())
    }

    #[test]
    fn match_edge_guards_require_a_mask_and_match_partition() -> Result<()> {
        use crate::functions::udwf::{mr_first_udwf, mr_last_udwf};

        let input = LogicalPlanBuilder::values(vec![vec![lit(7_i64)]])?
            .project(vec![
                col("column1").alias("denom"),
                lit(true).alias("mask"),
                lit(1_i64).alias(MatchMetadataColumn::MatchNumber.as_ref()),
            ])?
            .build()?;
        for function in [mr_first_udwf(), mr_last_udwf()] {
            for match_scoped in [false, true] {
                let value = lit(1_i64) / col("denom");
                let args = if match_scoped {
                    vec![value]
                } else {
                    vec![value, col("mask")]
                };
                let Expr::WindowFunction(mut window) = function.call(args) else {
                    unreachable!()
                };
                if match_scoped {
                    window.params.partition_by = vec![Expr::Column(Column::from_name(
                        MatchMetadataColumn::MatchNumber.as_ref(),
                    ))];
                }
                let original = Expr::WindowFunction(window);
                let (plan, bindings) =
                    materialize_windows(input.clone(), &[original], [])?;
                let expected = crate::compat::window_plan(
                    input.clone(),
                    bindings.aliased_expressions_from(0),
                )?;
                assert_eq!(plan, expected);
            }
        }
        Ok(())
    }

    #[test]
    fn aliased_windows_retain_filter_and_nesting_errors() -> Result<()> {
        let input = LogicalPlanBuilder::values(vec![vec![lit(7_i64)]])?.build()?;
        let plain =
            lag_udwf().call(vec![col("column1"), lit(1_u64), lit(ScalarValue::Null)]);
        let Expr::WindowFunction(mut filtered) = plain.clone() else {
            unreachable!()
        };
        filtered.params.filter = Some(Box::new(lit(true)));
        let nested = lag_udwf().call(vec![plain, lit(1_u64), lit(ScalarValue::Null)]);
        for (expr, expected) in [
            (
                Expr::WindowFunction(filtered),
                "FILTER clause can only be used with aggregate window functions",
            ),
            (nested, "Window function calls cannot be nested"),
        ] {
            let error = match materialize_windows(input.clone(), &[expr], []) {
                Err(error) => error,
                Ok(_) => panic!("invalid window was accepted"),
            };
            assert!(error.to_string().contains(expected), "{error}");
        }
        Ok(())
    }

    #[test]
    fn rebase_non_literal_preserves_literals_while_rebasing_computed_keys() -> Result<()>
    {
        let mut bindings = ExprBindings::new(&DFSchema::empty(), []);
        let lit_expr = lit("a");
        let computed = col("price") + lit(1_i64);
        let lit_col = bindings.register(lit_expr.clone());
        let computed_col = bindings.register(computed.clone());

        assert_eq!(bindings.rebase(&lit_expr)?, Expr::Column(lit_col));
        assert_eq!(bindings.rebase_non_literal(&lit_expr)?, lit_expr);
        assert_eq!(
            bindings.rebase_non_literal(&computed)?,
            Expr::Column(computed_col.clone())
        );
        let get_field_call =
            datafusion::functions::core::get_field().call(vec![col("s"), lit("a")]);
        assert_eq!(
            bindings.rebase_non_literal(&get_field_call)?,
            get_field_call
        );
        assert_eq!(
            bindings.rebase_non_literal(&(computed + lit("a")))?,
            Expr::Column(computed_col) + lit("a")
        );
        Ok(())
    }
}