lcpfs 2026.1.102

LCP File System - A ZFS-inspired copy-on-write filesystem for Rust
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
// Copyright 2025 LunaOS Contributors
// SPDX-License-Identifier: Apache-2.0
//
// AI Anomaly Detection
// Detect ransomware and unusual access patterns using statistical analysis.

use alloc::collections::BTreeMap;
use alloc::vec::Vec;
use lazy_static::lazy_static;
use libm;
use spin::Mutex;

// ═══════════════════════════════════════════════════════════════════════════
// ANOMALY DETECTION THRESHOLDS
// ═══════════════════════════════════════════════════════════════════════════

/// Threshold for rapid file creation (files per hour)
///
/// **Rationale**: Legitimate users rarely create >100 files/hour.
/// Ransomware typically creates thousands of encrypted copies rapidly.
const ANOMALY_RAPID_CREATE_THRESHOLD: usize = 100;

/// Threshold for mass deletion (files per hour)
///
/// **Rationale**: Mass deletion of 50+ files in an hour is highly unusual.
/// Ransomware often deletes originals after encryption.
const ANOMALY_MASS_DELETE_THRESHOLD: usize = 50;

/// Time window for anomaly detection (seconds)
///
/// **Rationale**: 1 hour (3600s) provides good balance between:
/// - Catching rapid attacks (immediate detection)
/// - Avoiding false positives (batched legitimate operations)
const ANOMALY_TIME_WINDOW_SECONDS: u64 = 3600;

/// Anomaly type
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AnomalyType {
    /// Rapid file creation (potential ransomware)
    RapidCreation,
    /// Mass file deletion
    MassDeletion,
    /// Unusual access time (e.g., 3 AM for office worker)
    UnusualTime,
    /// File extension change spike (ransomware indicator)
    ExtensionChange,
    /// Entropy spike (encrypted/compressed data)
    HighEntropy,
    /// Access from unusual location
    UnusualLocation,
    /// Rapid sequential writes to many files
    MassEncryption,
}

impl AnomalyType {
    /// Get severity score (0-100)
    pub fn severity(&self) -> u32 {
        match self {
            AnomalyType::MassEncryption => 95, // Very high - likely ransomware
            AnomalyType::RapidCreation => 80,
            AnomalyType::ExtensionChange => 85,
            AnomalyType::HighEntropy => 70,
            AnomalyType::MassDeletion => 90,
            AnomalyType::UnusualTime => 40,
            AnomalyType::UnusualLocation => 50,
        }
    }

    /// Get name
    pub fn name(&self) -> &'static str {
        match self {
            AnomalyType::RapidCreation => "rapid_creation",
            AnomalyType::MassDeletion => "mass_deletion",
            AnomalyType::UnusualTime => "unusual_time",
            AnomalyType::ExtensionChange => "extension_change",
            AnomalyType::HighEntropy => "high_entropy",
            AnomalyType::UnusualLocation => "unusual_location",
            AnomalyType::MassEncryption => "mass_encryption",
        }
    }
}

/// Action to take when anomaly is detected
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AnomalyAction {
    /// Allow operation to proceed (low severity, logging only)
    Allow,
    /// Warn but allow (medium severity)
    Warn,
    /// Block the operation (high severity)
    Block,
    /// Block and quarantine (critical severity - ransomware suspected)
    Quarantine,
}

impl AnomalyAction {
    /// Determine action based on severity score
    pub fn from_severity(severity: u32) -> Self {
        match severity {
            0..=40 => AnomalyAction::Allow,
            41..=70 => AnomalyAction::Warn,
            71..=89 => AnomalyAction::Block,
            90..=100 => AnomalyAction::Quarantine,
            _ => AnomalyAction::Block,
        }
    }

    /// Check if this action should block the operation
    pub fn should_block(&self) -> bool {
        matches!(self, AnomalyAction::Block | AnomalyAction::Quarantine)
    }
}

/// Detected anomaly
#[derive(Debug, Clone)]
pub struct Anomaly {
    /// Anomaly ID
    pub id: u64,
    /// Type of anomaly
    pub anomaly_type: AnomalyType,
    /// Timestamp when detected
    pub timestamp: u64,
    /// User ID
    pub user_id: u64,
    /// Dataset ID
    pub dataset_id: u64,
    /// Severity score (0-100)
    pub severity: u32,
    /// Additional details
    pub details: &'static str,
    /// Whether action was taken
    pub action_taken: bool,
    /// Recommended action
    pub action: AnomalyAction,
}

/// User behavior baseline (learned using Welford's algorithm)
#[derive(Debug, Clone)]
pub struct BehaviorBaseline {
    /// User ID
    pub user_id: u64,
    /// Average files created per hour
    pub avg_creates_per_hour: f64,
    /// Variance in creates per hour
    pub var_creates_per_hour: f64,
    /// Average files deleted per hour
    pub avg_deletes_per_hour: f64,
    /// Variance in deletes per hour
    pub var_deletes_per_hour: f64,
    /// Typical active hours (24-bit bitmap)
    pub active_hours: u32,
    /// Sample count (for Welford's algorithm)
    sample_count: u64,
}

impl BehaviorBaseline {
    /// Create new baseline
    pub fn new(user_id: u64) -> Self {
        Self {
            user_id,
            avg_creates_per_hour: 0.0,
            var_creates_per_hour: 0.0,
            avg_deletes_per_hour: 0.0,
            var_deletes_per_hour: 0.0,
            active_hours: 0,
            sample_count: 0,
        }
    }

    /// Update baseline with new observation (Welford's algorithm)
    pub fn update_creates(&mut self, creates: f64) {
        self.sample_count += 1;
        let n = self.sample_count as f64;
        let delta = creates - self.avg_creates_per_hour;
        self.avg_creates_per_hour += delta / n;
        let delta2 = creates - self.avg_creates_per_hour;
        self.var_creates_per_hour += delta * delta2;
    }

    /// Update deletes baseline
    pub fn update_deletes(&mut self, deletes: f64) {
        let n = (self.sample_count + 1) as f64;
        let delta = deletes - self.avg_deletes_per_hour;
        self.avg_deletes_per_hour += delta / n;
        let delta2 = deletes - self.avg_deletes_per_hour;
        self.var_deletes_per_hour += delta * delta2;
    }

    /// Mark hour as active
    pub fn mark_active_hour(&mut self, hour: u32) {
        if hour < 24 {
            self.active_hours |= 1 << hour;
        }
    }

    /// Check if hour is typical
    pub fn is_typical_hour(&self, hour: u32) -> bool {
        if hour >= 24 {
            return false;
        }
        (self.active_hours & (1 << hour)) != 0
    }

    /// Get standard deviation for creates
    pub fn creates_stddev(&self) -> f64 {
        if self.sample_count < 2 {
            return 0.0;
        }
        libm::sqrt(self.var_creates_per_hour / (self.sample_count - 1) as f64)
    }

    /// Check if creates count is anomalous (>3 sigma)
    pub fn is_creates_anomalous(&self, count: f64) -> bool {
        if self.sample_count < 10 {
            return false; // Need more samples
        }
        let sigma = self.creates_stddev();
        let z_score = (count - self.avg_creates_per_hour).abs() / sigma.max(1.0);
        z_score > 3.0 // 3-sigma rule
    }

    /// Check if deletes count is anomalous
    pub fn is_deletes_anomalous(&self, count: f64) -> bool {
        if self.sample_count < 10 {
            return false;
        }
        let sigma = libm::sqrt(self.var_deletes_per_hour / (self.sample_count - 1) as f64);
        let z_score = (count - self.avg_deletes_per_hour).abs() / sigma.max(1.0);
        z_score > 3.0
    }
}

/// Anomaly statistics
#[derive(Debug, Clone, Default)]
pub struct AnomalyStats {
    /// Total anomalies detected
    pub total_anomalies: u64,
    /// By type
    pub by_type: BTreeMap<&'static str, u64>,
    /// Actions taken
    pub actions_taken: u64,
    /// False positives (anomalies that were later cleared)
    pub false_positives: u64,
}

lazy_static! {
    /// Global anomaly detector
    static ref ANOMALY_DETECTOR: Mutex<AnomalyDetector> = Mutex::new(AnomalyDetector::new());
}

/// AI-based anomaly detector
pub struct AnomalyDetector {
    /// Learned baselines per user
    baselines: BTreeMap<u64, BehaviorBaseline>,
    /// Recent activity tracking (last hour)
    recent_creates: BTreeMap<u64, Vec<u64>>, // user_id -> [timestamps]
    recent_deletes: BTreeMap<u64, Vec<u64>>,
    /// Detected anomalies
    anomalies: Vec<Anomaly>,
    /// Next anomaly ID
    next_anomaly_id: u64,
    /// Statistics
    stats: AnomalyStats,
}

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

impl AnomalyDetector {
    /// Create new anomaly detector
    pub fn new() -> Self {
        Self {
            baselines: BTreeMap::new(),
            recent_creates: BTreeMap::new(),
            recent_deletes: BTreeMap::new(),
            anomalies: Vec::new(),
            next_anomaly_id: 1,
            stats: AnomalyStats::default(),
        }
    }

    /// Record file creation
    pub fn record_create(
        &mut self,
        user_id: u64,
        dataset_id: u64,
        timestamp: u64,
    ) -> Option<Anomaly> {
        // Track recent activity
        let creates = self.recent_creates.entry(user_id).or_default();
        creates.push(timestamp);

        // Remove old entries outside time window
        creates.retain(|&t| timestamp.saturating_sub(t) < ANOMALY_TIME_WINDOW_SECONDS);

        // Check for rapid creation anomaly
        if creates.len() > ANOMALY_RAPID_CREATE_THRESHOLD {
            // Exceeded threshold - potential ransomware activity
            return self.detect_anomaly(
                AnomalyType::RapidCreation,
                user_id,
                dataset_id,
                timestamp,
                "Rapid file creation detected",
            );
        }

        // Check against baseline
        let baseline = self
            .baselines
            .entry(user_id)
            .or_insert_with(|| BehaviorBaseline::new(user_id));
        if baseline.is_creates_anomalous(creates.len() as f64) {
            return self.detect_anomaly(
                AnomalyType::RapidCreation,
                user_id,
                dataset_id,
                timestamp,
                "Unusual creation rate",
            );
        }

        // Update baseline
        baseline.update_creates(creates.len() as f64);

        None
    }

    /// Record file deletion
    pub fn record_delete(
        &mut self,
        user_id: u64,
        dataset_id: u64,
        timestamp: u64,
    ) -> Option<Anomaly> {
        let deletes = self.recent_deletes.entry(user_id).or_default();
        deletes.push(timestamp);
        deletes.retain(|&t| timestamp.saturating_sub(t) < ANOMALY_TIME_WINDOW_SECONDS);

        // Check for mass deletion
        if deletes.len() > ANOMALY_MASS_DELETE_THRESHOLD {
            return self.detect_anomaly(
                AnomalyType::MassDeletion,
                user_id,
                dataset_id,
                timestamp,
                "Mass deletion detected",
            );
        }

        None
    }

    /// Check for unusual access time
    pub fn check_access_time(
        &mut self,
        user_id: u64,
        dataset_id: u64,
        timestamp: u64,
    ) -> Option<Anomaly> {
        let hour = ((timestamp / 3600) % 24) as u32;

        let baseline = self
            .baselines
            .entry(user_id)
            .or_insert_with(|| BehaviorBaseline::new(user_id));

        if !baseline.is_typical_hour(hour) && baseline.sample_count > 50 {
            return self.detect_anomaly(
                AnomalyType::UnusualTime,
                user_id,
                dataset_id,
                timestamp,
                "Access during unusual hours",
            );
        }

        baseline.mark_active_hour(hour);
        None
    }

    /// Check file entropy (high entropy = encrypted/compressed)
    pub fn check_entropy(
        &mut self,
        user_id: u64,
        dataset_id: u64,
        timestamp: u64,
        entropy: f64,
    ) -> Option<Anomaly> {
        // Entropy > 7.5 is very high (encrypted or compressed)
        if entropy > 7.5 {
            return self.detect_anomaly(
                AnomalyType::HighEntropy,
                user_id,
                dataset_id,
                timestamp,
                "High entropy file (potential encryption)",
            );
        }

        None
    }

    /// Detect ransomware pattern (mass encryption)
    pub fn detect_ransomware(
        &mut self,
        user_id: u64,
        dataset_id: u64,
        timestamp: u64,
    ) -> Option<Anomaly> {
        // Check for multiple indicators
        let creates = self
            .recent_creates
            .get(&user_id)
            .map(|v| v.len())
            .unwrap_or(0);
        let deletes = self
            .recent_deletes
            .get(&user_id)
            .map(|v| v.len())
            .unwrap_or(0);

        // Ransomware pattern: rapid creates + deletes (encrypting and deleting originals)
        if creates > 50 && deletes > 50 {
            return self.detect_anomaly(
                AnomalyType::MassEncryption,
                user_id,
                dataset_id,
                timestamp,
                "Ransomware pattern detected",
            );
        }

        None
    }

    /// Internal: Record anomaly detection
    fn detect_anomaly(
        &mut self,
        anomaly_type: AnomalyType,
        user_id: u64,
        dataset_id: u64,
        timestamp: u64,
        details: &'static str,
    ) -> Option<Anomaly> {
        let severity = anomaly_type.severity();
        let action = AnomalyAction::from_severity(severity);

        let anomaly = Anomaly {
            id: self.next_anomaly_id,
            anomaly_type,
            timestamp,
            user_id,
            dataset_id,
            severity,
            details,
            action_taken: action.should_block(),
            action,
        };

        self.next_anomaly_id += 1;
        self.anomalies.push(anomaly.clone());

        // Update stats
        self.stats.total_anomalies += 1;
        *self.stats.by_type.entry(anomaly_type.name()).or_insert(0) += 1;

        if action.should_block() {
            self.stats.actions_taken += 1;
        }

        Some(anomaly)
    }

    /// Get recent anomalies
    pub fn get_recent_anomalies(&self, limit: usize) -> Vec<Anomaly> {
        self.anomalies.iter().rev().take(limit).cloned().collect()
    }

    /// Get anomalies for user
    pub fn get_user_anomalies(&self, user_id: u64) -> Vec<Anomaly> {
        self.anomalies
            .iter()
            .filter(|a| a.user_id == user_id)
            .cloned()
            .collect()
    }

    /// Get statistics
    pub fn get_stats(&self) -> AnomalyStats {
        self.stats.clone()
    }
}

/// Global anomaly detection operations
pub struct AnomalyEngine;

impl AnomalyEngine {
    /// Check if file creation should be blocked. Returns Ok(()) if allowed, Err with details if blocked.
    pub fn check_create(user_id: u64, dataset_id: u64, timestamp: u64) -> Result<(), &'static str> {
        let mut detector = ANOMALY_DETECTOR.lock();
        if let Some(anomaly) = detector.record_create(user_id, dataset_id, timestamp) {
            if anomaly.action.should_block() {
                return Err(anomaly.details);
            }
        }
        Ok(())
    }

    /// Check if file deletion should be blocked. Returns Ok(()) if allowed, Err with details if blocked.
    pub fn check_delete(user_id: u64, dataset_id: u64, timestamp: u64) -> Result<(), &'static str> {
        let mut detector = ANOMALY_DETECTOR.lock();
        if let Some(anomaly) = detector.record_delete(user_id, dataset_id, timestamp) {
            if anomaly.action.should_block() {
                return Err(anomaly.details);
            }
        }
        Ok(())
    }

    /// Check if write operation should be blocked based on entropy.
    /// Returns Ok(()) if allowed, Err with details if blocked.
    pub fn check_write(
        user_id: u64,
        dataset_id: u64,
        timestamp: u64,
        data: &[u8],
    ) -> Result<(), &'static str> {
        // Calculate entropy of data being written
        let entropy = Self::calculate_entropy(data);

        let mut detector = ANOMALY_DETECTOR.lock();

        // Check entropy anomaly
        if let Some(anomaly) = detector.check_entropy(user_id, dataset_id, timestamp, entropy) {
            if anomaly.action.should_block() {
                return Err(anomaly.details);
            }
        }

        // Check for ransomware pattern
        if let Some(anomaly) = detector.detect_ransomware(user_id, dataset_id, timestamp) {
            if anomaly.action.should_block() {
                return Err(anomaly.details);
            }
        }

        Ok(())
    }

    /// Calculate Shannon entropy of data (bits per byte, 0-8 scale)
    fn calculate_entropy(data: &[u8]) -> f64 {
        if data.is_empty() {
            return 0.0;
        }

        // Count byte frequencies
        let mut counts = [0u64; 256];
        for &byte in data {
            counts[byte as usize] += 1;
        }

        // Calculate entropy
        let len = data.len() as f64;
        let mut entropy = 0.0;

        for &count in &counts {
            if count > 0 {
                let p = count as f64 / len;
                entropy -= p * libm::log2(p);
            }
        }

        entropy
    }

    /// Record file creation (legacy API - returns anomaly if detected)
    pub fn record_create(user_id: u64, dataset_id: u64, timestamp: u64) -> Option<Anomaly> {
        let mut detector = ANOMALY_DETECTOR.lock();
        detector.record_create(user_id, dataset_id, timestamp)
    }

    /// Record file deletion (legacy API - returns anomaly if detected)
    pub fn record_delete(user_id: u64, dataset_id: u64, timestamp: u64) -> Option<Anomaly> {
        let mut detector = ANOMALY_DETECTOR.lock();
        detector.record_delete(user_id, dataset_id, timestamp)
    }

    /// Check access time
    pub fn check_access_time(user_id: u64, dataset_id: u64, timestamp: u64) -> Option<Anomaly> {
        let mut detector = ANOMALY_DETECTOR.lock();
        detector.check_access_time(user_id, dataset_id, timestamp)
    }

    /// Check entropy
    pub fn check_entropy(
        user_id: u64,
        dataset_id: u64,
        timestamp: u64,
        entropy: f64,
    ) -> Option<Anomaly> {
        let mut detector = ANOMALY_DETECTOR.lock();
        detector.check_entropy(user_id, dataset_id, timestamp, entropy)
    }

    /// Detect ransomware
    pub fn detect_ransomware(user_id: u64, dataset_id: u64, timestamp: u64) -> Option<Anomaly> {
        let mut detector = ANOMALY_DETECTOR.lock();
        detector.detect_ransomware(user_id, dataset_id, timestamp)
    }

    /// Get recent anomalies
    pub fn recent_anomalies(limit: usize) -> Vec<Anomaly> {
        let detector = ANOMALY_DETECTOR.lock();
        detector.get_recent_anomalies(limit)
    }

    /// Get statistics
    pub fn stats() -> AnomalyStats {
        let detector = ANOMALY_DETECTOR.lock();
        detector.get_stats()
    }
}

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

    #[test]
    fn test_anomaly_severity() {
        assert!(AnomalyType::MassEncryption.severity() > AnomalyType::UnusualTime.severity());
        assert!(AnomalyType::MassDeletion.severity() > AnomalyType::HighEntropy.severity());
    }

    #[test]
    fn test_baseline_creation() {
        let baseline = BehaviorBaseline::new(1);
        assert_eq!(baseline.user_id, 1);
        assert_eq!(baseline.sample_count, 0);
    }

    #[test]
    fn test_welford_update() {
        let mut baseline = BehaviorBaseline::new(1);

        // Add samples: 10, 12, 11, 13, 9
        for &val in &[10.0, 12.0, 11.0, 13.0, 9.0] {
            baseline.update_creates(val);
        }

        // Mean should be 11.0
        assert!((baseline.avg_creates_per_hour - 11.0).abs() < 0.1);

        // Stddev should be ~1.58
        let stddev = baseline.creates_stddev();
        assert!(stddev > 1.0 && stddev < 2.0);
    }

    #[test]
    fn test_three_sigma_detection() {
        let mut baseline = BehaviorBaseline::new(1);

        // Build baseline around 10
        for _ in 0..20 {
            baseline.update_creates(10.0);
        }

        // Normal value should not be anomalous
        assert!(!baseline.is_creates_anomalous(10.0));
        assert!(!baseline.is_creates_anomalous(12.0));

        // Extreme value should be anomalous
        assert!(baseline.is_creates_anomalous(50.0));
    }

    #[test]
    fn test_active_hours() {
        let mut baseline = BehaviorBaseline::new(1);

        baseline.mark_active_hour(9); // 9 AM
        baseline.mark_active_hour(10);
        baseline.mark_active_hour(14);

        assert!(baseline.is_typical_hour(9));
        assert!(baseline.is_typical_hour(10));
        assert!(!baseline.is_typical_hour(3)); // 3 AM not typical
    }

    #[test]
    fn test_rapid_creation_detection() {
        let mut detector = AnomalyDetector::new();

        // Simulate rapid file creation
        for i in 0..110 {
            let result = detector.record_create(1, 100, 1000 + i);
            if i >= 100 {
                assert!(result.is_some()); // Should detect anomaly
            }
        }
    }

    #[test]
    fn test_mass_deletion_detection() {
        let mut detector = AnomalyDetector::new();

        // Simulate mass deletion
        for i in 0..60 {
            let result = detector.record_delete(1, 100, 1000 + i);
            if i >= 50 {
                assert!(result.is_some());
            }
        }
    }

    #[test]
    fn test_high_entropy_detection() {
        let mut detector = AnomalyDetector::new();

        // Low entropy (normal text file)
        assert!(detector.check_entropy(1, 100, 1000, 4.5).is_none());

        // High entropy (encrypted)
        assert!(detector.check_entropy(1, 100, 1001, 7.8).is_some());
    }

    #[test]
    fn test_ransomware_detection() {
        let mut detector = AnomalyDetector::new();

        // Simulate ransomware: create + delete many files
        for i in 0..60 {
            detector.record_create(1, 100, 1000 + i);
            detector.record_delete(1, 100, 1000 + i);
        }

        let result = detector.detect_ransomware(1, 100, 1060);
        assert!(result.is_some());
        let anomaly = result.expect("test: operation should succeed");
        assert_eq!(anomaly.anomaly_type, AnomalyType::MassEncryption);
        assert!(anomaly.severity > 90);
    }

    #[test]
    fn test_statistics() {
        let mut detector = AnomalyDetector::new();

        // Generate some anomalies
        for i in 0..110 {
            detector.record_create(1, 100, 1000 + i);
        }

        let stats = detector.get_stats();
        assert!(stats.total_anomalies > 0);
        assert!(stats.by_type.contains_key("rapid_creation"));
    }
}