crates/edge/cli/src/bench.rs 4.9 KiB 158 lines Raw
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.6 7 use std::time::Instant;8 9 use inf3r_json::{Value, parse};10 11 /// One second is the unit that `Duration` reports.12 const MS_PER_SECOND: f64 = 1_000.0;13 14 /// The key of the count that the server reports for a job.15 const TOKENS_OUT: &str = "tokens_out";16 17 /// The key of the first-token time that the server reports for a job.18 const FIRST_TOKEN_MS: &str = "first_token_ms";19 20 /// The key of the hundredths-of-a-token-per-second rate.21 const TOKENS_PER_S: &str = "tokens_per_s";22 23 /// Percentages are fractions of one hundred.24 const PERCENT: usize = 100;25 26 /// The middle of the distribution.27 const P50: usize = 50;28 29 /// The tail that a client notices.30 const P95: usize = 95;31 32 /// Runs one request many times and reports the distribution.33 #[derive(Clone, Copy, PartialEq, Eq, Debug)]34 pub struct Bench {35     /// The counted runs.36     pub runs: u32,37     /// The runs before the counted ones. They are not part of the sample.38     pub warmup: u32,39 }40 41 /// The distribution of one bench.42 #[derive(Clone, PartialEq, Debug)]43 pub struct Sample {44     /// The median in milliseconds.45     pub p50_ms: f64,46     /// The 95th percentile in milliseconds.47     pub p95_ms: f64,48     /// The shortest counted run in milliseconds.49     pub min_ms: f64,50     /// The longest counted run in milliseconds.51     pub max_ms: f64,52     /// The counted runs.53     pub runs: u32,54 }55 56 /// 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.60 pub fn run(bench: Bench, work: &mut dyn FnMut() -> Result<(), String>) -> Result<Sample, String> {61     if bench.runs == 0 {62         return Err("the bench needs at least one counted run".to_string());63     }64     for _ in 0..bench.warmup {65         work()?;66     }67     let mut times = Vec::with_capacity(bench.runs as usize);68     for _ in 0..bench.runs {69         let started = Instant::now();70         work()?;71         times.push(started.elapsed().as_secs_f64() * MS_PER_SECOND);72     }73     times.sort_by(f64::total_cmp);74     let (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.77         return Err("the bench recorded no time".to_string());78     };79     Ok(Sample {80         p50_ms: percentile(&times, P50),81         p95_ms: percentile(&times, P95),82         min_ms,83         max_ms,84         runs: bench.runs,85     })86 }87 88 /// The nearest-rank percentile of a sorted, non-empty sample.89 fn percentile(times: &[f64], percent: usize) -> f64 {90     let last = times.len() - 1;91     let rank = times.len() * percent;92     let index = rank.div_ceil(PERCENT).saturating_sub(1).min(last);93     times[index]94 }95 96 /// The three numbers that make two bindings comparable.97 #[derive(Clone, Copy, PartialEq, Eq, Debug)]98 pub(crate) struct Usage {99     /// The tokens that the job produced.100     pub tokens_out: u64,101     /// Milliseconds from the job's start to its first token.102     pub first_token_ms: u64,103     /// Hundredths of a token per second over the whole job.104     pub tokens_per_s: u64,105 }106 107 /// 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.113 pub(crate) fn usage(body: &str) -> Option<Usage> {114     if let Ok(value) = parse(body)115         && let Some(usage) = usage_of(&value)116     {117         return Some(usage);118     }119     sse_usage(body)120 }121 122 fn sse_usage(body: &str) -> Option<Usage> {123     let mut found = None;124     for line in body.lines() {125         let Some(data) = line.strip_prefix("data:") else {126             continue;127         };128         let data = data.trim();129         if data.is_empty() || data == "[DONE]" {130             continue;131         }132         if let Ok(value) = parse(data)133             && let Some(usage) = usage_of(&value)134         {135             found = Some(usage);136         }137     }138     found139 }140 141 fn usage_of(value: &Value) -> Option<Usage> {142     let counts = match value.get("usage") {143         Some(counts) => counts,144         None => {145             let body = value.get("body")?;146             match body.get("usage") {147                 Some(counts) => counts,148                 None if body.get("t").and_then(Value::as_str) == Some("usage") => body,149                 None => return None,150             }151         }152     };153     Some(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 }