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 images: vec![],
279 tool_calls: Some(vec![ToolCall {
280 id: "call_1".into(),
281 kind: "function".into(),
282 function: FunctionCall {
283 name: "write_file".into(),
284 arguments: arguments.into(),
285 },
286 }]),
287 tool_call_id: None,
288 name: None,
289 cache_control: None,
290 }];
291
292 assert_eq!(estimate_total_tokens(&messages), estimate_tokens(arguments));
293 }
294
295 /// A transcript whose size comes entirely from `write_file`/`edit`
296 /// tool-call arguments now crosses `should_compact`'s threshold, even
297 /// though every message's `content` is empty or trivial (#2261).
298 ///
299 /// Why: Reproduces the reported real-world case — a segment measured at
300 /// 23,541 real tokens that compacted zero times because the default
301 /// `token_threshold: 6_000` was gated on `content` alone.
302 /// What: Build a small transcript whose only assistant turn carries a
303 /// large `write_file` argument body (well over the default threshold)
304 /// and a matching `tool` result; assert `should_compact` now returns
305 /// `true` against `CompactionConfig::default()`.
306 /// Test: this test.
307 #[test]
308 fn should_compact_triggers_on_large_tool_call_arguments() {
309 use crate::llm::{FunctionCall, ToolCall};
310
311 // ~9,000 chars -> ~2,250 estimated tokens per call; three calls sum
312 // to ~6,750 tokens, comfortably clearing the 6,000-token default
313 // threshold via tool_calls alone, with every `content` field left
314 // `None`/trivial.
315 let big_content = "x".repeat(9_000);
316 let mut messages = vec![ChatMessage::system("s"), ChatMessage::user("do the thing")];
317 for i in 0..3 {
318 messages.push(ChatMessage {
319 role: "assistant".into(),
320 content: None,
321 images: vec![],
322 tool_calls: Some(vec![ToolCall {
323 id: format!("call_{i}"),
324 kind: "function".into(),
325 function: FunctionCall {
326 name: "write_file".into(),
327 arguments: format!(r#"{{"content":"{big_content}"}}"#),
328 },
329 }]),
330 tool_call_id: None,
331 name: None,
332 cache_control: None,
333 });
334 messages.push(ChatMessage::tool_result(
335 format!("call_{i}"),
336 "write_file",
337 "ok",
338 ));
339 }
340
341 assert!(should_compact(&messages, &CompactionConfig::default()));
342 }
343
344 #[test]
345 fn should_compact_respects_threshold() {
346 let cfg = CompactionConfig {
347 token_threshold: 2,
348 keep_last_messages: 1,
349 };
350 let small = vec![ChatMessage::user("ab")];
351 let large = vec![ChatMessage::user("abcdefghijkl")];
352 assert!(!should_compact(&small, &cfg));
353 assert!(should_compact(&large, &cfg));
354 }
355
356 // ── #2308: model-aware compaction threshold ─────────────────────────────
357
358 /// `for_context_window` scales the threshold proportionally to the
359 /// window size, for both a large (Bedrock-sized) and a small window.
360 ///
361 /// Why: This is the direct regression guard for the fix itself — the
362 /// threshold must track [`COMPACTION_THRESHOLD_FRACTION_PCT`] of
363 /// whatever window is passed in, not a flat constant.
364 /// What: 200,000 -> threshold within the 70-80% band (140,000-160,000);
365 /// 8,000 -> threshold scales down proportionally (5,600-6,400) rather
366 /// than staying pinned at a large absolute number.
367 /// Test: this test.
368 #[test]
369 fn for_context_window_scales_threshold_proportionally() {
370 let large = CompactionConfig::for_context_window(200_000);
371 assert!(
372 (140_000..=160_000).contains(&large.token_threshold),
373 "expected ~75% of 200_000, got {}",
374 large.token_threshold
375 );
376
377 let small = CompactionConfig::for_context_window(8_000);
378 assert!(
379 (5_600..=6_400).contains(&small.token_threshold),
380 "expected ~75% of 8_000, got {}",
381 small.token_threshold
382 );
383 }
384
385 /// The exact #2308 failure case: a ~10K-estimated-token transcript must
386 /// NOT trigger compaction against a 200K-window model's config.
387 ///
388 /// Why: Under the old flat `token_threshold: 6_000` default, a transcript
389 /// this size compacted almost immediately even though it's only ~5% of a
390 /// real 200K-token Bedrock Claude Sonnet window — the exact
391 /// "re-anchor thrash" this issue reports.
392 /// What: Build a transcript whose `estimate_total_tokens` is ~10,000
393 /// (via a single large user message, well within chars/4 rounding) and
394 /// assert `should_compact` is `false` against
395 /// `CompactionConfig::for_context_window(200_000)`.
396 /// Test: this test.
397 #[test]
398 fn should_compact_does_not_trigger_at_10k_tokens_against_200k_window() {
399 // 40_000 chars / 4 == 10_000 estimated tokens.
400 let messages = vec![ChatMessage::user("x".repeat(40_000))];
401 assert_eq!(estimate_total_tokens(&messages), 10_000);
402
403 let cfg = CompactionConfig::for_context_window(200_000);
404 assert!(
405 !should_compact(&messages, &cfg),
406 "a 10K-token transcript must not compact against a 200K-window model"
407 );
408 }
409
410 /// Compaction still fires once a transcript crosses ~75% of a 200K
411 /// window — the fix must not disable compaction outright.
412 ///
413 /// Why: The fix scales the threshold; it must not remove it. A
414 /// transcript genuinely approaching the model's real context limit must
415 /// still trigger compaction.
416 /// What: Build a transcript just over 150,000 estimated tokens and assert
417 /// `should_compact` is `true` against
418 /// `CompactionConfig::for_context_window(200_000)`.
419 /// Test: this test.
420 #[test]
421 fn should_compact_triggers_near_75pct_of_200k_window() {
422 // 601_000 chars / 4 == 150_250 estimated tokens, just over the
423 // 150_000 (75% of 200_000) threshold.
424 let messages = vec![ChatMessage::user("x".repeat(601_000))];
425 let cfg = CompactionConfig::for_context_window(200_000);
426 assert!(
427 should_compact(&messages, &cfg),
428 "a transcript just over 75% of the window must trigger compaction"
429 );
430 }
431
432 /// `estimate_total_tokens` applies the SAME units to content and to
433 /// tool-call arguments — no hidden scaling bug between the two.
434 ///
435 /// Why: Directly guards the "units" invariant the research for #2308
436 /// verified but which this fix must not regress: a content-only message
437 /// and a tool-call-only message of identical string length must produce
438 /// identical estimates.
439 /// What: Build one message with `content: Some(s)` and one with
440 /// `content: None` plus a single tool call whose `arguments` is the same
441 /// string `s`; assert both totals are equal.
442 /// Test: this test.
443 #[test]
444 fn estimate_total_tokens_units_match_between_content_and_tool_args() {
445 use crate::llm::{FunctionCall, ToolCall};
446
447 let s = "y".repeat(1000);
448
449 let content_only = vec![ChatMessage::assistant(s.clone())];
450 let tool_call_only = vec![ChatMessage {
451 role: "assistant".into(),
452 content: None,
453 images: vec![],
454 tool_calls: Some(vec![ToolCall {
455 id: "call_1".into(),
456 kind: "function".into(),
457 function: FunctionCall {
458 name: "write_file".into(),
459 arguments: s.clone(),
460 },
461 }]),
462 tool_call_id: None,
463 name: None,
464 cache_control: None,
465 }];
466
467 assert_eq!(
468 estimate_total_tokens(&content_only),
469 estimate_total_tokens(&tool_call_only)
470 );
471 }
472
473 #[test]
474 fn summarize_span_counts_roles_and_tools() {
475 let span = vec![
476 ChatMessage::assistant("thinking"),
477 tool_msg("bash"),
478 tool_msg("read_file"),
479 tool_msg("bash"),
480 ];
481 let summary = summarize_span(&span);
482 assert!(summary.contains("4 earlier messages"));
483 assert!(summary.contains("1 assistant turn"));
484 assert!(summary.contains("3 tool calls"));
485 assert!(summary.contains("bash"));
486 assert!(summary.contains("read_file"));
487 }
488
489 #[test]
490 fn summarize_span_handles_empty_span() {
491 assert_eq!(summarize_span(&[]), "[compacted 0 earlier messages]");
492 }
493}