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 / readers.rs
| 1 | //! The eight readers (sc L371) over a real TCP server: a stub engine, the byte codec (one token per |
| 2 | //! byte) and the loopback tests' hand-written HTTP/1.1 client. |
| 3 | |
| 4 | use std::io::{Read, Write}; |
| 5 | use std::net::{SocketAddr, TcpStream}; |
| 6 | use std::sync::Arc; |
| 7 | use std::time::Duration; |
| 8 | |
| 9 | use aien_serve_http::codec::ByteCodec; |
| 10 | use aien_serve_http::engine::StubEngine; |
| 11 | use aien_serve_http::server::{serve, ServerConfig}; |
| 12 | const TOKEN: &str = "integration-test-private-credential"; |
| 13 | use serde_json::Value; |
| 14 | |
| 15 | struct Server { |
| 16 | addr: SocketAddr, |
| 17 | _rt: tokio::runtime::Runtime, |
| 18 | } |
| 19 | |
| 20 | struct Reply { |
| 21 | status: u16, |
| 22 | #[allow(dead_code)] |
| 23 | headers: String, |
| 24 | body: String, |
| 25 | } |
| 26 | |
| 27 | fn dechunk(raw: &[u8]) -> Vec<u8> { |
| 28 | let mut out = Vec::new(); |
| 29 | let mut i = 0; |
| 30 | loop { |
| 31 | let line_end = raw[i..] |
| 32 | .windows(2) |
| 33 | .position(|w| w == b"\r\n") |
| 34 | .expect("chunk size line") |
| 35 | + i; |
| 36 | let size = |
| 37 | usize::from_str_radix(std::str::from_utf8(&raw[i..line_end]).unwrap().trim(), 16) |
| 38 | .expect("hex chunk size"); |
| 39 | if size == 0 { |
| 40 | return out; |
| 41 | } |
| 42 | out.extend_from_slice(&raw[line_end + 2..line_end + 2 + size]); |
| 43 | i = line_end + 2 + size + 2; |
| 44 | } |
| 45 | } |
| 46 | |
| 47 | fn request(addr: SocketAddr, method: &str, path: &str, body: Option<&str>) -> Reply { |
| 48 | let mut s = TcpStream::connect(addr).expect("connect"); |
| 49 | s.set_read_timeout(Some(Duration::from_secs(30))).unwrap(); |
| 50 | let body = body.unwrap_or(""); |
| 51 | let req = format!( |
| 52 | "{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}", |
| 53 | body.len() |
| 54 | ); |
| 55 | s.write_all(req.as_bytes()).unwrap(); |
| 56 | let mut raw = Vec::new(); |
| 57 | s.read_to_end(&mut raw).expect("read reply"); |
| 58 | let split = raw |
| 59 | .windows(4) |
| 60 | .position(|w| w == b"\r\n\r\n") |
| 61 | .expect("header end"); |
| 62 | let headers = String::from_utf8_lossy(&raw[..split]).to_string(); |
| 63 | let status: u16 = headers |
| 64 | .split_whitespace() |
| 65 | .nth(1) |
| 66 | .and_then(|s| s.parse().ok()) |
| 67 | .expect("status code"); |
| 68 | let body_raw = &raw[split + 4..]; |
| 69 | let body = if headers |
| 70 | .to_ascii_lowercase() |
| 71 | .contains("transfer-encoding: chunked") |
| 72 | { |
| 73 | String::from_utf8(dechunk(body_raw)).unwrap() |
| 74 | } else { |
| 75 | String::from_utf8(body_raw.to_vec()).unwrap() |
| 76 | }; |
| 77 | Reply { |
| 78 | status, |
| 79 | headers, |
| 80 | body, |
| 81 | } |
| 82 | } |
| 83 | |
| 84 | fn chat(addr: SocketAddr, body: &str) -> Reply { |
| 85 | request(addr, "POST", "/v1/chat/completions", Some(body)) |
| 86 | } |
| 87 | |
| 88 | fn json(r: &Reply) -> Value { |
| 89 | serde_json::from_str(&r.body).unwrap_or_else(|e| panic!("not JSON ({e}): {}", r.body)) |
| 90 | } |
| 91 | |
| 92 | /// `data:` payloads of an SSE body, in order; comment lines are skipped. |
| 93 | fn sse_data(body: &str) -> Vec<String> { |
| 94 | body.lines() |
| 95 | .filter_map(|l| l.strip_prefix("data: ").or_else(|| l.strip_prefix("data:"))) |
| 96 | .map(|s| s.trim().to_string()) |
| 97 | .collect() |
| 98 | } |
| 99 | |
| 100 | use std::sync::Mutex; |
| 101 | |
| 102 | use aien_serve_http::engine::{Engine, EngineError, GenerateOutcome, GenerateParams, GroupJob}; |
| 103 | use aien_serve_http::readers::ReadersConfig; |
| 104 | |
| 105 | /// A batching engine stand-in: says it runs `slots` at once and records every group it gets |
| 106 | /// (its prompts, as text) before running them in turn on the stub. |
| 107 | struct Spy { |
| 108 | inner: StubEngine, |
| 109 | slots: usize, |
| 110 | groups: Arc<Mutex<Vec<Vec<String>>>>, |
| 111 | } |
| 112 | |
| 113 | impl Engine for Spy { |
| 114 | fn kind(&self) -> &str { |
| 115 | "spy" |
| 116 | } |
| 117 | fn max_context_tokens(&self) -> usize { |
| 118 | self.inner.max_context_tokens() |
| 119 | } |
| 120 | fn concurrency(&self) -> usize { |
| 121 | self.slots |
| 122 | } |
| 123 | fn generate( |
| 124 | &self, |
| 125 | prompt: &[u32], |
| 126 | params: &GenerateParams, |
| 127 | on_token: &mut dyn FnMut(u32) -> bool, |
| 128 | ) -> Result<GenerateOutcome, EngineError> { |
| 129 | self.inner.generate(prompt, params, on_token) |
| 130 | } |
| 131 | fn generate_group( |
| 132 | &self, |
| 133 | jobs: &[GroupJob], |
| 134 | on_token: &mut dyn FnMut(usize, u32) -> bool, |
| 135 | ) -> Vec<Result<GenerateOutcome, EngineError>> { |
| 136 | let texts = jobs |
| 137 | .iter() |
| 138 | .map(|j| j.prompt.iter().map(|&t| t as u8 as char).collect()) |
| 139 | .collect(); |
| 140 | self.groups.lock().unwrap().push(texts); |
| 141 | jobs.iter() |
| 142 | .enumerate() |
| 143 | .map(|(i, j)| { |
| 144 | self.inner |
| 145 | .generate(&j.prompt, &j.params, &mut |t| on_token(i, t)) |
| 146 | }) |
| 147 | .collect() |
| 148 | } |
| 149 | } |
| 150 | |
| 151 | fn readers_cfg() -> ReadersConfig { |
| 152 | ReadersConfig { |
| 153 | threshold_tokens: 800, |
| 154 | ..ReadersConfig::new("test-model") |
| 155 | } |
| 156 | } |
| 157 | |
| 158 | fn start_spy(slots: usize, reply: &str) -> (Server, Arc<Mutex<Vec<Vec<String>>>>) { |
| 159 | start_spy_on( |
| 160 | slots, |
| 161 | StubEngine::new(reply.bytes().map(u32::from).collect()).with_max_context(1 << 16), |
| 162 | ) |
| 163 | } |
| 164 | |
| 165 | fn start_spy_on(slots: usize, inner: StubEngine) -> (Server, Arc<Mutex<Vec<Vec<String>>>>) { |
| 166 | let groups = Arc::new(Mutex::new(Vec::new())); |
| 167 | let spy = Spy { |
| 168 | inner, |
| 169 | slots, |
| 170 | groups: Arc::clone(&groups), |
| 171 | }; |
| 172 | let rt = tokio::runtime::Runtime::new().expect("runtime"); |
| 173 | let cfg = ServerConfig { |
| 174 | port: 0, |
| 175 | model_id: "test-model".into(), |
| 176 | readers: Some(readers_cfg()), |
| 177 | bearer_token: TOKEN.into(), |
| 178 | ..ServerConfig::default() |
| 179 | }; |
| 180 | let (addr, _handle) = rt |
| 181 | .block_on(serve(cfg, Arc::new(spy), Arc::new(ByteCodec))) |
| 182 | .expect("bind loopback"); |
| 183 | (Server { addr, _rt: rt }, groups) |
| 184 | } |
| 185 | |
| 186 | /// 60 lines in 12 paragraphs, each line naming itself: about 4,000 bytes. |
| 187 | fn long_doc() -> String { |
| 188 | let mut s = String::new(); |
| 189 | for l in 1..=60 { |
| 190 | s.push_str(&format!( |
| 191 | "line {l:02}: the quick brown fox jumps over the lazy dog {l:02}\n" |
| 192 | )); |
| 193 | if l % 5 == 0 { |
| 194 | s.push('\n'); |
| 195 | } |
| 196 | } |
| 197 | s |
| 198 | } |
| 199 | |
| 200 | fn body(model: &str, user: &str, extra: &str) -> String { |
| 201 | let msgs = serde_json::json!([ |
| 202 | {"role": "system", "content": "sys"}, |
| 203 | {"role": "user", "content": user}, |
| 204 | ]); |
| 205 | format!(r#"{{"model":"{model}","messages":{msgs}{extra}}}"#) |
| 206 | } |
| 207 | |
| 208 | #[test] |
| 209 | fn models_lists_the_readers_id_beside_the_plain_one() { |
| 210 | let (srv, _) = start_spy(8, "x"); |
| 211 | let v = json(&request(srv.addr, "GET", "/v1/models", None)); |
| 212 | let ids: Vec<&str> = v["data"] |
| 213 | .as_array() |
| 214 | .unwrap() |
| 215 | .iter() |
| 216 | .map(|m| m["id"].as_str().unwrap()) |
| 217 | .collect(); |
| 218 | assert_eq!(ids, ["test-model", "test-model-readers"]); |
| 219 | let r = request(srv.addr, "GET", "/v1/models/test-model-readers", None); |
| 220 | assert_eq!(r.status, 200); |
| 221 | assert_eq!(json(&r)["id"], "test-model-readers"); |
| 222 | } |
| 223 | |
| 224 | #[test] |
| 225 | fn a_short_input_on_the_readers_id_takes_the_plain_path() { |
| 226 | let (srv, groups) = start_spy(8, "plain answer"); |
| 227 | let v = json(&chat(srv.addr, &body("test-model-readers", "hi", ""))); |
| 228 | assert_eq!(v["choices"][0]["message"]["content"], "plain answer"); |
| 229 | assert_eq!(v["model"], "test-model-readers"); |
| 230 | assert!(v.get("aien_readers").is_none()); |
| 231 | assert!(groups.lock().unwrap().is_empty()); |
| 232 | // The plain id with a long input: the plain path too (the readers are opt-in by id). |
| 233 | let v = json(&chat(srv.addr, &body("test-model", &long_doc(), ""))); |
| 234 | assert!(v.get("aien_readers").is_none()); |
| 235 | assert!(groups.lock().unwrap().is_empty()); |
| 236 | } |
| 237 | |
| 238 | #[test] |
| 239 | fn a_long_input_is_read_by_eight_readers_in_one_group_and_the_notes_come_back() { |
| 240 | let (srv, groups) = start_spy(8, "NOTE"); |
| 241 | let user = format!("Which line mentions 42?\n\n{}", long_doc()); |
| 242 | let v = json(&chat(srv.addr, &body("test-model-readers", &user, ""))); |
| 243 | assert_eq!(v["model"], "test-model-readers"); |
| 244 | assert_eq!(v["choices"][0]["message"]["content"], "NOTE"); |
| 245 | let r = &v["aien_readers"]; |
| 246 | assert_eq!(r["readers"], 8); |
| 247 | let parts = r["parts"].as_array().unwrap(); |
| 248 | assert_eq!(parts.len(), 8); |
| 249 | for (k, p) in parts.iter().enumerate() { |
| 250 | assert_eq!(p["part"], k + 1); |
| 251 | assert_eq!(p["notes"], "NOTE"); |
| 252 | assert_eq!(p["note_tokens"], 4); |
| 253 | } |
| 254 | // One group of eight, in part order, each prompt holding its own part only. |
| 255 | let g = groups.lock().unwrap(); |
| 256 | assert_eq!(g.len(), 1); |
| 257 | assert_eq!(g[0].len(), 8); |
| 258 | for (k, prompt) in g[0].iter().enumerate() { |
| 259 | assert!(prompt.starts_with("<system>sys</system>"), "{prompt}"); |
| 260 | assert!(prompt.contains(&format!("You are reader {} of 8", k + 1))); |
| 261 | assert!(prompt.contains("Which line mentions 42?")); |
| 262 | let first = parts[k]["lines"][0].as_u64().unwrap() as usize; |
| 263 | assert!(prompt.contains(long_doc().lines().nth(first - 1).unwrap())); |
| 264 | } |
| 265 | // (Every reader also sees the message's beginning and end, where a request usually sits.) |
| 266 | assert!(!g[0][0].contains("line 30:"), "part 1 holds a middle line"); |
| 267 | // The usage counts the connect prompt (notes, not the input). |
| 268 | let pt = v["usage"]["prompt_tokens"].as_u64().unwrap(); |
| 269 | assert_eq!(pt, r["connect_prompt_tokens"].as_u64().unwrap()); |
| 270 | assert!((pt as usize) < long_doc().len()); |
| 271 | } |
| 272 | |
| 273 | #[test] |
| 274 | fn show_notes_puts_a_collapsed_preface_before_the_answer() { |
| 275 | let (srv, _) = start_spy(8, "NOTE"); |
| 276 | let v = json(&chat( |
| 277 | srv.addr, |
| 278 | &body( |
| 279 | "test-model-readers", |
| 280 | &long_doc(), |
| 281 | r#","aien_show_notes":true"#, |
| 282 | ), |
| 283 | )); |
| 284 | let c = v["choices"][0]["message"]["content"].as_str().unwrap(); |
| 285 | assert!( |
| 286 | c.starts_with("<details>\n<summary>Notes from 8 readers"), |
| 287 | "{c}" |
| 288 | ); |
| 289 | assert!(c.ends_with("</details>\n\nNOTE"), "{c}"); |
| 290 | assert_eq!(c.matches("NOTE").count(), 9); |
| 291 | } |
| 292 | |
| 293 | const REFUSAL: &str = "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"; |
| 294 | |
| 295 | /// The engine's own memory admission (inside `generate`, after the server's `admit` passed) |
| 296 | /// refusing a reader: the same 413 `prompt_exceeds_memory_budget` as a refusal in `prepare`, |
| 297 | /// not a 500. |
| 298 | #[test] |
| 299 | fn a_reader_refused_for_memory_inside_the_engine_is_a_413() { |
| 300 | let (srv, groups) = start_spy_on( |
| 301 | 8, |
| 302 | StubEngine::new(b"NOTE".iter().map(|&b| u32::from(b)).collect()) |
| 303 | .with_max_context(1 << 16) |
| 304 | .with_generate_refusal(REFUSAL), |
| 305 | ); |
| 306 | let r = chat(srv.addr, &body("test-model-readers", &long_doc(), "")); |
| 307 | assert_eq!(r.status, 413, "{}", r.body); |
| 308 | let j = json(&r); |
| 309 | assert_eq!(j["error"]["code"], "prompt_exceeds_memory_budget"); |
| 310 | let m = j["error"]["message"].as_str().unwrap(); |
| 311 | assert!( |
| 312 | m.starts_with("reader 1 of 8: ") && m.ends_with(REFUSAL), |
| 313 | "{m}" |
| 314 | ); |
| 315 | assert_eq!( |
| 316 | groups.lock().unwrap().len(), |
| 317 | 1, |
| 318 | "the refusal came from the group run" |
| 319 | ); |
| 320 | } |
| 321 | |
| 322 | /// Streaming readers open the response before reading, so the refusal is the stream's error |
| 323 | /// event, carrying the same code. |
| 324 | #[test] |
| 325 | fn a_streaming_reader_refused_for_memory_ends_with_the_memory_error_event() { |
| 326 | let (srv, _) = start_spy_on( |
| 327 | 8, |
| 328 | StubEngine::new(b"NOTE".iter().map(|&b| u32::from(b)).collect()) |
| 329 | .with_max_context(1 << 16) |
| 330 | .with_generate_refusal(REFUSAL), |
| 331 | ); |
| 332 | let r = chat( |
| 333 | srv.addr, |
| 334 | &body("test-model-readers", &long_doc(), r#","stream":true"#), |
| 335 | ); |
| 336 | assert_eq!(r.status, 200); |
| 337 | let ev = sse_data(&r.body); |
| 338 | assert_eq!(ev.last().unwrap(), "[DONE]"); |
| 339 | let err: Value = serde_json::from_str(&ev[ev.len() - 2]).unwrap(); |
| 340 | assert_eq!( |
| 341 | err["error"]["code"], "prompt_exceeds_memory_budget", |
| 342 | "{err}" |
| 343 | ); |
| 344 | assert!(err["error"]["message"].as_str().unwrap().ends_with(REFUSAL)); |
| 345 | } |
| 346 | |
| 347 | #[test] |
| 348 | fn streaming_sends_progress_then_the_notes_then_the_answer() { |
| 349 | let (srv, _) = start_spy(8, "NOTE"); |
| 350 | let r = chat( |
| 351 | srv.addr, |
| 352 | &body("test-model-readers", &long_doc(), r#","stream":true"#), |
| 353 | ); |
| 354 | assert_eq!(r.status, 200); |
| 355 | let ev = sse_data(&r.body); |
| 356 | assert_eq!(ev.last().unwrap(), "[DONE]"); |
| 357 | let chunks: Vec<Value> = ev[..ev.len() - 1] |
| 358 | .iter() |
| 359 | .map(|s| serde_json::from_str(s).unwrap()) |
| 360 | .collect(); |
| 361 | let progress: String = chunks |
| 362 | .iter() |
| 363 | .filter_map(|c| c["choices"][0]["delta"]["reasoning_content"].as_str()) |
| 364 | .collect(); |
| 365 | assert!(progress.starts_with("Reading "), "{progress}"); |
| 366 | assert!(progress.contains("Notes from 8 readers")); |
| 367 | let at = chunks |
| 368 | .iter() |
| 369 | .position(|c| c.get("aien_readers").is_some()) |
| 370 | .expect("notes chunk"); |
| 371 | assert_eq!( |
| 372 | chunks[at]["aien_readers"]["parts"] |
| 373 | .as_array() |
| 374 | .unwrap() |
| 375 | .len(), |
| 376 | 8 |
| 377 | ); |
| 378 | let answer: String = chunks[at..] |
| 379 | .iter() |
| 380 | .filter_map(|c| c["choices"][0]["delta"]["content"].as_str()) |
| 381 | .collect(); |
| 382 | assert_eq!(answer, "NOTE"); |
| 383 | assert_eq!( |
| 384 | chunks.last().unwrap()["choices"][0]["finish_reason"], |
| 385 | "stop" |
| 386 | ); |
| 387 | } |
| 388 | |
| 389 | #[test] |
| 390 | fn fewer_free_rows_mean_fewer_parts_and_one_engine_reads_in_turn() { |
| 391 | // A one-at-a-time engine: all eight parts, read in turn under its one permit. |
| 392 | let (srv, groups) = start_spy(1, "N"); |
| 393 | let v = json(&chat( |
| 394 | srv.addr, |
| 395 | &body("test-model-readers", &long_doc(), ""), |
| 396 | )); |
| 397 | assert_eq!(v["aien_readers"]["readers"], 8); |
| 398 | assert_eq!(groups.lock().unwrap()[0].len(), 8); |
| 399 | // A four-row engine: four parts. |
| 400 | let (srv, groups) = start_spy(4, "N"); |
| 401 | let v = json(&chat( |
| 402 | srv.addr, |
| 403 | &body("test-model-readers", &long_doc(), ""), |
| 404 | )); |
| 405 | assert_eq!(v["aien_readers"]["readers"], 4); |
| 406 | assert_eq!(groups.lock().unwrap()[0].len(), 4); |
| 407 | } |
| 408 | |
| 409 | /// Tool calling through the readers id (serve/q36-tools): a long tool result is read by the |
| 410 | /// readers, the readers' prompts carry no tools, and the answer's tool call comes back parsed. |
| 411 | #[test] |
| 412 | fn a_long_tool_result_is_read_and_the_answer_can_call_a_tool() { |
| 413 | let call = "<tool_call>\n<function=read_file>\n<parameter=path>\nsrc/main.rs\n</parameter>\n</function>\n</tool_call>"; |
| 414 | let (srv, groups) = start_spy(8, call); |
| 415 | let msgs = serde_json::json!([ |
| 416 | {"role": "system", "content": "sys"}, |
| 417 | {"role": "user", "content": "Find the crash, then open the file it names."}, |
| 418 | {"role": "assistant", "content": "", "tool_calls": [{"id": "c1", "type": "function", "function": {"name": "read_log", "arguments": "{}"}}]}, |
| 419 | {"role": "tool", "tool_call_id": "c1", "content": long_doc()}, |
| 420 | ]); |
| 421 | let tools = r#"[{"type":"function","function":{"name":"read_file","parameters":{"type":"object","properties":{"path":{"type":"string"}}}}}]"#; |
| 422 | let v = json(&chat( |
| 423 | srv.addr, |
| 424 | &format!(r#"{{"model":"test-model-readers","tools":{tools},"messages":{msgs}}}"#), |
| 425 | )); |
| 426 | assert_eq!(v["aien_readers"]["readers"], 8); |
| 427 | assert_eq!(v["choices"][0]["finish_reason"], "tool_calls", "{v}"); |
| 428 | let tc = &v["choices"][0]["message"]["tool_calls"][0]; |
| 429 | assert_eq!(tc["function"]["name"], "read_file"); |
| 430 | assert!(tc["function"]["arguments"] |
| 431 | .as_str() |
| 432 | .unwrap() |
| 433 | .contains("src/main.rs")); |
| 434 | let g = groups.lock().unwrap(); |
| 435 | for prompt in &g[0] { |
| 436 | assert!(!prompt.contains("<tools>"), "a reader got the tools"); |
| 437 | assert!(prompt.contains("Find the crash, then open the file it names.")); |
| 438 | } |
| 439 | } |