Skip to main content

lean_ctx_cloud/capture/
dedupe.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Dedupe of the capture gate (SPEC-ENGINE §3.1.5): an exact key over the
3//! normalised statement and a MinHash near-duplicate check, both keyed with
4//! the place id key `pk_id`, so two engines of a place reach the same
5//! verdict and nobody without the key can confirm a guessed statement.
6
7use unicode_normalization::UnicodeNormalization as _;
8
9use lean_ctx::core::knowledge::NodeType;
10
11/// Permutations of the MinHash signature.
12const PERMUTATIONS: usize = 64;
13/// Constant seeds (`DEDUPE_SEED_V1`): the same on every engine.
14const DEDUPE_SEED_V1: u64 = 0x6c65_616e_6374_7831;
15/// Estimated Jaccard at or above which two statements are near duplicates.
16const NEAR_THRESHOLD: f64 = 0.80;
17
18static PUNCTUATION: std::sync::LazyLock<regex::Regex> =
19    std::sync::LazyLock::new(|| regex::Regex::new(r"^\p{P}$").expect("static pattern"));
20
21/// norm v1 (C0 2.0 `vectors/norm.vectors.json`): NFKC → full Unicode
22/// lowercase → every character of general category P removed outside
23/// backtick spans (a backtick toggles a span and is kept; an unclosed span
24/// runs to the end) → each run of White_Space replaced by one space → trim.
25pub fn norm(s: &str) -> String {
26    // `str::to_lowercase` applies the full mapping, final sigma included.
27    let lower = s.nfkc().collect::<String>().to_lowercase();
28    let mut out = String::new();
29    let mut in_code = false;
30    let mut buf = [0u8; 4];
31    for c in lower.chars() {
32        if c == '`' {
33            in_code = !in_code;
34            out.push(c);
35        } else if c.is_whitespace() {
36            if !out.ends_with(' ') {
37                out.push(' ');
38            }
39        } else if in_code || !PUNCTUATION.is_match(c.encode_utf8(&mut buf)) {
40            out.push(c);
41        }
42    }
43    out.trim().to_string()
44}
45
46/// Exact dedupe key `dk = blake3_keyed(pk_id, node_type || 0x00 || norm)`.
47pub fn exact_key(pk_id: &[u8; 32], node_type: NodeType, statement: &str) -> [u8; 32] {
48    let mut h = blake3::Hasher::new_keyed(pk_id);
49    h.update(node_type.as_str().as_bytes());
50    h.update(&[0]);
51    h.update(norm(statement).as_bytes());
52    *h.finalize().as_bytes()
53}
54
55/// MinHash signature over keyed word 3-shingles.
56pub type Signature = [u64; PERMUTATIONS];
57
58fn mix(mut x: u64) -> u64 {
59    // splitmix64 finaliser: a fixed, portable permutation of u64.
60    x ^= x >> 30;
61    x = x.wrapping_mul(0xbf58_476d_1ce4_e5b9);
62    x ^= x >> 27;
63    x = x.wrapping_mul(0x94d0_49bb_1331_11eb);
64    x ^ (x >> 31)
65}
66
67pub fn signature(pk_id: &[u8; 32], statement: &str) -> Signature {
68    let normalized = norm(statement);
69    let words: Vec<&str> = normalized.split(' ').filter(|w| !w.is_empty()).collect();
70    let shingles: Vec<u64> = if words.len() < 3 {
71        vec![shingle_hash(pk_id, &words.join(" "))]
72    } else {
73        words
74            .windows(3)
75            .map(|w| shingle_hash(pk_id, &w.join(" ")))
76            .collect()
77    };
78    let mut sig = [u64::MAX; PERMUTATIONS];
79    for (i, slot) in sig.iter_mut().enumerate() {
80        let seed = mix(DEDUPE_SEED_V1.wrapping_add(i as u64));
81        for s in &shingles {
82            *slot = (*slot).min(mix(s ^ seed));
83        }
84    }
85    sig
86}
87
88fn shingle_hash(pk_id: &[u8; 32], shingle: &str) -> u64 {
89    let digest = blake3::keyed_hash(pk_id, shingle.as_bytes());
90    u64::from_le_bytes(digest.as_bytes()[..8].try_into().expect("8 bytes"))
91}
92
93/// Estimated Jaccard similarity of two signatures.
94pub fn similarity(a: &Signature, b: &Signature) -> f64 {
95    let same = a.iter().zip(b).filter(|(x, y)| x == y).count();
96    same as f64 / PERMUTATIONS as f64
97}
98
99pub fn is_near(a: &Signature, b: &Signature) -> bool {
100    similarity(a, b) >= NEAR_THRESHOLD
101}
102
103/// What a dedupe index knows about one captured node.
104#[derive(Debug, Clone)]
105pub struct Known {
106    pub node_type: NodeType,
107    pub signature: Signature,
108    /// References the node already carries.
109    pub refs: Vec<String>,
110}
111
112/// Dedupe verdict for a candidate.
113#[derive(Debug, Clone, PartialEq, Eq)]
114pub enum Verdict {
115    New,
116    Duplicate,
117    /// Near duplicate of node `index`; the candidate adds these references.
118    Merge {
119        index: usize,
120        refs: Vec<String>,
121    },
122}
123
124/// Exact keys and signatures of the place plus the current batch.
125#[derive(Debug, Default)]
126pub struct Index {
127    exact: std::collections::HashSet<[u8; 32]>,
128    known: Vec<Known>,
129}
130
131impl Index {
132    pub fn insert(&mut self, key: [u8; 32], known: Known) {
133        self.exact.insert(key);
134        self.known.push(known);
135    }
136
137    pub fn known_mut(&mut self, index: usize) -> Option<&mut Known> {
138        self.known.get_mut(index)
139    }
140
141    pub fn verdict(&self, key: &[u8; 32], known: &Known) -> Verdict {
142        if self.exact.contains(key) {
143            return Verdict::Duplicate;
144        }
145        let near = self.known.iter().position(|k| {
146            k.node_type == known.node_type && is_near(&k.signature, &known.signature)
147        });
148        match near {
149            None => Verdict::New,
150            Some(index) => {
151                let refs: Vec<String> = known
152                    .refs
153                    .iter()
154                    .filter(|r| !self.known[index].refs.contains(r))
155                    .cloned()
156                    .collect();
157                if refs.is_empty() {
158                    Verdict::Duplicate
159                } else {
160                    Verdict::Merge { index, refs }
161                }
162            }
163        }
164    }
165}
166
167#[cfg(test)]
168mod tests {
169    use super::*;
170
171    const KEY: [u8; 32] = [7; 32];
172
173    #[test]
174    fn norm_keeps_code_and_drops_punctuation() {
175        assert_eq!(
176            norm("  The  Relay, drops `a.b()`  frames!  "),
177            "the relay drops `a.b()` frames"
178        );
179        assert_eq!(norm("Fullwidth"), "fullwidth");
180    }
181
182    #[test]
183    fn exact_key_is_case_and_space_insensitive_and_typed() {
184        let a = exact_key(&KEY, NodeType::Fact, "The relay drops frames.");
185        assert_eq!(
186            a,
187            exact_key(&KEY, NodeType::Fact, "the  relay drops frames")
188        );
189        assert_ne!(
190            a,
191            exact_key(&KEY, NodeType::Gotcha, "The relay drops frames.")
192        );
193        assert_ne!(
194            a,
195            exact_key(&[8; 32], NodeType::Fact, "The relay drops frames.")
196        );
197    }
198
199    #[test]
200    fn near_duplicates_are_found_and_others_are_not() {
201        let base = "The outbox retries a refused push after the lease is renewed by the scheduler.";
202        let one_edit =
203            "The outbox retries a refused push after the lease is renewed by the scheduler again.";
204        let other =
205            "Sealed vaults wrap every content key with the current epoch key before upload.";
206        let s = signature(&KEY, base);
207        assert!(is_near(&s, &signature(&KEY, one_edit)));
208        assert!(!is_near(&s, &signature(&KEY, other)));
209        assert_eq!(s, signature(&KEY, base), "deterministic");
210    }
211
212    #[test]
213    fn near_duplicate_with_a_new_reference_merges() {
214        let text = "The outbox retries a refused push after the lease is renewed by the scheduler.";
215        let mut index = Index::default();
216        let known = |refs: &[&str]| Known {
217            node_type: NodeType::Fact,
218            signature: signature(&KEY, text),
219            refs: refs.iter().map(ToString::to_string).collect(),
220        };
221        index.insert(exact_key(&KEY, NodeType::Fact, text), known(&["file:a.rs"]));
222        let near = format!("{text} Always.");
223        let key = exact_key(&KEY, NodeType::Fact, &near);
224        assert_eq!(
225            index.verdict(&key, &known(&["file:a.rs"])),
226            Verdict::Duplicate
227        );
228        assert_eq!(
229            index.verdict(&key, &known(&["file:a.rs", "file:b.rs"])),
230            Verdict::Merge {
231                index: 0,
232                refs: vec!["file:b.rs".into()]
233            }
234        );
235    }
236}