1//! A local bench for one route.2//!3//! Spec section 15 rule 4 expects a bench but the core neither tracks nor4//! compares one. This module times the route on the operator's machine and5//! reports a distribution; it is a tool, not a gate.67use std::time::Instant;89use inf3r_json::{Value, parse};1011/// One second is the unit that `Duration` reports.12constMS_PER_SECOND: f64 = 1_000.0;1314/// The key of the count that the server reports for a job.15constTOKENS_OUT: &str = "tokens_out";1617/// The key of the first-token time that the server reports for a job.18constFIRST_TOKEN_MS: &str = "first_token_ms";1920/// The key of the hundredths-of-a-token-per-second rate.21constTOKENS_PER_S: &str = "tokens_per_s";2223/// Percentages are fractions of one hundred.24constPERCENT: usize = 100;2526/// The middle of the distribution.27constP50: usize = 50;2829/// The tail that a client notices.30constP95: usize = 95;3132/// Runs one request many times and reports the distribution.33 #[derive(Clone, Copy, PartialEq, Eq, Debug)]34pubstructBench {35/// The counted runs.36pub runs: u32,37/// The runs before the counted ones. They are not part of the sample.38pub warmup: u32,39 }4041/// The distribution of one bench.42 #[derive(Clone, PartialEq, Debug)]43pubstructSample {44/// The median in milliseconds.45pub p50_ms: f64,46/// The 95th percentile in milliseconds.47pub p95_ms: f64,48/// The shortest counted run in milliseconds.49pub min_ms: f64,50/// The longest counted run in milliseconds.51pub max_ms: f64,52/// The counted runs.53pub runs: u32,54 }5556/// Times `work` for `warmup` runs, then `runs` runs, and returns the sample.57///58/// The first `warmup` runs are not counted: a process that is cold is not the59/// process that a client meets.60pubfnrun(bench: Bench, work: &mutdynFnMut() -> Result<(), String>) -> Result<Sample, String> {61if bench.runs == 0 {62returnErr("the bench needs at least one counted run".to_string());63 }64for _ in0..bench.warmup {65work()?;66 }67letmut times = Vec::with_capacity(bench.runs as usize);68for _ in0..bench.runs {69let started = Instant::now();70work()?;71 times.push(started.elapsed().as_secs_f64() * MS_PER_SECOND);72 }73 times.sort_by(f64::total_cmp);74let (Some(min_ms), Some(&max_ms)) = (times.first().copied(), times.last()) else {75// The count is above zero, so this arm is unreachable. It is a return76// and not a panic because a library has no reason to abort a process.77returnErr("the bench recorded no time".to_string());78 };79Ok(Sample {80 p50_ms: percentile(×, P50),81 p95_ms: percentile(×, P95),82 min_ms,83 max_ms,84 runs: bench.runs,85 })86 }8788/// The nearest-rank percentile of a sorted, non-empty sample.89fnpercentile(times: &[f64], percent: usize) -> f64 {90let last = times.len() - 1;91let rank = times.len() * percent;92let index = rank.div_ceil(PERCENT).saturating_sub(1).min(last);93 times[index]94 }9596/// The three numbers that make two bindings comparable.97 #[derive(Clone, Copy, PartialEq, Eq, Debug)]98pub(crate) structUsage {99/// The tokens that the job produced.100pub tokens_out: u64,101/// Milliseconds from the job's start to its first token.102pub first_token_ms: u64,103/// Hundredths of a token per second over the whole job.104pub tokens_per_s: u64,105 }106107/// Reads the usage that the server reported.108///109/// The native route answers SSE, while `stream: false` answers one JSON body.110/// A JSON body carries the counters under `usage`. An SSE `usage` event carries111/// them at the top of `body`, and an older `done` event may carry a `usage`112/// object; both are read.113pub(crate) fnusage(body: &str) -> Option<Usage> {114ifletOk(value) = parse(body)115 && letSome(usage) = usage_of(&value)116 {117returnSome(usage);118 }119sse_usage(body)120 }121122fnsse_usage(body: &str) -> Option<Usage> {123letmut found = None;124for line in body.lines() {125letSome(data) = line.strip_prefix("data:") else {126continue;127 };128let data = data.trim();129if data.is_empty() || data == "[DONE]" {130continue;131 }132ifletOk(value) = parse(data)133 && letSome(usage) = usage_of(&value)134 {135 found = Some(usage);136 }137 }138 found139 }140141fnusage_of(value: &Value) -> Option<Usage> {142let counts = match value.get("usage") {143Some(counts) => counts,144None => {145let body = value.get("body")?;146match body.get("usage") {147Some(counts) => counts,148Noneif body.get("t").and_then(Value::as_str) == Some("usage") => body,149None => returnNone,150 }151 }152 };153Some(Usage {154 tokens_out: counts.get(TOKENS_OUT)?.as_u64()?,155 first_token_ms: counts.get(FIRST_TOKEN_MS)?.as_u64()?,156 tokens_per_s: counts.get(TOKENS_PER_S)?.as_u64()?,157 })158 }