aien-sovereign-core-mv
AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.
Brought by drakestapleton
aien-sovereign-core-mv / crates / aien-serve-http / tests / loopback.rs
| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright 2026 Drake Stapleton (AIEN / aien-dev) |
| 3 | // |
| 4 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | // you may not use this file except in compliance with the License. |
| 6 | // You may obtain a copy of the License at |
| 7 | // |
| 8 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | // |
| 10 | // Unless required by applicable law or agreed to in writing, software |
| 11 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | // See the License for the specific language governing permissions and |
| 14 | // limitations under the License. |
| 15 | |
| 16 | //! Loopback integration tests: a real TCP server with the stub engine and the |
| 17 | //! byte codec, driven by a hand-written HTTP/1.1 client (no extra crates). |
| 18 | |
| 19 | use std::io::{Read, Write}; |
| 20 | use std::net::{SocketAddr, TcpStream}; |
| 21 | use std::sync::Arc; |
| 22 | use std::time::Duration; |
| 23 | |
| 24 | use aien_serve_http::codec::{ByteCodec, Codec, CodecError}; |
| 25 | use aien_serve_http::engine::StubEngine; |
| 26 | use aien_serve_http::server::{serve, ServerConfig}; |
| 27 | use serde_json::Value; |
| 28 | const TOKEN: &str = "integration-test-private-credential"; |
| 29 | |
| 30 | struct Server { |
| 31 | addr: SocketAddr, |
| 32 | _rt: tokio::runtime::Runtime, |
| 33 | } |
| 34 | |
| 35 | fn start(engine: StubEngine, cfg: ServerConfig) -> Server { |
| 36 | let rt = tokio::runtime::Runtime::new().expect("runtime"); |
| 37 | let cfg = ServerConfig { |
| 38 | port: 0, |
| 39 | model_id: "test-model".into(), |
| 40 | bearer_token: TOKEN.into(), |
| 41 | ..cfg |
| 42 | }; |
| 43 | let (addr, _handle) = rt |
| 44 | .block_on(serve(cfg, Arc::new(engine), Arc::new(ByteCodec))) |
| 45 | .expect("bind loopback"); |
| 46 | Server { addr, _rt: rt } |
| 47 | } |
| 48 | |
| 49 | fn stub(reply: &str) -> StubEngine { |
| 50 | StubEngine::new(reply.bytes().map(u32::from).collect()) |
| 51 | } |
| 52 | |
| 53 | struct Reply { |
| 54 | status: u16, |
| 55 | headers: String, |
| 56 | body: String, |
| 57 | } |
| 58 | |
| 59 | fn dechunk(raw: &[u8]) -> Vec<u8> { |
| 60 | let mut out = Vec::new(); |
| 61 | let mut i = 0; |
| 62 | loop { |
| 63 | let line_end = raw[i..] |
| 64 | .windows(2) |
| 65 | .position(|w| w == b"\r\n") |
| 66 | .expect("chunk size line") |
| 67 | + i; |
| 68 | let size = |
| 69 | usize::from_str_radix(std::str::from_utf8(&raw[i..line_end]).unwrap().trim(), 16) |
| 70 | .expect("hex chunk size"); |
| 71 | if size == 0 { |
| 72 | return out; |
| 73 | } |
| 74 | out.extend_from_slice(&raw[line_end + 2..line_end + 2 + size]); |
| 75 | i = line_end + 2 + size + 2; |
| 76 | } |
| 77 | } |
| 78 | |
| 79 | fn request(addr: SocketAddr, method: &str, path: &str, body: Option<&str>) -> Reply { |
| 80 | let mut s = TcpStream::connect(addr).expect("connect"); |
| 81 | s.set_read_timeout(Some(Duration::from_secs(30))).unwrap(); |
| 82 | let body = body.unwrap_or(""); |
| 83 | let req = format!( |
| 84 | "{method} {path} HTTP/1.1\r\nHost: localhost\r\nAuthorization: Bearer {TOKEN}\r\nConnection: close\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{body}", |
| 85 | body.len() |
| 86 | ); |
| 87 | s.write_all(req.as_bytes()).unwrap(); |
| 88 | let mut raw = Vec::new(); |
| 89 | s.read_to_end(&mut raw).expect("read reply"); |
| 90 | let split = raw |
| 91 | .windows(4) |
| 92 | .position(|w| w == b"\r\n\r\n") |
| 93 | .expect("header end"); |
| 94 | let headers = String::from_utf8_lossy(&raw[..split]).to_string(); |
| 95 | let status: u16 = headers |
| 96 | .split_whitespace() |
| 97 | .nth(1) |
| 98 | .and_then(|s| s.parse().ok()) |
| 99 | .expect("status code"); |
| 100 | let body_raw = &raw[split + 4..]; |
| 101 | let body = if headers |
| 102 | .to_ascii_lowercase() |
| 103 | .contains("transfer-encoding: chunked") |
| 104 | { |
| 105 | String::from_utf8(dechunk(body_raw)).unwrap() |
| 106 | } else { |
| 107 | String::from_utf8(body_raw.to_vec()).unwrap() |
| 108 | }; |
| 109 | Reply { |
| 110 | status, |
| 111 | headers, |
| 112 | body, |
| 113 | } |
| 114 | } |
| 115 | |
| 116 | fn chat(addr: SocketAddr, body: &str) -> Reply { |
| 117 | request(addr, "POST", "/v1/chat/completions", Some(body)) |
| 118 | } |
| 119 | |
| 120 | fn json(r: &Reply) -> Value { |
| 121 | serde_json::from_str(&r.body).unwrap_or_else(|e| panic!("not JSON ({e}): {}", r.body)) |
| 122 | } |
| 123 | |
| 124 | /// `data:` payloads of an SSE body, in order; comment lines are skipped. |
| 125 | fn sse_data(body: &str) -> Vec<String> { |
| 126 | body.lines() |
| 127 | .filter_map(|l| l.strip_prefix("data: ").or_else(|| l.strip_prefix("data:"))) |
| 128 | .map(|s| s.trim().to_string()) |
| 129 | .collect() |
| 130 | } |
| 131 | |
| 132 | const PROMPT: &str = r#"{"model":"test-model","messages":[{"role":"system","content":"s"},{"role":"user","content":"hi"}]}"#; |
| 133 | // ByteCodec renders "<system>s</system>\n<user>hi</user>\n<assistant>" = 46 bytes. |
| 134 | const PROMPT_TOKENS: u64 = 46; |
| 135 | |
| 136 | #[test] |
| 137 | fn models_lists_the_one_served_id() { |
| 138 | let srv = start(stub("x"), ServerConfig::default()); |
| 139 | let r = request(srv.addr, "GET", "/v1/models", None); |
| 140 | assert_eq!(r.status, 200); |
| 141 | let v = json(&r); |
| 142 | assert_eq!(v["object"], "list"); |
| 143 | assert_eq!(v["data"][0]["id"], "test-model"); |
| 144 | assert_eq!(v["data"][0]["owned_by"], "aien/stub"); |
| 145 | let r = request(srv.addr, "GET", "/v1/models/other", None); |
| 146 | assert_eq!(r.status, 404); |
| 147 | assert_eq!(json(&r)["error"]["type"], "not_found_error"); |
| 148 | let h = json(&request(srv.addr, "GET", "/health", None)); |
| 149 | assert_eq!(h["status"], "ok"); |
| 150 | assert_eq!(h["busy"], false); |
| 151 | } |
| 152 | |
| 153 | #[test] |
| 154 | fn non_stream_completion_has_content_usage_and_finish() { |
| 155 | let srv = start(stub("Hello, world!"), ServerConfig::default()); |
| 156 | let r = chat(srv.addr, PROMPT); |
| 157 | assert_eq!(r.status, 200, "{}", r.body); |
| 158 | let v = json(&r); |
| 159 | assert_eq!(v["object"], "chat.completion"); |
| 160 | assert_eq!(v["model"], "test-model"); |
| 161 | assert_eq!(v["choices"][0]["message"]["role"], "assistant"); |
| 162 | assert_eq!(v["choices"][0]["message"]["content"], "Hello, world!"); |
| 163 | assert_eq!(v["choices"][0]["finish_reason"], "stop"); |
| 164 | assert_eq!(v["usage"]["prompt_tokens"], PROMPT_TOKENS); |
| 165 | assert_eq!(v["usage"]["completion_tokens"], 13); |
| 166 | assert_eq!(v["usage"]["total_tokens"], PROMPT_TOKENS + 13); |
| 167 | assert!(v["id"].as_str().unwrap().starts_with("chatcmpl-")); |
| 168 | } |
| 169 | |
| 170 | #[test] |
| 171 | fn stream_chunks_parse_and_end_with_done() { |
| 172 | let srv = start(stub("héllo wörld"), ServerConfig::default()); |
| 173 | let body = r#"{"messages":[{"role":"user","content":"hi"}],"stream":true}"#; |
| 174 | let r = chat(srv.addr, body); |
| 175 | assert_eq!(r.status, 200, "{}", r.body); |
| 176 | assert!( |
| 177 | r.headers |
| 178 | .to_ascii_lowercase() |
| 179 | .contains("content-type: text/event-stream"), |
| 180 | "{}", |
| 181 | r.headers |
| 182 | ); |
| 183 | let data = sse_data(&r.body); |
| 184 | assert!(data.len() >= 3, "{data:?}"); |
| 185 | assert_eq!(data.last().unwrap(), "[DONE]"); |
| 186 | let chunks: Vec<Value> = data[..data.len() - 1] |
| 187 | .iter() |
| 188 | .map(|d| serde_json::from_str(d).unwrap_or_else(|e| panic!("chunk not JSON ({e}): {d}"))) |
| 189 | .collect(); |
| 190 | assert!(chunks |
| 191 | .iter() |
| 192 | .all(|c| c["object"] == "chat.completion.chunk")); |
| 193 | assert_eq!(chunks[0]["choices"][0]["delta"]["role"], "assistant"); |
| 194 | let text: String = chunks |
| 195 | .iter() |
| 196 | .filter_map(|c| c["choices"][0]["delta"]["content"].as_str()) |
| 197 | .collect(); |
| 198 | assert_eq!(text, "héllo wörld"); |
| 199 | assert!( |
| 200 | chunks.iter().all(|c| !c.to_string().contains('\u{FFFD}')), |
| 201 | "a chunk split a character" |
| 202 | ); |
| 203 | let last = chunks.last().unwrap(); |
| 204 | assert_eq!(last["choices"][0]["finish_reason"], "stop"); |
| 205 | assert_eq!(last["usage"]["completion_tokens"], 13); |
| 206 | assert_eq!(last["usage"]["prompt_tokens"], 27); // "<user>hi</user>\n<assistant>" |
| 207 | } |
| 208 | |
| 209 | #[test] |
| 210 | fn second_request_while_busy_is_rejected_then_accepted() { |
| 211 | let reply: String = "x".repeat(60); |
| 212 | let srv = start( |
| 213 | stub(&reply).with_delay(Duration::from_millis(25)), |
| 214 | ServerConfig::default(), |
| 215 | ); |
| 216 | let addr = srv.addr; |
| 217 | let first = std::thread::spawn(move || { |
| 218 | chat( |
| 219 | addr, |
| 220 | r#"{"messages":[{"role":"user","content":"a"}],"stream":true}"#, |
| 221 | ) |
| 222 | }); |
| 223 | std::thread::sleep(Duration::from_millis(300)); |
| 224 | let busy = chat(addr, PROMPT); |
| 225 | assert_eq!(busy.status, 503, "{}", busy.body); |
| 226 | assert_eq!(json(&busy)["error"]["type"], "server_busy"); |
| 227 | assert!( |
| 228 | busy.headers.to_ascii_lowercase().contains("retry-after: 1"), |
| 229 | "{}", |
| 230 | busy.headers |
| 231 | ); |
| 232 | assert_eq!(json(&request(addr, "GET", "/health", None))["busy"], true); |
| 233 | let first = first.join().unwrap(); |
| 234 | assert_eq!(first.status, 200); |
| 235 | assert_eq!(sse_data(&first.body).last().unwrap(), "[DONE]"); |
| 236 | let after = chat(addr, PROMPT); |
| 237 | assert_eq!(after.status, 200, "{}", after.body); |
| 238 | assert_eq!(json(&after)["choices"][0]["message"]["content"], reply); |
| 239 | } |
| 240 | |
| 241 | fn raw_request(addr: SocketAddr, raw: &str) -> Reply { |
| 242 | let mut s = TcpStream::connect(addr).expect("connect"); |
| 243 | s.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); |
| 244 | s.write_all(raw.as_bytes()).unwrap(); |
| 245 | let mut bytes = Vec::new(); |
| 246 | s.read_to_end(&mut bytes).unwrap(); |
| 247 | let split = bytes.windows(4).position(|v| v == b"\r\n\r\n").unwrap(); |
| 248 | let headers = String::from_utf8_lossy(&bytes[..split]).into_owned(); |
| 249 | let status = headers.split_whitespace().nth(1).unwrap().parse().unwrap(); |
| 250 | let body = if headers |
| 251 | .to_ascii_lowercase() |
| 252 | .contains("transfer-encoding: chunked") |
| 253 | { |
| 254 | String::from_utf8(dechunk(&bytes[split + 4..])).unwrap() |
| 255 | } else { |
| 256 | String::from_utf8_lossy(&bytes[split + 4..]).into_owned() |
| 257 | }; |
| 258 | Reply { |
| 259 | status, |
| 260 | headers, |
| 261 | body, |
| 262 | } |
| 263 | } |
| 264 | |
| 265 | fn raw_post(addr: SocketAddr, headers: &str, body: &str) -> Reply { |
| 266 | raw_request(addr, &format!( |
| 267 | "POST /v1/chat/completions HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n{headers}Content-Length: {}\r\n\r\n{body}", |
| 268 | body.len() |
| 269 | )) |
| 270 | } |
| 271 | |
| 272 | #[test] |
| 273 | fn inference_requires_authorization_and_local_json_origin() { |
| 274 | let rt = tokio::runtime::Runtime::new().unwrap(); |
| 275 | let no_credential = ServerConfig { |
| 276 | port: 0, |
| 277 | ..ServerConfig::default() |
| 278 | }; |
| 279 | assert!(rt |
| 280 | .block_on(serve( |
| 281 | no_credential, |
| 282 | Arc::new(stub("x")), |
| 283 | Arc::new(ByteCodec) |
| 284 | )) |
| 285 | .is_err()); |
| 286 | let srv = start(stub("accepted"), ServerConfig::default()); |
| 287 | let missing = raw_post(srv.addr, "Content-Type: application/json\r\n", PROMPT); |
| 288 | assert_eq!(missing.status, 401); |
| 289 | assert_eq!( |
| 290 | raw_post( |
| 291 | srv.addr, |
| 292 | "Authorization: Bearer wrong\r\nContent-Type: application/json\r\n", |
| 293 | PROMPT |
| 294 | ) |
| 295 | .status, |
| 296 | 401 |
| 297 | ); |
| 298 | let auth = format!("Authorization: Bearer {TOKEN}\r\n"); |
| 299 | assert_eq!( |
| 300 | raw_post( |
| 301 | srv.addr, |
| 302 | &format!("{auth}Origin: https://hostile.example\r\nContent-Type: application/json\r\n"), |
| 303 | PROMPT |
| 304 | ) |
| 305 | .status, |
| 306 | 403 |
| 307 | ); |
| 308 | assert_eq!( |
| 309 | raw_post( |
| 310 | srv.addr, |
| 311 | &format!("{auth}Content-Type: text/plain\r\n"), |
| 312 | PROMPT |
| 313 | ) |
| 314 | .status, |
| 315 | 415 |
| 316 | ); |
| 317 | let hostile_host = format!("POST /v1/chat/completions HTTP/1.1\r\nHost: attacker.example\r\n{auth}Content-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{PROMPT}", PROMPT.len()); |
| 318 | assert_eq!(raw_request(srv.addr, &hostile_host).status, 403); |
| 319 | // None of these requests sends its declared body; refusal must precede extraction. |
| 320 | for (headers, expected) in [ |
| 321 | ("Content-Type: application/json\r\n".to_string(), 401), |
| 322 | ( |
| 323 | format!("{auth}Origin: https://hostile.example\r\nContent-Type: application/json\r\n"), |
| 324 | 403, |
| 325 | ), |
| 326 | (format!("{auth}Content-Type: text/plain\r\n"), 415), |
| 327 | ] { |
| 328 | let incomplete = format!("POST /v1/chat/completions HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n{headers}Content-Length: 100\r\n\r\n"); |
| 329 | assert_eq!(raw_request(srv.addr, &incomplete).status, expected); |
| 330 | } |
| 331 | let good = raw_post(srv.addr, &format!("{auth}Origin: http://localhost:{}\r\nContent-Type: application/json; charset=utf-8\r\n", srv.addr.port()), PROMPT); |
| 332 | assert_eq!(good.status, 200, "{}", good.body); |
| 333 | assert_eq!(json(&good)["choices"][0]["message"]["content"], "accepted"); |
| 334 | } |
| 335 | |
| 336 | /// Counts `encode` calls. The first call is the occupying request's own prompt: it reports that it |
| 337 | /// has been counted and then waits for the test's release. The server takes the engine slot before |
| 338 | /// reading the body and keeps it through tokenizing, so while that call waits the server is |
| 339 | /// saturated and the count already includes the occupying request; any later increment comes from |
| 340 | /// a request that met the busy server. |
| 341 | struct CountingCodec { |
| 342 | calls: std::sync::atomic::AtomicUsize, |
| 343 | entered: std::sync::mpsc::Sender<()>, |
| 344 | release: std::sync::Mutex<std::sync::mpsc::Receiver<()>>, |
| 345 | } |
| 346 | |
| 347 | impl Codec for CountingCodec { |
| 348 | fn render_chat(&self, turns: &[(&str, &str)]) -> Result<String, CodecError> { |
| 349 | ByteCodec.render_chat(turns) |
| 350 | } |
| 351 | fn encode(&self, text: &str) -> Result<Vec<u32>, CodecError> { |
| 352 | if self.calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst) == 0 { |
| 353 | let _ = self.entered.send(()); |
| 354 | // Ends on the test's release, or with an error once a failing test has dropped its |
| 355 | // sender, so a failed assertion never leaves this request (and the runtime) waiting. |
| 356 | let _ = self.release.lock().unwrap().recv(); |
| 357 | } |
| 358 | ByteCodec.encode(text) |
| 359 | } |
| 360 | fn decode(&self, ids: &[u32]) -> Result<String, CodecError> { |
| 361 | ByteCodec.decode(ids) |
| 362 | } |
| 363 | fn stop_token_ids(&self) -> Vec<u32> { |
| 364 | ByteCodec.stop_token_ids() |
| 365 | } |
| 366 | } |
| 367 | |
| 368 | #[test] |
| 369 | fn saturated_request_does_not_read_body_or_invoke_codec() { |
| 370 | use std::sync::atomic::Ordering; |
| 371 | let rt = tokio::runtime::Runtime::new().unwrap(); |
| 372 | let (entered_tx, entered) = std::sync::mpsc::channel(); |
| 373 | let (release, release_rx) = std::sync::mpsc::channel(); |
| 374 | let codec = Arc::new(CountingCodec { |
| 375 | calls: std::sync::atomic::AtomicUsize::new(0), |
| 376 | entered: entered_tx, |
| 377 | release: std::sync::Mutex::new(release_rx), |
| 378 | }); |
| 379 | let cfg = ServerConfig { |
| 380 | port: 0, |
| 381 | model_id: "test-model".into(), |
| 382 | bearer_token: TOKEN.into(), |
| 383 | ..ServerConfig::default() |
| 384 | }; |
| 385 | let (addr, _h) = rt |
| 386 | .block_on(serve(cfg, Arc::new(stub(&"x".repeat(60))), codec.clone())) |
| 387 | .unwrap(); |
| 388 | let first = std::thread::spawn(move || chat(addr, PROMPT)); |
| 389 | // `/health` reports busy as soon as the slot is taken, before the occupying request has read |
| 390 | // its body or tokenized; wait for its own encode so that call is not charged to the requests |
| 391 | // below. |
| 392 | entered |
| 393 | .recv_timeout(Duration::from_secs(30)) |
| 394 | .expect("occupying request never reached the tokenizer"); |
| 395 | assert_eq!(json(&request(addr, "GET", "/health", None))["busy"], true); |
| 396 | let before = codec.calls.load(Ordering::SeqCst); |
| 397 | assert_eq!(before, 1, "only the occupying request has tokenized"); |
| 398 | let full = raw_post( |
| 399 | addr, |
| 400 | &format!("Authorization: Bearer {TOKEN}\r\nContent-Type: application/json\r\n"), |
| 401 | PROMPT, |
| 402 | ); |
| 403 | assert_eq!(full.status, 503); |
| 404 | assert_eq!( |
| 405 | codec.calls.load(Ordering::SeqCst), |
| 406 | before, |
| 407 | "busy request invoked tokenizer" |
| 408 | ); |
| 409 | let incomplete = format!("POST /v1/chat/completions HTTP/1.1\r\nHost: localhost\r\nAuthorization: Bearer {TOKEN}\r\nContent-Type: application/json\r\nContent-Length: 100\r\nConnection: close\r\n\r\n"); |
| 410 | let rejected = raw_request(addr, &incomplete); |
| 411 | assert_eq!(rejected.status, 503, "{}", rejected.body); |
| 412 | assert_eq!(codec.calls.load(Ordering::SeqCst), before); |
| 413 | release.send(()).unwrap(); |
| 414 | assert_eq!(first.join().unwrap().status, 200); |
| 415 | } |
| 416 | |
| 417 | #[test] |
| 418 | fn bad_requests_get_openai_error_json() { |
| 419 | let srv = start( |
| 420 | stub("x"), |
| 421 | ServerConfig { |
| 422 | max_body_bytes: 2048, |
| 423 | ..ServerConfig::default() |
| 424 | }, |
| 425 | ); |
| 426 | let cases: Vec<(&str, String, u16, &str)> = vec![ |
| 427 | ("not json", "{nope".into(), 400, "invalid JSON"), |
| 428 | ("no messages", r#"{"messages":[]}"#.into(), 400, "non-empty"), |
| 429 | ( |
| 430 | "temperature", |
| 431 | r#"{"messages":[{"role":"user","content":"x"}],"temperature":5}"#.into(), |
| 432 | 400, |
| 433 | "temperature", |
| 434 | ), |
| 435 | ( |
| 436 | "image part", |
| 437 | r#"{"messages":[{"role":"user","content":[{"type":"image_url","image_url":{"url":"x"}}]}]}"#.into(), |
| 438 | 400, |
| 439 | "text parts", |
| 440 | ), |
| 441 | ( |
| 442 | "wrong model", |
| 443 | r#"{"model":"gpt-4","messages":[{"role":"user","content":"x"}]}"#.into(), |
| 444 | 404, |
| 445 | "not found", |
| 446 | ), |
| 447 | ( |
| 448 | "too large", |
| 449 | format!(r#"{{"messages":[{{"role":"user","content":"{}"}}]}}"#, "y".repeat(4000)), |
| 450 | 413, |
| 451 | "exceeds", |
| 452 | ), |
| 453 | ]; |
| 454 | for (name, body, status, needle) in cases { |
| 455 | let r = chat(srv.addr, &body); |
| 456 | assert_eq!(r.status, status, "{name}: {}", r.body); |
| 457 | let v = json(&r); |
| 458 | let msg = v["error"]["message"].as_str().unwrap_or_default(); |
| 459 | assert!(msg.contains(needle), "{name}: {msg}"); |
| 460 | } |
| 461 | // Tool calling is supported (Qwen3.6 tool format, coordinator 2026-10-21): tools, tool turns and |
| 462 | // assistant tool_calls render instead of being refused. |
| 463 | for body in [ |
| 464 | r#"{"messages":[{"role":"user","content":"x"}],"tools":[{"type":"function","function":{"name":"f","parameters":{}}}]}"#, |
| 465 | r#"{"messages":[{"role":"user","content":"x"},{"role":"assistant","content":null,"tool_calls":[{"id":"c","type":"function","function":{"name":"f","arguments":"{\"a\":1}"}}]},{"role":"tool","tool_call_id":"c","content":"ok"}],"tools":[{"type":"function","function":{"name":"f","parameters":{}}}]}"#, |
| 466 | ] { |
| 467 | let r = chat(srv.addr, body); |
| 468 | assert_eq!(r.status, 200, "tools request: {}", r.body); |
| 469 | } |
| 470 | let r = request(srv.addr, "GET", "/nope", None); |
| 471 | assert_eq!(r.status, 404); |
| 472 | assert_eq!(json(&r)["error"]["type"], "not_found_error"); |
| 473 | } |
| 474 | |
| 475 | #[test] |
| 476 | fn stop_sequences_and_max_tokens_apply() { |
| 477 | let srv = start(stub("Hello, world!"), ServerConfig::default()); |
| 478 | let r = chat( |
| 479 | srv.addr, |
| 480 | r#"{"messages":[{"role":"user","content":"hi"}],"stop":["world"]}"#, |
| 481 | ); |
| 482 | let v = json(&r); |
| 483 | assert_eq!(v["choices"][0]["message"]["content"], "Hello, "); |
| 484 | assert_eq!(v["choices"][0]["finish_reason"], "stop"); |
| 485 | |
| 486 | let r = chat( |
| 487 | srv.addr, |
| 488 | r#"{"messages":[{"role":"user","content":"hi"}],"max_tokens":5,"stream":true}"#, |
| 489 | ); |
| 490 | let data = sse_data(&r.body); |
| 491 | let chunks: Vec<Value> = data[..data.len() - 1] |
| 492 | .iter() |
| 493 | .map(|d| serde_json::from_str(d).unwrap()) |
| 494 | .collect(); |
| 495 | let text: String = chunks |
| 496 | .iter() |
| 497 | .filter_map(|c| c["choices"][0]["delta"]["content"].as_str()) |
| 498 | .collect(); |
| 499 | assert_eq!(text, "Hello"); |
| 500 | let last = chunks.last().unwrap(); |
| 501 | assert_eq!(last["choices"][0]["finish_reason"], "length"); |
| 502 | assert_eq!(last["usage"]["completion_tokens"], 5); |
| 503 | } |
| 504 | |
| 505 | #[test] |
| 506 | fn prompt_that_fills_the_context_is_refused() { |
| 507 | let srv = start(stub("x").with_max_context(30), ServerConfig::default()); |
| 508 | let r = chat(srv.addr, PROMPT); |
| 509 | assert_eq!(r.status, 400, "{}", r.body); |
| 510 | assert_eq!(json(&r)["error"]["code"], "context_length_exceeded"); |
| 511 | } |
| 512 | |
| 513 | #[test] |
| 514 | fn prompt_the_memory_cannot_hold_is_refused_with_413_and_the_limit() { |
| 515 | let why = "prompt of 66000 tokens needs 13.9 GB more host memory but only 9.0 GB is available; send at most about 0 tokens now"; |
| 516 | let srv = start(stub("x").with_admit_refusal(why), ServerConfig::default()); |
| 517 | let r = chat(srv.addr, PROMPT); |
| 518 | assert_eq!(r.status, 413, "{}", r.body); |
| 519 | let j = json(&r); |
| 520 | assert_eq!(j["error"]["code"], "prompt_exceeds_memory_budget"); |
| 521 | assert_eq!(j["error"]["message"], why); |
| 522 | } |
| 523 | |
| 524 | /// The engine's own admission (omega door: `generate` re-checks memory after the server's |
| 525 | /// `admit` passed) refusing is the same 413, streaming included (nothing has been sent yet). |
| 526 | #[test] |
| 527 | fn a_memory_refusal_inside_the_engine_is_the_same_413() { |
| 528 | let why = "prompt of 66000 tokens needs 13.9 GB more host memory but only 9.0 GB is available; send at most about 0 tokens now"; |
| 529 | let srv = start( |
| 530 | stub("x").with_generate_refusal(why), |
| 531 | ServerConfig::default(), |
| 532 | ); |
| 533 | for body in [ |
| 534 | PROMPT, |
| 535 | r#"{"messages":[{"role":"user","content":"hi"}],"stream":true}"#, |
| 536 | ] { |
| 537 | let r = chat(srv.addr, body); |
| 538 | assert_eq!(r.status, 413, "{body}: {}", r.body); |
| 539 | let j = json(&r); |
| 540 | assert_eq!(j["error"]["code"], "prompt_exceeds_memory_budget"); |
| 541 | assert_eq!(j["error"]["message"], why); |
| 542 | } |
| 543 | } |
| 544 | |
| 545 | #[test] |
| 546 | fn non_loopback_bind_is_refused() { |
| 547 | let rt = tokio::runtime::Runtime::new().unwrap(); |
| 548 | let cfg = ServerConfig { |
| 549 | bind: "0.0.0.0".parse().unwrap(), |
| 550 | port: 0, |
| 551 | ..ServerConfig::default() |
| 552 | }; |
| 553 | let err = rt |
| 554 | .block_on(serve(cfg, Arc::new(stub("x")), Arc::new(ByteCodec))) |
| 555 | .expect_err("must refuse"); |
| 556 | assert!(err.to_string().contains("loopback"), "{err}"); |
| 557 | } |
| 558 | |
| 559 | // --------------------------------------------------------------------------------------------- |
| 560 | // OWN-8B stage S: observed, seeded sampling through HTTP. The engine is the real Omega door over |
| 561 | // the tiny host-test Qwen3-MoE (`host-test-engine`: real logits, host matmuls, no chip), so these |
| 562 | // are gates (a) replay, (b) spread and (c) greedy of `scripts/sampling-gate.sh` on the host. |
| 563 | |
| 564 | mod sampling_gate { |
| 565 | use super::*; |
| 566 | use aien_inference_abi::qwen3_moe_omega::{host_test_engine, WeightFormat}; |
| 567 | use aien_serve_http::codec::{Codec, CodecError}; |
| 568 | use aien_serve_http::engine::{Engine, EngineError, GenerateOutcome, GenerateParams}; |
| 569 | use aien_serve_http::omega_engine::OmegaDoor; |
| 570 | use std::path::PathBuf; |
| 571 | |
| 572 | /// The tiny model has 64 tokens: bytes map to `b % 64` on the way in, token `t` decodes to |
| 573 | /// the printable byte `'0' + t` on the way out. Nothing stops early (no stop ids). |
| 574 | struct TinyCodec; |
| 575 | |
| 576 | impl Codec for TinyCodec { |
| 577 | fn render_chat(&self, turns: &[(&str, &str)]) -> Result<String, CodecError> { |
| 578 | ByteCodec.render_chat(turns) |
| 579 | } |
| 580 | fn encode(&self, text: &str) -> Result<Vec<u32>, CodecError> { |
| 581 | Ok(text.bytes().map(|b| u32::from(b) % 64).collect()) |
| 582 | } |
| 583 | fn decode(&self, tokens: &[u32]) -> Result<String, CodecError> { |
| 584 | Ok(tokens |
| 585 | .iter() |
| 586 | .map(|&t| char::from(b'0' + (t % 64) as u8)) |
| 587 | .collect()) |
| 588 | } |
| 589 | fn stop_token_ids(&self) -> Vec<u32> { |
| 590 | Vec::new() |
| 591 | } |
| 592 | } |
| 593 | |
| 594 | /// Negative controls: the real door with the request's seed or temperature overridden, |
| 595 | /// the way an engine that ignores the seed (or always takes the argmax) would behave. |
| 596 | struct Broken { |
| 597 | door: OmegaDoor, |
| 598 | force_seed: Option<u64>, |
| 599 | force_greedy: bool, |
| 600 | } |
| 601 | |
| 602 | impl Engine for Broken { |
| 603 | fn kind(&self) -> &str { |
| 604 | "broken-sampler" |
| 605 | } |
| 606 | fn max_context_tokens(&self) -> usize { |
| 607 | self.door.max_context_tokens() |
| 608 | } |
| 609 | fn generate( |
| 610 | &self, |
| 611 | prompt: &[u32], |
| 612 | params: &GenerateParams, |
| 613 | on_token: &mut dyn FnMut(u32) -> bool, |
| 614 | ) -> Result<GenerateOutcome, EngineError> { |
| 615 | let mut p = params.clone(); |
| 616 | if let Some(s) = self.force_seed { |
| 617 | p.seed = s; |
| 618 | } |
| 619 | if self.force_greedy { |
| 620 | p.temperature = 0.0; |
| 621 | } |
| 622 | self.door.generate(prompt, &p, on_token) |
| 623 | } |
| 624 | } |
| 625 | |
| 626 | fn lock_path(tag: &str) -> PathBuf { |
| 627 | std::env::temp_dir().join(format!("stage-s-{tag}-{}.lock", std::process::id())) |
| 628 | } |
| 629 | |
| 630 | fn door(tag: &str) -> OmegaDoor { |
| 631 | let e = host_test_engine::engine(WeightFormat::Fp8All, 256).expect("tiny engine"); |
| 632 | OmegaDoor::from_parts(e, lock_path(tag), Duration::from_secs(20)) |
| 633 | } |
| 634 | |
| 635 | fn serve_engine(engine: Arc<dyn Engine>) -> Server { |
| 636 | let rt = tokio::runtime::Runtime::new().expect("runtime"); |
| 637 | let cfg = ServerConfig { |
| 638 | port: 0, |
| 639 | model_id: "tiny".into(), |
| 640 | bearer_token: TOKEN.into(), |
| 641 | ..ServerConfig::default() |
| 642 | }; |
| 643 | let (addr, _h) = rt |
| 644 | .block_on(serve(cfg, engine, Arc::new(TinyCodec))) |
| 645 | .expect("bind loopback"); |
| 646 | Server { addr, _rt: rt } |
| 647 | } |
| 648 | |
| 649 | const PROMPTS: [&str; 4] = [ |
| 650 | "In one sentence, what is a Grace Blackwell GB10?", |
| 651 | "Count from one to ten in words, comma separated.", |
| 652 | "Name three colours.", |
| 653 | "Give me three numbered steps for checking a bolt is torqued correctly.", |
| 654 | ]; |
| 655 | |
| 656 | fn body(prompt: &str, temperature: f32, top_p: f32, top_k: u32, seed: Option<u64>) -> String { |
| 657 | let mut v = serde_json::json!({ |
| 658 | "model": "tiny", |
| 659 | "max_tokens": 48, |
| 660 | "temperature": temperature, |
| 661 | "top_p": top_p, |
| 662 | "top_k": top_k, |
| 663 | "messages": [{"role": "user", "content": prompt}], |
| 664 | }); |
| 665 | if let Some(s) = seed { |
| 666 | v["seed"] = s.into(); |
| 667 | } |
| 668 | v.to_string() |
| 669 | } |
| 670 | |
| 671 | /// (content, usage.aien_sampling) of one non-streaming request, sent the moment the previous |
| 672 | /// reply arrived (no retry: the slot is free once a reply is out). |
| 673 | fn ask(addr: SocketAddr, body: &str) -> (String, Value) { |
| 674 | let r = chat(addr, body); |
| 675 | assert_eq!(r.status, 200, "{}", r.body); |
| 676 | let v = json(&r); |
| 677 | let content = v["choices"][0]["message"]["content"] |
| 678 | .as_str() |
| 679 | .expect("content") |
| 680 | .to_string(); |
| 681 | (content, v["usage"]["aien_sampling"].clone()) |
| 682 | } |
| 683 | |
| 684 | /// Gate (a): seed 1 at temperature 1.0, top_p 1.0, top_k 0 twice: identical, per prompt. |
| 685 | fn gate_a(addr: SocketAddr) -> usize { |
| 686 | PROMPTS |
| 687 | .iter() |
| 688 | .filter(|p| { |
| 689 | let b = body(p, 1.0, 1.0, 0, Some(1)); |
| 690 | ask(addr, &b).0 == ask(addr, &b).0 |
| 691 | }) |
| 692 | .count() |
| 693 | } |
| 694 | |
| 695 | /// Gate (b): seeds 1, 2, 3 at the same settings: at least 2 distinct replies, per prompt. |
| 696 | fn gate_b(addr: SocketAddr) -> usize { |
| 697 | PROMPTS |
| 698 | .iter() |
| 699 | .filter(|p| { |
| 700 | let mut r: Vec<String> = (1..=3) |
| 701 | .map(|s| ask(addr, &body(p, 1.0, 1.0, 0, Some(s))).0) |
| 702 | .collect(); |
| 703 | r.sort(); |
| 704 | r.dedup(); |
| 705 | r.len() >= 2 |
| 706 | }) |
| 707 | .count() |
| 708 | } |
| 709 | |
| 710 | /// Gate (c): temperature 0 with seeds 1 and 2 equal each other and the engine's own greedy |
| 711 | /// tokens (taken directly from a fresh door, outside HTTP), per prompt. |
| 712 | fn gate_c(addr: SocketAddr) -> usize { |
| 713 | let reference = door("ref"); |
| 714 | PROMPTS |
| 715 | .iter() |
| 716 | .filter(|p| { |
| 717 | let (a, _) = ask(addr, &body(p, 0.0, 1.0, 0, Some(1))); |
| 718 | let (b, _) = ask(addr, &body(p, 0.0, 1.0, 0, Some(2))); |
| 719 | let rendered = TinyCodec |
| 720 | .render_chat(&[("user", p)]) |
| 721 | .and_then(|t| TinyCodec.encode(&t)) |
| 722 | .unwrap(); |
| 723 | let params = GenerateParams { |
| 724 | max_new_tokens: 48, |
| 725 | temperature: 0.0, |
| 726 | top_p: 1.0, |
| 727 | top_k: 0, |
| 728 | seed: 99, |
| 729 | stop_token_ids: vec![], |
| 730 | }; |
| 731 | let mut toks = Vec::new(); |
| 732 | reference |
| 733 | .generate(&rendered, ¶ms, &mut |t| { |
| 734 | toks.push(t); |
| 735 | true |
| 736 | }) |
| 737 | .unwrap(); |
| 738 | let greedy = TinyCodec.decode(&toks).unwrap(); |
| 739 | a == b && a == greedy |
| 740 | }) |
| 741 | .count() |
| 742 | } |
| 743 | |
| 744 | #[test] |
| 745 | fn honest_sampler_passes_a_b_c_and_records_every_draw() { |
| 746 | let srv = serve_engine(Arc::new(door("honest"))); |
| 747 | assert_eq!(gate_a(srv.addr), 4, "(a) replay"); |
| 748 | assert_eq!(gate_b(srv.addr), 4, "(b) spread"); |
| 749 | assert_eq!(gate_c(srv.addr), 4, "(c) greedy"); |
| 750 | |
| 751 | // The record: mode, the seed used, the settings, one kept-set size per sampled draw. |
| 752 | let (_, rec) = ask(srv.addr, &body(PROMPTS[0], 0.7, 0.8, 5, Some(446001))); |
| 753 | assert_eq!(rec["mode"], "sampled", "{rec}"); |
| 754 | assert_eq!(rec["seed"], 446001); |
| 755 | assert_eq!(rec["top_k"], 5); |
| 756 | assert_eq!(rec["top_k_applied"], true); |
| 757 | assert_eq!(rec["sampled_tokens"], 48); |
| 758 | let kept = rec["kept"].as_array().expect("kept sizes"); |
| 759 | assert_eq!(kept.len(), 48); |
| 760 | assert!( |
| 761 | kept.iter().all(|k| (1..=5).contains(&k.as_u64().unwrap())), |
| 762 | "{rec}" |
| 763 | ); |
| 764 | assert!(rec["mutant"].is_null()); |
| 765 | // Confidence: p_repeat = exp(reply_logprob), a probability in (0, 1]. |
| 766 | let (p, lp) = ( |
| 767 | rec["p_repeat"].as_f64().expect("p_repeat"), |
| 768 | rec["reply_logprob"].as_f64().expect("reply_logprob"), |
| 769 | ); |
| 770 | assert!(p > 0.0 && p <= 1.0 && (p - lp.exp()).abs() < 1e-9, "{rec}"); |
| 771 | let tp = rec["top_prob_min"].as_f64().expect("top_prob_min"); |
| 772 | assert!( |
| 773 | tp > 0.0 && tp <= rec["top_prob_mean"].as_f64().unwrap(), |
| 774 | "{rec}" |
| 775 | ); |
| 776 | let (_, rec) = ask(srv.addr, &body(PROMPTS[0], 0.0, 1.0, 0, Some(1))); |
| 777 | assert_eq!(rec["p_repeat"], 1.0, "{rec}"); |
| 778 | assert_eq!(rec["mode"], "greedy", "{rec}"); |
| 779 | assert_eq!( |
| 780 | ( |
| 781 | rec["greedy_tokens"].as_u64(), |
| 782 | rec["sampled_tokens"].as_u64() |
| 783 | ), |
| 784 | (Some(48), Some(0)) |
| 785 | ); |
| 786 | } |
| 787 | |
| 788 | #[test] |
| 789 | fn a_server_chosen_seed_is_echoed_and_replays() { |
| 790 | let srv = serve_engine(Arc::new(door("echo"))); |
| 791 | let (first, rec) = ask(srv.addr, &body(PROMPTS[2], 1.0, 1.0, 0, None)); |
| 792 | let seed = rec["seed"].as_u64().expect("echoed seed"); |
| 793 | let (again, rec2) = ask(srv.addr, &body(PROMPTS[2], 1.0, 1.0, 0, Some(seed))); |
| 794 | assert_eq!(first, again); |
| 795 | assert_eq!(rec["kept"], rec2["kept"]); |
| 796 | } |
| 797 | |
| 798 | #[test] |
| 799 | fn the_stream_carries_the_record_in_its_last_usage() { |
| 800 | let srv = serve_engine(Arc::new(door("stream"))); |
| 801 | let mut v: Value = serde_json::from_str(&body(PROMPTS[1], 1.0, 1.0, 0, Some(3))).unwrap(); |
| 802 | v["stream"] = true.into(); |
| 803 | let r = chat(srv.addr, &v.to_string()); |
| 804 | assert_eq!(r.status, 200, "{}", r.body); |
| 805 | let data = sse_data(&r.body); |
| 806 | let last: Value = serde_json::from_str(&data[data.len() - 2]).unwrap(); |
| 807 | assert_eq!(last["usage"]["aien_sampling"]["seed"], 3, "{last}"); |
| 808 | assert_eq!(last["usage"]["aien_sampling"]["sampled_tokens"], 48); |
| 809 | } |
| 810 | |
| 811 | #[test] |
| 812 | fn an_engine_that_ignores_the_seed_fails_spread() { |
| 813 | let broken = Broken { |
| 814 | door: door("ignore-seed"), |
| 815 | force_seed: Some(0), |
| 816 | force_greedy: false, |
| 817 | }; |
| 818 | let srv = serve_engine(Arc::new(broken)); |
| 819 | assert_eq!(gate_a(srv.addr), 4, "replay still holds"); |
| 820 | assert_eq!(gate_b(srv.addr), 0, "(b) must fail for a seed-blind engine"); |
| 821 | } |
| 822 | |
| 823 | #[test] |
| 824 | fn an_engine_that_is_always_greedy_fails_spread_and_passes_greedy() { |
| 825 | let broken = Broken { |
| 826 | door: door("force-greedy"), |
| 827 | force_seed: None, |
| 828 | force_greedy: true, |
| 829 | }; |
| 830 | let srv = serve_engine(Arc::new(broken)); |
| 831 | assert_eq!( |
| 832 | gate_b(srv.addr), |
| 833 | 0, |
| 834 | "(b) must fail for an always-greedy engine" |
| 835 | ); |
| 836 | assert_eq!(gate_c(srv.addr), 4, "(c) still passes"); |
| 837 | } |
| 838 | |
| 839 | /// The seeds of the :18091 finding draw distinct per-step seeds, and a flat 4-way choice at |
| 840 | /// temperature 1.0, top_p 1.0 takes at least 2 different tokens across seeds 1, 2, 3. |
| 841 | #[test] |
| 842 | fn repro_seeds_are_distinct_and_a_flat_choice_spreads() { |
| 843 | use aien_inference_abi::transformer_backend::{decode_sampling_seed, sample_with_params}; |
| 844 | use aien_inference_abi::SamplingParams; |
| 845 | let mut all: Vec<u64> = [446001u64, 447001, 448001] |
| 846 | .iter() |
| 847 | .flat_map(|&s| (0..8).map(move |step| decode_sampling_seed(s, step))) |
| 848 | .collect(); |
| 849 | let n = all.len(); |
| 850 | all.sort_unstable(); |
| 851 | all.dedup(); |
| 852 | assert_eq!(all.len(), n, "per-step seeds collide"); |
| 853 | let sp = SamplingParams { |
| 854 | temperature: 1.0, |
| 855 | top_p: 1.0, |
| 856 | ..Default::default() |
| 857 | }; |
| 858 | let mut picks: Vec<u32> = (1..=3u64) |
| 859 | .map(|s| sample_with_params(&[0.0; 4], &sp, decode_sampling_seed(s, 0)).0) |
| 860 | .collect(); |
| 861 | picks.sort_unstable(); |
| 862 | picks.dedup(); |
| 863 | assert!(picks.len() >= 2, "{picks:?}"); |
| 864 | } |
| 865 | } |