Skip to main content

aidaemon_memory/
retrieval_eval.rs

1//! Small deterministic metrics used by memory retrieval benchmarks.
2
3use std::collections::HashSet;
4
5#[derive(Debug, Clone, Copy, Default, PartialEq)]
6pub struct RetrievalMetrics {
7    pub recall_at_k: f32,
8    pub reciprocal_rank: f32,
9}
10
11/// Evaluate an ordered result list against one or more relevant owner IDs.
12/// Duplicate results do not inflate recall.
13pub fn evaluate_ranked(
14    ranked_owner_ids: &[String],
15    relevant_owner_ids: &HashSet<String>,
16    k: usize,
17) -> RetrievalMetrics {
18    if relevant_owner_ids.is_empty() || k == 0 {
19        return RetrievalMetrics::default();
20    }
21    let mut seen = HashSet::new();
22    let mut hits = 0usize;
23    let mut reciprocal_rank = 0.0;
24    for (rank, owner_id) in ranked_owner_ids.iter().take(k).enumerate() {
25        if !seen.insert(owner_id) || !relevant_owner_ids.contains(owner_id) {
26            continue;
27        }
28        hits += 1;
29        if reciprocal_rank == 0.0 {
30            reciprocal_rank = 1.0 / (rank + 1) as f32;
31        }
32    }
33    RetrievalMetrics {
34        recall_at_k: hits as f32 / relevant_owner_ids.len() as f32,
35        reciprocal_rank,
36    }
37}
38
39#[cfg(test)]
40mod tests {
41    use super::*;
42
43    #[test]
44    fn computes_recall_and_mrr_without_duplicate_inflation() {
45        let ranked = ["noise", "target-a", "target-a", "target-b"]
46            .map(str::to_string)
47            .to_vec();
48        let relevant = ["target-a", "target-b"]
49            .map(str::to_string)
50            .into_iter()
51            .collect();
52        let metrics = evaluate_ranked(&ranked, &relevant, 4);
53        assert_eq!(metrics.recall_at_k, 1.0);
54        assert_eq!(metrics.reciprocal_rank, 0.5);
55    }
56
57    #[test]
58    fn empty_judgment_is_well_defined() {
59        assert_eq!(
60            evaluate_ranked(&["x".to_string()], &HashSet::new(), 10),
61            RetrievalMetrics::default()
62        );
63    }
64}