rsigma-eval 0.28.0

Evaluator for Sigma detection and correlation rules: match rules against 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
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
//! Stateful correlation engine with time-windowed aggregation.
//!
//! `CorrelationEngine` wraps the stateless `Engine` and adds support for
//! Sigma correlation rules: `event_count`, `value_count`, `temporal`,
//! `temporal_ordered`, `value_sum`, `value_avg`, `value_percentile`,
//! and `value_median`.
//!
//! # Architecture
//!
//! 1. Events are first evaluated against detection rules (stateless)
//! 2. Detection matches update correlation window state (stateful)
//! 3. When a correlation condition is met, a `CorrelationResult` is emitted
//! 4. Correlation results can chain into higher-level correlations

mod introspect;
#[cfg(test)]
mod tests;
mod types;

pub use introspect::{CorrelationInfo, CorrelationStateSnapshot, GroupKeyPart, GroupStateInfo};
pub use types::*;

use std::borrow::Cow;
use std::collections::{BTreeMap, HashMap, HashSet};
use std::sync::Arc;

use chrono::Utc;

use rsigma_parser::{CorrelationRule, CorrelationType, SigmaCollection, SigmaRule, WindowMode};

use crate::correlation::{
    CompiledCorrelation, EventBuffer, EventRef, EventRefBuffer, GroupKey, RefEntry, Retained,
    WindowDecision, WindowState, apply_window_open, compile_correlation,
};
use crate::engine::{Engine, IdentifiedEvaluation};
use crate::error::{EvalError, Result};
use crate::event::{Event, EventValue};
use crate::logsource::{ExtractLogSource, LogSourceExtractor};
use crate::pipeline::{Pipeline, apply_pipelines, apply_pipelines_to_correlation};
use crate::result::{CorrelationBody, EvaluationResult, EventSource, ResultBody, RuleHeader};
use crate::rule_metadata::{RuleBundleMetadata, RuleMetadataLookup};
use crate::tenant::TenantId;
use crate::timestamp::{epoch_seconds_from_float, epoch_seconds_from_int, parse_timestamp_str};

type RuleIdentity = (Option<String>, Option<String>);

// =============================================================================
// Correlation Engine
// =============================================================================

/// Current snapshot schema version. Bump when the serialized format changes.
pub(crate) const SNAPSHOT_VERSION: u32 = 2;

/// Parent hops evaluated after a first-level correlation fire in one event.
/// The first-level result is produced by `feed_detections`; each loop
/// iteration here walks one parent. A chain longer than this is updated
/// and emitted through this many hops, then leftover parents are dropped
/// with a `WARN`.
const MAX_CHAIN_DEPTH: usize = 10;

/// Timespan above which a correlation without a per-group entry cap is
/// warned about at load: a busy group's window retains `timespan` x event
/// rate entries, which `max_state_entries` does not see.
const LONG_WINDOW_WARN_SECS: u64 = 3600;

/// Event retention a correlation needs for itself and for the chain above it.
#[derive(Debug, Clone, Default)]
struct Retention {
    /// Strongest event mode required by this correlation or any correlation
    /// that references it, directly or through another correlation.
    mode: CorrelationEventMode,
    /// Largest retention cap required by that chain.
    cap: usize,
    /// Whether any correlation that references this one retains events.
    feeds_retaining_parent: bool,
    /// The correlation's `rule_refs`, interned so each buffered event shares
    /// one string as its source rule. Empty when nothing is retained.
    rule_refs: Vec<Arc<str>>,
    /// The correlation's stable identifier, interned as the source of the
    /// entries it hands to its parents. `None` when nothing is retained.
    stable_id: Option<Arc<str>>,
}

/// The events, references, and sources a firing correlation reports.
#[derive(Default)]
struct ReportedEvents {
    events: Option<Vec<serde_json::Value>>,
    event_refs: Option<Vec<EventRef>>,
    event_sources: Option<Vec<EventSource>>,
}

/// Stateful correlation engine.
///
/// Wraps the stateless `Engine` for detection rules and adds time-windowed
/// correlation on top. Supports all 7 Sigma correlation types and chaining.
///
/// Generic over the inner engine's logsource extractor `L`, which defaults to
/// [`LogSourceExtractor`] (see [`Engine`]).
pub struct CorrelationEngine<L = LogSourceExtractor> {
    /// Inner stateless detection engine.
    engine: Engine<L>,
    /// Compiled correlation rules.
    correlations: Vec<CompiledCorrelation>,
    /// Maps rule ID/name -> indices into `correlations` that reference it.
    /// This allows quick lookup: "which correlations care about rule X?"
    rule_index: HashMap<String, Vec<usize>>,
    /// Maps detection rule index -> (rule_id, rule_name, rule_title) for reverse lookup.
    /// Used to find which correlations a detection match triggers.
    rule_ids: Vec<(Option<String>, Option<String>, String)>,
    /// Per-(tenant, correlation_index, group_key) window state.
    state: HashMap<StateKey, WindowState>,
    /// Last alert timestamp per (tenant, correlation_index, group_key) for suppression.
    last_alert: HashMap<StateKey, i64>,
    /// Per-(tenant, correlation_index, group_key) compressed event buffer (`Full` mode).
    event_buffers: HashMap<StateKey, EventBuffer>,
    /// Per-(tenant, correlation_index, group_key) event reference buffer (`Refs` mode).
    event_ref_buffers: HashMap<StateKey, EventRefBuffer>,
    /// Set of rule IDs/names (detections or correlations) that are
    /// "correlation-only" (referenced by correlations where `generate == false`).
    /// Used to filter their output when `config.emit_detections == false`.
    correlation_only_rules: std::collections::HashSet<String>,
    /// Rules referenced by at least one correlation with `generate: true`.
    /// Such a reference wins over correlation-only references.
    generated_rules: std::collections::HashSet<String>,
    /// Configuration.
    config: CorrelationConfig,
    /// Processing pipelines applied to rules during add_rule.
    pipelines: Vec<Pipeline>,
    /// Events skipped by `require_tenant` because they carried no tenant.
    untenanted_skipped: u64,
    /// Live state keys per tenant, kept in step with `state` while a
    /// per-tenant cap is set, so quota checks and eviction touch only that
    /// tenant's entries. Empty when there is no per-tenant cap.
    tenant_keys: HashMap<Option<TenantId>, HashSet<StateKey>>,
    /// Entries evicted because a tenant hit its quota.
    tenant_quota_evictions: u64,
    /// Sequence number the next processed event gets. Retained buffer entries
    /// carry it so a parent correlation can skip an event it already merged.
    next_event_seq: u64,
    /// Per-correlation event retention, recomputed when the rule set or the
    /// engine defaults change.
    retention: Vec<Retention>,
    /// Whether `retention` needs recomputing before the next event.
    retention_dirty: bool,
}

impl CorrelationEngine {
    /// Create a new correlation engine with the given configuration.
    pub fn new(config: CorrelationConfig) -> Self {
        Self::with_engine(config, Engine::new())
    }
}

impl<L> CorrelationEngine<L> {
    /// Create a new correlation engine whose inner detection engine prunes
    /// with `extractor`, a custom [`ExtractLogSource`] implementation.
    pub fn with_logsource_extractor(config: CorrelationConfig, extractor: L) -> Self {
        Self::with_engine(config, Engine::with_logsource_extractor(extractor))
    }

    fn with_engine(config: CorrelationConfig, engine: Engine<L>) -> Self {
        CorrelationEngine {
            engine,
            correlations: Vec::new(),
            rule_index: HashMap::new(),
            rule_ids: Vec::new(),
            state: HashMap::new(),
            last_alert: HashMap::new(),
            event_buffers: HashMap::new(),
            event_ref_buffers: HashMap::new(),
            correlation_only_rules: std::collections::HashSet::new(),
            generated_rules: std::collections::HashSet::new(),
            config,
            pipelines: Vec::new(),
            untenanted_skipped: 0,
            tenant_keys: HashMap::new(),
            tenant_quota_evictions: 0,
            next_event_seq: 1,
            retention: Vec::new(),
            retention_dirty: true,
        }
    }

    /// Add a pipeline to the engine.
    ///
    /// Pipelines are applied to rules during `add_rule` / `add_collection`.
    pub fn add_pipeline(&mut self, pipeline: Pipeline) {
        self.pipelines.push(pipeline);
        self.pipelines.sort_by_key(|p| p.priority);
    }

    /// Set global `include_event` on the inner detection engine.
    pub fn set_include_event(&mut self, include: bool) {
        self.engine.set_include_event(include);
    }

    /// Forward to [`crate::Engine::set_match_detail`] on the inner detection
    /// engine. Correlation detections inherit the level set here.
    pub fn set_match_detail(&mut self, level: crate::result::MatchDetailLevel) {
        self.engine.set_match_detail(level);
    }

    /// Forward to [`crate::Engine::set_bloom_prefilter`] on the inner
    /// detection engine. Off by default; the optimization helps only on
    /// substring-heavy rule sets paired with mostly-non-matching events.
    pub fn set_bloom_prefilter(&mut self, enabled: bool) {
        self.engine.set_bloom_prefilter(enabled);
    }

    /// Forward to [`crate::Engine::set_logsource_extractor`] on the inner
    /// detection engine. Correlation inherits logsource pruning, since
    /// `process_event` evaluates through this engine.
    pub fn set_logsource_extractor(&mut self, extractor: Option<L>) {
        self.engine.set_logsource_extractor(extractor);
    }

    /// Total rule candidates pruned by logsource on the inner engine.
    pub fn logsource_pruned_total(&self) -> u64 {
        self.engine.logsource_pruned_total()
    }

    /// Total evaluate calls with no extractable event logsource (fail-open).
    pub fn logsource_absent_total(&self) -> u64 {
        self.engine.logsource_absent_total()
    }

    /// Forward to [`crate::Engine::set_bloom_max_bytes`] on the inner
    /// detection engine.
    pub fn set_bloom_max_bytes(&mut self, max_bytes: usize) {
        self.engine.set_bloom_max_bytes(max_bytes);
    }

    /// Forward to [`crate::Engine::set_cross_rule_ac`] on the inner
    /// detection engine. Off by default. Available behind the
    /// `daachorse-index` Cargo feature.
    #[cfg(feature = "daachorse-index")]
    pub fn set_cross_rule_ac(&mut self, enabled: bool) {
        self.engine.set_cross_rule_ac(enabled);
    }

    /// Set the global correlation event mode.
    ///
    /// - `None`: no event storage (default)
    /// - `Full`: compressed event bodies
    /// - `Refs`: lightweight timestamp + ID references
    pub fn set_correlation_event_mode(&mut self, mode: CorrelationEventMode) {
        self.config.correlation_event_mode = mode;
        self.retention_dirty = true;
    }

    /// Set the maximum number of events to store per correlation window group.
    /// Only meaningful when `correlation_event_mode` is not `None`.
    pub fn set_max_correlation_events(&mut self, max: usize) {
        self.config.max_correlation_events = max;
        self.retention_dirty = true;
    }

    /// Add a single detection rule.
    ///
    /// If pipelines are set, the rule is cloned and transformed before compilation.
    /// The inner engine receives the already-transformed rule directly (not through
    /// its own pipeline, to avoid double transformation).
    pub fn add_rule(&mut self, rule: &SigmaRule) -> Result<()> {
        if self.pipelines.is_empty() {
            self.apply_custom_attributes(&rule.custom_attributes);
            self.rule_ids
                .push((rule.id.clone(), rule.name.clone(), rule.title.clone()));
            self.engine.add_rule(rule)?;
        } else {
            let mut transformed = rule.clone();
            apply_pipelines(&self.pipelines, &mut transformed)?;
            self.apply_custom_attributes(&transformed.custom_attributes);
            self.rule_ids.push((
                transformed.id.clone(),
                transformed.name.clone(),
                transformed.title.clone(),
            ));
            // Use compile_rule + add_compiled_rule to bypass inner engine's pipelines
            let compiled = crate::compiler::compile_rule(&transformed)?;
            self.engine.add_compiled_rule(compiled);
        }
        Ok(())
    }

    /// Read `rsigma.*` custom attributes from a rule and apply them to the
    /// engine configuration.  This allows pipelines to influence engine
    /// behaviour via `SetCustomAttribute` transformations — the same pattern
    /// used by pySigma backends (e.g. pySigma-backend-loki).
    ///
    /// Supported attributes:
    /// - `rsigma.timestamp_field` — prepends a field name to the timestamp
    ///   extraction priority list so the correlation engine can find the
    ///   event timestamp in non-standard field names.
    /// - `rsigma.suppress` — sets the default suppression window (e.g. `5m`).
    ///   Only applied when the CLI did not already set `--suppress`.
    /// - `rsigma.action` — sets the default post-fire action (`alert`/`reset`).
    ///   Only applied when the CLI did not already set `--action`.
    fn apply_custom_attributes(
        &mut self,
        attrs: &std::collections::HashMap<String, yaml_serde::Value>,
    ) {
        // rsigma.timestamp_field — prepend to priority list, skip duplicates
        if let Some(field) = attrs.get("rsigma.timestamp_field").and_then(|v| v.as_str())
            && !self.config.timestamp_fields.iter().any(|f| f == field)
        {
            self.config.timestamp_fields.insert(0, field.to_string());
        }

        // rsigma.suppress — only when CLI didn't already set one
        if let Some(val) = attrs.get("rsigma.suppress").and_then(|v| v.as_str())
            && self.config.suppress.is_none()
            && let Ok(ts) = rsigma_parser::Timespan::parse(val)
        {
            self.config.suppress = Some(ts.seconds);
        }

        // rsigma.action — only when CLI left it at the default (Alert)
        if let Some(val) = attrs.get("rsigma.action").and_then(|v| v.as_str())
            && self.config.action_on_match == CorrelationAction::Alert
            && let Ok(a) = val.parse::<CorrelationAction>()
        {
            self.config.action_on_match = a;
        }
    }

    /// Add a single correlation rule.
    pub fn add_correlation(&mut self, corr: &CorrelationRule) -> Result<()> {
        let owned;
        let effective = if self.pipelines.is_empty() {
            corr
        } else {
            owned = {
                let mut c = corr.clone();
                apply_pipelines_to_correlation(&self.pipelines, &mut c)?;
                c
            };
            &owned
        };

        // Apply engine-level custom attributes from the (possibly transformed)
        // correlation rule (e.g. rsigma.timestamp_field).
        self.apply_custom_attributes(&effective.custom_attributes);

        let compiled = compile_correlation(effective)?;
        if self.has_unbounded_long_window(&compiled) {
            log::warn!(
                "Correlation '{}' has a {}s timespan and no per-group entry cap; \
                 a busy group retains timespan x event rate entries. \
                 Set max_group_entries (--max-group-entries) or the rsigma.max_group_entries attribute to bound it.",
                compiled.id.as_deref().unwrap_or(&compiled.title),
                compiled.timespan_secs
            );
        }
        let idx = self.correlations.len();

        // Index by each referenced rule ID/name
        for rule_ref in &compiled.rule_refs {
            self.rule_index
                .entry(rule_ref.clone())
                .or_default()
                .push(idx);
        }

        // A rule is standalone when any referencing correlation requests it,
        // regardless of the order in which correlations are loaded.
        for rule_ref in &compiled.rule_refs {
            if compiled.generate {
                self.generated_rules.insert(rule_ref.clone());
                self.correlation_only_rules.remove(rule_ref);
            } else if !self.generated_rules.contains(rule_ref) {
                self.correlation_only_rules.insert(rule_ref.clone());
            }
        }

        self.correlations.push(compiled);
        self.retention_dirty = true;
        Ok(())
    }

    /// Whether `corr` keeps a window longer than [`LONG_WINDOW_WARN_SECS`]
    /// with no per-group entry cap from the rule or the engine config.
    fn has_unbounded_long_window(&self, corr: &CompiledCorrelation) -> bool {
        corr.timespan_secs > LONG_WINDOW_WARN_SECS
            && corr
                .max_group_entries
                .or(self.config.max_group_entries)
                .is_none()
    }

    /// Add all rules and correlations from a parsed collection.
    ///
    /// Detection rules are added first (so they're available for correlation
    /// references), then correlation rules. Detection rules are compiled
    /// sequentially and then pushed to the inner engine in a single batch,
    /// so the inverted index and bloom filter are rebuilt exactly once for
    /// the whole collection. Without this batching, large rule sets
    /// (multi-thousand rules) hit an O(N²) rebuild cost on load.
    pub fn add_collection(&mut self, collection: &SigmaCollection) -> Result<()> {
        let mut compiled_batch = Vec::with_capacity(collection.rules.len());
        if self.pipelines.is_empty() {
            for rule in &collection.rules {
                self.apply_custom_attributes(&rule.custom_attributes);
                self.rule_ids
                    .push((rule.id.clone(), rule.name.clone(), rule.title.clone()));
                compiled_batch.push(crate::compiler::compile_rule(rule)?);
            }
        } else {
            for rule in &collection.rules {
                let mut transformed = rule.clone();
                apply_pipelines(&self.pipelines, &mut transformed)?;
                self.apply_custom_attributes(&transformed.custom_attributes);
                self.rule_ids.push((
                    transformed.id.clone(),
                    transformed.name.clone(),
                    transformed.title.clone(),
                ));
                // Bypass the inner engine's pipelines (would double-transform)
                compiled_batch.push(crate::compiler::compile_rule(&transformed)?);
            }
        }
        self.engine.extend_compiled_rules(compiled_batch);
        // Apply filter rules to the inner engine's detection rules
        for filter in &collection.filters {
            self.engine.apply_filter(filter)?;
        }
        for corr in &collection.correlations {
            self.add_correlation(corr)?;
        }
        self.validate_rule_refs()?;
        self.detect_correlation_cycles()?;
        Ok(())
    }

    /// Validate that every correlation's `rule_refs` resolve to at least one
    /// known detection rule (by ID or name) or another correlation (by ID or name).
    fn validate_rule_refs(&self) -> Result<()> {
        let mut known: std::collections::HashSet<&str> = std::collections::HashSet::new();

        for (id, name, _) in &self.rule_ids {
            if let Some(id) = id {
                known.insert(id.as_str());
            }
            if let Some(name) = name {
                known.insert(name.as_str());
            }
        }
        for corr in &self.correlations {
            if let Some(ref id) = corr.id {
                known.insert(id.as_str());
            }
            if let Some(ref name) = corr.name {
                known.insert(name.as_str());
            }
        }

        for corr in &self.correlations {
            for rule_ref in &corr.rule_refs {
                if !known.contains(rule_ref.as_str()) {
                    return Err(EvalError::UnknownRuleRef(rule_ref.clone()));
                }
            }
        }
        Ok(())
    }

    /// Detect cycles in the correlation reference graph.
    ///
    /// Builds a directed graph where each correlation (identified by its id/name)
    /// has edges to the correlations it references via `rule_refs`. Uses DFS with
    /// a "gray/black" coloring scheme to detect back-edges (cycles).
    ///
    /// Returns `Err(EvalError::CorrelationCycle)` if a cycle is found.
    fn detect_correlation_cycles(&self) -> Result<()> {
        // Build a set of all correlation identifiers (id and/or name)
        let mut corr_identifiers: HashMap<&str, usize> = HashMap::new();
        for (idx, corr) in self.correlations.iter().enumerate() {
            if let Some(ref id) = corr.id {
                corr_identifiers.insert(id.as_str(), idx);
            }
            if let Some(ref name) = corr.name {
                corr_identifiers.insert(name.as_str(), idx);
            }
        }

        // Build adjacency list: corr index → set of corr indices it references
        let mut adj: Vec<Vec<usize>> = vec![Vec::new(); self.correlations.len()];
        for (idx, corr) in self.correlations.iter().enumerate() {
            for rule_ref in &corr.rule_refs {
                if let Some(&target_idx) = corr_identifiers.get(rule_ref.as_str()) {
                    adj[idx].push(target_idx);
                }
            }
        }

        // DFS cycle detection with three states: white (unvisited), gray (in stack), black (done)
        let mut state = vec![0u8; self.correlations.len()]; // 0=white, 1=gray, 2=black
        let mut path: Vec<usize> = Vec::new();

        for start in 0..self.correlations.len() {
            if state[start] == 0
                && let Some(cycle) = Self::dfs_find_cycle(start, &adj, &mut state, &mut path)
            {
                let names: Vec<String> = cycle
                    .iter()
                    .map(|&i| {
                        self.correlations[i]
                            .id
                            .as_deref()
                            .or(self.correlations[i].name.as_deref())
                            .unwrap_or(&self.correlations[i].title)
                            .to_string()
                    })
                    .collect();
                return Err(crate::error::EvalError::CorrelationCycle(
                    names.join(" -> "),
                ));
            }
        }
        Ok(())
    }

    /// DFS helper that returns the cycle path if a back-edge is found.
    fn dfs_find_cycle(
        node: usize,
        adj: &[Vec<usize>],
        state: &mut [u8],
        path: &mut Vec<usize>,
    ) -> Option<Vec<usize>> {
        state[node] = 1; // gray
        path.push(node);

        for &next in &adj[node] {
            if state[next] == 1 {
                // Back-edge found — extract cycle from path
                if let Some(pos) = path.iter().position(|&n| n == next) {
                    let mut cycle = path[pos..].to_vec();
                    cycle.push(next); // close the cycle
                    return Some(cycle);
                }
            }
            if state[next] == 0
                && let Some(cycle) = Self::dfs_find_cycle(next, adj, state, path)
            {
                return Some(cycle);
            }
        }

        path.pop();
        state[node] = 2; // black
        None
    }

    /// Process an event, extracting the timestamp from configured event fields.
    ///
    /// When no timestamp field is found, the `timestamp_fallback` policy applies:
    /// - `WallClock`: use `Utc::now()` (good for real-time streaming)
    /// - `Skip`: return detections only, skip correlation state updates
    pub fn process_event<E: Event>(&mut self, event: &E) -> ProcessResult
    where
        L: ExtractLogSource<E>,
    {
        self.process_event_for_tenant(event, None)
    }

    /// Process an event as `tenant`, extracting the timestamp from configured
    /// event fields.
    ///
    /// The tenant keys every window this event touches; correlation results
    /// carry it. `None` is the untenanted bucket used when tenancy is off.
    pub fn process_event_for_tenant<E: Event>(
        &mut self,
        event: &E,
        tenant: Option<&TenantId>,
    ) -> ProcessResult
    where
        L: ExtractLogSource<E>,
    {
        let detections = self.engine.evaluate_identified(event);
        self.correlate_identified_detections_for_tenant(event, detections, tenant)
    }

    /// Run the correlation layer over externally-produced detections.
    ///
    /// Like [`process_event`](Self::process_event) but the detections are
    /// supplied by the caller instead of computed by this engine's inner
    /// detection engine. This lets a multi-engine router run detection in a
    /// per-schema engine and still feed every detection into one shared
    /// correlation store. Timestamp extraction and the `timestamp_fallback`
    /// policy match `process_event`. Rule identity is recovered as in
    /// [`process_with_detections`](Self::process_with_detections).
    pub fn correlate_detections(
        &mut self,
        event: &impl Event,
        all_detections: Vec<EvaluationResult>,
    ) -> ProcessResult {
        self.correlate_detections_for_tenant(event, all_detections, None)
    }

    /// Like [`correlate_detections`](Self::correlate_detections) but as
    /// `tenant`.
    pub fn correlate_detections_for_tenant(
        &mut self,
        event: &impl Event,
        all_detections: Vec<EvaluationResult>,
        tenant: Option<&TenantId>,
    ) -> ProcessResult {
        let identities = all_detections
            .iter()
            .map(|detection| self.find_rule_identity(detection))
            .collect();
        self.correlate_with_identities(event, all_detections, identities, tenant)
    }

    /// Run the correlation layer over detections identified by this engine's
    /// rule table, keying every window by `tenant`.
    pub(crate) fn correlate_identified_detections_for_tenant(
        &mut self,
        event: &impl Event,
        detections: Vec<IdentifiedEvaluation>,
        tenant: Option<&TenantId>,
    ) -> ProcessResult {
        let (all_detections, identities) = split_identified(detections);
        self.correlate_with_identities(event, all_detections, identities, tenant)
    }

    fn correlate_with_identities(
        &mut self,
        event: &impl Event,
        all_detections: Vec<EvaluationResult>,
        identities: Vec<RuleIdentity>,
        tenant: Option<&TenantId>,
    ) -> ProcessResult {
        let ts = match self.extract_event_timestamp(event) {
            Some(ts) => ts,
            None => match self.config.timestamp_fallback {
                TimestampFallback::WallClock => Utc::now().timestamp(),
                TimestampFallback::Skip => {
                    // Still surface detections, but skip correlation state.
                    return self.filter_detections(all_detections, identities);
                }
            },
        };
        self.process_with_detection_identities(event, all_detections, identities, ts, tenant)
    }

    /// Process an event with an explicit Unix epoch timestamp (seconds).
    ///
    /// The timestamp is clamped to `[0, i64::MAX / 2]` to prevent overflow
    /// when adding timespan durations internally.
    pub fn process_event_at<E: Event>(&mut self, event: &E, timestamp_secs: i64) -> ProcessResult
    where
        L: ExtractLogSource<E>,
    {
        self.process_event_at_for_tenant(event, timestamp_secs, None)
    }

    /// Like [`process_event_at`](Self::process_event_at) but as `tenant`.
    pub fn process_event_at_for_tenant<E: Event>(
        &mut self,
        event: &E,
        timestamp_secs: i64,
        tenant: Option<&TenantId>,
    ) -> ProcessResult
    where
        L: ExtractLogSource<E>,
    {
        let detections = self.engine.evaluate_identified(event);
        let (all_detections, identities) = split_identified(detections);
        self.process_with_detection_identities(
            event,
            all_detections,
            identities,
            timestamp_secs,
            tenant,
        )
    }

    /// Process an event with pre-computed detection results.
    ///
    /// Enables external parallelism: callers can run detection (via
    /// [`evaluate`](Self::evaluate)) in parallel, then feed results here
    /// sequentially for stateful correlation.
    ///
    /// A result carries its rule's `id` but not its `name`, so a detection
    /// from a rule without an `id` is matched to its rule by title and feeds
    /// no correlation when several such rules share that title.
    /// [`process_event_at`](Self::process_event_at) and
    /// [`process_batch`](Self::process_batch) keep the compiled identity.
    pub fn process_with_detections(
        &mut self,
        event: &impl Event,
        all_detections: Vec<EvaluationResult>,
        timestamp_secs: i64,
    ) -> ProcessResult {
        self.process_with_detections_for_tenant(event, all_detections, timestamp_secs, None)
    }

    /// Like [`process_with_detections`](Self::process_with_detections) but as
    /// `tenant`.
    pub fn process_with_detections_for_tenant(
        &mut self,
        event: &impl Event,
        all_detections: Vec<EvaluationResult>,
        timestamp_secs: i64,
        tenant: Option<&TenantId>,
    ) -> ProcessResult {
        let identities = all_detections
            .iter()
            .map(|detection| self.find_rule_identity(detection))
            .collect();
        self.process_with_detection_identities(
            event,
            all_detections,
            identities,
            timestamp_secs,
            tenant,
        )
    }

    fn process_with_detection_identities(
        &mut self,
        event: &impl Event,
        all_detections: Vec<EvaluationResult>,
        identities: Vec<RuleIdentity>,
        timestamp_secs: i64,
        tenant: Option<&TenantId>,
    ) -> ProcessResult {
        let timestamp_secs = timestamp_secs.clamp(0, i64::MAX / 2);

        // A shared `None` bucket is never allowed when tenancy is required:
        // skip the event's correlation update and count it.
        if self.config.require_tenant && tenant.is_none() {
            self.untenanted_skipped += 1;
            return self.filter_detections(all_detections, identities);
        }

        // Memory management — evict before adding new state to enforce limit
        if self.state.len() >= self.config.max_state_entries {
            self.evict_all(timestamp_secs);
        }

        if self.retention_dirty {
            self.refresh_retention();
        }

        let event_seq = self.next_event_seq;
        self.next_event_seq = self.next_event_seq.saturating_add(1);

        // Feed detection matches into correlations
        let mut correlations: Vec<EvaluationResult> = Vec::new();
        let mut fired_indices = Vec::new();
        let mut fired_retained = Vec::new();
        self.feed_detections(
            event,
            &identities,
            timestamp_secs,
            tenant,
            event_seq,
            &mut correlations,
            &mut fired_indices,
            &mut fired_retained,
        );

        // Chain — parent firings go into a separate vec so we do not
        // alias `correlations` as both the input slice and the output.
        let mut chained = Vec::new();
        let mut chained_indices = Vec::new();
        self.chain_correlations(
            &correlations,
            &fired_indices,
            fired_retained,
            timestamp_secs,
            &mut chained,
            &mut chained_indices,
        );
        correlations.extend(chained);
        fired_indices.extend(chained_indices);

        // Filter detections and correlations by the generate flag of the
        // correlations that reference them.
        let mut out = self.filter_detections(all_detections, identities);
        out.extend(
            correlations
                .into_iter()
                .zip(fired_indices)
                .filter(|(_, idx)| {
                    let corr = &self.correlations[*idx];
                    let identities = corr.id.as_deref().into_iter().chain(corr.name.as_deref());
                    !self.is_correlation_only(identities)
                })
                .map(|(result, _)| result),
        );
        out
    }

    /// Number of events skipped by `require_tenant` because they carried no
    /// tenant.
    pub fn untenanted_skipped(&self) -> u64 {
        self.untenanted_skipped
    }

    /// Events skipped by `require_tenant` since the previous call, draining the
    /// counter.
    pub fn take_untenanted_skipped(&mut self) -> u64 {
        std::mem::take(&mut self.untenanted_skipped)
    }

    /// Set the per-tenant state cap. `None` leaves only the global cap.
    pub fn set_max_state_entries_per_tenant(&mut self, max: Option<usize>) {
        self.config.max_state_entries_per_tenant = max;
        self.tenant_keys.clear();
        if max.is_some() {
            for key in self.state.keys() {
                self.tenant_keys
                    .entry(key.tenant.clone())
                    .or_default()
                    .insert(key.clone());
            }
        }
    }

    /// Entries evicted because a tenant hit its quota since the previous call,
    /// draining the counter.
    pub fn take_tenant_quota_evictions(&mut self) -> u64 {
        std::mem::take(&mut self.tenant_quota_evictions)
    }

    /// Run stateless detection only (no correlation), delegating to the inner engine.
    ///
    /// Returns one [`EvaluationResult`] per matched detection. Takes `&self`
    /// so it can be called concurrently from multiple threads (e.g. via
    /// `rayon::par_iter`) while the mutable correlation phase runs
    /// sequentially afterwards.
    pub fn evaluate<E: Event>(&self, event: &E) -> Vec<EvaluationResult>
    where
        L: ExtractLogSource<E>,
    {
        self.engine.evaluate(event)
    }

    /// Process a batch of events: parallel detection, then sequential correlation.
    ///
    /// When the `parallel` feature is enabled, the stateless detection phase runs
    /// concurrently via rayon. Timestamp extraction also runs in the parallel
    /// phase (it borrows `&self.config` immutably). After `collect()` releases the
    /// immutable borrows, each event's pre-computed detections are fed into the
    /// stateful correlation engine sequentially.
    pub fn process_batch<E: Event + Sync>(&mut self, events: &[&E]) -> Vec<ProcessResult>
    where
        L: ExtractLogSource<E> + Sync,
    {
        self.process_batch_for_tenants(events, &[])
    }

    /// Process a batch of events, each as the tenant at its position in
    /// `tenants`.
    ///
    /// `tenants` is either empty (every event is untenanted) or exactly as
    /// long as `events`. Any other length is a caller bug: in debug builds it
    /// trips a `debug_assert!`, and in release builds it logs and returns one
    /// empty result per event.
    pub fn process_batch_for_tenants<E: Event + Sync>(
        &mut self,
        events: &[&E],
        tenants: &[Option<TenantId>],
    ) -> Vec<ProcessResult>
    where
        L: ExtractLogSource<E> + Sync,
    {
        if !tenants.is_empty() && tenants.len() != events.len() {
            debug_assert!(
                false,
                "tenants must be empty or parallel to events: {} tenants for {} events",
                tenants.len(),
                events.len()
            );
            log::error!(
                "tenant slice length mismatch: {} tenants for {} events; returning empty results",
                tenants.len(),
                events.len()
            );
            return vec![ProcessResult::new(); events.len()];
        }

        // Borrow split: take immutable refs to fields needed for the parallel phase.
        // These are released by collect() before the sequential &mut self phase.
        let engine = &self.engine;
        let ts_fields = &self.config.timestamp_fields;

        let batch_results: Vec<(Vec<IdentifiedEvaluation>, Option<i64>)> =
            crate::parallel::map_ordered(events, |e| {
                let detections = engine.evaluate_identified(e);
                let ts = extract_event_ts(e, ts_fields);
                (detections, ts)
            });

        // Sequential correlation phase
        let mut results = Vec::with_capacity(events.len());
        for (index, ((identified, ts_opt), event)) in
            batch_results.into_iter().zip(events).enumerate()
        {
            let tenant = crate::tenant::tenant_at(tenants, index);
            let (detections, identities) = split_identified(identified);
            let ts = match ts_opt {
                Some(ts) => ts,
                None => match self.config.timestamp_fallback {
                    TimestampFallback::WallClock => Utc::now().timestamp(),
                    TimestampFallback::Skip => {
                        // Still return detection results, but skip correlation
                        results.push(self.filter_detections(detections, identities));
                        continue;
                    }
                },
            };
            results.push(
                self.process_with_detection_identities(event, detections, identities, ts, tenant),
            );
        }
        results
    }

    /// Filter detections by the `generate` flag / `emit_detections` config.
    ///
    /// If `emit_detections` is false and some rules are correlation-only,
    /// their detection output is suppressed.
    fn filter_detections(
        &self,
        all_detections: Vec<EvaluationResult>,
        identities: Vec<RuleIdentity>,
    ) -> Vec<EvaluationResult> {
        if !self.config.emit_detections && !self.correlation_only_rules.is_empty() {
            all_detections
                .into_iter()
                .zip(identities)
                .filter_map(|(detection, (id, name))| {
                    let identities = id.as_deref().into_iter().chain(name.as_deref());
                    (!self.is_correlation_only(identities)).then_some(detection)
                })
                .collect()
        } else {
            all_detections
        }
    }

    /// Whether output for a rule (detection or correlation) with these
    /// identities is suppressed: only correlations without `generate: true`
    /// reference it, and `emit_detections` is off.
    fn is_correlation_only<'a>(
        &self,
        mut identities: impl Iterator<Item = &'a str> + Clone,
    ) -> bool {
        !self.config.emit_detections
            && identities
                .clone()
                .any(|identity| self.correlation_only_rules.contains(identity))
            && !identities.any(|identity| self.generated_rules.contains(identity))
    }

    /// Feed detection matches into correlation window states.
    #[allow(clippy::too_many_arguments)]
    fn feed_detections(
        &mut self,
        event: &impl Event,
        identities: &[RuleIdentity],
        ts: i64,
        tenant: Option<&TenantId>,
        event_seq: u64,
        out: &mut Vec<EvaluationResult>,
        fired_indices: &mut Vec<usize>,
        fired_retained: &mut Vec<Option<Retained>>,
    ) {
        // Collect all (corr_idx, rule_id, rule_name) tuples upfront to avoid
        // borrow conflicts between self.rule_ids and self.update_correlation.
        let mut work: Vec<(usize, Option<String>, Option<String>)> = Vec::new();

        for (rule_id, rule_name) in identities {
            // Collect correlation indices that reference this rule
            let mut corr_indices = Vec::new();
            if let Some(id) = rule_id
                && let Some(indices) = self.rule_index.get(id)
            {
                corr_indices.extend(indices);
            }
            if let Some(name) = rule_name
                && let Some(indices) = self.rule_index.get(name)
            {
                corr_indices.extend(indices);
            }

            corr_indices.sort_unstable();
            corr_indices.dedup();

            for &corr_idx in &corr_indices {
                work.push((corr_idx, rule_id.clone(), rule_name.clone()));
            }
        }

        for (corr_idx, rule_id, rule_name) in work {
            let before = out.len();
            let retained = self.update_correlation(
                corr_idx, event, ts, tenant, &rule_id, &rule_name, event_seq, out,
            );
            if out.len() > before {
                fired_indices.push(corr_idx);
                fired_retained.push(retained);
            }
        }
    }

    /// Find the (id, name) for a detection match by searching our rule_ids table.
    fn find_rule_identity(&self, det: &EvaluationResult) -> RuleIdentity {
        // Prefer the stable ID carried by the result.
        if let Some(ref match_id) = det.header.rule_id {
            for (id, name, _) in &self.rule_ids {
                if id.as_deref() == Some(match_id.as_str()) {
                    return (id.clone(), name.clone());
                }
            }
        }

        // `process_with_detections` accepts the public EvaluationResult shape,
        // which does not carry a rule name. Recover name-only rule identity
        // from the title retained alongside the compiled rule.
        let mut title_matches = self
            .rule_ids
            .iter()
            .filter(|(_, _, title)| title == &det.header.rule_title);
        if let Some((id, name, _)) = title_matches.next()
            && title_matches.next().is_none()
        {
            return (id.clone(), name.clone());
        }

        (det.header.rule_id.clone(), None)
    }

    /// Update a single correlation's state and check its condition.
    ///
    /// When the correlation fires and a correlation that references it
    /// retains events, returns the entries it retained at that moment, captured
    /// before an `action: reset` clears them.
    #[allow(clippy::too_many_arguments)]
    fn update_correlation(
        &mut self,
        corr_idx: usize,
        event: &impl Event,
        ts: i64,
        tenant: Option<&TenantId>,
        rule_id: &Option<String>,
        rule_name: &Option<String>,
        event_seq: u64,
        out: &mut Vec<EvaluationResult>,
    ) -> Option<Retained> {
        // Copy the scalars and resolve the group key while borrowing the
        // correlation immutably. The borrow ends before the state entry so the
        // tenant quota can evict from `self.state`.
        let (
            corr_type,
            timespan,
            window_mode,
            gap_secs,
            level,
            suppress_secs,
            action,
            event_mode,
            max_events,
            retention_mode,
            retention_cap,
            max_group_entries,
            rule_ref,
            source_rule,
            group_key,
        ) = {
            let corr = &self.correlations[corr_idx];
            let corr_type = corr.correlation_type;
            let timespan = corr.timespan_secs;
            let window_mode = corr.window_mode;
            let gap_secs = corr.gap_secs;
            let level = corr.level;
            let suppress_secs = corr.suppress_secs.or(self.config.suppress);
            let action = corr.action.unwrap_or(self.config.action_on_match);
            let event_mode = corr
                .event_mode
                .unwrap_or(self.config.correlation_event_mode);
            let max_events = corr
                .max_events
                .unwrap_or(self.config.max_correlation_events);
            let retention_mode = self.retention[corr_idx].mode;
            let retention_cap = self.retention[corr_idx].cap;
            let max_group_entries = corr.max_group_entries.or(self.config.max_group_entries);

            // Determine the rule_ref strings for alias resolution and temporal tracking.
            let mut ref_strs: Vec<&str> = Vec::new();
            if let Some(id) = rule_id.as_deref() {
                ref_strs.push(id);
            }
            if let Some(name) = rule_name.as_deref() {
                ref_strs.push(name);
            }
            let rule_pos = ref_strs.iter().find_map(|identity| {
                corr.rule_refs
                    .iter()
                    .position(|rule_ref| rule_ref == identity)
            });
            let rule_ref = rule_pos
                .map(|pos| corr.rule_refs[pos].clone())
                .unwrap_or_default();
            let source_rule =
                rule_pos.and_then(|pos| self.retention[corr_idx].rule_refs.get(pos).cloned());

            // An event without every group-by value cannot be assigned to a
            // correlation group.
            let group_key = GroupKey::extract(event, &corr.group_by, &ref_strs)?;

            (
                corr_type,
                timespan,
                window_mode,
                gap_secs,
                level,
                suppress_secs,
                action,
                event_mode,
                max_events,
                retention_mode,
                retention_cap,
                max_group_entries,
                rule_ref,
                source_rule,
                group_key,
            )
        };

        // Get or create window state
        let state_key = StateKey {
            tenant: tenant.cloned(),
            corr_idx,
            group_key: group_key.clone(),
        };
        let is_new = !self.state.contains_key(&state_key);
        if is_new
            && let Some(cap) = self.config.max_state_entries_per_tenant
            && self.tenant_len(&state_key.tenant) >= cap
        {
            self.evict_tenant(tenant, ts);
        }
        if is_new {
            self.note_tenant_insert(&state_key);
        }
        let state = self
            .state
            .entry(state_key.clone())
            .or_insert_with(|| WindowState::new_for(corr_type));

        // Re-borrow the correlation: `self.state` and `self.correlations` are
        // disjoint fields, so the mutable state borrow and this read coexist.
        let corr = &self.correlations[corr_idx];

        // Apply the window's pre-insert maintenance (sliding evict, tumbling
        // bucket reset/late-event discard, or session gap/cap reset). On
        // `Reset` the event buffers below are cleared in sync; on `Discard`
        // (a late arrival in an earlier tumbling bucket) the event is dropped
        // without touching the state or buffers.
        let cutoff = ts - timespan as i64;
        let decision = apply_window_open(state, ts, timespan, window_mode, gap_secs);
        if decision == WindowDecision::Discard {
            return None;
        }
        let reset = decision == WindowDecision::Reset;

        // Push the new event into the state
        match corr_type {
            CorrelationType::EventCount => {
                state.push_event_count(ts);
            }
            CorrelationType::ValueCount => {
                if let Some(ref fields) = corr.condition.field
                    && let Some(key) = composite_value_count_key(event, fields)
                {
                    state.push_value_count(ts, key);
                }
            }
            CorrelationType::Temporal | CorrelationType::TemporalOrdered => {
                state.push_temporal(ts, &rule_ref);
            }
            CorrelationType::ValueSum
            | CorrelationType::ValueAvg
            | CorrelationType::ValuePercentile
            | CorrelationType::ValueMedian => {
                if let Some(ref fields) = corr.condition.field
                    && let Some(field_name) = fields.first()
                    && let Some(val) = event.get_field(field_name)
                    && let Some(n) = value_to_f64_ev(&val)
                {
                    state.push_numeric(ts, n);
                }
            }
        }

        // Enforce the per-group entry cap. Session windows keep their oldest
        // entry as the span anchor so truncation cannot silently extend the
        // `timespan` cap.
        if let Some(cap) = max_group_entries {
            state.truncate_oldest(cap, window_mode == WindowMode::Session);
        }

        // Push event into the buffer its retention requires, which can be
        // stronger than this correlation's own mode when a parent retains
        // events. Keep the buffer's retained entries aligned with the window
        // state: sliding evicts by the trailing cutoff, while tumbling/session
        // clear the buffer when the window reset.
        match retention_mode {
            CorrelationEventMode::Full => {
                let buf = self
                    .event_buffers
                    .entry(state_key.clone())
                    .or_insert_with(|| EventBuffer::new(retention_cap));
                if window_mode == rsigma_parser::WindowMode::Sliding {
                    buf.evict(cutoff);
                } else if reset {
                    buf.clear();
                }
                let json = event.to_json();
                buf.push_seq(event_seq, ts, &json, source_rule);
            }
            CorrelationEventMode::Refs => {
                let buf = self
                    .event_ref_buffers
                    .entry(state_key.clone())
                    .or_insert_with(|| EventRefBuffer::new(retention_cap));
                if window_mode == rsigma_parser::WindowMode::Sliding {
                    buf.evict(cutoff);
                } else if reset {
                    buf.clear();
                }
                let json = event.to_json();
                buf.push_seq(event_seq, ts, &json, source_rule);
            }
            CorrelationEventMode::None => {}
        }

        // Check condition — after this, `state` is no longer used (NLL drops the borrow).
        let fired = state.check_condition(
            &corr.condition,
            corr_type,
            &corr.rule_refs,
            corr.extended_expr.as_ref(),
        );

        if let Some(agg_value) = fired {
            let alert_key = state_key.clone();

            // Suppression check: skip if we've already alerted within the suppress window
            let suppressed = if let Some(suppress) = suppress_secs {
                if let Some(&last_ts) = self.last_alert.get(&alert_key) {
                    (ts - last_ts) < suppress as i64
                } else {
                    false
                }
            } else {
                false
            };

            if !suppressed {
                let reported = self.reported_events(&alert_key, event_mode, max_events);
                let retained = self.capture_retained(&alert_key);

                // Only clone title/id/tags when we actually produce output
                let corr = &self.correlations[corr_idx];
                let result = EvaluationResult {
                    header: RuleHeader {
                        rule_title: corr.title.clone(),
                        rule_id: corr.id.clone(),
                        tenant_id: tenant.cloned(),
                        level,
                        tags: corr.tags.clone(),
                        custom_attributes: corr.custom_attributes.clone(),
                        enrichments: None,
                        ruleset: None,
                    },
                    body: ResultBody::Correlation(CorrelationBody {
                        correlation_type: corr_type,
                        group_key: group_key.to_pairs(&corr.group_by),
                        aggregated_value: agg_value,
                        timespan_secs: timespan,
                        events: reported.events,
                        event_refs: reported.event_refs,
                        event_sources: reported.event_sources,
                    }),
                };
                out.push(result);

                // Record alert time for suppression
                self.last_alert.insert(alert_key.clone(), ts);

                // Action on match
                if action == CorrelationAction::Reset {
                    if let Some(state) = self.state.get_mut(&alert_key) {
                        state.clear();
                    }
                    if let Some(buf) = self.event_buffers.get_mut(&alert_key) {
                        buf.clear();
                    }
                    if let Some(buf) = self.event_ref_buffers.get_mut(&alert_key) {
                        buf.clear();
                    }
                }
                return retained;
            }
        }
        None
    }

    /// Events or references a correlation reports for one group: the newest
    /// `cap` retained entries in its own `mode`, oldest first. A refs mode can
    /// read a buffer that a parent's retention made full.
    fn reported_events(
        &self,
        key: &StateKey,
        mode: CorrelationEventMode,
        cap: usize,
    ) -> ReportedEvents {
        match mode {
            CorrelationEventMode::Full => {
                let (events, sources) = self
                    .event_buffers
                    .get(key)
                    .map(|buf| buf.newest_events(cap))
                    .unwrap_or_default();
                ReportedEvents {
                    events: Some(events),
                    event_refs: None,
                    event_sources: Some(sources),
                }
            }
            CorrelationEventMode::Refs => {
                let (refs, sources) = if let Some(buf) = self.event_ref_buffers.get(key) {
                    buf.newest_refs(cap)
                } else if let Some(buf) = self.event_buffers.get(key) {
                    buf.newest_refs(cap)
                } else {
                    Default::default()
                };
                ReportedEvents {
                    events: None,
                    event_refs: Some(refs),
                    event_sources: Some(sources),
                }
            }
            CorrelationEventMode::None => ReportedEvents::default(),
        }
    }

    /// Entries a firing correlation hands to the correlations that reference
    /// it, or `None` when none of them retains events.
    fn capture_retained(&self, key: &StateKey) -> Option<Retained> {
        let retention = &self.retention[key.corr_idx];
        if !retention.feeds_retaining_parent {
            return None;
        }
        match retention.mode {
            CorrelationEventMode::Full => self.event_buffers.get(key).map(EventBuffer::retained),
            CorrelationEventMode::Refs => self
                .event_ref_buffers
                .get(key)
                .map(EventRefBuffer::retained),
            CorrelationEventMode::None => None,
        }
    }

    /// Merge the entries the firing child `via` delivered into a parent's
    /// buffer for `key`, converting full entries when the parent retains only
    /// references.
    fn merge_retained(&mut self, key: &StateKey, retained: &Retained, via: Option<&Arc<str>>) {
        let retention = &self.retention[key.corr_idx];
        let cap = retention.cap;
        match (retention.mode, retained) {
            (CorrelationEventMode::Full, Retained::Full(entries)) => {
                self.event_buffers
                    .entry(key.clone())
                    .or_insert_with(|| EventBuffer::new(cap))
                    .merge(entries, via);
            }
            (CorrelationEventMode::Refs, Retained::Refs(entries)) => {
                self.event_ref_buffers
                    .entry(key.clone())
                    .or_insert_with(|| EventRefBuffer::new(cap))
                    .merge(entries, via);
            }
            (CorrelationEventMode::Refs, Retained::Full(entries)) => {
                let refs: Vec<RefEntry> = entries.iter().filter_map(|e| e.to_ref()).collect();
                self.event_ref_buffers
                    .entry(key.clone())
                    .or_insert_with(|| EventRefBuffer::new(cap))
                    .merge(&refs, via);
            }
            // A child retains at least as strongly as every parent, so a full
            // parent only meets reference entries past the chain depth limit.
            (CorrelationEventMode::Full, Retained::Refs(_)) | (CorrelationEventMode::None, _) => {}
        }
    }

    /// Recompute the event retention each correlation needs from its own mode
    /// and cap and from every correlation that references it, directly or
    /// through another correlation.
    fn refresh_retention(&mut self) {
        let len = self.correlations.len();
        let mut retention = vec![Retention::default(); len];
        let mut done = vec![false; len];
        let mut visiting = vec![false; len];
        for idx in 0..len {
            self.compute_retention(idx, &mut retention, &mut done, &mut visiting, 0);
        }
        for (idx, entry) in retention.iter_mut().enumerate() {
            if entry.mode != CorrelationEventMode::None {
                entry.rule_refs = self.correlations[idx]
                    .rule_refs
                    .iter()
                    .map(|rule_ref| Arc::from(rule_ref.as_str()))
                    .collect();
                entry.stable_id = Some(Arc::from(self.correlation_stable_id(idx)));
            }
        }
        self.retention = retention;
        self.retention_dirty = false;
    }

    /// Resolve one correlation's retention by walking to the correlations that
    /// reference it. `add_correlation` alone does not reject cycles, so the
    /// walk stops on a correlation already being resolved and at
    /// [`MAX_CHAIN_DEPTH`].
    fn compute_retention(
        &self,
        idx: usize,
        out: &mut [Retention],
        done: &mut [bool],
        visiting: &mut [bool],
        depth: usize,
    ) -> Retention {
        if done[idx] {
            return out[idx].clone();
        }
        let own = self.own_retention(idx);
        if visiting[idx] || depth >= MAX_CHAIN_DEPTH {
            return own;
        }

        visiting[idx] = true;
        let mut result = own;
        for parent in self.referencing_correlations(idx) {
            let parent_retention = self.compute_retention(parent, out, done, visiting, depth + 1);
            result.mode = stronger_mode(result.mode, parent_retention.mode);
            if parent_retention.mode != CorrelationEventMode::None {
                result.feeds_retaining_parent = true;
                result.cap = result.cap.max(parent_retention.cap);
            }
        }
        visiting[idx] = false;

        out[idx] = result.clone();
        done[idx] = true;
        result
    }

    /// Event retention a correlation requests for itself, before propagation.
    fn own_retention(&self, idx: usize) -> Retention {
        let corr = &self.correlations[idx];
        let mode = corr
            .event_mode
            .unwrap_or(self.config.correlation_event_mode);
        let cap = corr
            .max_events
            .unwrap_or(self.config.max_correlation_events);
        Retention {
            mode,
            cap: if mode == CorrelationEventMode::None {
                0
            } else {
                cap
            },
            ..Retention::default()
        }
    }

    /// Correlations whose `rule_refs` name `idx`.
    fn referencing_correlations(&self, idx: usize) -> Vec<usize> {
        let mut parents = Vec::new();
        for key in self.chain_lookup_keys(idx) {
            if let Some(indices) = self.rule_index.get(&key) {
                for &parent in indices {
                    if !parents.contains(&parent) {
                        parents.push(parent);
                    }
                }
            }
        }
        parents
    }

    /// IDs and names a fired correlation can be referenced by.
    ///
    /// Parents index `rule_refs` as written in YAML (id or name). The
    /// emitted result only carries `rule_id`, so name-based parents need
    /// this extra key or they never see the child.
    fn chain_lookup_keys(&self, corr_idx: usize) -> Vec<String> {
        let corr = &self.correlations[corr_idx];
        let mut keys = Vec::with_capacity(2);
        keys.extend(corr.id.iter().cloned());
        if corr.name.as_ref() != corr.id.as_ref() {
            keys.extend(corr.name.iter().cloned());
        }
        keys
    }

    /// Propagate correlation results to higher-level correlations (chaining).
    ///
    /// When a correlation fires, any correlation that references it (by ID or name)
    /// is updated. Newly fired parents are appended to `out`, with their
    /// correlation indices in `out_indices`, and become the next `pending`
    /// set. Limits chain depth to 10 to prevent infinite loops.
    fn chain_correlations(
        &mut self,
        fired: &[EvaluationResult],
        fired_indices: &[usize],
        fired_retained: Vec<Option<Retained>>,
        ts: i64,
        out: &mut Vec<EvaluationResult>,
        out_indices: &mut Vec<usize>,
    ) {
        debug_assert_eq!(fired.len(), fired_indices.len());
        debug_assert_eq!(fired.len(), fired_retained.len());
        // Chaining only needs which correlation fired, for which group, and
        // the events it retained, so `pending` carries that instead of cloning
        // results. Retained entries live once per level in `retained` next to
        // the child that delivered them, and pending and work items index into
        // it, so a child that feeds several parents is not cloned per parent.
        // Only correlation results chain. Detections never reach here.
        let mut retained: Vec<(Retained, Option<Arc<str>>)> = Vec::new();
        #[allow(clippy::type_complexity)]
        let mut pending: Vec<(
            usize,
            Vec<(String, String)>,
            Option<TenantId>,
            Option<usize>,
        )> = fired_indices
            .iter()
            .zip(fired)
            .zip(fired_retained)
            .filter_map(|((&idx, result), entries)| {
                let group_key = result.as_correlation()?.group_key.clone();
                let slot = entries.map(|entries| {
                    retained.push((entries, self.retention[idx].stable_id.clone()));
                    retained.len() - 1
                });
                Some((idx, group_key, result.header.tenant_id.clone(), slot))
            })
            .collect();
        let mut depth = 0;

        while !pending.is_empty() && depth < MAX_CHAIN_DEPTH {
            depth += 1;

            // Collect work items: (corr_idx, group_key_pairs, fired_ref, tenant, retained slot)
            #[allow(clippy::type_complexity)]
            let mut work: Vec<(
                usize,
                Vec<(String, String)>,
                String,
                Option<TenantId>,
                Option<usize>,
            )> = Vec::new();
            let mut seen = std::collections::HashSet::<(usize, String, Option<TenantId>)>::new();
            for (source_idx, group_key, tenant, slot) in &pending {
                for key in self.chain_lookup_keys(*source_idx) {
                    if let Some(indices) = self.rule_index.get(&key) {
                        for &corr_idx in indices {
                            if seen.insert((corr_idx, key.clone(), tenant.clone())) {
                                work.push((
                                    corr_idx,
                                    group_key.clone(),
                                    key.clone(),
                                    tenant.clone(),
                                    *slot,
                                ));
                            }
                        }
                    }
                }
            }

            let mut next_pending = Vec::new();
            let mut next_retained = Vec::new();
            for (corr_idx, group_key_pairs, fired_ref, tenant, slot) in work {
                let (
                    corr_type,
                    timespan,
                    window_mode,
                    gap_secs,
                    level,
                    suppress_secs,
                    action,
                    event_mode,
                    max_events,
                    max_group_entries,
                    group_key,
                ) = {
                    let corr = &self.correlations[corr_idx];
                    let Some(group_key) = GroupKey::from_pairs(&group_key_pairs, &corr.group_by)
                    else {
                        continue;
                    };
                    (
                        corr.correlation_type,
                        corr.timespan_secs,
                        corr.window_mode,
                        corr.gap_secs,
                        corr.level,
                        corr.suppress_secs.or(self.config.suppress),
                        corr.action.unwrap_or(self.config.action_on_match),
                        corr.event_mode
                            .unwrap_or(self.config.correlation_event_mode),
                        corr.max_events
                            .unwrap_or(self.config.max_correlation_events),
                        corr.max_group_entries.or(self.config.max_group_entries),
                        group_key,
                    )
                };
                let state_key = StateKey {
                    tenant: tenant.clone(),
                    corr_idx,
                    group_key: group_key.clone(),
                };
                let is_new = !self.state.contains_key(&state_key);
                if is_new
                    && let Some(cap) = self.config.max_state_entries_per_tenant
                    && self.tenant_len(&state_key.tenant) >= cap
                {
                    self.evict_tenant(tenant.as_ref(), ts);
                }
                if is_new {
                    self.note_tenant_insert(&state_key);
                }
                let state = self
                    .state
                    .entry(state_key.clone())
                    .or_insert_with(|| WindowState::new_for(corr_type));

                // Late arrivals in an earlier tumbling bucket are discarded.
                // A tumbling or session reset clears the parent's buffers in
                // sync with its window state, as on the direct path.
                let decision = apply_window_open(state, ts, timespan, window_mode, gap_secs);
                if decision == WindowDecision::Discard {
                    continue;
                }
                if decision == WindowDecision::Reset {
                    if let Some(buf) = self.event_buffers.get_mut(&state_key) {
                        buf.clear();
                    }
                    if let Some(buf) = self.event_ref_buffers.get_mut(&state_key) {
                        buf.clear();
                    }
                }

                match corr_type {
                    CorrelationType::EventCount => {
                        state.push_event_count(ts);
                    }
                    CorrelationType::Temporal | CorrelationType::TemporalOrdered => {
                        state.push_temporal(ts, &fired_ref);
                    }
                    _ => {
                        state.push_event_count(ts);
                    }
                }

                // Same per-group cap as the direct path; session windows
                // keep the span anchor.
                if let Some(cap) = max_group_entries {
                    state.truncate_oldest(cap, window_mode == WindowMode::Session);
                }

                // `self.state` and `self.correlations` are disjoint fields, so
                // the mutable state borrow and this read coexist.
                let corr = &self.correlations[corr_idx];
                let fired = state.check_condition(
                    &corr.condition,
                    corr_type,
                    &corr.rule_refs,
                    corr.extended_expr.as_ref(),
                );

                if let Some(slot) = slot {
                    let (entries, via) = &retained[slot];
                    self.merge_retained(&state_key, entries, via.as_ref());
                }
                if window_mode == WindowMode::Sliding {
                    let cutoff = ts - timespan as i64;
                    if let Some(buf) = self.event_buffers.get_mut(&state_key) {
                        buf.evict(cutoff);
                    }
                    if let Some(buf) = self.event_ref_buffers.get_mut(&state_key) {
                        buf.evict(cutoff);
                    }
                }

                if let Some(agg_value) = fired {
                    let alert_key = state_key;
                    let suppressed = if let Some(suppress) = suppress_secs {
                        self.last_alert
                            .get(&alert_key)
                            .is_some_and(|&last_ts| (ts - last_ts) < suppress as i64)
                    } else {
                        false
                    };
                    if suppressed {
                        continue;
                    }

                    let reported = self.reported_events(&alert_key, event_mode, max_events);
                    let next_slot = self.capture_retained(&alert_key).map(|entries| {
                        next_retained.push((entries, self.retention[corr_idx].stable_id.clone()));
                        next_retained.len() - 1
                    });

                    let corr = &self.correlations[corr_idx];
                    let fired_group_key = group_key.to_pairs(&corr.group_by);
                    let result = EvaluationResult {
                        header: RuleHeader {
                            rule_title: corr.title.clone(),
                            rule_id: corr.id.clone(),
                            tenant_id: tenant.clone(),
                            level,
                            tags: corr.tags.clone(),
                            custom_attributes: corr.custom_attributes.clone(),
                            enrichments: None,
                            ruleset: None,
                        },
                        body: ResultBody::Correlation(CorrelationBody {
                            correlation_type: corr_type,
                            group_key: fired_group_key.clone(),
                            aggregated_value: agg_value,
                            timespan_secs: timespan,
                            events: reported.events,
                            event_refs: reported.event_refs,
                            event_sources: reported.event_sources,
                        }),
                    };
                    next_pending.push((corr_idx, fired_group_key, tenant.clone(), next_slot));
                    out.push(result);
                    out_indices.push(corr_idx);
                    self.last_alert.insert(alert_key.clone(), ts);

                    if action == CorrelationAction::Reset {
                        if let Some(state) = self.state.get_mut(&alert_key) {
                            state.clear();
                        }
                        if let Some(buf) = self.event_buffers.get_mut(&alert_key) {
                            buf.clear();
                        }
                        if let Some(buf) = self.event_ref_buffers.get_mut(&alert_key) {
                            buf.clear();
                        }
                    }
                }
            }

            pending = next_pending;
            retained = next_retained;
        }

        if !pending.is_empty() {
            log::warn!(
                "Correlation chain depth limit reached ({MAX_CHAIN_DEPTH}); \
                 {} pending result(s) were not propagated further. \
                 This may indicate a cycle in correlation references.",
                pending.len()
            );
        }
    }

    // =========================================================================
    // Timestamp extraction
    // =========================================================================

    /// Extract a Unix epoch timestamp (seconds) from an event.
    ///
    /// Tries each configured timestamp field in order. Supports:
    /// - Numeric values (epoch seconds, or epoch millis if > 1e12)
    /// - ISO 8601 strings (e.g., "2024-07-10T12:30:00Z")
    ///
    /// Returns `None` if no field yields a valid timestamp; a value before
    /// 1970 or past the representable range does not count as one.
    fn extract_event_timestamp(&self, event: &impl Event) -> Option<i64> {
        for field_name in &self.config.timestamp_fields {
            if let Some(val) = event.get_field(field_name)
                && let Some(ts) = parse_timestamp_value(&val)
            {
                return Some(ts);
            }
        }
        None
    }

    // =========================================================================
    // State management
    // =========================================================================

    /// Manually evict all expired state entries.
    pub fn evict_expired(&mut self, now_secs: i64) {
        self.evict_all(now_secs);
    }

    /// Index a new state key under its tenant while a per-tenant cap is set.
    fn note_tenant_insert(&mut self, key: &StateKey) {
        if self.config.max_state_entries_per_tenant.is_some() {
            self.tenant_keys
                .entry(key.tenant.clone())
                .or_default()
                .insert(key.clone());
        }
    }

    /// Drop a removed state key from its tenant's index.
    fn note_tenant_removal(&mut self, key: &StateKey) {
        if let Some(keys) = self.tenant_keys.get_mut(&key.tenant) {
            keys.remove(key);
            if keys.is_empty() {
                self.tenant_keys.remove(&key.tenant);
            }
        }
    }

    /// Live state entries of `tenant`, tracked while a per-tenant cap is set.
    fn tenant_len(&self, tenant: &Option<TenantId>) -> usize {
        self.tenant_keys.get(tenant).map_or(0, HashSet::len)
    }

    /// Remove one state entry and every sidecar keyed by it.
    fn remove_state_entry(&mut self, key: &StateKey) -> bool {
        let existed = self.state.remove(key).is_some();
        if existed {
            self.note_tenant_removal(key);
        }
        self.last_alert.remove(key);
        self.event_buffers.remove(key);
        self.event_ref_buffers.remove(key);
        existed
    }

    /// Evict one tenant's expired entries, then its stalest entries down to 90%
    /// of the configured per-tenant cap. Returns how many entries were removed.
    fn evict_tenant(&mut self, tenant: Option<&TenantId>, now_secs: i64) -> usize {
        let Some(cap) = self.config.max_state_entries_per_tenant else {
            return 0;
        };
        let tenant_key = tenant.cloned();
        let keys: Vec<StateKey> = self
            .tenant_keys
            .get(&tenant_key)
            .map(|keys| keys.iter().cloned().collect())
            .unwrap_or_default();

        // Expired phase: drop the tenant's emptied windows. `last_alert` stays,
        // so a group evicted here is still suppressed until `evict_all` ages
        // the alert out.
        let mut evicted = 0;
        for key in &keys {
            let Some(state) = self.state.get_mut(key) else {
                continue;
            };
            if let Some(correlation) = self.correlations.get(key.corr_idx) {
                let timespan = correlation.timespan_secs as i64;
                match correlation.window_mode {
                    WindowMode::Sliding => {
                        state.evict(now_secs - timespan);
                    }
                    mode @ (WindowMode::Tumbling | WindowMode::Session) => {
                        let staleness = if mode == WindowMode::Session {
                            correlation.gap_secs.map_or(timespan, |gap| gap as i64)
                        } else {
                            timespan
                        };
                        if state
                            .latest_timestamp()
                            .is_some_and(|last| now_secs - last > staleness)
                        {
                            state.clear();
                        }
                    }
                }
            }
            if state.is_empty() {
                self.state.remove(key);
                self.note_tenant_removal(key);
                self.event_buffers.remove(key);
                self.event_ref_buffers.remove(key);
                evicted += 1;
            }
        }

        // Stalest phase: at the cap, drop the tenant's stalest windows down to
        // 90% of it, and at least one.
        let count = self.tenant_len(&tenant_key);
        if count >= cap {
            let target = cap * 9 / 10;
            let excess = count.saturating_sub(target);
            let mut by_staleness: Vec<_> = self
                .tenant_keys
                .get(&tenant_key)
                .into_iter()
                .flatten()
                .filter_map(|key| {
                    self.state
                        .get(key)
                        .map(|state| (key, state.latest_timestamp().unwrap_or(i64::MIN)))
                })
                .collect();
            if excess < by_staleness.len() {
                by_staleness.select_nth_unstable_by_key(excess, |&(_, ts)| ts);
            }
            let stalest: Vec<_> = by_staleness
                .iter()
                .take(excess)
                .map(|&(key, _)| key.clone())
                .collect();
            for key in stalest {
                if self.remove_state_entry(&key) {
                    evicted += 1;
                }
            }
        }

        self.tenant_quota_evictions += evicted as u64;
        evicted
    }

    /// Evict expired entries and remove empty states.
    fn evict_all(&mut self, now_secs: i64) {
        // Phase 1: Time-based eviction — remove entries outside their correlation
        // window. Eviction is window-mode aware:
        //
        // - Sliding: trim entries older than the trailing cutoff, as always.
        // - Tumbling/session: never trim from the front — that would forget the
        //   bucket/session start and silently weaken the `timespan` cap (the
        //   window would drift toward sliding semantics). Instead, drop the
        //   whole group once it is stale (no event within its bucket span /
        //   session gap), which is exactly the point at which the next arrival
        //   would reset it anyway.
        let specs: Vec<(u64, WindowMode, Option<u64>)> = self
            .correlations
            .iter()
            .map(|c| (c.timespan_secs, c.window_mode, c.gap_secs))
            .collect();

        let mut removed_keys = Vec::new();
        self.state.retain(|key, state| {
            if let Some(&(timespan, mode, gap)) = specs.get(key.corr_idx) {
                match mode {
                    WindowMode::Sliding => {
                        state.evict(now_secs - timespan as i64);
                    }
                    WindowMode::Tumbling | WindowMode::Session => {
                        let staleness = if mode == WindowMode::Session {
                            gap.unwrap_or(timespan)
                        } else {
                            timespan
                        } as i64;
                        if state
                            .latest_timestamp()
                            .is_some_and(|last| now_secs - last > staleness)
                        {
                            state.clear();
                        }
                    }
                }
            }
            if state.is_empty() {
                removed_keys.push(key.clone());
                false
            } else {
                true
            }
        });
        for key in removed_keys {
            self.note_tenant_removal(&key);
        }

        // Evict event buffers in sync with window state: sliding buffers trim by
        // the trailing cutoff, tumbling/session buffers live and die with their
        // window state (dropped above when the group went stale).
        let state = &self.state;
        self.event_buffers.retain(|key, buf| {
            if let Some(&(timespan, mode, _)) = specs.get(key.corr_idx) {
                match mode {
                    WindowMode::Sliding => buf.evict(now_secs - timespan as i64),
                    WindowMode::Tumbling | WindowMode::Session => {
                        if !state.contains_key(key) {
                            return false;
                        }
                    }
                }
            }
            !buf.is_empty()
        });
        self.event_ref_buffers.retain(|key, buf| {
            if let Some(&(timespan, mode, _)) = specs.get(key.corr_idx) {
                match mode {
                    WindowMode::Sliding => buf.evict(now_secs - timespan as i64),
                    WindowMode::Tumbling | WindowMode::Session => {
                        if !state.contains_key(key) {
                            return false;
                        }
                    }
                }
            }
            !buf.is_empty()
        });

        // Phase 2: Hard cap — if still over limit after time-based eviction (e.g.
        // high-cardinality traffic with long windows), drop the stalest entries
        // until we're at 90% capacity to avoid evicting on every single event.
        if self.state.len() >= self.config.max_state_entries {
            let target = self.config.max_state_entries * 9 / 10;
            let excess = self.state.len() - target;

            log::warn!(
                "Correlation state hard cap reached ({} entries, max {}); \
                 evicting {} stalest entries to {} (90% capacity). \
                 This indicates high-cardinality traffic; consider raising \
                 max_state_entries or shortening correlation windows.",
                self.state.len(),
                self.config.max_state_entries,
                excess,
                target,
            );

            // Partition by latest timestamp so the `excess` stalest entries
            // come first, and clone only their keys.
            let mut by_staleness: Vec<_> = self
                .state
                .iter()
                .map(|(k, v)| (k, v.latest_timestamp().unwrap_or(i64::MIN)))
                .collect();
            if excess < by_staleness.len() {
                by_staleness.select_nth_unstable_by_key(excess, |&(_, ts)| ts);
            }
            let stalest: Vec<_> = by_staleness
                .iter()
                .take(excess)
                .map(|&(k, _)| k.clone())
                .collect();

            // Drop the stalest entries (and their associated event buffers)
            for key in stalest {
                self.remove_state_entry(&key);
            }
        }

        // Phase 3: Evict stale last_alert entries — remove if the suppress window
        // has passed or if the corresponding window state no longer exists.
        self.last_alert.retain(|key, &mut alert_ts| {
            let suppress = if key.corr_idx < self.correlations.len() {
                self.correlations[key.corr_idx]
                    .suppress_secs
                    .or(self.config.suppress)
                    .unwrap_or(0)
            } else {
                0
            };
            (now_secs - alert_ts) < suppress as i64
        });
    }

    /// Number of active state entries (for monitoring).
    pub fn state_count(&self) -> usize {
        self.state.len()
    }

    /// Number of detection rules loaded.
    pub fn detection_rule_count(&self) -> usize {
        self.engine.rule_count()
    }

    /// Number of correlation rules loaded.
    pub fn correlation_rule_count(&self) -> usize {
        self.correlations.len()
    }

    /// Number of active event buffers (for monitoring).
    pub fn event_buffer_count(&self) -> usize {
        self.event_buffers.len()
    }

    /// Total compressed bytes across all event buffers (for monitoring).
    pub fn event_buffer_bytes(&self) -> usize {
        self.event_buffers
            .values()
            .map(|b| b.compressed_bytes())
            .sum()
    }

    /// Number of active event ref buffers — `Refs` mode (for monitoring).
    pub fn event_ref_buffer_count(&self) -> usize {
        self.event_ref_buffers.len()
    }

    /// Access the inner stateless engine.
    pub fn engine(&self) -> &Engine<L> {
        &self.engine
    }

    /// Resolve a rule key (an id, or a title for a rule without one) to the
    /// documentation of every loaded rule that carries it, across both the
    /// detection rules and the correlations.
    pub fn rule_metadata(&self, key: &str) -> RuleMetadataLookup {
        let mut variants = Vec::new();
        self.collect_rule_metadata(key, &mut variants);
        RuleMetadataLookup::from_variants(variants)
    }

    pub(crate) fn collect_rule_metadata(&self, key: &str, out: &mut Vec<RuleBundleMetadata>) {
        self.engine.collect_rule_metadata(key, out);
        crate::rule_metadata::matching_correlations(&self.correlations, key, out);
    }

    /// Export all mutable correlation state as a serializable snapshot.
    ///
    /// The snapshot uses stable correlation identifiers (id > name > title)
    /// instead of internal indices, so it survives rule reloads as long as
    /// the correlation rules keep the same identifiers. State is nested per
    /// tenant; with tenancy off it is one `tenant: None` entry.
    pub fn export_state(&self) -> CorrelationSnapshot {
        let mut by_tenant: BTreeMap<Option<TenantId>, TenantStateSnapshot> = BTreeMap::new();

        for (key, ws) in &self.state {
            let corr_id = self.correlation_stable_id(key.corr_idx);
            by_tenant
                .entry(key.tenant.clone())
                .or_insert_with(|| TenantStateSnapshot::empty(key.tenant.clone()))
                .windows
                .entry(corr_id)
                .or_default()
                .push((key.group_key.clone(), ws.clone()));
        }

        for (key, ts) in &self.last_alert {
            let corr_id = self.correlation_stable_id(key.corr_idx);
            by_tenant
                .entry(key.tenant.clone())
                .or_insert_with(|| TenantStateSnapshot::empty(key.tenant.clone()))
                .last_alert
                .entry(corr_id)
                .or_default()
                .push((key.group_key.clone(), *ts));
        }

        for (key, buf) in &self.event_buffers {
            let corr_id = self.correlation_stable_id(key.corr_idx);
            by_tenant
                .entry(key.tenant.clone())
                .or_insert_with(|| TenantStateSnapshot::empty(key.tenant.clone()))
                .event_buffers
                .entry(corr_id)
                .or_default()
                .push((key.group_key.clone(), buf.clone()));
        }

        for (key, buf) in &self.event_ref_buffers {
            let corr_id = self.correlation_stable_id(key.corr_idx);
            by_tenant
                .entry(key.tenant.clone())
                .or_insert_with(|| TenantStateSnapshot::empty(key.tenant.clone()))
                .event_ref_buffers
                .entry(corr_id)
                .or_default()
                .push((key.group_key.clone(), buf.clone()));
        }

        CorrelationSnapshot {
            version: SNAPSHOT_VERSION,
            windows: HashMap::new(),
            last_alert: HashMap::new(),
            event_buffers: HashMap::new(),
            event_ref_buffers: HashMap::new(),
            tenants: by_tenant.into_values().collect(),
            rulesets: BTreeMap::new(),
        }
    }

    /// Import previously exported state, mapping stable identifiers back to
    /// current correlation indices. Entries whose identifiers no longer match
    /// any loaded correlation are silently dropped.
    ///
    /// A snapshot exported by a fan-out over exactly one ruleset imports that
    /// ruleset's state.
    ///
    /// Returns `false` (and imports nothing) if the snapshot version is
    /// incompatible with the current schema, or if the snapshot holds state
    /// for several rulesets.
    pub fn import_state(&mut self, snapshot: CorrelationSnapshot) -> bool {
        self.import_state_detailed(snapshot).is_some()
    }

    /// Like [`import_state`](Self::import_state), returning the counts of
    /// restored and discarded entries.
    ///
    /// Accepts versions 1 and 2. Attribution follows
    /// [`CorrelationConfig::require_tenant`]: with it set, untenanted entries
    /// are discarded; without it, tenanted entries are discarded. Returns
    /// `None` for an unknown version or a multi-ruleset snapshot that does not
    /// fit this engine.
    pub fn import_state_detailed(
        &mut self,
        mut snapshot: CorrelationSnapshot,
    ) -> Option<ImportStats> {
        if !matches!(snapshot.version, 1 | 2) {
            return None;
        }
        if !snapshot.rulesets.is_empty() {
            if snapshot.has_collection_state() || snapshot.rulesets.len() != 1 {
                return None;
            }
            let (_, inner) = std::mem::take(&mut snapshot.rulesets).pop_first()?;
            return self.import_state_detailed(inner);
        }
        let id_to_idx = self.build_id_to_index_map();
        let require_tenant = self.config.require_tenant;
        let mut stats = ImportStats::default();

        let mut tenant_states = std::mem::take(&mut snapshot.tenants);
        // The version 1 top-level maps are the untenanted bucket.
        tenant_states.push(TenantStateSnapshot {
            tenant: None,
            windows: snapshot.windows,
            last_alert: snapshot.last_alert,
            event_buffers: snapshot.event_buffers,
            event_ref_buffers: snapshot.event_ref_buffers,
        });

        for tenant_state in tenant_states {
            let entries = tenant_state.window_entries();
            let tenant = tenant_state.tenant;
            let keep = if require_tenant {
                tenant.is_some()
            } else {
                tenant.is_none()
            };
            if !keep {
                if tenant.is_none() {
                    stats.discarded_untenanted += entries;
                } else {
                    stats.discarded_tenanted += entries;
                }
                continue;
            }

            for (corr_id, groups) in tenant_state.windows {
                if let Some(&idx) = id_to_idx.get(&corr_id) {
                    for (gk, ws) in groups {
                        let key = StateKey {
                            tenant: tenant.clone(),
                            corr_idx: idx,
                            group_key: gk,
                        };
                        if self.state.insert(key.clone(), ws).is_none() {
                            self.note_tenant_insert(&key);
                        }
                        stats.restored += 1;
                    }
                }
            }

            for (corr_id, groups) in tenant_state.last_alert {
                if let Some(&idx) = id_to_idx.get(&corr_id) {
                    for (gk, ts) in groups {
                        self.last_alert.insert(
                            StateKey {
                                tenant: tenant.clone(),
                                corr_idx: idx,
                                group_key: gk,
                            },
                            ts,
                        );
                    }
                }
            }

            for (corr_id, groups) in tenant_state.event_buffers {
                if let Some(&idx) = id_to_idx.get(&corr_id) {
                    for (gk, buf) in groups {
                        self.event_buffers.insert(
                            StateKey {
                                tenant: tenant.clone(),
                                corr_idx: idx,
                                group_key: gk,
                            },
                            buf,
                        );
                    }
                }
            }

            for (corr_id, groups) in tenant_state.event_ref_buffers {
                if let Some(&idx) = id_to_idx.get(&corr_id) {
                    for (gk, buf) in groups {
                        self.event_ref_buffers.insert(
                            StateKey {
                                tenant: tenant.clone(),
                                corr_idx: idx,
                                group_key: gk,
                            },
                            buf,
                        );
                    }
                }
            }
        }

        self.resequence_imported_buffers();

        Some(stats)
    }

    /// Give restored buffer entries distinct sequence numbers, so a snapshot
    /// written before entries carried one still deduplicates on merge, and
    /// raise `next_event_seq` above every restored value.
    fn resequence_imported_buffers(&mut self) {
        let mut highest = 0u64;
        for buf in self.event_buffers.values() {
            highest = highest.max(buf.max_seq());
        }
        for buf in self.event_ref_buffers.values() {
            highest = highest.max(buf.max_seq());
        }
        self.next_event_seq = self.next_event_seq.max(highest.saturating_add(1));

        let mut next = self.next_event_seq;
        for buf in self.event_buffers.values_mut() {
            buf.sequence_unsequenced(&mut next);
        }
        for buf in self.event_ref_buffers.values_mut() {
            buf.sequence_unsequenced(&mut next);
        }
        self.next_event_seq = next;
    }

    /// Stable identifier for a correlation rule: prefers id, then name, then title.
    fn correlation_stable_id(&self, idx: usize) -> String {
        let corr = &self.correlations[idx];
        corr.id
            .clone()
            .or_else(|| corr.name.clone())
            .unwrap_or_else(|| corr.title.clone())
    }

    /// Build a reverse map from stable id → current correlation index.
    fn build_id_to_index_map(&self) -> HashMap<String, usize> {
        self.correlations
            .iter()
            .enumerate()
            .map(|(idx, _)| (self.correlation_stable_id(idx), idx))
            .collect()
    }
}

impl Default for CorrelationEngine {
    fn default() -> Self {
        Self::new(CorrelationConfig::default())
    }
}

/// Retention strength ordering: `full` over `refs` over `none`.
fn stronger_mode(a: CorrelationEventMode, b: CorrelationEventMode) -> CorrelationEventMode {
    match (a, b) {
        (CorrelationEventMode::Full, _) | (_, CorrelationEventMode::Full) => {
            CorrelationEventMode::Full
        }
        (CorrelationEventMode::Refs, _) | (_, CorrelationEventMode::Refs) => {
            CorrelationEventMode::Refs
        }
        _ => CorrelationEventMode::None,
    }
}

fn split_identified(
    identified: Vec<IdentifiedEvaluation>,
) -> (Vec<EvaluationResult>, Vec<RuleIdentity>) {
    identified
        .into_iter()
        .map(|identified| {
            (
                identified.result,
                (identified.rule_id, identified.rule_name),
            )
        })
        .unzip()
}

// =============================================================================
// Timestamp parsing helpers
// =============================================================================

/// Extract a timestamp from an event using the given field names.
///
/// Standalone version of `CorrelationEngine::extract_event_timestamp` for use
/// in contexts where borrowing `&self` is not possible (e.g. rayon closures).
fn extract_event_ts(event: &impl Event, timestamp_fields: &[String]) -> Option<i64> {
    for field_name in timestamp_fields {
        if let Some(val) = event.get_field(field_name)
            && let Some(ts) = parse_timestamp_value(&val)
        {
            return Some(ts);
        }
    }
    None
}

/// Parse an [`EventValue`] as a Unix epoch timestamp in seconds.
///
/// Values before 1970, non-finite floats, and dates past the representable
/// range are `None`, so the next timestamp field or the fallback applies.
fn parse_timestamp_value(val: &EventValue) -> Option<i64> {
    match val {
        EventValue::Int(i) => epoch_seconds_from_int(*i),
        EventValue::Float(f) => epoch_seconds_from_float(*f),
        EventValue::Str(s) => parse_timestamp_str(s)
            .map(|dt| dt.timestamp())
            .filter(|ts| *ts >= 0),
        _ => None,
    }
}

/// Render a value for a `value_count` distinct key. Unlike a group key, a
/// null counts as the distinct value `null`.
fn value_to_string_for_count(v: &EventValue) -> Option<String> {
    match v {
        EventValue::Null => Some("null".to_string()),
        v => v.as_str().map(Cow::into_owned),
    }
}

/// Build a composite distinct-key for `value_count` over one or more fields.
///
/// Each field's value is rendered with [`value_to_string_for_count`] and the
/// rendered parts are joined with `\u{1f}` (the ASCII Unit Separator), which
/// is unlikely to occur in normal log data. If any field is missing or has a
/// type that does not produce a stable string representation, the event is
/// excluded from the distinct count (return `None`), matching the historical
/// single-field behavior.
fn composite_value_count_key(event: &impl Event, fields: &[String]) -> Option<String> {
    // Common case: exactly one field. Avoid the separator overhead.
    if let [field_name] = fields {
        let val = event.get_field(field_name)?;
        return value_to_string_for_count(&val);
    }

    let mut parts = Vec::with_capacity(fields.len());
    for field_name in fields {
        let val = event.get_field(field_name)?;
        let rendered = value_to_string_for_count(&val)?;
        parts.push(rendered);
    }
    Some(parts.join("\u{1f}"))
}

/// Convert an [`EventValue`] to f64 for numeric aggregation.
fn value_to_f64_ev(v: &EventValue) -> Option<f64> {
    v.as_f64()
}