Skip to main content

qualia_core_db/solvers/ontology_align/
alignment_guard.rs

1//! Poisoned-alignment flood detection and contest-abuse guard (§GAP-07 / G30 / G31).
2//!
3//! Protects the contributor graph and human-ratification queue from:
4//! 1. Bogus `closeMatch` proposal floods / Sybil poisoning attempts (`G30`).
5//! 2. Denial-of-service through bad-faith or spam contest records (`G31`).
6//! Zero-heap hot path.
7
8use super::correspondence::Alignment;
9
10/// Errors arising from alignment security evaluation.
11#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12pub enum AlignmentSecurityError {
13    /// Proposal count exceeds the rate-limiting sliding window budget.
14    ProposalFloodExceeded,
15    /// Average match degree is suspiciously degraded (bulk noise/entropy injection).
16    LowEntropyPoisoning,
17    /// Contest quota exceeded for the submitting actor.
18    ContestRateLimitExceeded,
19}
20
21/// Evaluates an alignment proposal against poisoning flood metrics (`G30`).
22pub fn detect_poisoned_alignment_flood(
23    alignment: &Alignment,
24    recent_proposals_count: usize,
25    window_budget: usize,
26    min_mean_quality: f64,
27) -> Result<(), AlignmentSecurityError> {
28    if alignment.correspondences.is_empty() {
29        return Ok(());
30    }
31
32    if recent_proposals_count + alignment.correspondences.len() > window_budget {
33        return Err(AlignmentSecurityError::ProposalFloodExceeded);
34    }
35
36    let mean_degree = alignment.quality / alignment.correspondences.len() as f64;
37    if mean_degree < min_mean_quality {
38        return Err(AlignmentSecurityError::LowEntropyPoisoning);
39    }
40
41    Ok(())
42}
43
44/// A contest claim asserting factual, licence, or custodial dispute over a graph triple.
45#[derive(Debug, Clone, Copy, PartialEq, Eq)]
46pub struct ContestRecord {
47    pub contestant_did: u64,
48    pub target_assertion: u64,
49    pub timestamp_epoch: u32,
50    pub grounds_hash: u64,
51}
52
53/// Evaluates contest rate limits to prevent DoS via contest record storms (`G31`).
54/// Zero-heap inspection over caller-supplied slice of recent contests.
55pub fn check_contest_budget(
56    contestant_did: u64,
57    recent_contests: &[ContestRecord],
58    now: u32,
59    window_seconds: u32,
60    max_contests_per_window: usize,
61) -> Result<(), AlignmentSecurityError> {
62    let window_start = now.saturating_sub(window_seconds);
63    let mut actor_contests = 0usize;
64
65    for c in recent_contests {
66        if c.contestant_did == contestant_did && c.timestamp_epoch >= window_start {
67            actor_contests += 1;
68            if actor_contests >= max_contests_per_window {
69                return Err(AlignmentSecurityError::ContestRateLimitExceeded);
70            }
71        }
72    }
73
74    Ok(())
75}
76
77#[cfg(test)]
78mod tests {
79    use super::*;
80    use crate::solvers::ontology_align::correspondence::Correspondence;
81
82    #[test]
83    fn test_detect_poisoned_flood() {
84        let align = Alignment {
85            correspondences: vec![
86                Correspondence::propose(0, 0, 0.9),
87                Correspondence::propose(1, 1, 0.85),
88            ],
89            quality: 1.75,
90        };
91
92        // Within budget
93        assert!(detect_poisoned_alignment_flood(&align, 5, 10, 0.6).is_ok());
94
95        // Exceeds budget (flood)
96        assert_eq!(
97            detect_poisoned_alignment_flood(&align, 9, 10, 0.6),
98            Err(AlignmentSecurityError::ProposalFloodExceeded)
99        );
100
101        // Low entropy spam
102        let spam_align = Alignment {
103            correspondences: vec![
104                Correspondence::propose(0, 0, 0.1),
105                Correspondence::propose(1, 1, 0.2),
106            ],
107            quality: 0.3,
108        };
109        assert_eq!(
110            detect_poisoned_alignment_flood(&spam_align, 0, 10, 0.5),
111            Err(AlignmentSecurityError::LowEntropyPoisoning)
112        );
113    }
114
115    #[test]
116    fn test_contest_budget_rate_limiting() {
117        let actor = 0xAAAA;
118        let contests = [
119            ContestRecord {
120                contestant_did: actor,
121                target_assertion: 1,
122                timestamp_epoch: 100,
123                grounds_hash: 1,
124            },
125            ContestRecord {
126                contestant_did: actor,
127                target_assertion: 2,
128                timestamp_epoch: 120,
129                grounds_hash: 1,
130            },
131            ContestRecord {
132                contestant_did: 0xBBBB, // other actor
133                target_assertion: 3,
134                timestamp_epoch: 130,
135                grounds_hash: 1,
136            },
137        ];
138
139        // Actor has 2 contests in window [0, 200]; budget is 3 -> OK
140        assert!(check_contest_budget(actor, &contests, 150, 100, 3).is_ok());
141
142        // Budget is 2 -> Exceeded
143        assert_eq!(
144            check_contest_budget(actor, &contests, 150, 100, 2),
145            Err(AlignmentSecurityError::ContestRateLimitExceeded)
146        );
147
148        // Outside window (e.g. at t=300 with 100s window) -> 0 contests in window -> OK
149        assert!(check_contest_budget(actor, &contests, 300, 100, 2).is_ok());
150    }
151}