use super::*;
const LOAD_PAYLOAD_BYTES: [usize; 3] = [160_000, 230_000, 300_000];
pub const LOAD_PAYLOAD_BYTES_ENV_VAR: &str = "TCODE_SOAK_LOAD_PAYLOAD_BYTES";
fn resolve_payload_bytes() -> [usize; 3] {
let Ok(raw) = std::env::var(LOAD_PAYLOAD_BYTES_ENV_VAR) else {
return LOAD_PAYLOAD_BYTES;
};
let parsed: Vec<usize> = raw
.split(',')
.filter_map(|s| s.trim().parse::<usize>().ok())
.collect();
match parsed.as_slice() {
[a, b, c] => [*a, *b, *c],
_ => {
tracing::warn!(
"{LOAD_PAYLOAD_BYTES_ENV_VAR}={raw:?} did not parse as three comma-separated \
usize values; keeping the default {LOAD_PAYLOAD_BYTES:?}"
);
LOAD_PAYLOAD_BYTES
}
}
}
pub struct SoakLoadEchoLlmClient {
cursor: AtomicUsize,
payload_bytes: [usize; 3],
}
impl SoakLoadEchoLlmClient {
pub fn new() -> Self {
Self {
cursor: AtomicUsize::new(0),
payload_bytes: resolve_payload_bytes(),
}
}
}
impl Default for SoakLoadEchoLlmClient {
fn default() -> Self {
Self::new()
}
}
#[async_trait]
impl InferenceAdapter for SoakLoadEchoLlmClient {
crate::llm::mock_adapter_identity!("mock-soak-load-echo");
async fn chat(&self, _req: &ChatRequest) -> Result<ChatResponse, InferenceError> {
let idx = self.cursor.fetch_add(1, Ordering::SeqCst);
let fixture = match idx {
0 => load_goal_tool_call(idx, 1, self.payload_bytes[0]),
1 => load_clear_goal_tool_call(idx, 1),
2 => load_goal_tool_call(idx, 2, self.payload_bytes[1]),
3 => load_clear_goal_tool_call(idx, 2),
4 => load_goal_tool_call(idx, 3, self.payload_bytes[2]),
5 => load_clear_goal_tool_call(idx, 3),
6 => load_stop_fixture(),
_ => {
return Err(InferenceError::MissingConfig(format!(
"SoakLoadEchoLlmClient script exhausted at call {idx}"
)));
}
};
serde_json::from_value(fixture).map_err(|e| {
InferenceError::MissingConfig(format!(
"SoakLoadEchoLlmClient: invalid scripted fixture: {e}"
))
})
}
}
fn load_goal_tool_call(idx: usize, slot: usize, payload_bytes: usize) -> Value {
let text = synthetic_tool_output(payload_bytes);
json!({
"id": "mock-soak-load-set",
"choices": [{
"message": {
"role": "assistant",
"content": null,
"tool_calls": [{
"id": format!("call-soak-load-{idx}"),
"type": "function",
"function": {
"name": "set_goal",
"arguments": json!({"slot": slot, "text": text}).to_string()
}
}]
},
"finish_reason": "tool_calls"
}],
"usage": {"prompt_tokens": 15, "completion_tokens": 5, "total_tokens": 20}
})
}
fn load_clear_goal_tool_call(idx: usize, slot: usize) -> Value {
json!({
"id": "mock-soak-load-clear",
"choices": [{
"message": {
"role": "assistant",
"content": null,
"tool_calls": [{
"id": format!("call-soak-load-{idx}"),
"type": "function",
"function": {
"name": "clear_goal",
"arguments": json!({"slot": slot}).to_string()
}
}]
},
"finish_reason": "tool_calls"
}],
"usage": {"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15}
})
}
fn load_stop_fixture() -> Value {
json!({
"id": "mock-soak-load-stop",
"choices": [{
"message": {"role": "assistant", "content": "soak-load call complete", "tool_calls": []},
"finish_reason": "stop"
}],
"usage": {"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15}
})
}
fn synthetic_tool_output(target_bytes: usize) -> String {
const LINE_TEMPLATES: [&str; 6] = [
"+ let result = compute_budget(&transcript, cadence_cfg, keep_last_messages);\n",
"- let result = compute_budget(&transcript, keep_last_messages);\n",
"src/agent_loop/cadence.rs:187: match maybe_cadence_compress(&mut transcript) {\n",
"test agent_loop::cadence::tests::stays_under_budget_every_turn ... FAILED\n",
"thread 'cadence::tests' panicked at src/agent_loop/cadence_tests.rs:412:9:\n",
"assertion `left == right` failed: overhead_tokens exceeded cap_tokens\n",
];
let mut out = String::with_capacity(target_bytes + 128);
let mut i = 0usize;
while out.len() < target_bytes {
out.push_str(LINE_TEMPLATES[i % LINE_TEMPLATES.len()]);
i += 1;
}
out
}
#[cfg(test)]
mod tests {
use super::*;
use crate::agent_loop::CadenceConfig;
static PAYLOAD_BYTES_ENV_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
#[tokio::test]
async fn payload_bytes_env_override_parses_three_values_or_falls_back_to_default() {
let _guard = PAYLOAD_BYTES_ENV_LOCK.lock().await;
unsafe {
std::env::remove_var(LOAD_PAYLOAD_BYTES_ENV_VAR);
}
assert_eq!(
resolve_payload_bytes(),
LOAD_PAYLOAD_BYTES,
"unset falls back"
);
unsafe {
std::env::set_var(LOAD_PAYLOAD_BYTES_ENV_VAR, "220000,300000,400000");
}
assert_eq!(
resolve_payload_bytes(),
[220_000, 300_000, 400_000],
"three valid comma-separated values override the default"
);
unsafe {
std::env::set_var(LOAD_PAYLOAD_BYTES_ENV_VAR, "not-a-number");
}
assert_eq!(
resolve_payload_bytes(),
LOAD_PAYLOAD_BYTES,
"unparseable value falls back to the default, never panics/errors"
);
unsafe {
std::env::remove_var(LOAD_PAYLOAD_BYTES_ENV_VAR);
}
}
#[tokio::test]
async fn soak_load_script_ends_in_a_resumable_stop_and_sums_past_the_default_cap() {
let cap = CadenceConfig::default().overhead_cap_tokens(200_000);
let total_estimated_tokens: usize = LOAD_PAYLOAD_BYTES.iter().map(|bytes| bytes / 4).sum();
assert!(
total_estimated_tokens > cap,
"load payload sum ({total_estimated_tokens} tokens) must exceed the default \
overhead cap ({cap} tokens) for this soak variant to be load-realistic"
);
let client = SoakLoadEchoLlmClient::new();
let req = ChatRequest {
model: "mock".to_string(),
messages: vec![],
temperature: None,
max_tokens: None,
tools: None,
tool_choice: None,
usage: None,
stop: None,
};
for i in 0..6 {
let resp = client
.chat(&req)
.await
.unwrap_or_else(|e| panic!("call {i}: {e}"));
let calls = resp.first_tool_calls();
assert_eq!(calls.len(), 1, "call {i} must be exactly one tool call");
}
let stop = client.chat(&req).await.expect("call 6 (stop)");
assert!(
stop.first_tool_calls().is_empty(),
"final turn must have no tool calls"
);
let err = client.chat(&req).await;
assert!(
err.is_err(),
"the script must not silently repeat past its end"
);
}
}