STRA-338 S23: golden captures of the gateway answers for scripted model output, both families
Adds a test that drives the real create handler with 66 scripted token sequences (33 Qwen3.5, 33 gpt-oss/Harmony) as a
stream and as a buffered answer, and compares the bytes a client would read (status, content type, SSE frames, JSON
body, with ids and timestamps normalised) with tests/fixtures/golden/output_events.json. The cases cover plain text,
tool calls, reasoning, structured output, unclosed reasoning, length cuts, invalid and unknown calls, calls without
declared tools and worker failures. The captures were recorded on cbc1a9587 and are the identity proof of the S23
steps; the test also checks that two runs give the same captures. Synthetic scripts only, nothing from a real session.
This commit is contained in:
@@ -8,6 +8,7 @@ mod input_items;
|
||||
mod live;
|
||||
mod live_endpoint;
|
||||
mod live_tools;
|
||||
mod output_golden;
|
||||
mod reasoning;
|
||||
mod reasoning_live;
|
||||
mod sampling;
|
||||
|
||||
@@ -0,0 +1,209 @@
|
||||
//! Golden captures of what the gateway answers for a scripted model output, for both families (STRA-338 S23).
|
||||
//!
|
||||
//! A scripted worker answers the real `create` handler with a fixed token sequence, once as a stream and once as
|
||||
//! a buffered answer. The bytes the client would read (status, content type, SSE frames or the JSON body) are
|
||||
//! stored after the volatile parts (ids made of the clock and a counter, timestamps) are replaced. The scripts
|
||||
//! are in `tests/fixtures/golden/output_cases.json`, the expected captures in `output_events.json`; the S23
|
||||
//! steps move the output decoding behind `OutputEvent` and must not change one byte of the captures. All
|
||||
//! scripts are synthetic: no capture of a real session is committed.
|
||||
|
||||
use super::super::*;
|
||||
use super::live::{done, ready_state};
|
||||
use crate::codec::{QwenCodec, TextCodec};
|
||||
use crate::harmony_family::GptOssCodec;
|
||||
use axum::extract::State;
|
||||
use http_body_util::BodyExt;
|
||||
use leleka_tokenizer::gguf_bpe::GgufBpe;
|
||||
use std::{fs, path::PathBuf};
|
||||
|
||||
/// The two codecs a case may run under, and the vocabulary of the gpt-oss one for turning a script into ids.
|
||||
struct Codecs {
|
||||
qwen: Arc<QwenCodec>,
|
||||
gptoss: Arc<GptOssCodec>,
|
||||
gptoss_vocabulary: GgufBpe,
|
||||
}
|
||||
|
||||
/// The vocabulary of the gpt-oss test codec: the byte tokens and the Harmony markers as control tokens.
|
||||
fn gptoss_vocabulary() -> GgufBpe {
|
||||
let chars = leleka_tokenizer::gguf_bpe::byte_alphabet();
|
||||
let mut tokens: Vec<String> = chars.iter().map(|c| c.to_string()).collect();
|
||||
let mut types = vec![1i64; 256];
|
||||
let markers = [
|
||||
"<|start|>",
|
||||
"<|end|>",
|
||||
"<|message|>",
|
||||
"<|channel|>",
|
||||
"<|call|>",
|
||||
];
|
||||
for marker in markers
|
||||
.into_iter()
|
||||
.chain(["<|return|>", "<|constrain|>", "<|endoftext|>"])
|
||||
{
|
||||
tokens.push(marker.to_owned());
|
||||
types.push(3);
|
||||
}
|
||||
let parts: Vec<&str> = tokens.iter().map(String::as_str).collect();
|
||||
GgufBpe::from_parts(&parts, &types, &[], None, None, None).unwrap()
|
||||
}
|
||||
|
||||
/// The token ids of a script: `@name` is the special token `name`, anything else is text as byte-level tokens.
|
||||
fn script_ids(case: &Value, codecs: &Codecs) -> Vec<u32> {
|
||||
let gptoss = case["family"] == "gptoss";
|
||||
let mut ids = Vec::new();
|
||||
for part in case["script"].as_array().unwrap() {
|
||||
let part = part.as_str().unwrap();
|
||||
match (gptoss, part.strip_prefix('@')) {
|
||||
(true, Some(name)) => ids.push(codecs.gptoss_vocabulary.token_id(name).unwrap()),
|
||||
(true, None) => ids.extend(codecs.gptoss_vocabulary.encode(part, false)),
|
||||
(false, Some(name)) => ids.push(codecs.qwen.special_id(name).unwrap()),
|
||||
(false, None) => ids.extend(codecs.qwen.encode(part, false).unwrap()),
|
||||
}
|
||||
}
|
||||
ids
|
||||
}
|
||||
|
||||
/// The events a worker sends for the script and its end: `stop`, `length` or `fail:<message>`.
|
||||
fn worker_events(ids: &[u32], end: &str) -> Vec<Result<Event, String>> {
|
||||
let mut events: Vec<Result<Event, String>> =
|
||||
ids.iter().map(|id| Ok(Event::Token(*id))).collect();
|
||||
let finish = match end {
|
||||
"stop" => Finish::Stop,
|
||||
"length" => Finish::Length,
|
||||
_ => {
|
||||
events.push(Err(end.strip_prefix("fail:").unwrap().to_owned()));
|
||||
return events;
|
||||
}
|
||||
};
|
||||
events.push(Ok(Event::Done(done(ids.len() as u64, 9, finish))));
|
||||
events
|
||||
}
|
||||
|
||||
/// A worker that takes one command and answers it with `events`, buffered or streamed.
|
||||
fn answer_once(
|
||||
mut received: mpsc::Receiver<GenerationCommand>,
|
||||
events: Vec<Result<Event, String>>,
|
||||
) -> tokio::task::JoinHandle<()> {
|
||||
tokio::spawn(async move {
|
||||
let command = received.recv().await.unwrap();
|
||||
match command.result {
|
||||
GenerationResult::Finished => panic!("unexpected finished command"),
|
||||
GenerationResult::Buffered(sender) => {
|
||||
let _ = sender.send(events.into_iter().collect::<Result<Vec<_>, _>>());
|
||||
}
|
||||
GenerationResult::Streaming(sender) => {
|
||||
for event in events {
|
||||
if sender.send(event).await.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// The ids and timestamps of a capture replaced by fixed text.
|
||||
fn normalize(text: &str) -> String {
|
||||
let ids =
|
||||
regex::Regex::new(r"\b(resp|msg|rs|fc|ctc|call)_[0-9a-f]+_[0-9a-f]+(_[0-9]+)?").unwrap();
|
||||
let times = regex::Regex::new(r#""(created_at|completed_at)":[0-9]+"#).unwrap();
|
||||
let text = ids.replace_all(text, "${1}_ID");
|
||||
times.replace_all(&text, r#""${1}":0"#).into_owned()
|
||||
}
|
||||
|
||||
/// Status, content type and body of a response; a stream is read frame by frame.
|
||||
async fn capture(response: Response) -> String {
|
||||
let status = response.status().as_u16();
|
||||
let kind = response
|
||||
.headers()
|
||||
.get("content-type")
|
||||
.and_then(|value| value.to_str().ok());
|
||||
let head = format!("{status} {}\n", kind.unwrap_or(""));
|
||||
let mut body = response.into_body();
|
||||
let mut text = head;
|
||||
while let Some(frame) = body.frame().await {
|
||||
text.push_str(&String::from_utf8_lossy(
|
||||
&frame.unwrap().into_data().unwrap(),
|
||||
));
|
||||
}
|
||||
normalize(&text)
|
||||
}
|
||||
|
||||
/// The capture of one case in one mode.
|
||||
async fn run_case(case: &Value, stream: bool, codecs: &Codecs) -> String {
|
||||
let (mut state, received) = ready_state(&codecs.qwen).await;
|
||||
if case["family"] == "gptoss" {
|
||||
state.model.tokenizer = Some(codecs.gptoss.clone() as Arc<dyn TextCodec>);
|
||||
}
|
||||
let events = worker_events(&script_ids(case, codecs), case["end"].as_str().unwrap());
|
||||
let worker = answer_once(received, events);
|
||||
let mut payload =
|
||||
json!({"model": "strata-local", "input": "test", "stream": stream, "store": false});
|
||||
payload
|
||||
.as_object_mut()
|
||||
.unwrap()
|
||||
.extend(case["request"].as_object().unwrap().clone());
|
||||
let text = capture(create(State(state), Ok(Json(payload))).await).await;
|
||||
worker.await.unwrap();
|
||||
text
|
||||
}
|
||||
|
||||
fn fixture(name: &str) -> PathBuf {
|
||||
PathBuf::from(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("tests/fixtures/golden")
|
||||
.join(name)
|
||||
}
|
||||
|
||||
/// Every case in both modes, as `<name>/stream` and `<name>/buffered`.
|
||||
async fn capture_all() -> Vec<(String, String)> {
|
||||
let cases: Value =
|
||||
serde_json::from_str(&fs::read_to_string(fixture("output_cases.json")).unwrap()).unwrap();
|
||||
let (qwen, root) = super::fixtures::test_tokenizer();
|
||||
let gptoss = Arc::new(GptOssCodec::new(gptoss_vocabulary()).unwrap());
|
||||
let codecs = Codecs {
|
||||
qwen,
|
||||
gptoss,
|
||||
gptoss_vocabulary: gptoss_vocabulary(),
|
||||
};
|
||||
let mut captures = Vec::new();
|
||||
for case in cases.as_array().unwrap() {
|
||||
for (mode, stream) in [("stream", true), ("buffered", false)] {
|
||||
let name = format!("{}/{mode}", case["name"].as_str().unwrap());
|
||||
captures.push((name, run_case(case, stream, &codecs).await));
|
||||
}
|
||||
}
|
||||
fs::remove_dir_all(root).unwrap();
|
||||
captures
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn gateway_answers_for_scripted_output_match_the_recorded_golden() {
|
||||
let golden: Value =
|
||||
serde_json::from_str(&fs::read_to_string(fixture("output_events.json")).unwrap()).unwrap();
|
||||
let captures = capture_all().await;
|
||||
assert_eq!(
|
||||
captures.len(),
|
||||
golden.as_object().unwrap().len(),
|
||||
"case count"
|
||||
);
|
||||
for (name, actual) in captures {
|
||||
assert_eq!(golden[&name].as_str(), Some(actual.as_str()), "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Rewrites the expected captures from the current code. Only for a deliberate change of the gateway output.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[ignore = "regenerates tests/fixtures/golden/output_events.json"]
|
||||
async fn regenerate_output_golden() {
|
||||
let mut golden = serde_json::Map::new();
|
||||
for (name, text) in capture_all().await {
|
||||
golden.insert(name, Value::String(text));
|
||||
}
|
||||
let text = serde_json::to_string_pretty(&Value::Object(golden)).unwrap() + "\n";
|
||||
fs::write(fixture("output_events.json"), text).unwrap();
|
||||
}
|
||||
|
||||
/// The captures do not depend on the run: two runs agree.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn output_captures_are_deterministic() {
|
||||
assert_eq!(capture_all().await, capture_all().await);
|
||||
}
|
||||
+1634
File diff suppressed because it is too large
Load Diff
File diff suppressed because one or more lines are too long
Reference in New Issue
Block a user