Tests become directory modules named after what they test, with a shared fixtures/harness module:
control-plane/src/{responses,ggml_bridge,gguf_f32_stream,prepare_preview}/tests/, desktop-core/src/runtime_rpc/tests/;
integration targets become tests/<name>/main.rs plus topic modules and a harness (backend_worker_http, vision_http,
memory_gate_http, tool_corpus, mcp_hub, api_over_runtime, runtime_gateway_sdet, native_tools_sdet,
native_tools_retry_sdet, managed_worker, gateway); target names are unchanged. Sources: leleka-inference.rs becomes
src/bin/leleka-inference/ (main.rs plus one module per operator option group), the cp_replay example becomes
examples/cp_replay/, and the tonic service impl of runtime_rpc delegates to session_rpc, model_rpc and generate_rpc
(bodies unchanged). impl_* modules are renamed after what they hold (base_provenance, count_tokens, manifest_fetch,
fetcher, record, capture, in_flight, tool_policy, tool_plan, server). The self-spawning tests that name themselves
(credential_child, the managed worker fixture) use the new module path or stay at the target root.
Test ids: 543 before and after in both crates (strata-control, strata-desktop-core, --all-targets), 0 missing, 0 new,
0 outcome changes; 241 ids differ only in the module path. Warnings in the two crates: 0 before and after.
Counts (strata-control / strata-desktop-core): oversize files 19 -> 0 (13 + 6). Functions over 30 lines, complexity 10,
nesting 4, wide lines, prod: 187/135/17/199 -> 187/135/17/196 and 81/59/6/54 -> 81/59/6/54; test: 214/17/30/133 ->
214/17/30/133 and 65/3/3/30 -> 65/3/3/27. The 211 functions that moved verbatim are in limits-allowlist.json (owner
STRA-338) because the diff gate treats a moved function as added; the entries fall as the functions are shortened.
279 lines
11 KiB
Rust
279 lines
11 KiB
Rust
//! Codex-shaped requests: reasoning, tool choice, parallel calls and known prompt text.
|
|
|
|
use crate::harness::{
|
|
Stack, assert_stream_invariants, body, runtime_config, scripted_text, sse_events, text_of,
|
|
tool_markup,
|
|
};
|
|
use leleka_backend_api::Usage;
|
|
use leleka_backend_api::scripted::{Script, ScriptedEngine};
|
|
use serde_json::{Value, json};
|
|
use std::sync::Arc;
|
|
use std::time::Duration;
|
|
use strata_control::backend_worker::{BackendWorkerConfig, run_backend_worker};
|
|
use strata_control::worker::{WorkerState, WorkerStatus};
|
|
use tokio::sync::{RwLock, mpsc, watch};
|
|
|
|
fn shell_tool() -> Value {
|
|
json!({"type": "function", "name": "shell", "description": "Run a command", "strict": false,
|
|
"parameters": {"type": "object",
|
|
"properties": {"command": {"type": "array", "items": {"type": "string"}}},
|
|
"required": ["command"]}})
|
|
}
|
|
|
|
/// The request shape of the Codex console (fields and values as it sends them), two turns, stateless
|
|
/// replay of the first turn's output items, through the runtime stack. Synthetic prompts and scripted
|
|
/// engine output: this checks that the surface is accepted and the protocol holds, not Codex itself.
|
|
#[tokio::test]
|
|
async fn a_codex_shaped_request_streams_reasoning_and_a_tool_call_and_replays_statelessly() {
|
|
let stack = Stack::start("bw-codex").await;
|
|
let turn_one = json!({
|
|
"model": "fixture",
|
|
"instructions": "You are a coding agent.",
|
|
"input": [{"type": "message", "role": "user",
|
|
"content": [{"type": "input_text", "text": "List the files."}]}],
|
|
"tools": [shell_tool()],
|
|
"tool_choice": "auto",
|
|
"parallel_tool_calls": false,
|
|
"reasoning": {"effort": "medium", "summary": "auto"},
|
|
"store": false,
|
|
"stream": true,
|
|
"include": ["reasoning.encrypted_content"],
|
|
"prompt_cache_key": "019a0000-0000-7000-8000-000000000000",
|
|
"text": {"verbosity": "low"},
|
|
"service_tier": "priority",
|
|
"client_metadata": {"x-codex-installation-id": "synthetic-installation"}
|
|
});
|
|
let markup = "The user wants a listing.</think>\n\n<tool_call>\n<function=shell>\n<parameter=command>\n[\"ls\",\"-la\"]\n</parameter>\n</function>\n</tool_call>";
|
|
scripted_text(&stack.engine, markup, 11);
|
|
let (status, text) = stack.post("/v1/responses", &turn_one).await;
|
|
assert_eq!(status, 200, "{text}");
|
|
let events = sse_events(&text);
|
|
assert_stream_invariants(&events);
|
|
assert_eq!(events.last().unwrap()["type"], "response.completed");
|
|
let kinds: Vec<&str> = events.iter().map(|e| e["type"].as_str().unwrap()).collect();
|
|
assert!(
|
|
kinds.contains(&"response.reasoning_text.delta"),
|
|
"{kinds:?}"
|
|
);
|
|
assert!(
|
|
kinds.contains(&"response.function_call_arguments.done"),
|
|
"{kinds:?}"
|
|
);
|
|
let response = events.last().unwrap()["response"].clone();
|
|
assert_eq!(response["store"], json!(false));
|
|
let output = response["output"].as_array().unwrap().clone();
|
|
let reasoning = output.iter().find(|i| i["type"] == "reasoning").unwrap();
|
|
assert_eq!(reasoning["content"][0]["text"], "The user wants a listing.");
|
|
let call = output
|
|
.iter()
|
|
.find(|i| i["type"] == "function_call")
|
|
.unwrap()
|
|
.clone();
|
|
assert_eq!(call["name"], "shell");
|
|
assert_eq!(
|
|
serde_json::from_str::<Value>(call["arguments"].as_str().unwrap()).unwrap(),
|
|
json!({"command": ["ls", "-la"]})
|
|
);
|
|
|
|
// The prompt the engine saw: the instructions as the system turn, thinking opened for the model.
|
|
let prompt = stack.engine.requests()[0].prompt.clone();
|
|
assert!(prompt.starts_with("<|im_start|>system\n"), "{prompt}");
|
|
assert!(prompt.contains("You are a coding agent."), "{prompt}");
|
|
assert!(prompt.contains("List the files."), "{prompt}");
|
|
assert!(prompt.ends_with("<think>\n"), "{prompt}");
|
|
assert_eq!(stack.engine.requests()[0].max_output_tokens, 4096);
|
|
|
|
// store:false really stores nothing.
|
|
let (status, _) = stack
|
|
.get(&format!(
|
|
"/v1/responses/{}",
|
|
response["id"].as_str().unwrap()
|
|
))
|
|
.await;
|
|
assert_eq!(status, 404);
|
|
|
|
// Turn two replays the whole transcript, the way a stateless client does.
|
|
let mut input = turn_one["input"].as_array().unwrap().clone();
|
|
input.extend(output);
|
|
input.push(
|
|
json!({"type": "function_call_output", "call_id": call["call_id"],
|
|
"output": "Cargo.toml\nsrc"}),
|
|
);
|
|
let mut turn_two = turn_one.clone();
|
|
turn_two["input"] = Value::Array(input);
|
|
turn_two["reasoning"] = json!({"effort": "medium", "summary": "auto"});
|
|
scripted_text(
|
|
&stack.engine,
|
|
"There are two entries.</think>\n\nCargo.toml and src.",
|
|
13,
|
|
);
|
|
let (status, text) = stack.post("/v1/responses", &turn_two).await;
|
|
assert_eq!(status, 200, "{text}");
|
|
let events = sse_events(&text);
|
|
assert_stream_invariants(&events);
|
|
assert_eq!(events.last().unwrap()["type"], "response.completed");
|
|
let final_text = text_of(&events.last().unwrap()["response"]);
|
|
assert_eq!(final_text, "Cargo.toml and src.");
|
|
let second = &stack.engine.requests()[1].prompt;
|
|
assert!(second.contains("Cargo.toml\nsrc"), "{second}");
|
|
assert!(second.contains("The user wants a listing."), "{second}");
|
|
assert!(second.contains("<function=shell>"), "{second}");
|
|
stack.finish().await;
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn codex_tool_choice_and_parallel_calls_are_enforced_on_the_generated_calls() {
|
|
let stack = Stack::start("bw-toolchoice").await;
|
|
let two_calls = format!(
|
|
"{}\n{}",
|
|
tool_markup("shell", &json!({"command": ["ls"]})),
|
|
tool_markup("shell", &json!({"command": ["pwd"]}))
|
|
);
|
|
let request = |extra: Value| {
|
|
let mut value = body(json!({"tools": [shell_tool()], "stream": true}));
|
|
for (key, item) in extra.as_object().unwrap() {
|
|
value[key] = item.clone();
|
|
}
|
|
value
|
|
};
|
|
// parallel_tool_calls:false + two calls => the response fails instead of publishing both.
|
|
scripted_text(&stack.engine, &two_calls, 17);
|
|
let (_, text) = stack
|
|
.post(
|
|
"/v1/responses",
|
|
&request(json!({"parallel_tool_calls": false})),
|
|
)
|
|
.await;
|
|
let events = sse_events(&text);
|
|
assert_stream_invariants(&events);
|
|
assert_eq!(events.last().unwrap()["type"], "response.failed");
|
|
// parallel allowed => both calls arrive.
|
|
scripted_text(&stack.engine, &two_calls, 17);
|
|
let (_, text) = stack
|
|
.post(
|
|
"/v1/responses",
|
|
&request(json!({"parallel_tool_calls": true})),
|
|
)
|
|
.await;
|
|
let events = sse_events(&text);
|
|
assert_eq!(events.last().unwrap()["type"], "response.completed");
|
|
let calls = events.last().unwrap()["response"]["output"]
|
|
.as_array()
|
|
.unwrap()
|
|
.iter()
|
|
.filter(|i| i["type"] == "function_call")
|
|
.count();
|
|
assert_eq!(calls, 2);
|
|
// tool_choice none + a call => failure; required + plain text => failure; forced name mismatch.
|
|
scripted_text(
|
|
&stack.engine,
|
|
&tool_markup("shell", &json!({"command": ["ls"]})),
|
|
17,
|
|
);
|
|
let (_, text) = stack
|
|
.post("/v1/responses", &request(json!({"tool_choice": "none"})))
|
|
.await;
|
|
assert_eq!(sse_events(&text).last().unwrap()["type"], "response.failed");
|
|
scripted_text(&stack.engine, "just words", 17);
|
|
let (_, text) = stack
|
|
.post(
|
|
"/v1/responses",
|
|
&request(json!({"tool_choice": "required"})),
|
|
)
|
|
.await;
|
|
assert_eq!(sse_events(&text).last().unwrap()["type"], "response.failed");
|
|
scripted_text(
|
|
&stack.engine,
|
|
&tool_markup("shell", &json!({"command": ["ls"]})),
|
|
17,
|
|
);
|
|
let (_, text) = stack
|
|
.post(
|
|
"/v1/responses",
|
|
&request(json!({"tool_choice": {"type": "function", "name": "shell"}})),
|
|
)
|
|
.await;
|
|
assert_eq!(
|
|
sse_events(&text).last().unwrap()["type"],
|
|
"response.completed"
|
|
);
|
|
stack.finish().await;
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn a_known_prompt_text_is_sent_only_when_the_ids_decode_to_it() {
|
|
use strata_control::wire::Generate;
|
|
use strata_control::worker::{GenerationCommand, GenerationResult};
|
|
let stack = Stack::start("bw-known-text").await;
|
|
let (requests, requests_rx) = mpsc::channel(1);
|
|
let (_control, control_rx) = mpsc::channel(1);
|
|
let (engine, handle) = ScriptedEngine::new(ScriptedEngine::fixture_descriptor());
|
|
handle.respond_with(|_| {
|
|
Script::stop_with(
|
|
&["ok"],
|
|
Usage {
|
|
input_tokens: 1,
|
|
output_tokens: 1,
|
|
reused_input_tokens: 0,
|
|
},
|
|
)
|
|
});
|
|
let status = Arc::new(RwLock::new(WorkerStatus::default()));
|
|
let (_stop, stop_rx) = watch::channel(false);
|
|
let config = BackendWorkerConfig {
|
|
tokenizer: stack.tokenizer.clone(),
|
|
model: ScriptedEngine::fixture_descriptor(),
|
|
runtime: runtime_config(),
|
|
max_context: 262_144,
|
|
max_output_tokens: 4096,
|
|
health_interval: Duration::from_millis(20),
|
|
generation_timeout: None,
|
|
stall_timeout: None,
|
|
attach_retry: Duration::from_millis(20),
|
|
cancel_drain_timeout: Duration::from_secs(1),
|
|
prefix_view: None,
|
|
memory_view: None,
|
|
};
|
|
tokio::spawn(run_backend_worker(
|
|
Box::new(engine),
|
|
config,
|
|
status.clone(),
|
|
stop_rx,
|
|
requests_rx,
|
|
control_rx,
|
|
));
|
|
while status.read().await.state != WorkerState::Ready {
|
|
tokio::time::sleep(Duration::from_millis(5)).await;
|
|
}
|
|
let ask = async |text: &str, claimed: Option<&str>| {
|
|
let (sender, receiver) = tokio::sync::oneshot::channel();
|
|
requests
|
|
.send(GenerationCommand {
|
|
queue: None,
|
|
activity: None,
|
|
request: Generate {
|
|
token_ids: stack.tokenizer.encode(text, true).unwrap(),
|
|
max_new: 8,
|
|
prompt_text: claimed.map(Arc::from),
|
|
..Default::default()
|
|
},
|
|
result: GenerationResult::Buffered(sender),
|
|
})
|
|
.await
|
|
.unwrap();
|
|
receiver.await.unwrap().expect("served");
|
|
};
|
|
// the text the ids were produced from: the engine gets exactly that text
|
|
ask("hello tool<|im_end|>\n", Some("hello tool<|im_end|>\n")).await;
|
|
// a claim the ids do not decode to is not trusted: the engine gets the text of the ids
|
|
ask("hello tool", Some("something else entirely")).await;
|
|
// no claim: the ids are decoded and checked as before
|
|
ask("tool hello", None).await;
|
|
let prompts: Vec<String> = handle.requests().into_iter().map(|r| r.prompt).collect();
|
|
assert_eq!(
|
|
prompts,
|
|
["hello tool<|im_end|>\n", "hello tool", "tool hello"]
|
|
);
|
|
stack.finish().await;
|
|
}
|