lean_ctx/core/
information_bottleneck.rs1use super::entropy::normalized_token_entropy;
13use super::tokens::count_tokens;
14
15fn flush_omitted(out: &mut Vec<String>, run: &mut usize) {
16 if *run > 0 {
17 out.push(format!("// ... {} low-info lines omitted", *run));
18 *run = 0;
19 }
20}
21
22fn render_ib(lines: &[&str], scores: &[f64], threshold: f64) -> String {
23 debug_assert_eq!(lines.len(), scores.len());
24 let mut out = Vec::new();
25 let mut omit_run = 0usize;
26 for (&line, &score) in lines.iter().zip(scores.iter()) {
27 if score >= threshold {
28 flush_omitted(&mut out, &mut omit_run);
29 out.push(line.to_string());
30 } else {
31 omit_run += 1;
32 }
33 }
34 flush_omitted(&mut out, &mut omit_run);
35 out.join("\n")
36}
37
38pub fn compress_ib(text: &str, target_ratio: f64) -> String {
41 compress_ib_with_query(text, target_ratio, None)
42}
43
44fn relevance_terms(s: &str) -> Vec<String> {
46 s.to_lowercase()
47 .split(|c: char| !c.is_alphanumeric())
48 .filter(|t| t.len() >= 2)
49 .map(str::to_string)
50 .collect()
51}
52
53fn query_relevance_scores(lines: &[&str], query: &str) -> Option<Vec<f64>> {
56 let q_terms: std::collections::HashSet<String> = relevance_terms(query).into_iter().collect();
57 if q_terms.is_empty() {
58 return None;
59 }
60
61 let mut df: std::collections::HashMap<&str, usize> = std::collections::HashMap::new();
62 let line_terms: Vec<Vec<String>> = lines.iter().map(|l| relevance_terms(l)).collect();
63 for terms in &line_terms {
64 let unique: std::collections::HashSet<&str> = terms.iter().map(String::as_str).collect();
65 for t in unique {
66 if q_terms.contains(t) {
67 *df.entry(t).or_insert(0) += 1;
68 }
69 }
70 }
71 if df.is_empty() {
72 return None;
73 }
74
75 let n = lines.len() as f64;
76 let raw: Vec<f64> = line_terms
77 .iter()
78 .map(|terms| {
79 let mut seen: std::collections::HashSet<&str> = std::collections::HashSet::new();
80 terms
81 .iter()
82 .filter(|t| q_terms.contains(t.as_str()) && seen.insert(t.as_str()))
83 .map(|t| {
84 let d = *df.get(t.as_str()).unwrap_or(&1) as f64;
85 ((n + 1.0) / d).ln()
86 })
87 .sum::<f64>()
88 })
89 .collect();
90
91 let max = raw.iter().copied().fold(0.0_f64, f64::max);
92 if max <= 0.0 {
93 return None;
94 }
95 Some(raw.into_iter().map(|s| s / max).collect())
96}
97
98pub fn compress_ib_with_query(text: &str, target_ratio: f64, query: Option<&str>) -> String {
102 if text.is_empty() {
103 return String::new();
104 }
105 let input_tokens = count_tokens(text);
106 if input_tokens == 0 {
107 return text.to_string();
108 }
109 let ratio_target = target_ratio.clamp(0.02, 1.0);
110
111 let lines_vec: Vec<&str> = text.lines().collect();
112 let lines: &[&str] = &lines_vec;
113 let entropy_scores: Vec<f64> = lines
114 .iter()
115 .map(|ln| normalized_token_entropy(ln))
116 .collect();
117
118 let scores: Vec<f64> = match query.and_then(|q| query_relevance_scores(lines, q)) {
119 Some(relevance) => entropy_scores
120 .iter()
121 .zip(relevance.iter())
122 .map(|(e, r)| 0.5 * e + 0.5 * r)
123 .collect(),
124 None => entropy_scores,
125 };
126
127 let mut lo = 0.0_f64;
129 let mut hi = 1.0_f64;
130 let mut best = render_ib(lines, &scores, 0.0);
131 let mut best_diff = f64::INFINITY;
132
133 let mut consider = |thr: f64| {
134 let cand = render_ib(lines, &scores, thr);
135 let r = count_tokens(&cand) as f64 / input_tokens as f64;
136 let diff = (r - ratio_target).abs();
137 if diff < best_diff {
138 best_diff = diff;
139 best = cand;
140 }
141 };
142
143 for _ in 0..26 {
144 let mid = f64::midpoint(lo, hi);
145 let cand = render_ib(lines, &scores, mid);
146 let r = count_tokens(&cand) as f64 / input_tokens as f64;
147 consider(mid);
148 if r > ratio_target {
149 lo = mid;
150 } else {
151 hi = mid;
152 }
153 }
154
155 for thr in [0.0_f64, 1.0_f64, lo, hi, f64::midpoint(lo, hi)] {
156 consider(thr);
157 }
158
159 best
160}
161
162#[cfg(test)]
163mod tests {
164 use super::*;
165
166 #[test]
167 fn empty_and_ratio_one_keeps_content() {
168 assert_eq!(compress_ib("", 0.5), "");
169 let s = "fn main() {\n println!(\"hi\");\n}\n";
170 let full = compress_ib(s, 1.0);
171 assert!(full.contains("fn main"));
172 }
173
174 #[test]
175 fn strong_compression_drops_redundant_lines() {
176 let mut boring = String::new();
177 for _ in 0..30 {
178 boring.push_str("aaa bbb aaa bbb\n");
179 }
180 boring.push_str("unique_identifier_xyz_quartz\n");
181 let out = compress_ib(&boring, 0.15);
182 assert!(out.contains("low-info lines omitted"));
183 assert!(out.contains("unique_identifier_xyz_quartz"));
184 assert!(count_tokens(&out) < count_tokens(&boring));
185 }
186
187 #[test]
188 fn placeholder_counts_skipped_lines() {
189 let lines: Vec<String> = (0..5).map(|_| "x x x x".into()).collect();
190 let mut text = lines.join("\n");
191 text.push('\n');
192 text.push_str("serde Deserialize TraitBounds\n");
193 let out = compress_ib(&text, 0.25);
194 assert!(out.contains("low-info lines omitted"));
195 assert!(out.contains("serde"));
196 }
197
198 fn two_topic_fixture() -> String {
199 let mut s = String::new();
200 for _ in 0..10 {
201 s.push_str(
202 "fn parse_webhook_event(payload: Json) -> StripeEvent { decode(payload) }\n",
203 );
204 }
205 for _ in 0..10 {
206 s.push_str("fn render_dashboard_chart(data: Series) -> Svg { plot(data) }\n");
207 }
208 s
209 }
210
211 #[test]
212 fn different_queries_keep_different_lines() {
213 let text = two_topic_fixture();
214 let a = compress_ib_with_query(&text, 0.3, Some("stripe webhook event parsing"));
215 let b = compress_ib_with_query(&text, 0.3, Some("dashboard chart rendering svg"));
216 assert_ne!(a, b, "query must condition the kept lines");
217 assert!(a.contains("webhook"), "query-a keeps its topic: {a}");
218 assert!(b.contains("dashboard"), "query-b keeps its topic: {b}");
219 }
220
221 #[test]
222 fn no_query_is_byte_identical_to_entropy_only() {
223 let text = two_topic_fixture();
224 assert_eq!(
225 compress_ib_with_query(&text, 0.3, None),
226 compress_ib(&text, 0.3)
227 );
228 assert_eq!(
231 compress_ib_with_query(&text, 0.3, Some("zzz qqq vvv")),
232 compress_ib(&text, 0.3)
233 );
234 }
235
236 #[test]
237 fn compression_ratio_invariant_holds_with_query() {
238 let text = two_topic_fixture();
239 let out = compress_ib_with_query(&text, 0.3, Some("stripe webhook"));
240 let ratio = count_tokens(&out) as f64 / count_tokens(&text) as f64;
241 assert!(ratio <= 0.6, "ratio stays near target, got {ratio}");
245 assert!(out.contains("webhook") && !out.contains("dashboard"));
246 }
247}