Files
leleka/control-plane/tests/backend_worker_http/text_formats.rs
T

137 lines
5.5 KiB
Rust

//! Structured text formats and the prompts the contract refuses.
use crate::harness::{
Stack, assert_stream_invariants, body, scripted_text, sse_events, text_of, usage,
};
use crate::second_worker;
use leleka_backend_api::scripted::Script;
use serde_json::{Value, json};
use leleka_control_plane::wire::Generate;
fn result_schema_format() -> Value {
json!({"type": "json_schema", "name": "result", "strict": true,
"schema": {"type": "object", "properties": {"ok": {"type": "boolean"}},
"required": ["ok"], "additionalProperties": false}})
}
/// Scripts `output` as the engine's answer and asks for it under the schema format.
async fn post_with_schema(stack: &Stack, stream: bool, output: &str) -> (u16, String) {
scripted_text(&stack.engine, output, 4);
let request = body(json!({"stream": stream, "text": {"format": result_schema_format()}}));
stack.post("/v1/responses", &request).await
}
fn assert_valid_output_accepted(stream: bool, status: u16, text: &str) {
assert_eq!(status, 200, "{text}");
if stream {
let events = sse_events(text);
assert_stream_invariants(&events);
assert_eq!(events.last().unwrap()["type"], "response.completed");
} else {
let response: Value = serde_json::from_str(text).unwrap();
assert_eq!(text_of(&response), "{\"ok\":true}");
}
}
fn assert_invalid_output_fails(stream: bool, status: u16, text: &str) {
if stream {
assert_eq!(status, 200);
let events = sse_events(text);
assert_stream_invariants(&events);
assert_eq!(events.last().unwrap()["type"], "response.failed");
assert!(
!events
.iter()
.any(|e| e["type"] == "response.output_text.delta")
);
} else {
assert_eq!(status, 502, "{text}");
}
}
#[tokio::test]
async fn text_format_json_schema_accepts_valid_and_fails_invalid_output() {
let stack = Stack::start("bw-schema").await;
for stream in [false, true] {
let (status, text) = post_with_schema(&stack, stream, "{\"ok\":true}").await;
assert_valid_output_accepted(stream, status, &text);
let (status, text) = post_with_schema(&stack, stream, "{\"ok\":\"yes\"}").await;
assert_invalid_output_fails(stream, status, &text);
}
// The schema travels in the prompt (guidance), not as a decoding constraint.
assert!(stack.engine.requests()[0].prompt.contains("\"ok\""));
stack.finish().await;
}
/// The request is refused with a 400 that names every one of `needles`.
async fn assert_refused(stack: &Stack, request: Value, needles: &[&str]) {
let (status, text) = stack.post("/v1/responses", &request).await;
assert_eq!(status, 400, "{text}");
assert!(needles.iter().all(|n| text.contains(n)), "{text}");
}
#[tokio::test]
async fn text_the_contract_cannot_carry_is_refused_not_dropped() {
let stack = Stack::start("bw-refuse").await;
// Reasoning budget wrap-up needs token-level continuation.
let budget = body(json!({"reasoning": {"effort": "high"}, "reasoning_budget_tokens": 5}));
assert_refused(
&stack,
budget,
&["reasoning_budget_tokens", "unsupported_request_field"],
)
.await;
// Per-request engine tuning is not part of the contract.
let tune = body(json!({"strata_tune": {"pcie_frac": 0.5}}));
assert_refused(&stack, tune, &["strata_tune"]).await;
// Sampling that is not exact thousandths is refused like the daemon does.
let sampling = body(json!({"temperature": 0.0005}));
assert_refused(&stack, sampling, &["temperature"]).await;
// None of these reached the engine.
assert!(stack.engine.requests().is_empty());
// And the worker is still serving.
stack
.engine
.push(Script::stop_with(&["fine"], usage(1, 1, 0)));
assert_eq!(stack.post("/v1/responses", &body(json!({}))).await.0, 200);
stack.finish().await;
}
#[tokio::test]
async fn a_prompt_that_is_not_the_canonical_encoding_is_refused() {
// Two merged tokens "he","ll" are the canonical encoding of "hell" as "hell"; this id sequence is not.
let stack = Stack::start("bw-canonical").await;
let he = stack.tokenizer.encode("he", false).unwrap();
let ll = stack.tokenizer.encode("ll", false).unwrap();
assert_eq!(stack.tokenizer.encode("hell", false).unwrap().len(), 1);
let ids: Vec<u32> = he.iter().chain(ll.iter()).copied().collect();
// A second worker, fed the way the HTTP layer feeds it.
let worker = second_worker::start(&stack).await;
let request = Generate {
token_ids: ids,
max_new: 8,
..Default::default()
};
let outcome = second_worker::submit(&worker.requests, request).await;
let message = outcome.expect_err("a non-canonical prompt must not reach the engine");
assert!(message.contains("canonical encoding"), "{message}");
assert!(worker.handle.requests().is_empty());
stack.finish().await;
}
#[tokio::test]
async fn re_tokenized_pieces_keep_bytes_even_when_ids_differ_from_the_whole() {
let stack = Stack::start("bw-merges").await;
stack.engine.push(Script::stop_with(
&["he", "l", "l", "o tool"],
usage(3, 4, 0),
));
let (status, text) = stack.post("/v1/responses", &body(json!({}))).await;
assert_eq!(status, 200, "{text}");
let response: Value = serde_json::from_str(&text).unwrap();
assert_eq!(text_of(&response), "hello tool");
// Usage is what the engine counted (4), not what the merges make of the pieces.
assert_eq!(response["usage"]["output_tokens"], 4);
stack.finish().await;
}