datafusion-match-recognize 0.56.1

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

//! Consuming NFA seal and the public `CompiledAutomaton` type.
//!
//! The sibling modules compile individual pattern constructs. This module takes
//! ownership of their private draft graph, resolves symbols, builds compact
//! transition tables, computes graph metadata, and exposes the immutable
//! finished automaton.

use super::cost::{self, PatternCompileLimits};
use crate::core::{NormalizedPattern, Pattern, PatternAnalysisSummary, Symbol, SymbolId};
use crate::nfa::compiler::{
    DraftAutomaton, DraftLoopBackEdge, DraftPossessiveDecisionEdge, DraftState,
    DraftSymbolTransition, NfaBuilder,
};
use datafusion::common::{DataFusionError, HashMap, Result};
use std::{mem::size_of, sync::Arc};

use crate::nfa::types::{
    AnchorPredicate, AutomatonStateId, EpsilonTransition, NFA, PackedRows,
    PossessiveTransitionControl, StateDescriptor,
};

// Numeric transition slot zero is the reserved Empty symbol/program slot.
// Epsilon edges are stored separately. Runtime path symbols use the remaining
// u16 domain, so sealing rejects a wider table.
const MAX_COMPILED_USER_SYMBOLS: usize = u16::MAX as usize;
const FIRST_USER_SYMBOL_ID: usize = 1;

// Lane admission uses logical graph weights rather than compiler or runtime
// struct layouts, keeping execution-route selection independent of storage
// representation.
const LANE_ADMISSION_STATE_WEIGHT_BYTES: usize = 232;
// Dense rows carry a logical three-machine-word admission weight independent
// of their physical packed representation.
const LANE_ADMISSION_DENSE_ROW_WEIGHT_BYTES: usize = 3 * size_of::<usize>();

mod required;
use required::RequiredSymbols;
pub use required::{MAX_REQUIRED_ANCHORS, RequiredAnchor};
mod retained;

mod reachability;
use reachability::compute_reachable_symbols;

/// Resolved fixed prefix/suffix info with symbol IDs for path reconstruction.
///
/// Fixed segments contain resolved symbol IDs and strictly positive counts.
/// Each side's row total is checked during compilation and equals the sum of
/// its counts.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CompactPrefixSuffixInfo {
    /// (symbol_id, count) pairs for the fixed prefix.
    prefix: Vec<(SymbolId, usize)>,
    /// The variable middle symbol ID.
    middle_symbol_id: SymbolId,
    /// (symbol_id, count) pairs for the fixed suffix.
    suffix: Vec<(SymbolId, usize)>,
    /// Total number of rows consumed by the fixed prefix.
    prefix_rows: usize,
    /// Total number of rows consumed by the fixed suffix.
    suffix_rows: usize,
    /// Minimum rows for the middle part.
    middle_min_rows: usize,
}

impl CompactPrefixSuffixInfo {
    /// Fixed symbol/count pairs before the variable middle.
    #[inline]
    pub fn prefix(&self) -> &[(SymbolId, usize)] {
        &self.prefix
    }

    /// Symbol assigned to the variable-length middle.
    #[inline]
    pub const fn middle_symbol(&self) -> SymbolId {
        self.middle_symbol_id
    }

    /// Fixed symbol/count pairs after the variable middle.
    #[inline]
    pub fn suffix(&self) -> &[(SymbolId, usize)] {
        &self.suffix
    }

    /// Number of rows consumed by the fixed prefix.
    #[inline]
    pub const fn prefix_rows(&self) -> usize {
        self.prefix_rows
    }

    /// Number of rows consumed by the fixed suffix.
    #[inline]
    pub const fn suffix_rows(&self) -> usize {
        self.suffix_rows
    }

    /// Minimum rows consumed by the variable middle.
    #[inline]
    pub const fn middle_min_rows(&self) -> usize {
        self.middle_min_rows
    }
}

/// Graph shape that can reconstruct a path from its row bounds.
///
/// This is a structural property only. Execution decides whether a query may
/// actually use compact storage after considering skip behavior, predicate
/// evaluation, managed state, and runtime configuration.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CompactPathShape {
    /// Every consumed row belongs to the same symbol.
    Single(SymbolId),
    /// One variable-length symbol is surrounded by fixed-width segments.
    PrefixSuffix(CompactPrefixSuffixInfo),
}

/// Reachable row contexts with distinct anchor truth values.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AnchorEnvironment {
    /// A physical input row other than the first row.
    PhysicalInterior,
    /// The first physical input row, where the start anchor is true.
    PhysicalStart,
    /// The virtual position after the final physical row, where the end anchor
    /// is true.
    VirtualEnd,
    /// The sole virtual position in an empty input, where both anchors are true.
    VirtualStartEndEmpty,
}

impl AnchorEnvironment {
    const fn index(self) -> usize {
        self as usize
    }

    const fn matches(self, predicate: Option<AnchorPredicate>) -> bool {
        match predicate {
            None => true,
            Some(AnchorPredicate::StartOfInput) => {
                matches!(self, Self::PhysicalStart | Self::VirtualStartEndEmpty)
            }
            Some(AnchorPredicate::EndOfInput) => {
                matches!(self, Self::VirtualEnd | Self::VirtualStartEndEmpty)
            }
        }
    }
}

#[derive(Debug, Clone, Copy)]
struct AnchorState {
    dispatch_start: usize,
    closure_transition_bitmap: u64,
    first_accepting: Option<AutomatonStateId>,
    accepting_rank: Option<usize>,
}

#[derive(Debug)]
struct AnchorClosureTable {
    states: Box<[AnchorState]>,
    dispatch: Box<[AutomatonStateId]>,
}

#[derive(Debug)]
struct AnchorProgram([AnchorClosureTable; 4]);

/// Compiled, thread-safe automaton for a normalized `MATCH_RECOGNIZE` pattern.
///
/// The automaton owns graph structure and structural facts only. Source
/// identity, output clauses, evaluator requirements, and runtime policy belong
/// to execution.
#[derive(Debug)]
pub struct CompiledAutomaton {
    id_to_symbol: Vec<Option<String>>,
    nfa: NFA,
    /// Loop-end metadata shared by precomputed and row-dependent closures.
    loop_back_edges: Box<[LoopBackEdge]>,
    min_match_rows: usize,
    required: RequiredSymbols,
    max_match_rows: Option<usize>,
    has_anchors: bool,
    has_end_anchor: bool,
    anchored_at_end: bool,
    has_mandatory_start_anchor_prefix: bool,
    has_alternations: bool,
    compact_path_shape: Option<CompactPathShape>,

    /// Reachable-symbol bitmaps for domains of at most 64 slots. Wider domains
    /// cannot prove thread equivalence through a bitmap and retain no table.
    reachable_symbols: Option<Arc<[u64]>>,
    /// Transition bitmap reachable from each state via unconditional epsilon closure.
    ///
    /// Used by the executor to cheaply test whether a possessive continue branch
    /// can match the current row without recomputing closure reachability.
    unconditional_closure_transition_bitmap: Arc<[u64]>,
    /// First accepting state in each ordered unconditional epsilon closure.
    ///
    /// Anchor-aware execution uses separate construction-time closure tables.
    /// Unanchored execution uses this table for the corresponding lookup.
    unconditional_first_accepting_state: Arc<[Option<AutomatonStateId>]>,
    /// Acceptance's insertion position among ordered consuming outcomes.
    unconditional_accepting_rank: Box<[Option<usize>]>,
    anchor_program: Option<AnchorProgram>,
}

impl CompiledAutomaton {
    /// Compile a normalized pattern over the complete declared symbol domain.
    ///
    /// Each name in `declared_symbols` must occur at most once.
    ///
    /// Uses default limits; see [`Self::compile_with_limits`] for constraints and errors.
    #[cfg(any(test, feature = "internal-bench"))]
    pub fn compile(
        pattern: &NormalizedPattern,
        declared_symbols: &[String],
    ) -> Result<Self> {
        Self::compile_with_limits(
            pattern,
            declared_symbols,
            PatternCompileLimits::default(),
        )
    }

    /// Compile a normalized pattern with caller-provided resource limits.
    ///
    /// `declared_symbols` supplies the stable symbol domain, including symbols
    /// removed by normalization. Each name must occur at most once.
    /// Possessive markers are accepted as optimizer-proven row-local controls;
    /// this compiler does not validate the proof or implement general atomic
    /// repetition for caller-supplied composite, nullable, or anchored bodies.
    /// Source admission rejects caller-supplied possessive markers before this
    /// stage.
    ///
    /// # Errors
    ///
    /// Returns an error for undeclared pattern symbols, an oversized symbol
    /// domain, or compilation that exceeds the configured limits.
    pub fn compile_with_limits(
        pattern: &NormalizedPattern,
        declared_symbols: &[String],
        limits: PatternCompileLimits,
    ) -> Result<Self> {
        validate_user_symbol_count(declared_symbols)?;
        let symbol_mappings = resolve_symbol_mappings(declared_symbols)?;
        match pattern {
            NormalizedPattern::Ast(pattern) => {
                Self::compile_ast(pattern, symbol_mappings, limits)
            }
            NormalizedPattern::Never => Self::compile_never(symbol_mappings, limits),
            NormalizedPattern::Epsilon => {
                Self::compile_ast(&Pattern::Concat(Vec::new()), symbol_mappings, limits)
            }
        }
    }

    fn compile_ast(
        pattern: &Pattern,
        symbol_mappings: SymbolMappings,
        limits: PatternCompileLimits,
    ) -> Result<Self> {
        let num_symbols = symbol_mappings.id_to_symbol.len();
        cost::validate_pattern_compile_cost(pattern, num_symbols, limits)?;
        let metadata = pattern.analysis_summary();
        let structural = metadata.structural_info();
        let mut required = if structural.min_match_rows() > 0 {
            required::analyze(pattern, &symbol_mappings)
        } else {
            RequiredSymbols::default()
        };
        // The whole-partition singleton filter only binds complete packed domains.
        if num_symbols > 65 {
            required.mask = 0;
        }
        let facts = AutomatonStructuralFacts {
            min_match_rows: structural.min_match_rows(),
            required,
            max_match_rows: structural.max_match_rows(),
            has_anchors: structural.has_anchors(),
            has_end_anchor: pattern.has_end_anchor(),
            anchored_at_end: structural.anchored_at_end(),
            has_mandatory_start_anchor_prefix: has_mandatory_start_anchor_prefix(pattern),
            compact_path_shape: analyze_compact_path_shape(&symbol_mappings, &metadata),
        };
        let sealed = seal_draft_graph(
            NfaBuilder::build(pattern, limits)?,
            &symbol_mappings,
            limits,
            facts.has_anchors,
        )?;
        Ok(Self::from_sealed(symbol_mappings, sealed, facts))
    }

    fn compile_never(
        symbol_mappings: SymbolMappings,
        limits: PatternCompileLimits,
    ) -> Result<Self> {
        let draft = NfaBuilder::build_never(limits, "never".to_owned())?;

        let sealed = seal_draft_graph(draft, &symbol_mappings, limits, false)?;
        Ok(Self::from_sealed(
            symbol_mappings,
            sealed,
            AutomatonStructuralFacts {
                // Preserve the established routing behavior: a graph that can
                // never accept is not treated as an empty-match graph.
                min_match_rows: 1,
                required: RequiredSymbols::default(),
                max_match_rows: Some(0),
                has_anchors: false,
                has_end_anchor: false,
                anchored_at_end: false,
                has_mandatory_start_anchor_prefix: false,
                compact_path_shape: None,
            },
        ))
    }

    fn from_sealed(
        symbol_mappings: SymbolMappings,
        sealed: SealedGraphArtifacts,
        facts: AutomatonStructuralFacts,
    ) -> Self {
        Self {
            id_to_symbol: symbol_mappings.id_to_symbol,
            nfa: sealed.nfa,
            loop_back_edges: sealed.loop_back_edges,
            min_match_rows: facts.min_match_rows,
            required: facts.required,
            max_match_rows: facts.max_match_rows,
            has_anchors: facts.has_anchors,
            has_end_anchor: facts.has_end_anchor,
            anchored_at_end: facts.anchored_at_end,
            has_mandatory_start_anchor_prefix: facts.has_mandatory_start_anchor_prefix,
            has_alternations: sealed.graph_analysis.has_alternations,
            compact_path_shape: facts.compact_path_shape,
            reachable_symbols: sealed.reachable_symbols.map(Into::into),
            unconditional_closure_transition_bitmap: sealed
                .graph_analysis
                .unconditional_closure_transition_bitmap
                .into(),
            unconditional_first_accepting_state: sealed
                .graph_analysis
                .unconditional_first_accepting_state
                .into(),
            unconditional_accepting_rank: sealed
                .graph_analysis
                .unconditional_accepting_rank
                .into_boxed_slice(),
            anchor_program: sealed.anchor_program,
        }
    }

    /// Loop-back edges indexed by sealed state ID.
    pub(crate) fn loop_back_edges(&self) -> &[LoopBackEdge] {
        &self.loop_back_edges
    }

    /// User-symbol membership bits required on every accepting path. A missing
    /// bit can exclude a match only after inspecting its entire readable input.
    /// Zero means no absence proof is available.
    pub fn required_symbols_mask(&self) -> u64 {
        self.required.mask
    }

    /// Positional membership clauses that hold for every accepting path.
    pub fn required_anchors(&self) -> &[RequiredAnchor] {
        &self.required.anchors
    }

    /// Returns the total number of symbols, including the Empty placeholder.
    pub fn num_symbols(&self) -> usize {
        self.id_to_symbol.len()
    }

    /// Iterator over `(symbol_id, name)` pairs for user-defined symbols.
    pub fn symbols_iter(&self) -> impl Iterator<Item = (SymbolId, &str)> + '_ {
        let slots = self.num_symbols();
        self.id_to_symbol
            .iter()
            .enumerate()
            .skip(1) // skip Empty placeholder (id 0)
            .filter_map(move |(index, name)| {
                SymbolId::try_new(index, slots).zip(name.as_deref())
            })
    }

    /// Returns the minimum number of rows consumed by any possible match.
    #[inline]
    pub const fn min_match_rows(&self) -> usize {
        self.min_match_rows
    }

    /// Returns the maximum number of rows this pattern can match, if bounded.
    ///
    /// `None` indicates the pattern can match an unbounded number of rows.
    #[inline]
    pub const fn max_match_rows(&self) -> Option<usize> {
        self.max_match_rows
    }

    /// Returns `true` if the pattern contains any anchors (^ or $).
    #[inline]
    pub const fn has_anchors(&self) -> bool {
        self.has_anchors
    }

    #[inline]
    fn anchor_table(&self, environment: AnchorEnvironment) -> &AnchorClosureTable {
        &self
            .anchor_program
            .as_ref()
            .expect("anchored compiled patterns have precomputed closure tables")
            .0[environment.index()]
    }

    /// Ordered row-consuming states in the anchor-aware epsilon closure.
    #[inline]
    pub fn anchor_dispatch_closure(
        &self,
        environment: AnchorEnvironment,
        state_id: AutomatonStateId,
    ) -> &[AutomatonStateId] {
        let table = self.anchor_table(environment);
        let index = state_id.index();
        let start = table.states[index].dispatch_start;
        let end = table.states[index + 1].dispatch_start;
        &table.dispatch[start..end]
    }

    /// First accepting state in the anchor-aware epsilon closure.
    #[inline]
    pub fn anchor_first_accepting_state(
        &self,
        environment: AnchorEnvironment,
        state_id: AutomatonStateId,
    ) -> Option<AutomatonStateId> {
        self.anchor_table(environment).states[state_id.index()].first_accepting
    }

    /// Transition bitmap reachable from `state_id` via its epsilon closure in
    /// `environment` (or unconditional closure when `environment` is `None`).
    #[inline]
    pub fn closure_transition_bitmap(
        &self,
        environment: Option<AnchorEnvironment>,
        state_id: AutomatonStateId,
    ) -> u64 {
        match environment {
            Some(environment) => {
                self.anchor_table(environment).states[state_id.index()]
                    .closure_transition_bitmap
            }
            None => self.unconditional_closure_transition_bitmap[state_id.index()],
        }
    }

    /// Convert a consuming dispatch offset into its sink-inclusive rank.
    ///
    /// Dispatch omits acceptance, so offsets after the accepting insertion
    /// position need one extra rank. Lane uses this to mark edges that follow
    /// acceptance without scanning the dispatch list.
    #[inline]
    pub fn dispatch_preference_rank(
        &self,
        parent: AutomatonStateId,
        environment: Option<AnchorEnvironment>,
        offset: usize,
    ) -> usize {
        let accepting_rank = self.accepting_preference_rank(parent, environment);
        offset + usize::from(accepting_rank.is_some_and(|rank| rank <= offset))
    }

    /// Rank of accepting now among the parent's ordered next outcomes.
    #[inline]
    pub fn accepting_preference_rank(
        &self,
        parent: AutomatonStateId,
        environment: Option<AnchorEnvironment>,
    ) -> Option<usize> {
        match environment {
            Some(environment) => {
                self.anchor_table(environment).states[parent.index()].accepting_rank
            }
            None => self.unconditional_accepting_rank[parent.index()],
        }
    }

    /// Returns `true` if any pattern branch contains an end-of-partition anchor.
    #[inline]
    pub fn has_end_anchor(&self) -> bool {
        self.has_end_anchor
    }

    /// Returns whether every viable suffix is structurally end-anchored.
    #[inline]
    pub const fn anchored_at_end(&self) -> bool {
        self.anchored_at_end
    }

    /// Returns whether matching is forced to start at the partition boundary.
    #[inline]
    pub const fn has_mandatory_start_anchor_prefix(&self) -> bool {
        self.has_mandatory_start_anchor_prefix
    }

    /// Returns the dense symbol-name table.
    pub fn id_to_symbol(&self) -> &[Option<String>] {
        &self.id_to_symbol
    }

    /// Returns the compiled NFA.
    pub fn nfa(&self) -> &NFA {
        &self.nfa
    }

    /// Whether compilation constructed an alternative or repetition
    /// choice that requires preference-sensitive routing and deduplication.
    ///
    /// A singleton alternative retains this flag for established routing;
    /// exact repetitions and discarded zero-count bodies introduce no choice.
    #[inline]
    pub const fn has_alternations(&self) -> bool {
        self.has_alternations
    }

    /// Returns the graph's compact reconstruction shape, when one exists.
    #[inline]
    pub fn compact_path_shape(&self) -> Option<&CompactPathShape> {
        self.compact_path_shape.as_ref()
    }

    /// Returns transition bitmaps for unconditional epsilon closures.
    pub fn unconditional_closure_transition_bitmap(&self) -> &[u64] {
        &self.unconditional_closure_transition_bitmap
    }

    /// Returns the first accepting state in each unconditional epsilon closure.
    pub fn unconditional_first_accepting_state(
        &self,
    ) -> &Arc<[Option<AutomatonStateId>]> {
        &self.unconditional_first_accepting_state
    }
}

#[cfg(test)]
mod normalized_compile_tests;

struct SymbolMappings {
    id_to_symbol: Vec<Option<String>>,
    symbol_to_id: HashMap<String, SymbolId>,
    normalized_symbol_to_id: HashMap<String, SymbolId>,
}

struct GraphAnalysis {
    has_alternations: bool,
    unconditional_closure_transition_bitmap: Vec<u64>,
    unconditional_first_accepting_state: Vec<Option<AutomatonStateId>>,
    unconditional_accepting_rank: Vec<Option<usize>>,
}

struct AutomatonStructuralFacts {
    min_match_rows: usize,
    required: RequiredSymbols,
    max_match_rows: Option<usize>,
    has_anchors: bool,
    has_end_anchor: bool,
    anchored_at_end: bool,
    has_mandatory_start_anchor_prefix: bool,
    compact_path_shape: Option<CompactPathShape>,
}

struct SealedGraphArtifacts {
    nfa: NFA,
    loop_back_edges: Box<[LoopBackEdge]>,
    graph_analysis: GraphAnalysis,
    anchor_program: Option<AnchorProgram>,
    reachable_symbols: Option<Vec<u64>>,
}

struct ClosureWork {
    unconditional: Vec<Vec<usize>>,
    retained_entries: usize,
}

struct PackedStateBuffers {
    states: Vec<StateDescriptor>,
    transition_offsets: Vec<usize>,
    transition_targets: Vec<AutomatonStateId>,
    epsilon_offsets: Vec<usize>,
    epsilon_transitions: Vec<EpsilonTransition>,
    dispatch_offsets: Vec<usize>,
    dispatch_targets: Vec<AutomatonStateId>,
}

impl PackedStateBuffers {
    fn new(
        state_count: usize,
        dense_transition_cells: usize,
        pattern_display: &str,
    ) -> Result<Self> {
        let transition_offset_count = dense_transition_cells
            .checked_add(1)
            .ok_or_else(source_payload_overflow)?;
        let state_offset_count = state_count
            .checked_add(1)
            .ok_or_else(source_payload_overflow)?;
        let mut transition_offsets = reserved_vec(
            transition_offset_count,
            "transition offsets",
            pattern_display,
        )?;
        let mut epsilon_offsets =
            reserved_vec(state_offset_count, "epsilon offsets", pattern_display)?;
        let mut dispatch_offsets =
            reserved_vec(state_offset_count, "dispatch offsets", pattern_display)?;
        transition_offsets.push(0);
        epsilon_offsets.push(0);
        dispatch_offsets.push(0);
        Ok(Self {
            states: reserved_vec(state_count, "state descriptors", pattern_display)?,
            transition_offsets,
            transition_targets: Vec::new(),
            epsilon_offsets,
            epsilon_transitions: Vec::new(),
            dispatch_offsets,
            dispatch_targets: Vec::new(),
        })
    }
}

fn reserved_vec<T>(
    capacity: usize,
    resource: &str,
    pattern_display: &str,
) -> Result<Vec<T>> {
    let mut values = Vec::new();
    values.try_reserve_exact(capacity).map_err(|error| {
        DataFusionError::ResourcesExhausted(format!(
            "MATCH_RECOGNIZE NFA {resource} allocation failed while compiling pattern {pattern_display}: {error}"
        ))
    })?;
    Ok(values)
}

fn reserve_additional<T>(
    values: &mut Vec<T>,
    additional: usize,
    resource: &str,
    pattern_display: &str,
) -> Result<()> {
    values.try_reserve(additional).map_err(|error| {
        DataFusionError::ResourcesExhausted(format!(
            "MATCH_RECOGNIZE NFA {resource} allocation failed while compiling pattern {pattern_display}: {error}"
        ))
    })
}

fn seal_draft_graph(
    draft: DraftAutomaton,
    symbol_mappings: &SymbolMappings,
    limits: PatternCompileLimits,
    has_anchors: bool,
) -> Result<SealedGraphArtifacts> {
    let num_symbols = symbol_mappings.id_to_symbol.len();
    validate_draft_targets(&draft)?;
    let state_count = draft.states.len();
    let loop_back_edges = build_loop_back_edge_table(
        &draft.loop_back_edges,
        state_count,
        &draft.pattern_display,
    )?;
    let closures = compute_epsilon_closures(
        &draft,
        &loop_back_edges,
        limits,
        &draft.pattern_display,
    )?;
    // Acceptance ranks retain one entry per state. Keep their storage inside
    // the same budget as retained closure data.
    let mut retained_entries = closures.retained_entries;
    charge_closure_entries(
        &mut retained_entries,
        state_count,
        limits,
        &draft.pattern_display,
    )?;
    let dense_transition_cells = cost::validate_dense_transition_cells(
        state_count,
        num_symbols,
        limits,
        &draft.pattern_display,
    )?;

    let DraftAutomaton {
        states,
        start_state,
        possessive_decisions,
        has_choices,
        pattern_display,
        .. // Loop-back edges were resolved into the retained table above.
    } = draft;
    let mut has_row_transition =
        reserved_vec(state_count, "row-transition flags", &pattern_display)?;
    for state in &states {
        has_row_transition.push(state.symbol_transition.is_some());
    }

    let mut packed =
        PackedStateBuffers::new(state_count, dense_transition_cells, &pattern_display)?;
    for (index, state) in states.into_iter().enumerate() {
        reserve_additional(
            &mut packed.dispatch_targets,
            closures.unconditional[index].len(),
            "unconditional dispatch targets",
            &pattern_display,
        )?;
        for &target in &closures.unconditional[index] {
            if has_row_transition[target] {
                packed
                    .dispatch_targets
                    .push(AutomatonStateId::from_validated(target, state_count));
            }
        }
        packed.dispatch_offsets.push(packed.dispatch_targets.len());
        materialize_compiled_state(
            state,
            symbol_mappings,
            num_symbols,
            state_count,
            &pattern_display,
            &mut packed,
        )?;
    }

    let source_payload_floor_bytes = source_payload_floor_bytes(
        state_count,
        num_symbols,
        packed.transition_targets.len(),
        packed.dispatch_targets.len(),
    )?;
    let possessive_transition_controls = build_possessive_transition_controls(
        possessive_decisions,
        state_count,
        &pattern_display,
    )?;
    let start_state = AutomatonStateId::from_validated(start_state, state_count);
    let nfa = NFA::new(
        packed.states,
        num_symbols,
        PackedRows::new(packed.transition_offsets, packed.transition_targets),
        PackedRows::new(packed.epsilon_offsets, packed.epsilon_transitions),
        PackedRows::new(packed.dispatch_offsets, packed.dispatch_targets),
        possessive_transition_controls,
        start_state,
        source_payload_floor_bytes,
    );
    let graph_analysis = analyze_nfa_graph(
        &nfa,
        &closures.unconditional,
        &has_row_transition,
        has_choices,
    );
    let anchor_program = if has_anchors {
        let context = AnchorTableContext {
            nfa: &nfa,
            has_row_transition: &has_row_transition,
            loop_back_edges: &loop_back_edges,
            limits,
            pattern_display: &pattern_display,
        };
        Some(build_anchor_program(&context, retained_entries)?)
    } else {
        None
    };
    let reachable_symbols = if num_symbols <= u64::BITS as usize {
        Some(compute_reachable_symbols(
            &nfa,
            num_symbols,
            closures.unconditional,
            has_row_transition,
        ))
    } else {
        None
    };

    Ok(SealedGraphArtifacts {
        nfa,
        loop_back_edges: loop_back_edges.into_boxed_slice(),
        graph_analysis,
        anchor_program,
        reachable_symbols,
    })
}

fn build_possessive_transition_controls(
    decisions: Vec<DraftPossessiveDecisionEdge>,
    state_count: usize,
    pattern_display: &str,
) -> Result<PackedRows<PossessiveTransitionControl>> {
    let offset_count = state_count
        .checked_add(1)
        .ok_or_else(source_payload_overflow)?;
    let mut offsets =
        reserved_vec(offset_count, "possessive control offsets", pattern_display)?;
    let mut cursors =
        reserved_vec(state_count, "possessive control cursors", pattern_display)?;
    cursors.resize(state_count, 0usize);
    for decision in &decisions {
        cursors[decision.from_state] = cursors[decision.from_state]
            .checked_add(1)
            .ok_or_else(source_payload_overflow)?;
    }

    offsets.push(0);
    let mut next = 0usize;
    for count in &mut cursors {
        let row_start = next;
        next = next
            .checked_add(*count)
            .ok_or_else(source_payload_overflow)?;
        *count = row_start;
        offsets.push(next);
    }

    let zero = AutomatonStateId::from_validated(0, state_count);
    let placeholder = PossessiveTransitionControl::new(zero, zero);
    let mut controls =
        reserved_vec(decisions.len(), "possessive controls", pattern_display)?;
    controls.resize(decisions.len(), placeholder);
    for decision in decisions {
        let slot = cursors[decision.from_state];
        cursors[decision.from_state] =
            slot.checked_add(1).ok_or_else(source_payload_overflow)?;
        let continue_state =
            AutomatonStateId::from_validated(decision.continue_state, state_count);
        let exit_state =
            AutomatonStateId::from_validated(decision.exit_state, state_count);
        controls[slot] = PossessiveTransitionControl::new(continue_state, exit_state);
    }
    Ok(PackedRows::new(offsets, controls))
}

fn validate_user_symbol_count(symbols: &[String]) -> Result<()> {
    if symbols.len() > MAX_COMPILED_USER_SYMBOLS {
        return Err(DataFusionError::Plan(format!(
            "MATCH_RECOGNIZE pattern declares {} user symbols, but this implementation supports at most {}",
            symbols.len(),
            MAX_COMPILED_USER_SYMBOLS
        )));
    }
    Ok(())
}

fn resolve_symbol_mappings(symbols: &[String]) -> Result<SymbolMappings> {
    let mut id_to_symbol: Vec<Option<String>> = vec![None];
    let mut symbol_to_id: HashMap<String, SymbolId> = HashMap::new();
    let mut normalized_symbol_to_id: HashMap<String, SymbolId> = HashMap::new();
    let first_user_id = FIRST_USER_SYMBOL_ID;
    let slot_count = symbols.len() + first_user_id;
    for (offset, symbol) in symbols.iter().enumerate() {
        let symbol_id = SymbolId::try_new(first_user_id + offset, slot_count)
            .expect("validated symbol tables have a dense user-symbol domain");
        symbol_to_id.insert(symbol.clone(), symbol_id);
        normalized_symbol_to_id
            .entry(symbol.to_ascii_lowercase())
            .or_insert(symbol_id);
        id_to_symbol.push(Some(symbol.clone()));
    }
    Ok(SymbolMappings {
        id_to_symbol,
        symbol_to_id,
        normalized_symbol_to_id,
    })
}

fn resolve_symbol_id(symbol: &str, symbol_mappings: &SymbolMappings) -> Option<SymbolId> {
    symbol_mappings
        .symbol_to_id
        .get(symbol)
        .copied()
        .or_else(|| {
            symbol_mappings
                .normalized_symbol_to_id
                .get(&symbol.to_ascii_lowercase())
                .copied()
        })
}

fn materialize_compiled_state(
    state: DraftState,
    symbol_mappings: &SymbolMappings,
    num_symbols: usize,
    state_count: usize,
    pattern_display: &str,
    packed: &mut PackedStateBuffers,
) -> Result<()> {
    let DraftState {
        is_accepting,
        symbol_transition,
        epsilon_transitions,
        is_excluded,
    } = state;
    let mut transition_bitmap = 0u64;
    let resolved_transition = if let Some(DraftSymbolTransition { symbol, target }) =
        symbol_transition
    {
        let symbol_id = resolve_symbol_id(&symbol, symbol_mappings).ok_or_else(|| {
            DataFusionError::Plan(format!(
                "MATCH_RECOGNIZE pattern symbol '{symbol}' is not declared in the pattern symbol list"
            ))
        })?;
        if symbol_id.index() < 64 {
            transition_bitmap |= 1 << symbol_id.index();
        }
        Some((symbol_id.index(), target))
    } else {
        None
    };

    // Each draft state has at most one consuming edge. Offsets before its
    // symbol share the old target length; that symbol and later slots share
    // the new length. The full offset table was reserved before materialization.
    let offset_start = packed.transition_offsets.len();
    if let Some((symbol_index, target)) = resolved_transition {
        packed
            .transition_offsets
            .resize(offset_start + symbol_index, packed.transition_targets.len());
        reserve_additional(
            &mut packed.transition_targets,
            1,
            "transition targets",
            pattern_display,
        )?;
        packed
            .transition_targets
            .push(AutomatonStateId::from_validated(target, state_count));
    }
    packed
        .transition_offsets
        .resize(offset_start + num_symbols, packed.transition_targets.len());

    reserve_additional(
        &mut packed.epsilon_transitions,
        epsilon_transitions.len(),
        "epsilon transitions",
        pattern_display,
    )?;
    for transition in epsilon_transitions {
        packed.epsilon_transitions.push(EpsilonTransition::new(
            AutomatonStateId::from_validated(transition.target, state_count),
            transition.predicate,
        ));
    }
    packed
        .epsilon_offsets
        .push(packed.epsilon_transitions.len());

    packed.states.push(StateDescriptor::new(
        is_accepting,
        is_excluded,
        transition_bitmap,
    ));
    Ok(())
}

fn checked_state_id(
    index: usize,
    state_count: usize,
    context: &str,
) -> Result<AutomatonStateId> {
    AutomatonStateId::try_new(index, state_count).ok_or_else(|| {
        DataFusionError::Internal(format!(
            "MATCH_RECOGNIZE {context} references NFA state {index} outside a table of {state_count} states"
        ))
    })
}

fn validate_draft_targets(draft: &DraftAutomaton) -> Result<()> {
    let state_count = draft.states.len();
    checked_state_id(draft.start_state, state_count, "start state")?;
    // Paths retain only the destination ID, so every consumed target needs one source.
    let mut sources =
        reserved_vec(state_count, "symbol sources", &draft.pattern_display)?;
    sources.resize(state_count, None);
    for (index, state) in draft.states.iter().enumerate() {
        if let Some(transition) = &state.symbol_transition {
            checked_state_id(transition.target, state_count, "symbol transition")?;
            let source = AutomatonStateId::from_validated(index, state_count);
            if let Some(previous) = sources[transition.target].replace(source) {
                return Err(DataFusionError::Internal(format!(
                    "MATCH_RECOGNIZE consumed target {} has different symbol sources {previous} and {source} while compiling pattern {}",
                    transition.target, draft.pattern_display
                )));
            }
        }
        for transition in &state.epsilon_transitions {
            checked_state_id(transition.target, state_count, "epsilon transition")?;
        }
    }
    for decision in &draft.possessive_decisions {
        checked_state_id(decision.from_state, state_count, "possessive source")?;
        checked_state_id(
            decision.continue_state,
            state_count,
            "possessive continuation",
        )?;
        checked_state_id(decision.exit_state, state_count, "possessive exit")?;
    }
    for edge in &draft.loop_back_edges {
        checked_state_id(edge.from_state, state_count, "loop back-edge source")?;
        checked_state_id(edge.continue_state, state_count, "loop back-edge target")?;
    }
    Ok(())
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum LoopBackEdge {
    None,
    Standard(usize),
    Possessive(usize),
}

impl LoopBackEdge {
    pub(crate) fn is_back_edge_to(self, target: usize) -> bool {
        matches!(self, Self::Standard(t) | Self::Possessive(t) if t == target)
    }

    pub(crate) fn is_possessive(self) -> bool {
        matches!(self, Self::Possessive(_))
    }
}

fn build_loop_back_edge_table(
    edges: &[DraftLoopBackEdge],
    state_count: usize,
    pattern_display: &str,
) -> Result<Vec<LoopBackEdge>> {
    let mut table = reserved_vec(state_count, "loop back-edges", pattern_display)?;
    table.resize(state_count, LoopBackEdge::None);
    for edge in edges {
        let entry = if edge.is_possessive {
            LoopBackEdge::Possessive(edge.continue_state)
        } else {
            LoopBackEdge::Standard(edge.continue_state)
        };
        if table[edge.from_state] != LoopBackEdge::None {
            return Err(DataFusionError::Internal(format!(
                "MATCH_RECOGNIZE loop state {} has multiple loop back-edges while compiling pattern {pattern_display}",
                edge.from_state
            )));
        }
        table[edge.from_state] = entry;
    }
    Ok(table)
}

#[derive(Clone, Copy)]
enum ClosureFrame {
    Enter(usize),
    Finish(usize),
}

struct ClosureTraversal<'a> {
    seen: Vec<usize>,
    finished: Vec<usize>,
    on_stack: Vec<usize>,
    stack: Vec<ClosureFrame>,
    generation: usize,
    retained: usize,
    loop_back_edges: &'a [LoopBackEdge],
    limits: PatternCompileLimits,
    pattern_display: &'a str,
}

impl<'a> ClosureTraversal<'a> {
    fn new(
        state_count: usize,
        retained: usize,
        loop_back_edges: &'a [LoopBackEdge],
        limits: PatternCompileLimits,
        pattern_display: &'a str,
    ) -> Result<Self> {
        let mut seen = reserved_vec(state_count, "closure seen marks", pattern_display)?;
        seen.resize(state_count, 0);
        let mut finished =
            reserved_vec(state_count, "closure finished marks", pattern_display)?;
        finished.resize(state_count, 0);
        let mut on_stack =
            reserved_vec(state_count, "closure stack marks", pattern_display)?;
        on_stack.resize(state_count, 0);
        Ok(Self {
            seen,
            finished,
            on_stack,
            stack: Vec::new(),
            generation: 0,
            retained,
            loop_back_edges,
            limits,
            pattern_display,
        })
    }

    fn charge(&mut self, entries: usize) -> Result<()> {
        charge_closure_entries(
            &mut self.retained,
            entries,
            self.limits,
            self.pattern_display,
        )
    }

    fn push_frame(&mut self, frame: ClosureFrame) -> Result<()> {
        reserve_additional(&mut self.stack, 1, "closure stack", self.pattern_display)?;
        self.stack.push(frame);
        Ok(())
    }

    fn visit_closure<I>(
        &mut self,
        start_state: usize,
        edges: impl Fn(usize) -> I,
        mut on_visit: impl FnMut(usize) -> Result<usize>,
    ) -> Result<()>
    where
        I: DoubleEndedIterator<Item = (usize, bool)>,
    {
        self.generation += 1;
        let generation = self.generation;
        debug_assert!(self.stack.is_empty());
        self.push_frame(ClosureFrame::Enter(start_state))?;

        while let Some(frame) = self.stack.pop() {
            match frame {
                ClosureFrame::Finish(id) => {
                    self.on_stack[id] -= 1;
                    self.finished[id] = generation;
                }
                ClosureFrame::Enter(id) => {
                    // Finished states and possessive loop-end re-entries do not
                    // re-expand or jump past pending continue branches.
                    if self.finished[id] == generation
                        || (self.loop_back_edges[id].is_possessive()
                            && self.on_stack[id] > 0)
                    {
                        continue;
                    }
                    // Charge every non-skipped expansion, including cycle
                    // re-entries, so nested nullable loops cannot outrun
                    // `max_epsilon_closure_entries` in pops or stack depth.
                    self.charge(1)?;
                    if self.seen[id] != generation {
                        self.seen[id] = generation;
                        let extra_entries = on_visit(id)?;
                        if extra_entries != 0 {
                            self.charge(extra_entries)?;
                        }
                    }

                    self.on_stack[id] += 1;
                    self.push_frame(ClosureFrame::Finish(id))?;

                    // A LIFO stack needs reverse pushes to visit preferred edges first.
                    for (target, matched) in edges(id).rev() {
                        if matched
                            && !(self.loop_back_edges[id].is_back_edge_to(target)
                                && self.on_stack[target] > 0)
                            && self.finished[target] != generation
                        {
                            self.push_frame(ClosureFrame::Enter(target))?;
                        }
                    }
                }
            }
        }
        Ok(())
    }
}

fn compute_epsilon_closures(
    draft: &DraftAutomaton,
    loop_back_edges: &[LoopBackEdge],
    limits: PatternCompileLimits,
    pattern_display: &str,
) -> Result<ClosureWork> {
    let state_count = draft.states.len();
    let mut traversal =
        ClosureTraversal::new(state_count, 0, loop_back_edges, limits, pattern_display)?;
    let mut closures =
        reserved_vec(state_count, "unconditional closures", pattern_display)?;

    for state_id in 0..state_count {
        let mut unconditional = Vec::new();
        traversal.visit_closure(
            state_id,
            |id| {
                draft.states[id]
                    .epsilon_transitions
                    .iter()
                    .map(|t| (t.target, t.predicate.is_none()))
            },
            |id| {
                reserve_additional(
                    &mut unconditional,
                    1,
                    "unconditional closure",
                    pattern_display,
                )?;
                unconditional.push(id);
                Ok(0)
            },
        )?;

        // Retain DFS encounter order; numeric state order is not preference.
        closures.push(unconditional);
    }
    Ok(ClosureWork {
        unconditional: closures,
        retained_entries: traversal.retained,
    })
}

fn source_payload_floor_bytes(
    state_count: usize,
    symbol_slot_count: usize,
    transition_target_count: usize,
    dispatch_target_count: usize,
) -> Result<usize> {
    let state_bytes = LANE_ADMISSION_STATE_WEIGHT_BYTES
        .checked_mul(state_count)
        .ok_or_else(source_payload_overflow)?;
    let dense_row_count = state_count
        .checked_mul(symbol_slot_count)
        .ok_or_else(source_payload_overflow)?;
    let dense_row_bytes = LANE_ADMISSION_DENSE_ROW_WEIGHT_BYTES
        .checked_mul(dense_row_count)
        .ok_or_else(source_payload_overflow)?;
    let target_count = transition_target_count
        .checked_add(dispatch_target_count)
        .ok_or_else(source_payload_overflow)?;
    let target_bytes = size_of::<usize>()
        .checked_mul(target_count)
        .ok_or_else(source_payload_overflow)?;
    state_bytes
        .checked_add(dense_row_bytes)
        .and_then(|bytes| bytes.checked_add(target_bytes))
        .ok_or_else(source_payload_overflow)
}

fn source_payload_overflow() -> DataFusionError {
    DataFusionError::ResourcesExhausted(
        "MATCH_RECOGNIZE lane source payload exceeds usize".into(),
    )
}

struct AnchorTableContext<'a> {
    nfa: &'a NFA,
    has_row_transition: &'a [bool],
    loop_back_edges: &'a [LoopBackEdge],
    limits: PatternCompileLimits,
    pattern_display: &'a str,
}

fn build_anchor_program(
    ctx: &AnchorTableContext<'_>,
    retained: usize,
) -> Result<AnchorProgram> {
    use AnchorEnvironment::*;
    let mut traversal = ClosureTraversal::new(
        ctx.nfa.state_count(),
        retained,
        ctx.loop_back_edges,
        ctx.limits,
        ctx.pattern_display,
    )?;
    Ok(AnchorProgram([
        build_anchor_table(ctx, PhysicalInterior, &mut traversal)?,
        build_anchor_table(ctx, PhysicalStart, &mut traversal)?,
        build_anchor_table(ctx, VirtualEnd, &mut traversal)?,
        build_anchor_table(ctx, VirtualStartEndEmpty, &mut traversal)?,
    ]))
}

fn build_anchor_table(
    ctx: &AnchorTableContext<'_>,
    environment: AnchorEnvironment,
    traversal: &mut ClosureTraversal<'_>,
) -> Result<AnchorClosureTable> {
    let nfa = ctx.nfa;
    let state_count = nfa.state_count();
    let state_entries = state_count.checked_add(1).ok_or_else(|| {
        DataFusionError::ResourcesExhausted(
            "MATCH_RECOGNIZE epsilon-closure entry count overflow".into(),
        )
    })?;
    traversal.charge(state_entries)?;
    let mut states = reserved_vec(state_entries, "anchor states", ctx.pattern_display)?;
    let mut dispatch = Vec::new();
    let state_of = |idx| {
        let id = nfa
            .state_id(idx)
            .expect("anchor traversal uses checked sealed state IDs");
        (id, nfa.state(id))
    };
    for state_id in 0..state_count {
        let mut first_accepting = None;
        let mut accepting_rank = None;
        let mut closure_transition_bitmap = 0u64;
        let dispatch_start = dispatch.len();
        traversal.visit_closure(
            state_id,
            |id| {
                state_of(id).1.epsilon_transitions().iter().map(move |t| {
                    (t.target().index(), environment.matches(t.predicate()))
                })
            },
            |current| {
                let (current_id, current_state) = state_of(current);
                if current_state.is_accepting() && first_accepting.is_none() {
                    first_accepting = Some(current_id);
                    accepting_rank = Some(dispatch.len() - dispatch_start);
                }
                let has_row = ctx.has_row_transition[current];
                if has_row {
                    closure_transition_bitmap |= current_state.transition_bitmap();
                    reserve_additional(
                        &mut dispatch,
                        1,
                        "anchor dispatch targets",
                        ctx.pattern_display,
                    )?;
                    dispatch.push(current_id);
                }
                Ok(usize::from(has_row))
            },
        )?;
        states.push(AnchorState {
            dispatch_start,
            closure_transition_bitmap,
            first_accepting,
            accepting_rank,
        });
    }
    states.push(AnchorState {
        dispatch_start: dispatch.len(),
        closure_transition_bitmap: 0,
        first_accepting: None,
        accepting_rank: None,
    });
    Ok(AnchorClosureTable {
        states: states.into_boxed_slice(),
        dispatch: dispatch.into_boxed_slice(),
    })
}

fn charge_closure_entries(
    retained: &mut usize,
    entries: usize,
    limits: PatternCompileLimits,
    pattern_display: &str,
) -> Result<()> {
    *retained = retained.checked_add(entries).ok_or_else(|| {
        DataFusionError::ResourcesExhausted(
            "MATCH_RECOGNIZE epsilon-closure entry count overflow".into(),
        )
    })?;
    if *retained > limits.max_epsilon_closure_entries {
        return cost::compile_cost_err(
            cost::METRIC_EPSILON_CLOSURE_ENTRIES,
            *retained,
            limits.max_epsilon_closure_entries,
            pattern_display,
        );
    }
    Ok(())
}

fn analyze_nfa_graph(
    nfa: &NFA,
    unconditional_closures: &[Vec<usize>],
    has_row_transition: &[bool],
    has_choices: bool,
) -> GraphAnalysis {
    let mut unconditional_closure_transition_bitmap = vec![0u64; nfa.state_count()];
    let mut unconditional_first_accepting_state = vec![None; nfa.state_count()];
    let mut unconditional_accepting_rank = vec![None; nfa.state_count()];

    for (index, closure) in unconditional_closures.iter().enumerate() {
        let mut bitmap = 0u64;
        let mut first_accepting = None;
        let mut accepting_rank = None;
        let mut dispatch_count = 0;
        for &sid in closure {
            let id = nfa
                .state_id(sid)
                .expect("sealed closure contains checked state IDs");
            bitmap |= nfa.state(id).transition_bitmap();
            if first_accepting.is_none() && nfa.state(id).is_accepting() {
                first_accepting = Some(id);
                accepting_rank = Some(dispatch_count);
            }
            dispatch_count += usize::from(has_row_transition[sid]);
        }
        unconditional_closure_transition_bitmap[index] = bitmap;
        unconditional_first_accepting_state[index] = first_accepting;
        unconditional_accepting_rank[index] = accepting_rank;
    }
    GraphAnalysis {
        has_alternations: has_choices,
        unconditional_closure_transition_bitmap,
        unconditional_first_accepting_state,
        unconditional_accepting_rank,
    }
}

fn analyze_compact_path_shape(
    symbol_mappings: &SymbolMappings,
    pattern_metadata: &PatternAnalysisSummary,
) -> Option<CompactPathShape> {
    let structural_info = pattern_metadata.structural_info();
    if structural_info.has_anchors()
        || structural_info.has_exclusions()
        || structural_info.can_match_empty()
    {
        return None;
    }

    if let Some(symbol) = pattern_metadata
        .compact_single_symbol_name()
        .and_then(|name| resolve_symbol_id(name, symbol_mappings))
    {
        return Some(CompactPathShape::Single(symbol));
    }

    let info = pattern_metadata.fixed_prefix_suffix_structure()?;
    let resolve_segments = |segments: &[(String, usize)]| {
        let mut resolved = Vec::new();
        for (name, count) in segments {
            let id = resolve_symbol_id(name, symbol_mappings)?;
            if *count != 0 {
                resolved.push((id, *count));
            }
        }
        Some(resolved)
    };
    let prefix = resolve_segments(&info.prefix)?;
    let middle_symbol_id = resolve_symbol_id(&info.middle, symbol_mappings)?;
    let suffix = resolve_segments(&info.suffix)?;
    Some(CompactPathShape::PrefixSuffix(CompactPrefixSuffixInfo {
        prefix,
        middle_symbol_id,
        suffix,
        prefix_rows: info.prefix_rows,
        suffix_rows: info.suffix_rows,
        middle_min_rows: info.middle_min_rows,
    }))
}

fn has_mandatory_start_anchor_prefix(pattern: &Pattern) -> bool {
    match pattern {
        Pattern::Symbol(Symbol::Start) => true,
        Pattern::Group(inner) => has_mandatory_start_anchor_prefix(inner),
        Pattern::Concat(patterns) => patterns
            .first()
            .is_some_and(has_mandatory_start_anchor_prefix),
        Pattern::Repetition(inner, quantifier) => {
            quantifier.bounds().fixed_count() == Some(1)
                && has_mandatory_start_anchor_prefix(inner)
        }
        Pattern::Symbol(Symbol::Named(_) | Symbol::End)
        | Pattern::Exclude(_)
        | Pattern::Permute(_)
        | Pattern::Alternation(_) => false,
    }
}

impl CompiledAutomaton {
    /// Check if any symbols in the supplied bitmap are reachable from this state.
    /// Used to gate comparisons of state needed by future predicates.
    /// Conservatively returns true when the symbol domain does not fit a bitmap
    /// or the state is outside this automaton.
    #[inline]
    pub fn has_reachable_symbols(
        &self,
        state_id: AutomatonStateId,
        symbols_bitmap: u64,
    ) -> bool {
        self.reachable_symbols
            .as_ref()
            .and_then(|reachable| reachable.get(state_id.index()))
            .is_none_or(|reachable| *reachable & symbols_bitmap != 0)
    }
}

#[cfg(test)]
mod finalization_tests;

#[cfg(test)]
mod closure_budget_tests {
    use super::*;
    use crate::core::RepetitionQuantifier;

    fn nested_nullable_loop(depth: usize) -> Pattern {
        let mut pattern = Pattern::Repetition(
            Box::new(Pattern::Symbol(Symbol::Named("A".into()))),
            RepetitionQuantifier::AtMostOneReluctant,
        );
        for _ in 0..depth {
            pattern =
                Pattern::Repetition(Box::new(pattern), RepetitionQuantifier::ZeroOrMore);
        }
        pattern
    }

    #[test]
    fn nested_nullable_loop_reentry_pops_are_charged_against_closure_budget() {
        let symbols = vec!["A".to_string()];

        let unanchored = NormalizedPattern::Ast(nested_nullable_loop(12));
        let compiled = CompiledAutomaton::compile_with_limits(
            &unanchored,
            &symbols,
            PatternCompileLimits::default(),
        )
        .expect("nested nullable loop compiles within the default closure budget");
        let states = compiled.nfa().state_count();
        // Charging only first visits (at most `states * states`) plus retained
        // accepting ranks (`states`) would always stay at or below this bound.
        let first_visit_upper_bound = states * states + states;
        let err = CompiledAutomaton::compile_with_limits(
            &unanchored,
            &symbols,
            PatternCompileLimits {
                max_epsilon_closure_entries: first_visit_upper_bound,
                ..PatternCompileLimits::default()
            },
        )
        .expect_err("re-entry pops must exceed the first-visit-only upper bound");
        let expected = format!(
            "{} {} > {}",
            cost::METRIC_EPSILON_CLOSURE_ENTRIES,
            first_visit_upper_bound + 1,
            first_visit_upper_bound
        );
        assert!(
            matches!(&err, DataFusionError::Plan(message) if message.contains(&expected)),
            "expected closure budget error containing `{expected}`, got {err:?}"
        );

        let anchored = NormalizedPattern::Ast(Pattern::Concat(vec![
            Pattern::Symbol(Symbol::Start),
            nested_nullable_loop(8),
        ]));
        let compiled = CompiledAutomaton::compile_with_limits(
            &anchored,
            &symbols,
            PatternCompileLimits::default(),
        )
        .expect("anchored nested nullable loop compiles within the default budget");
        let states = compiled.nfa().state_count();
        // Upper bound if unconditional closure and all four anchor tables only
        // charged first visits, dispatch targets, and state/rank tables.
        let anchored_first_visit_bound =
            states * states + states + 4 * ((states + 1) + 2 * states * states);
        let err = CompiledAutomaton::compile_with_limits(
            &anchored,
            &symbols,
            PatternCompileLimits {
                max_epsilon_closure_entries: anchored_first_visit_bound,
                ..PatternCompileLimits::default()
            },
        )
        .expect_err("anchor closure re-entry pops must also be charged");
        assert!(
            matches!(
                &err,
                DataFusionError::Plan(message)
                    if message.contains(cost::METRIC_EPSILON_CLOSURE_ENTRIES)
            ),
            "expected anchor closure budget error, got {err:?}"
        );
    }
}