quamina 0.4.1

Fast pattern-matching library for filtering JSON events
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
//! Mutable pattern matchers for single-threaded pattern building.
//!
//! This module contains the mutable (RefCell-based) matchers used during pattern building:
//! - `MutableFieldMatcher`: Mutable field matcher with RefCell-based interior mutability
//! - `MutableValueMatcher`: Mutable value matcher with singleton optimization
//! - `CoreMatcher`: Single-threaded core matcher that builds and matches patterns

use std::cell::{Cell, RefCell};
use std::collections::{HashMap, HashSet};
use std::rc::Rc;
use std::sync::Arc;

use super::arena::{
    insert_string_into_arena, insert_suffix_into_arena, make_anything_but_arena_fa,
    make_cidr_arena_fa, make_monocase_arena_fa, make_numeric_greater_arena_fa,
    make_numeric_less_arena_fa, make_numeric_range_arena_fa, make_prefix_arena_fa,
    make_shellstyle_arena_fa, make_string_arena_fa, make_suffix_dfa, make_wildcard_arena_fa,
    merge_arena_nfas, traverse_arena_dfa, traverse_arena_dfa_backward, traverse_arena_nfa,
    ArenaNfaBuffers, StateArena, StateId,
};
use super::small_table::{FieldMatcher, NfaBuffers};
use crate::regexp::make_regexp_nfa_arena;

/// Wrap a byte slice in quotes: `val` → `"val"`.
///
/// Used by `add_transition()` to wrap string pattern values so that
/// the automaton can distinguish strings from numbers. Event values
/// from the flattener retain their JSON quotes, so pattern FAs must
/// also include quotes to match correctly.
#[inline]
fn quote_wrap(val: &[u8]) -> Vec<u8> {
    let mut result = Vec::with_capacity(val.len() + 2);
    result.push(b'"');
    result.extend_from_slice(val);
    result.push(b'"');
    result
}

/// A condition NFA for lookaround verification.
///
/// Each condition is an automaton that must match (or not match, if negative)
/// the full value for the overall pattern to succeed.
#[derive(Clone, Debug)]
pub struct ConditionNfa {
    pub arena: StateArena,
    pub start: StateId,
    /// True for negative conditions ((?!...) or (?<!...))
    pub is_negative: bool,
}

/// Arena NFA with conditions for multi-condition patterns (lookarounds).
///
/// The primary automaton is matched first. If it produces transitions,
/// all conditions are verified against the full value.
#[derive(Clone)]
pub struct MultiConditionNfa {
    pub primary_arena: StateArena,
    pub primary_start: StateId,
    /// Field matcher pointer for transition mapping
    pub field_matcher_ptr: *const FieldMatcher,
    /// Conditions to verify after primary matches
    pub conditions: Vec<ConditionNfa>,
}

/// Build a combined pattern for lookbehind verification.
///
/// For `(?<=foo)bar`: lookbehind="foo", primary="bar" -> combined="foobar"
/// The combined pattern is used to check if the full value matches.
fn build_lookbehind_combined_pattern(
    lookbehind: &crate::regexp::RegexpRoot,
    primary: &crate::regexp::RegexpRoot,
) -> crate::regexp::RegexpRoot {
    use crate::regexp::RegexpBranch;

    // Handle empty cases
    if lookbehind.is_empty() {
        return primary.clone();
    }
    if primary.is_empty() {
        return lookbehind.clone();
    }

    // Simple case: single branch in each
    if lookbehind.len() == 1 && primary.len() == 1 {
        let mut combined: RegexpBranch = lookbehind[0].clone();
        combined.extend(primary[0].clone());
        return vec![combined];
    }

    // Complex case: alternation in one or both
    // Create all combinations: (lb1|lb2)(p1|p2) -> lb1p1|lb1p2|lb2p1|lb2p2
    let mut combined_branches = Vec::new();
    for lb_branch in lookbehind {
        for p_branch in primary {
            let mut combined: RegexpBranch = lb_branch.clone();
            combined.extend(p_branch.clone());
            combined_branches.push(combined);
        }
    }
    combined_branches
}

/// A mutable field matcher used during pattern building.
/// This is similar to Go's fieldMatcher with its updateable atomic pointer.
#[derive(Default)]
pub struct MutableFieldMatcher<X: Clone + Eq + std::hash::Hash> {
    /// Map from field paths to value matchers
    pub transitions: RefCell<HashMap<String, Rc<MutableValueMatcher<X>>>>,
    /// Pattern identifiers that match when arriving at this state
    pub matches: RefCell<Vec<X>>,
    /// exists:true patterns - map from field path to next field matcher
    pub exists_true: RefCell<HashMap<String, Rc<Self>>>,
    /// exists:false patterns - map from field path to next field matcher
    pub exists_false: RefCell<HashMap<String, Rc<Self>>>,
}

impl<X: Clone + Eq + std::hash::Hash> MutableFieldMatcher<X> {
    pub fn new() -> Self {
        Self {
            transitions: RefCell::new(HashMap::new()),
            matches: RefCell::new(Vec::new()),
            exists_true: RefCell::new(HashMap::new()),
            exists_false: RefCell::new(HashMap::new()),
        }
    }

    /// Add a match identifier to this state
    pub fn add_match(&self, x: X) {
        self.matches.borrow_mut().push(x);
    }

    /// Add an exists transition (true or false)
    pub fn add_exists(&self, exists: bool, path: &str) -> Rc<Self> {
        let map = if exists {
            &self.exists_true
        } else {
            &self.exists_false
        };

        let mut map_borrow = map.borrow_mut();
        if let Some(existing) = map_borrow.get(path) {
            existing.clone()
        } else {
            let new_fm = Rc::new(Self::new());
            map_borrow.insert(path.to_string(), new_fm.clone());
            new_fm
        }
    }

    /// Add a value transition, returns the next field matchers
    pub fn add_transition(
        &self,
        path: &str,
        matchers: &[crate::json::Matcher],
        arena_byte_budget: usize,
    ) -> Result<Vec<Rc<Self>>, crate::QuaminaError> {
        use crate::json::Matcher;

        let mut transitions = self.transitions.borrow_mut();
        let vm = transitions
            .entry(path.to_string())
            .or_insert_with(|| Rc::new(MutableValueMatcher::with_budget(arena_byte_budget)));

        // Check if all matchers are Exact strings - use bulk optimization
        // Note: Exact values are pre-quoted for strings in json.rs value_to_string()
        let all_exact: Vec<&[u8]> = matchers
            .iter()
            .filter_map(|m| match m {
                Matcher::Exact(s) => Some(s.as_bytes()),
                _ => None,
            })
            .collect();

        if all_exact.len() == matchers.len() && all_exact.len() > 1 {
            // All matchers are Exact strings and there's more than one - use bulk method
            let next_fm = vm.add_string_transitions_bulk(&all_exact)?;
            return Ok(vec![next_fm]);
        }

        // Fall back to one-by-one processing
        let mut next_states = Vec::new();
        for matcher in matchers {
            let next_fm = vm.add_transition(matcher)?;
            next_states.push(next_fm);
        }
        Ok(next_states)
    }

    /// Transition on a field value during matching
    pub fn transition_on(
        &self,
        path: &str,
        value: &[u8],
        is_number: bool,
        bufs: &mut NfaBuffers,
    ) -> Vec<Rc<Self>> {
        let transitions = self.transitions.borrow();
        if let Some(vm) = transitions.get(path) {
            vm.transition_on(value, is_number, bufs)
        } else {
            vec![]
        }
    }
}

/// A mutable value matcher used during pattern building.
/// Similar to Go's valueMatcher with singleton optimization and automaton.
pub struct MutableValueMatcher<X: Clone + Eq + std::hash::Hash> {
    /// Optimization: for single exact match, store it directly
    pub(crate) singleton_match: RefCell<Option<Vec<u8>>>,
    /// Transition for singleton match
    pub(crate) singleton_transition: RefCell<Option<Rc<MutableFieldMatcher<X>>>>,
    /// Whether this matcher has numeric patterns (for Q-number conversion)
    pub(crate) has_numbers: Cell<bool>,
    /// Mapping from `Arc<FieldMatcher>` to `Rc<MutableFieldMatcher<X>>`
    /// This bridges the automaton's field transitions to our mutable field matchers
    pub(crate) transition_map: RefCell<HashMap<*const FieldMatcher, Rc<MutableFieldMatcher<X>>>>,
    /// Multi-condition NFAs for lookaround patterns
    /// NOTE: Kept separate from main_arena for lookaround verification
    pub(crate) multi_condition_nfas: RefCell<Vec<MultiConditionNfa>>,
    /// Buffers for arena NFA traversal
    pub(crate) arena_bufs: RefCell<ArenaNfaBuffers>,
    /// Unified arena-based FA for all pattern types
    pub(crate) main_arena: RefCell<Option<(StateArena, StateId)>>,
    /// Whether main_arena contains NFA states (epsilon transitions or spinout).
    /// When false, the fast traverse_arena_dfa path can be used instead of traverse_arena_nfa.
    pub(crate) main_arena_is_nfa: RefCell<bool>,
    /// Separate DFA trie for suffix patterns, traversed backward (right-to-left).
    /// Contains reversed suffix bytes; uses traverse_arena_dfa_backward at match time.
    pub(crate) suffix_arena: RefCell<Option<(StateArena, StateId)>>,
    /// Arena byte budget for pattern complexity limiting
    pub(crate) arena_byte_budget: usize,
}

impl<X: Clone + Eq + std::hash::Hash> Default for MutableValueMatcher<X> {
    fn default() -> Self {
        Self::new()
    }
}

impl<X: Clone + Eq + std::hash::Hash> MutableValueMatcher<X> {
    pub fn new() -> Self {
        Self {
            singleton_match: RefCell::new(None),
            singleton_transition: RefCell::new(None),
            has_numbers: Cell::new(false),
            transition_map: RefCell::new(HashMap::new()),
            multi_condition_nfas: RefCell::new(Vec::new()),
            arena_bufs: RefCell::new(ArenaNfaBuffers::new()),
            main_arena: RefCell::new(None),
            main_arena_is_nfa: RefCell::new(false),
            suffix_arena: RefCell::new(None),
            arena_byte_budget: usize::MAX,
        }
    }

    pub fn with_budget(budget: usize) -> Self {
        Self {
            singleton_match: RefCell::new(None),
            singleton_transition: RefCell::new(None),
            has_numbers: Cell::new(false),
            transition_map: RefCell::new(HashMap::new()),
            multi_condition_nfas: RefCell::new(Vec::new()),
            arena_bufs: RefCell::new(ArenaNfaBuffers::new()),
            main_arena: RefCell::new(None),
            main_arena_is_nfa: RefCell::new(false),
            suffix_arena: RefCell::new(None),
            arena_byte_budget: budget,
        }
    }

    /// Check whether the given arena size exceeds the budget.
    fn check_budget(&self, size: usize) -> Result<(), crate::QuaminaError> {
        if size > self.arena_byte_budget {
            return Err(crate::QuaminaError::PatternTooComplex(format!(
                "automaton byte size ({} bytes) exceeds budget ({} bytes)",
                size, self.arena_byte_budget
            )));
        }
        Ok(())
    }

    /// Check main_arena budget. Call after any in-place arena mutation.
    fn check_main_arena_budget(&self) -> Result<(), crate::QuaminaError> {
        let main = self.main_arena.borrow();
        if let Some((arena, _)) = main.as_ref() {
            self.check_budget(arena.estimated_byte_size())
        } else {
            Ok(())
        }
    }

    /// Helper to merge an arena FA into main_arena.
    /// If main_arena is empty, just set it. Otherwise, merge using merge_arena_nfas.
    /// Checks the arena byte budget before and after merging.
    fn merge_into_main_arena(
        &self,
        new_arena: StateArena,
        new_start: StateId,
    ) -> Result<(), crate::QuaminaError> {
        self.check_budget(new_arena.estimated_byte_size())?;

        let mut main = self.main_arena.borrow_mut();
        if let Some((existing_arena, existing_start)) = main.take() {
            let (merged, merged_start) =
                merge_arena_nfas(&existing_arena, existing_start, &new_arena, new_start);
            let merged_size = merged.estimated_byte_size();
            if merged_size > self.arena_byte_budget {
                // Restore existing arena on failure
                *main = Some((existing_arena, existing_start));
                return Err(crate::QuaminaError::PatternTooComplex(format!(
                    "automaton byte size ({} bytes) exceeds budget ({} bytes)",
                    merged_size, self.arena_byte_budget
                )));
            }
            *main = Some((merged, merged_start));
        } else {
            *main = Some((new_arena, new_start));
        }
        Ok(())
    }

    /// Consume the pending singleton (if any) into a standalone arena.
    /// Returns `Some((arena, start))` if there was a singleton, `None` otherwise.
    /// Registers the singleton's FieldMatcher in transition_map.
    fn take_singleton_as_arena(&self) -> Option<(StateArena, StateId)> {
        if self.singleton_match.borrow().is_none() {
            return None;
        }
        let singleton_val = self.singleton_match.borrow().clone().unwrap();
        let singleton_trans = self.singleton_transition.borrow().clone().unwrap();
        let singleton_arc = Arc::new(FieldMatcher::new());
        self.transition_map
            .borrow_mut()
            .insert(Arc::as_ptr(&singleton_arc), singleton_trans);

        let result = make_string_arena_fa(&singleton_val, singleton_arc);

        *self.singleton_match.borrow_mut() = None;
        *self.singleton_transition.borrow_mut() = None;

        Some(result)
    }

    /// Merge a new arena FA into main_arena, incorporating any pending singleton.
    ///
    /// This is the single entry point for all non-string pattern types
    /// (prefix, shellstyle, wildcard, anything-but, monocase, regexp,
    /// numeric-range, CIDR). It:
    ///   1. Consumes the singleton (if any) into an arena
    ///   2. Merges the singleton arena with the new arena
    ///   3. Merges the result into main_arena (with budget check)
    fn merge_with_singleton(
        &self,
        new_arena: StateArena,
        new_start: StateId,
    ) -> Result<(), crate::QuaminaError> {
        if let Some((singleton_arena, singleton_start)) = self.take_singleton_as_arena() {
            let (merged, merged_start) =
                merge_arena_nfas(&singleton_arena, singleton_start, &new_arena, new_start);
            self.merge_into_main_arena(merged, merged_start)
        } else {
            self.merge_into_main_arena(new_arena, new_start)
        }
    }

    /// Ensure main_arena exists, bootstrapping it from the singleton if needed.
    /// After this call, main_arena is guaranteed to be Some and singleton is cleared.
    fn ensure_main_arena_with_singleton(&self) -> Result<(), crate::QuaminaError> {
        if self.main_arena.borrow().is_some() {
            // Already exists — but if there's a pending singleton, fold it in.
            // Build a standalone arena from the singleton, then merge into main.
            if let Some((singleton_arena, singleton_start)) = self.take_singleton_as_arena() {
                self.merge_into_main_arena(singleton_arena, singleton_start)?;
            }
            return Ok(());
        }

        // No main_arena yet — create one
        if let Some((arena, start)) = self.take_singleton_as_arena() {
            self.check_budget(arena.estimated_byte_size())?;
            *self.main_arena.borrow_mut() = Some((arena, start));
        } else {
            // Create empty arena with a start state
            let mut arena = StateArena::new();
            let start = arena.alloc();
            arena.precompute_epsilon_closures();
            *self.main_arena.borrow_mut() = Some((arena, start));
        }
        Ok(())
    }

    /// Add a transition for a matcher, returns the next field matcher.
    ///
    /// String-based pattern values are wrapped in quotes before building FAs.
    /// This ensures string values (which retain quotes from the flattener) only
    /// match string patterns, not number events with identical digit content.
    pub fn add_transition(
        &self,
        matcher: &crate::json::Matcher,
    ) -> Result<Rc<MutableFieldMatcher<X>>, crate::QuaminaError> {
        use crate::json::Matcher;

        match matcher {
            // Exact values are pre-quoted for strings in json.rs value_to_string().
            // Boolean/null values remain unquoted, matching flattener output.
            Matcher::Exact(s) => self.add_string_transition(s.as_bytes()),
            Matcher::NumericExact(n) => self.add_numeric_transition(*n),
            Matcher::Prefix(s) => {
                // Prefix only needs opening quote — the FA matches prefix then
                // accepts anything after (including closing quote and VT)
                let mut quoted = Vec::with_capacity(s.len() + 1);
                quoted.push(b'"');
                quoted.extend_from_slice(s.as_bytes());
                self.add_prefix_transition(&quoted)
            }
            Matcher::Shellstyle(s) => self.add_shellstyle_transition(&quote_wrap(s.as_bytes())),
            Matcher::Wildcard(s) => self.add_wildcard_transition(&quote_wrap(s.as_bytes())),
            Matcher::AnythingBut(excluded) => {
                let excluded_bytes: Vec<Vec<u8>> =
                    excluded.iter().map(|s| quote_wrap(s.as_bytes())).collect();
                self.add_anything_but_transition(&excluded_bytes)
            }
            Matcher::AnythingButNumeric(excluded) => {
                // Mark as having numbers so values get Q-number conversion
                self.has_numbers.set(true);
                self.add_anything_but_numeric_transition(excluded)
            }
            Matcher::EqualsIgnoreCase(s) => self.add_monocase_transition(&quote_wrap(s.as_bytes())),
            Matcher::ParsedRegexp(ref tree) => self.add_regexp_transition(tree),
            Matcher::MultiCondition(ref mc) => self.add_multi_condition_transition(mc),
            Matcher::Suffix(s) => self.add_suffix_transition(s),
            Matcher::Numeric(cmp) => {
                // Numeric ranges use Q-number ordering in the automaton
                self.has_numbers.set(true);
                self.add_numeric_range_transition(cmp)
            }
            Matcher::Cidr(ref cidr) => self.add_cidr_transition(cidr),
            // Catch-all for any future matcher types
            _ => Ok(Rc::new(MutableFieldMatcher::new())),
        }
    }

    /// Add multiple string transitions.
    ///
    /// All values share the same next field matcher.
    /// Uses in-place arena insertion for O(n*L) total cost instead of O(n²).
    fn add_string_transitions_bulk(
        &self,
        values: &[&[u8]],
    ) -> Result<Rc<MutableFieldMatcher<X>>, crate::QuaminaError> {
        if values.is_empty() {
            return Ok(Rc::new(MutableFieldMatcher::new()));
        }

        // If only one value, use the normal path (singleton optimization)
        if values.len() == 1 {
            return self.add_string_transition(values[0]);
        }

        // Create a shared next state for all new values
        let next_fm = Rc::new(MutableFieldMatcher::new());
        let next_arc = Arc::new(FieldMatcher::new());
        self.transition_map
            .borrow_mut()
            .insert(Arc::as_ptr(&next_arc), next_fm.clone());

        // Ensure main_arena exists (bootstrap with first value if needed)
        self.ensure_main_arena_with_singleton()?;

        {
            let mut main = self.main_arena.borrow_mut();
            let (arena, start) = main.as_mut().unwrap();

            // Insert all values directly into the arena trie
            for val in values {
                insert_string_into_arena(arena, *start, val, next_arc.clone());
            }
            if *self.main_arena_is_nfa.borrow() {
                arena.precompute_epsilon_closures();
            }
        }
        self.check_main_arena_budget()?;

        Ok(next_fm)
    }

    fn add_string_transition(
        &self,
        val: &[u8],
    ) -> Result<Rc<MutableFieldMatcher<X>>, crate::QuaminaError> {
        // Check singleton optimization - only use if no automaton exists yet
        let singleton = self.singleton_match.borrow();
        let singleton_trans = self.singleton_transition.borrow();

        // Check if virgin state (no singleton, no main_arena, no suffix_arena)
        let is_virgin = singleton.is_none()
            && self.main_arena.borrow().is_none()
            && self.suffix_arena.borrow().is_none();

        if is_virgin {
            // Virgin state - use singleton optimization
            drop(singleton);
            drop(singleton_trans);

            let next_fm = Rc::new(MutableFieldMatcher::new());
            *self.singleton_match.borrow_mut() = Some(val.to_vec());
            *self.singleton_transition.borrow_mut() = Some(next_fm.clone());
            return Ok(next_fm);
        }

        // Check if singleton matches
        if let Some(ref existing) = *singleton {
            if existing == val {
                return Ok(singleton_trans.as_ref().unwrap().clone());
            }
        }
        drop(singleton);
        drop(singleton_trans);

        // Need to build arena-based automaton
        let next_fm = Rc::new(MutableFieldMatcher::new());
        let next_arc = Arc::new(FieldMatcher::new());
        // Register the mapping from Arc<FieldMatcher> to Rc<MutableFieldMatcher>
        self.transition_map
            .borrow_mut()
            .insert(Arc::as_ptr(&next_arc), next_fm.clone());

        // Ensure main_arena exists (bootstrap with singleton if needed)
        self.ensure_main_arena_with_singleton()?;

        // Insert directly into the arena trie — O(L) instead of O(arena_size)
        {
            let mut main = self.main_arena.borrow_mut();
            let (arena, start) = main.as_mut().unwrap();
            insert_string_into_arena(arena, *start, val, next_arc);
            if *self.main_arena_is_nfa.borrow() {
                arena.precompute_epsilon_closures();
            }
        }
        self.check_main_arena_budget()?;

        Ok(next_fm)
    }

    /// Add a numeric transition that supports Q-number matching.
    /// Builds both a string FA for the text representation and a Q-number FA.
    fn add_numeric_transition(
        &self,
        num: f64,
    ) -> Result<Rc<MutableFieldMatcher<X>>, crate::QuaminaError> {
        // Mark that this matcher has numeric patterns
        self.has_numbers.set(true);

        let val_str = num.to_string();
        let val = val_str.as_bytes();

        // Get Q-number representation
        let q_num = crate::numbits::q_num_from_f64(num);

        let next_fm = Rc::new(MutableFieldMatcher::new());
        let next_arc = Arc::new(FieldMatcher::new());
        self.transition_map
            .borrow_mut()
            .insert(Arc::as_ptr(&next_arc), next_fm.clone());

        // Ensure main_arena exists (bootstrap with singleton if needed)
        self.ensure_main_arena_with_singleton()?;

        // Insert both representations directly into the arena trie — O(L) each
        {
            let mut main = self.main_arena.borrow_mut();
            let (arena, start) = main.as_mut().unwrap();
            insert_string_into_arena(arena, *start, val, next_arc.clone());
            insert_string_into_arena(arena, *start, &q_num, next_arc);
            if *self.main_arena_is_nfa.borrow() {
                arena.precompute_epsilon_closures();
            }
        }
        self.check_main_arena_budget()?;

        Ok(next_fm)
    }

    fn add_prefix_transition(
        &self,
        prefix: &[u8],
    ) -> Result<Rc<MutableFieldMatcher<X>>, crate::QuaminaError> {
        let next_fm = Rc::new(MutableFieldMatcher::new());
        let next_arc = Arc::new(FieldMatcher::new());
        self.transition_map
            .borrow_mut()
            .insert(Arc::as_ptr(&next_arc), next_fm.clone());

        let (new_arena, new_start) = make_prefix_arena_fa(prefix, next_arc);
        self.merge_with_singleton(new_arena, new_start)?;

        Ok(next_fm)
    }

    fn add_shellstyle_transition(
        &self,
        pattern: &[u8],
    ) -> Result<Rc<MutableFieldMatcher<X>>, crate::QuaminaError> {
        let next_fm = Rc::new(MutableFieldMatcher::new());
        let next_arc = Arc::new(FieldMatcher::new());
        self.transition_map
            .borrow_mut()
            .insert(Arc::as_ptr(&next_arc), next_fm.clone());

        *self.main_arena_is_nfa.borrow_mut() = true;
        let (new_arena, new_start) = make_shellstyle_arena_fa(pattern, next_arc);
        self.merge_with_singleton(new_arena, new_start)?;

        Ok(next_fm)
    }

    /// Add a suffix pattern using a reversed DFA trie.
    ///
    /// Builds reversed bytes: `['"', reversed(suffix)]` (closing quote + reversed suffix).
    /// Inserts into a separate `suffix_arena` that is traversed backward at match time.
    /// This is O(max_suffix_len) instead of the O(value_len * NFA_states) shellstyle approach.
    fn add_suffix_transition(
        &self,
        suffix: &str,
    ) -> Result<Rc<MutableFieldMatcher<X>>, crate::QuaminaError> {
        // If there's a pending singleton, fold it into main_arena first
        // so transition_on doesn't short-circuit past suffix_arena
        if self.singleton_match.borrow().is_some() {
            if let Some((singleton_arena, singleton_start)) = self.take_singleton_as_arena() {
                self.merge_into_main_arena(singleton_arena, singleton_start)?;
            }
        }

        let next_fm = Rc::new(MutableFieldMatcher::new());
        let next_arc = Arc::new(FieldMatcher::new());
        self.transition_map
            .borrow_mut()
            .insert(Arc::as_ptr(&next_arc), next_fm.clone());

        // Build reversed suffix bytes: closing quote + reversed suffix
        let suffix_bytes = suffix.as_bytes();
        let mut reversed = Vec::with_capacity(suffix_bytes.len() + 1);
        reversed.push(b'"'); // closing JSON quote (first byte when scanning backward)
        reversed.extend(suffix_bytes.iter().rev());

        // Insert into suffix arena (separate DFA trie from main_arena)
        let mut suffix_arena = self.suffix_arena.borrow_mut();
        if let Some((ref mut arena, start)) = *suffix_arena {
            insert_suffix_into_arena(arena, start, &reversed, next_arc);
        } else {
            let (arena, start) = make_suffix_dfa(&reversed, next_arc);
            *suffix_arena = Some((arena, start));
        }

        Ok(next_fm)
    }

    fn add_wildcard_transition(
        &self,
        pattern: &[u8],
    ) -> Result<Rc<MutableFieldMatcher<X>>, crate::QuaminaError> {
        let next_fm = Rc::new(MutableFieldMatcher::new());
        let next_arc = Arc::new(FieldMatcher::new());
        self.transition_map
            .borrow_mut()
            .insert(Arc::as_ptr(&next_arc), next_fm.clone());

        *self.main_arena_is_nfa.borrow_mut() = true;
        let (new_arena, new_start) = make_wildcard_arena_fa(pattern, next_arc);
        self.merge_with_singleton(new_arena, new_start)?;

        Ok(next_fm)
    }

    fn add_anything_but_transition(
        &self,
        excluded: &[Vec<u8>],
    ) -> Result<Rc<MutableFieldMatcher<X>>, crate::QuaminaError> {
        let next_fm = Rc::new(MutableFieldMatcher::new());
        let next_arc = Arc::new(FieldMatcher::new());
        self.transition_map
            .borrow_mut()
            .insert(Arc::as_ptr(&next_arc), next_fm.clone());

        let (new_arena, new_start) = make_anything_but_arena_fa(excluded, next_arc);
        self.merge_with_singleton(new_arena, new_start)?;

        Ok(next_fm)
    }

    /// Add a numeric anything-but transition using Q-number FA.
    ///
    /// Matches any numeric value NOT in the excluded list.
    /// Values are compared using Q-number representation for proper numeric ordering.
    fn add_anything_but_numeric_transition(
        &self,
        excluded: &[f64],
    ) -> Result<Rc<MutableFieldMatcher<X>>, crate::QuaminaError> {
        let next_fm = Rc::new(MutableFieldMatcher::new());
        let next_arc = Arc::new(FieldMatcher::new());
        self.transition_map
            .borrow_mut()
            .insert(Arc::as_ptr(&next_arc), next_fm.clone());

        let excluded_q_nums: Vec<Vec<u8>> = excluded
            .iter()
            .map(|&n| crate::numbits::q_num_from_f64(n))
            .collect();

        let (new_arena, new_start) = make_anything_but_arena_fa(&excluded_q_nums, next_arc);
        self.merge_with_singleton(new_arena, new_start)?;

        Ok(next_fm)
    }

    fn add_monocase_transition(
        &self,
        val: &[u8],
    ) -> Result<Rc<MutableFieldMatcher<X>>, crate::QuaminaError> {
        let next_fm = Rc::new(MutableFieldMatcher::new());
        let next_arc = Arc::new(FieldMatcher::new());
        self.transition_map
            .borrow_mut()
            .insert(Arc::as_ptr(&next_arc), next_fm.clone());

        let (new_arena, new_start) = make_monocase_arena_fa(val, next_arc);
        self.merge_with_singleton(new_arena, new_start)?;

        Ok(next_fm)
    }

    fn add_regexp_transition(
        &self,
        tree: &crate::regexp::RegexpRoot,
    ) -> Result<Rc<MutableFieldMatcher<X>>, crate::QuaminaError> {
        let next_fm = Rc::new(MutableFieldMatcher::new());

        let (arena, start, field_matcher_arc) = make_regexp_nfa_arena(tree.clone());
        if arena.is_nondeterministic() {
            *self.main_arena_is_nfa.borrow_mut() = true;
        }

        self.transition_map
            .borrow_mut()
            .insert(Arc::as_ptr(&field_matcher_arc), next_fm.clone());

        self.merge_with_singleton(arena, start)?;

        Ok(next_fm)
    }

    /// Add a multi-condition transition for lookaround patterns.
    ///
    /// Multi-condition patterns have a primary pattern plus conditions (lookarounds):
    /// - Primary pattern is built as an arena NFA
    /// - Condition automata are built for verification during matching
    ///
    /// For lookahead: condition stores combined pattern (AB), build automaton directly.
    /// For lookbehind: condition stores B, combine with primary (A) to get BA.
    fn add_multi_condition_transition(
        &self,
        mc: &crate::json::MultiConditionPattern,
    ) -> Result<Rc<MutableFieldMatcher<X>>, crate::QuaminaError> {
        use crate::json::LookaroundCondition;

        let next_fm = Rc::new(MutableFieldMatcher::new());

        // Build primary pattern automaton (with quote transitions for field values)
        let (primary_arena, primary_start, field_matcher_arc) =
            make_regexp_nfa_arena(mc.primary.clone());

        self.transition_map
            .borrow_mut()
            .insert(Arc::as_ptr(&field_matcher_arc), next_fm.clone());

        // Build condition automata
        let mut condition_nfas = Vec::new();

        for condition in &mc.conditions {
            let (combined_pattern, is_negative) = match condition {
                LookaroundCondition::PositiveLookahead(pattern) => {
                    // Lookahead already stores the combined pattern (primary + lookahead)
                    (pattern.clone(), false)
                }
                LookaroundCondition::NegativeLookahead(pattern) => {
                    // Same as positive, but negative check
                    (pattern.clone(), true)
                }
                LookaroundCondition::PositiveLookbehind { pattern, .. } => {
                    // Lookbehind stores just the prefix pattern, combine with primary
                    // (?<=foo)bar: pattern="foo", primary="bar" -> combined="foobar"
                    let combined = build_lookbehind_combined_pattern(pattern, &mc.primary);
                    (combined, false)
                }
                LookaroundCondition::NegativeLookbehind { pattern, .. } => {
                    // Same as positive, but negative check
                    let combined = build_lookbehind_combined_pattern(pattern, &mc.primary);
                    (combined, true)
                }
            };

            // Build automaton for the combined pattern (with quote transitions)
            let (arena, start, _) = make_regexp_nfa_arena(combined_pattern);
            condition_nfas.push(ConditionNfa {
                arena,
                start,
                is_negative,
            });
        }

        // Check budget for the primary arena and all condition arenas
        self.check_budget(primary_arena.estimated_byte_size())?;
        for cond in &condition_nfas {
            self.check_budget(cond.arena.estimated_byte_size())?;
        }

        // Store in multi_condition_nfas for condition verification during matching
        self.multi_condition_nfas
            .borrow_mut()
            .push(MultiConditionNfa {
                primary_arena,
                primary_start,
                field_matcher_ptr: Arc::as_ptr(&field_matcher_arc),
                conditions: condition_nfas,
            });

        Ok(next_fm)
    }

    /// Add a numeric range transition using arena-based FA for better performance.
    ///
    /// For two-sided ranges (e.g., >= 5, < 100), we build a combined arena FA.
    /// For single-sided ranges (e.g., < 100), we build the relevant arena FA.
    /// Multiple numeric patterns are merged into main_arena using merge_arena_nfas.
    fn add_numeric_range_transition(
        &self,
        cmp: &crate::json::NumericComparison,
    ) -> Result<Rc<MutableFieldMatcher<X>>, crate::QuaminaError> {
        let next_fm = Rc::new(MutableFieldMatcher::new());
        let next_arc = Arc::new(FieldMatcher::new());
        self.transition_map
            .borrow_mut()
            .insert(Arc::as_ptr(&next_arc), next_fm.clone());

        // Build the arena FA based on the comparison operators
        let (new_arena, new_start) = match (&cmp.lower, &cmp.upper) {
            (Some((lower_incl, lower_val)), Some((upper_incl, upper_val))) => {
                // Two-sided range: build a combined arena FA
                make_numeric_range_arena_fa(
                    *lower_val,
                    *lower_incl,
                    *upper_val,
                    *upper_incl,
                    next_arc,
                )
            }
            (Some((incl, val)), None) => {
                // Lower bound only: >= or >
                make_numeric_greater_arena_fa(*val, *incl, next_arc)
            }
            (None, Some((incl, val))) => {
                // Upper bound only: <= or <
                make_numeric_less_arena_fa(*val, *incl, next_arc)
            }
            (None, None) => {
                // No bounds specified - match any number
                // This shouldn't happen in practice
                return Ok(next_fm);
            }
        };

        self.merge_with_singleton(new_arena, new_start)?;

        Ok(next_fm)
    }

    /// Add a CIDR pattern transition using automaton-based IP matching.
    ///
    /// Builds an arena-based FA that matches IP addresses in the specified CIDR range.
    fn add_cidr_transition(
        &self,
        cidr: &crate::json::CidrPattern,
    ) -> Result<Rc<MutableFieldMatcher<X>>, crate::QuaminaError> {
        let next_fm = Rc::new(MutableFieldMatcher::new());
        let next_arc = Arc::new(FieldMatcher::new());
        self.transition_map
            .borrow_mut()
            .insert(Arc::as_ptr(&next_arc), next_fm.clone());

        *self.main_arena_is_nfa.borrow_mut() = true;
        let (new_arena, new_start) = make_cidr_arena_fa(cidr, next_arc);
        self.merge_with_singleton(new_arena, new_start)?;

        Ok(next_fm)
    }

    /// Transition on a value during matching
    pub fn transition_on(
        &self,
        value: &[u8],
        is_number: bool,
        _bufs: &mut NfaBuffers,
    ) -> Vec<Rc<MutableFieldMatcher<X>>> {
        // Singleton fast path: when no multi-condition NFAs coexist with singleton,
        // we can short-circuit without touching transition_map.
        if self.multi_condition_nfas.borrow().is_empty() {
            if let Some(ref singleton_val) = *self.singleton_match.borrow() {
                if singleton_val == value {
                    if let Some(ref trans) = *self.singleton_transition.borrow() {
                        return vec![trans.clone()];
                    }
                }
                return vec![];
            }
        }

        let transition_map = self.transition_map.borrow();
        let mut result = Vec::new();

        // Check singleton match (when multi-condition NFAs coexist with singleton,
        // we couldn't use the fast path above)
        let has_singleton = if let Some(ref singleton_val) = *self.singleton_match.borrow() {
            if singleton_val == value {
                if let Some(ref trans) = *self.singleton_transition.borrow() {
                    result.push(trans.clone());
                }
            }
            true
        } else {
            false
        };

        // Try with Q-number conversion if this matcher has numbers and value is numeric
        // Use stack-allocated QNumberStack to avoid heap allocation
        let q_num_storage: Option<crate::numbits::QNumberStack> =
            if self.has_numbers.get() && is_number {
                // Try to parse as f64 and convert to Q-number
                if let Ok(s) = std::str::from_utf8(value) {
                    if let Ok(n) = s.parse::<f64>() {
                        Some(crate::numbits::q_num_stack(n))
                    } else {
                        None
                    }
                } else {
                    None
                }
            } else {
                None
            };
        let value_to_match: &[u8] = match &q_num_storage {
            Some(q) => q.as_slice(),
            None => value,
        };

        // When singleton is active, main_arena and suffix_arena are empty — skip them.
        if !has_singleton {
            // Traverse main_arena (unified arena for all pattern types)
            if let Some((ref arena, start)) = *self.main_arena.borrow() {
                let mut arena_bufs = self.arena_bufs.borrow_mut();
                if *self.main_arena_is_nfa.borrow() {
                    traverse_arena_nfa(arena, start, value_to_match, &mut arena_bufs);
                } else {
                    arena_bufs.transitions.clear();
                    traverse_arena_dfa(arena, start, value_to_match, &mut arena_bufs.transitions);
                }

                // Map Arc<FieldMatcher> transitions to Rc<MutableFieldMatcher<X>>
                for arc_fm in &arena_bufs.transitions {
                    let ptr = Arc::as_ptr(arc_fm);
                    if let Some(mutable_fm) = transition_map.get(&ptr) {
                        result.push(mutable_fm.clone());
                    }
                }
            }

            // Traverse suffix_arena backward (right-to-left DFA for suffix patterns)
            if let Some((ref arena, start)) = *self.suffix_arena.borrow() {
                let mut arena_bufs = self.arena_bufs.borrow_mut();
                arena_bufs.transitions.clear();
                traverse_arena_dfa_backward(
                    arena,
                    start,
                    value_to_match,
                    &mut arena_bufs.transitions,
                );

                for arc_fm in &arena_bufs.transitions {
                    let ptr = Arc::as_ptr(arc_fm);
                    if let Some(mutable_fm) = transition_map.get(&ptr) {
                        result.push(mutable_fm.clone());
                    }
                }
            }
        }

        // Traverse multi-condition NFAs (for lookaround patterns)
        // For lookaround patterns, we check conditions directly on the full value.
        // The conditions contain the combined patterns that capture full matching semantics:
        // - PositiveLookahead("foobar"): "foobar" must match full value
        // - NegativeLookahead("foobar"): "foobar" must NOT match full value
        // - Lookbehind conditions are pre-combined with primary during build
        let multi_condition_nfas = self.multi_condition_nfas.borrow();
        if !multi_condition_nfas.is_empty() {
            let mut condition_bufs = self.arena_bufs.borrow_mut();

            for mc_nfa in multi_condition_nfas.iter() {
                // Verify all conditions against the full value
                let mut all_conditions_pass = true;

                for condition in &mc_nfa.conditions {
                    // Traverse the condition automaton on the full value
                    traverse_arena_nfa(
                        &condition.arena,
                        condition.start,
                        value_to_match,
                        &mut condition_bufs,
                    );

                    let condition_matched = !condition_bufs.transitions.is_empty();

                    // Check if condition passes:
                    // - Positive condition: must match
                    // - Negative condition: must NOT match
                    let condition_passes = if condition.is_negative {
                        !condition_matched
                    } else {
                        condition_matched
                    };

                    if !condition_passes {
                        all_conditions_pass = false;
                        break; // Fast-fail: one condition failed, no need to check others
                    }
                }

                // Only add transitions if all conditions pass
                if all_conditions_pass {
                    let ptr = mc_nfa.field_matcher_ptr;
                    if let Some(mutable_fm) = transition_map.get(&ptr) {
                        // Avoid duplicates
                        if !result.iter().any(|r| Rc::ptr_eq(r, mutable_fm)) {
                            result.push(mutable_fm.clone());
                        }
                    }
                }
            }
        }

        result
    }
}

/// An event field for matching (simplified version of json::Field)
#[derive(Clone, Debug)]
pub struct EventField {
    pub path: String,
    pub value: String,
    pub array_trail: Vec<crate::json::ArrayPos>,
    /// True if the value is a JSON number (for Q-number conversion during matching)
    pub is_number: bool,
}

impl From<&crate::json::Field> for EventField {
    fn from(f: &crate::json::Field) -> Self {
        Self {
            path: f.path.clone(),
            value: f.value.clone(),
            array_trail: f.array_trail.clone(),
            is_number: f.is_number,
        }
    }
}

/// Zero-copy event field for matching.
/// Borrows path and value bytes directly from the flattened fields.
#[derive(Clone, Debug)]
pub struct EventFieldRef<'a> {
    /// Path as a string slice (converted from bytes)
    pub path: &'a str,
    /// Value as raw bytes
    pub value: &'a [u8],
    /// Array position tracking (borrowed slice)
    pub array_trail: &'a [crate::flatten_json::ArrayPos],
    /// True if the value is a JSON number
    pub is_number: bool,
}

/// Check if two array trails have no conflicts (using flatten_json::ArrayPos)
fn no_array_trail_conflict_ref(
    from: &[crate::flatten_json::ArrayPos],
    to: &[crate::flatten_json::ArrayPos],
) -> bool {
    for from_pos in from {
        for to_pos in to {
            if from_pos.array == to_pos.array && from_pos.pos != to_pos.pos {
                return false;
            }
        }
    }
    true
}

/// Check if two array trails have no conflicts
fn no_array_trail_conflict(from: &[crate::json::ArrayPos], to: &[crate::json::ArrayPos]) -> bool {
    for from_pos in from {
        for to_pos in to {
            if from_pos.array == to_pos.array && from_pos.pos != to_pos.pos {
                return false;
            }
        }
    }
    true
}

/// A set of matches (deduplicated)
struct MatchSet<X: Clone + Eq + std::hash::Hash> {
    seen: HashSet<X>,
    matches: Vec<X>,
}

impl<X: Clone + Eq + std::hash::Hash> MatchSet<X> {
    fn new() -> Self {
        Self {
            seen: HashSet::new(),
            matches: Vec::new(),
        }
    }

    fn add(&mut self, x: X) {
        if self.seen.insert(x.clone()) {
            self.matches.push(x);
        }
    }

    fn into_vec(self) -> Vec<X> {
        self.matches
    }
}

/// Core matcher that uses automaton-based matching for multiple fields.
///
/// This implements the Go quamina matching algorithm:
/// 1. Patterns are added by building a graph of FieldMatcher -> MutableValueMatcher -> FieldMatcher
/// 2. Event fields are sorted and matched against the automaton
/// 3. Matching recursively tries subsequent fields to find complete pattern matches
#[derive(Default)]
pub struct CoreMatcher<X: Clone + Eq + std::hash::Hash> {
    /// Root field matcher - the start state of the automaton
    root: Rc<MutableFieldMatcher<X>>,
    /// Arena byte budget for pattern complexity limiting
    arena_byte_budget: usize,
}

impl<X: Clone + Eq + std::hash::Hash> CoreMatcher<X> {
    /// Create a new CoreMatcher with default arena budget (10 MB).
    pub fn new() -> Self {
        Self {
            root: Rc::new(MutableFieldMatcher::new()),
            arena_byte_budget: crate::PatternLimits::default().arena_byte_budget,
        }
    }

    /// Add a pattern with the given identifier.
    ///
    /// The pattern_fields should be a list of (path, matchers) tuples.
    /// Fields are automatically sorted by path for matching.
    pub fn add_pattern(
        &self,
        x: X,
        pattern_fields: &[(String, Vec<crate::json::Matcher>)],
    ) -> Result<(), crate::QuaminaError> {
        // Sort fields lexically by path (like Go)
        let mut sorted_fields: Vec<_> = pattern_fields.to_vec();
        sorted_fields.sort_by(|a, b| a.0.cmp(&b.0));

        // Start with the root state
        let mut states: Vec<Rc<MutableFieldMatcher<X>>> = vec![self.root.clone()];

        for (path, matchers) in &sorted_fields {
            if matchers.is_empty() {
                continue;
            }

            let mut next_states = Vec::new();

            for state in &states {
                // Check for exists patterns
                let first_matcher = &matchers[0];
                match first_matcher {
                    crate::json::Matcher::Exists(true) => {
                        let next = state.add_exists(true, path);
                        next_states.push(next);
                    }
                    crate::json::Matcher::Exists(false) => {
                        let next = state.add_exists(false, path);
                        next_states.push(next);
                    }
                    _ => {
                        // Value matcher transition
                        let nexts = state.add_transition(path, matchers, self.arena_byte_budget)?;
                        next_states.extend(nexts);
                    }
                }
            }

            states = next_states;
        }

        // Mark terminal states with the pattern identifier
        for state in states {
            state.add_match(x.clone());
        }
        Ok(())
    }

    /// Match fields against patterns and return matching pattern identifiers.
    ///
    /// Fields should already be sorted by path.
    pub fn matches_for_fields(&self, fields: &[EventField]) -> Vec<X> {
        if fields.is_empty() {
            // Still need to check exists:false patterns
            return self.collect_exists_false_matches(&self.root);
        }

        let mut matches = MatchSet::new();
        let mut bufs = NfaBuffers::new();

        // For each field, try to match from the start state
        for i in 0..fields.len() {
            self.try_to_match(fields, i, &self.root, &mut matches, &mut bufs);
        }

        matches.into_vec()
    }

    /// Recursively try to match fields starting from the given index and state
    fn try_to_match(
        &self,
        fields: &[EventField],
        index: usize,
        state: &Rc<MutableFieldMatcher<X>>,
        matches: &mut MatchSet<X>,
        bufs: &mut NfaBuffers,
    ) {
        let field = &fields[index];

        // Check exists:true transition
        if let Some(exists_trans) = state.exists_true.borrow().get(&field.path) {
            // Add matches from this state
            for m in exists_trans.matches.borrow().iter() {
                matches.add(m.clone());
            }
            // Try subsequent fields
            for next_idx in (index + 1)..fields.len() {
                if no_array_trail_conflict(&field.array_trail, &fields[next_idx].array_trail) {
                    self.try_to_match(fields, next_idx, exists_trans, matches, bufs);
                }
            }
            // Check exists:false at end
            self.check_exists_false(state, fields, index, matches, bufs);
        }

        // Check exists:false (field doesn't exist)
        self.check_exists_false(state, fields, index, matches, bufs);

        // Try value transitions
        let next_states =
            state.transition_on(&field.path, field.value.as_bytes(), field.is_number, bufs);

        for next_state in next_states {
            // Add matches from next state
            for m in next_state.matches.borrow().iter() {
                matches.add(m.clone());
            }

            // Try subsequent fields
            for next_idx in (index + 1)..fields.len() {
                if no_array_trail_conflict(&field.array_trail, &fields[next_idx].array_trail) {
                    self.try_to_match(fields, next_idx, &next_state, matches, bufs);
                }
            }

            // Check exists:false at end
            self.check_exists_false(&next_state, fields, index, matches, bufs);
        }
    }

    /// Check exists:false patterns - field must NOT exist
    fn check_exists_false(
        &self,
        state: &Rc<MutableFieldMatcher<X>>,
        fields: &[EventField],
        index: usize,
        matches: &mut MatchSet<X>,
        bufs: &mut NfaBuffers,
    ) {
        for (path, exists_trans) in state.exists_false.borrow().iter() {
            // Check if this path exists in the fields
            let field_exists = fields.iter().any(|f| &f.path == path);

            if !field_exists {
                // Field doesn't exist - exists:false matches
                for m in exists_trans.matches.borrow().iter() {
                    matches.add(m.clone());
                }
                // Continue matching from this state
                self.try_to_match(fields, index, exists_trans, matches, bufs);
            }
        }
    }

    /// Collect matches from exists:false patterns when there are no fields
    fn collect_exists_false_matches(&self, state: &Rc<MutableFieldMatcher<X>>) -> Vec<X> {
        let mut result = Vec::new();
        for exists_trans in state.exists_false.borrow().values() {
            result.extend(exists_trans.matches.borrow().iter().cloned());
        }
        result
    }

    /// Match fields against patterns using zero-copy field references.
    ///
    /// Fields should already be sorted by path.
    /// The `bufs` parameter should be a reusable NfaBuffers instance for reduced allocations.
    pub fn matches_for_fields_ref(
        &self,
        fields: &[EventFieldRef<'_>],
        bufs: &mut NfaBuffers,
    ) -> Vec<X> {
        if fields.is_empty() {
            return self.collect_exists_false_matches(&self.root);
        }

        let mut matches = MatchSet::new();
        bufs.clear(); // Reset buffers for reuse

        for i in 0..fields.len() {
            self.try_to_match_ref(fields, i, &self.root, &mut matches, bufs);
        }

        matches.into_vec()
    }

    /// Recursively try to match fields (zero-copy version)
    fn try_to_match_ref(
        &self,
        fields: &[EventFieldRef<'_>],
        index: usize,
        state: &Rc<MutableFieldMatcher<X>>,
        matches: &mut MatchSet<X>,
        bufs: &mut NfaBuffers,
    ) {
        let field = &fields[index];

        // Check exists:true transition
        if let Some(exists_trans) = state.exists_true.borrow().get(field.path) {
            for m in exists_trans.matches.borrow().iter() {
                matches.add(m.clone());
            }
            for next_idx in (index + 1)..fields.len() {
                if no_array_trail_conflict_ref(field.array_trail, fields[next_idx].array_trail) {
                    self.try_to_match_ref(fields, next_idx, exists_trans, matches, bufs);
                }
            }
            self.check_exists_false_ref(state, fields, index, matches, bufs);
        }

        // Check exists:false
        self.check_exists_false_ref(state, fields, index, matches, bufs);

        // Try value transitions
        let next_states = state.transition_on(field.path, field.value, field.is_number, bufs);

        for next_state in next_states {
            for m in next_state.matches.borrow().iter() {
                matches.add(m.clone());
            }

            for next_idx in (index + 1)..fields.len() {
                if no_array_trail_conflict_ref(field.array_trail, fields[next_idx].array_trail) {
                    self.try_to_match_ref(fields, next_idx, &next_state, matches, bufs);
                }
            }

            self.check_exists_false_ref(&next_state, fields, index, matches, bufs);
        }
    }

    /// Check exists:false patterns (zero-copy version)
    fn check_exists_false_ref(
        &self,
        state: &Rc<MutableFieldMatcher<X>>,
        fields: &[EventFieldRef<'_>],
        index: usize,
        matches: &mut MatchSet<X>,
        bufs: &mut NfaBuffers,
    ) {
        for (path, exists_trans) in state.exists_false.borrow().iter() {
            let field_exists = fields.iter().any(|f| f.path == path);

            if !field_exists {
                for m in exists_trans.matches.borrow().iter() {
                    matches.add(m.clone());
                }
                self.try_to_match_ref(fields, index, exists_trans, matches, bufs);
            }
        }
    }

    /// Match fields against patterns using flattened fields directly.
    ///
    /// This avoids the intermediate EventFieldRef allocation by working
    /// directly with flatten_json::Field. Fields should already be sorted by path.
    pub fn matches_for_fields_direct(
        &self,
        fields: &[crate::flatten_json::Field<'_>],
        bufs: &mut NfaBuffers,
    ) -> Vec<X> {
        if fields.is_empty() {
            return self.collect_exists_false_matches(&self.root);
        }

        let mut matches = MatchSet::new();
        bufs.clear();

        for i in 0..fields.len() {
            self.try_to_match_direct(fields, i, &self.root, &mut matches, bufs);
        }

        matches.into_vec()
    }

    /// Recursively try to match fields (direct Field version)
    fn try_to_match_direct(
        &self,
        fields: &[crate::flatten_json::Field<'_>],
        index: usize,
        state: &Rc<MutableFieldMatcher<X>>,
        matches: &mut MatchSet<X>,
        bufs: &mut NfaBuffers,
    ) {
        let field = &fields[index];
        let path = field.path_str();
        let value = field.value_bytes();
        let array_trail = field.array_trail_slice();

        // Check exists:true transition
        if let Some(exists_trans) = state.exists_true.borrow().get(path) {
            for m in exists_trans.matches.borrow().iter() {
                matches.add(m.clone());
            }
            for next_idx in (index + 1)..fields.len() {
                if no_array_trail_conflict_ref(array_trail, fields[next_idx].array_trail_slice()) {
                    self.try_to_match_direct(fields, next_idx, exists_trans, matches, bufs);
                }
            }
            self.check_exists_false_direct(state, fields, index, matches, bufs);
        }

        // Check exists:false
        self.check_exists_false_direct(state, fields, index, matches, bufs);

        // Try value transitions
        let next_states = state.transition_on(path, value, field.is_number, bufs);

        for next_state in next_states {
            for m in next_state.matches.borrow().iter() {
                matches.add(m.clone());
            }

            for next_idx in (index + 1)..fields.len() {
                if no_array_trail_conflict_ref(array_trail, fields[next_idx].array_trail_slice()) {
                    self.try_to_match_direct(fields, next_idx, &next_state, matches, bufs);
                }
            }

            self.check_exists_false_direct(&next_state, fields, index, matches, bufs);
        }
    }

    /// Check exists:false patterns (direct Field version)
    fn check_exists_false_direct(
        &self,
        state: &Rc<MutableFieldMatcher<X>>,
        fields: &[crate::flatten_json::Field<'_>],
        index: usize,
        matches: &mut MatchSet<X>,
        bufs: &mut NfaBuffers,
    ) {
        for (path, exists_trans) in state.exists_false.borrow().iter() {
            let field_exists = fields.iter().any(|f| f.path_str() == path);

            if !field_exists {
                for m in exists_trans.matches.borrow().iter() {
                    matches.add(m.clone());
                }
                self.try_to_match_direct(fields, index, exists_trans, matches, bufs);
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::json::Matcher;
    use crate::regexp::parse_regexp;

    #[test]
    fn test_value_matcher_regexp_with_plus() {
        // Test that MutableValueMatcher correctly uses arena for regexp with +
        let vm: MutableValueMatcher<String> = MutableValueMatcher::new();

        // Create a regexp pattern with + quantifier
        let regexp_tree = parse_regexp("[a-z]+@example~.com").unwrap();
        let matcher = Matcher::ParsedRegexp(regexp_tree);

        let next_fm = vm.add_transition(&matcher).unwrap();

        // Verify arena was used (all patterns now use main_arena)
        assert!(
            vm.main_arena.borrow().is_some(),
            "main_arena should be set for regexp"
        );
        // Test matching
        let mut bufs = NfaBuffers::new();
        let value = qv(b"alice@example.com");
        let results = vm.transition_on(&value, false, &mut bufs);

        assert_eq!(
            results.len(),
            1,
            "Should match 'alice@example.com', got {} results",
            results.len()
        );
        assert!(
            Rc::ptr_eq(&results[0], &next_fm),
            "Should return the next field matcher"
        );

        // Test non-matching
        bufs.clear();
        let no_match_value = qv(b"alice@exampleXcom");
        let no_results = vm.transition_on(&no_match_value, false, &mut bufs);
        assert!(
            no_results.is_empty(),
            "Should not match 'alice@exampleXcom'"
        );
    }

    #[test]
    fn test_value_matcher_regexp_without_plus() {
        // Test that MutableValueMatcher uses arena for all regexp patterns
        let vm: MutableValueMatcher<String> = MutableValueMatcher::new();

        // Create a regexp pattern without + or * quantifier
        let regexp_tree = parse_regexp("[abc]").unwrap();
        let matcher = Matcher::ParsedRegexp(regexp_tree);

        let next_fm = vm.add_transition(&matcher).unwrap();

        // Verify arena was used (all patterns now use main_arena)
        assert!(
            vm.main_arena.borrow().is_some(),
            "main_arena should be set for regexp"
        );
        // Test matching
        let mut bufs = NfaBuffers::new();
        let value = qv(b"a");
        let results = vm.transition_on(&value, false, &mut bufs);

        assert_eq!(results.len(), 1, "Should match 'a'");
        assert!(
            Rc::ptr_eq(&results[0], &next_fm),
            "Should return the next field matcher"
        );
    }

    #[test]
    fn test_core_matcher_with_arena_regexp() {
        // Test the full CoreMatcher path with a regexp pattern using arena
        let cm: CoreMatcher<String> = CoreMatcher::new();

        // Parse the pattern like Quamina would
        let pattern_json = r#"{"email": [{"regex": "[a-z]+@example~.com"}]}"#;
        let pattern =
            crate::json::parse_pattern(pattern_json, &crate::PatternLimits::default()).unwrap();
        let pattern_vec: Vec<_> = pattern.into_iter().collect();

        cm.add_pattern("p1".to_string(), &pattern_vec).unwrap();

        // Create a field like the flattener would (strings retain JSON quotes)
        let fields = vec![EventField {
            path: "email".to_string(),
            value: "\"alice@example.com\"".to_string(),
            array_trail: vec![],
            is_number: false,
        }];

        let matches = cm.matches_for_fields(&fields);
        assert_eq!(matches, vec!["p1".to_string()], "Should match the pattern");

        // Test non-match
        let fields_no_match = vec![EventField {
            path: "email".to_string(),
            value: "\"alice@exampleXcom\"".to_string(),
            array_trail: vec![],
            is_number: false,
        }];

        let no_matches = cm.matches_for_fields(&fields_no_match);
        assert!(no_matches.is_empty(), "Should not match");
    }

    #[test]
    fn test_core_matcher_direct_with_arena_regexp() {
        // Test matches_for_fields_direct specifically (the path used by Quamina::matches_for_event)
        use std::sync::Arc;

        let cm: CoreMatcher<String> = CoreMatcher::new();

        // Parse the pattern like Quamina would
        let pattern_json = r#"{"email": [{"regex": "[a-z]+@example~.com"}]}"#;
        let pattern =
            crate::json::parse_pattern(pattern_json, &crate::PatternLimits::default()).unwrap();
        let pattern_vec: Vec<_> = pattern.into_iter().collect();

        cm.add_pattern("p1".to_string(), &pattern_vec).unwrap();

        // Create fields like matches_for_fields_direct expects (strings retain JSON quotes)
        let fields = vec![crate::flatten_json::Field {
            path: Arc::from(b"email".as_slice()),
            val: crate::flatten_json::FieldValue::Borrowed(b"\"alice@example.com\""),
            array_trail: [].as_slice().into(),
            is_number: false,
        }];

        let mut bufs = NfaBuffers::new();
        let matches = cm.matches_for_fields_direct(&fields, &mut bufs);
        assert_eq!(
            matches,
            vec!["p1".to_string()],
            "Should match the pattern via matches_for_fields_direct"
        );
    }

    /// Helper: wrap a byte slice in quotes to simulate flattener output for strings.
    /// The flattener preserves JSON quotes on string values, so test values
    /// passed to `transition_on` must include them.
    fn qv(s: &[u8]) -> Vec<u8> {
        let mut v = Vec::with_capacity(s.len() + 2);
        v.push(b'"');
        v.extend_from_slice(s);
        v.push(b'"');
        v
    }

    // =========================================================================
    // Integration tests for Arena-Only Migration (Step 2.3)
    // These tests verify behavior that must remain unchanged after migration
    // =========================================================================

    #[test]
    fn test_arena_migration_string_single() {
        // Test single exact string match
        let vm: MutableValueMatcher<String> = MutableValueMatcher::new();
        // Matcher::Exact for strings contains quoted value (like json.rs value_to_string produces)
        let matcher = Matcher::Exact("\"hello\"".to_string());
        let next_fm = vm.add_transition(&matcher).unwrap();

        let mut bufs = NfaBuffers::new();

        // Should match (quoted, like flattener output for strings)
        let results = vm.transition_on(&qv(b"hello"), false, &mut bufs);
        assert_eq!(results.len(), 1);
        assert!(Rc::ptr_eq(&results[0], &next_fm));

        // Should not match
        bufs.clear();
        let results = vm.transition_on(&qv(b"world"), false, &mut bufs);
        assert!(results.is_empty());
    }

    #[test]
    fn test_arena_migration_string_multiple() {
        // Test multiple exact string matches
        let vm: MutableValueMatcher<String> = MutableValueMatcher::new();

        // Matcher::Exact for strings contains quoted values (like json.rs value_to_string produces)
        let fm1 = vm
            .add_transition(&Matcher::Exact("\"foo\"".to_string()))
            .unwrap();
        let fm2 = vm
            .add_transition(&Matcher::Exact("\"bar\"".to_string()))
            .unwrap();
        let fm3 = vm
            .add_transition(&Matcher::Exact("\"baz\"".to_string()))
            .unwrap();

        let mut bufs = NfaBuffers::new();

        // Each should match (quoted)
        let results = vm.transition_on(&qv(b"foo"), false, &mut bufs);
        assert_eq!(results.len(), 1);
        assert!(Rc::ptr_eq(&results[0], &fm1));

        bufs.clear();
        let results = vm.transition_on(&qv(b"bar"), false, &mut bufs);
        assert_eq!(results.len(), 1);
        assert!(Rc::ptr_eq(&results[0], &fm2));

        bufs.clear();
        let results = vm.transition_on(&qv(b"baz"), false, &mut bufs);
        assert_eq!(results.len(), 1);
        assert!(Rc::ptr_eq(&results[0], &fm3));

        // None should match
        bufs.clear();
        let results = vm.transition_on(&qv(b"qux"), false, &mut bufs);
        assert!(results.is_empty());
    }

    #[test]
    fn test_arena_migration_prefix() {
        // Test prefix pattern
        let vm: MutableValueMatcher<String> = MutableValueMatcher::new();
        let matcher = Matcher::Prefix("hello".to_string());
        let next_fm = vm.add_transition(&matcher).unwrap();

        let mut bufs = NfaBuffers::new();

        // Should match any string starting with "hello" (quoted)
        let results = vm.transition_on(&qv(b"hello"), false, &mut bufs);
        assert_eq!(results.len(), 1);
        assert!(Rc::ptr_eq(&results[0], &next_fm));

        bufs.clear();
        let results = vm.transition_on(&qv(b"helloworld"), false, &mut bufs);
        assert_eq!(results.len(), 1);

        bufs.clear();
        let results = vm.transition_on(&qv(b"hello123"), false, &mut bufs);
        assert_eq!(results.len(), 1);

        // Should not match
        bufs.clear();
        let results = vm.transition_on(&qv(b"hell"), false, &mut bufs);
        assert!(results.is_empty());

        bufs.clear();
        let results = vm.transition_on(&qv(b"world"), false, &mut bufs);
        assert!(results.is_empty());
    }

    #[test]
    fn test_arena_migration_shellstyle() {
        // Test shellstyle wildcard pattern
        let vm: MutableValueMatcher<String> = MutableValueMatcher::new();
        let matcher = Matcher::Shellstyle("hello*world".to_string());
        let next_fm = vm.add_transition(&matcher).unwrap();

        let mut bufs = NfaBuffers::new();

        // Should match (quoted)
        let results = vm.transition_on(&qv(b"helloworld"), false, &mut bufs);
        assert_eq!(results.len(), 1);
        assert!(Rc::ptr_eq(&results[0], &next_fm));

        bufs.clear();
        let results = vm.transition_on(&qv(b"hello_world"), false, &mut bufs);
        assert_eq!(results.len(), 1);

        bufs.clear();
        let results = vm.transition_on(&qv(b"hello123world"), false, &mut bufs);
        assert_eq!(results.len(), 1);

        // Should not match
        bufs.clear();
        let results = vm.transition_on(&qv(b"helloworl"), false, &mut bufs);
        assert!(results.is_empty());

        bufs.clear();
        let results = vm.transition_on(&qv(b"worldhello"), false, &mut bufs);
        assert!(results.is_empty());
    }

    #[test]
    fn test_arena_migration_wildcard_escape() {
        // Test wildcard with escape sequences
        let vm: MutableValueMatcher<String> = MutableValueMatcher::new();
        // Pattern "foo\\*bar" should match literal "foo*bar"
        let matcher = Matcher::Wildcard("foo\\*bar".to_string());
        let next_fm = vm.add_transition(&matcher).unwrap();

        let mut bufs = NfaBuffers::new();

        // Should match literal * (quoted)
        let results = vm.transition_on(&qv(b"foo*bar"), false, &mut bufs);
        assert_eq!(results.len(), 1);
        assert!(Rc::ptr_eq(&results[0], &next_fm));

        // Should not match without *
        bufs.clear();
        let results = vm.transition_on(&qv(b"foobar"), false, &mut bufs);
        assert!(results.is_empty());
    }

    #[test]
    fn test_arena_migration_anything_but() {
        // Test anything-but pattern
        let vm: MutableValueMatcher<String> = MutableValueMatcher::new();
        let matcher = Matcher::AnythingBut(vec!["foo".to_string(), "bar".to_string()]);
        let next_fm = vm.add_transition(&matcher).unwrap();

        let mut bufs = NfaBuffers::new();

        // Should match anything except foo and bar (quoted)
        let results = vm.transition_on(&qv(b"baz"), false, &mut bufs);
        assert_eq!(results.len(), 1);
        assert!(Rc::ptr_eq(&results[0], &next_fm));

        bufs.clear();
        let results = vm.transition_on(&qv(b"qux"), false, &mut bufs);
        assert_eq!(results.len(), 1);

        // Should not match excluded values
        bufs.clear();
        let results = vm.transition_on(&qv(b"foo"), false, &mut bufs);
        assert!(results.is_empty());

        bufs.clear();
        let results = vm.transition_on(&qv(b"bar"), false, &mut bufs);
        assert!(results.is_empty());
    }

    #[test]
    fn test_arena_migration_monocase() {
        // Test case-insensitive matching
        let vm: MutableValueMatcher<String> = MutableValueMatcher::new();
        let matcher = Matcher::EqualsIgnoreCase("Hello".to_string());
        let next_fm = vm.add_transition(&matcher).unwrap();

        let mut bufs = NfaBuffers::new();

        // Should match any case combination (quoted)
        let results = vm.transition_on(&qv(b"Hello"), false, &mut bufs);
        assert_eq!(results.len(), 1);
        assert!(Rc::ptr_eq(&results[0], &next_fm));

        bufs.clear();
        let results = vm.transition_on(&qv(b"hello"), false, &mut bufs);
        assert_eq!(results.len(), 1);

        bufs.clear();
        let results = vm.transition_on(&qv(b"HELLO"), false, &mut bufs);
        assert_eq!(results.len(), 1);

        bufs.clear();
        let results = vm.transition_on(&qv(b"hElLo"), false, &mut bufs);
        assert_eq!(results.len(), 1);

        // Should not match different strings
        bufs.clear();
        let results = vm.transition_on(&qv(b"world"), false, &mut bufs);
        assert!(results.is_empty());
    }

    #[test]
    fn test_arena_migration_numeric_range() {
        use crate::json::NumericComparison;

        // Test numeric range patterns
        let vm: MutableValueMatcher<String> = MutableValueMatcher::new();

        // Match 10 <= x < 100
        let cmp = NumericComparison {
            lower: Some((true, 10.0)),   // >= 10
            upper: Some((false, 100.0)), // < 100
        };
        let matcher = Matcher::Numeric(cmp);
        let next_fm = vm.add_transition(&matcher).unwrap();

        let mut bufs = NfaBuffers::new();

        // Should match values in range (as numbers)
        let results = vm.transition_on(b"10", true, &mut bufs);
        assert_eq!(results.len(), 1);
        assert!(Rc::ptr_eq(&results[0], &next_fm));

        bufs.clear();
        let results = vm.transition_on(b"50", true, &mut bufs);
        assert_eq!(results.len(), 1);

        bufs.clear();
        let results = vm.transition_on(b"99", true, &mut bufs);
        assert_eq!(results.len(), 1);

        // Should not match values outside range
        bufs.clear();
        let results = vm.transition_on(b"9", true, &mut bufs);
        assert!(results.is_empty());

        bufs.clear();
        let results = vm.transition_on(b"100", true, &mut bufs);
        assert!(results.is_empty());
    }

    #[test]
    fn test_arena_migration_mixed_patterns() {
        // Test mixing different pattern types in same value matcher
        let vm: MutableValueMatcher<String> = MutableValueMatcher::new();

        // Add various pattern types
        // Exact values contain quotes (like json.rs value_to_string produces for strings)
        let fm_exact = vm
            .add_transition(&Matcher::Exact("\"exact\"".to_string()))
            .unwrap();
        let fm_prefix = vm
            .add_transition(&Matcher::Prefix("pre".to_string()))
            .unwrap();
        let fm_shell = vm
            .add_transition(&Matcher::Shellstyle("*wild*".to_string()))
            .unwrap();

        let mut bufs = NfaBuffers::new();

        // Test exact match (quoted like flattener output)
        let results = vm.transition_on(&qv(b"exact"), false, &mut bufs);
        assert_eq!(results.len(), 1);
        assert!(Rc::ptr_eq(&results[0], &fm_exact));

        // Test prefix match (quoted)
        bufs.clear();
        let results = vm.transition_on(&qv(b"prefix_value"), false, &mut bufs);
        assert_eq!(results.len(), 1);
        assert!(Rc::ptr_eq(&results[0], &fm_prefix));

        // Test shellstyle match (quoted)
        bufs.clear();
        let results = vm.transition_on(&qv(b"something_wild_here"), false, &mut bufs);
        assert_eq!(results.len(), 1);
        assert!(Rc::ptr_eq(&results[0], &fm_shell));

        // Test value matching multiple patterns (quoted)
        bufs.clear();
        let results = vm.transition_on(&qv(b"prewild"), false, &mut bufs);
        // Should match both prefix and shellstyle
        assert!(!results.is_empty());
    }

    // MIRI SKIP RATIONALE: CIDR /24 pattern construction + 4 IP traversals takes ~46s under
    // Miri. Coverage: test_cidr_arena_fa_ipv4_exact and test_cidr_arena_fa_ipv4_range
    // exercise the same arena CIDR construction/matching at the arena level.
    #[test]
    #[cfg_attr(miri, ignore)]
    fn test_arena_migration_cidr_v4() {
        use crate::json::CidrPattern;

        // Test IPv4 CIDR pattern
        let vm: MutableValueMatcher<String> = MutableValueMatcher::new();
        let cidr = CidrPattern::V4 {
            network: [192, 168, 1, 0],
            prefix_len: 24,
        };
        let matcher = Matcher::Cidr(cidr);
        let next_fm = vm.add_transition(&matcher).unwrap();

        let mut bufs = NfaBuffers::new();

        // Should match IPs in the /24 range (quoted, like flattener output for strings)
        let results = vm.transition_on(&qv(b"192.168.1.1"), false, &mut bufs);
        assert_eq!(results.len(), 1);
        assert!(Rc::ptr_eq(&results[0], &next_fm));

        bufs.clear();
        let results = vm.transition_on(&qv(b"192.168.1.255"), false, &mut bufs);
        assert_eq!(results.len(), 1);

        // Should not match IPs outside the range
        bufs.clear();
        let results = vm.transition_on(&qv(b"192.168.2.1"), false, &mut bufs);
        assert!(results.is_empty());

        bufs.clear();
        let results = vm.transition_on(&qv(b"10.0.0.1"), false, &mut bufs);
        assert!(results.is_empty());
    }

    #[test]
    fn test_arena_migration_core_matcher_all_types() {
        // End-to-end test with CoreMatcher using various pattern types
        let cm: CoreMatcher<String> = CoreMatcher::new();

        // Add patterns of different types
        // Matcher::Exact for strings contains quoted values (like json.rs value_to_string produces)
        cm.add_pattern(
            "exact".to_string(),
            &[(
                "field".to_string(),
                vec![Matcher::Exact("\"hello\"".to_string())],
            )],
        )
        .unwrap();
        cm.add_pattern(
            "prefix".to_string(),
            &[(
                "field".to_string(),
                vec![Matcher::Prefix("pre".to_string())],
            )],
        )
        .unwrap();
        cm.add_pattern(
            "shell".to_string(),
            &[(
                "field".to_string(),
                vec![Matcher::Shellstyle("*wild*".to_string())],
            )],
        )
        .unwrap();

        // Test exact match (string values include quotes like flattener output)
        let fields = vec![EventField {
            path: "field".to_string(),
            value: "\"hello\"".to_string(),
            array_trail: vec![],
            is_number: false,
        }];
        let matches = cm.matches_for_fields(&fields);
        assert!(matches.contains(&"exact".to_string()));

        // Test prefix match
        let fields = vec![EventField {
            path: "field".to_string(),
            value: "\"prefix_value\"".to_string(),
            array_trail: vec![],
            is_number: false,
        }];
        let matches = cm.matches_for_fields(&fields);
        assert!(matches.contains(&"prefix".to_string()));

        // Test shellstyle match
        let fields = vec![EventField {
            path: "field".to_string(),
            value: "\"something_wild_here\"".to_string(),
            array_trail: vec![],
            is_number: false,
        }];
        let matches = cm.matches_for_fields(&fields);
        assert!(matches.contains(&"shell".to_string()));
    }
}