Skip to main content

lean_ctx/core/terse/
scoring.rs

1//! Surprisal-based line scoring for deterministic compression.
2//!
3//! Each line receives an information density score based on:
4//! - Character-level entropy (Shannon)
5//! - Structural markers (paths, numbers, identifiers)
6//! - Repetition detection (overlap with previous lines)
7
8use std::collections::HashSet;
9
10/// Score for a single line — higher means more informative.
11#[derive(Debug, Clone)]
12pub struct LineScore {
13    pub line_idx: usize,
14    pub entropy: f32,
15    pub has_structural_marker: bool,
16    pub repetition_ratio: f32,
17    pub combined: f32,
18}
19
20const MAX_TRIGRAM_SET_SIZE: usize = 10_000;
21
22/// Scores all lines in the input text for information density.
23pub fn score_lines(text: &str) -> Vec<LineScore> {
24    let lines: Vec<&str> = text.lines().collect();
25    let mut seen_trigrams: HashSet<String> = HashSet::new();
26    let mut trigram_saturated = false;
27    let mut scores = Vec::with_capacity(lines.len());
28
29    for (idx, line) in lines.iter().enumerate() {
30        let trimmed = line.trim();
31
32        let entropy = char_entropy(trimmed);
33        let is_noise = is_encoded_blob(trimmed);
34        let has_marker = !is_noise && has_structural_marker(trimmed);
35        let rep_ratio = if trigram_saturated {
36            0.0
37        } else {
38            repetition_ratio(trimmed, &seen_trigrams)
39        };
40
41        if !trigram_saturated {
42            register_trigrams(trimmed, &mut seen_trigrams);
43            if seen_trigrams.len() >= MAX_TRIGRAM_SET_SIZE {
44                trigram_saturated = true;
45            }
46        }
47
48        let combined = compute_combined(entropy, has_marker, rep_ratio, is_noise);
49
50        scores.push(LineScore {
51            line_idx: idx,
52            entropy,
53            has_structural_marker: has_marker,
54            repetition_ratio: rep_ratio,
55            combined,
56        });
57    }
58
59    scores
60}
61
62fn char_entropy(line: &str) -> f32 {
63    if line.is_empty() {
64        return 0.0;
65    }
66    let mut freq = [0u32; 128];
67    let mut total = 0u32;
68    for b in line.bytes() {
69        if (b as usize) < 128 {
70            freq[b as usize] += 1;
71            total += 1;
72        }
73    }
74    if total == 0 {
75        return 0.0;
76    }
77    let mut ent = 0.0f32;
78    for &count in &freq {
79        if count > 0 {
80            let p = count as f32 / total as f32;
81            ent -= p * p.log2();
82        }
83    }
84    ent
85}
86
87fn has_structural_marker(line: &str) -> bool {
88    if line.contains('/') && (line.contains('.') || line.contains("src")) {
89        return true;
90    }
91    if line.chars().any(|c| c.is_ascii_digit()) {
92        return true;
93    }
94    if line.contains("error") || line.contains("Error") || line.contains("ERROR") {
95        return true;
96    }
97    if line.contains("warning") || line.contains("Warning") || line.contains("WARN") {
98        return true;
99    }
100    let long_idents = line
101        .split(|c: char| !c.is_alphanumeric() && c != '_')
102        .filter(|w| w.len() >= 6)
103        .count();
104    long_idents >= 2
105}
106
107fn repetition_ratio(line: &str, seen: &HashSet<String>) -> f32 {
108    let chars: Vec<char> = line.chars().collect();
109    if chars.len() < 9 {
110        return 0.0;
111    }
112    let total = chars.len().saturating_sub(2);
113    if total == 0 {
114        return 0.0;
115    }
116    let mut repeated = 0;
117    for i in 0..total {
118        let end = (i + 3).min(chars.len());
119        let trigram: String = chars[i..end].iter().collect();
120        if seen.contains(&trigram) {
121            repeated += 1;
122        }
123    }
124    repeated as f32 / total as f32
125}
126
127fn register_trigrams(line: &str, seen: &mut HashSet<String>) {
128    let chars: Vec<char> = line.chars().collect();
129    if chars.len() < 3 {
130        return;
131    }
132    for i in 0..chars.len().saturating_sub(2) {
133        let end = (i + 3).min(chars.len());
134        let trigram: String = chars[i..end].iter().collect();
135        seen.insert(trigram);
136    }
137}
138
139fn compute_combined(entropy: f32, has_marker: bool, rep_ratio: f32, is_noise: bool) -> f32 {
140    if is_noise {
141        return 0.0;
142    }
143    let marker_bonus = if has_marker { 0.3 } else { 0.0 };
144    let rep_penalty = rep_ratio * 0.5;
145    (entropy + marker_bonus - rep_penalty).max(0.0)
146}
147
148/// True when `line` contains an encoded blob (base64 or hex) — either as the
149/// whole line or as one whitespace-delimited token in a `label: <blob>`
150/// shaped line (`trace id: <hex>`, `commit <sha>`, `session token: <b64>`,
151/// all common in real logs) — rather than prose/code. High Shannon entropy
152/// but zero semantic content, so it must not be scored as information-dense.
153fn is_encoded_blob(line: &str) -> bool {
154    line.split_whitespace().any(is_blob_token)
155}
156
157/// True when a single whitespace-delimited token looks like a random,
158/// non-prose blob (base64 or hex) rather than an English word or code
159/// identifier. `pub(super)` so `quality::check` can also treat a long blob
160/// as a must-preserve identifier — a payload-shaped blob (e.g. the resolved
161/// hash from `git rev-parse HEAD`) must still trip the quality gate if
162/// dropped, even though it has no alphabetic characters for the ordinary
163/// identifier check to key on.
164pub(super) fn is_blob_token(token: &str) -> bool {
165    const MIN_BLOB_LEN: usize = 24;
166
167    if token.len() < MIN_BLOB_LEN {
168        return false;
169    }
170
171    let is_hex = token.chars().all(|c| c.is_ascii_hexdigit());
172
173    // Base64 padding/symbols are an unambiguous signal on their own. Without
174    // them, require the digit+upper+lower mix typical of random tokens so a
175    // long plain identifier (all-lowercase or camelCase, no digits) doesn't
176    // get misclassified as noise.
177    let has_b64_symbol = token.contains('+') || token.contains('/') || token.contains('=');
178    let charset_ok = token
179        .chars()
180        .all(|c| c.is_ascii_alphanumeric() || c == '+' || c == '/' || c == '=');
181    let has_digit = token.chars().any(|c| c.is_ascii_digit());
182    let has_upper = token.chars().any(|c| c.is_ascii_uppercase());
183    let has_lower = token.chars().any(|c| c.is_ascii_lowercase());
184    let is_base64 = charset_ok && (has_b64_symbol || (has_digit && has_upper && has_lower));
185
186    is_hex || is_base64
187}
188
189#[cfg(test)]
190mod tests {
191    use super::*;
192
193    #[test]
194    fn empty_line_zero_entropy() {
195        assert_eq!(char_entropy(""), 0.0);
196    }
197
198    #[test]
199    fn uniform_string_low_entropy() {
200        let e = char_entropy("aaaaaaaaaa");
201        assert!(e < 0.01, "uniform string should have ~0 entropy, got {e}");
202    }
203
204    #[test]
205    fn mixed_string_higher_entropy() {
206        let low = char_entropy("aaaaaaaaaa");
207        let high = char_entropy("abcdefghij");
208        assert!(high > low, "mixed > uniform entropy");
209    }
210
211    #[test]
212    fn structural_marker_path() {
213        assert!(has_structural_marker("src/core/config.rs"));
214    }
215
216    #[test]
217    fn structural_marker_error() {
218        assert!(has_structural_marker("error[E0308]: mismatched types"));
219    }
220
221    #[test]
222    fn structural_marker_missing() {
223        assert!(!has_structural_marker("this is a simple line"));
224    }
225
226    #[test]
227    fn encoded_blob_detected_as_noise() {
228        assert!(is_encoded_blob(
229            "MTIzNDU2Nzg5MGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6MDk4NzY1NDMyMQ=="
230        ));
231        assert!(is_encoded_blob(
232            "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08"
233        ));
234        assert!(!is_encoded_blob("src/core/config.rs"));
235        assert!(!is_encoded_blob("this is a simple line with words"));
236    }
237
238    #[test]
239    fn prefixed_blob_is_still_detected_as_noise() {
240        // Real logs almost always label the blob rather than emit it bare
241        // (`trace id: <hex>`, `commit <sha>`, `session token: <b64>`). Built
242        // at runtime (not a literal) so a fake test token isn't itself
243        // mistaken for a real secret by tooling.
244        let hex64: String = "9f86d0".repeat(11);
245        let b64_padded: String = format!("{}==", "aZ9".repeat(8));
246
247        assert!(is_encoded_blob(&format!("trace id: {hex64}")));
248        assert!(is_encoded_blob(&format!(
249            "build session token: {b64_padded}"
250        )));
251        assert!(is_encoded_blob(&format!("commit {hex64}")));
252    }
253
254    #[test]
255    fn prefixed_real_content_is_not_noise() {
256        assert!(!is_encoded_blob(
257            "error in module ConfigurationManagerFactory during init"
258        ));
259    }
260
261    #[test]
262    fn long_camel_case_identifier_is_not_noise() {
263        assert!(!is_encoded_blob(
264            "configureApplicationRuntimeEnvironmentSettings"
265        ));
266        assert!(!is_encoded_blob(
267            "configure_premium_feature_flags_for_tenant"
268        ));
269    }
270
271    #[test]
272    fn encoded_blob_scores_lower_than_real_error_line() {
273        let text = "error: connection refused at host during handshake attempt\nMTIzNDU2Nzg5MGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6MDk4NzY1NDMyMQ==";
274        let scores = score_lines(text);
275        assert!(
276            scores[0].combined > scores[1].combined,
277            "real error line should score above encoded blob noise: {} vs {}",
278            scores[0].combined,
279            scores[1].combined
280        );
281    }
282
283    #[test]
284    fn score_lines_returns_all_lines() {
285        let text = "line one\nline two\nline three";
286        let scores = score_lines(text);
287        assert_eq!(scores.len(), 3);
288    }
289
290    #[test]
291    fn repetitive_lines_get_lower_score() {
292        let text = "exactly the same line repeated here\nexactly the same line repeated here\nunique content with different words";
293        let scores = score_lines(text);
294        assert!(
295            scores[2].combined >= scores[1].combined,
296            "unique line should score >= repeated: {} vs {}",
297            scores[2].combined,
298            scores[1].combined
299        );
300    }
301}