Skip to main content

sqz_engine/
entropy_truncator.rs

1/// Adaptive Entropy-Weighted Truncation (Rate-Distortion Theory).
2///
3/// Instead of using fixed thresholds for truncate_strings and collapse_arrays,
4/// this module computes per-segment entropy and keeps segments above the
5/// median entropy while dropping segments below it. This preserves the
6/// information-dense parts and drops the redundant tail.
7///
8/// Based on rate-distortion theory: the optimal cutoff depends on the
9/// information density of the content being truncated, not a fixed length.
10
11use crate::error::Result;
12
13/// Configuration for entropy-weighted truncation.
14#[derive(Debug, Clone)]
15pub struct EntropyTruncConfig {
16    /// Minimum entropy (bits) below which a segment is considered low-information.
17    /// Segments below this are candidates for removal.
18    /// Default: computed dynamically as median of all segments.
19    pub min_entropy_override: Option<f64>,
20    /// Maximum number of low-entropy segments to keep (even if below threshold).
21    /// Ensures we don't drop everything.
22    /// Default: 2
23    pub min_kept_segments: usize,
24    /// Minimum segment length (chars) to analyze. Shorter segments are always kept.
25    /// Default: 20
26    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/// A segment with its computed entropy.
40#[derive(Debug, Clone)]
41pub struct ScoredSegment {
42    /// The segment text.
43    pub text: String,
44    /// Shannon entropy in bits.
45    pub entropy: f64,
46    /// Whether this segment was kept in the output.
47    pub kept: bool,
48}
49
50/// Result of entropy-weighted truncation.
51#[derive(Debug, Clone)]
52pub struct EntropyTruncResult {
53    /// The truncated output.
54    pub text: String,
55    /// Segments with their scores and keep/drop decisions.
56    pub segments: Vec<ScoredSegment>,
57    /// Number of segments dropped.
58    pub segments_dropped: usize,
59    /// Entropy threshold used.
60    pub threshold: f64,
61}
62
63/// Entropy-weighted truncator.
64pub 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    /// Truncate a string by keeping high-entropy (information-dense) segments
78    /// and dropping low-entropy (redundant) segments.
79    ///
80    /// Segments are split by double-newline (paragraph boundaries) or by
81    /// a fixed window if no paragraph breaks exist.
82    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        // Compute entropy for each segment
102        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        // Determine threshold: use override or compute median
115        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        // Mark segments below threshold for dropping
122        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        // Ensure we keep at least min_kept_segments
138        if kept_count < self.config.min_kept_segments {
139            // Re-add the highest-entropy dropped segments
140            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        // Build output
160        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            // Identifier factsheet: exact identifiers living in the dropped
172            // segments (SHAs, UUIDs, ticket codes, versions) ride along so
173            // lossy truncation can never silently lose a hash the agent
174            // needs to copy-paste. Deterministic and budget-capped.
175            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    /// Truncate a JSON array by keeping high-entropy elements and dropping
196    /// low-entropy (redundant) ones.
197    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        // Serialize each element and compute entropy
207        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        // Compute median entropy
217        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        // Keep elements above threshold, plus at least min_kept_segments
222        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        // Always keep at least min_kept_segments
234        while kept.len() < self.config.min_kept_segments && dropped > 0 {
235            // Add back highest-entropy dropped elements
236            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/// Result of entropy-weighted array truncation.
270#[derive(Debug, Clone)]
271pub struct EntropyTruncArrayResult {
272    /// The kept elements (plus optional summary element).
273    pub kept: Vec<serde_json::Value>,
274    /// Number of elements dropped.
275    pub dropped_count: usize,
276    /// Entropy threshold used.
277    pub threshold: f64,
278}
279
280// ── Helpers ───────────────────────────────────────────────────────────────────
281
282/// Compute Shannon entropy of a string in bits.
283/// Extract exact identifiers from `dropped` that do not also appear in
284/// `kept`: hex ids/SHAs (7+ chars containing a digit), UUIDs, ticket codes
285/// (ABC-123), and semantic versions. Capped at 16 entries / 256 chars total
286/// so the factsheet can't become its own bloat. Order follows first
287/// appearance, deduplicated.
288fn 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 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
360/// Compute the median of a sorted slice.
361fn 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
373/// Split text into segments at paragraph boundaries (double newlines).
374/// Falls back to fixed-size windows if no paragraph breaks exist.
375fn split_segments(text: &str) -> Vec<String> {
376    // Try splitting on double newlines first
377    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    // Fall back to splitting on single newlines into groups of ~10 lines
388    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// ── Tests ─────────────────────────────────────────────────────────────────────
401
402#[cfg(test)]
403mod tests {
404    use super::*;
405
406    #[test]
407    fn factsheet_preserves_ids_from_dropped_segments() {
408        let truncator = EntropyTruncator::new();
409        // Low-entropy segments carrying identifiers, high-entropy segments
410        // without them. The low ones get dropped; their ids must survive
411        // in the factsheet line.
412        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        // An id present in a KEPT segment must not be repeated in the sheet.
432        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        // All same character → entropy = 0
465        assert_eq!(shannon_entropy("aaaa"), 0.0);
466    }
467
468    #[test]
469    fn test_shannon_entropy_varied() {
470        // More varied text → higher entropy
471        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        // Create text with varied and repetitive paragraphs
503        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        // The varied paragraphs should be kept, repetitive may be dropped
509        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        // Add varied elements (high entropy — many different characters)
529        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        // Add many identical simple elements (low entropy — very repetitive)
532        for _ in 0..8 {
533            elements.push(serde_json::json!({"x": 1}));
534        }
535
536        let result = trunc.truncate_array(&elements).unwrap();
537        // Should keep the varied elements; may drop some repetitive ones
538        // At minimum, the result should not be larger than the input
539        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    // ── Property tests ────────────────────────────────────────────────────────
570
571    use proptest::prelude::*;
572
573    proptest! {
574        /// Truncation never produces empty output from non-empty input.
575        #[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        /// Shannon entropy is always non-negative.
588        #[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        /// Segments dropped count matches the actual difference.
597        #[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}