Skip to main content

xtask/
bench.rs

1//! Compile-time and editor-latency benchmarks (#3168).
2//!
3//! `cargo xtask bench` generates a synthetic project of N contexts
4//! ([`generate_project`]) and measures, against the release `bynk` and
5//! `bynk-lsp` binaries:
6//!
7//! - `cli_check` — `bynk check` on the project, a fresh process each run, so
8//!   the compiler's in-process caches are always cold;
9//! - `cli_recheck` — the same after a one-line edit (a fresh process again: it
10//!   shows whether anything survives between runs; today nothing does);
11//! - `lsp_first_round` — open one file and wait for its diagnostics: the
12//!   server's first, cold project-wide round;
13//! - `lsp_edit` — a one-line edit in an open buffer to the diagnostics for that
14//!   version arriving: the **edit-to-diagnostics** time, warm (the content-keyed
15//!   parse cache is populated by the first round).
16//!
17//! The LSP leg runs with `[lsp] diagnostics_debounce_ms = 0`, so the figure is
18//! the compute time; the shipped default debounce (300 ms) is added on top for
19//! a user, and is not part of the budget question this measures.
20//!
21//! Results are written per release to `design/benchmarks/v<version>.json`
22//! (`--record`), not gated per PR: shared CI runners are too noisy for a
23//! threshold. [`latest_record`] reads the newest one back for the
24//! `keystroke_latency` probe in `design/greenfield-status.md`.
25
26use crate::stamp::Version;
27use serde_json::{Value, json};
28use std::fs;
29use std::io::{BufRead, BufReader, Read, Write};
30use std::path::{Path, PathBuf};
31use std::process::{Child, Command, Stdio};
32use std::sync::mpsc;
33use std::time::{Duration, Instant};
34
35/// Where the per-release results live, relative to the repo root.
36pub const RECORD_DIR: &str = "design/benchmarks";
37
38/// How many agent/service/type groups each generated context holds.
39pub const GROUPS_PER_CONTEXT: usize = 3;
40
41/// The file the LSP benchmark edits, relative to the project root.
42pub const EDITED_FILE: &str = "src/ctx0.bynk";
43
44/// The generated project: `(relative path, contents)`. `contexts` independent
45/// contexts, each with `groups` groups of a refined type, a record, an agent
46/// with two handlers and an http service. Every file checks clean.
47pub fn generate_project(contexts: usize, groups: usize) -> Vec<(String, String)> {
48    generate_project_shaped(Shape::Independent, contexts, groups)
49}
50
51/// The two project shapes the benchmarks measure.
52#[derive(Clone, Copy, Debug, PartialEq, Eq)]
53pub enum Shape {
54    /// `contexts` independent contexts with small handler bodies: the shape the
55    /// budget (#3168) is stated on.
56    Independent,
57    /// Contexts that consume each other and larger handler bodies, closer to a
58    /// real project (#3243): context `i` consumes context `(i-1)/4`, a 4-ary
59    /// tree, so a project of N contexts is about `log4(N)` consumes-levels deep
60    /// and the contexts near the root are consumed by many. Every context
61    /// forwards a `price` call through its parent.
62    Linked,
63}
64
65impl Shape {
66    /// The shape's name, for progress and the CLI.
67    pub fn name(self) -> &'static str {
68        match self {
69            Shape::Independent => "independent",
70            Shape::Linked => "linked",
71        }
72    }
73
74    /// The key a record stores this shape's sizes under.
75    pub fn record_key(self) -> &'static str {
76        match self {
77            Shape::Independent => "sizes",
78            Shape::Linked => "linked_sizes",
79        }
80    }
81}
82
83/// [`generate_project`] for a given [`Shape`].
84pub fn generate_project_shaped(
85    shape: Shape,
86    contexts: usize,
87    groups: usize,
88) -> Vec<(String, String)> {
89    let mut files = vec![(
90        "bynk.toml".to_string(),
91        "[project]\nname = \"bench\"\nversion = \"0.1.0\"\n\n[lsp]\ndiagnostics_debounce_ms = 0\n"
92            .to_string(),
93    )];
94    for i in 0..contexts {
95        let source = match shape {
96            Shape::Independent => generate_context(i, groups),
97            Shape::Linked => generate_linked_context(i, groups),
98        };
99        files.push((format!("src/ctx{i}.bynk"), source));
100    }
101    files
102}
103
104/// A context of the [`Shape::Linked`] project: it consumes its parent, forwards
105/// `price` through it, and each group has a record, an agent with three handlers
106/// whose bodies do real work (a cross-context call, branching, a filter, a map
107/// and a sum), and an http service.
108fn generate_linked_context(index: usize, groups: usize) -> String {
109    let mut s = format!("context ctx{index}\n\n");
110    let parent = index.checked_sub(1).map(|i| i / 4);
111    if let Some(p) = parent {
112        s.push_str(&format!("consumes ctx{p}\n\n"));
113    }
114    let forward = match parent {
115        Some(p) => format!("    let p <- ctx{p}.price(n)\n    Effect.pure(p)\n"),
116        None => "    Effect.pure(n)\n".to_string(),
117    };
118    s.push_str(&format!(
119        "service price {{\n  on call(n: Int) -> Effect[Int] by Caller {{\n{forward}  }}\n}}\n\n"
120    ));
121    for j in 0..groups {
122        // The cross-context call in the first handler needs a parent to call.
123        let priced = match parent {
124            Some(p) => format!("    let p <- ctx{p}.price(row.qty)\n"),
125            None => "    let p = row.qty\n".to_string(),
126        };
127        s.push_str(&format!(
128            "type Id{j} = String where NonEmpty\n\n\
129             type Row{j} = {{\n  id:    Id{j},\n  label: String,\n  qty:   Int,\n  note:  String,\n}}\n\n\
130             agent Store{j} {{\n  key name: String\n\n  store rows: Map[String, Row{j}]\n\n  \
131             on call put(row: Row{j}) -> Effect[Row{j}] {{\n{priced}    \
132             let size = row.label.length() + row.note.length()\n    \
133             let tag = if (size > 10) {{ \"long\" }} else {{ \"short\" }}\n    \
134             let kept = if (p > 0) {{ row }} else {{ Row{j} {{ id: row.id, label: tag, qty: 1, note: row.note }} }}\n    \
135             let _ <- rows.put(kept.id, kept)\n    kept\n  }}\n\n  \
136             on call total(min: Int) -> Effect[Int] {{\n    rows.filter((r) => r.qty > min).sum((r) => r.qty)\n  }}\n\n  \
137             on call labels() -> Effect[List[String]] {{\n    rows.filter((r) => r.qty > 0).map((r) => r.label).collect()\n  }}\n}}\n\n\
138             service api{j} from http {{\n  \
139             on POST(\"/rows{j}\") (body: Row{j}) -> Effect[HttpResult[Row{j}]] by Visitor {{\n    \
140             let row <- Store{j}(\"default\").put(body)\n    Created(row)\n  }}\n}}\n\n"
141        ));
142    }
143    s
144}
145
146fn generate_context(index: usize, groups: usize) -> String {
147    let mut s = format!("context ctx{index}\n\n");
148    for j in 0..groups {
149        s.push_str(&format!(
150            "type Id{j} = String where NonEmpty\n\n\
151             type Row{j} = {{\n  id:    Id{j},\n  label: String,\n  count: Int,\n}}\n\n\
152             agent Store{j} {{\n  key name: String\n\n  store rows: Map[String, Row{j}]\n\n  \
153             on call put(row: Row{j}) -> Effect[Row{j}] {{\n    let _ <- rows.put(row.label, row)\n    row\n  }}\n\n  \
154             on call total() -> Effect[Int] {{\n    rows.filter((r) => r.count > 0).sum((r) => r.count)\n  }}\n}}\n\n\
155             service api{j} from http {{\n  \
156             on POST(\"/rows{j}\") (body: Row{j}) -> Effect[HttpResult[Row{j}]] by Visitor {{\n    \
157             let row <- Store{j}(\"default\").put(body)\n    Created(row)\n  }}\n}}\n\n"
158        ));
159    }
160    s
161}
162
163/// The one-line edit the benchmarks make: `valid` toggles a field's type
164/// between a real one and an unknown name, so each edit changes the diagnostics
165/// and the client can tell its own round from a stale one.
166pub fn edit_source(source: &str, valid: bool) -> String {
167    const GOOD: &str = "label: String,";
168    const BAD: &str = "label: Strng,";
169    if valid {
170        source.replacen(BAD, GOOD, 1)
171    } else {
172        source.replacen(GOOD, BAD, 1)
173    }
174}
175
176/// A **body-only** edit: a comparison inside a handler body becomes ill-typed
177/// and back (`> 0)` to `> "x")`). Nothing outside that body changes, so it is
178/// the edit an incremental analysis is meant to make cheap, and, like
179/// [`edit_source`], it moves the diagnostics so the client can see its own round.
180/// The signature edit [`edit_source`] makes is the pessimistic one for a cache.
181pub fn edit_body(source: &str, valid: bool) -> String {
182    const GOOD: &str = "> 0)";
183    const BAD: &str = "> \"x\")";
184    if valid {
185        source.replacen(BAD, GOOD, 1)
186    } else {
187        source.replacen(GOOD, BAD, 1)
188    }
189}
190
191/// Nearest-rank percentile of `samples` (milliseconds), `p` in 0..=100.
192pub fn percentile(samples: &[f64], p: f64) -> f64 {
193    assert!(!samples.is_empty(), "percentile of no samples");
194    let mut v = samples.to_vec();
195    v.sort_by(|a, b| a.partial_cmp(b).expect("no NaN timings"));
196    let rank = ((p / 100.0) * v.len() as f64).ceil() as usize;
197    v[rank.clamp(1, v.len()) - 1]
198}
199
200fn summary(samples: &[f64]) -> Value {
201    let round = |x: f64| (x * 10.0).round() / 10.0;
202    json!({
203        "runs": samples.len(),
204        "median_ms": round(percentile(samples, 50.0)),
205        "p95_ms": round(percentile(samples, 95.0)),
206        "max_ms": round(percentile(samples, 100.0)),
207    })
208}
209
210fn ms(d: Duration) -> f64 {
211    d.as_secs_f64() * 1000.0
212}
213
214/// Options for [`run`].
215pub struct Options {
216    pub sizes: Vec<usize>,
217    pub runs: usize,
218    pub edits: usize,
219    /// The shapes to measure; both by default.
220    pub shapes: Vec<Shape>,
221}
222
223impl Default for Options {
224    fn default() -> Self {
225        Options {
226            sizes: vec![10, 50, 200],
227            runs: 7,
228            edits: 20,
229            shapes: vec![Shape::Independent, Shape::Linked],
230        }
231    }
232}
233
234/// Run every size and return the result document (not yet written anywhere).
235pub fn run(root: &Path, opts: &Options, progress: &dyn Fn(&str)) -> Result<Value, String> {
236    let bynk = binary(root, "bynk")?;
237    let lsp = binary(root, "bynk-lsp")?;
238    let mut by_shape: Vec<(Shape, Vec<Value>)> = Vec::new();
239    for &shape in &opts.shapes {
240        let mut sizes = Vec::new();
241        for &n in &opts.sizes {
242            let label = format!("{n} {} contexts", shape.name());
243            progress(&format!("{label}: generating"));
244            let dir = root.join(match shape {
245                Shape::Independent => format!("target/bench-project-{n}"),
246                Shape::Linked => format!("target/bench-linked-project-{n}"),
247            });
248            let _ = fs::remove_dir_all(&dir);
249            let files = generate_project_shaped(shape, n, GROUPS_PER_CONTEXT);
250            let mut lines = 0usize;
251            for (rel, body) in &files {
252                let p = dir.join(rel);
253                fs::create_dir_all(p.parent().expect("has parent")).map_err(|e| e.to_string())?;
254                fs::write(&p, body).map_err(|e| e.to_string())?;
255                lines += body.lines().count();
256            }
257
258            progress(&format!("{label}: bynk check"));
259            let cli_check = time_cli(&bynk, &dir, opts.runs, false)?;
260            progress(&format!("{label}: bynk check after an edit"));
261            let cli_recheck = time_cli(&bynk, &dir, opts.runs, true)?;
262            progress(&format!("{label}: language server"));
263            let lsp_run = time_lsp(&lsp, &dir, opts.edits)?;
264
265            sizes.push(json!({
266                "contexts": n,
267                "groups_per_context": GROUPS_PER_CONTEXT,
268                "source_lines": lines,
269                "cli_check": summary(&cli_check),
270                "cli_recheck": summary(&cli_recheck),
271                "lsp_first_round": summary(&[lsp_run.first]),
272                "lsp_edit": summary(&lsp_run.edits),
273                "lsp_first_round_levels": level_medians(&lsp_run.first_levels.into_iter().collect::<Vec<_>>()),
274                "lsp_edit_levels": level_medians(&lsp_run.edit_levels),
275                "lsp_body_edit": summary(&lsp_run.body_edits),
276                "lsp_body_edit_levels": level_medians(&lsp_run.body_edit_levels),
277                "lsp_peak_rss_mb": lsp_run.peak_rss_mb,
278                "lsp_edit_outside_analysis_ms": outside_analysis(&lsp_run.edits, &lsp_run.edit_levels),
279            }));
280        }
281        by_shape.push((shape, sizes));
282    }
283    let mut record = json!({
284        "version": workspace_version(root)?,
285        "commit": git(root, &["rev-parse", "--short", "HEAD"]).unwrap_or_default(),
286        "host": host(),
287        "debounce_ms_in_lsp_runs": 0,
288    });
289    for (shape, sizes) in by_shape {
290        record[shape.record_key()] = Value::Array(sizes);
291    }
292    Ok(record)
293}
294
295fn workspace_version(root: &Path) -> Result<String, String> {
296    let src = fs::read_to_string(root.join("Cargo.toml")).map_err(|e| e.to_string())?;
297    crate::stamp::parse_workspace_version(&src)
298        .map(|v| v.to_string())
299        .ok_or_else(|| "no workspace version in Cargo.toml".to_string())
300}
301
302fn git(root: &Path, args: &[&str]) -> Option<String> {
303    let out = Command::new("git")
304        .args(args)
305        .current_dir(root)
306        .output()
307        .ok()?;
308    out.status
309        .success()
310        .then(|| String::from_utf8_lossy(&out.stdout).trim().to_string())
311}
312
313fn host() -> Value {
314    let cpu = fs::read_to_string("/proc/cpuinfo")
315        .ok()
316        .and_then(|s| {
317            s.lines()
318                .find(|l| l.starts_with("model name"))
319                .and_then(|l| l.split_once(':'))
320                .map(|(_, v)| v.trim().to_string())
321        })
322        .unwrap_or_else(|| "unknown".to_string());
323    json!({
324        "os": std::env::consts::OS,
325        "arch": std::env::consts::ARCH,
326        "cpu": cpu,
327        "logical_cpus": std::thread::available_parallelism().map(|n| n.get()).unwrap_or(0),
328    })
329}
330
331/// Build (release) and locate a workspace binary.
332fn binary(root: &Path, name: &str) -> Result<PathBuf, String> {
333    let status = Command::new("cargo")
334        .args(["build", "--release", "--quiet", "--package", name])
335        .current_dir(root)
336        .status()
337        .map_err(|e| format!("cannot run cargo: {e}"))?;
338    if !status.success() {
339        return Err(format!("cargo build --release -p {name} failed"));
340    }
341    let target = std::env::var_os("CARGO_TARGET_DIR")
342        .map(PathBuf::from)
343        .unwrap_or_else(|| root.join("target"));
344    let p = target.join("release").join(name);
345    p.exists()
346        .then_some(p.clone())
347        .ok_or_else(|| format!("{} not found after build", p.display()))
348}
349
350fn time_cli(bynk: &Path, dir: &Path, runs: usize, edit_first: bool) -> Result<Vec<f64>, String> {
351    let path = dir.join(EDITED_FILE);
352    let original = fs::read_to_string(&path).map_err(|e| e.to_string())?;
353    let mut samples = Vec::new();
354    for i in 0..runs {
355        if edit_first {
356            // Keep the project clean-checking: the edit is a value-level one-line
357            // change (a comment line carrying the run number).
358            fs::write(&path, format!("{original}// edit {i}\n")).map_err(|e| e.to_string())?;
359        }
360        let t = Instant::now();
361        let out = Command::new(bynk)
362            .arg("check")
363            .current_dir(dir)
364            .output()
365            .map_err(|e| e.to_string())?;
366        let elapsed = t.elapsed();
367        if !out.status.success() {
368            return Err(format!(
369                "bynk check failed on the generated project:\n{}",
370                String::from_utf8_lossy(&out.stderr)
371            ));
372        }
373        samples.push(ms(elapsed));
374    }
375    if edit_first {
376        fs::write(&path, original).map_err(|e| e.to_string())?;
377    }
378    Ok(samples)
379}
380
381// --- a minimal LSP client -------------------------------------------------
382
383struct Client {
384    child: Child,
385    rx: mpsc::Receiver<Value>,
386    /// The per-level timing line the server writes to stderr after each
387    /// analysis round (`BYNK_PHASE_TIMING`), as `[file, unit, definition, project]` ms.
388    timings: mpsc::Receiver<[f64; 4]>,
389}
390
391/// Parse `bynk-phase-timing file=1.0 unit=2.0 definition=3.0 project=4.0`.
392pub fn parse_timing_line(line: &str) -> Option<[f64; 4]> {
393    let rest = line.trim().strip_prefix("bynk-phase-timing")?;
394    let mut out = [f64::NAN; 4];
395    for part in rest.split_whitespace() {
396        let (k, v) = part.split_once('=')?;
397        let i = LEVELS.iter().position(|l| *l == k)?;
398        out[i] = v.parse().ok()?;
399    }
400    out.iter().all(|x| x.is_finite()).then_some(out)
401}
402
403/// R3.13's four query levels, in the order the timing line reports them.
404pub const LEVELS: [&str; 4] = ["file", "unit", "definition", "project"];
405
406fn send(child: &mut Child, msg: &Value) -> Result<(), String> {
407    let body = msg.to_string();
408    let stdin = child.stdin.as_mut().ok_or("no stdin")?;
409    write!(stdin, "Content-Length: {}\r\n\r\n{body}", body.len()).map_err(|e| e.to_string())?;
410    stdin.flush().map_err(|e| e.to_string())
411}
412
413impl Client {
414    fn spawn(lsp: &Path) -> Result<Client, String> {
415        let mut child = Command::new(lsp)
416            .stdin(Stdio::piped())
417            .stdout(Stdio::piped())
418            .stderr(Stdio::piped())
419            .env("BYNK_PHASE_TIMING", "1")
420            .spawn()
421            .map_err(|e| format!("cannot start bynk-lsp: {e}"))?;
422        let err = BufReader::new(child.stderr.take().ok_or("no stderr")?);
423        let (ttx, timings) = mpsc::channel();
424        std::thread::spawn(move || {
425            for line in err.lines().map_while(Result::ok) {
426                if let Some(t) = parse_timing_line(&line)
427                    && ttx.send(t).is_err()
428                {
429                    return;
430                }
431            }
432        });
433        let mut out = BufReader::new(child.stdout.take().ok_or("no stdout")?);
434        let (tx, rx) = mpsc::channel();
435        std::thread::spawn(move || {
436            loop {
437                let mut len = None;
438                loop {
439                    let mut line = String::new();
440                    match out.read_line(&mut line) {
441                        Ok(0) | Err(_) => return,
442                        Ok(_) => {}
443                    }
444                    let line = line.trim();
445                    if line.is_empty() {
446                        break;
447                    }
448                    if let Some(v) = line.strip_prefix("Content-Length:") {
449                        len = v.trim().parse::<usize>().ok();
450                    }
451                }
452                let Some(len) = len else { return };
453                let mut buf = vec![0u8; len];
454                if out.read_exact(&mut buf).is_err() {
455                    return;
456                }
457                if let Ok(v) = serde_json::from_slice::<Value>(&buf)
458                    && tx.send(v).is_err()
459                {
460                    return;
461                }
462            }
463        });
464        Ok(Client { child, rx, timings })
465    }
466
467    /// Drop any timing lines already received (a late line from a previous round).
468    fn discard_timings(&self) {
469        while self.timings.try_recv().is_ok() {}
470    }
471
472    /// The timing line of the round whose diagnostics just arrived. The server
473    /// writes it to stderr before it publishes, but stdout and stderr are read
474    /// by separate threads, so the diagnostics can be seen first: wait briefly
475    /// for the line rather than take whatever has arrived. `None` when the
476    /// server writes none (an older `bynk-lsp`), after a few seconds.
477    fn round_timing(&self) -> Option<[f64; 4]> {
478        self.timings.recv_timeout(Duration::from_secs(5)).ok()
479    }
480
481    /// Wait for a message satisfying `want`, answering any server-to-client
482    /// request on the way (an empty `null` result is accepted for all of them).
483    fn wait(&mut self, mut want: impl FnMut(&Value) -> bool) -> Result<Duration, String> {
484        let t = Instant::now();
485        loop {
486            let left = Duration::from_secs(120).saturating_sub(t.elapsed());
487            let msg = self
488                .rx
489                .recv_timeout(left)
490                .map_err(|_| "timed out after 120 s waiting for the language server (is the project path file-URI safe: no spaces, `#` or `%`?)".to_string())?;
491            let at = t.elapsed();
492            if want(&msg) {
493                return Ok(at);
494            }
495            if msg.get("method").is_some()
496                && let Some(id) = msg.get("id")
497            {
498                send(
499                    &mut self.child,
500                    &json!({"jsonrpc": "2.0", "id": id, "result": null}),
501                )?;
502            }
503        }
504    }
505}
506
507fn is_diagnostics_for(msg: &Value, uri: &str, version: i64) -> bool {
508    msg.get("method").and_then(Value::as_str) == Some("textDocument/publishDiagnostics")
509        && msg["params"]["uri"].as_str() == Some(uri)
510        && msg["params"]["version"].as_i64() == Some(version)
511}
512
513/// What one language-server run measured, in milliseconds.
514struct LspTimings {
515    first: f64,
516    edits: Vec<f64>,
517    /// The first round's `[file, unit, definition, project]` attribution.
518    first_levels: Option<[f64; 4]>,
519    /// One `[file, unit, definition, project]` per timed edit.
520    edit_levels: Vec<[f64; 4]>,
521    /// Edit-to-diagnostics for a **body-only** edit (see [`edit_body`]).
522    body_edits: Vec<f64>,
523    body_edit_levels: Vec<[f64; 4]>,
524    /// The server's peak resident set, in MB, read from `/proc` just before it
525    /// exits (`None` off Linux). Retained analysis state shows up here.
526    peak_rss_mb: Option<f64>,
527}
528
529/// `VmHWM` of process `pid` in MB, from `/proc/<pid>/status`.
530fn peak_rss_mb(pid: u32) -> Option<f64> {
531    let status = fs::read_to_string(format!("/proc/{pid}/status")).ok()?;
532    let kb: f64 = status
533        .lines()
534        .find_map(|l| l.strip_prefix("VmHWM:"))?
535        .trim()
536        .strip_suffix("kB")?
537        .trim()
538        .parse()
539        .ok()?;
540    Some((kb / 1024.0 * 10.0).round() / 10.0)
541}
542
543fn time_lsp(lsp: &Path, dir: &Path, edits: usize) -> Result<LspTimings, String> {
544    let dir = dir.canonicalize().map_err(|e| e.to_string())?;
545    let root_uri = format!("file://{}", dir.display());
546    let file = dir.join(EDITED_FILE);
547    let uri = format!("file://{}", file.display());
548    let clean = fs::read_to_string(&file).map_err(|e| e.to_string())?;
549    // The server publishes only when a file's diagnostics change, so a clean
550    // file never answers. Open it broken (a diagnostic to publish), then toggle:
551    // every edit flips the set, so every round is observable.
552    let text = edit_source(&clean, false);
553
554    let mut c = Client::spawn(lsp)?;
555    send(
556        &mut c.child,
557        &json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{
558            "processId": std::process::id(),
559            "rootUri": root_uri,
560            "capabilities": {},
561            "workspaceFolders": [{"uri": root_uri, "name": "bench"}],
562        }}),
563    )?;
564    c.wait(|m| m.get("id") == Some(&json!(1)) && m.get("method").is_none())?;
565    send(
566        &mut c.child,
567        &json!({"jsonrpc":"2.0","method":"initialized","params":{}}),
568    )?;
569
570    let did_open = |text: &str| {
571        json!({"jsonrpc":"2.0","method":"textDocument/didOpen","params":{"textDocument":{
572            "uri": uri, "languageId": "bynk", "version": 1, "text": text}}})
573    };
574    send(&mut c.child, &did_open(&text))?;
575    let first = c.wait(|m| is_diagnostics_for(m, &uri, 1))?;
576    let first_levels = c.round_timing();
577
578    let mut samples = Vec::new();
579    let mut edit_levels = Vec::new();
580    let warmup = 2;
581    for i in 0..(edits + warmup) {
582        let version = i as i64 + 2;
583        // Opened broken, so the first edit restores it.
584        let valid = i % 2 == 0;
585        let edited = edit_source(&clean, valid);
586        // Nothing from an earlier round may be mistaken for this one's.
587        c.discard_timings();
588        send(
589            &mut c.child,
590            &json!({"jsonrpc":"2.0","method":"textDocument/didChange","params":{
591                "textDocument": {"uri": uri, "version": version},
592                "contentChanges": [{"text": edited}],
593            }}),
594        )?;
595        let took = c.wait(|m| is_diagnostics_for(m, &uri, version))?;
596        let levels = c.round_timing();
597        if i >= warmup {
598            samples.push(ms(took));
599            edit_levels.extend(levels);
600        }
601    }
602
603    // The signature phase opened broken and toggles each edit, so it ends broken
604    // after an even number of edits and clean after an odd number. If broken,
605    // restore the clean text first (waiting for the round, which clears the
606    // diagnostic), so the body phase starts from a state where its first edit
607    // adds one; if already clean, sending the clean text again would change
608    // nothing, publish nothing, and wait forever.
609    let mut version = (edits + warmup) as i64 + 1;
610    if (edits + warmup).is_multiple_of(2) {
611        version += 1;
612        c.discard_timings();
613        send(
614            &mut c.child,
615            &json!({"jsonrpc":"2.0","method":"textDocument/didChange","params":{
616                "textDocument": {"uri": uri, "version": version},
617                "contentChanges": [{"text": clean}],
618            }}),
619        )?;
620        c.wait(|m| is_diagnostics_for(m, &uri, version))?;
621        let _ = c.round_timing();
622    }
623    let mut body_samples = Vec::new();
624    let mut body_levels = Vec::new();
625    for j in 0..(edits + warmup) {
626        version += 1;
627        // The first edit breaks the body, the next restores it, and so on.
628        let valid = j % 2 == 1;
629        let edited = edit_body(&clean, valid);
630        c.discard_timings();
631        send(
632            &mut c.child,
633            &json!({"jsonrpc":"2.0","method":"textDocument/didChange","params":{
634                "textDocument": {"uri": uri, "version": version},
635                "contentChanges": [{"text": edited}],
636            }}),
637        )?;
638        let took = c.wait(|m| is_diagnostics_for(m, &uri, version))?;
639        let levels = c.round_timing();
640        if j >= warmup {
641            body_samples.push(ms(took));
642            body_levels.extend(levels);
643        }
644    }
645
646    let peak_rss_mb = peak_rss_mb(c.child.id());
647    let _ = send(
648        &mut c.child,
649        &json!({"jsonrpc":"2.0","id":2,"method":"shutdown","params":null}),
650    );
651    let _ = send(&mut c.child, &json!({"jsonrpc":"2.0","method":"exit"}));
652    std::thread::sleep(Duration::from_millis(100));
653    let _ = c.child.kill();
654    let _ = c.child.wait();
655    Ok(LspTimings {
656        first: ms(first),
657        edits: samples,
658        first_levels,
659        edit_levels,
660        body_edits: body_samples,
661        body_edit_levels: body_levels,
662        peak_rss_mb,
663    })
664}
665
666/// Median time per edit spent outside the analysis round (the server's content
667/// sweep, converting and publishing diagnostics): the edit-to-diagnostics time
668/// less the four levels. `null` unless every timed edit has its timing line.
669fn outside_analysis(edits: &[f64], levels: &[[f64; 4]]) -> Value {
670    if edits.is_empty() || edits.len() != levels.len() {
671        return Value::Null;
672    }
673    let outside: Vec<f64> = edits
674        .iter()
675        .zip(levels)
676        .map(|(e, l)| (e - l.iter().sum::<f64>()).max(0.0))
677        .collect();
678    json!((percentile(&outside, 50.0) * 10.0).round() / 10.0)
679}
680
681/// Median of each level across `rows`, as a JSON object (`null` when there are none).
682fn level_medians(rows: &[[f64; 4]]) -> Value {
683    if rows.is_empty() {
684        return Value::Null;
685    }
686    let round = |x: f64| (x * 10.0).round() / 10.0;
687    let mut o = serde_json::Map::new();
688    for (i, name) in LEVELS.iter().enumerate() {
689        let col: Vec<f64> = rows.iter().map(|r| r[i]).collect();
690        o.insert((*name).to_string(), json!(round(percentile(&col, 50.0))));
691    }
692    Value::Object(o)
693}
694
695// --- recorded results -------------------------------------------------------
696
697/// The path of the record for `version`.
698pub fn record_path(root: &Path, version: &str) -> PathBuf {
699    root.join(RECORD_DIR).join(format!("v{version}.json"))
700}
701
702/// The newest recorded result (highest version) under `root`, with its version.
703pub fn latest_record(root: &Path) -> Option<(Version, Value)> {
704    let mut best: Option<(Version, PathBuf)> = None;
705    for entry in fs::read_dir(root.join(RECORD_DIR)).ok()?.flatten() {
706        let name = entry.file_name().to_string_lossy().into_owned();
707        let Some(v) = name
708            .strip_prefix('v')
709            .and_then(|n| n.strip_suffix(".json"))
710            .and_then(Version::parse)
711        else {
712            continue;
713        };
714        let newer = best
715            .as_ref()
716            .is_none_or(|(b, _)| (v.major, v.minor, v.patch) > (b.major, b.minor, b.patch));
717        if newer {
718            best = Some((v, entry.path()));
719        }
720    }
721    let (v, path) = best?;
722    Some((
723        v,
724        serde_json::from_str(&fs::read_to_string(path).ok()?).ok()?,
725    ))
726}
727
728/// The accepted editor-latency budget (#3168, accepted by the maintainer):
729/// the language server's edit-to-diagnostics **p95** stays under this many
730/// milliseconds on the [`BUDGET_CONTEXTS`]-context synthetic project. It is
731/// checked against each release record, not gated in CI. (The scheduler's own
732/// trigger is separate: [`TRIGGER_P95_MS`].)
733pub const BUDGET_P95_MS: f64 = 100.0;
734
735/// The project size the budget is stated for.
736pub const BUDGET_CONTEXTS: u64 = 50;
737
738/// The incremental-scheduler trigger (#1523, #3243): the scheduler decision is
739/// reopened when the language server's edit-to-diagnostics **p95** exceeds this
740/// many milliseconds at [`TRIGGER_CONTEXTS`] contexts, on **either** project
741/// shape, in a release record. It was the trigger the scheduler (S2 of #3243)
742/// was first deferred on; the maintainer has since decided to build it, and this
743/// stays as the yardstick the slices are measured against.
744pub const TRIGGER_P95_MS: f64 = 250.0;
745
746/// The project size the scheduler trigger is stated for.
747pub const TRIGGER_CONTEXTS: u64 = 200;
748
749/// The p95 at [`TRIGGER_CONTEXTS`] contexts for `shape`'s sizes, if measured.
750fn trigger_p95(record: &Value, shape: Shape) -> Option<f64> {
751    record[shape.record_key()]
752        .as_array()?
753        .iter()
754        .find(|s| s["contexts"].as_u64() == Some(TRIGGER_CONTEXTS))?["lsp_edit"]["p95_ms"]
755        .as_f64()
756}
757
758/// The scheduler trigger's reading on `record`, one clause: which shapes were
759/// measured at [`TRIGGER_CONTEXTS`] contexts, their p95, and whether the trigger
760/// is reached. `None` when neither shape measured that size.
761fn trigger_reading(record: &Value) -> Option<String> {
762    let cells: Vec<(Shape, f64)> = [Shape::Independent, Shape::Linked]
763        .into_iter()
764        .filter_map(|shape| Some((shape, trigger_p95(record, shape)?)))
765        .collect();
766    if cells.is_empty() {
767        return None;
768    }
769    let reached = cells.iter().any(|(_, p)| *p > TRIGGER_P95_MS);
770    let shown: Vec<String> = cells
771        .iter()
772        .map(|(shape, p)| format!("{} {p} ms", shape.name()))
773        .collect();
774    Some(format!(
775        "scheduler yardstick p95 > {TRIGGER_P95_MS} ms at {TRIGGER_CONTEXTS} contexts: {} ({})",
776        if reached { "REACHED" } else { "not reached" },
777        shown.join(", ")
778    ))
779}
780
781/// A warning for `cargo xtask bench` when `record` reaches the scheduler
782/// trigger on either shape; `None` otherwise.
783pub fn trigger_warning(record: &Value) -> Option<String> {
784    let reached = [Shape::Independent, Shape::Linked]
785        .into_iter()
786        .any(|shape| trigger_p95(record, shape).is_some_and(|p| p > TRIGGER_P95_MS));
787    reached.then(|| {
788        format!(
789            "{} — latency is at the incremental-scheduler yardstick (#3243, #1523)",
790            trigger_reading(record).unwrap_or_default()
791        )
792    })
793}
794
795/// The budget's verdict on a record: `Some(p95)` of the [`BUDGET_CONTEXTS`]-context
796/// size, or `None` when the record did not measure that size.
797fn budget_p95(record: &Value) -> Option<f64> {
798    record["sizes"]
799        .as_array()?
800        .iter()
801        .find(|s| s["contexts"].as_u64() == Some(BUDGET_CONTEXTS))?["lsp_edit"]["p95_ms"]
802        .as_f64()
803}
804
805/// A warning for `cargo xtask bench` to print when `record` breaches the
806/// budget; `None` when it is met or the size was not measured.
807pub fn budget_warning(record: &Value) -> Option<String> {
808    let p95 = budget_p95(record).filter(|p| *p >= BUDGET_P95_MS)?;
809    Some(format!(
810        "edit-to-diagnostics p95 is {p95} ms at {BUDGET_CONTEXTS} contexts, over the {BUDGET_P95_MS} ms budget (the accepted latency budget, #3168)"
811    ))
812}
813
814/// One-line reading of a record, for the `keystroke_latency` probe: the
815/// edit-to-diagnostics median at each measured size, smallest first.
816pub fn reading(version: Version, record: &Value) -> Option<String> {
817    let mut sizes: Vec<&Value> = record["sizes"].as_array()?.iter().collect();
818    sizes.sort_by_key(|s| s["contexts"].as_u64().unwrap_or(0));
819    let cells: Option<Vec<String>> = sizes
820        .iter()
821        .map(|s| {
822            Some(format!(
823                "{} contexts {} ms",
824                s["contexts"].as_u64()?,
825                s["lsp_edit"]["median_ms"].as_f64()?
826            ))
827        })
828        .collect();
829    let cells = cells.filter(|c| !c.is_empty())?;
830    let budget = match budget_p95(record) {
831        Some(p) if p < BUDGET_P95_MS => {
832            format!("; budget p95 < {BUDGET_P95_MS} ms at {BUDGET_CONTEXTS} contexts: met ({p} ms)")
833        }
834        Some(p) => format!(
835            "; budget p95 < {BUDGET_P95_MS} ms at {BUDGET_CONTEXTS} contexts: BREACHED ({p} ms)"
836        ),
837        None => {
838            format!("; budget p95 < {BUDGET_P95_MS} ms at {BUDGET_CONTEXTS} contexts: not measured")
839        }
840    };
841    let trigger = trigger_reading(record)
842        .map(|t| format!("; {t}"))
843        .unwrap_or_default();
844    Some(format!(
845        "edit-to-diagnostics median: {}; debounce excluded{budget}{trigger} (v{version}, {RECORD_DIR}/v{version}.json)",
846        cells.join(", ")
847    ))
848}
849
850#[cfg(test)]
851mod tests {
852    use super::*;
853
854    #[test]
855    fn the_generator_is_deterministic_and_sized() {
856        let a = generate_project(4, 3);
857        assert_eq!(a, generate_project(4, 3));
858        // The manifest plus one file per context.
859        assert_eq!(a.len(), 5);
860        assert!(a[0].1.contains("diagnostics_debounce_ms = 0"));
861        let ctx = &a.iter().find(|(p, _)| p == EDITED_FILE).unwrap().1;
862        assert!(ctx.starts_with("context ctx0\n"));
863        assert_eq!(ctx.matches("agent Store").count(), 3);
864        assert_eq!(ctx.matches("service api").count(), 3);
865    }
866
867    #[test]
868    fn the_edit_toggles_and_round_trips() {
869        let src = generate_context(0, 1);
870        let broken = edit_source(&src, false);
871        assert_ne!(broken, src);
872        assert_eq!(edit_source(&broken, true), src);
873    }
874
875    #[test]
876    fn the_timing_line_parses_in_level_order() {
877        let t =
878            parse_timing_line("bynk-phase-timing file=1.5 unit=2.0 definition=30.25 project=4.0");
879        assert_eq!(t, Some([1.5, 2.0, 30.25, 4.0]));
880        // A missing level, a bad number or another line is not a timing line.
881        assert_eq!(parse_timing_line("bynk-phase-timing file=1 unit=2"), None);
882        assert_eq!(
883            parse_timing_line("bynk-phase-timing file=x unit=2 definition=3 project=4"),
884            None
885        );
886        assert_eq!(parse_timing_line("some other log line"), None);
887    }
888
889    #[test]
890    fn level_medians_are_per_level() {
891        let rows = [
892            [1.0, 10.0, 100.0, 5.0],
893            [3.0, 30.0, 300.0, 7.0],
894            [2.0, 20.0, 200.0, 6.0],
895        ];
896        let m = level_medians(&rows);
897        assert_eq!(m["file"], json!(2.0));
898        assert_eq!(m["definition"], json!(200.0));
899        assert_eq!(level_medians(&[]), Value::Null);
900    }
901
902    #[test]
903    fn the_budget_is_read_from_the_50_context_p95() {
904        let rec = |p95: f64| {
905            json!({"sizes": [
906                {"contexts": 10, "lsp_edit": {"median_ms": 1.0, "p95_ms": 500.0}},
907                {"contexts": 50, "lsp_edit": {"median_ms": 40.0, "p95_ms": p95}},
908            ]})
909        };
910        // Only the 50-context size counts; a slow 10-context p95 does not breach.
911        assert_eq!(budget_warning(&rec(54.5)), None);
912        assert!(
913            budget_warning(&rec(100.0))
914                .unwrap()
915                .contains("over the 100 ms budget")
916        );
917        assert!(budget_warning(&rec(250.0)).unwrap().contains("#3168"));
918        // A record that did not measure 50 contexts says nothing, and reads "not measured".
919        let none = json!({"sizes": [{"contexts": 10, "source_lines": 1, "lsp_edit": {"median_ms": 1.0, "p95_ms": 1.0}}]});
920        assert_eq!(budget_warning(&none), None);
921        let v = Version::parse("0.1.0").unwrap();
922        assert!(reading(v, &none).unwrap().contains("not measured"));
923        assert!(reading(v, &rec(54.5)).unwrap().contains("met (54.5 ms)"));
924        assert!(
925            reading(v, &rec(120.0))
926                .unwrap()
927                .contains("BREACHED (120 ms)")
928        );
929    }
930
931    /// The trigger is p95 > 250 ms at 200 contexts on either shape; a shape that
932    /// did not measure 200 contexts says nothing.
933    #[test]
934    fn the_scheduler_trigger_is_checked_on_both_shapes() {
935        let at = |key: &str, p95: f64| json!({ key: [{"contexts": 200, "lsp_edit": {"median_ms": 1.0, "p95_ms": p95}}] });
936        let merged = |a: Value, b: Value| {
937            let mut m = a;
938            m["linked_sizes"] = b["linked_sizes"].clone();
939            m
940        };
941        let quiet = merged(at("sizes", 118.5), at("linked_sizes", 190.0));
942        assert_eq!(trigger_warning(&quiet), None);
943        assert!(
944            trigger_reading(&quiet)
945                .unwrap()
946                .contains("not reached (independent 118.5 ms, linked 190 ms)")
947        );
948        // Either shape reaching it is enough; exactly 250 is not over it.
949        let linked_over = merged(at("sizes", 118.5), at("linked_sizes", 250.1));
950        assert!(trigger_warning(&linked_over).unwrap().contains("REACHED"));
951        let indep_over = merged(at("sizes", 300.0), at("linked_sizes", 10.0));
952        assert!(trigger_warning(&indep_over).is_some());
953        assert_eq!(
954            trigger_warning(&merged(at("sizes", 250.0), at("linked_sizes", 250.0))),
955            None
956        );
957        // A record measuring neither shape at 200 contexts has no reading.
958        assert_eq!(trigger_reading(&json!({"sizes": [{"contexts": 50}]})), None);
959        // The probe line carries it when present, and still reads without it.
960        let v = Version::parse("0.1.0").unwrap();
961        let rec = json!({
962            "sizes": [
963                {"contexts": 50, "lsp_edit": {"median_ms": 1.0, "p95_ms": 2.0}},
964                {"contexts": 200, "lsp_edit": {"median_ms": 1.0, "p95_ms": 118.5}},
965            ],
966            "linked_sizes": [{"contexts": 200, "lsp_edit": {"median_ms": 1.0, "p95_ms": 190.0}}],
967        });
968        assert!(
969            reading(v, &rec)
970                .unwrap()
971                .contains("scheduler yardstick p95 > 250 ms at 200 contexts: not reached")
972        );
973    }
974
975    #[test]
976    fn the_linked_shape_consumes_a_parent_tree_and_keeps_the_edit_target() {
977        let files = generate_project_shaped(Shape::Linked, 10, 2);
978        let src = |i: usize| {
979            &files
980                .iter()
981                .find(|(p, _)| p == &format!("src/ctx{i}.bynk"))
982                .unwrap()
983                .1
984        };
985        // The root consumes nothing; the others consume `(i-1)/4`.
986        assert!(!src(0).contains("consumes"));
987        assert!(src(1).contains("consumes ctx0\n"));
988        assert!(src(4).contains("consumes ctx0\n"));
989        assert!(src(5).contains("consumes ctx1\n"));
990        assert!(src(9).contains("consumes ctx2\n"));
991        // Each group's handlers are bigger than the independent shape's.
992        assert_eq!(src(3).matches("agent Store").count(), 2);
993        assert!(src(3).lines().count() > generate_context(3, 2).lines().count());
994        // The edit still toggles a field in the edited file, and round-trips.
995        let edited = src(0);
996        assert_ne!(&edit_source(edited, false), edited);
997        assert_eq!(&edit_source(&edit_source(edited, false), true), edited);
998        // The independent generator is unchanged by shapes.
999        assert_eq!(
1000            generate_project(4, 3),
1001            generate_project_shaped(Shape::Independent, 4, 3)
1002        );
1003    }
1004
1005    #[test]
1006    fn the_body_edit_changes_only_a_body_and_round_trips() {
1007        for shape in [Shape::Independent, Shape::Linked] {
1008            let files = generate_project_shaped(shape, 4, 2);
1009            let src = &files.iter().find(|(p, _)| p == EDITED_FILE).unwrap().1;
1010            let broken = edit_body(src, false);
1011            assert_ne!(&broken, src, "{} has a body to edit", shape.name());
1012            // Only the one comparison changed: same length difference as the swap.
1013            assert_eq!(broken.len() + "> 0)".len(), src.len() + "> \"x\")".len());
1014            assert_eq!(&edit_body(&broken, true), src);
1015            // The signature edit and the body edit touch different things.
1016            // Both edits apply to the same file without disturbing each other.
1017            let both = edit_source(&broken, false);
1018            assert_ne!(both, broken, "the signature edit still applies");
1019            assert_eq!(&edit_body(&edit_source(&both, true), true), src);
1020        }
1021    }
1022
1023    #[test]
1024    fn percentile_is_nearest_rank() {
1025        let s = [5.0, 1.0, 3.0, 2.0, 4.0];
1026        assert_eq!(percentile(&s, 50.0), 3.0);
1027        assert_eq!(percentile(&s, 95.0), 5.0);
1028        assert_eq!(percentile(&s, 100.0), 5.0);
1029        assert_eq!(percentile(&[7.0], 50.0), 7.0);
1030    }
1031
1032    #[test]
1033    fn the_latest_record_is_the_highest_version_and_reads_back() {
1034        let root = std::env::temp_dir().join(format!("xtask-bench-latest-{}", std::process::id()));
1035        let _ = fs::remove_dir_all(&root);
1036        fs::create_dir_all(root.join(RECORD_DIR)).unwrap();
1037        assert!(latest_record(&root).is_none());
1038        let rec = |ms: f64| {
1039            json!({"sizes": [
1040                {"contexts": 10, "source_lines": 1, "lsp_edit": {"median_ms": 1.0, "p95_ms": 1.0}},
1041                {"contexts": 200, "source_lines": 9, "lsp_edit": {"median_ms": ms, "p95_ms": ms + 1.0}},
1042            ]})
1043        };
1044        fs::write(record_path(&root, "0.9.0"), rec(5.0).to_string()).unwrap();
1045        fs::write(record_path(&root, "0.10.0"), rec(8.5).to_string()).unwrap();
1046        fs::write(root.join(RECORD_DIR).join("notes.md"), "ignored").unwrap();
1047        let (v, r) = latest_record(&root).unwrap();
1048        assert_eq!(v.to_string(), "0.10.0");
1049        let line = reading(v, &r).unwrap();
1050        assert!(
1051            line.contains("10 contexts 1 ms, 200 contexts 8.5 ms;"),
1052            "{line}"
1053        );
1054    }
1055}