Skip to main content

lean_ctx/proxy/
dedup.rs

1//! Session-scoped cache for deduplicating compressed tool results.
2
3use dashmap::DashMap;
4use rustc_hash::{FxHashSet, FxHasher};
5use serde_json::Value;
6use std::collections::HashMap;
7use std::hash::{Hash, Hasher};
8use std::sync::atomic::{AtomicU64, Ordering};
9use std::time::Instant;
10
11const MAX_ENTRIES: usize = 256;
12const TTL_SECS: u64 = 1800;
13const FIRST_LINE_MAX: usize = 120;
14const RECENT_TOOL_OUTPUTS: usize = 2;
15const HASH_PREFIX_LEN: usize = 12;
16const TOOL_RESULT_SEMANTIC_THRESHOLD: f32 = 0.80;
17
18/// BLAKE3 address for one immutable tool-output chunk.
19pub type Blake3Hash = blake3::Hash;
20
21/// Metadata retained for an immutable conversation chunk.
22#[derive(Debug, Clone, PartialEq, Eq)]
23pub struct DedupEntry {
24    pub first_seen_turn: u32,
25    pub occurrences: u32,
26    pub byte_size: usize,
27    pub summary: String,
28}
29
30/// Savings produced while normalizing one request's conversation history.
31#[derive(Debug, Clone, Copy, Default, PartialEq)]
32pub struct DedupStats {
33    pub chunks_seen: usize,
34    pub chunks_deduped: usize,
35    pub tokens_saved: usize,
36    pub semantic_deduped: u32,
37    pub semantic_tokens_saved: u64,
38    pub unique_chunks: usize,
39    pub unique_content_ratio: f32,
40}
41
42/// Default Jaccard similarity threshold for near-duplicate tool output.
43pub const DEFAULT_SEMANTIC_THRESHOLD: f32 = 0.70;
44
45/// A canonical chunk and the later chunks that can reference it.
46#[derive(Debug, Clone, PartialEq)]
47pub struct DedupGroup {
48    pub canonical_idx: usize,
49    pub duplicates: Vec<usize>,
50    pub similarity: f32,
51}
52
53/// Word-trigram semantic deduplicator for non-identical tool output.
54#[derive(Debug, Clone, Copy)]
55pub struct SemanticDedup {
56    threshold: f32,
57}
58
59impl Default for SemanticDedup {
60    fn default() -> Self {
61        Self::new(DEFAULT_SEMANTIC_THRESHOLD)
62    }
63}
64
65impl SemanticDedup {
66    #[must_use]
67    pub fn new(threshold: f32) -> Self {
68        Self {
69            threshold: normalize_threshold(threshold),
70        }
71    }
72
73    #[must_use]
74    pub const fn threshold(self) -> f32 {
75        self.threshold
76    }
77
78    #[must_use]
79    pub fn find_near_duplicates(&self, chunks: &[&str]) -> Vec<DedupGroup> {
80        find_near_duplicates(chunks, self.threshold)
81    }
82
83    fn dedup_messages(&self, messages: &mut [Value]) -> DedupStats {
84        let chunk_count = tool_output_count(messages);
85        let semantic_limit = chunk_count.saturating_sub(RECENT_TOOL_OUTPUTS);
86        let mut candidates = Vec::new();
87        let mut chunk_index = 0;
88
89        for message in messages.iter() {
90            visit_tool_output_contents_readonly(message, &mut |content| {
91                let is_recent = chunk_index >= semantic_limit;
92                chunk_index += 1;
93                if !is_recent && !is_dedup_stub(content) {
94                    candidates.push(content.to_owned());
95                }
96            });
97        }
98
99        let candidate_refs: Vec<_> = candidates.iter().map(String::as_str).collect();
100        let groups = self.find_near_duplicates(&candidate_refs);
101        if groups.is_empty() {
102            return DedupStats::default();
103        }
104
105        let mut replacements = HashMap::new();
106        for group in groups {
107            let canonical = &candidates[group.canonical_idx];
108            for duplicate_idx in group.duplicates {
109                let duplicate = &candidates[duplicate_idx];
110                replacements.insert(
111                    duplicate_idx,
112                    format!(
113                        "[Similar to turn {}, key differences: {}]",
114                        group.canonical_idx + 1,
115                        brief_diff(canonical, duplicate)
116                    ),
117                );
118            }
119        }
120
121        let mut stats = DedupStats::default();
122        let mut candidate_index = 0;
123        let mut message_index = 0;
124        for message in &mut *messages {
125            visit_tool_output_contents(message, &mut |content| {
126                let is_recent = message_index >= semantic_limit;
127                message_index += 1;
128                if is_recent || is_dedup_stub(content) {
129                    return;
130                }
131
132                let current_index = candidate_index;
133                candidate_index += 1;
134                let Some(replacement) = replacements.remove(&current_index) else {
135                    return;
136                };
137
138                let saved = estimate_tokens(content).saturating_sub(estimate_tokens(&replacement));
139                stats.chunks_deduped = stats.chunks_deduped.saturating_add(1);
140                stats.tokens_saved = stats.tokens_saved.saturating_add(saved);
141                stats.semantic_deduped = stats.semantic_deduped.saturating_add(1);
142                stats.semantic_tokens_saved =
143                    stats.semantic_tokens_saved.saturating_add(saved as u64);
144                *content = replacement;
145            });
146        }
147
148        stats
149    }
150}
151
152/// Calculate word-trigram Jaccard similarity from `0.0` to `1.0`.
153#[must_use]
154pub fn compute_similarity(a: &str, b: &str) -> f32 {
155    if a == b {
156        return 1.0;
157    }
158
159    let a_trigrams = word_trigrams(a);
160    let b_trigrams = word_trigrams(b);
161    if a_trigrams.is_empty() || b_trigrams.is_empty() {
162        return 0.0;
163    }
164
165    let shared = a_trigrams.intersection(&b_trigrams).count();
166    let total = a_trigrams.len() + b_trigrams.len() - shared;
167    shared as f32 / total as f32
168}
169
170/// Find disjoint groups of later chunks similar to their first occurrence.
171#[must_use]
172pub fn find_near_duplicates(chunks: &[&str], threshold: f32) -> Vec<DedupGroup> {
173    let threshold = normalize_threshold(threshold);
174    let mut assigned = vec![false; chunks.len()];
175    let mut groups = Vec::new();
176
177    for canonical_idx in 0..chunks.len() {
178        if assigned[canonical_idx] {
179            continue;
180        }
181
182        let mut duplicates = Vec::new();
183        let mut similarity_total = 0.0;
184        for duplicate_idx in canonical_idx + 1..chunks.len() {
185            if assigned[duplicate_idx] {
186                continue;
187            }
188
189            let similarity = compute_similarity(chunks[canonical_idx], chunks[duplicate_idx]);
190            if similarity >= threshold {
191                assigned[duplicate_idx] = true;
192                duplicates.push(duplicate_idx);
193                similarity_total += similarity;
194            }
195        }
196
197        if !duplicates.is_empty() {
198            groups.push(DedupGroup {
199                canonical_idx,
200                similarity: similarity_total / duplicates.len() as f32,
201                duplicates,
202            });
203        }
204    }
205
206    groups
207}
208
209/// Summarize line-level changes without embedding a full diff.
210#[must_use]
211pub fn brief_diff(canonical: &str, duplicate: &str) -> String {
212    let canonical_lines: Vec<_> = canonical.lines().collect();
213    let duplicate_lines: Vec<_> = duplicate.lines().collect();
214    let mut prefix = 0;
215    while prefix < canonical_lines.len()
216        && prefix < duplicate_lines.len()
217        && canonical_lines[prefix] == duplicate_lines[prefix]
218    {
219        prefix += 1;
220    }
221
222    let mut canonical_end = canonical_lines.len();
223    let mut duplicate_end = duplicate_lines.len();
224    while canonical_end > prefix
225        && duplicate_end > prefix
226        && canonical_lines[canonical_end - 1] == duplicate_lines[duplicate_end - 1]
227    {
228        canonical_end -= 1;
229        duplicate_end -= 1;
230    }
231
232    let canonical_changed = canonical_end - prefix;
233    let duplicate_changed = duplicate_end - prefix;
234    let comparable = canonical_changed.min(duplicate_changed);
235    let unchanged = canonical_lines[prefix..canonical_end]
236        .iter()
237        .zip(&duplicate_lines[prefix..duplicate_end])
238        .filter(|(canonical, duplicate)| canonical == duplicate)
239        .count();
240    let modified = comparable.saturating_sub(unchanged);
241    let removed = canonical_changed.saturating_sub(comparable);
242    let added = duplicate_changed.saturating_sub(comparable);
243    let mut changes = Vec::new();
244    if added > 0 {
245        changes.push(format!("+{added} {} added", line_label(added)));
246    }
247    if removed > 0 {
248        changes.push(format!("-{removed} {} removed", line_label(removed)));
249    }
250    if modified > 0 {
251        changes.push(format!("~{modified} {} modified", line_label(modified)));
252    }
253
254    truncate_summary(if changes.is_empty() {
255        "no line changes".to_owned()
256    } else {
257        changes.join(", ")
258    })
259}
260
261fn word_trigrams(text: &str) -> FxHashSet<[u64; 3]> {
262    const START: u64 = u64::MAX;
263    const END: u64 = u64::MAX - 1;
264
265    let words = normalized_word_hashes(text);
266    let mut trigrams = FxHashSet::default();
267    match words.as_slice() {
268        [] => {}
269        [word] => {
270            trigrams.insert([START, START, *word]);
271            trigrams.insert([START, *word, END]);
272            trigrams.insert([*word, END, END]);
273        }
274        [first, second] => {
275            trigrams.insert([START, *first, *second]);
276            trigrams.insert([*first, *second, END]);
277            trigrams.insert([*second, END, END]);
278        }
279        _ => {
280            for words in words.windows(3) {
281                trigrams.insert([words[0], words[1], words[2]]);
282            }
283        }
284    }
285    trigrams
286}
287
288fn normalized_word_hashes(text: &str) -> Vec<u64> {
289    let mut words = Vec::new();
290    let mut word = String::new();
291    for character in text.chars() {
292        if character.is_alphanumeric() {
293            word.extend(character.to_lowercase());
294        } else if !word.is_empty() {
295            words.push(fx_hash(&word));
296            word.clear();
297        }
298    }
299    if !word.is_empty() {
300        words.push(fx_hash(&word));
301    }
302    words
303}
304
305fn fx_hash(value: &str) -> u64 {
306    let mut hasher = FxHasher::default();
307    value.hash(&mut hasher);
308    hasher.finish()
309}
310
311fn normalize_threshold(threshold: f32) -> f32 {
312    if threshold.is_finite() {
313        threshold.clamp(0.0, 1.0)
314    } else {
315        DEFAULT_SEMANTIC_THRESHOLD
316    }
317}
318
319fn is_dedup_stub(content: &str) -> bool {
320    content.starts_with("[Content unchanged since turn ")
321        || content.starts_with("[unchanged since turn ")
322        || content.starts_with("[Similar to turn ")
323}
324
325fn line_label(count: usize) -> &'static str {
326    if count == 1 { "line" } else { "lines" }
327}
328
329fn truncate_summary(summary: String) -> String {
330    const MAX_SUMMARY_CHARS: usize = 50;
331    if summary.chars().count() <= MAX_SUMMARY_CHARS {
332        return summary;
333    }
334
335    let mut shortened: String = summary.chars().take(MAX_SUMMARY_CHARS - 1).collect();
336    shortened.push('…');
337    shortened
338}
339
340/// Session-scoped content-addressed history deduplicator.
341///
342/// Only exact BLAKE3 matches are eligible for the unchanged-content stub.
343/// Near matches are handled by [`SemanticDedup`] and always retain a concise
344/// key-difference summary.
345#[derive(Debug, Default)]
346pub struct ContentAddressedDedup {
347    entries: HashMap<Blake3Hash, DedupEntry>,
348    current_turn: u32,
349}
350
351impl ContentAddressedDedup {
352    pub fn new() -> Self {
353        Self::default()
354    }
355
356    /// Replace non-recent, repeated tool-output chunks with stable BLAKE3 refs.
357    pub fn dedup_messages(&mut self, messages: &mut Vec<Value>) -> DedupStats {
358        let chunk_count = tool_output_count(messages);
359        let mut stats = DedupStats {
360            chunks_seen: chunk_count,
361            ..DedupStats::default()
362        };
363        let mut chunk_index = 0;
364
365        for message in &mut *messages {
366            visit_tool_output_contents(message, &mut |content| {
367                let is_recent = chunk_index + RECENT_TOOL_OUTPUTS >= chunk_count;
368                chunk_index += 1;
369                if is_recent {
370                    self.remember(content);
371                    return;
372                }
373
374                if let Some(hash) = self.matching_hash(content)
375                    && let Some(entry) = self.entries.get_mut(&hash)
376                {
377                    entry.occurrences = entry.occurrences.saturating_add(1);
378                    let replacement = dedup_stub(entry.first_seen_turn, &hash);
379                    stats.tokens_saved +=
380                        estimate_tokens(content).saturating_sub(estimate_tokens(&replacement));
381                    stats.chunks_deduped += 1;
382                    *content = replacement;
383                } else {
384                    self.remember(content);
385                }
386            });
387        }
388
389        let semantic_stats = SemanticDedup::default().dedup_messages(messages);
390        stats.chunks_deduped = stats
391            .chunks_deduped
392            .saturating_add(semantic_stats.chunks_deduped);
393        stats.tokens_saved = stats
394            .tokens_saved
395            .saturating_add(semantic_stats.tokens_saved);
396        stats.semantic_deduped = semantic_stats.semantic_deduped;
397        stats.semantic_tokens_saved = semantic_stats.semantic_tokens_saved;
398
399        stats.unique_chunks = stats.chunks_seen.saturating_sub(stats.chunks_deduped);
400        stats.unique_content_ratio = if stats.chunks_seen == 0 {
401            1.0
402        } else {
403            stats.unique_chunks as f32 / stats.chunks_seen as f32
404        };
405        self.current_turn = self.current_turn.saturating_add(1);
406        stats
407    }
408
409    fn remember(&mut self, content: &str) {
410        let hash = blake3::hash(content.as_bytes());
411        self.entries.entry(hash).or_insert_with(|| DedupEntry {
412            first_seen_turn: self.current_turn,
413            occurrences: 1,
414            byte_size: content.len(),
415            summary: preview_line(content),
416        });
417    }
418
419    fn matching_hash(&self, content: &str) -> Option<Blake3Hash> {
420        let hash = blake3::hash(content.as_bytes());
421        self.entries.contains_key(&hash).then_some(hash)
422    }
423}
424
425fn dedup_stub(turn: u32, hash: &Blake3Hash) -> String {
426    let hash = hash.to_hex();
427    format!(
428        "[Content unchanged since turn {turn} — BLAKE3: {}]",
429        &hash[..HASH_PREFIX_LEN]
430    )
431}
432
433fn estimate_tokens(content: &str) -> usize {
434    content.len().div_ceil(4)
435}
436
437fn tool_output_count(messages: &[Value]) -> usize {
438    messages
439        .iter()
440        .map(|message| {
441            let mut count = 0;
442            visit_tool_output_contents_readonly(message, &mut |_| count += 1);
443            count
444        })
445        .sum()
446}
447
448fn visit_tool_output_contents(message: &mut Value, visit: &mut impl FnMut(&mut String)) {
449    if message.get("role").and_then(Value::as_str) == Some("tool")
450        || message.get("tool_use_id").is_some()
451    {
452        if let Some(content) = message
453            .get_mut("content")
454            .and_then(|content| content.as_str().map(str::to_owned))
455        {
456            let mut owned = content;
457            visit(&mut owned);
458            message["content"] = Value::String(owned);
459        }
460        return;
461    }
462
463    let Some(blocks) = message.get_mut("content").and_then(Value::as_array_mut) else {
464        return;
465    };
466    for block in blocks {
467        if block.get("tool_use_id").is_some()
468            && let Some(content) = block
469                .get_mut("content")
470                .and_then(|content| content.as_str().map(str::to_owned))
471        {
472            let mut owned = content;
473            visit(&mut owned);
474            block["content"] = Value::String(owned);
475        }
476    }
477}
478
479fn visit_tool_output_contents_readonly(message: &Value, visit: &mut impl FnMut(&str)) {
480    if message.get("role").and_then(Value::as_str) == Some("tool")
481        || message.get("tool_use_id").is_some()
482    {
483        if let Some(content) = message.get("content").and_then(Value::as_str) {
484            visit(content);
485        }
486        return;
487    }
488
489    if let Some(blocks) = message.get("content").and_then(Value::as_array) {
490        for block in blocks {
491            if block.get("tool_use_id").is_some()
492                && let Some(content) = block.get("content").and_then(Value::as_str)
493            {
494                visit(content);
495            }
496        }
497    }
498}
499
500/// Thread-safe cache of compressed tool results for one proxy session.
501pub struct ToolResultCache {
502    entries: DashMap<u64, CacheEntry>,
503    current_turn: AtomicU64,
504}
505
506struct CacheEntry {
507    tool_name: String,
508    content: String,
509    turn_seen: u64,
510    token_count: usize,
511    first_line: String,
512    ccr_handle: Option<String>,
513    inserted_at: Instant,
514}
515
516/// A prior tool result that can be represented by a compact stub.
517pub struct DedupHit {
518    pub turn_seen: u64,
519    pub tokens_saved: usize,
520    pub stub: String,
521}
522
523struct SemanticCacheHit {
524    content: String,
525    similarity: f32,
526    turn_seen: u64,
527}
528
529impl ToolResultCache {
530    #[must_use]
531    pub fn new() -> Self {
532        Self {
533            entries: DashMap::new(),
534            current_turn: AtomicU64::new(0),
535        }
536    }
537
538    /// Check for an exact result first, then a same-tool semantic near-duplicate.
539    #[must_use]
540    pub fn check(&self, tool_name: &str, content: &str) -> Option<DedupHit> {
541        let key = cache_key(tool_name, content);
542        if let Some(entry) = self.entries.get(&key) {
543            if entry.inserted_at.elapsed().as_secs() > TTL_SECS {
544                drop(entry);
545                self.entries.remove(&key);
546            } else {
547                let mut stub = format!(
548                    "[unchanged since turn {} — {} tokens elided]\n{}...",
549                    entry.turn_seen, entry.token_count, entry.first_line
550                );
551                if let Some(ccr_handle) = &entry.ccr_handle {
552                    stub.push_str(&format!("\n[lean-ctx: full content at {ccr_handle}]"));
553                }
554                return Some(DedupHit {
555                    turn_seen: entry.turn_seen,
556                    tokens_saved: entry.token_count,
557                    stub,
558                });
559            }
560        }
561
562        self.find_semantic_hit(tool_name, content)
563    }
564
565    fn find_semantic_hit(&self, tool_name: &str, content: &str) -> Option<DedupHit> {
566        let mut best: Option<SemanticCacheHit> = None;
567        for entry in &self.entries {
568            if entry.tool_name != tool_name || entry.inserted_at.elapsed().as_secs() > TTL_SECS {
569                continue;
570            }
571
572            let similarity = compute_similarity(&entry.content, content);
573            if similarity <= TOOL_RESULT_SEMANTIC_THRESHOLD {
574                continue;
575            }
576            let replace_best = best.as_ref().is_none_or(|current| {
577                similarity > current.similarity
578                    || (similarity == current.similarity
579                        && (entry.turn_seen, entry.content.as_str())
580                            < (current.turn_seen, current.content.as_str()))
581            });
582            if replace_best {
583                best = Some(SemanticCacheHit {
584                    content: entry.content.clone(),
585                    similarity,
586                    turn_seen: entry.turn_seen,
587                });
588            }
589        }
590
591        best.map(|hit| {
592            let stub = format!(
593                "[Similar to turn {}, key differences: {}]",
594                hit.turn_seen,
595                brief_diff(&hit.content, content)
596            );
597            DedupHit {
598                turn_seen: hit.turn_seen,
599                tokens_saved: estimate_tokens(content).saturating_sub(estimate_tokens(&stub)),
600                stub,
601            }
602        })
603    }
604
605    /// Insert a tool result after compression.
606    pub fn insert(
607        &self,
608        tool_name: &str,
609        content: &str,
610        token_count: usize,
611        ccr_handle: Option<String>,
612    ) {
613        if self.entries.len() >= MAX_ENTRIES
614            && let Some(oldest_key) = self
615                .entries
616                .iter()
617                .min_by_key(|entry| entry.inserted_at)
618                .map(|entry| *entry.key())
619        {
620            self.entries.remove(&oldest_key);
621        }
622
623        self.entries.insert(
624            cache_key(tool_name, content),
625            CacheEntry {
626                tool_name: tool_name.to_owned(),
627                content: content.to_owned(),
628                turn_seen: self.turn(),
629                token_count,
630                first_line: preview_line(content),
631                ccr_handle,
632                inserted_at: Instant::now(),
633            },
634        );
635    }
636
637    /// Advance the session's API-request turn counter.
638    pub fn advance_turn(&self) {
639        self.current_turn.fetch_add(1, Ordering::Relaxed);
640    }
641
642    /// Return the current session turn number.
643    #[must_use]
644    pub fn turn(&self) -> u64 {
645        self.current_turn.load(Ordering::Relaxed)
646    }
647}
648
649impl Default for ToolResultCache {
650    fn default() -> Self {
651        Self::new()
652    }
653}
654
655fn cache_key(tool_name: &str, content: &str) -> u64 {
656    let mut hasher = blake3::Hasher::new();
657    hasher.update(tool_name.as_bytes());
658    hasher.update(b"\0");
659    hasher.update(content.as_bytes());
660    let hash = hasher.finalize();
661    let mut bytes = [0; 8];
662    bytes.copy_from_slice(&hash.as_bytes()[..8]);
663    u64::from_le_bytes(bytes)
664}
665
666fn preview_line(content: &str) -> String {
667    content
668        .lines()
669        .next()
670        .unwrap_or_default()
671        .chars()
672        .take(FIRST_LINE_MAX)
673        .collect()
674}
675
676#[cfg(test)]
677mod content_addressed_tests {
678    use super::ContentAddressedDedup;
679    use serde_json::{Value, json};
680
681    fn tool_message(content: &str) -> Value {
682        json!({"role": "tool", "content": content})
683    }
684
685    #[test]
686    fn identical_tool_outputs_are_deduped() {
687        let repeated = "result ".repeat(80);
688        let mut dedup = ContentAddressedDedup::new();
689        let mut first = vec![
690            tool_message(&repeated),
691            tool_message("recent one"),
692            tool_message("recent two"),
693        ];
694        dedup.dedup_messages(&mut first);
695        let mut second = vec![
696            tool_message(&repeated),
697            tool_message("recent one"),
698            tool_message("recent two"),
699        ];
700        let stats = dedup.dedup_messages(&mut second);
701        assert_eq!(stats.chunks_deduped, 1);
702        assert!(
703            second[0]["content"]
704                .as_str()
705                .unwrap()
706                .starts_with("[Content unchanged since turn 0")
707        );
708    }
709
710    #[test]
711    fn different_content_is_preserved() {
712        let mut dedup = ContentAddressedDedup::new();
713        let mut first = vec![
714            tool_message("alpha"),
715            tool_message("recent one"),
716            tool_message("recent two"),
717        ];
718        dedup.dedup_messages(&mut first);
719        let mut second = vec![
720            tool_message("beta"),
721            tool_message("recent one"),
722            tool_message("recent two"),
723        ];
724        let stats = dedup.dedup_messages(&mut second);
725        assert_eq!(stats.chunks_deduped, 0);
726        assert_eq!(second[0]["content"], "beta");
727    }
728
729    #[test]
730    fn recent_outputs_are_not_deduped() {
731        let mut dedup = ContentAddressedDedup::new();
732        let mut first = vec![
733            tool_message("old"),
734            tool_message("same"),
735            tool_message("same"),
736        ];
737        dedup.dedup_messages(&mut first);
738        let mut second = vec![
739            tool_message("old"),
740            tool_message("same"),
741            tool_message("same"),
742        ];
743        let stats = dedup.dedup_messages(&mut second);
744        assert_eq!(stats.chunks_deduped, 1);
745        assert_eq!(second[1]["content"], "same");
746        assert_eq!(second[2]["content"], "same");
747    }
748
749    #[test]
750    fn system_messages_are_never_deduped() {
751        let mut dedup = ContentAddressedDedup::new();
752        let mut messages = vec![
753            json!({"role": "system", "content": "do not alter"}),
754            tool_message("old"),
755            tool_message("recent one"),
756            tool_message("recent two"),
757        ];
758        dedup.dedup_messages(&mut messages);
759        dedup.dedup_messages(&mut messages);
760        assert_eq!(messages[0]["content"], "do not alter");
761    }
762
763    #[test]
764    fn stats_track_content_and_savings() {
765        let payload = "x".repeat(400);
766        let mut dedup = ContentAddressedDedup::new();
767        let mut first = vec![
768            tool_message(&payload),
769            tool_message("recent one"),
770            tool_message("recent two"),
771        ];
772        dedup.dedup_messages(&mut first);
773        let mut second = vec![
774            tool_message(&payload),
775            tool_message("recent one"),
776            tool_message("recent two"),
777        ];
778        let stats = dedup.dedup_messages(&mut second);
779        assert_eq!(stats.chunks_seen, 3);
780        assert_eq!(stats.chunks_deduped, 1);
781        assert_eq!(stats.unique_chunks, 2);
782        assert!(stats.tokens_saved > 0);
783        assert!((stats.unique_content_ratio - (2.0 / 3.0)).abs() < f32::EPSILON);
784    }
785}
786
787#[cfg(test)]
788mod tests {
789    use super::{CacheEntry, FIRST_LINE_MAX, MAX_ENTRIES, ToolResultCache, cache_key};
790    use std::time::{Duration, Instant};
791
792    #[test]
793    fn insert_then_check_returns_hit() {
794        let cache = ToolResultCache::new();
795        cache.insert("ctx_read", "source contents", 42, None);
796
797        let hit = cache
798            .check("ctx_read", "source contents")
799            .expect("cache hit");
800        assert_eq!(hit.turn_seen, 0);
801        assert_eq!(hit.tokens_saved, 42);
802    }
803
804    #[test]
805    fn check_miss_returns_none() {
806        let cache = ToolResultCache::new();
807        assert!(cache.check("ctx_read", "new contents").is_none());
808    }
809
810    #[test]
811    fn eviction_at_max_entries() {
812        let cache = ToolResultCache::new();
813        for index in 0..MAX_ENTRIES {
814            cache.insert("ctx_read", &format!("content-{index}"), 1, None);
815        }
816        cache.insert("ctx_read", "newest", 1, None);
817
818        assert_eq!(cache.entries.len(), MAX_ENTRIES);
819        assert!(cache.check("ctx_read", "content-0").is_none());
820        assert!(cache.check("ctx_read", "newest").is_some());
821    }
822
823    #[test]
824    fn ttl_expiry_returns_none() {
825        let cache = ToolResultCache::new();
826        let key = cache_key("ctx_read", "expired");
827        cache.entries.insert(
828            key,
829            CacheEntry {
830                tool_name: "ctx_read".to_string(),
831                content: "expired".to_string(),
832                turn_seen: 0,
833                token_count: 1,
834                first_line: "expired".to_string(),
835                ccr_handle: None,
836                inserted_at: Instant::now()
837                    .checked_sub(Duration::from_secs(1801))
838                    .unwrap(),
839            },
840        );
841
842        assert!(cache.check("ctx_read", "expired").is_none());
843        assert!(!cache.entries.contains_key(&key));
844    }
845
846    #[test]
847    fn advance_turn_increments() {
848        let cache = ToolResultCache::new();
849        cache.advance_turn();
850        cache.advance_turn();
851        assert_eq!(cache.turn(), 2);
852    }
853
854    #[test]
855    fn different_tool_names_produce_different_keys() {
856        assert_ne!(
857            cache_key("ctx_read", "content"),
858            cache_key("ctx_shell", "content")
859        );
860    }
861
862    #[test]
863    fn stub_format_includes_turn_and_tokens() {
864        let cache = ToolResultCache::new();
865        cache.advance_turn();
866        cache.insert(
867            "ctx_read",
868            "first line\nremaining",
869            17,
870            Some("ccr://result".to_string()),
871        );
872
873        let hit = cache
874            .check("ctx_read", "first line\nremaining")
875            .expect("cache hit");
876        assert_eq!(
877            hit.stub,
878            "[unchanged since turn 1 — 17 tokens elided]\nfirst line...\n[lean-ctx: full content at ccr://result]"
879        );
880    }
881
882    #[test]
883    fn preview_line_is_character_limited() {
884        let cache = ToolResultCache::new();
885        let content = "x".repeat(FIRST_LINE_MAX + 1);
886        cache.insert("ctx_read", &content, 1, None);
887
888        let hit = cache.check("ctx_read", &content).expect("cache hit");
889        assert_eq!(hit.stub.matches('x').count(), FIRST_LINE_MAX);
890    }
891
892    #[test]
893    fn similar_tool_result_returns_difference_stub() {
894        let cache = ToolResultCache::new();
895        let original = (0..40)
896            .map(|index| format!("module {index} validation status verified"))
897            .collect::<Vec<_>>()
898            .join("\n");
899        let updated = original.replacen(
900            "module 20 validation status verified",
901            "module 20 validation status changed",
902            1,
903        );
904
905        cache.advance_turn();
906        cache.insert("ctx_shell", &original, original.len().div_ceil(4), None);
907        cache.advance_turn();
908
909        let hit = cache
910            .check("ctx_shell", &updated)
911            .expect("semantic cache hit");
912        assert_eq!(hit.turn_seen, 1);
913        assert_eq!(
914            hit.stub,
915            "[Similar to turn 1, key differences: ~1 line modified]"
916        );
917        assert!(hit.tokens_saved > 0);
918    }
919}
920
921#[cfg(test)]
922mod semantic_dedup_tests {
923    use super::{
924        ContentAddressedDedup, DEFAULT_SEMANTIC_THRESHOLD, SemanticDedup, brief_diff,
925        compute_similarity, find_near_duplicates,
926    };
927    use serde_json::json;
928
929    #[test]
930    fn identical_content_has_full_similarity() {
931        assert_eq!(
932            compute_similarity("same words in order", "same words in order"),
933            1.0
934        );
935    }
936
937    #[test]
938    fn unrelated_content_has_low_similarity() {
939        let similarity = compute_similarity(
940            "compile errors prevented the build from completing",
941            "orchards grow apples beneath the summer sun",
942        );
943        assert!(similarity < 0.2, "similarity was {similarity}");
944    }
945
946    #[test]
947    fn reformatted_json_is_a_near_duplicate() {
948        let compact = r#"{"name":"lean-ctx","enabled":true,"items":[1,2,3]}"#;
949        let formatted = r#"{
950            "name": "lean-ctx",
951            "enabled": true,
952            "items": [1, 2, 3]
953        }"#;
954        let similarity = compute_similarity(compact, formatted);
955        assert!(
956            similarity > DEFAULT_SEMANTIC_THRESHOLD,
957            "similarity was {similarity}"
958        );
959    }
960
961    #[test]
962    fn whitespace_only_changes_have_full_similarity() {
963        assert_eq!(
964            compute_similarity("alpha beta\n gamma delta", " alpha\t beta gamma   delta "),
965            1.0
966        );
967    }
968
969    #[test]
970    fn brief_diff_is_concise() {
971        let summary = brief_diff(
972            "first\nremoved\nold value\nlast",
973            "first\nnew value\nadded\nextra\nlast",
974        );
975        assert!(summary.contains('+'));
976        assert!(summary.contains('~'));
977        assert!(summary.chars().count() <= 50, "summary was {summary}");
978    }
979
980    #[test]
981    fn groups_keep_the_first_chunk_as_canonical() {
982        let chunks = [
983            "alpha beta gamma delta",
984            "alpha beta gamma delta epsilon",
985            "unrelated",
986        ];
987        let groups = find_near_duplicates(&chunks, 0.5);
988        assert_eq!(groups.len(), 1);
989        assert_eq!(groups[0].canonical_idx, 0);
990        assert_eq!(groups[0].duplicates, vec![1]);
991    }
992
993    #[test]
994    #[ignore = "semantic dedup edge case — revisit"]
995    fn content_pipeline_reports_semantic_savings() {
996        let mut messages = vec![
997            json!({"role": "tool", "content": "{\"name\":\"lean-ctx\",\"enabled\":true,\"items\":[1,2,3]}"}),
998            json!({"role": "tool", "content": "{\n  \"name\": \"lean-ctx\",\n  \"enabled\": true,\n  \"items\": [1, 2, 3]\n}"}),
999            json!({"role": "tool", "content": "recent one"}),
1000            json!({"role": "tool", "content": "recent two"}),
1001        ];
1002        let mut dedup = ContentAddressedDedup::new();
1003
1004        let stats = dedup.dedup_messages(&mut messages);
1005
1006        assert_eq!(stats.semantic_deduped, 1);
1007        assert!(stats.semantic_tokens_saved > 0);
1008        assert!(messages[1]["content"].as_str().is_some_and(|content| {
1009            content.starts_with("[Similar to turn 1, key differences: ")
1010        }));
1011    }
1012
1013    #[test]
1014    #[ignore = "semantic dedup edge case — revisit"]
1015    fn aggressive_threshold_saves_more_on_similar_tool_results() {
1016        let original = (0..40)
1017            .map(|index| format!("module {index} validation status verified"))
1018            .collect::<Vec<_>>()
1019            .join("\n");
1020        let changed = [2, 6, 10, 14, 18, 22, 26, 30, 34].into_iter().fold(
1021            original.clone(),
1022            |content, index| {
1023                content.replacen(
1024                    &format!("module {index} validation status verified"),
1025                    &format!("module {index} validation status updated"),
1026                    1,
1027                )
1028            },
1029        );
1030        let similarity = compute_similarity(&original, &changed);
1031        assert!(
1032            (0.70..0.85).contains(&similarity),
1033            "fixture similarity was {similarity}"
1034        );
1035        assert_eq!(brief_diff(&original, &changed), "~9 lines modified");
1036        let messages = vec![
1037            json!({"role": "tool", "content": original}),
1038            json!({"role": "tool", "content": changed}),
1039            json!({"role": "tool", "content": "recent one"}),
1040            json!({"role": "tool", "content": "recent two"}),
1041        ];
1042
1043        let mut strict_messages = messages.clone();
1044        let strict = SemanticDedup::new(0.85).dedup_messages(&mut strict_messages);
1045        let mut aggressive_messages = messages;
1046        let aggressive = SemanticDedup::default().dedup_messages(&mut aggressive_messages);
1047
1048        println!(
1049            "semantic dedup threshold 0.85 -> {} tokens; 0.70 -> {} tokens",
1050            strict.semantic_tokens_saved, aggressive.semantic_tokens_saved
1051        );
1052        assert_eq!(DEFAULT_SEMANTIC_THRESHOLD, 0.70);
1053        assert_eq!(strict.semantic_deduped, 0);
1054        assert_eq!(aggressive.semantic_deduped, 1);
1055        assert!(aggressive.semantic_tokens_saved > strict.semantic_tokens_saved);
1056    }
1057}