trusty_code/task/mock_llm_soak_load.rs
1//! [`SoakLoadEchoLlmClient`] — the scripted `InferenceAdapter` behind
2//! `TCODE_MOCK_LLM=echo-soak-load` (epic #3866, follow-up to #3869/PR #3887).
3//! Sibling of [`super::mock_llm_soak::SoakEchoLlmClient`], same 7-turn/call,
4//! resumable-`stop`-ending shape (see that module's docs for why 7, not 8,
5//! and why the client must be re-constructed per `task.run` call) — the
6//! ONLY difference is the SIZE of every non-`clear_goal` turn's argument.
7//!
8//! Why: PR #3887's soak (issue #3869) proved the #2346 cadence mechanism
9//! *functions* (28 fires, 0 threshold-compaction events, working-context
10//! floor 94-95%) but its own report flagged, as the single biggest caveat,
11//! that it never got anywhere near the 60%-floor boundary: `SoakEchoLlmClient`
12//! carries five near-empty turns (~20-30 bytes) and exactly ONE ~8 KB
13//! oversized turn per call — peak overhead measured ~7% of a 200K window,
14//! nowhere near the 80K-token/40%-overhead cap the epic's guarantee is
15//! actually about. This client is the follow-up soak that report called for:
16//! every `set_goal` turn (not one in six) now carries a payload sized to
17//! approximate a REAL tool-output magnitude a long coding session
18//! accumulates — a multi-file `git diff`, a `grep`/search-result dump, a
19//! `cargo test` failure log — so a single `task.run` call's active zone
20//! alone approaches or exceeds the 80K-token cap on a 200K window, forcing
21//! [`cadence::enforce_budget`]'s continuous per-turn path to actually
22//! compact on (most) turns, not just once per soak.
23//! What: same 3x (`set_goal`/`clear_goal`) pair + bare `stop` shape as
24//! [`super::mock_llm_soak::SoakEchoLlmClient`], but the three `set_goal`
25//! payloads are [`LOAD_PAYLOAD_BYTES`] — representative sizes for
26//! (in order) a large `git diff`, a `grep -r`-sized result dump, and a
27//! `cargo test` failure log, chosen so their SUM (~172K estimated tokens at
28//! this crate's chars/4 heuristic) is well past the 80K-token cap
29//! (`CadenceConfig::default().overhead_cap_tokens(200_000)`) within ONE
30//! call, not just cumulatively across the whole soak. Empirically (see the
31//! epic #3866 load-soak evidence this client produced) this size drives the
32//! measured working-context floor down to exactly the 60% target boundary
33//! (60-61% on a 245-turn run, 126 cadence-fire samples) — i.e. it is sized
34//! to find the guarantee's edge, not comfortably clear it. A follow-up,
35//! deliberately MORE extreme payload (~230K tokens/call) was used
36//! exploratively (not shipped as the default here) and reproducibly drove
37//! the floor down to 48% — a genuine breach of the 60% target — while the
38//! independent threshold/fallback compactor still never fired and session
39//! fidelity (goal state, transcript, resumability) still held; see the
40//! evidence doc for the full writeup of both runs. On that "independent":
41//! the zero-fire signals this client's soak observes (JSONL, `TranscriptRecord.
42//! compaction_events`, `lifetime_compaction_alarm_count`) all derive from one
43//! shared detection call site in `agent_loop::compaction_control` — see
44//! `crates/trusty-code/scripts/compression_load_soak.py`'s fidelity-check
45//! comment and the evidence doc's Driver section for what that does and does
46//! not rule out. [`synthetic_tool_output`]'s payload text is shaped to look
47//! like a real diff/log for a human reading the evidence, but text SHAPE is
48//! not itself a measured variable here — only `payload_bytes` is; see that
49//! function's docs.
50//! Test: `tests::soak_load_script_ends_in_a_resumable_stop_and_sums_past_the_default_cap`.
51
52use super::*;
53
54/// Per-turn `set_goal` payload sizes (bytes), in script order — representative
55/// of a large `git diff`, a `grep`/search-result dump, and a `cargo test`
56/// failure log respectively. Chosen so the three SUM
57/// (`LOAD_PAYLOAD_BYTES.iter().sum::<usize>() / 4` estimated tokens) exceeds
58/// `CadenceConfig::default().overhead_cap_tokens(200_000)` (80,000) — see
59/// module docs for the empirical floor this size drives (60-61%, right at
60/// the epic's target boundary).
61const LOAD_PAYLOAD_BYTES: [usize; 3] = [160_000, 230_000, 300_000];
62
63/// Escape-hatch env var overriding [`LOAD_PAYLOAD_BYTES`] for one process —
64/// three comma-separated `usize` values, e.g.
65/// `TCODE_SOAK_LOAD_PAYLOAD_BYTES=220000,300000,400000` to reproduce this
66/// soak's exploratory FAIL profile without hand-editing this file and
67/// rebuilding (issue raised in epic #3866 load-soak review: a future soak
68/// against #3911's backstop will need to re-run this heavier profile). An
69/// unset var, or a value that doesn't parse as exactly three
70/// comma-separated `usize`s, silently falls back to
71/// [`LOAD_PAYLOAD_BYTES`] — never an error, matching every other escape
72/// hatch in this crate's mock-LLM/cadence config
73/// (`cadence::CADENCE_TURNS_ENV_VAR`'s identical graceful-degrade
74/// convention).
75/// Test: `tests::payload_bytes_env_override_parses_three_values_or_falls_back_to_default`.
76pub const LOAD_PAYLOAD_BYTES_ENV_VAR: &str = "TCODE_SOAK_LOAD_PAYLOAD_BYTES";
77
78/// Resolve the per-turn payload sizes: [`LOAD_PAYLOAD_BYTES_ENV_VAR`] when
79/// set to three valid comma-separated `usize`s, otherwise
80/// [`LOAD_PAYLOAD_BYTES`]. See [`LOAD_PAYLOAD_BYTES_ENV_VAR`]'s docs.
81fn resolve_payload_bytes() -> [usize; 3] {
82 let Ok(raw) = std::env::var(LOAD_PAYLOAD_BYTES_ENV_VAR) else {
83 return LOAD_PAYLOAD_BYTES;
84 };
85 let parsed: Vec<usize> = raw
86 .split(',')
87 .filter_map(|s| s.trim().parse::<usize>().ok())
88 .collect();
89 match parsed.as_slice() {
90 [a, b, c] => [*a, *b, *c],
91 _ => {
92 tracing::warn!(
93 "{LOAD_PAYLOAD_BYTES_ENV_VAR}={raw:?} did not parse as three comma-separated \
94 usize values; keeping the default {LOAD_PAYLOAD_BYTES:?}"
95 );
96 LOAD_PAYLOAD_BYTES
97 }
98 }
99}
100
101/// A deterministic, offline `InferenceAdapter` driving load-realistic
102/// per-turn payload sizes for the compression-effectiveness follow-up soak
103/// (epic #3866).
104///
105/// Why/What: see module docs. Identical control flow to
106/// [`super::mock_llm_soak::SoakEchoLlmClient`] — only the argument sizes
107/// differ.
108/// Test: `tests::soak_load_script_ends_in_a_resumable_stop_and_sums_past_the_default_cap`.
109pub struct SoakLoadEchoLlmClient {
110 cursor: AtomicUsize,
111 /// Resolved once at construction via [`resolve_payload_bytes`] — see
112 /// [`LOAD_PAYLOAD_BYTES_ENV_VAR`]'s docs for the override.
113 payload_bytes: [usize; 3],
114}
115
116impl SoakLoadEchoLlmClient {
117 /// Construct a fresh client at the start of its script, resolving
118 /// per-turn payload sizes from [`LOAD_PAYLOAD_BYTES_ENV_VAR`]
119 /// (falling back to [`LOAD_PAYLOAD_BYTES`]).
120 pub fn new() -> Self {
121 Self {
122 cursor: AtomicUsize::new(0),
123 payload_bytes: resolve_payload_bytes(),
124 }
125 }
126}
127
128impl Default for SoakLoadEchoLlmClient {
129 fn default() -> Self {
130 Self::new()
131 }
132}
133
134#[async_trait]
135impl InferenceAdapter for SoakLoadEchoLlmClient {
136 crate::llm::mock_adapter_identity!("mock-soak-load-echo");
137
138 async fn chat(&self, _req: &ChatRequest) -> Result<ChatResponse, InferenceError> {
139 let idx = self.cursor.fetch_add(1, Ordering::SeqCst);
140 let fixture = match idx {
141 0 => load_goal_tool_call(idx, 1, self.payload_bytes[0]),
142 1 => load_clear_goal_tool_call(idx, 1),
143 2 => load_goal_tool_call(idx, 2, self.payload_bytes[1]),
144 3 => load_clear_goal_tool_call(idx, 2),
145 4 => load_goal_tool_call(idx, 3, self.payload_bytes[2]),
146 5 => load_clear_goal_tool_call(idx, 3),
147 6 => load_stop_fixture(),
148 _ => {
149 return Err(InferenceError::MissingConfig(format!(
150 "SoakLoadEchoLlmClient script exhausted at call {idx}"
151 )));
152 }
153 };
154 serde_json::from_value(fixture).map_err(|e| {
155 InferenceError::MissingConfig(format!(
156 "SoakLoadEchoLlmClient: invalid scripted fixture: {e}"
157 ))
158 })
159 }
160}
161
162/// Build a `set_goal(slot, text)` tool-call fixture carrying a
163/// `payload_bytes`-sized body shaped to visually resemble a real tool
164/// output (readable evidence, not a measurement variable — see
165/// [`synthetic_tool_output`]'s docs for why byte count, not text shape, is
166/// what actually drives every number this soak reports).
167fn load_goal_tool_call(idx: usize, slot: usize, payload_bytes: usize) -> Value {
168 let text = synthetic_tool_output(payload_bytes);
169 json!({
170 "id": "mock-soak-load-set",
171 "choices": [{
172 "message": {
173 "role": "assistant",
174 "content": null,
175 "tool_calls": [{
176 "id": format!("call-soak-load-{idx}"),
177 "type": "function",
178 "function": {
179 "name": "set_goal",
180 "arguments": json!({"slot": slot, "text": text}).to_string()
181 }
182 }]
183 },
184 "finish_reason": "tool_calls"
185 }],
186 "usage": {"prompt_tokens": 15, "completion_tokens": 5, "total_tokens": 20}
187 })
188}
189
190/// Build a `clear_goal(slot)` tool-call fixture — deliberately tiny (mirrors
191/// `super::mock_llm_soak::soak_clear_goal_tool_call`) so every large
192/// contribution to the transcript comes from the `set_goal` turns above,
193/// keeping the per-turn size attribution unambiguous when reading the
194/// resulting `compression.jsonl`.
195fn load_clear_goal_tool_call(idx: usize, slot: usize) -> Value {
196 json!({
197 "id": "mock-soak-load-clear",
198 "choices": [{
199 "message": {
200 "role": "assistant",
201 "content": null,
202 "tool_calls": [{
203 "id": format!("call-soak-load-{idx}"),
204 "type": "function",
205 "function": {
206 "name": "clear_goal",
207 "arguments": json!({"slot": slot}).to_string()
208 }
209 }]
210 },
211 "finish_reason": "tool_calls"
212 }],
213 "usage": {"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15}
214 })
215}
216
217/// The final, no-tool-calls fixture — see
218/// `super::mock_llm_soak::stop_fixture`'s identical rationale.
219fn load_stop_fixture() -> Value {
220 json!({
221 "id": "mock-soak-load-stop",
222 "choices": [{
223 "message": {"role": "assistant", "content": "soak-load call complete", "tool_calls": []},
224 "finish_reason": "stop"
225 }],
226 "usage": {"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15}
227 })
228}
229
230/// Synthesize `target_bytes` of line-oriented text visually resembling a
231/// real tool output (unified-diff hunks, `grep path:line:match` rows,
232/// `cargo test` `FAILED`/panic/assertion lines), cycling a handful of
233/// realistic line templates until `target_bytes` is reached, rather than one
234/// giant repeated-character blob.
235///
236/// **Text shape is NOT a validated variable in this soak — only
237/// `payload_bytes` (`LOAD_PAYLOAD_BYTES`) is.** Every measurement this soak
238/// reports comes from a path that is content-blind: `estimate_tokens` is
239/// `text.chars().count() / 4` (`agent_loop::compaction::estimate_tokens`) —
240/// pure byte/char count, no parsing; `enforce_budget`/`resolve_keep_from`
241/// evict whole messages by position, never by content; and
242/// `summarize_span` replaces an evicted span with a small fixed-format
243/// placeholder regardless of what was in it. A `"x".repeat(target_bytes)`
244/// blob of the same length would produce byte-for-byte identical
245/// `tokens_before`/`tokens_after`/`ratio`/floor numbers to what this
246/// generator produces. The realistic line shapes exist purely so a human
247/// reading the committed JSONL/evidence sees plausible-looking content
248/// instead of a wall of `x` — a readability choice for this soak's evidence
249/// artifacts, not something that changes, or was measured to change, any
250/// reported result. This also bounds what the soak does and does not test:
251/// it says nothing about whether a content-AWARE compaction strategy (e.g.
252/// one that tried to preserve high-signal diff lines over boilerplate)
253/// would behave differently — this crate's actual compaction path has no
254/// such strategy to test.
255fn synthetic_tool_output(target_bytes: usize) -> String {
256 const LINE_TEMPLATES: [&str; 6] = [
257 "+ let result = compute_budget(&transcript, cadence_cfg, keep_last_messages);\n",
258 "- let result = compute_budget(&transcript, keep_last_messages);\n",
259 "src/agent_loop/cadence.rs:187: match maybe_cadence_compress(&mut transcript) {\n",
260 "test agent_loop::cadence::tests::stays_under_budget_every_turn ... FAILED\n",
261 "thread 'cadence::tests' panicked at src/agent_loop/cadence_tests.rs:412:9:\n",
262 "assertion `left == right` failed: overhead_tokens exceeded cap_tokens\n",
263 ];
264 let mut out = String::with_capacity(target_bytes + 128);
265 let mut i = 0usize;
266 while out.len() < target_bytes {
267 out.push_str(LINE_TEMPLATES[i % LINE_TEMPLATES.len()]);
268 i += 1;
269 }
270 out
271}
272
273#[cfg(test)]
274mod tests {
275 use super::*;
276 use crate::agent_loop::CadenceConfig;
277
278 /// Serializes every test in this module that mutates
279 /// [`LOAD_PAYLOAD_BYTES_ENV_VAR`], mirroring `telemetry::DATA_DIR_ENV_LOCK`'s
280 /// identical rationale (`cargo test` runs this crate's tests in
281 /// parallel within one process, so concurrent env mutation of the same
282 /// var would race).
283 static PAYLOAD_BYTES_ENV_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
284
285 /// [`LOAD_PAYLOAD_BYTES_ENV_VAR`] set to three valid comma-separated
286 /// `usize`s overrides [`LOAD_PAYLOAD_BYTES`]; unset, or set to garbage,
287 /// falls back to the default rather than erroring — the documented
288 /// graceful-degrade contract new callers (e.g. a future soak re-running
289 /// the exploratory FAIL profile against #3911's backstop) rely on.
290 #[tokio::test]
291 async fn payload_bytes_env_override_parses_three_values_or_falls_back_to_default() {
292 let _guard = PAYLOAD_BYTES_ENV_LOCK.lock().await;
293
294 // SAFETY: test-only env mutation; serialized by `PAYLOAD_BYTES_ENV_LOCK`.
295 unsafe {
296 std::env::remove_var(LOAD_PAYLOAD_BYTES_ENV_VAR);
297 }
298 assert_eq!(
299 resolve_payload_bytes(),
300 LOAD_PAYLOAD_BYTES,
301 "unset falls back"
302 );
303
304 // SAFETY: test-only env mutation; serialized by `PAYLOAD_BYTES_ENV_LOCK`.
305 unsafe {
306 std::env::set_var(LOAD_PAYLOAD_BYTES_ENV_VAR, "220000,300000,400000");
307 }
308 assert_eq!(
309 resolve_payload_bytes(),
310 [220_000, 300_000, 400_000],
311 "three valid comma-separated values override the default"
312 );
313
314 // SAFETY: test-only env mutation; serialized by `PAYLOAD_BYTES_ENV_LOCK`.
315 unsafe {
316 std::env::set_var(LOAD_PAYLOAD_BYTES_ENV_VAR, "not-a-number");
317 }
318 assert_eq!(
319 resolve_payload_bytes(),
320 LOAD_PAYLOAD_BYTES,
321 "unparseable value falls back to the default, never panics/errors"
322 );
323
324 // SAFETY: test-only env mutation; serialized by `PAYLOAD_BYTES_ENV_LOCK`.
325 unsafe {
326 std::env::remove_var(LOAD_PAYLOAD_BYTES_ENV_VAR);
327 }
328 }
329
330 /// The script must be 7 calls long, ending in a bare `stop`, with the
331 /// three `set_goal` payloads' estimated tokens (chars/4, this crate's
332 /// `estimate_tokens` heuristic) summing to MORE than the default
333 /// 200K-window/40%-overhead cap (80,000) — the exact property that
334 /// makes this client "load-realistic" versus the original
335 /// `SoakEchoLlmClient`'s single ~8 KB one-off turn. If this regresses
336 /// (e.g. someone shrinks `LOAD_PAYLOAD_BYTES`), the whole point of this
337 /// harness variant is silently lost, so it's asserted directly here
338 /// rather than only discovered empirically against a live daemon.
339 #[tokio::test]
340 async fn soak_load_script_ends_in_a_resumable_stop_and_sums_past_the_default_cap() {
341 let cap = CadenceConfig::default().overhead_cap_tokens(200_000);
342 let total_estimated_tokens: usize = LOAD_PAYLOAD_BYTES.iter().map(|bytes| bytes / 4).sum();
343 assert!(
344 total_estimated_tokens > cap,
345 "load payload sum ({total_estimated_tokens} tokens) must exceed the default \
346 overhead cap ({cap} tokens) for this soak variant to be load-realistic"
347 );
348
349 let client = SoakLoadEchoLlmClient::new();
350 let req = ChatRequest {
351 model: "mock".to_string(),
352 messages: vec![],
353 temperature: None,
354 max_tokens: None,
355 tools: None,
356 tool_choice: None,
357 usage: None,
358 response_schema: None,
359 stop: None,
360 };
361
362 for i in 0..6 {
363 let resp = client
364 .chat(&req)
365 .await
366 .unwrap_or_else(|e| panic!("call {i}: {e}"));
367 let calls = resp.first_tool_calls();
368 assert_eq!(calls.len(), 1, "call {i} must be exactly one tool call");
369 }
370
371 // 7th call (idx 6): bare stop, no tool calls.
372 let stop = client.chat(&req).await.expect("call 6 (stop)");
373 assert!(
374 stop.first_tool_calls().is_empty(),
375 "final turn must have no tool calls"
376 );
377
378 // An 8th call must error, never panic or silently repeat.
379 let err = client.chat(&req).await;
380 assert!(
381 err.is_err(),
382 "the script must not silently repeat past its end"
383 );
384 }
385}