Skip to main content

fetchium_core/proactive/
anomaly.rs

1//! Anomaly detection on monitored content (PRD §33).
2//!
3//! Flags significant content changes by comparing the ContentDiff produced
4//! by the monitor module against configurable thresholds.
5
6use crate::error::FetchiumResult;
7use crate::monitor::diff::ContentDiff;
8use serde::{Deserialize, Serialize};
9
10/// Configuration for anomaly detection.
11#[derive(Debug, Clone, Serialize, Deserialize)]
12pub struct AnomalyConfig {
13    /// Similarity ratio below which we flag an anomaly (0.0–1.0).
14    /// Default: 0.7 (30% change triggers anomaly).
15    pub similarity_threshold: f32,
16    /// Minimum line additions+deletions to be considered anomalous.
17    pub min_changed_lines: usize,
18}
19
20impl Default for AnomalyConfig {
21    fn default() -> Self {
22        Self {
23            similarity_threshold: 0.70,
24            min_changed_lines: 10,
25        }
26    }
27}
28
29/// Result of an anomaly check.
30#[derive(Debug, Clone, Serialize, Deserialize)]
31pub struct AnomalyReport {
32    pub url: String,
33    pub is_anomalous: bool,
34    pub similarity: f32,
35    pub changed_lines: usize,
36    pub summary: String,
37}
38
39/// Check whether a `ContentDiff` represents an anomalous change.
40pub fn check_anomaly(
41    url: &str,
42    diff: &ContentDiff,
43    cfg: &AnomalyConfig,
44) -> FetchiumResult<AnomalyReport> {
45    let changed_lines = diff.additions + diff.deletions;
46    let is_anomalous =
47        diff.similarity < cfg.similarity_threshold || changed_lines >= cfg.min_changed_lines;
48
49    let summary = if is_anomalous {
50        format!(
51            "ANOMALY detected: similarity={:.2}, {} lines changed",
52            diff.similarity, changed_lines
53        )
54    } else {
55        format!(
56            "Normal change: similarity={:.2}, {} lines changed",
57            diff.similarity, changed_lines
58        )
59    };
60
61    Ok(AnomalyReport {
62        url: url.to_string(),
63        is_anomalous,
64        similarity: diff.similarity,
65        changed_lines,
66        summary,
67    })
68}
69
70#[cfg(test)]
71mod tests {
72    use super::*;
73
74    fn make_diff(additions: usize, deletions: usize, similarity: f32) -> ContentDiff {
75        ContentDiff {
76            additions,
77            deletions,
78            similarity,
79            changes: Vec::new(),
80        }
81    }
82
83    #[test]
84    fn test_anomaly_low_similarity() {
85        let diff = make_diff(100, 80, 0.20);
86        let report =
87            check_anomaly("https://example.com", &diff, &AnomalyConfig::default()).unwrap();
88        assert!(report.is_anomalous);
89    }
90
91    #[test]
92    fn test_no_anomaly_high_similarity() {
93        let diff = make_diff(1, 0, 0.99);
94        let report =
95            check_anomaly("https://example.com", &diff, &AnomalyConfig::default()).unwrap();
96        assert!(!report.is_anomalous);
97    }
98}