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