Skip to main content

lean_ctx/core/
entropy.rs

1use std::collections::{HashMap, HashSet};
2use std::hash::{Hash, Hasher};
3use std::io::Write;
4
5use flate2::Compression;
6use flate2::write::GzEncoder;
7
8use super::tokens::{count_tokens, encode_tokens};
9
10const BPE_ENTROPY_THRESHOLD: f64 = 1.0;
11
12/// Result of entropy-based compression: output text, token counts, and techniques used.
13#[derive(Debug)]
14pub struct EntropyResult {
15    pub output: String,
16    pub original_tokens: usize,
17    pub compressed_tokens: usize,
18    pub techniques: Vec<String>,
19}
20
21impl EntropyResult {
22    /// Returns the percentage of tokens saved by compression.
23    pub fn savings_percent(&self) -> f64 {
24        if self.original_tokens == 0 {
25            return 0.0;
26        }
27        let saved = self.original_tokens.saturating_sub(self.compressed_tokens);
28        (saved as f64 / self.original_tokens as f64) * 100.0
29    }
30}
31
32/// Computes Shannon entropy (bits) over character frequencies in the text.
33pub fn shannon_entropy(text: &str) -> f64 {
34    if text.is_empty() {
35        return 0.0;
36    }
37    let mut freq: HashMap<char, usize> = HashMap::new();
38    let total = text.chars().count();
39
40    for c in text.chars() {
41        *freq.entry(c).or_default() += 1;
42    }
43
44    freq.values().fold(0.0_f64, |acc, &count| {
45        let p = count as f64 / total as f64;
46        acc - p * p.log2()
47    })
48}
49
50/// Shannon entropy over already-encoded BPE token IDs (o200k_base).
51pub fn token_entropy_from_ids(tokens: &[u32]) -> f64 {
52    if tokens.is_empty() {
53        return 0.0;
54    }
55    let total = tokens.len();
56    let mut freq: HashMap<u32, usize> = HashMap::new();
57    for &t in tokens {
58        *freq.entry(t).or_default() += 1;
59    }
60    // Sum in a canonical (sorted-by-count) order: f64 addition is not
61    // associative, so folding over HashMap iteration order — random per instance
62    // — would make the entropy, and thus `density`/`entropy` mode output,
63    // non-deterministic across processes and defeat prompt caching (#498).
64    let mut counts: Vec<usize> = freq.into_values().collect();
65    counts.sort_unstable();
66    counts.iter().fold(0.0_f64, |acc, &count| {
67        let p = count as f64 / total as f64;
68        acc - p * p.log2()
69    })
70}
71
72/// Shannon entropy over BPE token IDs (o200k_base).
73/// More LLM-relevant than character entropy since LLMs process BPE tokens.
74pub fn token_entropy(text: &str) -> f64 {
75    let tokens = encode_tokens(text);
76    token_entropy_from_ids(&tokens)
77}
78
79/// Normalized Shannon entropy over encoded token IDs: H(X) / log₂(n), n = unique token count.
80pub fn normalized_token_entropy_from_ids(tokens: &[u32]) -> f64 {
81    if tokens.is_empty() {
82        return 0.0;
83    }
84    let total = tokens.len();
85    let mut freq: HashMap<u32, usize> = HashMap::new();
86    for &t in tokens {
87        *freq.entry(t).or_default() += 1;
88    }
89    let n_unique = freq.len();
90    if n_unique <= 1 {
91        return 0.0;
92    }
93    // Canonical summation order for determinism (#498); see `token_entropy_from_ids`.
94    let mut counts: Vec<usize> = freq.into_values().collect();
95    counts.sort_unstable();
96    let h = counts.iter().fold(0.0_f64, |acc, &count| {
97        let p = count as f64 / total as f64;
98        acc - p * p.log2()
99    });
100    let h_max = (n_unique as f64).log2();
101    h / h_max
102}
103
104/// Normalized Shannon entropy: H(X) / log₂(n) where n = number of unique symbols.
105/// Returns a value in [0, 1] where 0 = perfectly predictable, 1 = maximum entropy.
106/// This makes thresholds comparable across different alphabet sizes.
107pub fn normalized_token_entropy(text: &str) -> f64 {
108    let tokens = encode_tokens(text);
109    normalized_token_entropy_from_ids(&tokens)
110}
111
112/// Computes word-set Jaccard similarity between two strings (0.0–1.0).
113pub fn jaccard_similarity(a: &str, b: &str) -> f64 {
114    let set_a: HashSet<&str> = a.split_whitespace().collect();
115    let set_b: HashSet<&str> = b.split_whitespace().collect();
116
117    let intersection = set_a.intersection(&set_b).count();
118    let union = set_a.union(&set_b).count();
119
120    if union == 0 {
121        return 0.0;
122    }
123    intersection as f64 / union as f64
124}
125
126/// N-gram Jaccard similarity — preserves word order (unlike word-set Jaccard).
127pub fn ngram_jaccard(a: &str, b: &str, n: usize) -> f64 {
128    let set_a = ngram_set(a, n);
129    let set_b = ngram_set(b, n);
130
131    let intersection = set_a.intersection(&set_b).count();
132    let union = set_a.union(&set_b).count();
133
134    if union == 0 {
135        return 0.0;
136    }
137    intersection as f64 / union as f64
138}
139
140fn ngram_set(text: &str, n: usize) -> HashSet<Vec<String>> {
141    let words: Vec<&str> = text.split_whitespace().collect();
142    if words.len() < n {
143        let mut set = HashSet::new();
144        if !words.is_empty() {
145            set.insert(words.iter().map(std::string::ToString::to_string).collect());
146        }
147        return set;
148    }
149    words
150        .windows(n)
151        .map(|w| w.iter().map(std::string::ToString::to_string).collect())
152        .collect()
153}
154
155/// Minhash signature for approximate Jaccard via LSH.
156/// Uses k independent hash functions (polynomial hashing with different seeds).
157pub fn minhash_signature(text: &str, n: usize, k: usize) -> Vec<u64> {
158    let ngrams = ngram_set(text, n);
159    if ngrams.is_empty() {
160        return vec![u64::MAX; k];
161    }
162    let mut signature = vec![u64::MAX; k];
163    for ngram in &ngrams {
164        for (i, min) in signature.iter_mut().enumerate() {
165            let h = hash_with_seed(ngram, i as u64);
166            if h < *min {
167                *min = h;
168            }
169        }
170    }
171    signature
172}
173
174/// Approximate Jaccard from two minhash signatures.
175pub fn minhash_similarity(sig_a: &[u64], sig_b: &[u64]) -> f64 {
176    if sig_a.len() != sig_b.len() || sig_a.is_empty() {
177        return 0.0;
178    }
179    let matches = sig_a
180        .iter()
181        .zip(sig_b.iter())
182        .filter(|(a, b)| a == b)
183        .count();
184    matches as f64 / sig_a.len() as f64
185}
186
187fn hash_with_seed<T: Hash>(value: &T, seed: u64) -> u64 {
188    let mut hasher = std::collections::hash_map::DefaultHasher::new();
189    seed.hash(&mut hasher);
190    value.hash(&mut hasher);
191    hasher.finish()
192}
193
194/// Kolmogorov complexity proxy: K(x) ≈ len(gzip(x)) / len(x).
195/// Lower values = more compressible = more redundant.
196pub fn kolmogorov_proxy(content: &str) -> f64 {
197    if content.is_empty() {
198        return 1.0;
199    }
200    let mut encoder = GzEncoder::new(Vec::new(), Compression::default());
201    encoder.write_all(content.as_bytes()).ok();
202    let compressed = encoder.finish().unwrap_or_default();
203    compressed.len() as f64 / content.len() as f64
204}
205
206/// Classification of content compressibility based on Kolmogorov proxy (gzip ratio).
207#[derive(Debug, Clone, Copy, PartialEq, Eq)]
208pub enum CompressibilityClass {
209    High,
210    Medium,
211    Low,
212}
213
214impl CompressibilityClass {
215    /// Returns a human-readable label with the Kolmogorov threshold range.
216    pub fn label(&self) -> &'static str {
217        match self {
218            Self::High => "high (K<0.3)",
219            Self::Medium => "medium (0.3≤K<0.6)",
220            Self::Low => "low (K≥0.6)",
221        }
222    }
223}
224
225/// Classify how compressible content is based on gzip ratio.
226pub fn compressibility_class(content: &str) -> CompressibilityClass {
227    let k = kolmogorov_proxy(content);
228    if k < 0.3 {
229        CompressibilityClass::High
230    } else if k < 0.6 {
231        CompressibilityClass::Medium
232    } else {
233        CompressibilityClass::Low
234    }
235}
236
237/// Compresses content by removing low-entropy lines and deduplicating patterns.
238pub fn entropy_compress(content: &str) -> EntropyResult {
239    entropy_compress_with_thresholds(content, BPE_ENTROPY_THRESHOLD, 0.7, &[])
240}
241
242/// Entropy compression with the opportunistic semantic redundancy filter
243/// (#544) pinned OFF. The regular path uses the shared embedding engine
244/// whenever it happens to be loaded, so its output depends on runtime state.
245/// Benchmarks and the scorecard (#211) need run-to-run and machine-to-machine
246/// reproducibility, so they must go through this entry point.
247pub fn entropy_compress_deterministic(content: &str) -> EntropyResult {
248    entropy_compress_inner(content, BPE_ENTROPY_THRESHOLD, 0.7, &[], false, &[])
249}
250
251/// Entropy compression with file-type-adaptive thresholds and event emission.
252/// `force_keep` lines (explicit `protect` tokens, #709) survive verbatim; pass
253/// `&[]` to keep the pre-protect behaviour byte-identical (#498).
254pub fn entropy_compress_adaptive(
255    content: &str,
256    path: &str,
257    force_keep: &[String],
258) -> EntropyResult {
259    let thresholds = super::adaptive_thresholds::read_thresholds(path, content);
260    let before_lines = content.lines().count() as u32;
261    let result = entropy_compress_with_thresholds(
262        content,
263        thresholds.bpe_entropy,
264        thresholds.jaccard,
265        force_keep,
266    );
267    let after_lines = result.output.lines().count() as u32;
268
269    if before_lines != after_lines {
270        super::events::emit(super::events::EventKind::Compression {
271            path: path.to_string(),
272            before_lines,
273            after_lines,
274            strategy: "entropy_adaptive".to_string(),
275            kept_line_count: after_lines,
276            removed_line_count: before_lines.saturating_sub(after_lines),
277        });
278    }
279
280    result
281}
282
283/// Like [`entropy_compress_adaptive`] but overrides the file-adaptive BPE-entropy
284/// threshold (e.g. from the aggressiveness knob) while keeping the file-adaptive
285/// jaccard. Pure function of its inputs (#498). Higher `bpe_entropy` drops more
286/// low-information lines.
287pub fn entropy_compress_with_threshold(
288    content: &str,
289    path: &str,
290    bpe_entropy: f64,
291    force_keep: &[String],
292) -> EntropyResult {
293    let thresholds = super::adaptive_thresholds::read_thresholds(path, content);
294    entropy_compress_with_thresholds(content, bpe_entropy, thresholds.jaccard, force_keep)
295}
296
297/// Task-conditioned entropy compression: lines that would normally be dropped
298/// for low entropy are kept if they contain task-relevant keywords.  This is
299/// the Information Bottleneck proxy: we compress away only what is neither
300/// surprising (high H) *nor* task-relevant (mentions goal concepts).
301/// Falls back to pure entropy when `task_keywords` is empty.
302pub fn entropy_compress_task_conditioned(
303    content: &str,
304    path: &str,
305    task_keywords: &[String],
306    force_keep: &[String],
307) -> EntropyResult {
308    let thresholds = super::adaptive_thresholds::read_thresholds(path, content);
309    let before_lines = content.lines().count() as u32;
310    let result = entropy_compress_with_task(
311        content,
312        thresholds.bpe_entropy,
313        thresholds.jaccard,
314        task_keywords,
315        force_keep,
316    );
317    let after_lines = result.output.lines().count() as u32;
318    if before_lines != after_lines {
319        super::events::emit(super::events::EventKind::Compression {
320            path: path.to_string(),
321            before_lines,
322            after_lines,
323            strategy: "entropy_task_conditioned".to_string(),
324            kept_line_count: after_lines,
325            removed_line_count: before_lines.saturating_sub(after_lines),
326        });
327    }
328    result
329}
330
331/// Real line embedder for the semantic redundancy filter (#544): uses the
332/// shared neural engine only when it is ALREADY loaded (never blocks a read
333/// on a model load) and only for files small enough that per-line embedding
334/// stays within the read-path latency budget. Embeddings are cached by line
335/// hash so re-reads cost nothing.
336#[cfg(feature = "embeddings")]
337fn line_embedder(line_count: usize) -> impl Fn(&str) -> Option<Vec<f32>> {
338    use std::collections::HashMap;
339    use std::sync::Mutex;
340
341    const MAX_LINES_FOR_SEMANTIC: usize = 400;
342    const CACHE_CAP: usize = 8192;
343    static LINE_EMBED_CACHE: Mutex<Option<HashMap<u64, Vec<f32>>>> = Mutex::new(None);
344
345    let engine = if line_count <= MAX_LINES_FOR_SEMANTIC {
346        crate::tools::ctx_knowledge::embeddings::embedding_engine_nonblocking()
347    } else {
348        None
349    };
350
351    move |line: &str| {
352        let engine = engine?;
353        if line.len() < 8 {
354            return None;
355        }
356        let mut hasher = std::collections::hash_map::DefaultHasher::new();
357        std::hash::Hash::hash(&line, &mut hasher);
358        let key = std::hash::Hasher::finish(&hasher);
359
360        if let Ok(mut guard) = LINE_EMBED_CACHE.lock()
361            && let Some(hit) = guard.get_or_insert_with(HashMap::new).get(&key)
362        {
363            return Some(hit.clone());
364        }
365        let emb = engine.embed(line).ok()?;
366        if let Ok(mut guard) = LINE_EMBED_CACHE.lock() {
367            let map = guard.get_or_insert_with(HashMap::new);
368            if map.len() >= CACHE_CAP {
369                map.clear();
370            }
371            map.insert(key, emb.clone());
372        }
373        Some(emb)
374    }
375}
376
377#[cfg(not(feature = "embeddings"))]
378fn line_embedder(_line_count: usize) -> impl Fn(&str) -> Option<Vec<f32>> {
379    |_: &str| None
380}
381
382/// Read-path entropy compression. The semantic redundancy filter (#544) is
383/// off here: it ran only while the embedding model happened to be loaded, so
384/// two reads of the same file could return different text — which breaks the
385/// output-determinism contract (#498) and, since #1910 made `entropy` drop
386/// lines at all, showed up as `read_mode_deterministic:entropy` failing.
387fn entropy_compress_with_task(
388    content: &str,
389    entropy_threshold: f64,
390    jaccard_threshold: f64,
391    task_keywords: &[String],
392    force_keep: &[String],
393) -> EntropyResult {
394    entropy_compress_inner(
395        content,
396        entropy_threshold,
397        jaccard_threshold,
398        task_keywords,
399        false,
400        force_keep,
401    )
402}
403
404fn entropy_compress_inner(
405    content: &str,
406    entropy_threshold: f64,
407    jaccard_threshold: f64,
408    task_keywords: &[String],
409    semantic: bool,
410    force_keep: &[String],
411) -> EntropyResult {
412    let original_tokens = count_tokens(content);
413    let mut lines: Vec<&str> = content.lines().collect();
414    let mut techniques = Vec::new();
415
416    let kw_lower: Vec<String> = task_keywords.iter().map(|k| k.to_lowercase()).collect();
417    let original_count = lines.len();
418    let mut task_rescued = 0usize;
419    // Semantic redundancy (#544): when the embedding engine is already
420    // loaded, kept lines that embed near-identically to earlier kept lines
421    // are dropped (MMR). Without the engine the closure returns None and the
422    // decision path is byte-identical to the Zipf-only filter.
423    // `semantic=false` (deterministic contract) requests an embedder above
424    // the size cutoff, which never resolves an engine.
425    let embed = line_embedder(if semantic { original_count } else { usize::MAX });
426    let mut scoring_ctx = super::surprise::ScoringCtx::new();
427    // #1910: the threshold sets how much of *this* file is shed (most
428    // predictable lines first), so it — and aggressiveness — take effect.
429    let floor = super::surprise::surprise_floor(lines.iter().copied(), entropy_threshold);
430    lines.retain(|line| {
431        let trimmed = line.trim();
432        // Explicit protect tokens (#709) win over every lossy heuristic: a line
433        // containing one is force-kept verbatim before any threshold is applied.
434        if super::protect::line_is_protected(line, force_keep) {
435            return true;
436        }
437        if super::surprise::should_keep_line_semantic(trimmed, floor, &embed, &mut scoring_ctx) {
438            return true;
439        }
440        // Task-conditioned rescue: keep predictable lines that mention task keywords.
441        if !kw_lower.is_empty() {
442            let lower = trimmed.to_lowercase();
443            if kw_lower.iter().any(|kw| lower.contains(kw.as_str())) {
444                task_rescued += 1;
445                return true;
446            }
447        }
448        false
449    });
450    let removed = original_count - lines.len();
451    if removed > 0 || task_rescued > 0 {
452        let mut msg = format!("⊘ {removed} predictable lines");
453        if task_rescued > 0 {
454            msg.push_str(&format!(" [+{task_rescued} task-rescued]"));
455        }
456        techniques.push(msg);
457    }
458
459    let blocks = extract_blocks(&lines);
460    let groups = find_pattern_groups(&blocks, jaccard_threshold);
461    let mut dedup_count = 0;
462    for group in &groups {
463        if group.len() > 1 {
464            dedup_count += group.len() - 1;
465        }
466    }
467    if dedup_count > 0 {
468        techniques.push(format!("⊘ {dedup_count} duplicate patterns (J≥0.7)"));
469    }
470
471    let mut result: Vec<String> = Vec::new();
472    let mut skip_indices: std::collections::HashSet<usize> = std::collections::HashSet::new();
473    for group in &groups {
474        if group.len() > 1 {
475            for &idx in &group[1..] {
476                // Protected lines (#709) are a hard keep: never dedup them away,
477                // not just exempt them from the entropy threshold above.
478                if !super::protect::line_is_protected(lines[idx], force_keep) {
479                    skip_indices.insert(idx);
480                }
481            }
482        }
483    }
484    for (i, line) in lines.iter().enumerate() {
485        if !skip_indices.contains(&i) {
486            result.push(line.to_string());
487        }
488    }
489
490    let mut collapsed = Vec::new();
491    let mut blank_count = 0;
492    for line in &result {
493        if line.trim().is_empty() {
494            blank_count += 1;
495            if blank_count <= 1 {
496                collapsed.push(line.clone());
497            }
498        } else {
499            blank_count = 0;
500            collapsed.push(line.clone());
501        }
502    }
503    let output = collapsed.join("\n");
504    let compressed_tokens = count_tokens(&output);
505
506    // Safeguard: BPE re-tokenization of a line subset can, for tiny adversarial
507    // inputs, exceed the original token count (e.g. a dropped trailing newline
508    // merges differently). Never inflate — fall back to the original verbatim.
509    let final_output = if compressed_tokens > original_tokens {
510        content.to_string()
511    } else {
512        output
513    };
514    let final_tokens = if compressed_tokens > original_tokens {
515        original_tokens
516    } else {
517        compressed_tokens
518    };
519
520    EntropyResult {
521        output: final_output,
522        original_tokens,
523        compressed_tokens: final_tokens,
524        techniques,
525    }
526}
527
528fn entropy_compress_with_thresholds(
529    content: &str,
530    entropy_threshold: f64,
531    jaccard_threshold: f64,
532    force_keep: &[String],
533) -> EntropyResult {
534    entropy_compress_with_task(
535        content,
536        entropy_threshold,
537        jaccard_threshold,
538        &[],
539        force_keep,
540    )
541}
542
543/// #798: Walk kept lines in source order; when a kept line has unclosed
544/// call/index delimiters `()` `[]`, force-keep subsequent lines until
545/// balance is restored. Prevents partial call expressions like
546/// `logger.info(` surviving without their arguments.
547///
548/// Intentionally ignores `{}` — block braces wrap large code bodies and
549/// force-keeping entire function blocks would defeat the density target.
550fn delimiter_balance_force_keep(
551    lines: &[&str],
552    scored: &[(usize, f64, usize)],
553    keep: &mut [bool],
554    used: &mut usize,
555    kept_count: &mut usize,
556) {
557    let tok_for =
558        |idx: usize| -> usize { scored.iter().find(|(i, _, _)| *i == idx).map_or(1, |s| s.2) };
559
560    // Phase 1: identify multi-line delimiter spans (opener_line, closer_line).
561    let mut spans: Vec<(usize, usize)> = Vec::new();
562    let mut open_stack: Vec<usize> = Vec::new();
563    for (i, line) in lines.iter().enumerate() {
564        for ch in line.chars() {
565            match ch {
566                '(' | '[' => open_stack.push(i),
567                ')' | ']' => {
568                    if let Some(opener) = open_stack.pop()
569                        && opener != i
570                    {
571                        spans.push((opener, i));
572                    }
573                }
574                _ => {}
575            }
576        }
577    }
578
579    // Phase 2: if ANY line in a span is kept, force-keep all lines in it.
580    // This handles both directions: opener->continuation and continuation->opener.
581    for &(start, end) in &spans {
582        let any_kept = (start..=end).any(|i| keep[i]);
583        if any_kept {
584            for (i, kept) in keep
585                .iter_mut()
586                .enumerate()
587                .skip(start)
588                .take(end - start + 1)
589            {
590                if !*kept {
591                    *kept = true;
592                    *used += tok_for(i);
593                    *kept_count += 1;
594                }
595            }
596        }
597    }
598}
599
600/// Budget-based compression to a target density (SDE principle: aim for a
601/// *target* information density instead of maximum compression).
602///
603/// Keeps the highest-entropy lines — in original order — until the BPE token
604/// budget `original_tokens * target` is exhausted. Deterministic: ties break
605/// on line index. `target` is clamped to [0.05, 1.0]; the top-scored line is
606/// always kept so output is never empty for non-empty input.
607pub fn entropy_compress_to_density(content: &str, target: f64) -> EntropyResult {
608    let target = target.clamp(0.05, 1.0);
609    let original_tokens = count_tokens(content);
610    if content.is_empty() || original_tokens == 0 {
611        return EntropyResult {
612            output: String::new(),
613            original_tokens,
614            compressed_tokens: 0,
615            techniques: vec![format!("density target={target:.2} (empty input)")],
616        };
617    }
618
619    #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
620    let budget = ((original_tokens as f64) * target).ceil() as usize;
621
622    let lines: Vec<&str> = content.lines().collect();
623    let mut scored: Vec<(usize, f64, usize)> = lines
624        .iter()
625        .enumerate()
626        .map(|(i, l)| {
627            let trimmed = l.trim();
628            // +1 approximates the newline token; keeps the per-line sum close
629            // to the whole-file count so the budget is meaningful.
630            let toks = count_tokens(trimmed).max(1);
631            (i, token_entropy(trimmed), toks)
632        })
633        .collect();
634    scored.sort_by(|a, b| {
635        b.1.partial_cmp(&a.1)
636            .unwrap_or(std::cmp::Ordering::Equal)
637            .then(a.0.cmp(&b.0))
638    });
639
640    let mut keep = vec![false; lines.len()];
641    let mut used = 0usize;
642    let mut kept_count = 0usize;
643    // The single most informative line is always kept, even if it alone
644    // exceeds the budget — a density target that drops the highest-signal
645    // line would be self-defeating. Everything else fills greedily.
646    if let Some(&(idx, _, toks)) = scored.first() {
647        keep[idx] = true;
648        used += toks;
649        kept_count += 1;
650    }
651    for &(idx, _h, toks) in scored.iter().skip(1) {
652        if used + toks > budget {
653            continue;
654        }
655        keep[idx] = true;
656        used += toks;
657        kept_count += 1;
658    }
659
660    // #798 Delimiter Balance Guard: when a kept line opens unclosed
661    // delimiters ( [ {, force-keep subsequent lines until the balance
662    // is restored. This prevents `logger.info(` from being kept while
663    // its arguments are dropped, leaving syntactically broken output.
664    delimiter_balance_force_keep(&lines, &scored, &mut keep, &mut used, &mut kept_count);
665
666    let mut out_lines: Vec<&str> = Vec::with_capacity(kept_count);
667    for (i, line) in lines.iter().enumerate() {
668        if keep[i] {
669            out_lines.push(line);
670        }
671    }
672    let output = out_lines.join("\n");
673    let compressed_tokens = count_tokens(&output);
674
675    let dropped = lines.len() - kept_count;
676    EntropyResult {
677        output,
678        original_tokens,
679        compressed_tokens,
680        techniques: vec![format!(
681            "density target={target:.2} budget={budget} tok, kept {kept_count}/{} lines (⊘ {dropped})",
682            lines.len()
683        )],
684    }
685}
686
687/// Per-line entropy statistics for a block of content.
688#[derive(Debug)]
689pub struct EntropyAnalysis {
690    pub avg_entropy: f64,
691    pub low_entropy_count: usize,
692    pub high_entropy_count: usize,
693    pub total_lines: usize,
694}
695
696/// Analyzes per-line BPE token entropy, counting low/high entropy lines.
697pub fn analyze_entropy(content: &str) -> EntropyAnalysis {
698    let lines: Vec<&str> = content.lines().collect();
699    let total = lines.len();
700    let mut sum = 0.0;
701    let mut low = 0;
702    let mut high = 0;
703    let mut counted = 0;
704
705    for line in &lines {
706        let trimmed = line.trim();
707        if trimmed.is_empty() {
708            continue;
709        }
710        let h = token_entropy(trimmed);
711        sum += h;
712        counted += 1;
713        if h < BPE_ENTROPY_THRESHOLD {
714            low += 1;
715        }
716        if h > 3.0 {
717            high += 1;
718        }
719    }
720
721    EntropyAnalysis {
722        avg_entropy: if counted > 0 {
723            sum / counted as f64
724        } else {
725            0.0
726        },
727        low_entropy_count: low,
728        high_entropy_count: high,
729        total_lines: total,
730    }
731}
732
733struct Block {
734    content: String,
735}
736
737fn extract_blocks(lines: &[&str]) -> Vec<Block> {
738    let mut blocks = Vec::new();
739    let mut current = String::new();
740
741    for line in lines {
742        let trimmed = line.trim();
743        if trimmed.is_empty() && !current.is_empty() {
744            blocks.push(Block {
745                content: current.clone(),
746            });
747            current.clear();
748        } else if !trimmed.is_empty() {
749            current.push_str(trimmed);
750            current.push('\n');
751        }
752    }
753
754    if !current.is_empty() {
755        blocks.push(Block { content: current });
756    }
757
758    blocks
759}
760
761fn find_pattern_groups(blocks: &[Block], threshold: f64) -> Vec<Vec<usize>> {
762    // Exact n-gram Jaccard, but with precomputed n-gram sets per block to avoid
763    // rebuilding allocations per pair. Includes a size-ratio impossibility check
764    // (max possible Jaccard is |A|/|B| for |A|<=|B|).
765    let sets: Vec<HashSet<Vec<String>>> = blocks.iter().map(|b| ngram_set(&b.content, 2)).collect();
766    let sizes: Vec<usize> = sets.iter().map(std::collections::HashSet::len).collect();
767
768    let mut groups: Vec<Vec<usize>> = Vec::new();
769    let mut assigned: HashSet<usize> = HashSet::new();
770
771    for i in 0..blocks.len() {
772        if assigned.contains(&i) {
773            continue;
774        }
775        let mut group = vec![i];
776        for j in (i + 1)..blocks.len() {
777            if assigned.contains(&j) {
778                continue;
779            }
780            let size_i = sizes[i];
781            let size_j = sizes[j];
782            let min_sz = size_i.min(size_j);
783            let max_sz = size_i.max(size_j);
784            if max_sz > 0 && (min_sz as f64) < (threshold * max_sz as f64) {
785                continue;
786            }
787            let inter = sets[i].intersection(&sets[j]).count();
788            let union = size_i + size_j - inter;
789            if union > 0 && (inter as f64 / union as f64) >= threshold {
790                group.push(j);
791                assigned.insert(j);
792            }
793        }
794        if group.len() > 1 {
795            assigned.insert(i);
796        }
797        groups.push(group);
798    }
799
800    groups
801}
802
803#[cfg(test)]
804mod tests {
805    use super::*;
806
807    #[test]
808    fn protect_force_keeps_lines_in_entropy() {
809        // A block of identical low-information lines that entropy + dedup would
810        // normally collapse to a single survivor (or drop entirely).
811        let mut content = String::new();
812        for _ in 0..15 {
813            content.push_str("boilerplate noise line\n");
814        }
815        let baseline =
816            entropy_compress_inner(&content, BPE_ENTROPY_THRESHOLD, 0.7, &[], false, &[]);
817        let protected = entropy_compress_inner(
818            &content,
819            BPE_ENTROPY_THRESHOLD,
820            0.7,
821            &[],
822            false,
823            &["boilerplate".to_string()],
824        );
825        let baseline_hits = baseline.output.matches("boilerplate").count();
826        let protected_hits = protected.output.matches("boilerplate").count();
827        // Every protected line survives verbatim — a hard keep over both the
828        // entropy threshold and the dedup pass.
829        assert_eq!(
830            protected_hits, 15,
831            "all protected lines must survive: {}",
832            protected.output
833        );
834        assert!(
835            protected_hits >= baseline_hits,
836            "protect must keep at least as many lines as the baseline"
837        );
838    }
839
840    #[test]
841    fn empty_force_keep_is_byte_identical() {
842        // The protect feature must not perturb the unprotected path (#498).
843        let content = "fn a() {}\n// note\nlet x = 1;\nlet x = 1;\n// note\n";
844        let a = entropy_compress_inner(content, BPE_ENTROPY_THRESHOLD, 0.7, &[], false, &[]);
845        let b = entropy_compress_deterministic(content);
846        assert_eq!(a.output, b.output);
847    }
848
849    #[test]
850    fn shannon_entropy_empty_is_zero() {
851        assert_eq!(shannon_entropy(""), 0.0);
852    }
853
854    #[test]
855    fn shannon_entropy_single_char() {
856        assert_eq!(shannon_entropy("aaaa"), 0.0);
857    }
858
859    #[test]
860    fn shannon_entropy_high_for_varied_text() {
861        let varied = "abcdefghijklmnopqrstuvwxyz0123456789";
862        let uniform = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
863        assert!(
864            shannon_entropy(varied) > shannon_entropy(uniform),
865            "varied text should have higher entropy"
866        );
867    }
868
869    #[test]
870    fn jaccard_identical_is_one() {
871        let sim = jaccard_similarity("hello world", "hello world");
872        assert!((sim - 1.0).abs() < f64::EPSILON);
873    }
874
875    #[test]
876    fn jaccard_disjoint_is_zero() {
877        let sim = jaccard_similarity("abc", "xyz");
878        assert_eq!(sim, 0.0);
879    }
880
881    #[test]
882    fn jaccard_partial_overlap() {
883        let sim = jaccard_similarity("hello world", "hello rust");
884        assert!(sim > 0.0 && sim < 1.0);
885    }
886
887    #[test]
888    fn entropy_compress_produces_output() {
889        let content = "fn main() {\n    println!(\"hello\");\n}\n\n// comment\n// another comment\n\nfn helper() {\n    let x = 42;\n}\n";
890        let result = entropy_compress(content);
891        assert!(!result.output.is_empty(), "should produce non-empty output");
892        assert!(result.compressed_tokens <= result.original_tokens);
893    }
894
895    #[test]
896    fn entropy_result_savings() {
897        let r = EntropyResult {
898            output: "short".to_string(),
899            original_tokens: 100,
900            compressed_tokens: 60,
901            techniques: vec!["test".to_string()],
902        };
903        assert!((r.savings_percent() - 40.0).abs() < 0.1);
904    }
905
906    #[test]
907    fn entropy_result_zero_original() {
908        let r = EntropyResult {
909            output: String::new(),
910            original_tokens: 0,
911            compressed_tokens: 0,
912            techniques: vec![],
913        };
914        assert_eq!(r.savings_percent(), 0.0);
915    }
916
917    #[test]
918    fn token_entropy_empty_is_zero() {
919        assert_eq!(token_entropy(""), 0.0);
920    }
921
922    #[test]
923    fn token_entropy_single_repeated_token() {
924        assert_eq!(token_entropy("}"), 0.0);
925    }
926
927    #[test]
928    fn token_entropy_higher_for_diverse_code() {
929        let diverse = "let result = compute_something(x, y, z);";
930        let repetitive = "aaaa aaaa aaaa aaaa";
931        assert!(
932            token_entropy(diverse) > token_entropy(repetitive),
933            "diverse code should have higher BPE token entropy"
934        );
935    }
936
937    #[test]
938    fn token_entropy_vs_char_entropy_differ() {
939        let code = "fn main() { println!(\"hello world\"); }";
940        let te = token_entropy(code);
941        let ce = shannon_entropy(code);
942        assert!(te != ce, "BPE and char entropy should differ for code");
943    }
944
945    #[test]
946    fn ngram_jaccard_preserves_order() {
947        let a = "a b c d";
948        let b = "d c b a";
949        let word_j = jaccard_similarity(a, b);
950        let ngram_j = ngram_jaccard(a, b, 2);
951        assert!(
952            ngram_j < word_j,
953            "reordered text should have lower bigram Jaccard ({ngram_j}) than word Jaccard ({word_j})"
954        );
955    }
956
957    #[test]
958    fn ngram_jaccard_identical_is_one() {
959        let text = "fn main() { println!(\"hello\"); }";
960        let j = ngram_jaccard(text, text, 2);
961        assert!((j - 1.0).abs() < f64::EPSILON);
962    }
963
964    #[test]
965    fn ngram_jaccard_disjoint_is_zero() {
966        let j = ngram_jaccard("alpha beta gamma", "delta epsilon zeta", 2);
967        assert_eq!(j, 0.0);
968    }
969
970    #[test]
971    fn minhash_approximates_jaccard() {
972        let a = "fn main() { let x = 1; let y = 2; let z = x + y; println!(z); }";
973        let b = "fn main() { let x = 1; let y = 2; let z = x + y; return z; }";
974        let exact = ngram_jaccard(a, b, 2);
975        let sig_a = minhash_signature(a, 2, 128);
976        let sig_b = minhash_signature(b, 2, 128);
977        let approx = minhash_similarity(&sig_a, &sig_b);
978        assert!(
979            (exact - approx).abs() < 0.2,
980            "minhash ({approx}) should approximate exact ({exact}) within 0.2"
981        );
982    }
983
984    #[test]
985    fn minhash_empty_text() {
986        let sig = minhash_signature("", 2, 64);
987        assert!(sig.iter().all(|&v| v == u64::MAX));
988    }
989
990    #[test]
991    fn kolmogorov_empty_is_one() {
992        assert_eq!(kolmogorov_proxy(""), 1.0);
993    }
994
995    #[test]
996    fn kolmogorov_repetitive_is_low() {
997        let repetitive = "aaa\n".repeat(1000);
998        let k = kolmogorov_proxy(&repetitive);
999        assert!(
1000            k < 0.1,
1001            "highly repetitive text should compress well: K={k}"
1002        );
1003    }
1004
1005    #[test]
1006    fn kolmogorov_diverse_is_higher() {
1007        let repetitive = "aaa\n".repeat(500);
1008        let diverse = (0..500)
1009            .map(|i| format!("line_{i}_unique_content_{}", i * 17 % 97))
1010            .collect::<Vec<_>>()
1011            .join("\n");
1012        assert!(
1013            kolmogorov_proxy(&diverse) > kolmogorov_proxy(&repetitive),
1014            "diverse content should have higher K than repetitive"
1015        );
1016    }
1017
1018    #[test]
1019    fn compressibility_class_repetitive_is_high() {
1020        let text = "use std::io;\n".repeat(200);
1021        assert_eq!(compressibility_class(&text), CompressibilityClass::High);
1022    }
1023
1024    #[test]
1025    fn kolmogorov_diverse_higher_than_repetitive() {
1026        let rep = "test\n".repeat(500);
1027        let diverse = (0..500)
1028            .map(|i| format!("unique_line_{i}_xk{}", i * 31 % 1000))
1029            .collect::<Vec<_>>()
1030            .join("\n");
1031        assert!(
1032            kolmogorov_proxy(&diverse) > kolmogorov_proxy(&rep),
1033            "diverse content should have higher K"
1034        );
1035    }
1036
1037    fn density_fixture() -> String {
1038        (0..120)
1039            .map(|i| {
1040                if i % 3 == 0 {
1041                    format!(
1042                        "fn compute_value_{i}(input: &str, flags: u32) -> Result<Output, Error> {{"
1043                    )
1044                } else if i % 3 == 1 {
1045                    format!("    let intermediate_{i} = transform(input, flags ^ {i});")
1046                } else {
1047                    "}".to_string()
1048                }
1049            })
1050            .collect::<Vec<_>>()
1051            .join("\n")
1052    }
1053
1054    #[test]
1055    fn density_respects_token_budget() {
1056        let content = density_fixture();
1057        let orig = count_tokens(&content);
1058        for target in [0.3, 0.5, 0.7] {
1059            let r = entropy_compress_to_density(&content, target);
1060            let actual = r.compressed_tokens as f64 / orig as f64;
1061            // Tolerance of 0.15: the delimiter balance guard (#798) may
1062            // force-keep call/index continuation lines beyond the budget.
1063            assert!(
1064                actual <= target + 0.15,
1065                "target {target}: actual density {actual:.2} exceeds budget"
1066            );
1067            assert!(!r.output.is_empty());
1068        }
1069    }
1070
1071    #[test]
1072    fn density_is_deterministic() {
1073        let content = density_fixture();
1074        let a = entropy_compress_to_density(&content, 0.4);
1075        let b = entropy_compress_to_density(&content, 0.4);
1076        assert_eq!(a.output, b.output);
1077        assert_eq!(a.compressed_tokens, b.compressed_tokens);
1078    }
1079
1080    #[test]
1081    fn density_target_one_keeps_everything() {
1082        let content = density_fixture();
1083        let r = entropy_compress_to_density(&content, 1.0);
1084        assert_eq!(r.output, content);
1085    }
1086
1087    #[test]
1088    fn density_clamps_out_of_range_target() {
1089        let content = density_fixture();
1090        let low = entropy_compress_to_density(&content, 0.0);
1091        assert!(!low.output.is_empty(), "clamped to 0.05, never empty");
1092        let high = entropy_compress_to_density(&content, 5.0);
1093        assert_eq!(high.output, content, "clamped to 1.0 keeps all");
1094    }
1095
1096    #[test]
1097    fn density_empty_input() {
1098        let r = entropy_compress_to_density("", 0.5);
1099        assert_eq!(r.compressed_tokens, 0);
1100        assert!(r.output.is_empty());
1101    }
1102
1103    #[test]
1104    fn density_delimiter_balance_guard() {
1105        // #798: when `logger.info(` is kept, its continuation lines must
1106        // also survive so the output is syntactically valid.
1107        let content = [
1108            "import logging",
1109            "logger = logging.getLogger(__name__)",
1110            "logger.info(",
1111            "    'Processing batch %d of %d',",
1112            "    batch_idx,",
1113            "    total_batches,",
1114            ")",
1115            "result = process(data)",
1116        ]
1117        .join("\n");
1118        let r = entropy_compress_to_density(&content, 0.5);
1119        // If `logger.info(` is kept, all lines through `)` must be too.
1120        if r.output.contains("logger.info(") {
1121            assert!(
1122                r.output.contains(')'),
1123                "delimiter guard must keep closing paren: {}",
1124                r.output
1125            );
1126            assert!(
1127                r.output.contains("batch_idx"),
1128                "delimiter guard must keep continuation args: {}",
1129                r.output
1130            );
1131        }
1132    }
1133
1134    #[test]
1135    fn density_delimiter_backward_propagation() {
1136        // #798 regression: when a high-entropy continuation line inside a
1137        // multi-line call is kept by the entropy scorer, the opener line
1138        // must also be force-kept (backward propagation through the span).
1139        //
1140        // Uses many low-entropy padding lines to force the budget to drop the
1141        // opener while the high-entropy format string survives on its own merit.
1142        let mut lines: Vec<&str> = Vec::new();
1143        lines.push("import logging");
1144        lines.push("logger = logging.getLogger(__name__)");
1145        lines.push("");
1146        // Low-entropy padding to push density budget down
1147        lines.extend(std::iter::repeat_n("    x = 1", 20));
1148        lines.push("    logger.info(");
1149        lines.push("        \"Processed item %s status=%s result=%s region=%s\",");
1150        lines.push("        item.id,");
1151        lines.push("        item.status,");
1152        lines.push("        result.summary,");
1153        lines.push("        region_name");
1154        lines.push("    )");
1155        // More padding
1156        lines.extend(std::iter::repeat_n("    y = 2", 10));
1157        let content = lines.join("\n");
1158        let r = entropy_compress_to_density(&content, 0.3);
1159        // The format string has high entropy and will be kept.
1160        // The span guard must then force-keep the opener + closer.
1161        if r.output.contains("Processed item") {
1162            assert!(
1163                r.output.contains("logger.info("),
1164                "backward propagation: opener must be kept when format string is kept.\nGot: {}",
1165                r.output
1166            );
1167            assert!(
1168                r.output.contains(')'),
1169                "backward propagation: closer must also be kept.\nGot: {}",
1170                r.output
1171            );
1172        }
1173        // Also verify: if logger.info( is kept, all args through ) are kept
1174        if r.output.contains("logger.info(") {
1175            assert!(
1176                r.output.contains("item.id"),
1177                "forward propagation: args must be kept when opener is kept.\nGot: {}",
1178                r.output
1179            );
1180        }
1181    }
1182
1183    #[test]
1184    fn density_prefers_high_entropy_lines() {
1185        let content =
1186            "}\n}\n}\nlet complex_result = compute_unique_hash(seed, nonce, payload);\n}\n}";
1187        let r = entropy_compress_to_density(content, 0.6);
1188        assert!(
1189            r.output.contains("compute_unique_hash"),
1190            "high-entropy line must survive: {}",
1191            r.output
1192        );
1193    }
1194}