benchmarks-mv
Measurement harnesses and evidence bundles for AIEN on the NVIDIA DGX Spark GB10. Speed is reported against the machine's physical limit and my own previous run. Attachment of AienOS.
Brought by drakestapleton
benchmarks-mv / src / harness / llm_stream.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 | //! Streaming benchmark for an OpenAI-compatible `/v1/chat/completions` endpoint. |
| 17 | //! |
| 18 | //! Measurement rules (issue aien-spark/aien-architecture#233, lane P0): |
| 19 | //! - One clock: `std::time::Instant` (monotonic). `request_start` is taken immediately |
| 20 | //! before the request bytes are written to an already-connected socket. An event's arrival |
| 21 | //! is the `Instant` taken immediately after the socket read that delivered its final byte |
| 22 | //! returned (see `sse.rs`). |
| 23 | //! - One SSE event is not assumed to be one model token. Token metrics are reported only |
| 24 | //! when the backend returns `usage.completion_tokens` for every successful request |
| 25 | //! (`token_accounting: "backend_usage"`); otherwise only event metrics are reported |
| 26 | //! (`token_accounting: "events_not_tokens"`). |
| 27 | //! - Percentiles come from N real observations with N recorded; p95 only when N >= 20. |
| 28 | //! - Read errors and timeouts are failures, never end-of-stream. |
| 29 | |
| 30 | use super::sse::{HttpResponseParser, SseEvent, SseParser}; |
| 31 | use serde::Serialize; |
| 32 | use serde_json::{json, Map, Value}; |
| 33 | use std::collections::BTreeMap; |
| 34 | use std::io::{ErrorKind, Read, Write}; |
| 35 | use std::net::{TcpStream, ToSocketAddrs}; |
| 36 | use std::path::{Path, PathBuf}; |
| 37 | use std::process::Command; |
| 38 | use std::sync::atomic::{AtomicU32, Ordering}; |
| 39 | use std::sync::Mutex; |
| 40 | use std::time::{Duration, Instant}; |
| 41 | |
| 42 | pub const CLOCK: &str = "std::time::Instant monotonic"; |
| 43 | pub const RECORD_SCHEMA: &str = "aien-bench-record/1"; |
| 44 | pub const SAMPLES_SCHEMA: &str = "aien-bench-samples/1"; |
| 45 | /// `workload.name` of every llm-stream record; such a run always runs a model. |
| 46 | pub const WORKLOAD: &str = "llm_streaming"; |
| 47 | /// Repository name on Interplane (interplane.io/drakestapleton/benchmarks-mv); GitHub is not used. |
| 48 | pub const REPO: &str = "drakestapleton/benchmarks-mv"; |
| 49 | /// p95 is reported only from at least this many observations. |
| 50 | pub const P95_MIN_SAMPLES: usize = 20; |
| 51 | const MAX_ERROR_BODY_BYTES: usize = 64 * 1024; |
| 52 | const ERROR_SNIPPET_CHARS: usize = 512; |
| 53 | |
| 54 | /// Everything that identifies one streaming benchmark run. Labels (engine, model, |
| 55 | /// precision, context length) are reported exactly as configured. |
| 56 | #[derive(Debug, Clone)] |
| 57 | pub struct StreamConfig { |
| 58 | pub host: String, |
| 59 | pub port: u16, |
| 60 | pub path: String, |
| 61 | pub model: String, |
| 62 | pub engine: String, |
| 63 | pub precision: Option<String>, |
| 64 | pub context_length: Option<u64>, |
| 65 | pub max_tokens: u32, |
| 66 | pub prompt: String, |
| 67 | pub requests: u32, |
| 68 | pub concurrency: u32, |
| 69 | pub warmup: u32, |
| 70 | pub request_usage: bool, |
| 71 | pub connect_timeout: Duration, |
| 72 | pub read_timeout: Duration, |
| 73 | /// sha256 of the serving binary that answered (DRA-166); `None` when the operator gave none. |
| 74 | pub binary_sha256: Option<String>, |
| 75 | /// sha256 of the model checkpoint the server loaded (DRA-166); `None` when not given. |
| 76 | pub model_sha256: Option<String>, |
| 77 | } |
| 78 | |
| 79 | impl Default for StreamConfig { |
| 80 | /// The endpoint and model id the old hardcoded harness used; labels left unlabeled. |
| 81 | fn default() -> Self { |
| 82 | Self { |
| 83 | host: "127.0.0.1".to_string(), |
| 84 | port: 18006, |
| 85 | path: "/v1/chat/completions".to_string(), |
| 86 | model: "atlas-lightning-omni".to_string(), |
| 87 | engine: "unlabeled".to_string(), |
| 88 | precision: None, |
| 89 | context_length: None, |
| 90 | max_tokens: 20, |
| 91 | prompt: "Explain unified memory architecture in ten words.".to_string(), |
| 92 | requests: 1, |
| 93 | concurrency: 1, |
| 94 | warmup: 1, |
| 95 | request_usage: true, |
| 96 | connect_timeout: Duration::from_secs(5), |
| 97 | read_timeout: Duration::from_secs(20), |
| 98 | binary_sha256: None, |
| 99 | model_sha256: None, |
| 100 | } |
| 101 | } |
| 102 | } |
| 103 | |
| 104 | impl StreamConfig { |
| 105 | pub fn endpoint(&self) -> String { |
| 106 | format!("{}:{}{}", self.host, self.port, self.path) |
| 107 | } |
| 108 | |
| 109 | pub fn request_body(&self) -> String { |
| 110 | let mut body = json!({ |
| 111 | "model": self.model, |
| 112 | "messages": [{"role": "user", "content": self.prompt}], |
| 113 | "max_tokens": self.max_tokens, |
| 114 | "stream": true, |
| 115 | }); |
| 116 | if self.request_usage { |
| 117 | body["stream_options"] = json!({"include_usage": true}); |
| 118 | } |
| 119 | body.to_string() |
| 120 | } |
| 121 | |
| 122 | pub fn request_bytes(&self) -> Vec<u8> { |
| 123 | let body = self.request_body(); |
| 124 | let host = if self.host.contains(':') { |
| 125 | format!("[{}]", self.host) |
| 126 | } else { |
| 127 | self.host.clone() |
| 128 | }; |
| 129 | format!( |
| 130 | "POST {} HTTP/1.1\r\nHost: {}:{}\r\nContent-Type: application/json\r\nAccept: text/event-stream\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}", |
| 131 | self.path, |
| 132 | host, |
| 133 | self.port, |
| 134 | body.len(), |
| 135 | body |
| 136 | ) |
| 137 | .into_bytes() |
| 138 | } |
| 139 | } |
| 140 | |
| 141 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] |
| 142 | #[serde(rename_all = "snake_case")] |
| 143 | pub enum EventKind { |
| 144 | /// At least one choice carries non-empty `delta.content`, `delta.reasoning_content` or `text`. |
| 145 | Content, |
| 146 | /// Valid chunk without content: role-only, empty delta, finish_reason-only, usage-only. |
| 147 | NonContent, |
| 148 | Done, |
| 149 | Error, |
| 150 | Malformed, |
| 151 | } |
| 152 | |
| 153 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 154 | pub struct Classified { |
| 155 | pub kind: EventKind, |
| 156 | pub completion_tokens: Option<u64>, |
| 157 | pub prompt_tokens: Option<u64>, |
| 158 | } |
| 159 | |
| 160 | /// Classify one SSE event's `data` (and optional `event` name). |
| 161 | pub fn classify(event: Option<&str>, data: &str) -> Classified { |
| 162 | let mut c = Classified { |
| 163 | kind: EventKind::Malformed, |
| 164 | completion_tokens: None, |
| 165 | prompt_tokens: None, |
| 166 | }; |
| 167 | if data.trim() == "[DONE]" { |
| 168 | c.kind = EventKind::Done; |
| 169 | return c; |
| 170 | } |
| 171 | let Ok(Value::Object(obj)) = serde_json::from_str::<Value>(data) else { |
| 172 | if event == Some("error") { |
| 173 | c.kind = EventKind::Error; |
| 174 | } |
| 175 | return c; |
| 176 | }; |
| 177 | if event == Some("error") || obj.get("error").is_some_and(|e| !e.is_null()) { |
| 178 | c.kind = EventKind::Error; |
| 179 | return c; |
| 180 | } |
| 181 | if let Some(usage) = obj.get("usage") { |
| 182 | c.completion_tokens = usage.get("completion_tokens").and_then(Value::as_u64); |
| 183 | c.prompt_tokens = usage.get("prompt_tokens").and_then(Value::as_u64); |
| 184 | } |
| 185 | let non_empty = |v: Option<&Value>| v.and_then(Value::as_str).is_some_and(|s| !s.is_empty()); |
| 186 | let has_content = obj |
| 187 | .get("choices") |
| 188 | .and_then(Value::as_array) |
| 189 | .is_some_and(|choices| { |
| 190 | choices.iter().any(|ch| { |
| 191 | let delta = ch.get("delta"); |
| 192 | non_empty(delta.and_then(|d| d.get("content"))) |
| 193 | || non_empty(delta.and_then(|d| d.get("reasoning_content"))) |
| 194 | || non_empty(ch.get("text")) |
| 195 | }) |
| 196 | }); |
| 197 | c.kind = if has_content { |
| 198 | EventKind::Content |
| 199 | } else { |
| 200 | EventKind::NonContent |
| 201 | }; |
| 202 | c |
| 203 | } |
| 204 | |
| 205 | /// How one request ended. Only `Complete` contributes observations. |
| 206 | #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize)] |
| 207 | #[serde(rename_all = "snake_case")] |
| 208 | pub enum Outcome { |
| 209 | Complete, |
| 210 | ConnectError, |
| 211 | WriteError, |
| 212 | ReadError, |
| 213 | ReadTimeout, |
| 214 | MalformedStream, |
| 215 | TruncatedHead, |
| 216 | HttpStatus, |
| 217 | StreamErrorEvent, |
| 218 | TruncatedBody, |
| 219 | ZeroEvents, |
| 220 | MissingDone, |
| 221 | NoContent, |
| 222 | } |
| 223 | |
| 224 | impl Outcome { |
| 225 | pub fn as_str(self) -> &'static str { |
| 226 | match self { |
| 227 | Outcome::Complete => "complete", |
| 228 | Outcome::ConnectError => "connect_error", |
| 229 | Outcome::WriteError => "write_error", |
| 230 | Outcome::ReadError => "read_error", |
| 231 | Outcome::ReadTimeout => "read_timeout", |
| 232 | Outcome::MalformedStream => "malformed_stream", |
| 233 | Outcome::TruncatedHead => "truncated_head", |
| 234 | Outcome::HttpStatus => "http_status", |
| 235 | Outcome::StreamErrorEvent => "stream_error_event", |
| 236 | Outcome::TruncatedBody => "truncated_body", |
| 237 | Outcome::ZeroEvents => "zero_events", |
| 238 | Outcome::MissingDone => "missing_done", |
| 239 | Outcome::NoContent => "no_content", |
| 240 | } |
| 241 | } |
| 242 | } |
| 243 | |
| 244 | #[derive(Debug, Clone, Serialize)] |
| 245 | pub struct EventRecord { |
| 246 | pub offset_ms: f64, |
| 247 | pub read_index: u64, |
| 248 | pub kind: EventKind, |
| 249 | } |
| 250 | |
| 251 | /// Raw per-request observations. Offsets are milliseconds since `request_start`. |
| 252 | #[derive(Debug, Clone, Serialize)] |
| 253 | pub struct RequestSample { |
| 254 | pub index: u32, |
| 255 | pub outcome: Outcome, |
| 256 | pub detail: Option<String>, |
| 257 | pub connect_ms: Option<f64>, |
| 258 | pub http_status: Option<u16>, |
| 259 | pub content_type: Option<String>, |
| 260 | pub first_byte_ms: Option<f64>, |
| 261 | pub head_ms: Option<f64>, |
| 262 | pub first_content_ms: Option<f64>, |
| 263 | pub last_content_ms: Option<f64>, |
| 264 | pub completion_ms: Option<f64>, |
| 265 | pub done_seen: bool, |
| 266 | pub content_events: u64, |
| 267 | pub non_content_events: u64, |
| 268 | pub error_events: u64, |
| 269 | pub malformed_events: u64, |
| 270 | pub usage_completion_tokens: Option<u64>, |
| 271 | pub usage_prompt_tokens: Option<u64>, |
| 272 | pub reads: u64, |
| 273 | pub bytes: u64, |
| 274 | pub sse_comments: u64, |
| 275 | pub sse_ignored_lines: u64, |
| 276 | pub sse_invalid_utf8_lines: u64, |
| 277 | pub sse_empty_dispatches: u64, |
| 278 | pub error_body: Option<String>, |
| 279 | pub events: Vec<EventRecord>, |
| 280 | } |
| 281 | |
| 282 | impl RequestSample { |
| 283 | fn empty(index: u32) -> Self { |
| 284 | Self { |
| 285 | index, |
| 286 | outcome: Outcome::ReadError, |
| 287 | detail: None, |
| 288 | connect_ms: None, |
| 289 | http_status: None, |
| 290 | content_type: None, |
| 291 | first_byte_ms: None, |
| 292 | head_ms: None, |
| 293 | first_content_ms: None, |
| 294 | last_content_ms: None, |
| 295 | completion_ms: None, |
| 296 | done_seen: false, |
| 297 | content_events: 0, |
| 298 | non_content_events: 0, |
| 299 | error_events: 0, |
| 300 | malformed_events: 0, |
| 301 | usage_completion_tokens: None, |
| 302 | usage_prompt_tokens: None, |
| 303 | reads: 0, |
| 304 | bytes: 0, |
| 305 | sse_comments: 0, |
| 306 | sse_ignored_lines: 0, |
| 307 | sse_invalid_utf8_lines: 0, |
| 308 | sse_empty_dispatches: 0, |
| 309 | error_body: None, |
| 310 | events: Vec::new(), |
| 311 | } |
| 312 | } |
| 313 | |
| 314 | pub fn is_complete(&self) -> bool { |
| 315 | self.outcome == Outcome::Complete |
| 316 | } |
| 317 | } |
| 318 | |
| 319 | /// Pure state machine for one streamed response: feed reads with their arrival instants. |
| 320 | pub struct StreamAccumulator { |
| 321 | start: Instant, |
| 322 | http: HttpResponseParser, |
| 323 | sse: SseParser, |
| 324 | body: Vec<u8>, |
| 325 | events: Vec<SseEvent>, |
| 326 | error_body: Vec<u8>, |
| 327 | sample: RequestSample, |
| 328 | failure: Option<(Outcome, String)>, |
| 329 | finished: bool, |
| 330 | } |
| 331 | |
| 332 | impl StreamAccumulator { |
| 333 | pub fn new(index: u32, request_start: Instant) -> Self { |
| 334 | Self { |
| 335 | start: request_start, |
| 336 | http: HttpResponseParser::new(), |
| 337 | sse: SseParser::new(), |
| 338 | body: Vec::new(), |
| 339 | events: Vec::new(), |
| 340 | error_body: Vec::new(), |
| 341 | sample: RequestSample::empty(index), |
| 342 | failure: None, |
| 343 | finished: false, |
| 344 | } |
| 345 | } |
| 346 | |
| 347 | fn ms(&self, at: Instant) -> f64 { |
| 348 | at.saturating_duration_since(self.start).as_secs_f64() * 1000.0 |
| 349 | } |
| 350 | |
| 351 | pub fn is_finished(&self) -> bool { |
| 352 | self.finished |
| 353 | } |
| 354 | |
| 355 | /// Bytes of one read that returned at `at`. |
| 356 | pub fn feed(&mut self, bytes: &[u8], at: Instant) { |
| 357 | if self.finished { |
| 358 | return; |
| 359 | } |
| 360 | let read_index = self.sample.reads; |
| 361 | self.sample.reads += 1; |
| 362 | self.sample.bytes += bytes.len() as u64; |
| 363 | if self.sample.first_byte_ms.is_none() && !bytes.is_empty() { |
| 364 | self.sample.first_byte_ms = Some(self.ms(at)); |
| 365 | } |
| 366 | self.body.clear(); |
| 367 | if let Err(e) = self.http.feed(bytes, &mut self.body) { |
| 368 | self.fail(Outcome::MalformedStream, e.to_string()); |
| 369 | return; |
| 370 | } |
| 371 | let Some(head) = self.http.head().cloned() else { |
| 372 | return; |
| 373 | }; |
| 374 | if self.sample.head_ms.is_none() { |
| 375 | self.sample.head_ms = Some(self.ms(at)); |
| 376 | self.sample.http_status = Some(head.status); |
| 377 | self.sample.content_type = head.content_type.clone(); |
| 378 | } |
| 379 | if !head.is_success() { |
| 380 | let room = MAX_ERROR_BODY_BYTES.saturating_sub(self.error_body.len()); |
| 381 | let take = room.min(self.body.len()); |
| 382 | self.error_body.extend_from_slice(&self.body[..take]); |
| 383 | if self.http.body_complete() || room == 0 { |
| 384 | self.finished = true; |
| 385 | } |
| 386 | return; |
| 387 | } |
| 388 | if let Err(e) = self.sse.feed(&self.body, at, read_index, &mut self.events) { |
| 389 | self.fail(Outcome::MalformedStream, e.to_string()); |
| 390 | return; |
| 391 | } |
| 392 | let events = std::mem::take(&mut self.events); |
| 393 | for ev in events { |
| 394 | let c = classify(ev.event.as_deref(), &ev.data); |
| 395 | let offset_ms = self.ms(ev.at); |
| 396 | self.sample.events.push(EventRecord { |
| 397 | offset_ms, |
| 398 | read_index: ev.read_index, |
| 399 | kind: c.kind, |
| 400 | }); |
| 401 | if c.completion_tokens.is_some() { |
| 402 | self.sample.usage_completion_tokens = c.completion_tokens; |
| 403 | } |
| 404 | if c.prompt_tokens.is_some() { |
| 405 | self.sample.usage_prompt_tokens = c.prompt_tokens; |
| 406 | } |
| 407 | match c.kind { |
| 408 | EventKind::Content => { |
| 409 | self.sample.content_events += 1; |
| 410 | if self.sample.first_content_ms.is_none() { |
| 411 | self.sample.first_content_ms = Some(offset_ms); |
| 412 | } |
| 413 | self.sample.last_content_ms = Some(offset_ms); |
| 414 | } |
| 415 | EventKind::NonContent => self.sample.non_content_events += 1, |
| 416 | EventKind::Error => self.sample.error_events += 1, |
| 417 | EventKind::Malformed => self.sample.malformed_events += 1, |
| 418 | EventKind::Done => { |
| 419 | self.sample.done_seen = true; |
| 420 | self.sample.completion_ms = Some(offset_ms); |
| 421 | self.finished = true; |
| 422 | break; |
| 423 | } |
| 424 | } |
| 425 | } |
| 426 | if self.http.body_complete() { |
| 427 | self.finished = true; |
| 428 | } |
| 429 | } |
| 430 | |
| 431 | /// The peer closed the connection (read returned 0). |
| 432 | pub fn eof(&mut self) { |
| 433 | self.finished = true; |
| 434 | } |
| 435 | |
| 436 | /// A transport failure; the first one wins. |
| 437 | pub fn fail(&mut self, outcome: Outcome, detail: String) { |
| 438 | if self.failure.is_none() { |
| 439 | self.failure = Some((outcome, detail)); |
| 440 | } |
| 441 | self.finished = true; |
| 442 | } |
| 443 | |
| 444 | pub fn finish(mut self) -> RequestSample { |
| 445 | let s = &mut self.sample; |
| 446 | s.sse_comments = self.sse.comments; |
| 447 | s.sse_ignored_lines = self.sse.ignored_lines; |
| 448 | s.sse_invalid_utf8_lines = self.sse.invalid_utf8_lines; |
| 449 | s.sse_empty_dispatches = self.sse.empty_dispatches; |
| 450 | if !self.error_body.is_empty() { |
| 451 | let text = String::from_utf8_lossy(&self.error_body); |
| 452 | s.error_body = Some(text.chars().take(ERROR_SNIPPET_CHARS).collect()); |
| 453 | } |
| 454 | let total_events = s.events.len(); |
| 455 | let (outcome, detail) = if let Some((o, d)) = self.failure.take() { |
| 456 | (o, Some(d)) |
| 457 | } else if s.http_status.is_none() { |
| 458 | ( |
| 459 | Outcome::TruncatedHead, |
| 460 | Some("stream ended before a complete HTTP response head".to_string()), |
| 461 | ) |
| 462 | } else if !self.http.head().is_some_and(|h| h.is_success()) { |
| 463 | ( |
| 464 | Outcome::HttpStatus, |
| 465 | Some(format!("HTTP {}", s.http_status.unwrap_or(0))), |
| 466 | ) |
| 467 | } else if s.error_events > 0 { |
| 468 | ( |
| 469 | Outcome::StreamErrorEvent, |
| 470 | Some(format!("{} error event(s) in stream", s.error_events)), |
| 471 | ) |
| 472 | } else if s.done_seen { |
| 473 | if s.content_events == 0 { |
| 474 | ( |
| 475 | Outcome::NoContent, |
| 476 | Some("data: [DONE] without any content event".to_string()), |
| 477 | ) |
| 478 | } else { |
| 479 | (Outcome::Complete, None) |
| 480 | } |
| 481 | } else if !self.http.complete_at_eof() || self.sse.has_pending() { |
| 482 | ( |
| 483 | Outcome::TruncatedBody, |
| 484 | Some("body ended before its framing or the last SSE event completed".to_string()), |
| 485 | ) |
| 486 | } else if total_events == 0 { |
| 487 | (Outcome::ZeroEvents, Some("no SSE events".to_string())) |
| 488 | } else { |
| 489 | ( |
| 490 | Outcome::MissingDone, |
| 491 | Some("stream ended without data: [DONE]".to_string()), |
| 492 | ) |
| 493 | }; |
| 494 | s.outcome = outcome; |
| 495 | s.detail = detail; |
| 496 | if outcome != Outcome::Complete { |
| 497 | s.completion_ms = None; |
| 498 | } |
| 499 | self.sample |
| 500 | } |
| 501 | } |
| 502 | |
| 503 | /// One request over a fresh TCP connection (`Connection: close`). |
| 504 | pub fn measure_one(cfg: &StreamConfig, index: u32) -> RequestSample { |
| 505 | let connect_start = Instant::now(); |
| 506 | let addr = match (cfg.host.as_str(), cfg.port) |
| 507 | .to_socket_addrs() |
| 508 | .map_err(|e| e.to_string()) |
| 509 | .and_then(|mut a| a.next().ok_or_else(|| "no address".to_string())) |
| 510 | { |
| 511 | Ok(a) => a, |
| 512 | Err(e) => return failed(index, Outcome::ConnectError, format!("resolve: {}", e)), |
| 513 | }; |
| 514 | let mut stream = match TcpStream::connect_timeout(&addr, cfg.connect_timeout) { |
| 515 | Ok(s) => s, |
| 516 | Err(e) => return failed(index, Outcome::ConnectError, format!("{}: {}", addr, e)), |
| 517 | }; |
| 518 | let connect_ms = connect_start.elapsed().as_secs_f64() * 1000.0; |
| 519 | if let Err(e) = stream |
| 520 | .set_read_timeout(Some(cfg.read_timeout)) |
| 521 | .and_then(|_| stream.set_write_timeout(Some(cfg.read_timeout))) |
| 522 | .and_then(|_| stream.set_nodelay(true)) |
| 523 | { |
| 524 | return failed(index, Outcome::ConnectError, e.to_string()); |
| 525 | } |
| 526 | let req = cfg.request_bytes(); |
| 527 | let request_start = Instant::now(); |
| 528 | let mut acc = StreamAccumulator::new(index, request_start); |
| 529 | if let Err(e) = stream.write_all(&req) { |
| 530 | acc.fail(Outcome::WriteError, e.to_string()); |
| 531 | } |
| 532 | let mut buf = vec![0u8; 16 * 1024]; |
| 533 | while !acc.is_finished() { |
| 534 | match stream.read(&mut buf) { |
| 535 | Ok(0) => acc.eof(), |
| 536 | Ok(n) => { |
| 537 | let at = Instant::now(); |
| 538 | acc.feed(&buf[..n], at); |
| 539 | } |
| 540 | Err(e) if e.kind() == ErrorKind::Interrupted => {} |
| 541 | Err(e) if matches!(e.kind(), ErrorKind::WouldBlock | ErrorKind::TimedOut) => acc.fail( |
| 542 | Outcome::ReadTimeout, |
| 543 | format!("no bytes for {:?}: {}", cfg.read_timeout, e), |
| 544 | ), |
| 545 | Err(e) => acc.fail(Outcome::ReadError, e.to_string()), |
| 546 | } |
| 547 | } |
| 548 | let mut sample = acc.finish(); |
| 549 | sample.connect_ms = Some(connect_ms); |
| 550 | sample |
| 551 | } |
| 552 | |
| 553 | fn failed(index: u32, outcome: Outcome, detail: String) -> RequestSample { |
| 554 | let mut s = RequestSample::empty(index); |
| 555 | s.outcome = outcome; |
| 556 | s.detail = Some(detail); |
| 557 | s |
| 558 | } |
| 559 | |
| 560 | pub struct StreamRun { |
| 561 | pub warmup: Vec<RequestSample>, |
| 562 | pub samples: Vec<RequestSample>, |
| 563 | pub wall: Duration, |
| 564 | } |
| 565 | |
| 566 | /// Warmup requests run serially and are discarded; then `requests` measured requests run |
| 567 | /// on `concurrency` threads. |
| 568 | pub fn run_stream_benchmark(cfg: &StreamConfig) -> StreamRun { |
| 569 | let warmup = (0..cfg.warmup).map(|i| measure_one(cfg, i)).collect(); |
| 570 | let next = AtomicU32::new(0); |
| 571 | let results = Mutex::new(Vec::with_capacity(cfg.requests as usize)); |
| 572 | let workers = cfg.concurrency.clamp(1, cfg.requests.max(1)); |
| 573 | let t0 = Instant::now(); |
| 574 | std::thread::scope(|scope| { |
| 575 | for _ in 0..workers { |
| 576 | scope.spawn(|| loop { |
| 577 | let i = next.fetch_add(1, Ordering::Relaxed); |
| 578 | if i >= cfg.requests { |
| 579 | break; |
| 580 | } |
| 581 | let s = measure_one(cfg, i); |
| 582 | results.lock().unwrap_or_else(|p| p.into_inner()).push(s); |
| 583 | }); |
| 584 | } |
| 585 | }); |
| 586 | let wall = t0.elapsed(); |
| 587 | let mut samples = results.into_inner().unwrap_or_else(|p| p.into_inner()); |
| 588 | samples.sort_by_key(|s| s.index); |
| 589 | StreamRun { |
| 590 | warmup, |
| 591 | samples, |
| 592 | wall, |
| 593 | } |
| 594 | } |
| 595 | |
| 596 | /// Percentiles from real observations only. |
| 597 | #[derive(Debug, Clone, PartialEq)] |
| 598 | pub struct Distribution { |
| 599 | pub samples: usize, |
| 600 | pub p50: Option<f64>, |
| 601 | pub p95: Option<f64>, |
| 602 | } |
| 603 | |
| 604 | fn nearest_rank(sorted: &[f64], p: f64) -> f64 { |
| 605 | let n = sorted.len(); |
| 606 | let rank = ((p / 100.0) * n as f64).ceil() as usize; |
| 607 | sorted[rank.clamp(1, n) - 1] |
| 608 | } |
| 609 | |
| 610 | /// Nearest-rank percentiles: p50 when N >= 1, p95 only when N >= [`P95_MIN_SAMPLES`]. This is |
| 611 | /// the console view; a record carries p50 only from `evidence::min_samples_for(50)` on |
| 612 | /// (see `put_dist`). |
| 613 | pub fn distribution(values: &[f64]) -> Distribution { |
| 614 | let mut sorted: Vec<f64> = values.iter().copied().filter(|v| v.is_finite()).collect(); |
| 615 | sorted.sort_by(f64::total_cmp); |
| 616 | let n = sorted.len(); |
| 617 | Distribution { |
| 618 | samples: n, |
| 619 | p50: (n >= 1).then(|| nearest_rank(&sorted, 50.0)), |
| 620 | p95: (n >= P95_MIN_SAMPLES).then(|| nearest_rank(&sorted, 95.0)), |
| 621 | } |
| 622 | } |
| 623 | |
| 624 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 625 | pub enum TokenAccounting { |
| 626 | BackendUsage, |
| 627 | EventsNotTokens, |
| 628 | } |
| 629 | |
| 630 | impl TokenAccounting { |
| 631 | pub fn as_str(self) -> &'static str { |
| 632 | match self { |
| 633 | TokenAccounting::BackendUsage => "backend_usage", |
| 634 | TokenAccounting::EventsNotTokens => "events_not_tokens", |
| 635 | } |
| 636 | } |
| 637 | } |
| 638 | |
| 639 | #[derive(Debug, Clone)] |
| 640 | pub struct StreamSummary { |
| 641 | pub requests_attempted: usize, |
| 642 | pub requests_ok: usize, |
| 643 | pub failures: BTreeMap<&'static str, usize>, |
| 644 | pub wall_ms: f64, |
| 645 | pub ttft: Distribution, |
| 646 | pub first_byte: Distribution, |
| 647 | pub e2e: Distribution, |
| 648 | pub inter_event: Distribution, |
| 649 | pub content_events_total: u64, |
| 650 | pub events_coalesced_in_read: u64, |
| 651 | pub malformed_events_total: u64, |
| 652 | pub events_per_sec: Option<f64>, |
| 653 | pub token_accounting: TokenAccounting, |
| 654 | pub usage_requests: usize, |
| 655 | pub output_tokens_total: Option<u64>, |
| 656 | pub output_tokens_per_sec: Option<f64>, |
| 657 | pub tpot: Option<Distribution>, |
| 658 | } |
| 659 | |
| 660 | pub fn summarize(samples: &[RequestSample], wall: Duration) -> StreamSummary { |
| 661 | let ok: Vec<&RequestSample> = samples.iter().filter(|s| s.is_complete()).collect(); |
| 662 | let mut failures = BTreeMap::new(); |
| 663 | for s in samples.iter().filter(|s| !s.is_complete()) { |
| 664 | *failures.entry(s.outcome.as_str()).or_insert(0) += 1; |
| 665 | } |
| 666 | let mut gaps = Vec::new(); |
| 667 | let mut coalesced = 0; |
| 668 | for s in &ok { |
| 669 | let mut prev: Option<&EventRecord> = None; |
| 670 | for e in s.events.iter().filter(|e| e.kind == EventKind::Content) { |
| 671 | if let Some(p) = prev { |
| 672 | gaps.push(e.offset_ms - p.offset_ms); |
| 673 | if p.read_index == e.read_index { |
| 674 | coalesced += 1; |
| 675 | } |
| 676 | } |
| 677 | prev = Some(e); |
| 678 | } |
| 679 | } |
| 680 | let wall_s = wall.as_secs_f64(); |
| 681 | let content_events_total: u64 = ok.iter().map(|s| s.content_events).sum(); |
| 682 | let usage_requests = ok |
| 683 | .iter() |
| 684 | .filter(|s| s.usage_completion_tokens.is_some()) |
| 685 | .count(); |
| 686 | let token_accounting = if !ok.is_empty() && usage_requests == ok.len() { |
| 687 | TokenAccounting::BackendUsage |
| 688 | } else { |
| 689 | TokenAccounting::EventsNotTokens |
| 690 | }; |
| 691 | let (output_tokens_total, output_tokens_per_sec, tpot) = |
| 692 | if token_accounting == TokenAccounting::BackendUsage { |
| 693 | let total: u64 = ok.iter().filter_map(|s| s.usage_completion_tokens).sum(); |
| 694 | let tpot: Vec<f64> = ok |
| 695 | .iter() |
| 696 | .filter_map(|s| { |
| 697 | let tokens = s.usage_completion_tokens?; |
| 698 | let window = s.last_content_ms? - s.first_content_ms?; |
| 699 | (tokens >= 2 && window > 0.0).then(|| window / (tokens - 1) as f64) |
| 700 | }) |
| 701 | .collect(); |
| 702 | ( |
| 703 | Some(total), |
| 704 | (wall_s > 0.0).then(|| total as f64 / wall_s), |
| 705 | Some(distribution(&tpot)), |
| 706 | ) |
| 707 | } else { |
| 708 | (None, None, None) |
| 709 | }; |
| 710 | let pick = |f: fn(&RequestSample) -> Option<f64>| -> Vec<f64> { |
| 711 | ok.iter().filter_map(|s| f(s)).collect() |
| 712 | }; |
| 713 | StreamSummary { |
| 714 | requests_attempted: samples.len(), |
| 715 | requests_ok: ok.len(), |
| 716 | failures, |
| 717 | wall_ms: wall_s * 1000.0, |
| 718 | ttft: distribution(&pick(|s| s.first_content_ms)), |
| 719 | first_byte: distribution(&pick(|s| s.first_byte_ms)), |
| 720 | e2e: distribution(&pick(|s| s.completion_ms)), |
| 721 | inter_event: distribution(&gaps), |
| 722 | content_events_total, |
| 723 | events_coalesced_in_read: coalesced, |
| 724 | malformed_events_total: ok.iter().map(|s| s.malformed_events).sum(), |
| 725 | events_per_sec: (!ok.is_empty() && wall_s > 0.0) |
| 726 | .then(|| content_events_total as f64 / wall_s), |
| 727 | token_accounting, |
| 728 | usage_requests, |
| 729 | output_tokens_total, |
| 730 | output_tokens_per_sec, |
| 731 | tpot, |
| 732 | } |
| 733 | } |
| 734 | |
| 735 | #[derive(Debug, Clone)] |
| 736 | pub struct SourceIdentity { |
| 737 | pub commit: String, |
| 738 | pub dirty: bool, |
| 739 | } |
| 740 | |
| 741 | #[derive(Debug, Clone)] |
| 742 | pub struct BuildIdentity { |
| 743 | pub profile: String, |
| 744 | pub rustc: String, |
| 745 | } |
| 746 | |
| 747 | #[derive(Debug, Clone)] |
| 748 | pub struct HardwareIdentity { |
| 749 | pub host: String, |
| 750 | pub cpu: String, |
| 751 | pub gpu: String, |
| 752 | } |
| 753 | |
| 754 | /// Commit and dirty flag of the source tree this binary was built from, read with git at |
| 755 | /// run time. Refuses (Err) rather than inventing a commit. |
| 756 | pub fn source_identity() -> Result<SourceIdentity, String> { |
| 757 | let dir = env!("CARGO_MANIFEST_DIR"); |
| 758 | let head = Command::new("git") |
| 759 | .args(["-C", dir, "rev-parse", "HEAD"]) |
| 760 | .output() |
| 761 | .map_err(|e| format!("git rev-parse failed: {}", e))?; |
| 762 | let commit = String::from_utf8_lossy(&head.stdout).trim().to_string(); |
| 763 | if !head.status.success() |
| 764 | || commit.len() != 40 |
| 765 | || !commit.bytes().all(|b| b.is_ascii_hexdigit()) |
| 766 | { |
| 767 | return Err(format!("cannot read a 40-hex commit from {}", dir)); |
| 768 | } |
| 769 | let status = Command::new("git") |
| 770 | .args(["-C", dir, "status", "--porcelain", "--untracked-files=no"]) |
| 771 | .output() |
| 772 | .map_err(|e| format!("git status failed: {}", e))?; |
| 773 | if !status.status.success() { |
| 774 | return Err(format!("git status failed in {}", dir)); |
| 775 | } |
| 776 | Ok(SourceIdentity { |
| 777 | commit, |
| 778 | dirty: !status.stdout.is_empty(), |
| 779 | }) |
| 780 | } |
| 781 | |
| 782 | pub fn build_identity() -> BuildIdentity { |
| 783 | let rustc = Command::new("rustc") |
| 784 | .arg("-V") |
| 785 | .output() |
| 786 | .ok() |
| 787 | .filter(|o| o.status.success()) |
| 788 | .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string()) |
| 789 | .unwrap_or_else(|| "unknown".to_string()); |
| 790 | BuildIdentity { |
| 791 | profile: if cfg!(debug_assertions) { |
| 792 | "debug" |
| 793 | } else { |
| 794 | "release" |
| 795 | } |
| 796 | .to_string(), |
| 797 | rustc, |
| 798 | } |
| 799 | } |
| 800 | |
| 801 | /// Host name, CPU model and GPU model from /proc only (no GPU tool is run). |
| 802 | pub fn hardware_identity() -> HardwareIdentity { |
| 803 | let host = std::fs::read_to_string("/proc/sys/kernel/hostname") |
| 804 | .or_else(|_| std::fs::read_to_string("/etc/hostname")) |
| 805 | .map(|h| h.trim().to_string()) |
| 806 | .unwrap_or_else(|_| "unknown".to_string()); |
| 807 | let cpu = std::fs::read_to_string("/proc/cpuinfo") |
| 808 | .ok() |
| 809 | .and_then(|c| { |
| 810 | c.lines() |
| 811 | .find(|l| l.starts_with("model name")) |
| 812 | .and_then(|l| l.split_once(':')) |
| 813 | .map(|(_, v)| v.trim().to_string()) |
| 814 | }) |
| 815 | .unwrap_or_else(|| std::env::consts::ARCH.to_string()); |
| 816 | let mut gpus = Vec::new(); |
| 817 | if let Ok(dir) = std::fs::read_dir("/proc/driver/nvidia/gpus") { |
| 818 | for entry in dir.flatten() { |
| 819 | if let Ok(info) = std::fs::read_to_string(entry.path().join("information")) { |
| 820 | if let Some((_, v)) = info |
| 821 | .lines() |
| 822 | .find(|l| l.starts_with("Model:")) |
| 823 | .and_then(|l| l.split_once(':')) |
| 824 | { |
| 825 | let model = v.trim(); |
| 826 | gpus.push(if model.is_empty() || model == "Unknown" { |
| 827 | "NVIDIA GPU (driver reports model Unknown)".to_string() |
| 828 | } else { |
| 829 | model.to_string() |
| 830 | }); |
| 831 | } |
| 832 | } |
| 833 | } |
| 834 | } |
| 835 | gpus.sort(); |
| 836 | HardwareIdentity { |
| 837 | host, |
| 838 | cpu, |
| 839 | gpu: if gpus.is_empty() { |
| 840 | "none_detected".to_string() |
| 841 | } else { |
| 842 | gpus.join(", ") |
| 843 | }, |
| 844 | } |
| 845 | } |
| 846 | |
| 847 | fn put_dist(m: &mut Map<String, Value>, name: &str, d: &Distribution) { |
| 848 | // The record contract (src/evidence.rs) admits a pNN only when it can differ from the |
| 849 | // maximum, so a record carries p50 from 2 observations on (the console report keeps it). |
| 850 | let p50_min = crate::evidence::min_samples_for(50) as usize; |
| 851 | if let Some(v) = d.p50.filter(|_| d.samples >= p50_min) { |
| 852 | m.insert(format!("{}_p50", name), json!(v)); |
| 853 | } |
| 854 | if let Some(v) = d.p95 { |
| 855 | m.insert(format!("{}_p95", name), json!(v)); |
| 856 | } |
| 857 | m.insert(format!("{}_samples", name), json!(d.samples)); |
| 858 | } |
| 859 | |
| 860 | /// The `aien-bench-record/1` JSON for one run. |
| 861 | pub fn build_record( |
| 862 | cfg: &StreamConfig, |
| 863 | summary: &StreamSummary, |
| 864 | source: &SourceIdentity, |
| 865 | build: &BuildIdentity, |
| 866 | hw: &HardwareIdentity, |
| 867 | evidence: &[String], |
| 868 | ) -> Value { |
| 869 | let mut m = Map::new(); |
| 870 | m.insert( |
| 871 | "requests_attempted".into(), |
| 872 | json!(summary.requests_attempted), |
| 873 | ); |
| 874 | m.insert("requests_ok".into(), json!(summary.requests_ok)); |
| 875 | m.insert( |
| 876 | "requests_failed".into(), |
| 877 | json!(summary.requests_attempted - summary.requests_ok), |
| 878 | ); |
| 879 | m.insert("wall_ms".into(), json!(summary.wall_ms)); |
| 880 | put_dist(&mut m, "ttft_ms", &summary.ttft); |
| 881 | put_dist(&mut m, "first_byte_ms", &summary.first_byte); |
| 882 | put_dist(&mut m, "e2e_ms", &summary.e2e); |
| 883 | put_dist(&mut m, "inter_event_ms", &summary.inter_event); |
| 884 | m.insert( |
| 885 | "content_events_total".into(), |
| 886 | json!(summary.content_events_total), |
| 887 | ); |
| 888 | m.insert( |
| 889 | "events_coalesced_in_read".into(), |
| 890 | json!(summary.events_coalesced_in_read), |
| 891 | ); |
| 892 | if let Some(v) = summary.events_per_sec { |
| 893 | m.insert("events_per_sec".into(), json!(v)); |
| 894 | } |
| 895 | if let Some(v) = summary.output_tokens_total { |
| 896 | m.insert("output_tokens_total".into(), json!(v)); |
| 897 | } |
| 898 | if let Some(v) = summary.output_tokens_per_sec { |
| 899 | m.insert("output_tokens_per_sec".into(), json!(v)); |
| 900 | } |
| 901 | if let Some(d) = &summary.tpot { |
| 902 | put_dist(&mut m, "tpot_ms", d); |
| 903 | } |
| 904 | |
| 905 | let mut defs = Map::new(); |
| 906 | let mut def = |k: &str, v: String| { |
| 907 | defs.insert(k.to_string(), json!(v)); |
| 908 | }; |
| 909 | def("request_start", "Instant taken immediately before the HTTP request bytes are written to an already-connected TCP socket; connect time is excluded and kept per request in the samples file as connect_ms".into()); |
| 910 | def("arrival", "an event's arrival is the Instant taken immediately after the socket read that delivered its final byte returned; events completed by one read share that arrival".into()); |
| 911 | def( |
| 912 | "first_byte_ms", |
| 913 | "request_start to arrival of the first response byte".into(), |
| 914 | ); |
| 915 | def("ttft_ms", "request_start to arrival of the first content event: an SSE event whose JSON has a non-empty choices[].delta.content, choices[].delta.reasoning_content or choices[].text. Role-only, empty-delta, finish-only and usage-only events are not content".into()); |
| 916 | def("e2e_ms", "request_start to arrival of data: [DONE]".into()); |
| 917 | def("inter_event_ms", "gap between arrivals of consecutive content events of one request, pooled over successful requests; SSE events, not model tokens".into()); |
| 918 | def("events_coalesced_in_read", "content events that arrived in the same socket read as the previous content event of their request; their inter-event gap is 0 by construction".into()); |
| 919 | def( |
| 920 | "events_per_sec", |
| 921 | "content events of successful requests divided by wall_ms; events, not tokens".into(), |
| 922 | ); |
| 923 | def( |
| 924 | "wall_ms", |
| 925 | "first measured request dispatch to last measured request finish; warmup excluded".into(), |
| 926 | ); |
| 927 | def("success", "a request succeeds when it returns HTTP 2xx, has at least one content event, no error event, and ends with data: [DONE]; read errors and read timeouts are failures, never end of stream".into()); |
| 928 | def("percentiles", format!("nearest-rank over the N successful observations of that metric; p50 only when N >= {}, p95 only when N >= {}; N is recorded as <metric>_samples", crate::evidence::min_samples_for(50), P95_MIN_SAMPLES)); |
| 929 | def("warmup", format!("{} warmup request(s) with the same prompt and max_tokens ran serially first and were discarded", cfg.warmup)); |
| 930 | if summary.token_accounting == TokenAccounting::BackendUsage { |
| 931 | def("output_tokens_per_sec", "sum of backend-reported usage.completion_tokens over successful requests divided by wall_ms".into()); |
| 932 | def("tpot_ms", "per request: (last content event arrival - first content event arrival) / (usage.completion_tokens - 1); requests with fewer than 2 tokens are excluded".into()); |
| 933 | } |
| 934 | def( |
| 935 | "requests_attempted", |
| 936 | "measured requests sent (warmup excluded)".into(), |
| 937 | ); |
| 938 | def( |
| 939 | "requests_ok", |
| 940 | "measured requests that succeeded (see success)".into(), |
| 941 | ); |
| 942 | def("requests_failed", "requests_attempted - requests_ok".into()); |
| 943 | def( |
| 944 | "content_events_total", |
| 945 | "content events over successful requests; SSE events, not model tokens".into(), |
| 946 | ); |
| 947 | def( |
| 948 | "output_tokens_total", |
| 949 | "sum of backend-reported usage.completion_tokens over successful requests".into(), |
| 950 | ); |
| 951 | // Every metric key needs a definition in the record contract (src/evidence.rs); the |
| 952 | // percentile and sample-count keys of a distribution are defined from their base metric. |
| 953 | for k in m.keys() { |
| 954 | if defs.contains_key(k) { |
| 955 | continue; |
| 956 | } |
| 957 | let text = if let Some(base) = k.strip_suffix("_samples") { |
| 958 | format!("number of successful observations of {base}") |
| 959 | } else if let Some((base, q)) = k.rsplit_once("_p") { |
| 960 | format!("nearest-rank p{q} of {base} (see percentiles)") |
| 961 | } else { |
| 962 | continue; |
| 963 | }; |
| 964 | defs.insert(k.clone(), json!(text)); |
| 965 | } |
| 966 | |
| 967 | let mut limitations = vec![ |
| 968 | "Commit and dirty flag were read from the source tree with git at run time, not embedded at build time; rustc is the toolchain on PATH at run time.".to_string(), |
| 969 | "Arrival times have socket-read granularity: bytes that arrive together in one read cannot be told apart.".to_string(), |
| 970 | "Not reviewed or qualified against a pinned baseline; EXPERIMENTAL until it is.".to_string(), |
| 971 | ]; |
| 972 | match summary.token_accounting { |
| 973 | TokenAccounting::EventsNotTokens if summary.requests_ok == 0 => limitations.push( |
| 974 | "events_not_tokens: no request succeeded, so no event or token metrics exist.".to_string(), |
| 975 | ), |
| 976 | TokenAccounting::EventsNotTokens => limitations.push(format!( |
| 977 | "events_not_tokens: the backend reported usage.completion_tokens for {} of {} successful requests, so no token counts, tokens per second or per-token latency are reported; event metrics count SSE events, which may carry zero, one or several tokens.", |
| 978 | summary.usage_requests, summary.requests_ok |
| 979 | )), |
| 980 | TokenAccounting::BackendUsage => limitations.push( |
| 981 | "Token counts are the backend's own usage.completion_tokens, not verified by this client.".to_string(), |
| 982 | ), |
| 983 | } |
| 984 | if summary.events_coalesced_in_read > 0 { |
| 985 | limitations.push(format!( |
| 986 | "{} content event(s) arrived in the same read as the previous one; their 0 ms gaps are in inter_event_ms.", |
| 987 | summary.events_coalesced_in_read |
| 988 | )); |
| 989 | } |
| 990 | if summary.ttft.samples < P95_MIN_SAMPLES { |
| 991 | limitations.push(format!( |
| 992 | "Only {} successful request(s): p95 values are omitted (need {}).", |
| 993 | summary.ttft.samples, P95_MIN_SAMPLES |
| 994 | )); |
| 995 | } |
| 996 | if summary.ttft.samples < crate::evidence::min_samples_for(50) as usize { |
| 997 | limitations.push(format!( |
| 998 | "Only {} successful request(s): p50 values are omitted from the record (need {}).", |
| 999 | summary.ttft.samples, |
| 1000 | crate::evidence::min_samples_for(50) |
| 1001 | )); |
| 1002 | } |
| 1003 | if !summary.failures.is_empty() { |
| 1004 | let kinds: Vec<String> = summary |
| 1005 | .failures |
| 1006 | .iter() |
| 1007 | .map(|(k, n)| format!("{} {}", n, k)) |
| 1008 | .collect(); |
| 1009 | limitations.push(format!( |
| 1010 | "{} of {} measured request(s) failed ({}); metrics use successful requests only.", |
| 1011 | summary.requests_attempted - summary.requests_ok, |
| 1012 | summary.requests_attempted, |
| 1013 | kinds.join(", ") |
| 1014 | )); |
| 1015 | } |
| 1016 | if summary.malformed_events_total > 0 { |
| 1017 | limitations.push(format!( |
| 1018 | "{} SSE event(s) in successful requests were not valid JSON and were ignored.", |
| 1019 | summary.malformed_events_total |
| 1020 | )); |
| 1021 | } |
| 1022 | if cfg.precision.is_none() { |
| 1023 | limitations.push("Precision was not labeled by the operator.".to_string()); |
| 1024 | } |
| 1025 | if cfg.engine == "unlabeled" { |
| 1026 | limitations.push("Engine was not labeled by the operator.".to_string()); |
| 1027 | } |
| 1028 | if !cfg.request_usage { |
| 1029 | limitations.push( |
| 1030 | "stream_options.include_usage was not requested, so backends that only send usage on request did not send it.".to_string(), |
| 1031 | ); |
| 1032 | } |
| 1033 | |
| 1034 | let mut backend = json!({ |
| 1035 | "engine": cfg.engine, |
| 1036 | "model": cfg.model, |
| 1037 | "precision": cfg.precision.clone().unwrap_or_else(|| "unlabeled".to_string()), |
| 1038 | "endpoint": cfg.endpoint(), |
| 1039 | }); |
| 1040 | if let Some(ctx) = cfg.context_length { |
| 1041 | backend["context_length"] = json!(ctx); |
| 1042 | } |
| 1043 | // DRA-166 binding. Digests are written only when the operator named the files; a record |
| 1044 | // without them fails the record contract (bench_verify_records) and llm-stream exits 3. |
| 1045 | if let Some(h) = &cfg.binary_sha256 { |
| 1046 | backend["binary_sha256"] = json!(h); |
| 1047 | } |
| 1048 | if let Some(h) = &cfg.model_sha256 { |
| 1049 | backend["model_sha256"] = json!(h); |
| 1050 | } |
| 1051 | limitations.push( |
| 1052 | "parity: llm-stream times one endpoint and compares no output against a reference, so parity is NOT_RUN and methodology.tolerance names no tolerance.".to_string(), |
| 1053 | ); |
| 1054 | if cfg.binary_sha256.is_some() || cfg.model_sha256.is_some() { |
| 1055 | limitations.push( |
| 1056 | "backend.binary_sha256, backend.model_sha256: digests of the files the operator named with --llm-binary and --llm-model-file; llm-stream does not check that the process answering on the endpoint runs that binary or loaded that model.".to_string(), |
| 1057 | ); |
| 1058 | } |
| 1059 | |
| 1060 | json!({ |
| 1061 | "schema": RECORD_SCHEMA, |
| 1062 | "status": if summary.requests_ok == 0 { "FAIL" } else { "EXPERIMENTAL" }, |
| 1063 | "source": {"repo": REPO, "commit": source.commit, "dirty": source.dirty}, |
| 1064 | "build": {"profile": build.profile, "rustc": build.rustc}, |
| 1065 | "workload": { |
| 1066 | "name": WORKLOAD, |
| 1067 | "prompt_bytes": cfg.prompt.len(), |
| 1068 | "max_tokens": cfg.max_tokens, |
| 1069 | "requests": cfg.requests, |
| 1070 | "concurrency": cfg.concurrency, |
| 1071 | }, |
| 1072 | "hardware": {"host": hw.host, "cpu": hw.cpu, "gpu": hw.gpu}, |
| 1073 | "backend": backend, |
| 1074 | "methodology": { |
| 1075 | "clock": CLOCK, |
| 1076 | "definitions": Value::Object(defs), |
| 1077 | "token_accounting": summary.token_accounting.as_str(), |
| 1078 | "samples": summary.ttft.samples, |
| 1079 | "warmup": cfg.warmup, |
| 1080 | "tolerance": "none: no output comparison in llm-stream (see parity)", |
| 1081 | }, |
| 1082 | "parity": {"reference": "none", "verdict": "NOT_RUN"}, |
| 1083 | "metrics": Value::Object(m), |
| 1084 | "evidence": evidence, |
| 1085 | "limitations": limitations, |
| 1086 | }) |
| 1087 | } |
| 1088 | |
| 1089 | /// sha256 (64 lowercase hex characters) binding the binary or model a record names (DRA-166). |
| 1090 | /// A file is hashed by streaming its bytes. A directory (a sharded checkpoint) is hashed as the |
| 1091 | /// sha256 of its manifest: one line `<file sha256> <path relative to the directory>\n` per |
| 1092 | /// regular file below it, symlinks followed, lines sorted by path. A symlink that leads back to |
| 1093 | /// a directory already being walked (a cycle) is refused with an error, not followed forever. |
| 1094 | pub fn file_sha256(path: &Path) -> Result<String, String> { |
| 1095 | let meta = std::fs::metadata(path).map_err(|e| format!("read {}: {}", path.display(), e))?; |
| 1096 | if !meta.is_dir() { |
| 1097 | return stream_sha256(path); |
| 1098 | } |
| 1099 | let mut files = Vec::new(); |
| 1100 | let mut walking = Vec::new(); |
| 1101 | collect_files(path, Path::new(""), &mut walking, &mut files)?; |
| 1102 | if files.is_empty() { |
| 1103 | return Err(format!("{}: directory holds no files", path.display())); |
| 1104 | } |
| 1105 | files.sort(); |
| 1106 | let mut manifest = String::new(); |
| 1107 | for rel in &files { |
| 1108 | let h = stream_sha256(&path.join(rel))?; |
| 1109 | manifest.push_str(&format!("{h} {}\n", rel.display())); |
| 1110 | } |
| 1111 | Ok(hex_digest(manifest.as_bytes())) |
| 1112 | } |
| 1113 | |
| 1114 | fn stream_sha256(path: &Path) -> Result<String, String> { |
| 1115 | use sha2::{Digest, Sha256}; |
| 1116 | let mut f = std::fs::File::open(path).map_err(|e| format!("read {}: {}", path.display(), e))?; |
| 1117 | let mut hasher = Sha256::new(); |
| 1118 | std::io::copy(&mut f, &mut hasher).map_err(|e| format!("read {}: {}", path.display(), e))?; |
| 1119 | Ok(hasher |
| 1120 | .finalize() |
| 1121 | .iter() |
| 1122 | .map(|b| format!("{b:02x}")) |
| 1123 | .collect()) |
| 1124 | } |
| 1125 | |
| 1126 | fn hex_digest(bytes: &[u8]) -> String { |
| 1127 | use sha2::{Digest, Sha256}; |
| 1128 | Sha256::digest(bytes) |
| 1129 | .iter() |
| 1130 | .map(|b| format!("{b:02x}")) |
| 1131 | .collect() |
| 1132 | } |
| 1133 | |
| 1134 | /// `walking` holds the canonical paths of the directories from `root` down to `rel`, so a |
| 1135 | /// directory symlink back to one of them is a cycle. |
| 1136 | fn collect_files( |
| 1137 | root: &Path, |
| 1138 | rel: &Path, |
| 1139 | walking: &mut Vec<PathBuf>, |
| 1140 | out: &mut Vec<PathBuf>, |
| 1141 | ) -> Result<(), String> { |
| 1142 | let dir = root.join(rel); |
| 1143 | let canonical = |
| 1144 | std::fs::canonicalize(&dir).map_err(|e| format!("read {}: {}", dir.display(), e))?; |
| 1145 | if walking.contains(&canonical) { |
| 1146 | return Err(format!( |
| 1147 | "{}: symlink cycle (leads back to {})", |
| 1148 | dir.display(), |
| 1149 | canonical.display() |
| 1150 | )); |
| 1151 | } |
| 1152 | walking.push(canonical); |
| 1153 | let entries = std::fs::read_dir(&dir).map_err(|e| format!("read {}: {}", dir.display(), e))?; |
| 1154 | for entry in entries { |
| 1155 | let entry = entry.map_err(|e| format!("read {}: {}", dir.display(), e))?; |
| 1156 | let child = rel.join(entry.file_name()); |
| 1157 | let meta = std::fs::metadata(root.join(&child)) |
| 1158 | .map_err(|e| format!("read {}: {}", root.join(&child).display(), e))?; |
| 1159 | if meta.is_dir() { |
| 1160 | collect_files(root, &child, walking, out)?; |
| 1161 | } else if meta.is_file() { |
| 1162 | out.push(child); |
| 1163 | } |
| 1164 | } |
| 1165 | walking.pop(); |
| 1166 | Ok(()) |
| 1167 | } |
| 1168 | |
| 1169 | /// Write `<stem>.samples.json` (raw per-request observations) and `<stem>.json` (the |
| 1170 | /// record) into `root/out_dir`, and return the record's path. The record's `evidence` path is |
| 1171 | /// `out_dir/<stem>.samples.json`, relative to `root`: the same root `bench_verify_records` |
| 1172 | /// resolves evidence against (the repository). An `out_dir` that is absolute or leaves the |
| 1173 | /// root gives an evidence path the record contract refuses, so such a record is not a claim. |
| 1174 | pub fn write_run( |
| 1175 | root: &Path, |
| 1176 | out_dir: &Path, |
| 1177 | cfg: &StreamConfig, |
| 1178 | run: &StreamRun, |
| 1179 | summary: &StreamSummary, |
| 1180 | source: &SourceIdentity, |
| 1181 | ) -> Result<PathBuf, String> { |
| 1182 | let dir = root.join(out_dir); |
| 1183 | std::fs::create_dir_all(&dir).map_err(|e| format!("create {}: {}", dir.display(), e))?; |
| 1184 | let stem = format!( |
| 1185 | "llm_streaming-{}", |
| 1186 | chrono::Utc::now().format("%Y%m%dT%H%M%S%.3fZ") |
| 1187 | ); |
| 1188 | let samples_name = format!("{}.samples.json", stem); |
| 1189 | let record_name = format!("{}.json", stem); |
| 1190 | // `./records` and `records` name the same place; the record keeps the plain form. |
| 1191 | let rel_dir: PathBuf = out_dir |
| 1192 | .components() |
| 1193 | .filter(|c| !matches!(c, std::path::Component::CurDir)) |
| 1194 | .collect(); |
| 1195 | let evidence = rel_dir.join(&samples_name).to_string_lossy().into_owned(); |
| 1196 | let samples = json!({ |
| 1197 | "schema": SAMPLES_SCHEMA, |
| 1198 | "record": record_name, |
| 1199 | "clock": CLOCK, |
| 1200 | "offsets": "milliseconds since request_start of the same request", |
| 1201 | "warmup": run.warmup, |
| 1202 | "samples": run.samples, |
| 1203 | }); |
| 1204 | let record = build_record( |
| 1205 | cfg, |
| 1206 | summary, |
| 1207 | source, |
| 1208 | &build_identity(), |
| 1209 | &hardware_identity(), |
| 1210 | std::slice::from_ref(&evidence), |
| 1211 | ); |
| 1212 | let write = |name: &str, v: &Value| { |
| 1213 | let path = dir.join(name); |
| 1214 | let text = serde_json::to_string_pretty(v).map_err(|e| e.to_string())?; |
| 1215 | std::fs::write(&path, text + "\n").map_err(|e| format!("write {}: {}", path.display(), e)) |
| 1216 | }; |
| 1217 | write(&samples_name, &samples)?; |
| 1218 | write(&record_name, &record)?; |
| 1219 | Ok(dir.join(record_name)) |
| 1220 | } |
| 1221 | |
| 1222 | #[cfg(test)] |
| 1223 | mod tests { |
| 1224 | use super::*; |
| 1225 | use std::io::BufRead; |
| 1226 | use std::net::TcpListener; |
| 1227 | |
| 1228 | const HEAD_CHUNKED: &[u8] = |
| 1229 | b"HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nTransfer-Encoding: chunked\r\n\r\n"; |
| 1230 | const HEAD_CLOSE: &[u8] = b"HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\n\r\n"; |
| 1231 | |
| 1232 | fn content(text: &str) -> String { |
| 1233 | format!( |
| 1234 | "data: {{\"choices\":[{{\"index\":0,\"delta\":{{\"content\":\"{}\"}}}}]}}\n\n", |
| 1235 | text |
| 1236 | ) |
| 1237 | } |
| 1238 | |
| 1239 | fn chunk(payload: &str) -> Vec<u8> { |
| 1240 | let mut v = format!("{:x}\r\n", payload.len()).into_bytes(); |
| 1241 | v.extend_from_slice(payload.as_bytes()); |
| 1242 | v.extend_from_slice(b"\r\n"); |
| 1243 | v |
| 1244 | } |
| 1245 | |
| 1246 | /// Feed `reads` as separate reads, read i arriving at base + 10*(i+1) ms, then EOF. |
| 1247 | fn run_reads(reads: &[Vec<u8>]) -> RequestSample { |
| 1248 | let base = Instant::now(); |
| 1249 | let mut acc = StreamAccumulator::new(0, base); |
| 1250 | for (i, r) in reads.iter().enumerate() { |
| 1251 | acc.feed(r, base + Duration::from_millis(10 * (i as u64 + 1))); |
| 1252 | if acc.is_finished() { |
| 1253 | return acc.finish(); |
| 1254 | } |
| 1255 | } |
| 1256 | acc.eof(); |
| 1257 | acc.finish() |
| 1258 | } |
| 1259 | |
| 1260 | fn cat(parts: &[&[u8]]) -> Vec<u8> { |
| 1261 | parts.concat() |
| 1262 | } |
| 1263 | |
| 1264 | #[test] |
| 1265 | fn frame_split_across_reads_uses_completing_read_time() { |
| 1266 | let ev = content("hi"); |
| 1267 | let (a, b) = ev.as_bytes().split_at(10); |
| 1268 | let s = run_reads(&[ |
| 1269 | HEAD_CLOSE.to_vec(), |
| 1270 | a.to_vec(), |
| 1271 | b.to_vec(), |
| 1272 | b"data: [DONE]\n\n".to_vec(), |
| 1273 | ]); |
| 1274 | assert_eq!(s.outcome, Outcome::Complete); |
| 1275 | assert_eq!(s.head_ms, Some(10.0)); |
| 1276 | assert_eq!( |
| 1277 | s.first_content_ms, |
| 1278 | Some(30.0), |
| 1279 | "stamped at the read with the final byte" |
| 1280 | ); |
| 1281 | assert_eq!(s.completion_ms, Some(40.0)); |
| 1282 | assert_eq!(s.content_events, 1); |
| 1283 | } |
| 1284 | |
| 1285 | #[test] |
| 1286 | fn multiple_events_in_one_read_are_coalesced_and_counted() { |
| 1287 | let body = format!("{}{}{}", content("a"), content("b"), content("c")); |
| 1288 | let s = run_reads(&[ |
| 1289 | cat(&[HEAD_CLOSE, body.as_bytes()]), |
| 1290 | content("d").into_bytes(), |
| 1291 | b"data: [DONE]\n\n".to_vec(), |
| 1292 | ]); |
| 1293 | assert_eq!(s.outcome, Outcome::Complete); |
| 1294 | assert_eq!(s.content_events, 4); |
| 1295 | let sum = summarize(std::slice::from_ref(&s), Duration::from_millis(100)); |
| 1296 | assert_eq!(sum.events_coalesced_in_read, 2); |
| 1297 | assert_eq!(sum.inter_event.samples, 3); |
| 1298 | assert_eq!(sum.inter_event.p50, Some(0.0)); |
| 1299 | assert_eq!(sum.inter_event.p95, None); |
| 1300 | assert_eq!(sum.token_accounting, TokenAccounting::EventsNotTokens); |
| 1301 | assert!((sum.events_per_sec.unwrap() - 40.0).abs() < 1e-9); |
| 1302 | } |
| 1303 | |
| 1304 | #[test] |
| 1305 | fn malformed_stream_is_a_failure_and_bad_json_is_counted() { |
| 1306 | let bad_chunk = run_reads(&[cat(&[HEAD_CHUNKED, b"zz\r\nxx"])]); |
| 1307 | assert_eq!(bad_chunk.outcome, Outcome::MalformedStream); |
| 1308 | assert_eq!(bad_chunk.first_content_ms, None); |
| 1309 | |
| 1310 | let bad_json = run_reads(&[ |
| 1311 | cat(&[HEAD_CLOSE, b"data: {not json\n\n"]), |
| 1312 | content("ok").into_bytes(), |
| 1313 | b"data: [DONE]\n\n".to_vec(), |
| 1314 | ]); |
| 1315 | assert_eq!(bad_json.outcome, Outcome::Complete); |
| 1316 | assert_eq!(bad_json.malformed_events, 1); |
| 1317 | assert_eq!(bad_json.first_content_ms, Some(20.0)); |
| 1318 | } |
| 1319 | |
| 1320 | #[test] |
| 1321 | fn zero_events_and_done_only_are_failures() { |
| 1322 | let zero = run_reads(&[cat(&[HEAD_CLOSE, b": ping\n\n"])]); |
| 1323 | assert_eq!(zero.outcome, Outcome::ZeroEvents); |
| 1324 | assert_eq!(zero.sse_comments, 1); |
| 1325 | |
| 1326 | let empty = run_reads(&[]); |
| 1327 | assert_eq!(empty.outcome, Outcome::TruncatedHead); |
| 1328 | |
| 1329 | let done_only = run_reads(&[cat(&[HEAD_CLOSE, b"data: [DONE]\n\n"])]); |
| 1330 | assert_eq!(done_only.outcome, Outcome::NoContent); |
| 1331 | let sum = summarize(&[zero, done_only], Duration::from_millis(5)); |
| 1332 | assert_eq!(sum.requests_ok, 0); |
| 1333 | assert_eq!(sum.ttft.samples, 0); |
| 1334 | assert_eq!(sum.ttft.p50, None); |
| 1335 | assert_eq!(sum.events_per_sec, None); |
| 1336 | } |
| 1337 | |
| 1338 | #[test] |
| 1339 | fn http_500_body_is_kept_and_never_measured() { |
| 1340 | let s = run_reads(&[ |
| 1341 | b"HTTP/1.1 500 Internal Server Error\r\nContent-Type: application/json\r\nContent-Length: 25\r\n\r\n{\"error\":".to_vec(), |
| 1342 | b"\"model crashed\"}".to_vec(), |
| 1343 | ]); |
| 1344 | assert_eq!(s.outcome, Outcome::HttpStatus); |
| 1345 | assert_eq!(s.http_status, Some(500)); |
| 1346 | assert_eq!( |
| 1347 | s.error_body.as_deref(), |
| 1348 | Some("{\"error\":\"model crashed\"}") |
| 1349 | ); |
| 1350 | assert_eq!(s.first_content_ms, None); |
| 1351 | assert_eq!(s.events.len(), 0); |
| 1352 | } |
| 1353 | |
| 1354 | #[test] |
| 1355 | fn error_event_in_a_200_stream_fails_the_request() { |
| 1356 | let s = run_reads(&[cat(&[ |
| 1357 | HEAD_CLOSE, |
| 1358 | content("a").as_bytes(), |
| 1359 | b"data: {\"error\":{\"message\":\"oom\"}}\n\ndata: [DONE]\n\n", |
| 1360 | ])]); |
| 1361 | assert_eq!(s.outcome, Outcome::StreamErrorEvent); |
| 1362 | assert_eq!(s.error_events, 1); |
| 1363 | assert_eq!(s.completion_ms, None); |
| 1364 | } |
| 1365 | |
| 1366 | #[test] |
| 1367 | fn non_token_events_do_not_start_ttft() { |
| 1368 | let role = "data: {\"choices\":[{\"index\":0,\"delta\":{\"role\":\"assistant\"}}]}\n\n"; |
| 1369 | let empty = "data: {\"choices\":[{\"index\":0,\"delta\":{\"content\":\"\"}}]}\n\n"; |
| 1370 | let finish = |
| 1371 | "data: {\"choices\":[{\"index\":0,\"delta\":{},\"finish_reason\":\"stop\"}]}\n\n"; |
| 1372 | let s = run_reads(&[ |
| 1373 | cat(&[HEAD_CHUNKED, &chunk(role)]), |
| 1374 | chunk(empty), |
| 1375 | chunk(&content("x")), |
| 1376 | chunk(finish), |
| 1377 | cat(&[&chunk("data: [DONE]\n\n"), b"0\r\n\r\n"]), |
| 1378 | ]); |
| 1379 | assert_eq!(s.outcome, Outcome::Complete); |
| 1380 | assert_eq!(s.non_content_events, 3); |
| 1381 | assert_eq!(s.content_events, 1); |
| 1382 | assert_eq!(s.first_byte_ms, Some(10.0)); |
| 1383 | assert_eq!(s.first_content_ms, Some(30.0)); |
| 1384 | } |
| 1385 | |
| 1386 | #[test] |
| 1387 | fn truncated_responses_are_failures_not_eof() { |
| 1388 | // Chunked body cut mid-event. |
| 1389 | let s = run_reads(&[cat(&[ |
| 1390 | HEAD_CHUNKED, |
| 1391 | &chunk(&content("a")), |
| 1392 | b"20\r\ndata: {\"cho", |
| 1393 | ])]); |
| 1394 | assert_eq!(s.outcome, Outcome::TruncatedBody); |
| 1395 | assert_eq!(s.content_events, 1); |
| 1396 | // Read-until-close body that closes cleanly but never sends [DONE]. |
| 1397 | let s = run_reads(&[cat(&[HEAD_CLOSE, content("a").as_bytes()])]); |
| 1398 | assert_eq!(s.outcome, Outcome::MissingDone); |
| 1399 | // Head cut short. |
| 1400 | let s = run_reads(&[b"HTTP/1.1 200 OK\r\nContent-Ty".to_vec()]); |
| 1401 | assert_eq!(s.outcome, Outcome::TruncatedHead); |
| 1402 | // A read error after content is a failure. |
| 1403 | let base = Instant::now(); |
| 1404 | let mut acc = StreamAccumulator::new(0, base); |
| 1405 | acc.feed(&cat(&[HEAD_CLOSE, content("a").as_bytes()]), base); |
| 1406 | acc.fail(Outcome::ReadError, "connection reset".into()); |
| 1407 | assert_eq!(acc.finish().outcome, Outcome::ReadError); |
| 1408 | } |
| 1409 | |
| 1410 | #[test] |
| 1411 | fn usage_present_vs_absent_accounting() { |
| 1412 | let usage = |
| 1413 | "data: {\"choices\":[],\"usage\":{\"prompt_tokens\":7,\"completion_tokens\":9}}\n\n"; |
| 1414 | let with_usage = run_reads(&[ |
| 1415 | cat(&[HEAD_CLOSE, content("a").as_bytes()]), |
| 1416 | content("bcd").into_bytes(), |
| 1417 | content("e").into_bytes(), |
| 1418 | cat(&[usage.as_bytes(), b"data: [DONE]\n\n"]), |
| 1419 | ]); |
| 1420 | assert_eq!(with_usage.usage_completion_tokens, Some(9)); |
| 1421 | assert_eq!(with_usage.usage_prompt_tokens, Some(7)); |
| 1422 | let sum = summarize(std::slice::from_ref(&with_usage), Duration::from_secs(1)); |
| 1423 | assert_eq!(sum.token_accounting, TokenAccounting::BackendUsage); |
| 1424 | assert_eq!(sum.output_tokens_total, Some(9)); |
| 1425 | assert_eq!(sum.output_tokens_per_sec, Some(9.0)); |
| 1426 | // first content at 10 ms, last at 30 ms, 9 tokens: 20 / 8 ms per token. |
| 1427 | assert_eq!(sum.tpot.as_ref().unwrap().p50, Some(2.5)); |
| 1428 | |
| 1429 | let without = run_reads(&[ |
| 1430 | cat(&[HEAD_CLOSE, content("a").as_bytes()]), |
| 1431 | cat(&[content("b").as_bytes(), b"data: [DONE]\n\n"]), |
| 1432 | ]); |
| 1433 | let mixed = summarize(&[with_usage, without], Duration::from_secs(1)); |
| 1434 | assert_eq!(mixed.token_accounting, TokenAccounting::EventsNotTokens); |
| 1435 | assert_eq!(mixed.usage_requests, 1); |
| 1436 | assert_eq!(mixed.output_tokens_per_sec, None); |
| 1437 | assert!(mixed.tpot.is_none()); |
| 1438 | |
| 1439 | let rec = build_record( |
| 1440 | &StreamConfig::default(), |
| 1441 | &mixed, |
| 1442 | &SourceIdentity { |
| 1443 | commit: "0".repeat(40), |
| 1444 | dirty: false, |
| 1445 | }, |
| 1446 | &BuildIdentity { |
| 1447 | profile: "debug".into(), |
| 1448 | rustc: "rustc test".into(), |
| 1449 | }, |
| 1450 | &HardwareIdentity { |
| 1451 | host: "h".into(), |
| 1452 | cpu: "c".into(), |
| 1453 | gpu: "none_detected".into(), |
| 1454 | }, |
| 1455 | &["x.samples.json".to_string()], |
| 1456 | ); |
| 1457 | assert_eq!(rec["methodology"]["token_accounting"], "events_not_tokens"); |
| 1458 | let metrics = rec["metrics"].as_object().unwrap(); |
| 1459 | assert!( |
| 1460 | metrics |
| 1461 | .keys() |
| 1462 | .all(|k| !k.contains("token") && !k.contains("tpot") && !k.contains("itl")), |
| 1463 | "no token metric under events_not_tokens: {:?}", |
| 1464 | metrics.keys() |
| 1465 | ); |
| 1466 | assert!(metrics.contains_key("events_per_sec")); |
| 1467 | } |
| 1468 | |
| 1469 | #[test] |
| 1470 | fn percentile_rule_needs_enough_samples() { |
| 1471 | let one = distribution(&[42.0]); |
| 1472 | assert_eq!((one.samples, one.p50, one.p95), (1, Some(42.0), None)); |
| 1473 | let nineteen: Vec<f64> = (1..=19).map(f64::from).collect(); |
| 1474 | assert_eq!(distribution(&nineteen).p95, None); |
| 1475 | let twenty: Vec<f64> = (1..=20).map(f64::from).collect(); |
| 1476 | let d = distribution(&twenty); |
| 1477 | assert_eq!((d.samples, d.p50, d.p95), (20, Some(10.0), Some(19.0))); |
| 1478 | assert_eq!(distribution(&[]).p50, None); |
| 1479 | } |
| 1480 | |
| 1481 | #[test] |
| 1482 | fn single_sample_record_omits_percentiles() { |
| 1483 | let s = run_reads(&[ |
| 1484 | cat(&[HEAD_CLOSE, content("a").as_bytes()]), |
| 1485 | cat(&[content("b").as_bytes(), b"data: [DONE]\n\n"]), |
| 1486 | ]); |
| 1487 | let sum = summarize(&[s], Duration::from_millis(50)); |
| 1488 | let rec = build_record( |
| 1489 | &StreamConfig::default(), |
| 1490 | &sum, |
| 1491 | &SourceIdentity { |
| 1492 | commit: "a".repeat(40), |
| 1493 | dirty: true, |
| 1494 | }, |
| 1495 | &build_identity(), |
| 1496 | &hardware_identity(), |
| 1497 | &["x.samples.json".to_string()], |
| 1498 | ); |
| 1499 | assert_eq!(rec["schema"], RECORD_SCHEMA); |
| 1500 | assert_eq!(rec["status"], "EXPERIMENTAL"); |
| 1501 | assert_eq!(rec["methodology"]["samples"], 1); |
| 1502 | // one observation: the record omits p50 (contract: a p50 needs 2) and says so |
| 1503 | assert!(rec["metrics"].get("ttft_ms_p50").is_none()); |
| 1504 | assert!(rec["limitations"] |
| 1505 | .as_array() |
| 1506 | .unwrap() |
| 1507 | .iter() |
| 1508 | .any(|l| l.as_str().unwrap().contains("p50 values are omitted"))); |
| 1509 | assert_eq!(rec["metrics"]["ttft_ms_samples"], 1); |
| 1510 | assert!(rec["metrics"].get("ttft_ms_p95").is_none()); |
| 1511 | assert_eq!(rec["backend"]["model"], "atlas-lightning-omni"); |
| 1512 | assert_eq!(rec["backend"]["precision"], "unlabeled"); |
| 1513 | assert_eq!( |
| 1514 | rec["backend"]["endpoint"], |
| 1515 | "127.0.0.1:18006/v1/chat/completions" |
| 1516 | ); |
| 1517 | for key in [ |
| 1518 | "source", |
| 1519 | "build", |
| 1520 | "workload", |
| 1521 | "hardware", |
| 1522 | "evidence", |
| 1523 | "limitations", |
| 1524 | ] { |
| 1525 | assert!(rec.get(key).is_some(), "missing {}", key); |
| 1526 | } |
| 1527 | } |
| 1528 | |
| 1529 | /// DRA-166: the record binds warmup, tolerance and a NOT_RUN parity with its limitation; it |
| 1530 | /// meets the binding contract only when both digests were supplied. |
| 1531 | #[test] |
| 1532 | fn record_binding_needs_both_digests() { |
| 1533 | let s = run_reads(&[ |
| 1534 | cat(&[HEAD_CLOSE, content("a").as_bytes()]), |
| 1535 | cat(&[content("b").as_bytes(), b"data: [DONE]\n\n"]), |
| 1536 | ]); |
| 1537 | let sum = summarize(&[s], Duration::from_millis(50)); |
| 1538 | let binding = |cfg: &StreamConfig| -> Vec<String> { |
| 1539 | let rec = build_record( |
| 1540 | cfg, |
| 1541 | &sum, |
| 1542 | &SourceIdentity { |
| 1543 | commit: "a".repeat(40), |
| 1544 | dirty: true, |
| 1545 | }, |
| 1546 | &build_identity(), |
| 1547 | &hardware_identity(), |
| 1548 | &["Cargo.toml".to_string()], |
| 1549 | ); |
| 1550 | assert_eq!(rec["methodology"]["warmup"], cfg.warmup); |
| 1551 | assert_eq!(rec["parity"]["verdict"], "NOT_RUN"); |
| 1552 | let mut out = Vec::new(); |
| 1553 | crate::evidence::check_record( |
| 1554 | Path::new(env!("CARGO_MANIFEST_DIR")), |
| 1555 | "r.json", |
| 1556 | &rec, |
| 1557 | &mut out, |
| 1558 | ); |
| 1559 | out.iter() |
| 1560 | .filter(|d| { |
| 1561 | d.field.starts_with("backend.binary") |
| 1562 | || d.field.starts_with("backend.model") |
| 1563 | || d.field.starts_with("parity") |
| 1564 | || d.field == "methodology.warmup" |
| 1565 | || d.field == "methodology.tolerance" |
| 1566 | }) |
| 1567 | .map(|d| d.to_string()) |
| 1568 | .collect() |
| 1569 | }; |
| 1570 | let missing = "missing (a claimed result names the sha256 of what was measured)"; |
| 1571 | assert_eq!( |
| 1572 | binding(&StreamConfig::default()), |
| 1573 | vec![ |
| 1574 | format!("r.json: backend.binary_sha256: {missing}"), |
| 1575 | format!("r.json: backend.model_sha256: {missing}"), |
| 1576 | ] |
| 1577 | ); |
| 1578 | let cfg = StreamConfig { |
| 1579 | binary_sha256: Some("c".repeat(64)), |
| 1580 | model_sha256: Some("d".repeat(64)), |
| 1581 | warmup: 3, |
| 1582 | ..StreamConfig::default() |
| 1583 | }; |
| 1584 | assert_eq!(binding(&cfg), Vec::<String>::new()); |
| 1585 | let short = StreamConfig { |
| 1586 | binary_sha256: Some("c".repeat(63)), |
| 1587 | ..cfg.clone() |
| 1588 | }; |
| 1589 | assert_eq!( |
| 1590 | binding(&short), |
| 1591 | vec![format!( |
| 1592 | "r.json: backend.binary_sha256: \"{}\" is not a 64-character lowercase hex sha256", |
| 1593 | "c".repeat(63) |
| 1594 | )] |
| 1595 | ); |
| 1596 | } |
| 1597 | |
| 1598 | #[test] |
| 1599 | fn file_sha256_hashes_bytes() { |
| 1600 | let p = Path::new(env!("CARGO_MANIFEST_DIR")) |
| 1601 | .join("tests/fixtures/records/good/evidence/parity_tokens.txt"); |
| 1602 | assert_eq!( |
| 1603 | file_sha256(&p).unwrap(), |
| 1604 | "94a2668d9e83872b4918ba6f6c4222a110991eb0db58c5c9a0cdc68ad2dcbed8" |
| 1605 | ); |
| 1606 | assert!(file_sha256(Path::new("/nonexistent/aien-bench")).is_err()); |
| 1607 | } |
| 1608 | |
| 1609 | #[test] |
| 1610 | fn file_sha256_of_a_directory_is_its_sorted_manifest() { |
| 1611 | let d = std::env::temp_dir().join(format!("bench-model-dir-{}", std::process::id())); |
| 1612 | let _ = std::fs::remove_dir_all(&d); |
| 1613 | std::fs::create_dir_all(d.join("sub")).unwrap(); |
| 1614 | std::fs::write(d.join("b.safetensors"), b"bb").unwrap(); |
| 1615 | std::fs::write(d.join("sub/a.json"), b"a").unwrap(); |
| 1616 | let got = file_sha256(&d).unwrap(); |
| 1617 | let manifest = format!( |
| 1618 | "{} b.safetensors\n{} sub/a.json\n", |
| 1619 | hex_digest(b"bb"), |
| 1620 | hex_digest(b"a") |
| 1621 | ); |
| 1622 | assert_eq!(got, hex_digest(manifest.as_bytes())); |
| 1623 | std::fs::write(d.join("sub/a.json"), b"A").unwrap(); |
| 1624 | assert_ne!(file_sha256(&d).unwrap(), got); |
| 1625 | std::fs::remove_dir_all(&d).unwrap(); |
| 1626 | let empty = std::env::temp_dir().join(format!("bench-empty-dir-{}", std::process::id())); |
| 1627 | std::fs::create_dir_all(&empty).unwrap(); |
| 1628 | assert!(file_sha256(&empty).is_err()); |
| 1629 | std::fs::remove_dir_all(&empty).unwrap(); |
| 1630 | } |
| 1631 | |
| 1632 | #[cfg(unix)] |
| 1633 | #[test] |
| 1634 | fn file_sha256_refuses_a_symlink_cycle() { |
| 1635 | let d = std::env::temp_dir().join(format!("bench-cycle-dir-{}", std::process::id())); |
| 1636 | let _ = std::fs::remove_dir_all(&d); |
| 1637 | std::fs::create_dir_all(d.join("sub")).unwrap(); |
| 1638 | std::fs::write(d.join("sub/a.json"), b"a").unwrap(); |
| 1639 | std::os::unix::fs::symlink("..", d.join("sub/up")).unwrap(); |
| 1640 | let err = file_sha256(&d).unwrap_err(); |
| 1641 | assert!(err.contains("symlink cycle"), "{err}"); |
| 1642 | // A symlink to a sibling directory that is not an ancestor is followed, not refused. |
| 1643 | std::fs::remove_file(d.join("sub/up")).unwrap(); |
| 1644 | std::fs::create_dir_all(d.join("other")).unwrap(); |
| 1645 | std::fs::write(d.join("other/b.json"), b"b").unwrap(); |
| 1646 | std::os::unix::fs::symlink("../other", d.join("sub/link")).unwrap(); |
| 1647 | let manifest = format!( |
| 1648 | "{} other/b.json\n{} sub/a.json\n{} sub/link/b.json\n", |
| 1649 | hex_digest(b"b"), |
| 1650 | hex_digest(b"a"), |
| 1651 | hex_digest(b"b") |
| 1652 | ); |
| 1653 | assert_eq!(file_sha256(&d).unwrap(), hex_digest(manifest.as_bytes())); |
| 1654 | std::fs::remove_dir_all(&d).unwrap(); |
| 1655 | } |
| 1656 | |
| 1657 | #[test] |
| 1658 | fn request_body_escapes_prompt_and_asks_for_usage() { |
| 1659 | let cfg = StreamConfig { |
| 1660 | prompt: "say \"hi\"\nnow".into(), |
| 1661 | ..StreamConfig::default() |
| 1662 | }; |
| 1663 | let v: Value = serde_json::from_str(&cfg.request_body()).unwrap(); |
| 1664 | assert_eq!(v["messages"][0]["content"], "say \"hi\"\nnow"); |
| 1665 | assert_eq!(v["stream"], true); |
| 1666 | assert_eq!(v["stream_options"]["include_usage"], true); |
| 1667 | } |
| 1668 | |
| 1669 | /// Loopback fake server: answers each connection with `script` (pieces written with a |
| 1670 | /// pause between them), then closes. |
| 1671 | fn fake_server( |
| 1672 | connections: usize, |
| 1673 | script: Vec<Vec<u8>>, |
| 1674 | pause: Duration, |
| 1675 | ) -> (u16, std::thread::JoinHandle<Vec<String>>) { |
| 1676 | let listener = TcpListener::bind("127.0.0.1:0").unwrap(); |
| 1677 | let port = listener.local_addr().unwrap().port(); |
| 1678 | let handle = std::thread::spawn(move || { |
| 1679 | let mut bodies = Vec::new(); |
| 1680 | for _ in 0..connections { |
| 1681 | let (mut sock, _) = listener.accept().unwrap(); |
| 1682 | let mut reader = std::io::BufReader::new(sock.try_clone().unwrap()); |
| 1683 | let mut len = 0usize; |
| 1684 | loop { |
| 1685 | let mut line = String::new(); |
| 1686 | reader.read_line(&mut line).unwrap(); |
| 1687 | if let Some(v) = line.to_ascii_lowercase().strip_prefix("content-length:") { |
| 1688 | len = v.trim().parse().unwrap(); |
| 1689 | } |
| 1690 | if line == "\r\n" || line.is_empty() { |
| 1691 | break; |
| 1692 | } |
| 1693 | } |
| 1694 | let mut body = vec![0u8; len]; |
| 1695 | reader.read_exact(&mut body).unwrap(); |
| 1696 | bodies.push(String::from_utf8(body).unwrap()); |
| 1697 | for piece in &script { |
| 1698 | if sock.write_all(piece).is_err() { |
| 1699 | break; |
| 1700 | } |
| 1701 | let _ = sock.flush(); |
| 1702 | std::thread::sleep(pause); |
| 1703 | } |
| 1704 | } |
| 1705 | bodies |
| 1706 | }); |
| 1707 | (port, handle) |
| 1708 | } |
| 1709 | |
| 1710 | #[test] |
| 1711 | fn end_to_end_over_loopback_with_concurrency() { |
| 1712 | let usage = "data: {\"choices\":[],\"usage\":{\"completion_tokens\":3}}\n\n"; |
| 1713 | let script = vec![ |
| 1714 | HEAD_CHUNKED.to_vec(), |
| 1715 | chunk(&content("a")), |
| 1716 | chunk(&content("b")), |
| 1717 | chunk(&format!("{}{}data: [DONE]\n\n", content("c"), usage)), |
| 1718 | b"0\r\n\r\n".to_vec(), |
| 1719 | ]; |
| 1720 | let (port, server) = fake_server(3, script, Duration::from_millis(5)); |
| 1721 | let cfg = StreamConfig { |
| 1722 | port, |
| 1723 | requests: 2, |
| 1724 | concurrency: 2, |
| 1725 | warmup: 1, |
| 1726 | model: "fake-model".into(), |
| 1727 | engine: "fake-engine".into(), |
| 1728 | ..StreamConfig::default() |
| 1729 | }; |
| 1730 | let run = run_stream_benchmark(&cfg); |
| 1731 | let bodies = server.join().unwrap(); |
| 1732 | assert_eq!(bodies.len(), 3); |
| 1733 | assert!(bodies |
| 1734 | .iter() |
| 1735 | .all(|b| b.contains("\"model\":\"fake-model\""))); |
| 1736 | assert_eq!(run.warmup.len(), 1); |
| 1737 | assert_eq!(run.samples.len(), 2); |
| 1738 | for s in &run.samples { |
| 1739 | assert_eq!(s.outcome, Outcome::Complete, "{:?}", s.detail); |
| 1740 | assert_eq!(s.content_events, 3); |
| 1741 | assert!(s.first_content_ms.unwrap() <= s.completion_ms.unwrap()); |
| 1742 | } |
| 1743 | let sum = summarize(&run.samples, run.wall); |
| 1744 | assert_eq!(sum.requests_ok, 2); |
| 1745 | assert_eq!(sum.token_accounting, TokenAccounting::BackendUsage); |
| 1746 | assert_eq!(sum.ttft.samples, 2); |
| 1747 | assert!(sum.ttft.p95.is_none()); |
| 1748 | |
| 1749 | let dir = std::env::temp_dir().join(format!("aien-bench-p0-{}", std::process::id())); |
| 1750 | let path = write_run( |
| 1751 | &dir, |
| 1752 | Path::new("./records"), |
| 1753 | &cfg, |
| 1754 | &run, |
| 1755 | &sum, |
| 1756 | &SourceIdentity { |
| 1757 | commit: "b".repeat(40), |
| 1758 | dirty: false, |
| 1759 | }, |
| 1760 | ) |
| 1761 | .unwrap(); |
| 1762 | let rec: Value = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap(); |
| 1763 | let evidence = rec["evidence"][0].as_str().unwrap(); |
| 1764 | assert!(evidence.starts_with("records/llm_streaming-"), "{evidence}"); |
| 1765 | assert!(dir.join(evidence).is_file()); |
| 1766 | assert_eq!(path, dir.join("records").join(path.file_name().unwrap())); |
| 1767 | assert_eq!(rec["backend"]["engine"], "fake-engine"); |
| 1768 | std::fs::remove_dir_all(&dir).unwrap(); |
| 1769 | } |
| 1770 | |
| 1771 | #[test] |
| 1772 | fn loopback_http_500_and_stall_and_refused() { |
| 1773 | let (port, server) = fake_server( |
| 1774 | 1, |
| 1775 | vec![b"HTTP/1.1 503 Service Unavailable\r\nContent-Length: 4\r\n\r\nbusy".to_vec()], |
| 1776 | Duration::from_millis(1), |
| 1777 | ); |
| 1778 | let cfg = StreamConfig { |
| 1779 | port, |
| 1780 | ..StreamConfig::default() |
| 1781 | }; |
| 1782 | let s = measure_one(&cfg, 0); |
| 1783 | server.join().unwrap(); |
| 1784 | assert_eq!(s.outcome, Outcome::HttpStatus); |
| 1785 | assert_eq!(s.error_body.as_deref(), Some("busy")); |
| 1786 | |
| 1787 | // Head and one event, then silence longer than the read timeout. |
| 1788 | let (port, server) = fake_server( |
| 1789 | 1, |
| 1790 | vec![cat(&[HEAD_CLOSE, content("a").as_bytes()])], |
| 1791 | Duration::from_millis(600), |
| 1792 | ); |
| 1793 | let cfg = StreamConfig { |
| 1794 | port, |
| 1795 | read_timeout: Duration::from_millis(150), |
| 1796 | ..StreamConfig::default() |
| 1797 | }; |
| 1798 | let s = measure_one(&cfg, 0); |
| 1799 | server.join().unwrap(); |
| 1800 | assert_eq!(s.outcome, Outcome::ReadTimeout, "{:?}", s.detail); |
| 1801 | assert_eq!(s.content_events, 1); |
| 1802 | |
| 1803 | let port = { |
| 1804 | let l = TcpListener::bind("127.0.0.1:0").unwrap(); |
| 1805 | l.local_addr().unwrap().port() |
| 1806 | }; |
| 1807 | let cfg = StreamConfig { |
| 1808 | port, |
| 1809 | ..StreamConfig::default() |
| 1810 | }; |
| 1811 | assert_eq!(measure_one(&cfg, 0).outcome, Outcome::ConnectError); |
| 1812 | } |
| 1813 | } |