synapse-waf 0.9.1

High-performance WAF and reverse proxy with embedded intelligence — built on Cloudflare Pingora
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
//! Thread-safe actor manager using DashMap for concurrent access.
//!
//! Implements per-actor state tracking with LRU eviction and background cleanup.

use std::cmp::Ordering as CmpOrdering;
use std::collections::HashSet;
use std::net::IpAddr;
use std::sync::atomic::{AtomicU32, AtomicU64, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};

use dashmap::DashMap;
use parking_lot::RwLock as PLRwLock;
use serde::{Deserialize, Serialize};
use tokio::sync::Notify;

// ============================================================================
// Configuration
// ============================================================================

/// Configuration for ActorManager.
#[derive(Debug, Clone)]
pub struct ActorConfig {
    /// Maximum number of actors to track (LRU eviction when exceeded).
    /// Default: 100,000
    pub max_actors: usize,

    /// Interval in seconds between decay cycles.
    /// Default: 900 (15 minutes)
    pub decay_interval_secs: u64,

    /// Interval in seconds between persistence cycles.
    /// Default: 300 (5 minutes)
    pub persist_interval_secs: u64,

    /// Threshold for correlation confidence.
    /// Default: 0.7
    pub correlation_threshold: f64,

    /// Factor by which risk scores decay each cycle.
    /// Default: 0.9
    pub risk_decay_factor: f64,

    /// Maximum number of rule matches to track per actor.
    /// Default: 100
    pub max_rule_matches: usize,

    /// Maximum number of session IDs to track per actor.
    /// Prevents memory exhaustion from session hijacking attacks.
    /// Default: 50
    pub max_session_ids: usize,

    /// Maximum number of fingerprints to track per actor.
    /// Prevents memory exhaustion from fingerprint flooding attacks.
    /// Default: 20
    pub max_fingerprints_per_actor: usize,

    /// Maximum number of global fingerprint-to-actor mappings.
    /// Prevents memory exhaustion from unique fingerprint attacks.
    /// Default: 500,000 (5x max_actors)
    pub max_fingerprint_mappings: usize,

    /// Whether actor tracking is enabled.
    /// Default: true
    pub enabled: bool,

    /// Maximum risk score (default: 100.0).
    pub max_risk: f64,
}

impl Default for ActorConfig {
    fn default() -> Self {
        Self {
            max_actors: 100_000,
            decay_interval_secs: 900,
            persist_interval_secs: 300,
            correlation_threshold: 0.7,
            risk_decay_factor: 0.9,
            max_rule_matches: 100,
            max_session_ids: 50,               // Prevents memory exhaustion
            max_fingerprints_per_actor: 20,    // Prevents per-actor memory exhaustion
            max_fingerprint_mappings: 500_000, // 5x max_actors for global limit
            enabled: true,
            max_risk: 100.0,
        }
    }
}

// ============================================================================
// Rule Match Record
// ============================================================================

/// Rule match record for actor history.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RuleMatch {
    /// Rule identifier (e.g., "sqli-001").
    pub rule_id: String,

    /// Timestamp when the rule was matched (ms since epoch).
    pub timestamp: u64,

    /// Risk contribution from this rule match.
    pub risk_contribution: f64,

    /// Category of the rule (e.g., "sqli", "xss", "path_traversal").
    pub category: String,
}

impl RuleMatch {
    /// Create a new rule match record.
    pub fn new(rule_id: String, risk_contribution: f64, category: String) -> Self {
        Self {
            rule_id,
            timestamp: now_ms(),
            risk_contribution,
            category,
        }
    }
}

// ============================================================================
// Actor State
// ============================================================================

/// Per-actor state tracking.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ActorState {
    /// Unique actor identifier (UUID v4).
    pub actor_id: String,

    /// Accumulated risk score (0.0 - max_risk).
    pub risk_score: f64,

    /// History of rule matches for this actor.
    pub rule_matches: Vec<RuleMatch>,

    /// Count of anomalous behaviors detected.
    pub anomaly_count: u64,

    /// Session IDs associated with this actor.
    pub session_ids: Vec<String>,

    /// First seen timestamp (ms since epoch).
    pub first_seen: u64,

    /// Last seen timestamp (ms since epoch).
    pub last_seen: u64,

    /// IP addresses associated with this actor.
    #[serde(with = "ip_set_serde")]
    pub ips: HashSet<IpAddr>,

    /// Fingerprints associated with this actor.
    pub fingerprints: HashSet<String>,

    /// Whether this actor is currently blocked.
    pub is_blocked: bool,

    /// Reason for blocking (if blocked).
    pub block_reason: Option<String>,

    /// Timestamp when blocked (ms since epoch).
    pub blocked_since: Option<u64>,
}

impl ActorState {
    /// Create a new actor state.
    pub fn new(actor_id: String) -> Self {
        let now = now_ms();
        Self {
            actor_id,
            risk_score: 0.0,
            rule_matches: Vec::new(),
            anomaly_count: 0,
            session_ids: Vec::new(),
            first_seen: now,
            last_seen: now,
            ips: HashSet::new(),
            fingerprints: HashSet::new(),
            is_blocked: false,
            block_reason: None,
            blocked_since: None,
        }
    }

    /// Update last seen timestamp.
    pub fn touch(&mut self) {
        self.last_seen = now_ms();
    }

    /// Add an IP address to this actor.
    pub fn add_ip(&mut self, ip: IpAddr) {
        self.ips.insert(ip);
        self.touch();
    }

    /// Add a fingerprint to this actor with a maximum limit.
    ///
    /// Returns `true` if the fingerprint was added, `false` if at capacity or empty.
    pub fn add_fingerprint(&mut self, fingerprint: String, max_fingerprints: usize) -> bool {
        if fingerprint.is_empty() {
            return false;
        }

        // Check if already present (no limit needed)
        if self.fingerprints.contains(&fingerprint) {
            self.touch();
            return true;
        }

        // Enforce per-actor fingerprint limit to prevent memory exhaustion
        if self.fingerprints.len() >= max_fingerprints {
            // At capacity - don't add new fingerprint
            self.touch();
            return false;
        }

        self.fingerprints.insert(fingerprint);
        self.touch();
        true
    }

    /// Add a rule match to this actor's history.
    pub fn add_rule_match(&mut self, rule_match: RuleMatch, max_matches: usize) {
        self.rule_matches.push(rule_match);
        self.touch();

        // Trim to max matches (keep most recent)
        if self.rule_matches.len() > max_matches {
            let excess = self.rule_matches.len() - max_matches;
            self.rule_matches.drain(0..excess);
        }
    }

    /// Get the count of matches for a specific rule.
    pub fn get_rule_match_count(&self, rule_id: &str) -> usize {
        self.rule_matches
            .iter()
            .filter(|m| m.rule_id == rule_id)
            .count()
    }
}

/// Custom serde implementation for HashSet<IpAddr>.
mod ip_set_serde {
    use serde::{Deserialize, Deserializer, Serialize, Serializer};
    use std::collections::HashSet;
    use std::net::IpAddr;

    pub fn serialize<S>(set: &HashSet<IpAddr>, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let strings: Vec<String> = set.iter().map(|ip| ip.to_string()).collect();
        strings.serialize(serializer)
    }

    pub fn deserialize<'de, D>(deserializer: D) -> Result<HashSet<IpAddr>, D::Error>
    where
        D: Deserializer<'de>,
    {
        let strings: Vec<String> = Vec::deserialize(deserializer)?;
        let mut set = HashSet::new();
        for s in strings {
            if let Ok(ip) = s.parse() {
                set.insert(ip);
            }
        }
        Ok(set)
    }
}

// ============================================================================
// Statistics
// ============================================================================

/// Statistics for monitoring the actor manager.
#[derive(Debug, Default)]
pub struct ActorStats {
    /// Total number of actors currently tracked.
    pub total_actors: AtomicU64,

    /// Number of blocked actors.
    pub blocked_actors: AtomicU64,

    /// Total correlations made (IP-to-actor or fingerprint-to-actor).
    pub correlations_made: AtomicU64,

    /// Total actors evicted due to LRU capacity.
    pub evictions: AtomicU64,

    /// Total actors created.
    pub total_created: AtomicU64,

    /// Total rule matches recorded.
    pub total_rule_matches: AtomicU64,

    /// Total fingerprint mappings evicted due to capacity limits.
    pub fingerprint_evictions: AtomicU64,
}

impl ActorStats {
    /// Create a new stats instance.
    pub fn new() -> Self {
        Self::default()
    }

    /// Get a snapshot of the current statistics.
    pub fn snapshot(&self) -> ActorStatsSnapshot {
        ActorStatsSnapshot {
            total_actors: self.total_actors.load(Ordering::Relaxed),
            blocked_actors: self.blocked_actors.load(Ordering::Relaxed),
            correlations_made: self.correlations_made.load(Ordering::Relaxed),
            evictions: self.evictions.load(Ordering::Relaxed),
            total_created: self.total_created.load(Ordering::Relaxed),
            total_rule_matches: self.total_rule_matches.load(Ordering::Relaxed),
            fingerprint_evictions: self.fingerprint_evictions.load(Ordering::Relaxed),
        }
    }
}

/// Snapshot of actor statistics (for serialization).
#[derive(Debug, Clone, Serialize)]
pub struct ActorStatsSnapshot {
    pub total_actors: u64,
    pub blocked_actors: u64,
    pub correlations_made: u64,
    pub evictions: u64,
    pub total_created: u64,
    pub total_rule_matches: u64,
    pub fingerprint_evictions: u64,
}

// ============================================================================
// Actor Manager
// ============================================================================

/// Manages actor state with LRU eviction.
///
/// Cached JA4 cluster data: (timestamp, [(fingerprint, actor_ids, max_risk)])
type FingerprintClusterCache = Option<(Instant, Vec<(String, Vec<String>, f64)>)>;

/// Thread-safe implementation using DashMap for lock-free concurrent access.
#[derive(Debug)]
pub struct ActorManager {
    /// Actors by actor_id (primary storage).
    actors: DashMap<String, ActorState>,

    /// IP address to actor_id mapping.
    ip_to_actor: DashMap<IpAddr, String>,

    /// Fingerprint to actor_id mapping.
    fingerprint_to_actor: DashMap<String, String>,

    /// Configuration.
    config: ActorConfig,

    /// Statistics.
    stats: Arc<ActorStats>,

    /// Shutdown signal.
    shutdown: Arc<Notify>,

    /// Touch counter for lazy eviction.
    touch_counter: AtomicU32,

    /// JA4 cluster cache for TUI performance (labs-tui optimization).
    fingerprint_groups_cache: PLRwLock<FingerprintClusterCache>,
}

impl ActorManager {
    /// Create a new actor manager with the given configuration.
    pub fn new(config: ActorConfig) -> Self {
        Self {
            actors: DashMap::with_capacity(config.max_actors),
            ip_to_actor: DashMap::with_capacity(config.max_actors),
            fingerprint_to_actor: DashMap::with_capacity(config.max_actors * 2),
            config,
            stats: Arc::new(ActorStats::new()),
            shutdown: Arc::new(Notify::new()),
            touch_counter: AtomicU32::new(0),
            fingerprint_groups_cache: PLRwLock::new(None),
        }
    }

    /// Get the configuration.
    pub fn config(&self) -> &ActorConfig {
        &self.config
    }

    /// Check if actor tracking is enabled.
    pub fn is_enabled(&self) -> bool {
        self.config.enabled
    }

    /// Get the number of tracked actors.
    pub fn len(&self) -> usize {
        self.actors.len()
    }

    /// Check if the store is empty.
    pub fn is_empty(&self) -> bool {
        self.actors.is_empty()
    }

    /// Get or create an actor for the given IP and optional fingerprint.
    ///
    /// # Correlation Logic
    /// 1. Check if IP is already mapped to an actor
    /// 2. Check if fingerprint is already mapped to an actor
    /// 3. If both match different actors, prefer fingerprint (more stable)
    /// 4. If no match, create a new actor
    ///
    /// # Returns
    /// The actor_id for the correlated or newly created actor.
    pub fn get_or_create_actor(&self, ip: IpAddr, fingerprint: Option<&str>) -> String {
        if !self.config.enabled {
            return generate_actor_id();
        }

        // Check capacity and evict if needed
        self.maybe_evict();

        // Try to correlate to existing actor
        if let Some(actor_id) = self.correlate_actor(ip, fingerprint) {
            // Update the existing actor
            if let Some(mut entry) = self.actors.get_mut(&actor_id) {
                entry.add_ip(ip);
                if let Some(fp) = fingerprint {
                    if !fp.is_empty() {
                        // Only update fingerprint mapping if the actor accepted it
                        if entry
                            .add_fingerprint(fp.to_string(), self.config.max_fingerprints_per_actor)
                        {
                            // Check global fingerprint mapping capacity before inserting
                            self.maybe_evict_fingerprint_mappings();
                            self.fingerprint_to_actor
                                .insert(fp.to_string(), actor_id.clone());
                        }
                    }
                }
                // Ensure IP mapping is current
                self.ip_to_actor.insert(ip, actor_id.clone());
            }
            return actor_id;
        }

        // Create new actor
        let actor_id = generate_actor_id();
        let mut actor = ActorState::new(actor_id.clone());
        actor.add_ip(ip);

        if let Some(fp) = fingerprint {
            if !fp.is_empty() {
                // Only update fingerprint mapping if the actor accepted it
                if actor.add_fingerprint(fp.to_string(), self.config.max_fingerprints_per_actor) {
                    // Check global fingerprint mapping capacity before inserting
                    self.maybe_evict_fingerprint_mappings();
                    self.fingerprint_to_actor
                        .insert(fp.to_string(), actor_id.clone());
                }
            }
        }

        // Insert mappings
        self.ip_to_actor.insert(ip, actor_id.clone());
        self.actors.insert(actor_id.clone(), actor);

        // Update stats
        self.stats.total_actors.fetch_add(1, Ordering::Relaxed);
        self.stats.total_created.fetch_add(1, Ordering::Relaxed);

        actor_id
    }

    /// Record a rule match for an actor.
    ///
    /// # Arguments
    /// * `actor_id` - The actor ID to record the match for
    /// * `rule_id` - The rule that matched
    /// * `risk_contribution` - Risk points to add
    /// * `category` - Category of the rule (e.g., "sqli", "xss")
    pub fn record_rule_match(
        &self,
        actor_id: &str,
        rule_id: &str,
        risk_contribution: f64,
        category: &str,
    ) {
        if !self.config.enabled {
            return;
        }

        if let Some(mut entry) = self.actors.get_mut(actor_id) {
            let rule_match =
                RuleMatch::new(rule_id.to_string(), risk_contribution, category.to_string());

            // Add risk (capped at max)
            entry.risk_score = (entry.risk_score + risk_contribution).min(self.config.max_risk);

            // Add rule match to history
            entry.add_rule_match(rule_match, self.config.max_rule_matches);

            // Update stats
            self.stats
                .total_rule_matches
                .fetch_add(1, Ordering::Relaxed);
        }
    }

    /// Touch an actor to update last seen timestamp.
    pub fn touch_actor(&self, actor_id: &str) {
        if !self.config.enabled {
            return;
        }

        if let Some(mut entry) = self.actors.get_mut(actor_id) {
            entry.touch();
        }
    }

    /// Get actor state by ID.
    pub fn get_actor(&self, actor_id: &str) -> Option<ActorState> {
        self.actors.get(actor_id).map(|entry| entry.value().clone())
    }

    /// Get actor by IP address.
    pub fn get_actor_by_ip(&self, ip: IpAddr) -> Option<ActorState> {
        self.ip_to_actor
            .get(&ip)
            .and_then(|actor_id| self.actors.get(actor_id.value()).map(|e| e.value().clone()))
    }

    /// Get actor by fingerprint.
    pub fn get_actor_by_fingerprint(&self, fingerprint: &str) -> Option<ActorState> {
        self.fingerprint_to_actor
            .get(fingerprint)
            .and_then(|actor_id| self.actors.get(actor_id.value()).map(|e| e.value().clone()))
    }

    /// Block an actor.
    ///
    /// # Returns
    /// `true` if the actor was blocked, `false` if not found.
    pub fn block_actor(&self, actor_id: &str, reason: &str) -> bool {
        if let Some(mut entry) = self.actors.get_mut(actor_id) {
            if !entry.is_blocked {
                entry.is_blocked = true;
                entry.block_reason = Some(reason.to_string());
                entry.blocked_since = Some(now_ms());
                self.stats.blocked_actors.fetch_add(1, Ordering::Relaxed);
            }
            true
        } else {
            false
        }
    }

    /// Unblock an actor.
    ///
    /// # Returns
    /// `true` if the actor was unblocked, `false` if not found.
    pub fn unblock_actor(&self, actor_id: &str) -> bool {
        if let Some(mut entry) = self.actors.get_mut(actor_id) {
            if entry.is_blocked {
                entry.is_blocked = false;
                entry.block_reason = None;
                entry.blocked_since = None;
                self.stats.blocked_actors.fetch_sub(1, Ordering::Relaxed);
            }
            true
        } else {
            false
        }
    }

    /// Check if an actor is blocked.
    pub fn is_blocked(&self, actor_id: &str) -> bool {
        self.actors
            .get(actor_id)
            .map(|entry| entry.is_blocked)
            .unwrap_or(false)
    }

    /// Associate a session with an actor.
    /// Session IDs are bounded by max_session_ids to prevent memory exhaustion.
    pub fn bind_session(&self, actor_id: &str, session_id: &str) {
        if let Some(mut entry) = self.actors.get_mut(actor_id) {
            if !entry.session_ids.contains(&session_id.to_string()) {
                // SECURITY: Enforce max session_ids to prevent memory exhaustion
                if entry.session_ids.len() >= self.config.max_session_ids {
                    // Remove oldest session (FIFO)
                    entry.session_ids.remove(0);
                }
                entry.session_ids.push(session_id.to_string());
                entry.touch();
            }
        }
    }

    /// List actors with pagination.
    ///
    /// # Arguments
    /// * `limit` - Maximum number of actors to return
    /// * `offset` - Number of actors to skip
    ///
    /// # Returns
    /// Vector of actor states sorted by last_seen (most recent first).
    pub fn list_actors(&self, limit: usize, offset: usize) -> Vec<ActorState> {
        let mut actors: Vec<ActorState> = self
            .actors
            .iter()
            .map(|entry| entry.value().clone())
            .collect();

        // Sort by last_seen (most recent first)
        actors.sort_by_key(|a| std::cmp::Reverse(a.last_seen));

        // Apply pagination
        actors.into_iter().skip(offset).take(limit).collect()
    }

    /// List actors above a minimum risk score.
    ///
    /// Results are sorted by risk score (desc), then last_seen (desc).
    pub fn list_by_min_risk(&self, min_risk: f64, limit: usize, offset: usize) -> Vec<ActorState> {
        let mut actors: Vec<ActorState> = self
            .actors
            .iter()
            .filter(|entry| entry.value().risk_score >= min_risk)
            .map(|entry| entry.value().clone())
            .collect();

        actors.sort_by(|a, b| {
            b.risk_score
                .partial_cmp(&a.risk_score)
                .unwrap_or(CmpOrdering::Equal)
                .then_with(|| b.last_seen.cmp(&a.last_seen))
        });

        actors.into_iter().skip(offset).take(limit).collect()
    }

    /// List blocked actors.
    pub fn list_blocked_actors(&self) -> Vec<ActorState> {
        self.actors
            .iter()
            .filter(|entry| entry.is_blocked)
            .map(|entry| entry.value().clone())
            .collect()
    }

    /// Returns groups of actors sharing the same fingerprints.
    /// Used for identifying botnet clusters in the TUI.
    ///
    /// Optimized with a 1-second cache to avoid full table scans on every TUI tick.
    pub fn get_fingerprint_groups(&self, limit: usize) -> Vec<(String, Vec<String>, f64)> {
        // Check cache first
        {
            let cache = self.fingerprint_groups_cache.read();
            if let Some((timestamp, data)) = &*cache {
                if timestamp.elapsed() < Duration::from_secs(1) {
                    let mut result = data.clone();
                    result.truncate(limit);
                    return result;
                }
            }
        }

        use std::collections::HashMap;
        let mut groups: HashMap<String, (Vec<String>, f64)> = HashMap::new();

        for entry in self.actors.iter() {
            let actor = entry.value();
            for fp in &actor.fingerprints {
                let group = groups
                    .entry(fp.clone())
                    .or_insert_with(|| (Vec::new(), 0.0));
                group.0.push(actor.actor_id.clone());
                group.1 = group.1.max(actor.risk_score);
            }
        }

        let mut sorted_groups: Vec<_> = groups
            .into_iter()
            .map(|(fp, (actors, risk))| (fp, actors, risk))
            .collect();

        // Sort by number of actors in group (descending)
        sorted_groups.sort_by_key(|a| std::cmp::Reverse(a.1.len()));

        // Update cache
        {
            let mut cache = self.fingerprint_groups_cache.write();
            *cache = Some((Instant::now(), sorted_groups.clone()));
        }

        sorted_groups.truncate(limit);
        sorted_groups
    }

    /// Start background tasks (decay, cleanup).
    ///
    /// Spawns a background task that periodically:
    /// 1. Decays risk scores by the decay factor
    /// 2. Evicts stale actors if over capacity
    pub fn start_background_tasks(self: Arc<Self>) {
        let manager = self;
        let decay_interval = Duration::from_secs(manager.config.decay_interval_secs);

        tokio::spawn(async move {
            let mut interval = tokio::time::interval(decay_interval);

            loop {
                tokio::select! {
                    _ = interval.tick() => {
                        // Check shutdown
                        if Arc::strong_count(&manager.shutdown) == 1 {
                            // Only this task holds a reference, shutting down
                            break;
                        }

                        // Decay risk scores
                        manager.decay_scores();

                        // Evict stale actors
                        manager.evict_if_needed();
                    }
                    _ = manager.shutdown.notified() => {
                        log::info!("Actor manager background tasks shutting down");
                        break;
                    }
                }
            }
        });
    }

    /// Signal shutdown for background tasks.
    pub fn shutdown(&self) {
        self.shutdown.notify_one();
    }

    /// Get statistics.
    pub fn stats(&self) -> &ActorStats {
        &self.stats
    }

    /// Clear all actors (primarily for testing).
    pub fn clear(&self) {
        self.actors.clear();
        self.ip_to_actor.clear();
        self.fingerprint_to_actor.clear();
        self.stats.total_actors.store(0, Ordering::Relaxed);
        self.stats.blocked_actors.store(0, Ordering::Relaxed);
    }

    /// Create a snapshot of all actors for persistence.
    ///
    /// Returns all actors regardless of status.
    pub fn snapshot(&self) -> Vec<ActorState> {
        self.actors.iter().map(|e| e.value().clone()).collect()
    }

    /// Restore actors from a snapshot.
    ///
    /// Clears existing state and loads the provided actors.
    pub fn restore(&self, actors: Vec<ActorState>) {
        // Clear existing state
        self.clear();

        let mut blocked_count: u64 = 0;

        // Restore actors and mappings
        for actor in actors {
            let actor_id = actor.actor_id.clone();

            // Restore IP mappings
            for ip in &actor.ips {
                self.ip_to_actor.insert(*ip, actor_id.clone());
            }

            // Restore fingerprint mappings
            for fp in &actor.fingerprints {
                self.fingerprint_to_actor
                    .insert(fp.clone(), actor_id.clone());
            }

            // Track blocked count
            if actor.is_blocked {
                blocked_count += 1;
            }

            // Insert actor
            self.actors.insert(actor_id, actor);
        }

        // Update stats
        let actor_count = self.actors.len() as u64;
        self.stats
            .total_actors
            .store(actor_count, Ordering::Relaxed);
        self.stats
            .blocked_actors
            .store(blocked_count, Ordering::Relaxed);
        self.stats
            .total_created
            .store(actor_count, Ordering::Relaxed);
    }

    // ========================================================================
    // Private Methods
    // ========================================================================

    /// Decay risk scores for all actors.
    fn decay_scores(&self) {
        let decay_factor = self.config.risk_decay_factor;

        for mut entry in self.actors.iter_mut() {
            let actor = entry.value_mut();
            if actor.risk_score > 0.0 {
                actor.risk_score *= decay_factor;

                // Floor very small values to zero
                if actor.risk_score < 0.01 {
                    actor.risk_score = 0.0;
                }
            }
        }
    }

    /// Evict actors if over capacity.
    fn evict_if_needed(&self) {
        let current_len = self.actors.len();
        if current_len <= self.config.max_actors {
            return;
        }

        // Evict oldest 1% of actors
        let evict_count = (self.config.max_actors / 100).max(1);
        self.evict_oldest(evict_count);
    }

    /// Maybe evict oldest actors if at capacity.
    ///
    /// Uses lazy eviction: only check every 100th operation.
    fn maybe_evict(&self) {
        let count = self.touch_counter.fetch_add(1, Ordering::Relaxed);
        if !count.is_multiple_of(100) {
            return;
        }

        if self.actors.len() < self.config.max_actors {
            return;
        }

        // Evict oldest 1% of actors
        let evict_count = (self.config.max_actors / 100).max(1);
        self.evict_oldest(evict_count);
    }

    /// Maybe evict fingerprint mappings if at capacity.
    ///
    /// Prevents unbounded memory growth from fingerprint flooding attacks.
    /// Evicts random entries when capacity is exceeded (fingerprints don't
    /// have timestamps, so we use random eviction).
    fn maybe_evict_fingerprint_mappings(&self) {
        let current_len = self.fingerprint_to_actor.len();
        if current_len < self.config.max_fingerprint_mappings {
            return;
        }

        // Evict 10% of entries to avoid repeated evictions
        let target_len = (self.config.max_fingerprint_mappings * 9) / 10;
        let to_evict = current_len.saturating_sub(target_len);

        if to_evict == 0 {
            return;
        }

        // Collect keys to evict (sample from iteration order)
        let keys_to_evict: Vec<String> = self
            .fingerprint_to_actor
            .iter()
            .take(to_evict)
            .map(|entry| entry.key().clone())
            .collect();

        // Remove collected entries
        for key in keys_to_evict {
            self.fingerprint_to_actor.remove(&key);
        }

        self.stats
            .fingerprint_evictions
            .fetch_add(to_evict as u64, Ordering::Relaxed);
    }

    /// Evict the N oldest actors by last_seen timestamp.
    ///
    /// Uses sampling to avoid O(n) collection of all actors.
    fn evict_oldest(&self, count: usize) {
        let sample_size = (count * 10).min(1000).min(self.actors.len());

        if sample_size == 0 {
            return;
        }

        // Sample actors
        let mut candidates: Vec<(String, u64)> = Vec::with_capacity(sample_size);
        for entry in self.actors.iter().take(sample_size) {
            candidates.push((entry.key().clone(), entry.value().last_seen));
        }

        // Sort by last_seen (oldest first)
        candidates.sort_unstable_by_key(|(_, ts)| *ts);

        // Evict oldest N from sample
        for (actor_id, _) in candidates.into_iter().take(count) {
            self.remove_actor(&actor_id);
            self.stats.evictions.fetch_add(1, Ordering::Relaxed);
        }
    }

    /// Remove an actor and clean up all mappings.
    fn remove_actor(&self, actor_id: &str) {
        if let Some((_, actor)) = self.actors.remove(actor_id) {
            // Remove IP mappings
            for ip in &actor.ips {
                self.ip_to_actor.remove(ip);
            }

            // Remove fingerprint mappings
            for fp in &actor.fingerprints {
                self.fingerprint_to_actor.remove(fp);
            }

            // Update stats
            self.stats.total_actors.fetch_sub(1, Ordering::Relaxed);
            if actor.is_blocked {
                self.stats.blocked_actors.fetch_sub(1, Ordering::Relaxed);
            }
        }
    }

    /// Correlate an IP and/or fingerprint to an existing actor.
    ///
    /// # Returns
    /// The actor_id if correlation found, None otherwise.
    fn correlate_actor(&self, ip: IpAddr, fingerprint: Option<&str>) -> Option<String> {
        let ip_actor = self.ip_to_actor.get(&ip).map(|r| r.value().clone());

        let fp_actor = fingerprint.and_then(|fp| {
            if fp.is_empty() {
                None
            } else {
                self.fingerprint_to_actor.get(fp).map(|r| r.value().clone())
            }
        });

        match (ip_actor, fp_actor) {
            (Some(ip_id), Some(fp_id)) => {
                // Both match - prefer fingerprint (more stable)
                if ip_id == fp_id {
                    Some(ip_id)
                } else {
                    // Different actors - merge them by preferring fingerprint
                    self.stats.correlations_made.fetch_add(1, Ordering::Relaxed);
                    Some(fp_id)
                }
            }
            (Some(id), None) => {
                self.stats.correlations_made.fetch_add(1, Ordering::Relaxed);
                Some(id)
            }
            (None, Some(id)) => {
                self.stats.correlations_made.fetch_add(1, Ordering::Relaxed);
                Some(id)
            }
            (None, None) => None,
        }
    }
}

impl Default for ActorManager {
    fn default() -> Self {
        Self::new(ActorConfig::default())
    }
}

// ============================================================================
// Helper Functions
// ============================================================================

/// Generate a unique actor ID using cryptographically secure random bytes.
fn generate_actor_id() -> String {
    // Use getrandom for cryptographically secure random bytes
    let mut bytes = [0u8; 16];
    getrandom::getrandom(&mut bytes).expect("Failed to get random bytes");

    // Format as UUID v4 with proper version and variant bits
    bytes[6] = (bytes[6] & 0x0F) | 0x40; // Version 4
    bytes[8] = (bytes[8] & 0x3F) | 0x80; // Variant 1

    format!(
        "{:08x}-{:04x}-{:04x}-{:04x}-{:012x}",
        u32::from_be_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]),
        u16::from_be_bytes([bytes[4], bytes[5]]),
        u16::from_be_bytes([bytes[6], bytes[7]]),
        u16::from_be_bytes([bytes[8], bytes[9]]),
        u64::from_be_bytes([
            0, 0, bytes[10], bytes[11], bytes[12], bytes[13], bytes[14], bytes[15]
        ])
    )
}

/// Get current time in milliseconds since Unix epoch.
#[inline]
fn now_ms() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_millis() as u64)
        .unwrap_or(0)
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use std::thread;

    // ========================================================================
    // Helper Functions
    // ========================================================================

    fn create_test_manager() -> ActorManager {
        ActorManager::new(ActorConfig {
            max_actors: 1000,
            ..Default::default()
        })
    }

    fn create_test_ip(last_octet: u8) -> IpAddr {
        format!("192.168.1.{}", last_octet).parse().unwrap()
    }

    // ========================================================================
    // Actor Creation and Retrieval Tests
    // ========================================================================

    #[test]
    fn test_actor_creation() {
        let manager = create_test_manager();
        let ip = create_test_ip(1);

        let actor_id = manager.get_or_create_actor(ip, None);

        assert!(!actor_id.is_empty());
        assert_eq!(manager.len(), 1);

        let actor = manager.get_actor(&actor_id).unwrap();
        assert_eq!(actor.actor_id, actor_id);
        assert!(actor.ips.contains(&ip));
        assert!(!actor.is_blocked);
    }

    #[test]
    fn test_actor_retrieval_by_ip() {
        let manager = create_test_manager();
        let ip = create_test_ip(1);

        let actor_id = manager.get_or_create_actor(ip, None);
        let retrieved = manager.get_actor_by_ip(ip).unwrap();

        assert_eq!(retrieved.actor_id, actor_id);
    }

    #[test]
    fn test_actor_retrieval_by_fingerprint() {
        let manager = create_test_manager();
        let ip = create_test_ip(1);
        let fingerprint = "t13d1516h2_abc123";

        let actor_id = manager.get_or_create_actor(ip, Some(fingerprint));
        let retrieved = manager.get_actor_by_fingerprint(fingerprint).unwrap();

        assert_eq!(retrieved.actor_id, actor_id);
    }

    #[test]
    fn test_actor_nonexistent() {
        let manager = create_test_manager();

        assert!(manager.get_actor("nonexistent").is_none());
        assert!(manager.get_actor_by_ip(create_test_ip(99)).is_none());
        assert!(manager.get_actor_by_fingerprint("nonexistent").is_none());
    }

    // ========================================================================
    // IP and Fingerprint Correlation Tests
    // ========================================================================

    #[test]
    fn test_ip_correlation() {
        let manager = create_test_manager();
        let ip = create_test_ip(1);

        // First request
        let actor_id1 = manager.get_or_create_actor(ip, None);

        // Second request from same IP
        let actor_id2 = manager.get_or_create_actor(ip, None);

        assert_eq!(actor_id1, actor_id2);
        assert_eq!(manager.len(), 1);
    }

    #[test]
    fn test_fingerprint_correlation() {
        let manager = create_test_manager();
        let ip1 = create_test_ip(1);
        let ip2 = create_test_ip(2);
        let fingerprint = "t13d1516h2_shared";

        // First request
        let actor_id1 = manager.get_or_create_actor(ip1, Some(fingerprint));

        // Second request from different IP but same fingerprint
        let actor_id2 = manager.get_or_create_actor(ip2, Some(fingerprint));

        assert_eq!(actor_id1, actor_id2);
        assert_eq!(manager.len(), 1);

        // Verify both IPs are associated
        let actor = manager.get_actor(&actor_id1).unwrap();
        assert!(actor.ips.contains(&ip1));
        assert!(actor.ips.contains(&ip2));
    }

    #[test]
    fn test_fingerprint_preferred_over_ip() {
        let manager = create_test_manager();
        let ip1 = create_test_ip(1);
        let ip2 = create_test_ip(2);
        let fp1 = "fingerprint_1";
        let fp2 = "fingerprint_2";

        // Create actor with IP1 and FP1
        let actor_id1 = manager.get_or_create_actor(ip1, Some(fp1));

        // Create actor with IP2 and FP2
        let actor_id2 = manager.get_or_create_actor(ip2, Some(fp2));

        assert_ne!(actor_id1, actor_id2);

        // Now request with IP1 but FP2 - should correlate to FP2's actor
        let actor_id3 = manager.get_or_create_actor(ip1, Some(fp2));

        assert_eq!(actor_id3, actor_id2);
    }

    // ========================================================================
    // Rule Match Recording Tests
    // ========================================================================

    #[test]
    fn test_record_rule_match() {
        let manager = create_test_manager();
        let ip = create_test_ip(1);

        let actor_id = manager.get_or_create_actor(ip, None);
        manager.record_rule_match(&actor_id, "sqli-001", 25.0, "sqli");

        let actor = manager.get_actor(&actor_id).unwrap();
        assert_eq!(actor.rule_matches.len(), 1);
        assert_eq!(actor.rule_matches[0].rule_id, "sqli-001");
        assert_eq!(actor.rule_matches[0].risk_contribution, 25.0);
        assert_eq!(actor.rule_matches[0].category, "sqli");
        assert_eq!(actor.risk_score, 25.0);
    }

    #[test]
    fn test_rule_match_risk_accumulation() {
        let manager = create_test_manager();
        let ip = create_test_ip(1);

        let actor_id = manager.get_or_create_actor(ip, None);
        manager.record_rule_match(&actor_id, "sqli-001", 25.0, "sqli");
        manager.record_rule_match(&actor_id, "xss-001", 20.0, "xss");
        manager.record_rule_match(&actor_id, "sqli-002", 30.0, "sqli");

        let actor = manager.get_actor(&actor_id).unwrap();
        assert_eq!(actor.rule_matches.len(), 3);
        assert_eq!(actor.risk_score, 75.0);
    }

    #[test]
    fn test_rule_match_risk_capped() {
        let manager = create_test_manager();
        let ip = create_test_ip(1);

        let actor_id = manager.get_or_create_actor(ip, None);

        // Add more than max_risk
        for _ in 0..15 {
            manager.record_rule_match(&actor_id, "sqli-001", 10.0, "sqli");
        }

        let actor = manager.get_actor(&actor_id).unwrap();
        assert!(actor.risk_score <= 100.0);
    }

    #[test]
    fn test_rule_match_history_limit() {
        let config = ActorConfig {
            max_rule_matches: 5,
            ..Default::default()
        };
        let manager = ActorManager::new(config);
        let ip = create_test_ip(1);

        let actor_id = manager.get_or_create_actor(ip, None);

        // Add more than max_rule_matches
        for i in 0..10 {
            manager.record_rule_match(&actor_id, &format!("rule-{}", i), 5.0, "test");
        }

        let actor = manager.get_actor(&actor_id).unwrap();
        assert_eq!(actor.rule_matches.len(), 5);

        // Should keep most recent
        assert_eq!(actor.rule_matches[0].rule_id, "rule-5");
        assert_eq!(actor.rule_matches[4].rule_id, "rule-9");
    }

    // ========================================================================
    // Blocking/Unblocking Tests
    // ========================================================================

    #[test]
    fn test_block_actor() {
        let manager = create_test_manager();
        let ip = create_test_ip(1);

        let actor_id = manager.get_or_create_actor(ip, None);

        assert!(!manager.is_blocked(&actor_id));

        let result = manager.block_actor(&actor_id, "High risk score");

        assert!(result);
        assert!(manager.is_blocked(&actor_id));

        let actor = manager.get_actor(&actor_id).unwrap();
        assert!(actor.is_blocked);
        assert_eq!(actor.block_reason, Some("High risk score".to_string()));
        assert!(actor.blocked_since.is_some());
    }

    #[test]
    fn test_unblock_actor() {
        let manager = create_test_manager();
        let ip = create_test_ip(1);

        let actor_id = manager.get_or_create_actor(ip, None);
        manager.block_actor(&actor_id, "Test");

        assert!(manager.is_blocked(&actor_id));

        let result = manager.unblock_actor(&actor_id);

        assert!(result);
        assert!(!manager.is_blocked(&actor_id));

        let actor = manager.get_actor(&actor_id).unwrap();
        assert!(!actor.is_blocked);
        assert!(actor.block_reason.is_none());
        assert!(actor.blocked_since.is_none());
    }

    #[test]
    fn test_block_nonexistent() {
        let manager = create_test_manager();

        assert!(!manager.block_actor("nonexistent", "Test"));
        assert!(!manager.unblock_actor("nonexistent"));
        assert!(!manager.is_blocked("nonexistent"));
    }

    // ========================================================================
    // LRU Eviction Tests
    // ========================================================================

    #[test]
    fn test_lru_eviction() {
        let config = ActorConfig {
            max_actors: 100,
            ..Default::default()
        };
        let manager = ActorManager::new(config);

        // Add 150 actors (over capacity)
        // Lazy eviction triggers every 100 operations, evicting 1% (1 actor) each time
        for i in 0..150 {
            let ip = format!("10.0.{}.{}", i / 256, i % 256).parse().unwrap();
            manager.get_or_create_actor(ip, None);
        }

        // Lazy eviction doesn't aggressively enforce the limit
        // At most we create 150 - evictions triggered at operations 100 and 150 (with some actors evicted)
        assert!(manager.len() <= 150);

        // Force more evictions by touching the manager more times
        for i in 0..200 {
            let ip = format!("10.1.{}.{}", i / 256, i % 256).parse().unwrap();
            manager.get_or_create_actor(ip, None);
        }

        // After 350 total operations (multiple eviction cycles), should be closer to limit
        // but still may exceed due to lazy eviction nature
        let final_len = manager.len();
        let evictions = manager.stats().evictions.load(Ordering::Relaxed);

        // Verify evictions did occur
        assert!(evictions > 0, "Expected evictions to occur, got 0");

        // The key invariant: we should have created many actors but evicted some
        let created = manager.stats().total_created.load(Ordering::Relaxed);
        assert!(
            created > final_len as u64,
            "Expected some actors to be evicted"
        );

        println!(
            "LRU eviction test: created={}, evicted={}, final_len={}",
            created, evictions, final_len
        );
    }

    #[test]
    fn test_eviction_removes_mappings() {
        let config = ActorConfig {
            max_actors: 10,
            ..Default::default()
        };
        let manager = ActorManager::new(config);

        // Create first actor and get its ID
        let first_ip = create_test_ip(1);
        let first_fingerprint = "first_fp";
        let first_actor_id = manager.get_or_create_actor(first_ip, Some(first_fingerprint));

        // Sleep to ensure different timestamps
        std::thread::sleep(std::time::Duration::from_millis(10));

        // Add many more actors to trigger eviction of the first
        for i in 10..200 {
            let ip = format!("10.0.{}.{}", i / 256, i % 256).parse().unwrap();
            manager.get_or_create_actor(ip, Some(&format!("fp_{}", i)));
        }

        // If first actor was evicted, its mappings should be gone
        if manager.get_actor(&first_actor_id).is_none() {
            assert!(manager.ip_to_actor.get(&first_ip).is_none());
            assert!(manager
                .fingerprint_to_actor
                .get(first_fingerprint)
                .is_none());
        }
    }

    // ========================================================================
    // Score Decay Tests
    // ========================================================================

    #[test]
    fn test_decay_scores() {
        let config = ActorConfig {
            risk_decay_factor: 0.5,
            ..Default::default()
        };
        let manager = ActorManager::new(config);
        let ip = create_test_ip(1);

        let actor_id = manager.get_or_create_actor(ip, None);
        manager.record_rule_match(&actor_id, "test", 100.0, "test");

        // Verify initial score
        let actor = manager.get_actor(&actor_id).unwrap();
        assert_eq!(actor.risk_score, 100.0);

        // Apply decay
        manager.decay_scores();

        // Verify decayed score
        let actor = manager.get_actor(&actor_id).unwrap();
        assert_eq!(actor.risk_score, 50.0);

        // Apply decay again
        manager.decay_scores();

        let actor = manager.get_actor(&actor_id).unwrap();
        assert_eq!(actor.risk_score, 25.0);
    }

    #[test]
    fn test_decay_floors_to_zero() {
        let config = ActorConfig {
            risk_decay_factor: 0.001,
            ..Default::default()
        };
        let manager = ActorManager::new(config);
        let ip = create_test_ip(1);

        let actor_id = manager.get_or_create_actor(ip, None);
        manager.record_rule_match(&actor_id, "test", 1.0, "test");

        // Apply decay multiple times
        for _ in 0..5 {
            manager.decay_scores();
        }

        // Very small values should floor to zero
        let actor = manager.get_actor(&actor_id).unwrap();
        assert_eq!(actor.risk_score, 0.0);
    }

    // ========================================================================
    // Session Binding Tests
    // ========================================================================

    #[test]
    fn test_bind_session() {
        let manager = create_test_manager();
        let ip = create_test_ip(1);

        let actor_id = manager.get_or_create_actor(ip, None);
        manager.bind_session(&actor_id, "session-123");
        manager.bind_session(&actor_id, "session-456");
        manager.bind_session(&actor_id, "session-123"); // Duplicate

        let actor = manager.get_actor(&actor_id).unwrap();
        assert_eq!(actor.session_ids.len(), 2);
        assert!(actor.session_ids.contains(&"session-123".to_string()));
        assert!(actor.session_ids.contains(&"session-456".to_string()));
    }

    // ========================================================================
    // List Tests
    // ========================================================================

    #[test]
    fn test_list_actors() {
        let manager = create_test_manager();

        // Create some actors
        for i in 0..10 {
            let ip = create_test_ip(i);
            manager.get_or_create_actor(ip, None);
            std::thread::sleep(std::time::Duration::from_millis(1));
        }

        // List with pagination
        let first_page = manager.list_actors(5, 0);
        assert_eq!(first_page.len(), 5);

        let second_page = manager.list_actors(5, 5);
        assert_eq!(second_page.len(), 5);

        // Should be sorted by last_seen (most recent first)
        for window in first_page.windows(2) {
            assert!(window[0].last_seen >= window[1].last_seen);
        }
    }

    #[test]
    fn test_list_blocked_actors() {
        let manager = create_test_manager();

        // Create actors and block some
        for i in 0..10 {
            let ip = create_test_ip(i);
            let actor_id = manager.get_or_create_actor(ip, None);
            if i % 2 == 0 {
                manager.block_actor(&actor_id, "Test");
            }
        }

        let blocked = manager.list_blocked_actors();
        assert_eq!(blocked.len(), 5);

        for actor in blocked {
            assert!(actor.is_blocked);
        }
    }

    // ========================================================================
    // Concurrent Access Tests
    // ========================================================================

    #[test]
    fn test_concurrent_access() {
        let manager = Arc::new(create_test_manager());
        let mut handles = vec![];

        // Spawn 10 threads, each creating and updating actors
        for thread_id in 0..10 {
            let manager = Arc::clone(&manager);
            handles.push(thread::spawn(move || {
                for i in 0..100 {
                    let ip: IpAddr = format!("10.{}.0.{}", thread_id, i % 256).parse().unwrap();
                    let fingerprint = format!("fp_t{}_{}", thread_id, i % 5);
                    let actor_id = manager.get_or_create_actor(ip, Some(&fingerprint));
                    manager.record_rule_match(&actor_id, "test", 1.0, "test");
                }
            }));
        }

        for handle in handles {
            handle.join().unwrap();
        }

        // Verify no panics and reasonable state
        assert!(manager.len() > 0);
        assert!(manager.stats().total_created.load(Ordering::Relaxed) > 0);
    }

    #[test]
    fn test_stress_concurrent_updates() {
        let manager = Arc::new(ActorManager::new(ActorConfig {
            max_actors: 10_000,
            max_fingerprint_mappings: 50_000,
            ..Default::default()
        }));
        let mut handles = vec![];

        // Higher concurrency and mixed operations to exercise thread safety.
        for thread_id in 0..16 {
            let manager = Arc::clone(&manager);
            handles.push(thread::spawn(move || {
                for i in 0..500 {
                    let ip: IpAddr = format!("10.{}.{}.{}", thread_id, i / 256, i % 256)
                        .parse()
                        .unwrap();
                    let fingerprint = format!("fp_t{}_{}", thread_id, i % 20);
                    let actor_id = manager.get_or_create_actor(ip, Some(&fingerprint));

                    manager.record_rule_match(&actor_id, "stress", 0.5, "stress");

                    if i % 5 == 0 {
                        manager.touch_actor(&actor_id);
                    }
                    if i % 200 == 0 {
                        manager.block_actor(&actor_id, "stress");
                    }
                }
            }));
        }

        for handle in handles {
            handle.join().unwrap();
        }

        let stats = manager.stats();
        assert!(manager.len() > 0);
        assert!(stats.total_created.load(Ordering::Relaxed) > 0);
        assert!(stats.total_rule_matches.load(Ordering::Relaxed) > 0);
    }

    // ========================================================================
    // Statistics Tests
    // ========================================================================

    #[test]
    fn test_stats() {
        let manager = create_test_manager();

        // Initial stats
        let stats = manager.stats().snapshot();
        assert_eq!(stats.total_actors, 0);
        assert_eq!(stats.blocked_actors, 0);
        assert_eq!(stats.total_created, 0);

        // Create actors
        for i in 0..5 {
            let ip = create_test_ip(i);
            let actor_id = manager.get_or_create_actor(ip, None);
            manager.record_rule_match(&actor_id, "test", 10.0, "test");
        }

        // Block one
        let actor = manager.list_actors(1, 0)[0].clone();
        manager.block_actor(&actor.actor_id, "Test");

        let stats = manager.stats().snapshot();
        assert_eq!(stats.total_actors, 5);
        assert_eq!(stats.blocked_actors, 1);
        assert_eq!(stats.total_created, 5);
        assert_eq!(stats.total_rule_matches, 5);
    }

    // ========================================================================
    // Clear Tests
    // ========================================================================

    #[test]
    fn test_clear() {
        let manager = create_test_manager();

        // Add some actors
        for i in 0..10 {
            let ip = create_test_ip(i);
            let actor_id = manager.get_or_create_actor(ip, Some(&format!("fp_{}", i)));
            manager.block_actor(&actor_id, "Test");
        }

        assert_eq!(manager.len(), 10);

        manager.clear();

        assert_eq!(manager.len(), 0);
        assert!(manager.ip_to_actor.is_empty());
        assert!(manager.fingerprint_to_actor.is_empty());
        assert_eq!(manager.stats().total_actors.load(Ordering::Relaxed), 0);
        assert_eq!(manager.stats().blocked_actors.load(Ordering::Relaxed), 0);
    }

    // ========================================================================
    // Default Implementation Tests
    // ========================================================================

    #[test]
    fn test_default() {
        let manager = ActorManager::default();

        assert!(manager.is_enabled());
        assert!(manager.is_empty());
        assert_eq!(manager.config().max_actors, 100_000);
    }

    // ========================================================================
    // Actor ID Generation Tests
    // ========================================================================

    #[test]
    fn test_actor_id_uniqueness() {
        let mut ids = HashSet::new();
        for _ in 0..1000 {
            let id = generate_actor_id();
            assert!(!ids.contains(&id), "Duplicate ID generated: {}", id);
            ids.insert(id);
        }
    }

    #[test]
    fn test_actor_id_format() {
        let id = generate_actor_id();

        // Should be UUID-like format: xxxxxxxx-xxxx-4xxx-xxxx-xxxxxxxxxxxx
        assert_eq!(id.len(), 36);
        assert_eq!(id.chars().nth(8), Some('-'));
        assert_eq!(id.chars().nth(13), Some('-'));
        assert_eq!(id.chars().nth(14), Some('4')); // Version 4
        assert_eq!(id.chars().nth(18), Some('-'));
        assert_eq!(id.chars().nth(23), Some('-'));
    }

    // ========================================================================
    // Edge Case Tests
    // ========================================================================

    #[test]
    fn test_empty_fingerprint() {
        let manager = create_test_manager();
        let ip = create_test_ip(1);

        // Empty fingerprint should be ignored
        let actor_id = manager.get_or_create_actor(ip, Some(""));

        let actor = manager.get_actor(&actor_id).unwrap();
        assert!(actor.fingerprints.is_empty());
        assert!(manager.fingerprint_to_actor.is_empty());
    }

    #[test]
    fn test_ipv6_addresses() {
        let manager = create_test_manager();

        let ipv6_1: IpAddr = "2001:db8::1".parse().unwrap();
        let ipv6_2: IpAddr = "2001:db8::2".parse().unwrap();

        let actor_id1 = manager.get_or_create_actor(ipv6_1, Some("ipv6_fp"));
        let actor_id2 = manager.get_or_create_actor(ipv6_2, Some("ipv6_fp"));

        assert_eq!(actor_id1, actor_id2);

        let actor = manager.get_actor(&actor_id1).unwrap();
        assert!(actor.ips.contains(&ipv6_1));
        assert!(actor.ips.contains(&ipv6_2));
    }

    #[test]
    fn test_disabled_manager() {
        let config = ActorConfig {
            enabled: false,
            ..Default::default()
        };
        let manager = ActorManager::new(config);

        assert!(!manager.is_enabled());

        let ip = create_test_ip(1);
        let actor_id = manager.get_or_create_actor(ip, None);

        // Should still generate an ID but not track
        assert!(!actor_id.is_empty());
        assert!(manager.is_empty());

        // Record rule match should be no-op
        manager.record_rule_match(&actor_id, "test", 10.0, "test");
        assert!(manager.get_actor(&actor_id).is_none());
    }
}