lean_ctx_cloud/capture/
dedupe.rs1use unicode_normalization::UnicodeNormalization as _;
8
9use lean_ctx::core::knowledge::NodeType;
10
11const PERMUTATIONS: usize = 64;
13const DEDUPE_SEED_V1: u64 = 0x6c65_616e_6374_7831;
15const 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
21pub fn norm(s: &str) -> String {
26 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
46pub 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
55pub type Signature = [u64; PERMUTATIONS];
57
58fn mix(mut x: u64) -> u64 {
59 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
93pub 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#[derive(Debug, Clone)]
105pub struct Known {
106 pub node_type: NodeType,
107 pub signature: Signature,
108 pub refs: Vec<String>,
110}
111
112#[derive(Debug, Clone, PartialEq, Eq)]
114pub enum Verdict {
115 New,
116 Duplicate,
117 Merge {
119 index: usize,
120 refs: Vec<String>,
121 },
122}
123
124#[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}