Skip to main content

trusty_code/task/
mock_llm_soak.rs

1//! [`SoakEchoLlmClient`] — the scripted `InferenceAdapter` behind
2//! `TCODE_MOCK_LLM=echo-soak` (issue #3869, epic #3866 Slice C). Split out
3//! of `task::mock_llm` (`#[path = "mock_llm_soak.rs"] mod mock_llm_soak;`)
4//! purely to keep that file under the crate's 500-SLOC cap — see
5//! `session::registry`'s `events`/`memory_sink_ext` split for the identical
6//! precedent. `use super::*` below pulls in every type this file needs from
7//! the parent (`ChatRequest`, `ChatResponse`, `InferenceAdapter`, `InferenceError`,
8//! `AtomicUsize`, `Ordering`, `async_trait`, `Value`, `json`).
9//!
10//! Why: the compression-effectiveness soak harness
11//! (`crates/trusty-code/scripts/compression_soak.py`) drives 200+ PM turns
12//! by calling `task.run(session_id=..., ...)` repeatedly against ONE
13//! persistent session — `task::protocol::task_run` rebuilds the
14//! `Arc<dyn InferenceAdapter>` fresh on EVERY call (`build_llm_client()`), so
15//! this client's script only ever needs to cover ONE call's worth of PM
16//! turns, not the whole soak. Every other scripted client in
17//! `task::mock_llm` ends its final turn with an explicit `finish_task`/
18//! delegate hand-off; this one deliberately ends with a bare `stop` (no
19//! tool calls) — the ONLY way a `task.run` call completes with
20//! `SessionStatus::Finished` rather than `Failed`
21//! (`session::registry::SessionRegistry::begin_execution` permanently
22//! rejects further `task.run` calls once a session is `Failed`/`Cancelled`/
23//! `DeadlineExceeded` — only `Finished` sessions may resume, see that
24//! method's docs), which is what lets the harness call `task.run` on the
25//! SAME `session_id` dozens of times in a row.
26//! What: [`SoakEchoLlmClient`] plays a FIXED 7-response script per
27//! construction (i.e. per `task.run` call): three `set_goal`/`clear_goal`
28//! pairs — the third `set_goal` carries a deliberately OVERSIZED `text`
29//! argument (~8 KB) to exercise `cadence::enforce_budget`'s CONTINUOUS,
30//! every-turn enforcement path (issue #3869's explicit requirement — a soak
31//! that never produces an oversized turn doesn't test the mechanism the
32//! epic cared about most) — then a final bare `stop`. 7 turns stays safely
33//! under `AgentLoopConfig::default().max_turns` (8), so the loop always
34//! completes via the natural "no tool calls" path, never `TurnCapExceeded`.
35//! Test: `tests::soak_script_ends_in_a_resumable_stop_and_has_one_oversized_turn`.
36
37use super::*;
38
39/// Approximate byte length of the deliberately OVERSIZED `set_goal` `text`
40/// argument [`SoakEchoLlmClient`] emits partway through its script — big
41/// enough to move `cadence::estimate_total_tokens` without single-handedly
42/// blowing the whole context window in one turn.
43const SOAK_OVERSIZED_TEXT_LEN: usize = 8_000;
44
45/// A deterministic, offline `InferenceAdapter` for issue #3869's
46/// compression-effectiveness soak harness (epic #3866 Slice C).
47///
48/// Why: see the module docs above.
49/// What: an atomic cursor `idx`, incremented every call within ONE
50/// construction (one per `task.run` call — see module docs): calls 0/2/4
51/// are `set_goal` on slot `1 + (idx / 2)`, calls 1/3 are `clear_goal` on the
52/// matching slot, call 4's `set_goal` carries the oversized text, and call 6
53/// is a bare `stop`. Calls 5 clears the slot the oversized text just used.
54/// Running past call 6 returns an `InferenceError` (script exhausted) rather than
55/// panicking, mirroring every other client in the parent module — the
56/// harness must never call `chat` an 8th time in one `task.run`.
57/// Test: `tests::soak_script_ends_in_a_resumable_stop_and_has_one_oversized_turn`.
58pub struct SoakEchoLlmClient {
59    cursor: AtomicUsize,
60}
61
62impl SoakEchoLlmClient {
63    /// Construct a fresh client at the start of its script.
64    pub fn new() -> Self {
65        Self {
66            cursor: AtomicUsize::new(0),
67        }
68    }
69}
70
71impl Default for SoakEchoLlmClient {
72    fn default() -> Self {
73        Self::new()
74    }
75}
76
77#[async_trait]
78impl InferenceAdapter for SoakEchoLlmClient {
79    crate::llm::mock_adapter_identity!("mock-soak-echo");
80
81    async fn chat(&self, _req: &ChatRequest) -> Result<ChatResponse, InferenceError> {
82        let idx = self.cursor.fetch_add(1, Ordering::SeqCst);
83        let fixture = match idx {
84            0 => soak_goal_tool_call("set_goal", idx, 1, "soak progress marker 0"),
85            1 => soak_clear_goal_tool_call(idx, 1),
86            2 => soak_goal_tool_call("set_goal", idx, 2, "soak progress marker 2"),
87            3 => soak_clear_goal_tool_call(idx, 2),
88            4 => soak_goal_tool_call("set_goal", idx, 3, &"x".repeat(SOAK_OVERSIZED_TEXT_LEN)),
89            5 => soak_clear_goal_tool_call(idx, 3),
90            6 => stop_fixture(),
91            _ => {
92                return Err(InferenceError::MissingConfig(format!(
93                    "SoakEchoLlmClient script exhausted at call {idx}"
94                )));
95            }
96        };
97        serde_json::from_value(fixture).map_err(|e| {
98            InferenceError::MissingConfig(format!(
99                "SoakEchoLlmClient: invalid scripted fixture: {e}"
100            ))
101        })
102    }
103}
104
105/// Build a `set_goal(slot, text)` tool-call fixture for [`SoakEchoLlmClient`].
106fn soak_goal_tool_call(tool_name: &str, idx: usize, slot: usize, text: &str) -> Value {
107    json!({
108        "id": "mock-soak-set",
109        "choices": [{
110            "message": {
111                "role": "assistant",
112                "content": null,
113                "tool_calls": [{
114                    "id": format!("call-soak-{idx}"),
115                    "type": "function",
116                    "function": {
117                        "name": tool_name,
118                        "arguments": json!({"slot": slot, "text": text}).to_string()
119                    }
120                }]
121            },
122            "finish_reason": "tool_calls"
123        }],
124        "usage": {"prompt_tokens": 15, "completion_tokens": 5, "total_tokens": 20}
125    })
126}
127
128/// Build a `clear_goal(slot)` tool-call fixture for [`SoakEchoLlmClient`].
129fn soak_clear_goal_tool_call(idx: usize, slot: usize) -> Value {
130    json!({
131        "id": "mock-soak-clear",
132        "choices": [{
133            "message": {
134                "role": "assistant",
135                "content": null,
136                "tool_calls": [{
137                    "id": format!("call-soak-{idx}"),
138                    "type": "function",
139                    "function": {
140                        "name": "clear_goal",
141                        "arguments": json!({"slot": slot}).to_string()
142                    }
143                }]
144            },
145            "finish_reason": "tool_calls"
146        }],
147        "usage": {"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15}
148    })
149}
150
151/// The final, no-tool-calls fixture — the ONLY way this script's `task.run`
152/// call completes with `SessionStatus::Finished` (resumable) rather than
153/// `Failed` (permanently terminal). See module docs.
154fn stop_fixture() -> Value {
155    json!({
156        "id": "mock-soak-stop",
157        "choices": [{
158            "message": {"role": "assistant", "content": "soak call complete", "tool_calls": []},
159            "finish_reason": "stop"
160        }],
161        "usage": {"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15}
162    })
163}
164
165#[cfg(test)]
166mod tests {
167    use super::*;
168
169    /// The script must be 7 calls long, ending in a bare `stop`, with
170    /// exactly one oversized `set_goal` argument along the way — the exact
171    /// shape `compression_soak.py` relies on to keep resuming the same
172    /// session (issue #3869).
173    #[tokio::test]
174    async fn soak_script_ends_in_a_resumable_stop_and_has_one_oversized_turn() {
175        let client = SoakEchoLlmClient::new();
176        let req = ChatRequest {
177            model: "mock".to_string(),
178            messages: vec![],
179            temperature: None,
180            max_tokens: None,
181            tools: None,
182            tool_choice: None,
183            usage: None,
184            response_schema: None,
185            stop: None,
186        };
187
188        let mut oversized_count = 0;
189        for i in 0..6 {
190            let resp = client
191                .chat(&req)
192                .await
193                .unwrap_or_else(|e| panic!("call {i}: {e}"));
194            let calls = resp.first_tool_calls();
195            assert_eq!(calls.len(), 1, "call {i} must be exactly one tool call");
196            if calls[0].function.name == "set_goal" {
197                let args: Value =
198                    serde_json::from_str(&calls[0].function.arguments).expect("valid json args");
199                if args["text"].as_str().unwrap_or("").len() >= SOAK_OVERSIZED_TEXT_LEN {
200                    oversized_count += 1;
201                }
202            }
203        }
204        assert_eq!(oversized_count, 1, "expected exactly one oversized turn");
205
206        // 7th call (idx 6): bare stop, no tool calls.
207        let stop = client.chat(&req).await.expect("call 6 (stop)");
208        assert!(
209            stop.first_tool_calls().is_empty(),
210            "final turn must have no tool calls"
211        );
212
213        // An 8th call must error, never panic or silently repeat.
214        let err = client.chat(&req).await;
215        assert!(
216            err.is_err(),
217            "the script must not silently repeat past its end"
218        );
219    }
220}