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-kv-bench / src / report.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 | //! The benchmark's output contract (CUTS.md C9, schema B6; ADR 0003 sections |
| 17 | //! 10, 15.1 and 16.5). |
| 18 | //! |
| 19 | //! Every row carries a mode, a platform and a `cache_state` label. A row is |
| 20 | //! either `OK` (measured, every metric present) or `NOT_RUN` (a reason and no |
| 21 | //! numbers). Latency summaries never mix cache states. Every report carries |
| 22 | //! the native physical rows as `NOT_RUN` (B8): a host run cannot speak for |
| 23 | //! native hardware. |
| 24 | |
| 25 | use serde::{Deserialize, Serialize}; |
| 26 | use sha2::{Digest, Sha256}; |
| 27 | use std::collections::BTreeMap; |
| 28 | use std::fmt; |
| 29 | |
| 30 | /// Version tag of the JSON this module writes. |
| 31 | pub const SCHEMA: &str = "aien.pkv.bench.v1"; |
| 32 | |
| 33 | /// The `cache_state` labels (ADR 15.1). `none`: the mode reads nothing from |
| 34 | /// the store; `page_cache`: objects were written moments before the read and |
| 35 | /// no cache drop happened; `device`: residency verified as zero before the |
| 36 | /// read; `unknown`: not verified either way. |
| 37 | pub const CACHE_STATES: [&str; 4] = ["none", "page_cache", "device", "unknown"]; |
| 38 | |
| 39 | /// Platform labels of ADR 16.5. Only `hosted` may carry numbers in a host run. |
| 40 | pub const HOSTED: &str = "hosted"; |
| 41 | pub const PLATFORMS: [&str; 4] = [ |
| 42 | HOSTED, |
| 43 | "native_emulator", |
| 44 | "native physical (Pi 5)", |
| 45 | "native_physical", |
| 46 | ]; |
| 47 | |
| 48 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] |
| 49 | pub enum RowStatus { |
| 50 | #[serde(rename = "OK")] |
| 51 | Ok, |
| 52 | #[serde(rename = "NOT_RUN")] |
| 53 | NotRun, |
| 54 | } |
| 55 | |
| 56 | #[derive(Debug, Clone, PartialEq)] |
| 57 | pub enum BenchError { |
| 58 | MissingLabel { label: &'static str, mode: String }, |
| 59 | BadLabel { label: &'static str, value: String }, |
| 60 | MissingField { field: &'static str, mode: String }, |
| 61 | Inconsistent { mode: String, what: String }, |
| 62 | MixedCacheState { first: String, other: String }, |
| 63 | NothingToSummarize, |
| 64 | MissingNotRun { platform: String }, |
| 65 | } |
| 66 | |
| 67 | impl fmt::Display for BenchError { |
| 68 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 69 | match self { |
| 70 | BenchError::MissingLabel { label, mode } => { |
| 71 | write!(f, "row {mode:?} has no {label} label") |
| 72 | } |
| 73 | BenchError::BadLabel { label, value } => write!(f, "unknown {label} label {value:?}"), |
| 74 | BenchError::MissingField { field, mode } => { |
| 75 | write!(f, "row {mode:?} reports no {field}") |
| 76 | } |
| 77 | BenchError::Inconsistent { mode, what } => write!(f, "row {mode:?}: {what}"), |
| 78 | BenchError::MixedCacheState { first, other } => write!( |
| 79 | f, |
| 80 | "refusing to summarize cache_state {first:?} together with {other:?}" |
| 81 | ), |
| 82 | BenchError::NothingToSummarize => write!(f, "no measured row to summarize"), |
| 83 | BenchError::MissingNotRun { platform } => { |
| 84 | write!(f, "report has no NOT_RUN row for {platform}") |
| 85 | } |
| 86 | } |
| 87 | } |
| 88 | } |
| 89 | |
| 90 | impl std::error::Error for BenchError {} |
| 91 | |
| 92 | /// One mode at one concurrency and prompt length, or one NOT_RUN entry. |
| 93 | #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] |
| 94 | pub struct Row { |
| 95 | pub mode: String, |
| 96 | pub status: RowStatus, |
| 97 | pub reason: Option<String>, |
| 98 | pub platform: String, |
| 99 | pub cache_state: Option<String>, |
| 100 | pub concurrency: Option<u32>, |
| 101 | pub prompt_tokens: Option<u32>, |
| 102 | /// `second_turn` (the measured request continues a conversation) or |
| 103 | /// `single_turn` (resident-only: one request, nothing leaves memory). |
| 104 | pub workload: Option<String>, |
| 105 | /// Store I/O operations the storage worker may have dispatched at once |
| 106 | /// (`WorkerConfig::dispatch_depth`); 0 when the mode uses no store. |
| 107 | pub queue_depth: Option<u32>, |
| 108 | pub completed_requests: Option<u64>, |
| 109 | pub failed_requests: Option<u64>, |
| 110 | /// Request latency, submit to the finish event (microseconds). |
| 111 | pub p50_us: Option<u64>, |
| 112 | pub p95_us: Option<u64>, |
| 113 | /// Submit to the first generated token. |
| 114 | pub ttft_p50_us: Option<u64>, |
| 115 | pub ttft_p95_us: Option<u64>, |
| 116 | /// Tokens after each request's first, over the decode window. |
| 117 | pub decode_tokens_per_s: Option<f64>, |
| 118 | /// `kv_pool_allocated_bytes` (constant after start, ADR 10). |
| 119 | pub peak_allocated_bytes: Option<u64>, |
| 120 | /// Peak `kv_pool_holder_blocks` times the block stride. Holders are pool |
| 121 | /// blocks, so this is inside `peak_allocated_bytes`, never added to it. |
| 122 | pub peak_holder_bytes: Option<u64>, |
| 123 | /// `kv_host_tail_scratch_bytes` for store modes (ADR 10), else 0. |
| 124 | pub peak_staging_bytes: Option<u64>, |
| 125 | /// `VmHWM` after a reset at the start of the row. |
| 126 | pub peak_rss_bytes: Option<u64>, |
| 127 | /// Prefix tokens restored from the store over the measured requests. |
| 128 | pub restored_tokens: Option<u64>, |
| 129 | pub latency_samples_us: Vec<u64>, |
| 130 | pub ttft_samples_us: Vec<u64>, |
| 131 | } |
| 132 | |
| 133 | impl Row { |
| 134 | /// An empty measured row; the harness fills the metrics. |
| 135 | pub fn new_ok( |
| 136 | mode: &str, |
| 137 | platform: &str, |
| 138 | cache_state: &str, |
| 139 | concurrency: u32, |
| 140 | prompt_tokens: u32, |
| 141 | workload: &str, |
| 142 | ) -> Self { |
| 143 | Self { |
| 144 | mode: mode.to_string(), |
| 145 | status: RowStatus::Ok, |
| 146 | reason: None, |
| 147 | platform: platform.to_string(), |
| 148 | cache_state: Some(cache_state.to_string()), |
| 149 | concurrency: Some(concurrency), |
| 150 | prompt_tokens: Some(prompt_tokens), |
| 151 | workload: Some(workload.to_string()), |
| 152 | queue_depth: None, |
| 153 | completed_requests: None, |
| 154 | failed_requests: None, |
| 155 | p50_us: None, |
| 156 | p95_us: None, |
| 157 | ttft_p50_us: None, |
| 158 | ttft_p95_us: None, |
| 159 | decode_tokens_per_s: None, |
| 160 | peak_allocated_bytes: None, |
| 161 | peak_holder_bytes: None, |
| 162 | peak_staging_bytes: None, |
| 163 | peak_rss_bytes: None, |
| 164 | restored_tokens: None, |
| 165 | latency_samples_us: Vec::new(), |
| 166 | ttft_samples_us: Vec::new(), |
| 167 | } |
| 168 | } |
| 169 | |
| 170 | /// A row that was not run, with the reason and no numbers. |
| 171 | pub fn not_run(mode: &str, platform: &str, cache_state: &str, reason: &str) -> Self { |
| 172 | let mut row = Self::new_ok(mode, platform, cache_state, 0, 0, "none"); |
| 173 | row.status = RowStatus::NotRun; |
| 174 | row.reason = Some(reason.to_string()); |
| 175 | row.concurrency = None; |
| 176 | row.prompt_tokens = None; |
| 177 | row.workload = None; |
| 178 | row |
| 179 | } |
| 180 | |
| 181 | /// Sets the four percentiles from the raw samples (nearest rank). |
| 182 | pub fn fill_percentiles(&mut self) { |
| 183 | self.p50_us = percentile(&self.latency_samples_us, 50); |
| 184 | self.p95_us = percentile(&self.latency_samples_us, 95); |
| 185 | self.ttft_p50_us = percentile(&self.ttft_samples_us, 50); |
| 186 | self.ttft_p95_us = percentile(&self.ttft_samples_us, 95); |
| 187 | } |
| 188 | |
| 189 | fn metric_fields(&self) -> [(&'static str, bool); 13] { |
| 190 | [ |
| 191 | ("completed_requests", self.completed_requests.is_some()), |
| 192 | ("failed_requests", self.failed_requests.is_some()), |
| 193 | ("p50_us", self.p50_us.is_some()), |
| 194 | ("p95_us", self.p95_us.is_some()), |
| 195 | ("ttft_p50_us", self.ttft_p50_us.is_some()), |
| 196 | ("ttft_p95_us", self.ttft_p95_us.is_some()), |
| 197 | ("decode_tokens_per_s", self.decode_tokens_per_s.is_some()), |
| 198 | ("peak_allocated_bytes", self.peak_allocated_bytes.is_some()), |
| 199 | ("peak_holder_bytes", self.peak_holder_bytes.is_some()), |
| 200 | ("peak_staging_bytes", self.peak_staging_bytes.is_some()), |
| 201 | ("peak_rss_bytes", self.peak_rss_bytes.is_some()), |
| 202 | ("queue_depth", self.queue_depth.is_some()), |
| 203 | ("restored_tokens", self.restored_tokens.is_some()), |
| 204 | ] |
| 205 | } |
| 206 | |
| 207 | /// Refuses a row without its labels, a measured row missing any metric, |
| 208 | /// and a NOT_RUN row that carries numbers or no reason. |
| 209 | pub fn check(&self) -> Result<(), BenchError> { |
| 210 | let mode = self.mode.clone(); |
| 211 | if self.mode.trim().is_empty() { |
| 212 | return Err(BenchError::MissingLabel { |
| 213 | label: "mode", |
| 214 | mode, |
| 215 | }); |
| 216 | } |
| 217 | if self.platform.trim().is_empty() { |
| 218 | return Err(BenchError::MissingLabel { |
| 219 | label: "platform", |
| 220 | mode, |
| 221 | }); |
| 222 | } |
| 223 | if !PLATFORMS.contains(&self.platform.as_str()) { |
| 224 | return Err(BenchError::BadLabel { |
| 225 | label: "platform", |
| 226 | value: self.platform.clone(), |
| 227 | }); |
| 228 | } |
| 229 | let Some(cache) = self.cache_state.as_deref().filter(|c| !c.is_empty()) else { |
| 230 | return Err(BenchError::MissingLabel { |
| 231 | label: "cache_state", |
| 232 | mode, |
| 233 | }); |
| 234 | }; |
| 235 | if !CACHE_STATES.contains(&cache) { |
| 236 | return Err(BenchError::BadLabel { |
| 237 | label: "cache_state", |
| 238 | value: cache.to_string(), |
| 239 | }); |
| 240 | } |
| 241 | match self.status { |
| 242 | RowStatus::NotRun => { |
| 243 | if self.reason.as_deref().is_none_or(|r| r.trim().is_empty()) { |
| 244 | return Err(BenchError::MissingField { |
| 245 | field: "reason", |
| 246 | mode, |
| 247 | }); |
| 248 | } |
| 249 | if let Some((field, _)) = self.metric_fields().iter().find(|(_, set)| *set) { |
| 250 | return Err(BenchError::Inconsistent { |
| 251 | mode, |
| 252 | what: format!("NOT_RUN row carries {field}"), |
| 253 | }); |
| 254 | } |
| 255 | if !self.latency_samples_us.is_empty() || !self.ttft_samples_us.is_empty() { |
| 256 | return Err(BenchError::Inconsistent { |
| 257 | mode, |
| 258 | what: "NOT_RUN row carries samples".into(), |
| 259 | }); |
| 260 | } |
| 261 | Ok(()) |
| 262 | } |
| 263 | RowStatus::Ok => { |
| 264 | for (field, label) in [ |
| 265 | ("concurrency", self.concurrency.is_some()), |
| 266 | ("prompt_tokens", self.prompt_tokens.is_some()), |
| 267 | ("workload", self.workload.is_some()), |
| 268 | ] { |
| 269 | if !label { |
| 270 | return Err(BenchError::MissingField { field, mode }); |
| 271 | } |
| 272 | } |
| 273 | if let Some((field, _)) = self.metric_fields().iter().find(|(_, set)| !*set) { |
| 274 | return Err(BenchError::MissingField { field, mode }); |
| 275 | } |
| 276 | let completed = self.completed_requests.unwrap_or(0); |
| 277 | if completed == 0 { |
| 278 | return Err(BenchError::Inconsistent { |
| 279 | mode, |
| 280 | what: "zero completed requests".into(), |
| 281 | }); |
| 282 | } |
| 283 | if self.latency_samples_us.len() as u64 != completed |
| 284 | || self.ttft_samples_us.len() as u64 != completed |
| 285 | { |
| 286 | return Err(BenchError::Inconsistent { |
| 287 | mode, |
| 288 | what: format!( |
| 289 | "{} latency and {} ttft samples for {completed} completed requests", |
| 290 | self.latency_samples_us.len(), |
| 291 | self.ttft_samples_us.len() |
| 292 | ), |
| 293 | }); |
| 294 | } |
| 295 | let want = ( |
| 296 | percentile(&self.latency_samples_us, 50), |
| 297 | percentile(&self.latency_samples_us, 95), |
| 298 | percentile(&self.ttft_samples_us, 50), |
| 299 | percentile(&self.ttft_samples_us, 95), |
| 300 | ); |
| 301 | let have = (self.p50_us, self.p95_us, self.ttft_p50_us, self.ttft_p95_us); |
| 302 | if want != have { |
| 303 | return Err(BenchError::Inconsistent { |
| 304 | mode, |
| 305 | what: format!("percentiles {have:?} do not match the samples {want:?}"), |
| 306 | }); |
| 307 | } |
| 308 | if self.peak_allocated_bytes == Some(0) || self.peak_rss_bytes == Some(0) { |
| 309 | return Err(BenchError::Inconsistent { |
| 310 | mode, |
| 311 | what: "a zero allocation or RSS peak is not a measurement".into(), |
| 312 | }); |
| 313 | } |
| 314 | Ok(()) |
| 315 | } |
| 316 | } |
| 317 | } |
| 318 | } |
| 319 | |
| 320 | /// Nearest-rank percentile: the smallest sample with at least `p` percent of |
| 321 | /// the samples at or below it. `None` for no samples. |
| 322 | pub fn percentile(samples: &[u64], p: u32) -> Option<u64> { |
| 323 | if samples.is_empty() { |
| 324 | return None; |
| 325 | } |
| 326 | let mut sorted = samples.to_vec(); |
| 327 | sorted.sort_unstable(); |
| 328 | let n = sorted.len() as u64; |
| 329 | let rank = (u64::from(p) * n).div_ceil(100).max(1); |
| 330 | Some(sorted[(rank - 1) as usize]) |
| 331 | } |
| 332 | |
| 333 | /// A latency summary over rows that share one cache state. |
| 334 | #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] |
| 335 | pub struct Summary { |
| 336 | pub cache_state: String, |
| 337 | pub samples: usize, |
| 338 | pub p50_us: u64, |
| 339 | pub p95_us: u64, |
| 340 | } |
| 341 | |
| 342 | /// Pools the request-latency samples of `rows`. Refuses NOT_RUN or invalid |
| 343 | /// rows and any mix of cache states (ADR 15.1: page-cache hits and device |
| 344 | /// reads are never averaged together). |
| 345 | pub fn summarize(rows: &[&Row]) -> Result<Summary, BenchError> { |
| 346 | let mut cache: Option<&str> = None; |
| 347 | let mut samples = Vec::new(); |
| 348 | for row in rows { |
| 349 | row.check()?; |
| 350 | if row.status != RowStatus::Ok { |
| 351 | return Err(BenchError::NothingToSummarize); |
| 352 | } |
| 353 | let c = row.cache_state.as_deref().unwrap_or_default(); |
| 354 | match cache { |
| 355 | None => cache = Some(c), |
| 356 | Some(first) if first != c => { |
| 357 | return Err(BenchError::MixedCacheState { |
| 358 | first: first.to_string(), |
| 359 | other: c.to_string(), |
| 360 | }) |
| 361 | } |
| 362 | Some(_) => {} |
| 363 | } |
| 364 | samples.extend_from_slice(&row.latency_samples_us); |
| 365 | } |
| 366 | let (Some(cache), Some(p50), Some(p95)) = |
| 367 | (cache, percentile(&samples, 50), percentile(&samples, 95)) |
| 368 | else { |
| 369 | return Err(BenchError::NothingToSummarize); |
| 370 | }; |
| 371 | Ok(Summary { |
| 372 | cache_state: cache.to_string(), |
| 373 | samples: samples.len(), |
| 374 | p50_us: p50, |
| 375 | p95_us: p95, |
| 376 | }) |
| 377 | } |
| 378 | |
| 379 | /// The rows every report carries as NOT_RUN (B8, ADR 11 and 16.5). |
| 380 | pub fn required_not_run_rows() -> Vec<Row> { |
| 381 | vec![ |
| 382 | Row::not_run( |
| 383 | "native-physical", |
| 384 | "native_physical", |
| 385 | "device", |
| 386 | "Spark-native physical run is blocked on aienos#336 (not authorized); a host run cannot stand in for it", |
| 387 | ), |
| 388 | Row::not_run( |
| 389 | "native-physical", |
| 390 | "native physical (Pi 5)", |
| 391 | "device", |
| 392 | "Pi 5 physical lane is cut P3 (ADR 16), needs Drake's authorization and a free Pi; not run", |
| 393 | ), |
| 394 | ] |
| 395 | } |
| 396 | |
| 397 | #[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] |
| 398 | pub struct Machine { |
| 399 | pub hostname: String, |
| 400 | pub kernel: String, |
| 401 | pub arch: String, |
| 402 | pub cpu_model: String, |
| 403 | pub cpus: usize, |
| 404 | /// The process nice value during the run. |
| 405 | pub nice: i64, |
| 406 | } |
| 407 | |
| 408 | #[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] |
| 409 | pub struct Workload { |
| 410 | pub concurrency: Vec<u32>, |
| 411 | pub prompt_tokens: Vec<u32>, |
| 412 | pub rounds: u32, |
| 413 | pub turn1_max_tokens: u32, |
| 414 | pub turn2_suffix_tokens: u32, |
| 415 | pub turn2_max_tokens: u32, |
| 416 | pub block_size: u32, |
| 417 | pub chunk_blocks: u32, |
| 418 | pub dispatch_depth: u32, |
| 419 | } |
| 420 | |
| 421 | /// Provenance of one run (docs/plans/public-surface-cleanup.md bar: commit, |
| 422 | /// machine, exact command, raw samples, digest, definitions). |
| 423 | #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] |
| 424 | pub struct ReportMeta { |
| 425 | pub measurement_id: String, |
| 426 | pub git_sha: String, |
| 427 | pub git_dirty: bool, |
| 428 | pub command: String, |
| 429 | pub started_utc: String, |
| 430 | pub platform: String, |
| 431 | pub machine: Machine, |
| 432 | pub backend: String, |
| 433 | pub model: String, |
| 434 | pub workload: Workload, |
| 435 | } |
| 436 | |
| 437 | #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] |
| 438 | pub struct Report { |
| 439 | pub schema: String, |
| 440 | #[serde(flatten)] |
| 441 | pub meta: ReportMeta, |
| 442 | pub definitions: BTreeMap<String, String>, |
| 443 | pub rows: Vec<Row>, |
| 444 | /// sha256 of the JSON array of every row's (mode, concurrency, |
| 445 | /// prompt_tokens, latency samples, ttft samples), in row order. |
| 446 | pub samples_sha256: String, |
| 447 | } |
| 448 | |
| 449 | /// The measurement definitions written into every report. |
| 450 | pub fn definitions() -> BTreeMap<String, String> { |
| 451 | [ |
| 452 | ("p50_us/p95_us", "request latency: submit_work call to the step that emitted the Finished event; nearest-rank percentiles over every measured request of the row"), |
| 453 | ("ttft_p50_us/ttft_p95_us", "submit_work call to the end of the step that emitted the request's first token"), |
| 454 | ("decode_tokens_per_s", "sum over requests of (tokens - 1) divided by the summed per-round window from the earliest first token to the last finish"), |
| 455 | ("peak_allocated_bytes", "kv_pool_allocated_bytes: the KV pool allocation, constant after start (ADR 0003 section 10)"), |
| 456 | ("peak_holder_bytes", "peak kv_pool_holder_blocks times the block stride, sampled after every step; inside the pool, not added to it"), |
| 457 | ("peak_staging_bytes", "kv_host_tail_scratch_bytes (one block stride) for modes that use the store, 0 otherwise; buffered reads use the page cache, reported as cache_state"), |
| 458 | ("peak_rss_bytes", "VmHWM of the bench process after writing 5 to /proc/self/clear_refs at the start of the row"), |
| 459 | ("queue_depth", "store I/O operations the storage worker may dispatch at once (WorkerConfig.dispatch_depth); 0 when the mode uses no store"), |
| 460 | ("resident-only", "single_turn: one request per conversation (prompt, turn2_max_tokens), store off; nothing ever leaves memory"), |
| 461 | ("cold-prefill", "second_turn: turn 1 then turn 2 = turn-1 prompt + turn-1 output + suffix, store off; turn 2 prefills everything"), |
| 462 | ("restore-from-page-cache", "second_turn with the host store on: turn 1 parks, turn 2 restores the stored prefix (objects written moments before, no cache drop) and prefills the rest; every measured request must commit a restore"), |
| 463 | ("store bounds", "restore-from-page-cache sets AIEN_KV_STORE_MAX_RESTORE_OPS and AIEN_KV_STORE_MAX_PARK_OPS to concurrency x (chunks of the longest turn + 1), never below the defaults 48 and 64 (run::store_op_bounds); the old park default of 16 refused 8 of 24 parks at 8 conversations (ADR 0003 section 18.4)"), |
| 464 | ("timing", "token and finish times are taken when the bench drains the completion channel after each spine step (step granularity)"), |
| 465 | ] |
| 466 | .into_iter() |
| 467 | .map(|(k, v)| (k.to_string(), v.to_string())) |
| 468 | .collect() |
| 469 | } |
| 470 | |
| 471 | fn samples_digest(rows: &[Row]) -> String { |
| 472 | let samples: Vec<_> = rows |
| 473 | .iter() |
| 474 | .map(|r| { |
| 475 | ( |
| 476 | &r.mode, |
| 477 | r.concurrency, |
| 478 | r.prompt_tokens, |
| 479 | &r.latency_samples_us, |
| 480 | &r.ttft_samples_us, |
| 481 | ) |
| 482 | }) |
| 483 | .collect(); |
| 484 | let bytes = serde_json::to_vec(&samples).unwrap_or_default(); |
| 485 | Sha256::digest(&bytes) |
| 486 | .iter() |
| 487 | .map(|b| format!("{b:02x}")) |
| 488 | .collect() |
| 489 | } |
| 490 | |
| 491 | /// Builds and checks a report: appends the required NOT_RUN rows, refuses any |
| 492 | /// invalid row, and refuses a measured row on a platform other than `hosted`. |
| 493 | pub fn build_report(meta: ReportMeta, mut rows: Vec<Row>) -> Result<Report, BenchError> { |
| 494 | for row in &rows { |
| 495 | row.check()?; |
| 496 | if row.status == RowStatus::Ok && row.platform != HOSTED { |
| 497 | return Err(BenchError::Inconsistent { |
| 498 | mode: row.mode.clone(), |
| 499 | what: format!( |
| 500 | "a host run cannot report measured numbers for platform {:?}", |
| 501 | row.platform |
| 502 | ), |
| 503 | }); |
| 504 | } |
| 505 | } |
| 506 | for want in required_not_run_rows() { |
| 507 | if !rows |
| 508 | .iter() |
| 509 | .any(|r| r.platform == want.platform && r.mode == want.mode) |
| 510 | { |
| 511 | rows.push(want); |
| 512 | } |
| 513 | } |
| 514 | let report = Report { |
| 515 | schema: SCHEMA.to_string(), |
| 516 | meta, |
| 517 | definitions: definitions(), |
| 518 | samples_sha256: samples_digest(&rows), |
| 519 | rows, |
| 520 | }; |
| 521 | check_report(&report)?; |
| 522 | Ok(report) |
| 523 | } |
| 524 | |
| 525 | /// Re-checks a report read back from disk: schema, rows, the NOT_RUN physical |
| 526 | /// rows and the samples digest. |
| 527 | pub fn check_report(report: &Report) -> Result<(), BenchError> { |
| 528 | if report.schema != SCHEMA { |
| 529 | return Err(BenchError::BadLabel { |
| 530 | label: "schema", |
| 531 | value: report.schema.clone(), |
| 532 | }); |
| 533 | } |
| 534 | for row in &report.rows { |
| 535 | row.check()?; |
| 536 | } |
| 537 | for want in required_not_run_rows() { |
| 538 | let ok = report.rows.iter().any(|r| { |
| 539 | r.platform == want.platform && r.mode == want.mode && r.status == RowStatus::NotRun |
| 540 | }); |
| 541 | if !ok { |
| 542 | return Err(BenchError::MissingNotRun { |
| 543 | platform: want.platform, |
| 544 | }); |
| 545 | } |
| 546 | } |
| 547 | if report.samples_sha256 != samples_digest(&report.rows) { |
| 548 | return Err(BenchError::Inconsistent { |
| 549 | mode: "report".into(), |
| 550 | what: "samples_sha256 does not match the rows".into(), |
| 551 | }); |
| 552 | } |
| 553 | Ok(()) |
| 554 | } |
| 555 | |
| 556 | fn opt<T: fmt::Display>(v: Option<T>) -> String { |
| 557 | v.map(|v| v.to_string()).unwrap_or_else(|| "-".into()) |
| 558 | } |
| 559 | |
| 560 | /// The Markdown table for BENCH.md, generated from a checked report (ADR 0001 |
| 561 | /// decision 3: no hand-edited numbers). |
| 562 | pub fn render_markdown(report: &Report) -> Result<String, BenchError> { |
| 563 | check_report(report)?; |
| 564 | let m = &report.meta; |
| 565 | let mut out = String::new(); |
| 566 | out.push_str(&format!( |
| 567 | "Measurement `{}`, commit `{}`{}, {} UTC, platform `{}`, backend `{}`, host `{}` ({}, {} CPUs, kernel {}, nice {}).\n\n", |
| 568 | m.measurement_id, |
| 569 | m.git_sha, |
| 570 | if m.git_dirty { " (dirty tree)" } else { "" }, |
| 571 | m.started_utc, |
| 572 | m.platform, |
| 573 | m.backend, |
| 574 | m.machine.hostname, |
| 575 | m.machine.arch, |
| 576 | m.machine.cpus, |
| 577 | m.machine.kernel, |
| 578 | m.machine.nice, |
| 579 | )); |
| 580 | out.push_str(&format!("Command: `{}`\n\n", m.command)); |
| 581 | out.push_str("| mode | status | cache_state | conc | prompt | done/failed | p50 us | p95 us | ttft p50 us | ttft p95 us | decode tok/s | restored tok | pool bytes | holder peak | staging | peak RSS | queue depth |\n"); |
| 582 | out.push_str("|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|\n"); |
| 583 | for r in &report.rows { |
| 584 | if r.status == RowStatus::NotRun { |
| 585 | out.push_str(&format!( |
| 586 | "| {} ({}) | NOT_RUN | {} | - | - | - | - | - | - | - | - | - | - | - | - | - | - |\n", |
| 587 | r.mode, |
| 588 | r.platform, |
| 589 | opt(r.cache_state.as_deref()), |
| 590 | )); |
| 591 | continue; |
| 592 | } |
| 593 | out.push_str(&format!( |
| 594 | "| {} | OK | {} | {} | {} | {}/{} | {} | {} | {} | {} | {} | {} | {} | {} | {} | {} | {} |\n", |
| 595 | r.mode, |
| 596 | opt(r.cache_state.as_deref()), |
| 597 | opt(r.concurrency), |
| 598 | opt(r.prompt_tokens), |
| 599 | opt(r.completed_requests), |
| 600 | opt(r.failed_requests), |
| 601 | opt(r.p50_us), |
| 602 | opt(r.p95_us), |
| 603 | opt(r.ttft_p50_us), |
| 604 | opt(r.ttft_p95_us), |
| 605 | r.decode_tokens_per_s |
| 606 | .map(|v| format!("{v:.0}")) |
| 607 | .unwrap_or_else(|| "-".into()), |
| 608 | opt(r.restored_tokens), |
| 609 | opt(r.peak_allocated_bytes), |
| 610 | opt(r.peak_holder_bytes), |
| 611 | opt(r.peak_staging_bytes), |
| 612 | opt(r.peak_rss_bytes), |
| 613 | opt(r.queue_depth), |
| 614 | )); |
| 615 | } |
| 616 | out.push_str("\nNOT_RUN reasons:\n\n"); |
| 617 | for r in report.rows.iter().filter(|r| r.status == RowStatus::NotRun) { |
| 618 | out.push_str(&format!( |
| 619 | "- {} ({}): {}\n", |
| 620 | r.mode, |
| 621 | r.platform, |
| 622 | r.reason.as_deref().unwrap_or_default() |
| 623 | )); |
| 624 | } |
| 625 | Ok(out) |
| 626 | } |