trusty_code/agent_loop/compaction.rs
1//! Non-destructive context compaction trigger + summary generation (#2070).
2//!
3//! Why: vision spec §5.4 ("Non-Destructive Compaction + Last-Message Replay")
4//! calls for a token-efficiency middleware in the agent-loop message buffer:
5//! once the running transcript grows past a threshold, older turns should be
6//! collapsed into a short summary rather than sent verbatim on every
7//! subsequent request — while never discarding the original content. This
8//! module holds the two pure, transcript-shape-agnostic pieces of that
9//! mechanism — the trigger decision and the summary text — so
10//! `super::transcript::Transcript` (which owns the actual entries and their
11//! `compacted` flags) can stay focused on state management. Splitting the
12//! policy (when / what to say) from the mechanism (marking entries, replaying
13//! the last user turn) keeps both halves independently testable.
14//! What: [`CompactionConfig`] (the tunable threshold + active-zone size —
15//! production code builds one via [`CompactionConfig::for_context_window`],
16//! #2308, rather than the legacy flat [`Default`] impl),
17//! [`estimate_tokens`] (a cheap chars/4 heuristic — no tokenizer dependency),
18//! [`should_compact`] (threshold check), and [`summarize_span`] (a
19//! deterministic one-line summary of a compacted message span, built from
20//! role counts and any tool names invoked — never an LLM call, so compaction
21//! never blocks the loop on network I/O).
22//! Test: `compaction::tests::*`.
23
24use crate::llm::ChatMessage;
25
26/// Tuning knobs for non-destructive context compaction (#2070, §5.4).
27///
28/// Why: A caller (production: `AgentLoop`; tests: unit tests exercising
29/// `Transcript` directly) needs to control both "how big is too big" and
30/// "how much of the recent conversation counts as the active work zone" —
31/// bundling them avoids two separate parameters threading through every call
32/// site.
33/// What: `token_threshold` is compared against the transcript's
34/// [`estimate_tokens`] total; `keep_last_messages` is the number of the most
35/// recent messages (the active work zone, §5.4 item 4) that are never
36/// eligible for compaction regardless of size.
37/// Test: `compaction::tests::default_is_sane`.
38#[derive(Debug, Clone, Copy)]
39pub struct CompactionConfig {
40 /// Estimated-token threshold that triggers compaction once exceeded.
41 pub token_threshold: usize,
42 /// Number of most-recent messages kept verbatim (the active work zone).
43 pub keep_last_messages: usize,
44}
45
46/// Percentage of a model's context window at which compaction fires (#2308).
47///
48/// Why: A flat `token_threshold` (the old `6_000` constant) is model-blind —
49/// for a 200K-token Bedrock Claude Sonnet window that is ~3% utilisation,
50/// meaning ordinary coding turns (post-#2261 tool-call-arg counting) blow
51/// through it every couple of turns, destroying working context via
52/// "re-anchor thrash". Scaling the threshold to a fraction of the ACTUAL
53/// resolved context window (see [`crate::provider::resolve_context_window`])
54/// fixes this at the root: compaction now fires only once the transcript is
55/// genuinely close to exhausting the model's real budget. 75% leaves a
56/// generous headroom margin for the completion tokens of the turn that
57/// crosses the threshold, plus the summary/replay overhead compaction itself
58/// introduces.
59/// What: Used by [`CompactionConfig::for_context_window`] as
60/// `context_window * COMPACTION_THRESHOLD_FRACTION_PCT / 100`.
61/// Test: `compaction::tests::for_context_window_scales_threshold_proportionally`.
62pub const COMPACTION_THRESHOLD_FRACTION_PCT: usize = 75;
63
64impl CompactionConfig {
65 /// Derive a `CompactionConfig` proportional to a model's real context
66 /// window (#2308).
67 ///
68 /// Why: This is the production constructor — the flat, model-blind
69 /// `Default` threshold (see that impl's doc) is the root cause of #2308's
70 /// pathological re-compaction. Every production call site that knows its
71 /// model slug must resolve the model's real context window (via
72 /// [`crate::provider::resolve_context_window`]) and build its
73 /// `CompactionConfig` through this constructor instead.
74 /// What: `token_threshold` is `context_window * `
75 /// [`COMPACTION_THRESHOLD_FRACTION_PCT`]` / 100`; `keep_last_messages` is
76 /// unchanged from the previous default (6).
77 /// Test: `compaction::tests::for_context_window_scales_threshold_proportionally`,
78 /// `compaction::tests::should_compact_does_not_trigger_at_10k_tokens_against_200k_window`,
79 /// `compaction::tests::should_compact_triggers_near_75pct_of_200k_window`.
80 pub fn for_context_window(context_window: usize) -> Self {
81 Self {
82 token_threshold: context_window * COMPACTION_THRESHOLD_FRACTION_PCT / 100,
83 keep_last_messages: 6,
84 }
85 }
86}
87
88impl Default for CompactionConfig {
89 /// LEGACY/TEST-ONLY default — a flat, model-blind `6_000`-token threshold.
90 ///
91 /// Why: This was the pre-#2308 production default; the root cause of
92 /// #2308's pathological re-compaction (roughly every 2 turns at
93 /// 4-13K estimated tokens) is exactly this hard-coded constant, which is
94 /// only ~3% of a real Bedrock Claude Sonnet 200K-token context window.
95 /// Kept for back-compat (tests that want a small, deterministic
96 /// threshold without wiring a model slug) but production code must call
97 /// [`CompactionConfig::for_context_window`] instead so the threshold
98 /// scales with the model actually in use.
99 /// What: §5.4 gives no exact numbers; these defaults keep several full
100 /// tool-call round-trips (a handful of assistant+tool pairs) uncompacted
101 /// while triggering well before a typical model's context window is at
102 /// risk — but ONLY for a small/unknown context window; see
103 /// [`CompactionConfig::for_context_window`] for the model-aware
104 /// production path.
105 fn default() -> Self {
106 Self {
107 token_threshold: 6_000,
108 keep_last_messages: 6,
109 }
110 }
111}
112
113/// Estimate the token count of a text span using a cheap chars/4 heuristic.
114///
115/// Why: The agent loop has no tokenizer dependency today and adding one only
116/// to gate a compaction trigger would be disproportionate; the standard
117/// chars-divided-by-four rule of thumb is accurate enough to decide "is this
118/// transcript getting large", which is all the trigger needs.
119/// What: Returns `text.chars().count() / 4`, floor-divided.
120/// Test: `compaction::tests::estimate_tokens_uses_chars_over_four`.
121pub fn estimate_tokens(text: &str) -> usize {
122 text.chars().count() / 4
123}
124
125/// Sum the estimated token count across a span of messages.
126///
127/// Why: The trigger decision operates on the whole transcript's estimated
128/// size, not any single message. (#2261) `content` alone systematically
129/// undercounts coding sessions: `write_file`/`edit` tool calls carry their
130/// argument bodies (the actual file contents being written) in
131/// `ChatMessage.tool_calls[].function.arguments`, not `content` — an
132/// assistant turn that only calls a tool has `content: None` entirely. A
133/// real segment measured at 23,541 tokens (by this same heuristic applied to
134/// the full request body) never compacted under the old content-only sum
135/// because the default `token_threshold: 6_000` was never crossed.
136/// What: Sums `estimate_tokens` over each message's `content` PLUS, for
137/// every entry in `tool_calls`, `estimate_tokens` over that call's
138/// `function.arguments` JSON string. Role/name overhead is still
139/// intentionally ignored — the heuristic only needs to track growth trend,
140/// not byte-exact accounting.
141/// Test: `compaction::tests::estimate_total_tokens_sums_content`,
142/// `compaction::tests::estimate_total_tokens_sums_tool_call_arguments`.
143pub fn estimate_total_tokens(messages: &[ChatMessage]) -> usize {
144 messages
145 .iter()
146 .map(|m| {
147 let content_tokens = estimate_tokens(m.content.as_deref().unwrap_or_default());
148 let tool_call_tokens: usize = m
149 .tool_calls
150 .iter()
151 .flatten()
152 .map(|call| estimate_tokens(&call.function.arguments))
153 .sum();
154 content_tokens + tool_call_tokens
155 })
156 .sum()
157}
158
159/// Whether the transcript's estimated size warrants compaction.
160///
161/// Why: Centralises the threshold comparison so `Transcript::maybe_compact`
162/// reads as policy application, not arithmetic.
163/// What: `true` when `estimate_total_tokens(messages) > cfg.token_threshold`.
164/// Test: `compaction::tests::should_compact_respects_threshold`.
165pub fn should_compact(messages: &[ChatMessage], cfg: &CompactionConfig) -> bool {
166 estimate_total_tokens(messages) > cfg.token_threshold
167}
168
169/// Build a deterministic one-line summary of a span of messages being
170/// compacted (§5.4 item 2: "Replace their content with a one-line summary").
171///
172/// Why: A real LLM-generated summary would require a synchronous network
173/// call in the middle of the loop's turn boundary — expensive, and a new
174/// failure mode compaction must not introduce. A deterministic summary built
175/// from role counts and invoked tool names is cheap, always available, and
176/// gives the model (and a human auditor) enough of a pointer to know what was
177/// elided.
178/// What: Counts assistant/tool/other messages in `span` and collects the
179/// distinct tool names named in `tool` role messages (via their `name`
180/// field), rendering `"[compacted N earlier messages: A assistant turn(s),
181/// T tool call(s) (name1, name2, ...)]"`. Returns a fixed placeholder for an
182/// empty span (should not occur in practice, but must not panic).
183/// Test: `compaction::tests::summarize_span_counts_roles_and_tools`,
184/// `compaction::tests::summarize_span_handles_empty_span`.
185pub fn summarize_span(span: &[ChatMessage]) -> String {
186 if span.is_empty() {
187 return "[compacted 0 earlier messages]".to_string();
188 }
189
190 let assistant_count = span.iter().filter(|m| m.role == "assistant").count();
191 let mut tool_names: Vec<&str> = span
192 .iter()
193 .filter(|m| m.role == "tool")
194 .filter_map(|m| m.name.as_deref())
195 .collect();
196 tool_names.sort_unstable();
197 tool_names.dedup();
198
199 let tool_count = span.iter().filter(|m| m.role == "tool").count();
200 let tools_suffix = if tool_names.is_empty() {
201 String::new()
202 } else {
203 format!(" ({})", tool_names.join(", "))
204 };
205
206 format!(
207 "[compacted {} earlier message{}: {} assistant turn{}, {} tool call{}{}]",
208 span.len(),
209 plural_suffix(span.len()),
210 assistant_count,
211 plural_suffix(assistant_count),
212 tool_count,
213 plural_suffix(tool_count),
214 tools_suffix,
215 )
216}
217
218/// Return `"s"` unless `n == 1`, for readable pluralisation in the summary.
219fn plural_suffix(n: usize) -> &'static str {
220 if n == 1 { "" } else { "s" }
221}
222
223// ── Tests ─────────────────────────────────────────────────────────────────────
224
225#[cfg(test)]
226mod tests {
227 use super::*;
228
229 fn tool_msg(name: &str) -> ChatMessage {
230 ChatMessage::tool_result("call_1", name, "result")
231 }
232
233 #[test]
234 fn default_is_sane() {
235 let cfg = CompactionConfig::default();
236 assert!(cfg.token_threshold > 0);
237 assert!(cfg.keep_last_messages > 0);
238 }
239
240 #[test]
241 fn estimate_tokens_uses_chars_over_four() {
242 assert_eq!(estimate_tokens("abcd"), 1);
243 assert_eq!(estimate_tokens("abcdefgh"), 2);
244 assert_eq!(estimate_tokens(""), 0);
245 }
246
247 #[test]
248 fn estimate_total_tokens_sums_content() {
249 let messages = vec![
250 ChatMessage::user("abcd"),
251 ChatMessage::assistant("abcdefgh"),
252 ];
253 assert_eq!(estimate_total_tokens(&messages), 3);
254 }
255
256 /// A tool-call-only assistant turn (`content: None`, arguments carrying
257 /// the actual payload — e.g. a `write_file` body) contributes its
258 /// argument-string tokens to the total, not zero (#2261).
259 ///
260 /// Why: This is the exact bug #2261 reports: `estimate_total_tokens`
261 /// previously summed only `content`, so a transcript whose size lives
262 /// entirely in `write_file`/`edit` tool-call arguments was invisible to
263 /// the compaction trigger — `should_compact` never fired regardless of
264 /// how large those arguments grew.
265 /// What: Build an assistant message with `content: None` and one
266 /// `tool_calls` entry whose `function.arguments` is a known-length JSON
267 /// string; assert the total equals `estimate_tokens` of that arguments
268 /// string (content contributes 0 since it's `None`).
269 /// Test: this test.
270 #[test]
271 fn estimate_total_tokens_sums_tool_call_arguments() {
272 use crate::llm::{FunctionCall, ToolCall};
273
274 let arguments = r#"{"path":"src/main.rs","content":"fn main() {}"}"#;
275 let messages = vec![ChatMessage {
276 role: "assistant".into(),
277 content: None,
278 tool_calls: Some(vec![ToolCall {
279 id: "call_1".into(),
280 kind: "function".into(),
281 function: FunctionCall {
282 name: "write_file".into(),
283 arguments: arguments.into(),
284 },
285 }]),
286 tool_call_id: None,
287 name: None,
288 cache_control: None,
289 }];
290
291 assert_eq!(estimate_total_tokens(&messages), estimate_tokens(arguments));
292 }
293
294 /// A transcript whose size comes entirely from `write_file`/`edit`
295 /// tool-call arguments now crosses `should_compact`'s threshold, even
296 /// though every message's `content` is empty or trivial (#2261).
297 ///
298 /// Why: Reproduces the reported real-world case — a segment measured at
299 /// 23,541 real tokens that compacted zero times because the default
300 /// `token_threshold: 6_000` was gated on `content` alone.
301 /// What: Build a small transcript whose only assistant turn carries a
302 /// large `write_file` argument body (well over the default threshold)
303 /// and a matching `tool` result; assert `should_compact` now returns
304 /// `true` against `CompactionConfig::default()`.
305 /// Test: this test.
306 #[test]
307 fn should_compact_triggers_on_large_tool_call_arguments() {
308 use crate::llm::{FunctionCall, ToolCall};
309
310 // ~9,000 chars -> ~2,250 estimated tokens per call; three calls sum
311 // to ~6,750 tokens, comfortably clearing the 6,000-token default
312 // threshold via tool_calls alone, with every `content` field left
313 // `None`/trivial.
314 let big_content = "x".repeat(9_000);
315 let mut messages = vec![ChatMessage::system("s"), ChatMessage::user("do the thing")];
316 for i in 0..3 {
317 messages.push(ChatMessage {
318 role: "assistant".into(),
319 content: None,
320 tool_calls: Some(vec![ToolCall {
321 id: format!("call_{i}"),
322 kind: "function".into(),
323 function: FunctionCall {
324 name: "write_file".into(),
325 arguments: format!(r#"{{"content":"{big_content}"}}"#),
326 },
327 }]),
328 tool_call_id: None,
329 name: None,
330 cache_control: None,
331 });
332 messages.push(ChatMessage::tool_result(
333 format!("call_{i}"),
334 "write_file",
335 "ok",
336 ));
337 }
338
339 assert!(should_compact(&messages, &CompactionConfig::default()));
340 }
341
342 #[test]
343 fn should_compact_respects_threshold() {
344 let cfg = CompactionConfig {
345 token_threshold: 2,
346 keep_last_messages: 1,
347 };
348 let small = vec![ChatMessage::user("ab")];
349 let large = vec![ChatMessage::user("abcdefghijkl")];
350 assert!(!should_compact(&small, &cfg));
351 assert!(should_compact(&large, &cfg));
352 }
353
354 // ── #2308: model-aware compaction threshold ─────────────────────────────
355
356 /// `for_context_window` scales the threshold proportionally to the
357 /// window size, for both a large (Bedrock-sized) and a small window.
358 ///
359 /// Why: This is the direct regression guard for the fix itself — the
360 /// threshold must track [`COMPACTION_THRESHOLD_FRACTION_PCT`] of
361 /// whatever window is passed in, not a flat constant.
362 /// What: 200,000 -> threshold within the 70-80% band (140,000-160,000);
363 /// 8,000 -> threshold scales down proportionally (5,600-6,400) rather
364 /// than staying pinned at a large absolute number.
365 /// Test: this test.
366 #[test]
367 fn for_context_window_scales_threshold_proportionally() {
368 let large = CompactionConfig::for_context_window(200_000);
369 assert!(
370 (140_000..=160_000).contains(&large.token_threshold),
371 "expected ~75% of 200_000, got {}",
372 large.token_threshold
373 );
374
375 let small = CompactionConfig::for_context_window(8_000);
376 assert!(
377 (5_600..=6_400).contains(&small.token_threshold),
378 "expected ~75% of 8_000, got {}",
379 small.token_threshold
380 );
381 }
382
383 /// The exact #2308 failure case: a ~10K-estimated-token transcript must
384 /// NOT trigger compaction against a 200K-window model's config.
385 ///
386 /// Why: Under the old flat `token_threshold: 6_000` default, a transcript
387 /// this size compacted almost immediately even though it's only ~5% of a
388 /// real 200K-token Bedrock Claude Sonnet window — the exact
389 /// "re-anchor thrash" this issue reports.
390 /// What: Build a transcript whose `estimate_total_tokens` is ~10,000
391 /// (via a single large user message, well within chars/4 rounding) and
392 /// assert `should_compact` is `false` against
393 /// `CompactionConfig::for_context_window(200_000)`.
394 /// Test: this test.
395 #[test]
396 fn should_compact_does_not_trigger_at_10k_tokens_against_200k_window() {
397 // 40_000 chars / 4 == 10_000 estimated tokens.
398 let messages = vec![ChatMessage::user("x".repeat(40_000))];
399 assert_eq!(estimate_total_tokens(&messages), 10_000);
400
401 let cfg = CompactionConfig::for_context_window(200_000);
402 assert!(
403 !should_compact(&messages, &cfg),
404 "a 10K-token transcript must not compact against a 200K-window model"
405 );
406 }
407
408 /// Compaction still fires once a transcript crosses ~75% of a 200K
409 /// window — the fix must not disable compaction outright.
410 ///
411 /// Why: The fix scales the threshold; it must not remove it. A
412 /// transcript genuinely approaching the model's real context limit must
413 /// still trigger compaction.
414 /// What: Build a transcript just over 150,000 estimated tokens and assert
415 /// `should_compact` is `true` against
416 /// `CompactionConfig::for_context_window(200_000)`.
417 /// Test: this test.
418 #[test]
419 fn should_compact_triggers_near_75pct_of_200k_window() {
420 // 601_000 chars / 4 == 150_250 estimated tokens, just over the
421 // 150_000 (75% of 200_000) threshold.
422 let messages = vec![ChatMessage::user("x".repeat(601_000))];
423 let cfg = CompactionConfig::for_context_window(200_000);
424 assert!(
425 should_compact(&messages, &cfg),
426 "a transcript just over 75% of the window must trigger compaction"
427 );
428 }
429
430 /// `estimate_total_tokens` applies the SAME units to content and to
431 /// tool-call arguments — no hidden scaling bug between the two.
432 ///
433 /// Why: Directly guards the "units" invariant the research for #2308
434 /// verified but which this fix must not regress: a content-only message
435 /// and a tool-call-only message of identical string length must produce
436 /// identical estimates.
437 /// What: Build one message with `content: Some(s)` and one with
438 /// `content: None` plus a single tool call whose `arguments` is the same
439 /// string `s`; assert both totals are equal.
440 /// Test: this test.
441 #[test]
442 fn estimate_total_tokens_units_match_between_content_and_tool_args() {
443 use crate::llm::{FunctionCall, ToolCall};
444
445 let s = "y".repeat(1000);
446
447 let content_only = vec![ChatMessage::assistant(s.clone())];
448 let tool_call_only = vec![ChatMessage {
449 role: "assistant".into(),
450 content: None,
451 tool_calls: Some(vec![ToolCall {
452 id: "call_1".into(),
453 kind: "function".into(),
454 function: FunctionCall {
455 name: "write_file".into(),
456 arguments: s.clone(),
457 },
458 }]),
459 tool_call_id: None,
460 name: None,
461 cache_control: None,
462 }];
463
464 assert_eq!(
465 estimate_total_tokens(&content_only),
466 estimate_total_tokens(&tool_call_only)
467 );
468 }
469
470 #[test]
471 fn summarize_span_counts_roles_and_tools() {
472 let span = vec![
473 ChatMessage::assistant("thinking"),
474 tool_msg("bash"),
475 tool_msg("read_file"),
476 tool_msg("bash"),
477 ];
478 let summary = summarize_span(&span);
479 assert!(summary.contains("4 earlier messages"));
480 assert!(summary.contains("1 assistant turn"));
481 assert!(summary.contains("3 tool calls"));
482 assert!(summary.contains("bash"));
483 assert!(summary.contains("read_file"));
484 }
485
486 #[test]
487 fn summarize_span_handles_empty_span() {
488 assert_eq!(summarize_span(&[]), "[compacted 0 earlier messages]");
489 }
490}