Skip to main content

lean_ctx/proxy/
dedup.rs

1//! Request-local, lossless deduplication of repeated tool output.
2//!
3//! Invariant (#1980): a tool output is only ever replaced by text from which
4//! the model can reconstruct it *within the same request* — a reference to an
5//! earlier tool result that is still present verbatim, plus, for a near
6//! duplicate, the changed lines verbatim. Nothing is remembered across
7//! requests: the model is stateless, so a reference to content it saw in an
8//! earlier request points at nothing. References use the earlier result's
9//! tool-call id; outputs without one are never referenced.
10
11use std::collections::{HashMap, VecDeque};
12
13use serde_json::Value;
14
15/// The newest tool outputs always stay verbatim: an agent checking state
16/// (`ls`, a test run, a build) must read the fresh result itself, not a delta.
17const RECENT_TOOL_OUTPUTS: usize = 2;
18/// Earlier verbatim results a near duplicate is compared against.
19const DELTA_WINDOW: usize = 16;
20
21/// Savings produced while deduplicating one request.
22#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
23pub struct DedupStats {
24    pub chunks_seen: usize,
25    pub exact_deduped: usize,
26    pub delta_deduped: usize,
27    pub tokens_saved: usize,
28}
29
30/// An earlier tool result that stays verbatim and can therefore be referenced.
31struct Canonical {
32    id: String,
33    content: String,
34}
35
36/// Replace repeated, non-recent tool outputs in `messages` with references to
37/// an earlier, verbatim tool result in the same slice.
38///
39/// Pure function of `messages`: equal input yields equal output. A block's
40/// rewrite depends only on the blocks before it and on whether it is among the
41/// newest tool outputs, which always stay verbatim.
42pub fn dedup_tool_outputs(messages: &mut [Value]) -> DedupStats {
43    let chunk_count: usize = messages.iter().map(tool_output_count).sum();
44    let mut stats = DedupStats {
45        chunks_seen: chunk_count,
46        ..DedupStats::default()
47    };
48    let mut by_hash: HashMap<blake3::Hash, String> = HashMap::new();
49    let mut window: VecDeque<Canonical> = VecDeque::with_capacity(DELTA_WINDOW);
50    let mut chunk_index = 0;
51
52    for message in messages.iter_mut() {
53        visit_tool_outputs(message, &mut |id, content| {
54            let is_recent = chunk_index + RECENT_TOOL_OUTPUTS >= chunk_count;
55            chunk_index += 1;
56            let hash = blake3::hash(content.as_bytes());
57
58            if !is_recent {
59                let replacement = by_hash
60                    .get(&hash)
61                    .map(String::as_str)
62                    .map(exact_stub)
63                    .filter(|stub| estimate_tokens(stub) < estimate_tokens(content));
64                if let Some(stub) = replacement {
65                    stats.exact_deduped += 1;
66                    stats.tokens_saved += estimate_tokens(content) - estimate_tokens(&stub);
67                    *content = stub;
68                    return;
69                }
70                if let Some(stub) = best_delta_stub(&window, content) {
71                    stats.delta_deduped += 1;
72                    stats.tokens_saved += estimate_tokens(content) - estimate_tokens(&stub);
73                    *content = stub;
74                    return;
75                }
76            }
77
78            // Stays verbatim: referenceable by later outputs when it has an id.
79            if let Some(id) = id {
80                by_hash.entry(hash).or_insert_with(|| id.to_owned());
81                if window.len() == DELTA_WINDOW {
82                    window.pop_front();
83                }
84                window.push_back(Canonical {
85                    id: id.to_owned(),
86                    content: content.clone(),
87                });
88            }
89        });
90    }
91    stats
92}
93
94fn exact_stub(canonical_id: &str) -> String {
95    format!("[lean-ctx: identical to tool result {canonical_id} above]")
96}
97
98/// The smallest delta stub against any windowed canonical, if it is at most
99/// half the size of `content`. Ties keep the earliest canonical.
100fn best_delta_stub(window: &VecDeque<Canonical>, content: &str) -> Option<String> {
101    let budget = estimate_tokens(content) / 2;
102    window
103        .iter()
104        .filter_map(|canonical| delta_stub(canonical, content))
105        .filter(|stub| estimate_tokens(stub) <= budget)
106        .min_by_key(String::len)
107}
108
109/// Describe `content` as `canonical` with one contiguous block of lines
110/// changed, carrying the new lines verbatim so the result is reconstructible.
111fn delta_stub(canonical: &Canonical, content: &str) -> Option<String> {
112    // `lines()` drops line endings, so only LF text with the same trailing
113    // newline state is reproduced exactly by "canonical with these lines".
114    if canonical.content.contains('\r')
115        || content.contains('\r')
116        || canonical.content.ends_with('\n') != content.ends_with('\n')
117    {
118        return None;
119    }
120    let old: Vec<&str> = canonical.content.lines().collect();
121    let new: Vec<&str> = content.lines().collect();
122    let prefix = old
123        .iter()
124        .zip(&new)
125        .take_while(|(old_line, new_line)| old_line == new_line)
126        .count();
127    let max_suffix = old.len().min(new.len()) - prefix;
128    let suffix = old
129        .iter()
130        .rev()
131        .zip(new.iter().rev())
132        .take(max_suffix)
133        .take_while(|(old_line, new_line)| old_line == new_line)
134        .count();
135    let removed = &old[prefix..old.len() - suffix];
136    let inserted = &new[prefix..new.len() - suffix];
137    let id = &canonical.id;
138
139    let change = match (removed.is_empty(), inserted.is_empty()) {
140        // Only line-ending differences: not a change `lines()` can express.
141        (true, true) => return None,
142        (true, false) if prefix == 0 => "these lines are inserted at the start".to_owned(),
143        (true, false) => format!("these lines are inserted after line {prefix}"),
144        (false, true) => {
145            return Some(format!(
146                "[lean-ctx: tool result {id} above, except {} removed]",
147                line_span(prefix, removed.len(), "is", "are")
148            ));
149        }
150        (false, false) => format!(
151            "{} replaced by",
152            line_span(prefix, removed.len(), "is", "are")
153        ),
154    };
155    Some(format!(
156        "[lean-ctx: tool result {id} above, except {change}:\n{}\n]",
157        inserted.join("\n")
158    ))
159}
160
161/// "line 5 is" / "lines 5–7 are" for `count` lines after the first `prefix`.
162fn line_span(prefix: usize, count: usize, singular: &str, plural: &str) -> String {
163    let first = prefix + 1;
164    if count == 1 {
165        format!("line {first} {singular}")
166    } else {
167        format!("lines {first}–{} {plural}", prefix + count)
168    }
169}
170
171fn estimate_tokens(content: &str) -> usize {
172    content.len().div_ceil(4)
173}
174
175fn tool_output_count(message: &Value) -> usize {
176    if is_tool_message(message) {
177        return usize::from(message.get("content").is_some_and(Value::is_string));
178    }
179    message
180        .get("content")
181        .and_then(Value::as_array)
182        .map_or(0, |blocks| {
183            blocks
184                .iter()
185                .filter(|block| {
186                    block.get("tool_use_id").is_some()
187                        && block.get("content").is_some_and(Value::is_string)
188                })
189                .count()
190        })
191}
192
193fn is_tool_message(message: &Value) -> bool {
194    message.get("role").and_then(Value::as_str) == Some("tool")
195        || message.get("tool_use_id").is_some()
196}
197
198/// Visit every string tool output in `message` with its tool-call id: an
199/// OpenAI `role: "tool"` message (`tool_call_id`) or Anthropic `tool_result`
200/// blocks (`tool_use_id`). Array-shaped results are left untouched.
201fn visit_tool_outputs(message: &mut Value, visit: &mut impl FnMut(Option<&str>, &mut String)) {
202    if is_tool_message(message) {
203        let id = ["tool_call_id", "tool_use_id"]
204            .iter()
205            .find_map(|key| message.get(*key).and_then(Value::as_str))
206            .map(str::to_owned);
207        if let Some(Value::String(content)) = message.get_mut("content") {
208            visit(id.as_deref(), content);
209        }
210        return;
211    }
212
213    let Some(blocks) = message.get_mut("content").and_then(Value::as_array_mut) else {
214        return;
215    };
216    for block in blocks {
217        let Some(id) = block
218            .get("tool_use_id")
219            .and_then(Value::as_str)
220            .map(str::to_owned)
221        else {
222            continue;
223        };
224        if let Some(Value::String(content)) = block.get_mut("content") {
225            visit(Some(&id), content);
226        }
227    }
228}
229
230#[cfg(test)]
231mod tests {
232    use super::dedup_tool_outputs;
233    use serde_json::{Value, json};
234
235    fn tool(id: &str, content: &str) -> Value {
236        json!({"role": "tool", "tool_call_id": id, "content": content})
237    }
238
239    fn content(message: &Value) -> &str {
240        message["content"].as_str().unwrap()
241    }
242
243    fn ls_output(date: &str) -> String {
244        let mut lines: Vec<String> = (0..30)
245            .map(|index| {
246                format!("-rw-r--r--  1 dev  staff  {index:>6} Oct  1 09:00 src/file_{index}.rs")
247            })
248            .collect();
249        lines[12] = format!("-rwxr-xr-x  1 dev  staff  52428800 {date} target/release/lean-ctx");
250        lines.join("\n")
251    }
252
253    // #1980: a near duplicate used to become "[Similar to turn N, key
254    // differences: ~1 line modified]", hiding the fresh value (a rebuilt
255    // binary's date). The delta must carry the changed line verbatim.
256    #[test]
257    fn near_duplicate_keeps_the_changed_lines_verbatim() {
258        let before = ls_output("Oct  1 09:00");
259        let after = ls_output("Oct  2 18:53");
260        let mut messages = vec![
261            tool("call_1", &before),
262            tool("call_2", &after),
263            tool("call_3", "recent one"),
264            tool("call_4", "recent two"),
265        ];
266
267        let stats = dedup_tool_outputs(&mut messages);
268
269        assert_eq!(content(&messages[0]), before);
270        assert_eq!(
271            content(&messages[1]),
272            "[lean-ctx: tool result call_1 above, except line 13 is replaced by:\n\
273             -rwxr-xr-x  1 dev  staff  52428800 Oct  2 18:53 target/release/lean-ctx\n]"
274        );
275        assert_eq!(stats.delta_deduped, 1);
276    }
277
278    // #1980: dedup state used to persist across requests, so a re-sent output
279    // matched itself and was replaced by a reference to nothing. Every
280    // request is judged on its own; a unique output stays verbatim however
281    // often the same history is sent.
282    #[test]
283    fn resent_history_never_references_content_absent_from_the_request() {
284        let unique = "unique tool output ".repeat(40);
285        let request = vec![
286            tool("call_1", &unique),
287            tool("call_2", "recent one"),
288            tool("call_3", "recent two"),
289        ];
290        for _ in 0..2 {
291            let mut resent = request.clone();
292            assert_eq!(dedup_tool_outputs(&mut resent).tokens_saved, 0);
293            assert_eq!(resent, request);
294        }
295    }
296
297    #[test]
298    fn exact_duplicate_references_the_earlier_result_by_id() {
299        let repeated = "cargo test: 812 passed\n".repeat(20);
300        let mut messages = vec![
301            json!({"role": "user", "content": [
302                {"type": "tool_result", "tool_use_id": "toolu_a", "content": repeated}
303            ]}),
304            json!({"role": "user", "content": [
305                {"type": "tool_result", "tool_use_id": "toolu_b", "content": repeated}
306            ]}),
307            tool("call_3", "recent one"),
308            tool("call_4", "recent two"),
309        ];
310
311        let stats = dedup_tool_outputs(&mut messages);
312
313        assert_eq!(messages[0]["content"][0]["content"], json!(repeated));
314        assert_eq!(
315            messages[1]["content"][0]["content"],
316            json!("[lean-ctx: identical to tool result toolu_a above]")
317        );
318        assert_eq!(stats.exact_deduped, 1);
319    }
320
321    // A delta built on `lines()` cannot express line-ending changes; such a
322    // pair must stay verbatim rather than reconstruct to the wrong bytes.
323    #[test]
324    fn line_ending_differences_are_never_described_as_a_delta() {
325        let lf = ls_output("Oct  1 09:00");
326        for changed in [
327            ls_output("Oct  2 18:53").replace('\n', "\r\n"),
328            format!("{}\n", ls_output("Oct  2 18:53")),
329        ] {
330            let mut messages = vec![
331                tool("call_1", &lf),
332                tool("call_2", &changed),
333                tool("call_3", "recent one"),
334                tool("call_4", "recent two"),
335            ];
336            assert_eq!(dedup_tool_outputs(&mut messages).delta_deduped, 0);
337            assert_eq!(content(&messages[1]), changed);
338        }
339    }
340
341    #[test]
342    fn outputs_without_an_id_are_never_referenced() {
343        let repeated = "same output ".repeat(40);
344        let mut messages = vec![
345            json!({"role": "tool", "content": repeated}),
346            tool("call_2", &repeated),
347            tool("call_3", "recent one"),
348            tool("call_4", "recent two"),
349        ];
350        let original = messages.clone();
351
352        assert_eq!(dedup_tool_outputs(&mut messages).tokens_saved, 0);
353        assert_eq!(messages, original);
354    }
355}