Skip to main content

wafrift_evolution/search/
novelty.rs

1use crate::evolution::crossover::mutation::mutate_with_log;
2use crate::evolution::{Chromosome, GenePool, population::random_chromosome};
3use crate::lineage::Lineage;
4use crate::search::{EvalCandidate, SearchAlgorithm};
5use crate::types::{Budget, EvolutionError, OracleVerdict, SearchStats};
6use rand::Rng;
7use rand::rngs::StdRng;
8use serde::{Deserialize, Serialize};
9use std::collections::HashMap;
10
11/// Novelty search with k-NN behavioral distance archive.
12#[derive(Debug, Clone, Serialize, Deserialize)]
13pub struct NoveltySearch {
14    population: Vec<Chromosome>,
15    archive: Vec<Chromosome>,
16    gene_pool: GenePool,
17    generation: u32,
18    eval_counter: u64,
19    k: usize,
20    threshold: f64,
21    #[serde(skip)]
22    in_flight: HashMap<u64, Chromosome>,
23}
24
25impl NoveltySearch {
26    #[must_use]
27    pub fn new(k: usize, threshold: f64) -> Self {
28        Self {
29            population: Vec::new(),
30            archive: Vec::new(),
31            gene_pool: GenePool::default_wafrift(),
32            generation: 0,
33            eval_counter: 0,
34            k,
35            threshold,
36            in_flight: HashMap::new(),
37        }
38    }
39
40    fn phenotypic_distance(a: &Chromosome, b: &Chromosome) -> f64 {
41        let genes_a: Vec<_> = a.genes.iter().map(|(n, v)| format!("{n}={v}")).collect();
42        let genes_b: Vec<_> = b.genes.iter().map(|(n, v)| format!("{n}={v}")).collect();
43        levenshtein_distance(&genes_a.join("|"), &genes_b.join("|")) as f64
44            / (genes_a.len().max(genes_b.len()).max(1) as f64)
45    }
46
47    fn novelty_score(&self, chromosome: &Chromosome) -> f64 {
48        let mut neighbors: Vec<f64> = self
49            .archive
50            .iter()
51            .chain(self.population.iter())
52            .map(|other| Self::phenotypic_distance(chromosome, other))
53            .collect();
54        neighbors.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
55        neighbors.truncate(self.k);
56        if neighbors.is_empty() {
57            return f64::INFINITY;
58        }
59        neighbors.iter().sum::<f64>() / neighbors.len() as f64
60    }
61
62    fn generate_individual(&self, rng: &mut StdRng) -> Chromosome {
63        if self.population.is_empty() {
64            return random_chromosome(&self.gene_pool, rng);
65        }
66        let parent = &self.population[rng.gen_range(0..self.population.len())];
67        let mut child = parent.clone();
68        let log = mutate_with_log(&mut child, &self.gene_pool, 0.3, rng);
69        child.lineage = Lineage::mutation(parent, log, self.generation);
70        child
71    }
72}
73
74impl Default for NoveltySearch {
75    fn default() -> Self {
76        Self::new(15, 0.3)
77    }
78}
79
80impl SearchAlgorithm for NoveltySearch {
81    fn name(&self) -> &'static str {
82        "novelty_search"
83    }
84
85    fn initialize(&mut self, population: Vec<Chromosome>, gene_pool: &GenePool, _rng: &mut StdRng) {
86        self.gene_pool = gene_pool.clone();
87        self.population = population;
88        self.archive.clear();
89        self.in_flight.clear();
90    }
91
92    fn request_evaluations(&mut self, n: usize, rng: &mut StdRng) -> Vec<EvalCandidate> {
93        let mut out = Vec::with_capacity(n);
94        for _ in 0..n {
95            self.eval_counter += 1;
96            let candidate = self.generate_individual(rng);
97            self.in_flight.insert(self.eval_counter, candidate.clone());
98            out.push(EvalCandidate {
99                id: self.eval_counter,
100                chromosome: candidate,
101            });
102        }
103        out
104    }
105
106    fn submit_evaluations(&mut self, results: Vec<(u64, OracleVerdict)>) {
107        let mut evaluated: Vec<Chromosome> = Vec::with_capacity(results.len());
108        for (id, verdict) in results {
109            if let Some(mut candidate) = self.in_flight.remove(&id) {
110                candidate.record_verdict(&verdict);
111                evaluated.push(candidate);
112            }
113        }
114
115        // Add to archive based on novelty. Cap the archive at 10_000
116        // to prevent unbounded growth on long-running scans (every
117        // novel candidate would otherwise stay alive forever, leaking
118        // memory until OOM). When full, evict the least-novel entry
119        // by score so the highest-novelty history is retained.
120        const ARCHIVE_CAP: usize = 10_000;
121        for candidate in evaluated {
122            let score = self.novelty_score(&candidate);
123            if score > self.threshold {
124                if self.archive.len() >= ARCHIVE_CAP
125                    && let Some((min_idx, _)) = self
126                        .archive
127                        .iter()
128                        .enumerate()
129                        .map(|(i, c)| (i, self.novelty_score(c)))
130                        .min_by(|(_, a), (_, b)| {
131                            a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal)
132                        })
133                {
134                    self.archive.swap_remove(min_idx);
135                }
136                self.archive.push(candidate.clone());
137            }
138            self.population.push(candidate);
139        }
140
141        // Cull population to reasonable size, keeping most novel
142        if self.population.len() > 100 {
143            let temp: Vec<Chromosome> = self.population.drain(..).collect();
144            let mut scored: Vec<(f64, Chromosome)> = temp
145                .into_iter()
146                .map(|c| (self.novelty_score(&c), c))
147                .collect();
148            scored.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(std::cmp::Ordering::Equal));
149            scored.truncate(100);
150            self.population = scored.into_iter().map(|(_, c)| c).collect();
151        }
152
153        self.generation += 1;
154    }
155
156    fn should_terminate(&self, stats: &SearchStats, budget: &Budget) -> bool {
157        stats.evaluations >= budget.max_requests
158            || stats.generation >= budget.max_generations
159            || stats.stagnation_counter >= budget.stagnation_limit
160    }
161
162    fn best(&self) -> Option<&Chromosome> {
163        self.population
164            .iter()
165            .chain(self.archive.iter())
166            .max_by(|a, b| {
167                a.fitness
168                    .partial_cmp(&b.fitness)
169                    .unwrap_or(std::cmp::Ordering::Equal)
170            })
171    }
172
173    fn checkpoint(&self) -> Result<Vec<u8>, EvolutionError> {
174        serde_json::to_vec(self).map_err(EvolutionError::SerializationFailed)
175    }
176
177    fn restore(&mut self, bytes: &[u8]) -> Result<(), EvolutionError> {
178        if bytes.len() > crate::types::MAX_CHECKPOINT_BYTES {
179            return Err(EvolutionError::OversizedData {
180                context: "novelty checkpoint restore".into(),
181                size: bytes.len(),
182                max: crate::types::MAX_CHECKPOINT_BYTES,
183            });
184        }
185        *self = serde_json::from_slice(bytes).map_err(EvolutionError::DeserializationFailed)?;
186        self.in_flight.clear();
187        Ok(())
188    }
189
190    /// Population + archive — both are live state the algorithm draws
191    /// candidates from. Diversity over the union is the meaningful
192    /// signal for adaptive mutation pressure.
193    fn population_snapshot(&self) -> Vec<Chromosome> {
194        let mut out = Vec::with_capacity(self.population.len() + self.archive.len());
195        out.extend(self.population.iter().cloned());
196        out.extend(self.archive.iter().cloned());
197        out
198    }
199
200    fn clone_box(&self) -> Box<dyn SearchAlgorithm> {
201        Box::new(self.clone())
202    }
203}
204
205fn levenshtein_distance(a: &str, b: &str) -> usize {
206    let a_chars: Vec<char> = a.chars().collect();
207    let b_chars: Vec<char> = b.chars().collect();
208    let mut prev = vec![0; b_chars.len() + 1];
209    let mut curr = vec![0; b_chars.len() + 1];
210    for (j, slot) in prev.iter_mut().enumerate().take(b_chars.len() + 1) {
211        *slot = j;
212    }
213    for i in 1..=a_chars.len() {
214        curr[0] = i;
215        for j in 1..=b_chars.len() {
216            let cost = if a_chars[i - 1] == b_chars[j - 1] {
217                0
218            } else {
219                1
220            };
221            curr[j] = (curr[j - 1] + 1).min(prev[j] + 1).min(prev[j - 1] + cost);
222        }
223        std::mem::swap(&mut prev, &mut curr);
224    }
225    prev[b_chars.len()]
226}
227
228#[cfg(test)]
229mod tests {
230    use super::*;
231    use rand::SeedableRng;
232
233    fn dummy_chromosome(encoding: &str, grammar: &str, content_type: &str) -> Chromosome {
234        Chromosome::new(vec![
235            ("encoding".into(), encoding.into()),
236            ("grammar_rule".into(), grammar.into()),
237            ("content_type".into(), content_type.into()),
238        ])
239    }
240
241    #[test]
242    fn initialize_sets_population() {
243        let mut alg = NoveltySearch::new(5, 0.3);
244        let pool = GenePool::default_wafrift();
245        let mut rng = StdRng::seed_from_u64(1);
246        let pop = vec![
247            dummy_chromosome("UrlEncode", "sqli", "json"),
248            dummy_chromosome("CaseAlternation", "cmdi", "form"),
249        ];
250        alg.initialize(pop.clone(), &pool, &mut rng);
251        assert_eq!(alg.population.len(), 2);
252        assert!(alg.archive.is_empty());
253    }
254
255    #[test]
256    fn request_evaluations_returns_unique_ids() {
257        let mut alg = NoveltySearch::new(5, 0.3);
258        let pool = GenePool::default_wafrift();
259        let mut rng = StdRng::seed_from_u64(2);
260        alg.initialize(
261            vec![dummy_chromosome("UrlEncode", "sqli", "json")],
262            &pool,
263            &mut rng,
264        );
265
266        let c1 = alg.request_evaluations(2, &mut rng);
267        let c2 = alg.request_evaluations(2, &mut rng);
268        let ids: Vec<_> = c1.iter().chain(c2.iter()).map(|c| c.id).collect();
269        let unique: std::collections::HashSet<_> = ids.iter().copied().collect();
270        assert_eq!(ids.len(), unique.len());
271    }
272
273    #[test]
274    fn submit_evaluation_populates_archive_and_population() {
275        let mut alg = NoveltySearch::new(5, 0.0); // threshold = 0 → everything is novel
276        let pool = GenePool::default_wafrift();
277        let mut rng = StdRng::seed_from_u64(3);
278        alg.initialize(vec![], &pool, &mut rng);
279
280        let candidates = alg.request_evaluations(2, &mut rng);
281        let id1 = candidates[0].id;
282        let id2 = candidates[1].id;
283
284        alg.submit_evaluations(vec![
285            (
286                id1,
287                OracleVerdict {
288                    passed: true,
289                    status_delta: 1,
290                    body_delta: 1,
291                    latency_ms: 10,
292                    confidence: 0.9,
293                    triggered_rules: 0,
294                },
295            ),
296            (
297                id2,
298                OracleVerdict {
299                    passed: false,
300                    status_delta: 0,
301                    body_delta: 0,
302                    latency_ms: 10,
303                    confidence: 0.1,
304                    triggered_rules: 1,
305                },
306            ),
307        ]);
308
309        assert!(!alg.population.is_empty());
310        assert!(!alg.archive.is_empty());
311        assert!(alg.best().is_some());
312    }
313
314    #[test]
315    fn archive_respects_threshold() {
316        let mut alg = NoveltySearch::new(5, f64::INFINITY); // threshold = ∞ → nothing is novel
317        let pool = GenePool::default_wafrift();
318        let mut rng = StdRng::seed_from_u64(4);
319        alg.initialize(vec![], &pool, &mut rng);
320
321        let candidates = alg.request_evaluations(3, &mut rng);
322        let results: Vec<_> = candidates
323            .iter()
324            .map(|c| {
325                (
326                    c.id,
327                    OracleVerdict {
328                        passed: true,
329                        status_delta: 1,
330                        body_delta: 1,
331                        latency_ms: 10,
332                        confidence: 0.9,
333                        triggered_rules: 0,
334                    },
335                )
336            })
337            .collect();
338        alg.submit_evaluations(results);
339        // With infinite threshold, nothing should enter the archive
340        assert!(alg.archive.is_empty());
341        // But population still grows
342        assert!(!alg.population.is_empty());
343    }
344
345    #[test]
346    fn checkpoint_roundtrip_clears_in_flight() {
347        let mut alg = NoveltySearch::new(5, 0.3);
348        let pool = GenePool::default_wafrift();
349        let mut rng = StdRng::seed_from_u64(5);
350        alg.initialize(
351            vec![dummy_chromosome("UrlEncode", "sqli", "json")],
352            &pool,
353            &mut rng,
354        );
355        let _ = alg.request_evaluations(3, &mut rng);
356        assert!(!alg.in_flight.is_empty());
357
358        let bytes = alg.checkpoint().expect("checkpoint must serialize");
359        let mut restored = NoveltySearch::new(5, 0.3);
360        restored.restore(&bytes).expect("restore must succeed");
361        assert!(restored.in_flight.is_empty());
362    }
363
364    #[test]
365    fn should_terminate_respects_budget() {
366        let alg = NoveltySearch::new(5, 0.3);
367        let budget = Budget::default_wafrift();
368        let stats = SearchStats {
369            generation: budget.max_generations - 1,
370            ..SearchStats::default()
371        };
372        assert!(!alg.should_terminate(&stats, &budget));
373        let stats = SearchStats {
374            generation: budget.max_generations,
375            ..SearchStats::default()
376        };
377        assert!(alg.should_terminate(&stats, &budget));
378    }
379
380    #[test]
381    fn best_returns_none_for_empty_population_and_archive() {
382        let alg = NoveltySearch::new(5, 0.3);
383        assert!(alg.best().is_none());
384    }
385
386    #[test]
387    fn phenotypic_distance_is_symmetric() {
388        let a = dummy_chromosome("UrlEncode", "sqli", "json");
389        let b = dummy_chromosome("CaseAlternation", "cmdi", "form");
390        let d1 = NoveltySearch::phenotypic_distance(&a, &b);
391        let d2 = NoveltySearch::phenotypic_distance(&b, &a);
392        assert!((d1 - d2).abs() < f64::EPSILON);
393    }
394
395    #[test]
396    fn phenotypic_distance_self_is_zero() {
397        let a = dummy_chromosome("UrlEncode", "sqli", "json");
398        let d = NoveltySearch::phenotypic_distance(&a, &a);
399        assert!(d.abs() < f64::EPSILON);
400    }
401
402    #[test]
403    fn levenshtein_distance_smoke() {
404        assert_eq!(super::levenshtein_distance("kitten", "sitting"), 3);
405        assert_eq!(super::levenshtein_distance("", ""), 0);
406        assert_eq!(super::levenshtein_distance("a", ""), 1);
407        assert_eq!(super::levenshtein_distance("", "b"), 1);
408    }
409}