1use crate::error::Result;
12
13#[derive(Debug, Clone)]
15pub struct EntropyTruncConfig {
16 pub min_entropy_override: Option<f64>,
20 pub min_kept_segments: usize,
24 pub min_segment_length: usize,
27}
28
29impl Default for EntropyTruncConfig {
30 fn default() -> Self {
31 Self {
32 min_entropy_override: None,
33 min_kept_segments: 2,
34 min_segment_length: 20,
35 }
36 }
37}
38
39#[derive(Debug, Clone)]
41pub struct ScoredSegment {
42 pub text: String,
44 pub entropy: f64,
46 pub kept: bool,
48}
49
50#[derive(Debug, Clone)]
52pub struct EntropyTruncResult {
53 pub text: String,
55 pub segments: Vec<ScoredSegment>,
57 pub segments_dropped: usize,
59 pub threshold: f64,
61}
62
63pub struct EntropyTruncator {
65 config: EntropyTruncConfig,
66}
67
68impl EntropyTruncator {
69 pub fn new() -> Self {
70 Self::with_config(EntropyTruncConfig::default())
71 }
72
73 pub fn with_config(config: EntropyTruncConfig) -> Self {
74 Self { config }
75 }
76
77 pub fn truncate_string(&self, text: &str) -> Result<EntropyTruncResult> {
83 let segments = split_segments(text);
84
85 if segments.len() <= 1 {
86 return Ok(EntropyTruncResult {
87 text: text.to_string(),
88 segments: segments
89 .into_iter()
90 .map(|s| ScoredSegment {
91 entropy: shannon_entropy(&s),
92 text: s,
93 kept: true,
94 })
95 .collect(),
96 segments_dropped: 0,
97 threshold: 0.0,
98 });
99 }
100
101 let mut scored: Vec<ScoredSegment> = segments
103 .into_iter()
104 .map(|s| {
105 let entropy = shannon_entropy(&s);
106 ScoredSegment {
107 text: s,
108 entropy,
109 kept: true,
110 }
111 })
112 .collect();
113
114 let threshold = self.config.min_entropy_override.unwrap_or_else(|| {
116 let mut entropies: Vec<f64> = scored.iter().map(|s| s.entropy).collect();
117 entropies.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
118 median(&entropies)
119 });
120
121 let mut kept_count = 0usize;
123 let total = scored.len();
124
125 for seg in &mut scored {
126 if seg.text.len() < self.config.min_segment_length {
127 seg.kept = true;
128 kept_count += 1;
129 } else if seg.entropy >= threshold {
130 seg.kept = true;
131 kept_count += 1;
132 } else {
133 seg.kept = false;
134 }
135 }
136
137 if kept_count < self.config.min_kept_segments {
139 let mut dropped_indices: Vec<(usize, f64)> = scored
141 .iter()
142 .enumerate()
143 .filter(|(_, s)| !s.kept)
144 .map(|(i, s)| (i, s.entropy))
145 .collect();
146 dropped_indices.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));
147
148 for (idx, _) in dropped_indices {
149 if kept_count >= self.config.min_kept_segments {
150 break;
151 }
152 scored[idx].kept = true;
153 kept_count += 1;
154 }
155 }
156
157 let segments_dropped = total - kept_count;
158
159 let kept_texts: Vec<&str> = scored
161 .iter()
162 .filter(|s| s.kept)
163 .map(|s| s.text.as_str())
164 .collect();
165
166 let mut text = kept_texts.join("\n\n");
167 if segments_dropped > 0 {
168 text.push_str(&format!(
169 "\n[{segments_dropped} low-information segments omitted]"
170 ));
171 let dropped_text: Vec<&str> = scored
176 .iter()
177 .filter(|s| !s.kept)
178 .map(|s| s.text.as_str())
179 .collect();
180 let kept_joined = kept_texts.join("\n");
181 let ids = extract_identifiers(&dropped_text.join("\n"), &kept_joined);
182 if !ids.is_empty() {
183 text.push_str(&format!("\n[ids in omitted segments: {}]", ids.join(", ")));
184 }
185 }
186
187 Ok(EntropyTruncResult {
188 text,
189 segments: scored,
190 segments_dropped,
191 threshold,
192 })
193 }
194
195 pub fn truncate_array(&self, elements: &[serde_json::Value]) -> Result<EntropyTruncArrayResult> {
198 if elements.len() <= 2 {
199 return Ok(EntropyTruncArrayResult {
200 kept: elements.to_vec(),
201 dropped_count: 0,
202 threshold: 0.0,
203 });
204 }
205
206 let scored: Vec<(serde_json::Value, f64)> = elements
208 .iter()
209 .map(|e| {
210 let s = serde_json::to_string(e).unwrap_or_default();
211 let entropy = shannon_entropy(&s);
212 (e.clone(), entropy)
213 })
214 .collect();
215
216 let mut entropies: Vec<f64> = scored.iter().map(|(_, e)| *e).collect();
218 entropies.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
219 let threshold = self.config.min_entropy_override.unwrap_or_else(|| median(&entropies));
220
221 let mut kept = Vec::new();
223 let mut dropped = 0usize;
224
225 for (elem, entropy) in &scored {
226 if *entropy >= threshold || kept.len() < self.config.min_kept_segments {
227 kept.push(elem.clone());
228 } else {
229 dropped += 1;
230 }
231 }
232
233 while kept.len() < self.config.min_kept_segments && dropped > 0 {
235 let mut remaining: Vec<&(serde_json::Value, f64)> = scored
237 .iter()
238 .filter(|(e, _)| !kept.contains(e))
239 .collect();
240 remaining.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));
241 if let Some((elem, _)) = remaining.first() {
242 kept.push((*elem).clone());
243 dropped -= 1;
244 } else {
245 break;
246 }
247 }
248
249 if dropped > 0 {
250 kept.push(serde_json::Value::String(format!(
251 "[{dropped} low-information elements omitted]"
252 )));
253 }
254
255 Ok(EntropyTruncArrayResult {
256 kept,
257 dropped_count: dropped,
258 threshold,
259 })
260 }
261}
262
263impl Default for EntropyTruncator {
264 fn default() -> Self {
265 Self::new()
266 }
267}
268
269#[derive(Debug, Clone)]
271pub struct EntropyTruncArrayResult {
272 pub kept: Vec<serde_json::Value>,
274 pub dropped_count: usize,
276 pub threshold: f64,
278}
279
280fn extract_identifiers(dropped: &str, kept: &str) -> Vec<String> {
289 const MAX_IDS: usize = 16;
290 const MAX_CHARS: usize = 256;
291
292 let mut out: Vec<String> = Vec::new();
293 let mut budget = 0usize;
294 let mut push = |candidate: &str, out: &mut Vec<String>, budget: &mut usize| {
295 if out.len() >= MAX_IDS || *budget + candidate.len() > MAX_CHARS {
296 return;
297 }
298 if kept.contains(candidate) || out.iter().any(|s| s == candidate) {
299 return;
300 }
301 *budget += candidate.len() + 2;
302 out.push(candidate.to_string());
303 };
304
305 for token in dropped.split(|c: char| c.is_whitespace() || "()[]{}<>\"'`,;".contains(c)) {
306 let token = token.trim_end_matches(|c: char| c == '.' || c == ':');
307 if token.len() < 5 || token.len() > 64 {
308 continue;
309 }
310 let is_hex_id = token.len() >= 7
311 && token.chars().all(|c| c.is_ascii_hexdigit())
312 && token.chars().any(|c| c.is_ascii_digit())
313 && token.chars().any(|c| c.is_ascii_alphabetic());
314 let is_uuid = token.len() == 36
315 && token
316 .chars()
317 .all(|c| c.is_ascii_hexdigit() || c == '-')
318 && token.matches('-').count() == 4;
319 let is_ticket = token.contains('-')
320 && token.split('-').count() == 2
321 && token.split('-').next().is_some_and(|p| {
322 (2..=10).contains(&p.len()) && p.chars().all(|c| c.is_ascii_uppercase())
323 })
324 && token.split('-').nth(1).is_some_and(|p| {
325 !p.is_empty() && p.chars().all(|c| c.is_ascii_digit())
326 });
327 let is_version = token.starts_with('v')
328 && token[1..].split('.').count() >= 2
329 && token[1..].split('.').all(|p| !p.is_empty() && p.chars().all(|c| c.is_ascii_digit()));
330
331 if is_hex_id || is_uuid || is_ticket || is_version {
332 push(token, &mut out, &mut budget);
333 }
334 }
335 out
336}
337
338fn shannon_entropy(text: &str) -> f64 {
339 if text.is_empty() {
340 return 0.0;
341 }
342
343 let mut freq = [0u32; 256];
344 let len = text.len() as f64;
345
346 for &byte in text.as_bytes() {
347 freq[byte as usize] += 1;
348 }
349
350 let mut entropy = 0.0f64;
351 for &count in &freq {
352 if count > 0 {
353 let p = count as f64 / len;
354 entropy -= p * p.log2();
355 }
356 }
357 entropy
358}
359
360fn median(sorted: &[f64]) -> f64 {
362 if sorted.is_empty() {
363 return 0.0;
364 }
365 let mid = sorted.len() / 2;
366 if sorted.len() % 2 == 0 {
367 (sorted[mid - 1] + sorted[mid]) / 2.0
368 } else {
369 sorted[mid]
370 }
371}
372
373fn split_segments(text: &str) -> Vec<String> {
376 let segments: Vec<String> = text
378 .split("\n\n")
379 .map(|s| s.to_string())
380 .filter(|s| !s.trim().is_empty())
381 .collect();
382
383 if segments.len() > 1 {
384 return segments;
385 }
386
387 let lines: Vec<&str> = text.lines().collect();
389 if lines.len() <= 10 {
390 return vec![text.to_string()];
391 }
392
393 let chunk_size = 10;
394 lines
395 .chunks(chunk_size)
396 .map(|chunk| chunk.join("\n"))
397 .collect()
398}
399
400#[cfg(test)]
403mod tests {
404 use super::*;
405
406 #[test]
407 fn factsheet_preserves_ids_from_dropped_segments() {
408 let truncator = EntropyTruncator::new();
409 let low_a = format!("{} deadbeef42 PROJ-1482", "aaaaaaaaaa ".repeat(8));
413 let low_b = format!(
414 "{} 550e8400-e29b-41d4-a716-446655440000 v1.4.0",
415 "bbbbbbbbbb ".repeat(8)
416 );
417 let high_a = "The quick brown fox jumps over the lazy dog by silver rivers today.";
418 let high_b = "Zephyrs quickly vex jumbled gnomes while quartz dwarfs mix pyjamas.";
419 let input = format!("{low_a}\n\n{high_a}\n\n{low_b}\n\n{high_b}");
420
421 let result = truncator.truncate_string(&input).unwrap();
422 assert!(result.segments_dropped > 0, "fixture must drop segments");
423 assert!(result.text.contains("[ids in omitted segments:"), "{}", result.text);
424 for id in ["deadbeef42", "PROJ-1482", "550e8400-e29b-41d4-a716-446655440000", "v1.4.0"] {
425 assert!(result.text.contains(id), "lost id {id}: {}", result.text);
426 }
427 }
428
429 #[test]
430 fn factsheet_skips_ids_already_kept() {
431 let dropped = "deadbeef42 and cafe1234567";
433 let kept = "deadbeef42 remains visible";
434 let ids = extract_identifiers(dropped, kept);
435 assert!(!ids.contains(&"deadbeef42".to_string()));
436 assert!(ids.contains(&"cafe1234567".to_string()));
437 }
438
439 #[test]
440 fn factsheet_is_budget_capped() {
441 let dropped: String = (0..50)
442 .map(|i| format!("PROJ-{}{:04}", 1000 + i, i))
443 .collect::<Vec<_>>()
444 .join(" ");
445 let ids = extract_identifiers(&dropped, "");
446 assert!(ids.len() <= 16, "cap at 16 facts, got {}", ids.len());
447 let total: usize = ids.iter().map(|s| s.len() + 2).sum();
448 assert!(total <= 256 + 16, "char budget exceeded: {total}");
449 }
450
451 #[test]
452 fn factsheet_ignores_plain_words_and_numbers() {
453 let ids = extract_identifiers("building the module quickly 123456789 finished", "");
454 assert!(ids.is_empty(), "plain words/ints are not ids: {ids:?}");
455 }
456
457 #[test]
458 fn test_shannon_entropy_empty() {
459 assert_eq!(shannon_entropy(""), 0.0);
460 }
461
462 #[test]
463 fn test_shannon_entropy_single_char() {
464 assert_eq!(shannon_entropy("aaaa"), 0.0);
466 }
467
468 #[test]
469 fn test_shannon_entropy_varied() {
470 let low = shannon_entropy("aaaa");
472 let high = shannon_entropy("abcdefghijklmnop");
473 assert!(high > low);
474 }
475
476 #[test]
477 fn test_median_empty() {
478 assert_eq!(median(&[]), 0.0);
479 }
480
481 #[test]
482 fn test_median_odd() {
483 assert_eq!(median(&[1.0, 2.0, 3.0]), 2.0);
484 }
485
486 #[test]
487 fn test_median_even() {
488 assert_eq!(median(&[1.0, 2.0, 3.0, 4.0]), 2.5);
489 }
490
491 #[test]
492 fn test_truncate_string_short_input() {
493 let trunc = EntropyTruncator::new();
494 let result = trunc.truncate_string("hello world").unwrap();
495 assert_eq!(result.text, "hello world");
496 assert_eq!(result.segments_dropped, 0);
497 }
498
499 #[test]
500 fn test_truncate_string_with_paragraphs() {
501 let trunc = EntropyTruncator::new();
502 let varied = "The quick brown fox jumps over the lazy dog with many different words and characters.";
504 let repetitive = "aaa aaa aaa aaa aaa aaa aaa aaa aaa aaa aaa aaa aaa aaa aaa aaa aaa aaa aaa aaa";
505 let text = format!("{varied}\n\n{repetitive}\n\n{varied}");
506
507 let result = trunc.truncate_string(&text).unwrap();
508 assert!(result.text.contains("quick brown fox"));
510 }
511
512 #[test]
513 fn test_truncate_array_short() {
514 let trunc = EntropyTruncator::new();
515 let elements = vec![
516 serde_json::json!(1),
517 serde_json::json!(2),
518 ];
519 let result = trunc.truncate_array(&elements).unwrap();
520 assert_eq!(result.kept.len(), 2);
521 assert_eq!(result.dropped_count, 0);
522 }
523
524 #[test]
525 fn test_truncate_array_with_redundant_elements() {
526 let trunc = EntropyTruncator::new();
527 let mut elements = Vec::new();
528 elements.push(serde_json::json!({"name": "Alice Johnson", "role": "senior software engineer", "department": "platform infrastructure", "id": 12345}));
530 elements.push(serde_json::json!({"name": "Bob Williams", "role": "product designer", "department": "user experience research", "id": 67890}));
531 for _ in 0..8 {
533 elements.push(serde_json::json!({"x": 1}));
534 }
535
536 let result = trunc.truncate_array(&elements).unwrap();
537 assert!(result.kept.len() <= elements.len());
540 }
541
542 #[test]
543 fn test_split_segments_paragraphs() {
544 let text = "para 1\n\npara 2\n\npara 3";
545 let segments = split_segments(text);
546 assert_eq!(segments.len(), 3);
547 }
548
549 #[test]
550 fn test_split_segments_no_paragraphs() {
551 let lines: Vec<String> = (0..25).map(|i| format!("line {i}")).collect();
552 let text = lines.join("\n");
553 let segments = split_segments(&text);
554 assert!(segments.len() > 1);
555 }
556
557 #[test]
558 fn test_custom_config() {
559 let config = EntropyTruncConfig {
560 min_entropy_override: Some(3.0),
561 min_kept_segments: 1,
562 min_segment_length: 5,
563 };
564 let trunc = EntropyTruncator::with_config(config);
565 let result = trunc.truncate_string("hello\n\nworld").unwrap();
566 assert!(!result.text.is_empty());
567 }
568
569 use proptest::prelude::*;
572
573 proptest! {
574 #[test]
576 fn prop_truncation_non_empty(
577 text in "[a-z ]{20,200}"
578 ) {
579 let trunc = EntropyTruncator::new();
580 let result = trunc.truncate_string(&text).unwrap();
581 prop_assert!(
582 !result.text.is_empty(),
583 "truncation should not produce empty output"
584 );
585 }
586
587 #[test]
589 fn prop_entropy_non_negative(
590 text in ".{1,100}"
591 ) {
592 let e = shannon_entropy(&text);
593 prop_assert!(e >= 0.0, "entropy should be non-negative, got {e}");
594 }
595
596 #[test]
598 fn prop_segments_accounting(
599 paragraphs in proptest::collection::vec("[a-z ]{10,50}", 3..=8usize),
600 ) {
601 let text = paragraphs.join("\n\n");
602 let trunc = EntropyTruncator::new();
603 let result = trunc.truncate_string(&text).unwrap();
604
605 let total = result.segments.len();
606 let kept = result.segments.iter().filter(|s| s.kept).count();
607 prop_assert_eq!(
608 result.segments_dropped, total - kept,
609 "segments_dropped should equal total - kept"
610 );
611 }
612 }
613}