Skip to main content

lean_ctx_proxy/
session_elide.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Long-session elision for Anthropic Messages requests.
3//!
4//! In a long agent session most of every request is old tool output the model
5//! has already acted on. Once the client's `messages` serialize to more than
6//! [`THRESHOLD_BYTES`], every `tool_result` older than the live window whose
7//! text is longer than [`MIN_ELIDE_BYTES`] leaves as a one-line stub. The
8//! original goes to the content-addressed tee store (`{state}/tee/`, files
9//! 0600 in a private state directory) and the stub names that file, so the
10//! model gets the full text back with `cat` or its file read — Claude Code in
11//! governor mode has no MCP tools, so `ctx_expand` alone would not do.
12//!
13//! ## Why this rewrites inside the cached prefix
14//!
15//! Claude Code puts a cache marker on the last message, so the history pruner
16//! (which never touches the client-cached prefix, #448) never fires there.
17//! Elision deliberately does. It is bounded:
18//!
19//! - the window is the cache-aware staircase of
20//!   `history_prune::prune_boundary`: it advances only in whole strides of
21//!   16 messages and keeps at least 8, so the cached prefix breaks once per
22//!   stride, not every turn;
23//! - the stub is a pure function of the block's text (#498), so a block
24//!   elided once leaves with the same bytes on every later turn;
25//! - the size test reads the client's own messages, which only grow, so a
26//!   session that crossed the threshold stays across it;
27//! - it runs on every request of such a session, the person's prompt turns
28//!   included: a prompt turn then sends the same elided prefix as the tool
29//!   turn before it and reads the cache, instead of sending the history
30//!   whole and writing it again.
31//!
32//! Measured on Claude Code with Haiku 5.5, long sessions: cost x0.74
33//! (95 % CI 0.53–0.94) against native, 12/12 tasks solved on both arms. The
34//! one cache write per stride is cheaper than reading the full history on
35//! every turn of that stride.
36//!
37//! The determinism guard and the prefix replay know this exception: a
38//! forwarded prefix that first differs at a newly elided message is the
39//! sanctioned stride break ([`newly_elided`], [`message_is_elided`]).
40//!
41//! Under protection (a policy pack, governed or sovereign mode) the tee store
42//! holds nothing originless: a block leaves shortened only with a recovery
43//! copy bound to its lineage (`compress::shorten_with_copy`), otherwise it
44//! stays whole. Content never reaches a log.
45
46use serde_json::Value;
47
48/// Serialized size of the client's `messages` above which old tool output is
49/// elided (measured arm: 180 000 characters).
50pub const THRESHOLD_BYTES: usize = 180_000;
51
52/// Tool output at or below this size stays as it is: the stub would save
53/// little and the model often still quotes short results.
54pub const MIN_ELIDE_BYTES: usize = 2_000;
55
56/// How every elision stub opens; also what [`message_is_elided`] recognises.
57pub const STUB_OPEN: &str = "[lean-ctx: earlier tool output elided";
58
59/// Serialized size of `messages`, without building the string.
60fn serialized_len(messages: &[Value]) -> usize {
61    struct Count(usize);
62    impl std::io::Write for Count {
63        fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
64            self.0 += buf.len();
65            Ok(buf.len())
66        }
67        fn flush(&mut self) -> std::io::Result<()> {
68            Ok(())
69        }
70    }
71    let mut count = Count(0);
72    let _ = serde_json::to_writer(&mut count, messages);
73    count.0
74}
75
76/// Elide old tool output in `messages` when they exceed `threshold` bytes.
77/// Returns the index of the last message that carries a stub, or `None` when
78/// nothing was elided.
79pub fn elide(messages: &mut [Value], threshold: usize) -> Option<usize> {
80    if serialized_len(messages) <= threshold {
81        return None;
82    }
83    let boundary = super::history_prune::prune_boundary(
84        lean_ctx::core::config::HistoryMode::CacheAware,
85        messages.len(),
86    );
87    let mut last = None;
88    for (index, message) in messages[..boundary].iter_mut().enumerate() {
89        if message.get("role").and_then(Value::as_str) != Some("user") {
90            continue;
91        }
92        let Some(blocks) = message.get_mut("content").and_then(Value::as_array_mut) else {
93            continue;
94        };
95        for block in blocks {
96            if elide_block(block) {
97                last = Some(index);
98            }
99        }
100    }
101    last
102}
103
104/// The text of a tool result that may be elided: a string, or an array made
105/// only of text items without a cache marker (an image or a nested marker
106/// keeps the block whole).
107fn elidable_text(content: &Value) -> Option<String> {
108    match content {
109        Value::String(text) => Some(text.clone()),
110        Value::Array(items) => {
111            let mut parts = Vec::with_capacity(items.len());
112            for item in items {
113                if item.get("type").and_then(Value::as_str) != Some("text")
114                    || item.get("cache_control").is_some()
115                {
116                    return None;
117                }
118                parts.push(item.get("text")?.as_str()?);
119            }
120            Some(parts.join("\n"))
121        }
122        _ => None,
123    }
124}
125
126/// Replace one `tool_result` block's content by its stub. Only `content`
127/// changes: `tool_use_id`, `is_error` and `cache_control` stay.
128fn elide_block(block: &mut Value) -> bool {
129    if block.get("type").and_then(Value::as_str) != Some("tool_result") {
130        return false;
131    }
132    let Some(original) = block.get("content").and_then(elidable_text) else {
133        return false;
134    };
135    if original.len() <= MIN_ELIDE_BYTES
136        || original.starts_with(STUB_OPEN)
137        || original.contains("<protect>")
138    {
139        return false;
140    }
141    let chars = original.chars().count();
142    let stub = if super::compress::protected() {
143        let call_id = block.get("tool_use_id").and_then(Value::as_str);
144        let _block = super::sticky_tools::block(call_id);
145        let Some(stub) = super::compress::shorten_with_copy(
146            &original,
147            &format!("{STUB_OPEN} ({chars} chars).]"),
148        ) else {
149            return false;
150        };
151        stub
152    } else {
153        // No recovery copy, no elision: the model keeps the text it had.
154        let Some(path) = super::ccr::persist_once(&original) else {
155            return false;
156        };
157        format!(
158            "{STUB_OPEN} ({chars} chars) to keep this long session lean; full text: {}]",
159            locator(std::path::Path::new(&path))
160        )
161    };
162    block["content"] = Value::String(stub);
163    true
164}
165
166/// How the stub names the archive without the account name: `cat ~/…` under
167/// the home directory (Bash expands it), else the store-relative name that
168/// `ctx_expand` resolves. A pure function of the path, so byte-stable.
169fn locator(path: &std::path::Path) -> String {
170    if let Some(home) = std::env::var_os("HOME").filter(|h| !h.is_empty())
171        && let Ok(rest) = path.strip_prefix(&home)
172    {
173        return format!("cat ~/{}", rest.display());
174    }
175    let name = path
176        .file_name()
177        .map_or_else(String::new, |n| n.to_string_lossy().into_owned());
178    format!("ctx_expand(id=\"{name}\") (LeanCTX state directory, tee/{name})")
179}
180
181/// Whether `message` carries a tool result that left as an elision stub.
182pub fn message_is_elided(message: &Value) -> bool {
183    message
184        .get("content")
185        .and_then(Value::as_array)
186        .is_some_and(|blocks| {
187            blocks.iter().any(|block| {
188                block.get("type").and_then(Value::as_str) == Some("tool_result")
189                    && block
190                        .get("content")
191                        .and_then(Value::as_str)
192                        .is_some_and(|text| text.starts_with(STUB_OPEN))
193            })
194        })
195}
196
197/// Whether the elision that reached message `last` is new against a forwarded
198/// request (`prefix_bytes`): that request covered message `last` and sent it
199/// without a stub. Elision only advances in whole strides, so the last elided
200/// message decides; a prefix replay must not restore the older bytes then.
201pub fn newly_elided(prefix_bytes: &[u8], last: usize) -> bool {
202    let Ok(previous) = serde_json::from_slice::<Value>(prefix_bytes) else {
203        return true;
204    };
205    previous
206        .get("messages")
207        .and_then(Value::as_array)
208        .and_then(|messages| messages.get(last))
209        .is_some_and(|message| !message_is_elided(message))
210}
211
212#[cfg(test)]
213mod tests {
214    use super::*;
215    use serde_json::json;
216
217    /// A tool loop: `turns` tool calls, each with a `size`-byte result.
218    fn session(turns: usize, size: usize) -> Vec<Value> {
219        let mut messages = vec![json!({"role": "user", "content": "fix the build"})];
220        for turn in 0..turns {
221            let id = format!("t{turn}");
222            messages.push(json!({"role": "assistant", "content": [
223                {"type": "tool_use", "id": id, "name": "Bash", "input": {"command": "make"}}
224            ]}));
225            let output = format!("output {turn} line\n").repeat(size / 15);
226            messages.push(json!({"role": "user", "content": [
227                {"type": "tool_result", "tool_use_id": id, "content": output}
228            ]}));
229        }
230        let last = messages.len() - 1;
231        messages[last]["content"][0]["cache_control"] = json!({"type": "ephemeral", "ttl": "1h"});
232        messages
233    }
234
235    #[test]
236    fn below_the_threshold_nothing_changes() {
237        let _data = lean_ctx::core::data_dir::isolated_data_dir();
238        let _community = lean_ctx::core::policy::runtime::TestPolicyOverride::set(None);
239        let mut messages = session(20, 5_000);
240        let before = messages.clone();
241        assert_eq!(elide(&mut messages, THRESHOLD_BYTES), None);
242        assert_eq!(messages, before);
243    }
244
245    #[test]
246    fn old_large_results_leave_as_a_stub_that_names_the_original() {
247        let _data = lean_ctx::core::data_dir::isolated_data_dir();
248        let _community = lean_ctx::core::policy::runtime::TestPolicyOverride::set(None);
249        let mut messages = session(30, 5_000);
250        // A small old result and a nested marker stay whole.
251        messages[2]["content"][0]["content"] = json!("ok");
252        messages[4]["content"][0]["content"] = json!([{"type": "text", "text": "x".repeat(5_000), "cache_control": {"type": "ephemeral"}}]);
253        let original = messages[6]["content"][0]["content"]
254            .as_str()
255            .unwrap()
256            .to_owned();
257        let before = messages.clone();
258
259        let last = elide(&mut messages, 100_000).expect("elided");
260        let boundary = (messages.len() - 8) / 16 * 16;
261        // The last tool-result turn before the stride boundary (odd indices
262        // are assistant turns).
263        assert_eq!(last, boundary - 2, "the window ends at the stride boundary");
264
265        assert_eq!(messages[2], before[2], "small result untouched");
266        assert_eq!(messages[4], before[4], "nested marker untouched");
267        let stub = messages[6]["content"][0]["content"].as_str().unwrap();
268        assert!(stub.starts_with(STUB_OPEN), "{stub}");
269        let path = if let Some(rest) = stub.split("cat ~/").nth(1) {
270            std::path::PathBuf::from(std::env::var_os("HOME").unwrap())
271                .join(rest.trim_end_matches(']'))
272        } else {
273            let id = stub
274                .split("id=\"")
275                .nth(1)
276                .unwrap()
277                .split('"')
278                .next()
279                .unwrap();
280            lean_ctx::core::ccr::resolve_tee(id).expect("archive resolves")
281        };
282        if let Some(home) = std::env::var("HOME").ok().filter(|h| !h.is_empty()) {
283            assert!(!stub.contains(&home), "no account path in the stub: {stub}");
284        }
285        // The fixture holds no secret, so the redacted archive is the original.
286        assert_eq!(std::fs::read_to_string(&path).unwrap(), original);
287        #[cfg(unix)]
288        {
289            use std::os::unix::fs::PermissionsExt;
290            let mode = std::fs::metadata(&path).unwrap().permissions().mode();
291            assert_eq!(mode & 0o777, 0o600, "the archive is private");
292        }
293        assert!(message_is_elided(&messages[6]));
294        assert_eq!(
295            messages[boundary..],
296            before[boundary..],
297            "the live window, with its cache marker, is untouched"
298        );
299
300        // Same block, same stub — also after the TTL cleanup removed the
301        // archive, which the next pass writes again.
302        let once = messages.clone();
303        std::fs::remove_file(&path).unwrap();
304        let mut again = before.clone();
305        elide(&mut again, 100_000);
306        assert_eq!(again, once, "content-deterministic stub (#498)");
307        assert_eq!(std::fs::read_to_string(&path).unwrap(), original);
308    }
309
310    #[test]
311    fn the_prefix_stays_byte_identical_within_a_stride() {
312        let _data = lean_ctx::core::data_dir::isolated_data_dir();
313        let _community = lean_ctx::core::policy::runtime::TestPolicyOverride::set(None);
314        // 61 and 63 messages share the boundary 48; 73 moves it to 64.
315        let mut turn = session(30, 5_000);
316        let mut next = session(31, 5_000);
317        let mut jump = session(36, 5_000);
318        elide(&mut turn, 100_000);
319        elide(&mut next, 100_000);
320        let last = elide(&mut jump, 100_000).unwrap();
321        let prefix = |m: &[Value]| serde_json::to_vec(&m[..48]).unwrap();
322        assert_eq!(prefix(&turn), prefix(&next));
323        assert_eq!(prefix(&turn), prefix(&jump));
324
325        let forwarded = serde_json::to_vec(&json!({"messages": next})).unwrap();
326        assert!(newly_elided(&forwarded, last), "the stride jump is new");
327        let forwarded = serde_json::to_vec(&json!({"messages": jump})).unwrap();
328        assert!(!newly_elided(&forwarded, last), "already sent elided");
329    }
330}