Rust comments that named scripts/offline/*, gen_goldens.py, oracle/gen_*.{sh,cpp,py}, build_oracle.sh and similar retired generators now say where the data
came from (the Original's code, Strata 41cf05a0) or drop the sentence. The path/generator text of seven generated fixtures (sampler_oracle.json, sampling_keys.json,
memory_plan_golden.json, rope_golden.json, cvec_oracle.json, stra161 fixtures.json, commentary-tool-prompt.json) is reworded; no test reads those fields and no pin
covers their bytes. cmd_time/doc.rs: the two path texts in the format string; its lines are re-broken so they stay within 120 columns (the string is unchanged
otherwise). Comment-only except those data/string spots; no behaviour change.
227 lines
8.6 KiB
Rust
227 lines
8.6 KiB
Rust
#![cfg(unix)] // the engine stand-in is a /bin/sh script
|
|
//! The operational HTTP surface (`/props`, `/slots`, `/settings`, `/load`, `/unload`, `/v1/load`,
|
|
//! `/v1/unload`, `/v1/status`, `/api/health`, CORS, own-page guard) against the real Python
|
|
//! handlers: every scenario in `tests/fixtures/golden/http_surface.json` was recorded from
|
|
//! `Strata 41cf05a0, serve/server.py`, and is replayed here
|
|
//! against the Rust router with a real worker supervisor and the mock engine.
|
|
//!
|
|
//! Deliberate differences, skipped in the comparison: the chat template text, the build/version
|
|
//! strings, wall-clock fields, JSON parser error wording, the extra `/v1/responses` dialect, and
|
|
//! `x-api-key` (the Rust server accepts it on the Messages routes only).
|
|
|
|
#[path = "http_surface/harness.rs"]
|
|
mod harness;
|
|
|
|
use harness::Harness;
|
|
use leleka_control_plane::worker::WorkerState;
|
|
use serde_json::{Value, json};
|
|
|
|
fn fixture() -> Value {
|
|
serde_json::from_str(include_str!("fixtures/golden/http_surface.json")).unwrap()
|
|
}
|
|
|
|
fn remove_keys(value: &mut Value, keys: &[&str]) {
|
|
if let Some(map) = value.as_object_mut() {
|
|
for key in keys {
|
|
map.remove(*key);
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Both servers list the model and its aliases; the Python records carry llama-server extras.
|
|
fn reduce_models(value: &Value) -> Value {
|
|
let reduced: Vec<Value> = value["data"]
|
|
.as_array()
|
|
.into_iter()
|
|
.flatten()
|
|
.map(|record| {
|
|
json!({"id": record["id"], "alias_of": record["alias_of"],
|
|
"aliases": record["aliases"],
|
|
"status": record["status"]["value"].as_str().unwrap_or("loaded")})
|
|
})
|
|
.collect();
|
|
json!({"data": reduced})
|
|
}
|
|
|
|
fn strip_status_fields(value: &mut Value) {
|
|
remove_keys(
|
|
value,
|
|
&[
|
|
"engine",
|
|
"started",
|
|
"uptime_s",
|
|
"machine",
|
|
"dialects",
|
|
"last_timings",
|
|
// Rust-only extensions
|
|
"prefix_cache",
|
|
"memory",
|
|
],
|
|
);
|
|
if let Some(activity) = value.get_mut("activity") {
|
|
remove_keys(activity, &["last_request_at"]);
|
|
}
|
|
}
|
|
|
|
/// Remove what is allowed to differ and return the rest.
|
|
fn normalized(path: &str, mut value: Value) -> Value {
|
|
let path = path.split('?').next().unwrap();
|
|
match path {
|
|
"/v1/models" | "/models" => value = reduce_models(&value),
|
|
// `/health` stays the minimal liveness body of the existing smoke contract; `/api/health`
|
|
// carries the Python fields.
|
|
"/health" => value = json!({"status": value["status"]}),
|
|
"/props" => remove_keys(&mut value, &["chat_template", "build_info", "model_path"]),
|
|
"/v1/status" | "/v1/load" | "/v1/unload" => strip_status_fields(&mut value),
|
|
_ => {}
|
|
}
|
|
value
|
|
}
|
|
|
|
/// The Python server forwards its JSON parser's message; the Rust parser words it differently.
|
|
fn is_parser_message(status: u64, body: &Value) -> bool {
|
|
status == 400
|
|
&& body["error"]["message"].as_str().is_some_and(|m| m.contains("line 1 column") || m.contains("Expecting"))
|
|
}
|
|
|
|
/// What the Rust router answered: status, the CORS/vary headers and the JSON (or text) body.
|
|
struct Got {
|
|
status: u16,
|
|
headers: Vec<(String, String)>,
|
|
body: Value,
|
|
}
|
|
|
|
fn request_builder(
|
|
client: &reqwest::Client,
|
|
url: String,
|
|
method: &str,
|
|
(headers, body): (&serde_json::Map<String, Value>, &Value),
|
|
) -> reqwest::RequestBuilder {
|
|
let mut builder = client.request(reqwest::Method::from_bytes(method.as_bytes()).unwrap(), url);
|
|
let mut has_content_type = false;
|
|
for (key, value) in headers {
|
|
has_content_type |= key.eq_ignore_ascii_case("content-type");
|
|
builder = builder.header(key.as_str(), value.as_str().unwrap());
|
|
}
|
|
match body {
|
|
Value::Null => {}
|
|
Value::String(raw) => builder = builder.body(raw.clone()),
|
|
other => {
|
|
if !has_content_type {
|
|
builder = builder.header("content-type", "application/json");
|
|
}
|
|
builder = builder.body(other.to_string());
|
|
}
|
|
}
|
|
builder
|
|
}
|
|
|
|
async fn send(builder: reqwest::RequestBuilder, context: &str) -> Got {
|
|
let response = builder.send().await.unwrap_or_else(|e| panic!("{context}: {e}"));
|
|
let status = response.status().as_u16();
|
|
let headers: Vec<(String, String)> = response
|
|
.headers()
|
|
.iter()
|
|
.filter(|(k, _)| k.as_str().starts_with("access-control-") || k.as_str() == "vary")
|
|
.map(|(k, v)| (k.as_str().to_owned(), v.to_str().unwrap().to_owned()))
|
|
.collect();
|
|
let text = response.text().await.unwrap();
|
|
let body: Value =
|
|
if text.is_empty() { Value::Null } else { serde_json::from_str(&text).unwrap_or(Value::String(text)) };
|
|
Got { status, headers, body }
|
|
}
|
|
|
|
fn assert_response_status(got: &Got, step: &Value, context: &str) {
|
|
assert_eq!(u64::from(got.status), step["status"].as_u64().unwrap(), "{context}: {}", got.body);
|
|
}
|
|
|
|
fn assert_response_headers(got: &Got, step: &Value, context: &str) {
|
|
let got_headers = &got.headers;
|
|
let want_headers = step["headers"].as_object().unwrap();
|
|
assert_eq!(got_headers.len(), want_headers.len(), "{context}: {got_headers:?}");
|
|
for (key, value) in want_headers {
|
|
assert!(
|
|
got_headers.iter().any(|(k, v)| k == key && v == value.as_str().unwrap()),
|
|
"{context}: header {key}: {got_headers:?}"
|
|
);
|
|
}
|
|
}
|
|
|
|
/// Compares the body with the recorded one; true when only the error type could be compared.
|
|
fn assert_body(got: &Got, step: &Value, path: &str, context: &str) -> bool {
|
|
let got_body = &got.body;
|
|
if got.status == 401 {
|
|
// The Rust server's authentication body is its own (OpenAI-style code and message).
|
|
assert_eq!(got_body["error"]["type"], step["body"]["error"]["type"], "{context}");
|
|
false
|
|
} else if is_parser_message(step["status"].as_u64().unwrap(), &step["body"]) {
|
|
assert_eq!(got_body["error"]["type"], step["body"]["error"]["type"], "{context}");
|
|
true
|
|
} else {
|
|
let want_path = path.split('?').next().unwrap();
|
|
let want_body = normalized(want_path, step["body"].clone());
|
|
let got_body = normalized(want_path, got_body.clone());
|
|
assert_eq!(got_body, want_body, "{context}");
|
|
false
|
|
}
|
|
}
|
|
|
|
async fn assert_worker_loaded(harness: &Harness, step: &Value, context: &str) {
|
|
let loaded = harness.state.engine.worker.read().await.state == WorkerState::Ready;
|
|
assert_eq!(loaded, step["state"]["loaded"].as_bool().unwrap(), "{context}: loaded");
|
|
}
|
|
|
|
async fn assert_shared_settings(harness: &Harness, step: &Value, context: &str) {
|
|
assert_eq!(
|
|
harness.state.services.settings.shared().to_json(),
|
|
step["state"]["shared"],
|
|
"{context}: shared settings"
|
|
);
|
|
}
|
|
|
|
/// Replays one recorded step; returns (compared, skipped) counts.
|
|
async fn replay_step(
|
|
client: &reqwest::Client,
|
|
harness: &Harness,
|
|
(name, index): (&str, usize),
|
|
step: &Value,
|
|
) -> (u32, u32) {
|
|
let request = &step["request"];
|
|
let method = request["method"].as_str().unwrap();
|
|
let path = request["path"].as_str().unwrap();
|
|
let context = format!("{name} step {index}: {method} {path}");
|
|
let headers = request["headers"].as_object().cloned().unwrap_or_default();
|
|
if headers.keys().any(|k| k.eq_ignore_ascii_case("x-api-key")) {
|
|
return (0, 1);
|
|
}
|
|
let url = format!("{}{path}", harness.base);
|
|
let builder = request_builder(client, url, method, (&headers, &request["body"]));
|
|
let got = send(builder, &context).await;
|
|
assert_response_status(&got, step, &context);
|
|
assert_response_headers(&got, step, &context);
|
|
let skipped = assert_body(&got, step, path, &context);
|
|
assert_worker_loaded(harness, step, &context).await;
|
|
assert_shared_settings(harness, step, &context).await;
|
|
(1, u32::from(skipped))
|
|
}
|
|
|
|
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
|
async fn the_rust_surface_answers_like_the_python_server() {
|
|
let fixture = fixture();
|
|
let scenarios = fixture["scenarios"].as_object().unwrap();
|
|
assert!(scenarios.len() >= 17);
|
|
let client = reqwest::Client::builder().redirect(reqwest::redirect::Policy::none()).build().unwrap();
|
|
let mut compared = 0;
|
|
let mut skipped = 0;
|
|
for (name, scenario) in scenarios {
|
|
let harness = Harness::start(name, &scenario["setup"]).await;
|
|
for (index, step) in scenario["steps"].as_array().unwrap().iter().enumerate() {
|
|
let (done, left) = replay_step(&client, &harness, (name, index), step).await;
|
|
compared += done;
|
|
skipped += left;
|
|
}
|
|
harness.finish().await;
|
|
}
|
|
assert!(compared > 120, "{compared} compared, {skipped} skipped");
|
|
}
|