1use std::sync::OnceLock;
14
15use super::tokens::encode_tokens;
16
17static VOCAB_LOG_PROBS: OnceLock<Vec<f64>> = OnceLock::new();
18
19fn get_vocab_log_probs() -> &'static Vec<f64> {
23 VOCAB_LOG_PROBS.get_or_init(|| {
24 let vocab_size = 200_000usize;
25 let h_n: f64 = (1..=vocab_size).map(|r| 1.0 / r as f64).sum();
26 (0..vocab_size)
27 .map(|rank| {
28 let r = rank + 1; let p = 1.0 / (r as f64 * h_n);
30 -p.log2()
31 })
32 .collect()
33 })
34}
35
36pub fn line_surprise(text: &str) -> f64 {
44 let tokens = encode_tokens(text);
45 if tokens.is_empty() {
46 return 0.0;
47 }
48 let log_probs = get_vocab_log_probs();
49 let max_id = log_probs.len();
50
51 let total: f64 = tokens
52 .iter()
53 .map(|&t| {
54 let id = t as usize;
55 if id < max_id {
56 log_probs[id]
57 } else {
58 17.6 }
60 })
61 .sum();
62
63 total / tokens.len() as f64
64}
65
66#[derive(Debug, Clone, Copy, PartialEq, Eq)]
69pub enum SurpriseLevel {
70 Low,
72 Medium,
74 High,
76}
77
78pub fn classify_surprise(text: &str) -> SurpriseLevel {
79 let s = line_surprise(text);
80 if s < 8.0 {
81 SurpriseLevel::Low
82 } else if s < 12.0 {
83 SurpriseLevel::Medium
84 } else {
85 SurpriseLevel::High
86 }
87}
88
89const DROP_SHARE_ORIGIN: f64 = 0.4;
91const DROP_SHARE_SLOPE: f64 = 0.4;
93const MAX_DROP_SHARE: f64 = 0.6;
95
96#[must_use]
102pub fn drop_share(entropy_threshold: f64) -> f64 {
103 ((entropy_threshold - DROP_SHARE_ORIGIN) * DROP_SHARE_SLOPE).clamp(0.0, MAX_DROP_SHARE)
104}
105
106#[must_use]
117pub fn surprise_floor<'a>(lines: impl IntoIterator<Item = &'a str>, entropy_threshold: f64) -> f64 {
118 let mut scores: Vec<f64> = lines
119 .into_iter()
120 .map(str::trim)
121 .filter(|t| t.len() >= 3)
122 .map(line_surprise)
123 .collect();
124 #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
125 let cut = (scores.len() as f64 * drop_share(entropy_threshold)).floor() as usize;
126 if cut == 0 {
127 return f64::NEG_INFINITY;
128 }
129 scores.sort_by(f64::total_cmp);
130 scores[cut.min(scores.len() - 1)]
131}
132
133pub fn should_keep_line(trimmed: &str, surprise_floor: f64) -> bool {
139 trimmed.len() < 3 || line_surprise(trimmed) >= surprise_floor
140}
141
142const KEPT_WINDOW: usize = 64;
164const REDUNDANCY_COSINE: f64 = 0.92;
166
167#[derive(Default)]
169pub struct ScoringCtx {
170 kept: std::collections::VecDeque<Vec<f32>>,
171}
172
173impl ScoringCtx {
174 pub fn new() -> Self {
175 Self::default()
176 }
177
178 pub fn push_kept(&mut self, embedding: Vec<f32>) {
179 if self.kept.len() >= KEPT_WINDOW {
180 self.kept.pop_front();
181 }
182 self.kept.push_back(embedding);
183 }
184
185 pub fn max_cosine(&self, emb: &[f32]) -> f64 {
187 self.kept
188 .iter()
189 .map(|k| cosine(k, emb))
190 .fold(0.0_f64, f64::max)
191 }
192}
193
194fn cosine(a: &[f32], b: &[f32]) -> f64 {
195 if a.is_empty() || a.len() != b.len() {
196 return 0.0;
197 }
198 let mut dot = 0.0_f64;
199 let mut na = 0.0_f64;
200 let mut nb = 0.0_f64;
201 for (x, y) in a.iter().zip(b.iter()) {
202 dot += f64::from(*x) * f64::from(*y);
203 na += f64::from(*x) * f64::from(*x);
204 nb += f64::from(*y) * f64::from(*y);
205 }
206 if na <= 0.0 || nb <= 0.0 {
207 return 0.0;
208 }
209 dot / (na.sqrt() * nb.sqrt())
210}
211
212pub fn should_keep_line_semantic(
218 trimmed: &str,
219 surprise_floor: f64,
220 embed: &dyn Fn(&str) -> Option<Vec<f32>>,
221 ctx: &mut ScoringCtx,
222) -> bool {
223 if !should_keep_line(trimmed, surprise_floor) {
224 return false;
225 }
226 let Some(emb) = embed(trimmed) else {
227 return true;
228 };
229 if ctx.max_cosine(&emb) >= REDUNDANCY_COSINE {
230 return false;
231 }
232 ctx.push_kept(emb);
233 true
234}
235
236#[cfg(test)]
237pub mod tests {
238 use super::*;
239
240 #[test]
241 fn common_code_has_low_surprise() {
242 let common = "let x = 1;";
243 let s = line_surprise(common);
244 assert!(s > 0.0, "surprise should be positive");
245 }
246
247 #[test]
248 fn rare_identifiers_have_higher_surprise() {
249 let common = "let x = 1;";
250 let rare = "let zygomorphic_validator = XenolithProcessor::new();";
251 assert!(
252 line_surprise(rare) > line_surprise(common),
253 "rare identifiers should have higher surprise"
254 );
255 }
256
257 #[test]
258 fn empty_returns_zero() {
259 assert_eq!(line_surprise(""), 0.0);
260 }
261
262 #[test]
263 fn classify_surprise_is_consistent() {
264 let simple = "let x = 1;";
265 let complex = "ZygomorphicXenolithValidator::process_quantum_state(&mut ctx)";
266 let s_simple = line_surprise(simple);
267 let s_complex = line_surprise(complex);
268 assert!(
269 s_complex > s_simple,
270 "rare identifiers ({s_complex}) should have higher surprise than common code ({s_simple})"
271 );
272 }
273
274 #[test]
275 fn should_keep_preserves_rare_lines() {
276 let rare = "ZygomorphicValidator::process_xenolith(&mut state)";
277 let common = [
278 "let a = 1;",
279 "let b = 2;",
280 "x += 1;",
281 "return None;",
282 "Ok(())",
283 "let mut v = Vec::new();",
284 "if x { y }",
285 "self.len()",
286 "use std::fmt;",
287 ];
288 let mut file = common.to_vec();
289 file.push(rare);
290 let floor = surprise_floor(file.iter().copied(), 1.9);
292 assert!(should_keep_line(rare, floor), "rare line must survive");
293 let shed = common
294 .iter()
295 .filter(|l| !should_keep_line(l, floor))
296 .count();
297 assert!(shed >= 1, "boilerplate is shed first (floor {floor})");
298 assert!(should_keep_line("}", floor), "sub-3-byte lines always stay");
299 }
300
301 #[test]
304 fn drop_share_is_monotonic_and_bounded() {
305 assert_eq!(drop_share(0.0), 0.0);
306 assert_eq!(drop_share(DROP_SHARE_ORIGIN), 0.0);
307 let mut prev = drop_share(0.6);
308 for step in 1..=13 {
309 let t = 0.6 + 0.1 * f64::from(step);
310 let share = drop_share(t);
311 assert!(share > prev, "{t}: {share} must exceed {prev}");
312 prev = share;
313 }
314 assert_eq!(drop_share(10.0), MAX_DROP_SHARE);
315 }
316
317 #[test]
318 fn surprise_floor_cuts_the_requested_share() {
319 let lines: Vec<String> = (0..40)
320 .map(|i| format!("let value_{i} = compute_{}(input);", "x".repeat(i % 7)))
321 .collect();
322 let refs = || lines.iter().map(String::as_str);
323 for t in [0.6, 1.0, 1.4, 1.9] {
324 let floor = surprise_floor(refs(), t);
325 let dropped = refs().filter(|l| !should_keep_line(l, floor)).count();
326 #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
327 let cap = (40.0 * drop_share(t)).floor() as usize;
328 assert!(dropped <= cap, "t={t}: dropped {dropped} > cap {cap}");
329 assert_eq!(floor, surprise_floor(refs(), t), "deterministic (#498)");
330 }
331 assert_eq!(surprise_floor(refs(), 0.4), f64::NEG_INFINITY);
332 assert_eq!(surprise_floor(std::iter::empty(), 1.9), f64::NEG_INFINITY);
333 }
334
335 #[allow(clippy::unnecessary_wraps)] fn bow_embed(line: &str) -> Option<Vec<f32>> {
340 let mut v = vec![0.0f32; 64];
341 for tok in line.to_lowercase().split(|c: char| !c.is_alphanumeric()) {
342 if tok.len() < 2 {
343 continue;
344 }
345 let mut h = 0u64;
346 for b in tok.bytes() {
347 h = h.wrapping_mul(31).wrapping_add(u64::from(b));
348 }
349 v[(h % 64) as usize] += 1.0;
350 }
351 Some(v)
352 }
353
354 #[test]
355 fn semantic_dedup_drops_near_duplicate_kept_lines() {
356 let mut ctx = ScoringCtx::new();
357 let embed = |s: &str| bow_embed(s);
358 let a = "fn validate_user_payload(payload: &UserPayload) -> Result<(), ValidationError>";
359 let b = "fn validate_user_payload(payload: &UserPayload) -> Result<(), ValidationError> ";
361 let c = "const MAX_RETRY_BACKOFF_MS: u64 = 30_000;";
362
363 assert!(should_keep_line_semantic(a, 0.5, &embed, &mut ctx));
364 assert!(
365 !should_keep_line_semantic(b, 0.5, &embed, &mut ctx),
366 "near-identical line must be dropped as redundant"
367 );
368 assert!(
369 should_keep_line_semantic(c, 0.5, &embed, &mut ctx),
370 "distinct line stays"
371 );
372 }
373
374 #[test]
375 fn no_embedder_is_identical_to_zipf_path() {
376 let mut ctx = ScoringCtx::new();
377 let none = |_: &str| None;
378 for line in [
379 "fn main() { run(); }",
380 "let x = 1;",
381 "ZygomorphicXenolithValidator::process_quantum_state(&mut ctx)",
382 "// plain comment",
383 ] {
384 assert_eq!(
385 should_keep_line_semantic(line, 1.0, &none, &mut ctx),
386 should_keep_line(line, 1.0),
387 "without embeddings the decision must match the Zipf path: {line}"
388 );
389 }
390 }
391
392 #[test]
393 fn kept_window_is_bounded() {
394 let mut ctx = ScoringCtx::new();
395 for i in 0..200 {
396 ctx.push_kept(vec![i as f32; 8]);
397 }
398 assert!(ctx.kept.len() <= 64);
399 }
400
401 #[test]
402 fn cosine_handles_degenerate_inputs() {
403 assert_eq!(cosine(&[], &[]), 0.0);
404 assert_eq!(cosine(&[1.0], &[1.0, 2.0]), 0.0);
405 assert_eq!(cosine(&[0.0, 0.0], &[0.0, 0.0]), 0.0);
406 assert!((cosine(&[1.0, 0.0], &[1.0, 0.0]) - 1.0).abs() < 1e-9);
407 }
408}