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 / door_522.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 | //! Host checks for the sc#522 review follow-ups of the HTTP door: request preparation |
| 17 | //! (chat rendering and tokenizing) must not run on the async runtime, and a busy chip must |
| 18 | //! answer in the same OpenAI error envelope as every other error. |
| 19 | |
| 20 | use std::io::{Read, Write}; |
| 21 | use std::net::{SocketAddr, TcpStream}; |
| 22 | use std::sync::{mpsc, Arc, Mutex}; |
| 23 | use std::time::Duration; |
| 24 | |
| 25 | use aien_serve_http::codec::{ByteCodec, Codec, CodecError}; |
| 26 | use aien_serve_http::engine::{Engine, EngineError, GenerateOutcome, GenerateParams, StubEngine}; |
| 27 | use aien_serve_http::server::{serve, ServerConfig}; |
| 28 | use serde_json::Value; |
| 29 | |
| 30 | /// The server refuses unauthenticated requests (main's bearer cutover); every request here sends it. |
| 31 | const TOKEN: &str = "door-522-test-credential"; |
| 32 | |
| 33 | const PROMPT: &str = |
| 34 | r#"{"model":"test-model","messages":[{"role":"user","content":"hi"}],"max_tokens":4}"#; |
| 35 | |
| 36 | /// Serves on a CURRENT-THREAD runtime driven by its own thread: anything that blocks the |
| 37 | /// runtime thread stalls every other request, which is what the off-runtime test detects. |
| 38 | fn start_single_thread(engine: Arc<dyn Engine>, codec: Arc<dyn Codec>) -> SocketAddr { |
| 39 | let (tx, rx) = mpsc::channel(); |
| 40 | std::thread::spawn(move || { |
| 41 | let rt = tokio::runtime::Builder::new_current_thread() |
| 42 | .enable_all() |
| 43 | .build() |
| 44 | .expect("runtime"); |
| 45 | rt.block_on(async move { |
| 46 | let cfg = ServerConfig { |
| 47 | port: 0, |
| 48 | model_id: "test-model".into(), |
| 49 | bearer_token: TOKEN.into(), |
| 50 | ..ServerConfig::default() |
| 51 | }; |
| 52 | let (addr, handle) = serve(cfg, engine, codec).await.expect("bind loopback"); |
| 53 | tx.send(addr).expect("report addr"); |
| 54 | let _ = handle.await; |
| 55 | }); |
| 56 | }); |
| 57 | rx.recv_timeout(Duration::from_secs(10)).expect("server up") |
| 58 | } |
| 59 | |
| 60 | struct Reply { |
| 61 | status: u16, |
| 62 | headers: String, |
| 63 | body: String, |
| 64 | } |
| 65 | |
| 66 | /// One HTTP/1.1 exchange; `Err` when the server does not answer within `wait`. |
| 67 | fn request( |
| 68 | addr: SocketAddr, |
| 69 | method: &str, |
| 70 | path: &str, |
| 71 | body: &str, |
| 72 | wait: Duration, |
| 73 | ) -> std::io::Result<Reply> { |
| 74 | let mut s = TcpStream::connect(addr)?; |
| 75 | s.set_read_timeout(Some(wait))?; |
| 76 | let req = format!( |
| 77 | "{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}", |
| 78 | body.len() |
| 79 | ); |
| 80 | s.write_all(req.as_bytes())?; |
| 81 | let mut raw = Vec::new(); |
| 82 | s.read_to_end(&mut raw)?; |
| 83 | let split = raw |
| 84 | .windows(4) |
| 85 | .position(|w| w == b"\r\n\r\n") |
| 86 | .expect("header end"); |
| 87 | let headers = String::from_utf8_lossy(&raw[..split]).to_string(); |
| 88 | let status = headers |
| 89 | .split_whitespace() |
| 90 | .nth(1) |
| 91 | .and_then(|s| s.parse().ok()) |
| 92 | .expect("status code"); |
| 93 | Ok(Reply { |
| 94 | status, |
| 95 | headers, |
| 96 | body: String::from_utf8_lossy(&raw[split + 4..]).to_string(), |
| 97 | }) |
| 98 | } |
| 99 | |
| 100 | /// [`ByteCodec`] whose `encode` reports that it started, then blocks until released (or 20 s). |
| 101 | struct GateCodec { |
| 102 | entered: Mutex<mpsc::Sender<()>>, |
| 103 | release: Mutex<mpsc::Receiver<()>>, |
| 104 | } |
| 105 | |
| 106 | impl Codec for GateCodec { |
| 107 | fn render_chat(&self, turns: &[(&str, &str)]) -> Result<String, CodecError> { |
| 108 | ByteCodec.render_chat(turns) |
| 109 | } |
| 110 | fn encode(&self, text: &str) -> Result<Vec<u32>, CodecError> { |
| 111 | let _ = self.entered.lock().unwrap().send(()); |
| 112 | let _ = self |
| 113 | .release |
| 114 | .lock() |
| 115 | .unwrap() |
| 116 | .recv_timeout(Duration::from_secs(20)); |
| 117 | ByteCodec.encode(text) |
| 118 | } |
| 119 | fn decode(&self, tokens: &[u32]) -> Result<String, CodecError> { |
| 120 | ByteCodec.decode(tokens) |
| 121 | } |
| 122 | fn stop_token_ids(&self) -> Vec<u32> { |
| 123 | ByteCodec.stop_token_ids() |
| 124 | } |
| 125 | } |
| 126 | |
| 127 | #[test] |
| 128 | fn tokenizing_does_not_block_the_runtime() { |
| 129 | let (entered_tx, entered_rx) = mpsc::channel(); |
| 130 | let (release_tx, release_rx) = mpsc::channel(); |
| 131 | let codec = GateCodec { |
| 132 | entered: Mutex::new(entered_tx), |
| 133 | release: Mutex::new(release_rx), |
| 134 | }; |
| 135 | let engine = StubEngine::new(b"ok".iter().map(|&b| u32::from(b)).collect()); |
| 136 | let addr = start_single_thread(Arc::new(engine), Arc::new(codec)); |
| 137 | |
| 138 | let chat = std::thread::spawn(move || { |
| 139 | request( |
| 140 | addr, |
| 141 | "POST", |
| 142 | "/v1/chat/completions", |
| 143 | PROMPT, |
| 144 | Duration::from_secs(30), |
| 145 | ) |
| 146 | }); |
| 147 | entered_rx |
| 148 | .recv_timeout(Duration::from_secs(10)) |
| 149 | .expect("encode started"); |
| 150 | // The tokenizer is now blocked. With it on the runtime thread, /health cannot answer. |
| 151 | let health = request(addr, "GET", "/health", "", Duration::from_secs(3)); |
| 152 | release_tx.send(()).expect("release encode"); |
| 153 | let health = health.expect("/health answers while a prompt is being tokenized"); |
| 154 | assert_eq!(health.status, 200, "{}", health.body); |
| 155 | |
| 156 | let chat = chat.join().unwrap().expect("chat reply"); |
| 157 | assert_eq!(chat.status, 200, "{}", chat.body); |
| 158 | let v: Value = serde_json::from_str(&chat.body).expect("json"); |
| 159 | assert_eq!(v["choices"][0]["message"]["content"], "ok"); |
| 160 | } |
| 161 | |
| 162 | /// An engine whose chip is always held by another job. |
| 163 | struct BusyEngine; |
| 164 | |
| 165 | impl Engine for BusyEngine { |
| 166 | fn kind(&self) -> &str { |
| 167 | "busy" |
| 168 | } |
| 169 | fn max_context_tokens(&self) -> usize { |
| 170 | 4096 |
| 171 | } |
| 172 | fn generate( |
| 173 | &self, |
| 174 | _prompt: &[u32], |
| 175 | _params: &GenerateParams, |
| 176 | _on_token: &mut dyn FnMut(u32) -> bool, |
| 177 | ) -> Result<GenerateOutcome, EngineError> { |
| 178 | Err(EngineError::Busy( |
| 179 | "GPU lock held by another job for 30 s".into(), |
| 180 | )) |
| 181 | } |
| 182 | } |
| 183 | |
| 184 | #[test] |
| 185 | fn gpu_busy_is_an_openai_error_envelope() { |
| 186 | let addr = start_single_thread(Arc::new(BusyEngine), Arc::new(ByteCodec)); |
| 187 | for stream in [false, true] { |
| 188 | let body = PROMPT.replace( |
| 189 | "\"max_tokens\":4", |
| 190 | &format!("\"max_tokens\":4,\"stream\":{stream}"), |
| 191 | ); |
| 192 | let r = request( |
| 193 | addr, |
| 194 | "POST", |
| 195 | "/v1/chat/completions", |
| 196 | &body, |
| 197 | Duration::from_secs(30), |
| 198 | ) |
| 199 | .expect("reply"); |
| 200 | assert_eq!(r.status, 503, "stream={stream}: {}", r.body); |
| 201 | assert!( |
| 202 | r.headers.to_ascii_lowercase().contains("retry-after: 5"), |
| 203 | "stream={stream}: {}", |
| 204 | r.headers |
| 205 | ); |
| 206 | let v: Value = serde_json::from_str(&r.body) |
| 207 | .unwrap_or_else(|e| panic!("stream={stream}: not JSON ({e}): {}", r.body)); |
| 208 | let err = &v["error"]; |
| 209 | assert_eq!(err["type"], "server_busy", "stream={stream}: {v}"); |
| 210 | assert_eq!(err["code"], "gpu_busy", "stream={stream}: {v}"); |
| 211 | let msg = err["message"].as_str().expect("message string"); |
| 212 | assert!(msg.contains("GPU busy"), "stream={stream}: {msg}"); |
| 213 | assert!( |
| 214 | msg.contains("held by another job"), |
| 215 | "stream={stream}: {msg}" |
| 216 | ); |
| 217 | assert!(err.get("param").is_some(), "stream={stream}: {v}"); |
| 218 | } |
| 219 | } |