perf(bench): smith-bench with callgrind instruction budgets, cargo x perf and bench, perf CI job, report sections
5f9e275d2cd436e02e29a11803ea0d5963deb658
Oliver Jan Krylow <oliver@bugabinga.net> ·
unsigned
- Parent 1: 0926027b6ec3
There are many coding harnesses - but this one is fast
5f9e275d2cd436e02e29a11803ea0d5963deb658
Oliver Jan Krylow <oliver@bugabinga.net> ·
unsigned
+1454 / −91 text lines
new file mode 100644+11 / −0 text lines
+5 / −1 text lines
- golden corpus: checked-in sessions; replay and trace byte-identical; regenerated only with a frame-version bump. - instruction budgets: callgrind instruction counts per hot path (`gungraun`), pinned in `smith-bench/budgets.toml` with a ±2 % band; a regression fails, an improvement fails until re-pinned; re-pins are deliberate commits, toolchain bumps the expected trigger. - wall clock: `criterion` and `hyperfine` compare two builds on one machine in one session; numbers are never committed and never gate. - coverage: `cargo-llvm-cov` over every tier; reported per push as a diff, never a percentage gate; uncovered spec sentences are the backlog.- Tiers: `cargo x test` (unit, property, snapshot, bounds; every commit) → `cargo x e2e` (binary; every push) → `cargo x coverage` (report) → nightly (`mutants`, golden regeneration check).- Tiers: `cargo x test` (unit, property, snapshot, bounds; every commit) → `cargo x e2e` (binary; every push) → `cargo x perf` (instruction budgets; every push) → `cargo x coverage` (report) → nightly (`mutants`, golden regeneration check).- Evidence bundles: `cargo x report` collects every tier (JUnit, coverage, last mutation run) into `target/report/`; the nightly job and a manual `report` job publish it.smith-harness/ orchestration, wasm plugin host, plugin system, SDK, event bridge, built-ins, helpsmith-bench/ benchmarks: instruction budgets, wall-clock A/B; never shipped- `smith-bench`: any workspace crate; nothing depends on it.new file mode 100644+49 / −0 text lines
---id: SMH-PLAN-2_O9OFR0type: plantitle: "Benchmarking: Budgets, A/B, Profiling"spec: SMH-SPEC-SPEC0001status: approveddepends_on: [SMH-PLAN-DFOG846Z]---# Benchmarking: Budgets, A/B, Profiling## Entry- RULES `## Testing` names instruction budgets and wall-clock A/B; `## Memory` says the allocator is a benchmark result.- Spec targets: help within 100 ms, frames within 16 ms, encoding 1,000 entries within 5 ms.- Allocation-count bounds exist (`smith-alloc`); one criterion bench exists (`smith/benches/message_creation.rs`).- `target-cpu=native` from the user config is not applied in this repo, so instruction counts depend on the toolchain, not the machine.## Decisions- Three signals, each where it is strong: allocation counts (exact, tests), instruction counts (`gungraun` over callgrind, exact per toolchain, CI gate), wall clock (`criterion`, `hyperfine`, local A/B, never committed).- Budgets are pinned per bench in `smith-bench/budgets.toml`; the gate is a ±2 % band on `Ir`; both directions fail so pins stay honest; re-pin is a deliberate commit.- One workspace member `smith-bench` owns every bench; it depends on any workspace crate; nothing depends on it; it is a default member so `cargo x check` type-checks benches (`cargo test --benches` is not run).- `gungraun-runner` is a build tool installed by xtask at a pinned version matching the crate.- Wall-clock spec targets are informational rows in the report bundle, never a gate.## Order1. `smith-bench` crate: library benches for frame encode and decode of 1,000 entries, `Session::from_frames`, `fork_at`, agent request build with masking, one SSE fixture per adapter, `canonical_json`, `handle_line`; binary bench for `smith --help` and `smith eval --mock`; criterion bench moved from `smith`.2. `budgets.toml`: one `ir` pin per bench id, written by `cargo x perf --pin`.3. `cargo x perf`: install runner, run gungraun benches with `--save-summary=json`, compare every `Ir` to its pin within ±2 %, write `target/report/perf.md`; `--pin` rewrites budgets; `cargo x bench` runs criterion with passthrough.4. CI: `.ci/perf.kdl` per push (valgrind installed in the job); `report` bundle gains the perf section and a hyperfine row for `smith --help` and `smith eval --mock`.5. Research note and TO_DISCUSS cleanup; deslop and compress passes.## Interfaces- `xtask`: `perf [--pin]`, `bench [args]`; `bootstrap` installs `gungraun-runner`.- `smith-bench/budgets.toml`: `[<file>::<group>::<function>::<id>] ir = N`.- `.ci/perf.kdl`.## Risks- Callgrind runs are slow; the set stays small and every bench runs one shot.- Toolchain bumps shift counts; the re-pin commit names the toolchain.- Binary benches include process start-up; that is the point for `--help`, noise for anything else.## Exit- `cargo x perf` green with pins; CI `perf` job observed; report bundle carries the perf section.new file mode 100644+111 / −0 text lines
---id: SMH-RESEARCH-UPU3A0HOtype: researchtitle: "Benchmarking: First Instruction Pins and Measurement Notes"---# Benchmarking: First Instruction Pins and Measurement NotesDate: 2026-09-26.Status: evidence from implementing SMH-PLAN-2_O9OFR0; candidates, not mandates.## Setup- Machine: AMD Ryzen 5 5600X, CachyOS, kernel 7.2.7, glibc 2.44, valgrind 3.25.1.- Toolchain: `rustc 1.98.1 (48a229cea 2026-09-01)`, bench profile (release, thin LTO, one codegen unit, line tables, not stripped).- `gungraun` 0.19.4 and `gungraun-runner` 0.19.4 (installed by `cargo x bootstrap` or `cargo x perf` through `cargo-binstall`).- Callgrind runs with `--cache-sim=no`: the gate reads only `Ir`, and cache simulation only adds run time.- `target-cpu=native` is not applied in this repo (`.cargo/config.toml` sets no `target-cpu`), so codegen is the generic x86-64 baseline.## Pinned instruction countsPinned by `cargo x perf --pin`, stored in `smith-bench/budgets.toml`.| bench | Ir | spread seen run to run ||---|---:|---|| `instructions::agent::run_turn::history_1000_masked` | 11270600 | ≈ 0.1 % || `instructions::providers::sse::anthropic` | 109026 | ≤ 0.18 % || `instructions::providers::sse::gemini` | 47234 | ≤ 0.01 % || `instructions::providers::sse::openai` | 81236 | identical || `instructions::rpc::handle_line::ping` | 6885 | ≈ 1.5 % (6861 to 6965) || `instructions::session::canonical_json::nested` | 1138903 | ≤ 0.05 % || `instructions::session::decode::linear_1000` | 11056510 | identical || `instructions::session::decode::tool_calls_1000` | 10284262 | identical || `instructions::session::encode::linear_1000` | 5736448 | identical || `instructions::session::encode::tool_calls_1000` | 5133175 | identical || `instructions::session::fork_at::linear_1000` | 232844 | ≤ 0.03 % || `instructions::session::from_frames::linear_1000` | 1392615 | ≤ 0.07 % || `startup::cli::smith::eval_mock` | 1156689 | ≈ 0.1 % || `startup::cli::smith::help` | 741164 | identical |Spreads come from about fifteen runs on the machine above, direct `cargo bench` and `cargo x perf` combined.Every bench stays well inside the ±2 % band except `handle_line::ping`, whose 1.5 % spread leaves little margin.## Why some library counts are not identicalInstruction counts are exact only for code whose path does not depend on ambient randomness or time.Three sources were found in the measured code, not in the harness:- `std::collections::HashMap` and `IndexMap` (serde_json `preserve_order`) seed `RandomState` per process; probe sequences, and so instruction counts, change with the seed (`Session::from_frames`, every `serde_json` object parse, `handle_line`).- `Uuid::now_v7` takes a different branch when two IDs fall into the same millisecond (`fork_at`, `EntryFrame::new`, `run_turn`, decoders that mint a `MessageId`).- glibc `malloc` and `free` paths depend on arena state.`ping` shows it most because it is small (≈ 7,000 instructions) and dominated by one JSON parse, one `IndexMap` insert per key, and allocator calls.## Environment findings- gungraun clears the environment of every bench but keeps `LD_LIBRARY_PATH`. `cargo run` (so every `cargo x` command) prepends library directories to it, and the dynamic loader walks each entry at start-up. The same `smith --help` binary measured 753,965 `Ir` through plain `cargo bench` and 760,523 through `cargo x perf`. `startup.rs` now sets `LD_LIBRARY_PATH` empty for the measured command; both launch paths then read 741,164.- `cargo x` children inherit `CARGO_MANIFEST_DIR=xtask` from `cargo run`. `ring`'s build script tracks that variable, so alternating `cargo x perf` with a plain `cargo build --release` rebuilds `ring`, `rustls`, `ureq`, `smith-harness`, and `smith-cli` each time (≈ 25 s here). The binary stays byte-identical; only time is lost. This predates the change and affects every `cargo x` subcommand that runs cargo.- Instruction counts depend on the toolchain, the codegen flags, and the C library. Start-up benches count the dynamic loader and libc initialization; every bench counts glibc `malloc`, `free`, `memcpy`, and `memchr`, whose implementation glibc selects at run time from the CPU features valgrind reports. Pins taken on this machine are therefore not guaranteed to hold in the `docker.io/library/rust:latest` CI image (Debian glibc).## Run time- `cargo x perf`, warm (both builds cached): 3.2 s wall, of which the fourteen callgrind runs take about 3 s.- `cargo x perf`, cold on this machine: the release `smith` build took 2 min 42 s and the bench build 48 s, then the same 3 s of runs.- `cargo x report` with hyperfine present: 52 s here (coverage tiers dominate).## Summary field path`--output-format=json` prints one line per bench (summary schema version `"6"`); `--save-summary=json` writes the same object to `target/gungraun/smith-bench/<file>/<group>/<function>.<id>/summary.json`.- Bench key: top-level `module_path` (`<file>::<group>::<function>`) plus `::` plus top-level `id`.- Total `Ir`: `profiles[0].summaries.total.summary.Callgrind.Ir.metrics`, which is `{"Left":{"Int":n}}` on a first run and `{"Both":[{"Int":n},{"Int":previous}]}` once gungraun has a previous run; the new value is the first `Int`.`xtask` has no JSON dependency, so `cargo x perf` reads the stdout lines with a small anchor-based extractor (`bench_ir`): the first `"module_path":"…"` and `"id":"…"`, then the first `{"Int":…}` after `"total":` → `"Ir":` → `"metrics":`.Bench names carry no escapes, and JSON string escaping keeps these anchors from matching inside the `details` strings.A line starting with `{` that the extractor cannot read fails the gate, so schema drift surfaces as a failure rather than a silent pass.Reading the per-bench `summary.json` files instead would need the same extractor plus a directory walk; the stdout lines were simpler.## Deviations from the plan and assignment- Two gungraun bench files instead of one: `main!` accepts either library or binary groups, never both, so `instructions.rs` holds the library groups and `startup.rs` the binary group.- `cargo x perf` selects `--bench instructions --bench startup` instead of `--benches`: `--benches` would also start the criterion harness with gungraun's arguments, and cargo passes the same arguments to every selected target. The fixture library sets `bench = false` for the same reason.- Agent request build is measured through `Agent::run_turn`: `build_request` is private, and `run_turn` is its smallest public seam. The bench runs one turn over 1,000 recorded messages with a registered secret; it also records the user message and a one-delta reply, which is small next to decoding and masking 1,000 messages. The history holds no plaintext secret, which matches real sessions: recording masks input first, so masking at request build scans every message and replaces nothing.- `canonical_json` is private; the bench records a tool call with a four-level, reverse-ordered nested input through `EntryFrame::new`, which canonicalizes before encoding.- The SSE fixtures are literal copies of the adapters' conformance fixture lines: those live in `#[cfg(test)]` modules and are not reachable from another crate.- Frame encode and decode are two benches (`encode`, `decode`), each for a linear chat and a tool-call session of 1,000 entries.- The criterion bench moved from `smith/benches/message_creation.rs` to `smith-bench/benches/wall_clock.rs`.- `budgets.toml` uses one `"<bench>" = { ir = <n> }` line per bench under `[budgets]`; no per-bench `band` key was needed, because no bench, binary benches included, varied by more than 2 % run to run.- The report's wall-clock section also exports `hyperfine.md` (hyperfine's own markdown table) next to `hyperfine.json`, so xtask needs no JSON parser for it; a `--prepare` step empties the profile before each run, because `smith eval` appends to its session file otherwise.## Candidates- Pin in the CI image, not on a workstation, if the first CI `perf` run disagrees with these pins; then run `cargo x perf` locally in that image to compare.- Widen `handle_line::ping` only if it ever leaves the band, or measure a batch of lines so hashing noise averages out.- Remove `CARGO_MANIFEST_DIR` from the environment of cargo children in xtask to stop the `ring` rebuild ping-pong.## Sources- [gungraun guide](https://gungraun.github.io/gungraun/latest/html/): default environment clearing, entry points, binary benchmarks, command-line arguments, machine-readable output.- `gungraun-runner` 0.19.4 source, `src/runner/args.rs`: environment clearing preserves `LD_PRELOAD` and `LD_LIBRARY_PATH`.+147 / −1 text lines
[[package]]name = "derive_more"version = "2.1.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d751e9e49156b02b44f9c1815bcb94b984cdcc4396ecc32521c739452808b134"dependencies = [ "derive_more-impl",][[package]]name = "derive_more-impl"version = "2.1.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "799a97264921d8623a957f6c3b9011f3b5492f557bbb7a5a19b7fa6d06ba8dcb"dependencies = [ "proc-macro2", "quote", "rustc_version", "syn 2.0.119",][[package]]name = "gungraun"version = "0.19.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "9300d38d30facf6870c15bc9e243edcc47e5ddc270c9d2c1ae824a00b1faea79"dependencies = [ "bincode-next", "derive_more", "gungraun-macros", "gungraun-runner",][[package]]name = "gungraun-macros"version = "0.9.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d7f3214bae6cfd6739f4f29edb262bae439c6393a7b7b12c4eeb96417c2e50df"dependencies = [ "derive_more", "proc-macro-error3", "proc-macro2", "quote", "rustc_version", "serde", "serde_json", "syn 2.0.119",][[package]]name = "gungraun-runner"version = "0.19.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "47c68c92812da579a2510a2cc702d5aa3251992b9662d4a98502ca46e0cbe16e"dependencies = [ "either-or-both", "serde",][[package]]name = "proc-macro-error-attr3"version = "3.1.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "9e564d14133360e1ae169ffde5da25881b5fa47261665b8e5713c212c27799da"dependencies = [ "proc-macro2", "quote",][[package]]name = "proc-macro-error3"version = "3.1.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "8f0d4471b3436c22106b21913b1dda531558918ae9b7ec55d58aa84b43552233"dependencies = [ "proc-macro-error-attr3", "proc-macro2", "quote", "syn 3.0.6",] "criterion",+9 / −0 text lines
+1 / −1 text lines
- Guest std ergonomics: sealed wasi shims for io, clocks, cli landed (SMH-SPEC-WASM0001 Sealed WASI); random, wall-clock, filesystem, sockets substitutes land on demand when a guest needs them. Trigger: first non-echo guest failing instantiation.- Benchmarking: regression detection + learning, relative comparisons, in-repo baselines, no machine-specific numbers. Trigger: RELS planning.- Benchmarking: moved to SMH-PLAN-2_O9OFR0 (`.system/plans/SMH-PLAN-2_O9OFR0-benchmarking/`).new file mode 100644+39 / −0 text lines
[package]name = "smith-bench"edition.workspace = trueversion.workspace = truelicense.workspace = truepublish = false# No libtest bench harness for the fixture library: it would reject the# runner arguments `cargo bench` passes to every selected target.[lib]path = "src/lib.rs"bench = false# Fixture builders need the benched crates as library dependencies.[dependencies]smith = { path = "../smith", version = "0.1.0" }smith-core = { path = "../smith-core", version = "0.1.0" }smith-ai = { path = "../smith-ai", version = "0.1.0" }smith-rpc = { path = "../smith-rpc", version = "0.1.0" }futures = { workspace = true }serde_json = { workspace = true }[dev-dependencies]gungraun = { workspace = true }criterion = { workspace = true }# Instruction budgets: callgrind through gungraun, gated by `cargo x perf`.[[bench]]name = "instructions"harness = false[[bench]]name = "startup"harness = false# Wall clock: criterion A/B through `cargo x bench`; never gates.[[bench]]name = "wall_clock"harness = falsenew file mode 100644+161 / −0 text lines
//! Instruction budgets per hot path (`SMH-SPEC-SPEC0001`, Performance and//! portability): callgrind counts through gungraun, pinned in//! `smith-bench/budgets.toml` and gated by `cargo x perf` within ±2 %.//!//! Sizes follow the spec targets: 1,000 entries for encoding and restore,//! one provider stream per adapter, one RPC line. Every bench takes its//! input from a setup and returns what it built, so neither construction//! nor drop is counted. Process start-up lives in `startup.rs`.#![expect( missing_docs, reason = "gungraun benchmark macros generate undocumented public modules and items")]use gungraun::Callgrind;use gungraun::prelude::*;use smith_ai::{AnthropicDecoder, GeminiDecoder, OpenAiDecoder, StreamDecoder};use smith_bench::{ anthropic_sse, frames_of, gemini_sse, linear_session, masked_agent, nested_json, openai_sse, tool_call_session,};use smith_core::agent::Agent;use smith_core::frame::{DEFAULT_MAX_FRAME_BYTES, Frame, Recovery, encode_entry, read_frames};use smith_core::session::{EntryContent, EntryFrame, Session};use smith_rpc::RpcState;use std::hint::black_box;fn linear(len: usize) -> Session { linear_session(len).expect("linear session")}fn tool_calls(pairs: usize) -> Session { tool_call_session(pairs).expect("tool-call session")}/// A session and its entries encoded back to back, as a store file holds/// them.fn encoded(session: Session) -> (Session, Vec<u8>) { let bytes = encode_all(&session); (session, bytes)}fn encode_all(session: &Session) -> Vec<u8> { let mut out = Vec::new(); for entry in session.active_branch().entries() { let frame = encode_entry(entry, session.bytes(entry), DEFAULT_MAX_FRAME_BYTES) .expect("entry encodes"); out.extend_from_slice(&frame); } out}#[library_benchmark]#[bench::linear_1000(linear(1000))]#[bench::tool_calls_1000(tool_calls(500))]fn encode(session: Session) -> (Session, Vec<u8>) { let bytes = encode_all(black_box(&session)); (session, black_box(bytes))}#[library_benchmark]#[bench::linear_1000(encoded(linear(1000)))]#[bench::tool_calls_1000(encoded(tool_calls(500)))]fn decode(input: (Session, Vec<u8>)) -> ((Session, Vec<u8>), Recovery) { let recovery = read_frames(&mut black_box(input.1.as_slice()), DEFAULT_MAX_FRAME_BYTES); (input, black_box(recovery))}#[library_benchmark]#[bench::linear_1000(frames_of(&linear(1000)))]fn from_frames(frames: Vec<Frame>) -> (Vec<Frame>, Session) { let session = Session::from_frames(black_box(&frames)).expect("frames restore"); (frames, black_box(session))}#[library_benchmark]#[bench::linear_1000(linear(1000))]fn fork_at(session: Session) -> (Session, Session) { let leaf = session.selected_id().expect("non-empty session"); let fork = session.fork_at(black_box(leaf)).expect("leaf is known"); (session, black_box(fork))}/// Tool-call content with a nested, non-canonical input: recording it/// canonicalizes the input before encoding (`canonical_json` is private;/// `EntryFrame::new` is its public seam).fn tool_call_with(input: serde_json::Value) -> EntryContent { EntryContent::ToolCall { name: "write".to_string(), input, call_id: smith::ToolCallId::new(), }}#[library_benchmark]#[bench::nested(tool_call_with(nested_json(4)))]fn canonical_json(content: EntryContent) -> (EntryContent, EntryFrame) { let frame = EntryFrame::new(None, black_box(&content)).expect("content encodes"); (content, black_box(frame))}library_benchmark_group!( name = session, benchmarks = [encode, decode, from_frames, fork_at, canonical_json]);fn masked(history: usize) -> Agent { masked_agent(history).expect("agent history")}// One turn over a long history: the request build decodes and masks// every message since the compaction boundary (`build_request` is// private; `run_turn` is its smallest public seam and adds recording the// user message and the one-delta reply).#[library_benchmark]#[bench::history_1000_masked(masked(1000))]fn run_turn(mut agent: Agent) -> Agent { let outcome = agent.run_turn(black_box("next step, please")); black_box(outcome.expect("turn settles")); agent}library_benchmark_group!(name = agent, benchmarks = [run_turn]);fn stream_of(decoder: Box<dyn StreamDecoder>, bytes: Vec<u8>) -> (Box<dyn StreamDecoder>, Vec<u8>) { (decoder, bytes)}// One fixture stream through a fresh adapter, in one chunk, to its stop.#[library_benchmark]#[bench::openai(stream_of(Box::new(OpenAiDecoder::new()), openai_sse()))]#[bench::anthropic(stream_of(Box::new(AnthropicDecoder::new()), anthropic_sse()))]#[bench::gemini(stream_of(Box::new(GeminiDecoder::new()), gemini_sse()))]fn sse(input: (Box<dyn StreamDecoder>, Vec<u8>)) -> (Vec<u8>, Vec<smith::StreamEvent>) { let (mut decoder, bytes) = input; let mut events = decoder.push(black_box(&bytes)).expect("stream decodes"); events.extend(decoder.finish().expect("stream stops")); (bytes, black_box(events))}library_benchmark_group!(name = providers, benchmarks = [sse]);fn rpc_state() -> RpcState { RpcState::new(masked(0))}// One control line through the reader; the agent worker thread is idle// and not counted.#[library_benchmark]#[bench::ping(rpc_state())]fn handle_line(mut state: RpcState) -> (RpcState, Vec<String>) { let lines = smith_rpc::handle_line(&mut state, black_box(r#"{"id":1,"method":"ping"}"#)); (state, black_box(lines))}library_benchmark_group!(name = rpc, benchmarks = [handle_line]);main!( config = LibraryBenchmarkConfig::default().tool(Callgrind::with_args(["--cache-sim=no"])), library_benchmark_groups = [session, agent, providers, rpc]);new file mode 100644+57 / −0 text lines
//! Instruction budgets of process start-up (`SMH-SPEC-SPEC0001`,//! Performance and portability: help within 100 ms): the release binary//! under callgrind, pinned in `smith-bench/budgets.toml` and gated by//! `cargo x perf`.//!//! Start-up is the measurement here, so the whole process counts. The//! binary comes from `SMITH_BIN`, which `cargo x perf` builds and sets.//! Every run gets fresh, empty XDG roots and, gungraun clearing the//! environment, no provider variable: the e2e tests' isolation. The//! clearing keeps `LD_LIBRARY_PATH`, which `cargo run` (so `cargo x`)//! extends; the dynamic loader walks every entry, so it is emptied to//! keep start-up counts independent of how the bench was launched.#![expect( missing_docs, reason = "gungraun benchmark macros generate undocumented public modules and items")]use gungraun::Callgrind;use gungraun::prelude::*;use std::path::{Path, PathBuf};/// Profile root of every run, under cargo's per-target scratch directory.fn home() -> PathBuf { Path::new(env!("CARGO_TARGET_TMPDIR")).join("smith-bench-home")}/// An empty profile, so no run sees what an earlier one left behind.fn fresh_home() { let home = home(); let _ = std::fs::remove_dir_all(&home); std::fs::create_dir_all(&home).expect("profile root");}#[binary_benchmark(setup = fresh_home())]#[bench::help(&["--help"])]#[bench::eval_mock(&["eval", "--mock", "hello"])]fn smith(args: &[&str]) -> gungraun::Command { let binary = std::env::var("SMITH_BIN") .expect("SMITH_BIN names the release smith binary; run `cargo x perf`"); let home = home(); gungraun::Command::new(binary) .args(args) .env("XDG_CONFIG_HOME", home.join("config")) .env("XDG_DATA_HOME", home.join("data")) .env("XDG_STATE_HOME", home.join("state")) .env("XDG_CACHE_HOME", home.join("cache")) .env("LD_LIBRARY_PATH", "") .build()}binary_benchmark_group!(name = cli, benchmarks = smith);main!( config = BinaryBenchmarkConfig::default().tool(Callgrind::with_args(["--cache-sim=no"])), binary_benchmark_groups = cli);new file mode 100644+31 / −0 text lines
//! Wall-clock benches for local A/B comparisons (`SMH-SPEC-SPEC0001`,//! Performance and portability): criterion through `cargo x bench`.//!//! Numbers answer "faster here, now" on one machine in one session; they//! are never committed and never gate. Compare two builds with//! `cargo x bench -- --save-baseline <change>` then `--baseline <change>`.use criterion::{Criterion, criterion_main};use smith::{Message, MessageId, Role};use std::hint::black_box;fn message_creation(criterion: &mut Criterion) { let mut group = criterion.benchmark_group("message_creation"); group.bench_function("message_id", |bencher| { bencher.iter(|| black_box(MessageId::new())); }); group.bench_function("empty_message", |bencher| { bencher.iter(|| black_box(Message::new(Role::Assistant))); }); group.bench_function("text_message", |bencher| { bencher.iter(|| black_box(Message::with_text(Role::User, "benchmark text"))); }); group.finish();}fn benches() { let mut criterion = Criterion::default().configure_from_args(); message_creation(&mut criterion);}criterion_main!(benches);new file mode 100644+19 / −0 text lines
# Callgrind instruction budgets (Ir) per bench, gated within ±2 % by `cargo x perf`.# Written by `cargo x perf --pin`; a re-pin is a deliberate commit that says why.# Pinned with rustc 1.98.1 (48a229cea 2026-09-01).[budgets]"instructions::agent::run_turn::history_1000_masked" = { ir = 11270600 }"instructions::providers::sse::anthropic" = { ir = 109026 }"instructions::providers::sse::gemini" = { ir = 47234 }"instructions::providers::sse::openai" = { ir = 81236 }"instructions::rpc::handle_line::ping" = { ir = 6885 }"instructions::session::canonical_json::nested" = { ir = 1138903 }"instructions::session::decode::linear_1000" = { ir = 11056510 }"instructions::session::decode::tool_calls_1000" = { ir = 10284262 }"instructions::session::encode::linear_1000" = { ir = 5736448 }"instructions::session::encode::tool_calls_1000" = { ir = 5133175 }"instructions::session::fork_at::linear_1000" = { ir = 232844 }"instructions::session::from_frames::linear_1000" = { ir = 1392615 }"startup::cli::smith::eval_mock" = { ir = 1156689 }"startup::cli::smith::help" = { ir = 741164 }new file mode 100644+246 / −0 text lines
//! Shared fixtures for Smith benchmarks (`SMH-SPEC-SPEC0001`, Performance//! and portability).//!//! Benches live in `benches/`: `instructions` counts callgrind instructions//! against the pins in `budgets.toml` (`cargo x perf`), `wall_clock` runs//! criterion for local A/B comparisons (`cargo x bench`). Builders here run//! in bench setup, outside every measured region, and use only public API,//! so a bench measures what a caller of the crate gets.#![forbid(unsafe_code)]use futures::StreamExt;use smith::error::Result;use smith::id::{MessageId, ToolCallId};use smith::message::{Message, Role};use smith::stream::{StopReason, StreamEvent};use smith::{StreamFn, Usage};use smith_core::agent::Agent;use smith_core::frame::Frame;use smith_core::session::{EntryContent, EntryFrame, Session};use smith_core::tools::ToolSession;use std::sync::Arc;/// Plaintext the agent fixture registers as a secret.pub const SECRET: &str = "sk-bench-0123456789abcdef";/// A session of `len` chat messages, alternating user and assistant.////// # Errors////// Returns the session error of the first failed append.pub fn linear_session(len: usize) -> Result<Session> { let mut session = Session::new(); for turn in 0..len { let role = if turn % 2 == 0 { Role::User } else { Role::Assistant }; let message = Message::with_text(role, format!("turn {turn}: a short chat message")); session.append(&EntryContent::Message(message))?; } Ok(session)}/// A session of `pairs` tool calls, each followed by its result.////// # Errors////// Returns the session error of the first failed append.pub fn tool_call_session(pairs: usize) -> Result<Session> { let mut session = Session::new(); for call in 0..pairs { let call_id = ToolCallId::new(); session.append(&EntryContent::ToolCall { name: "read".to_string(), input: serde_json::json!({"path": format!("src/module_{call}.rs"), "limit": 200}), call_id, })?; session.append(&EntryContent::ToolResult { ok: true, output: format!("pub fn item_{call}() -> u32 {{ {call} }}\n"), call_id, })?; } Ok(session)}/// The decoded frames a store would read back for `session`: its header,/// then one entry frame per record of the active branch.#[must_use]pub fn frames_of(session: &Session) -> Vec<Frame> { let entries = session.active_branch().entries(); let mut frames = Vec::with_capacity(entries.len() + 1); frames.push(Frame::Header { header: session.header(), }); frames.extend(entries.iter().map(|entry| Frame::Known { entry: EntryFrame { id: entry.id, parent: entry.parent, timestamp_ms: entry.timestamp_ms, kind: entry.kind, content: session.bytes(entry).to_vec(), }, })); frames}/// A JSON value `depth` levels deep, four keys per object, every object/// in reverse key order so canonicalization has to reorder all of them.#[must_use]pub fn nested_json(depth: u32) -> serde_json::Value { let mut object = serde_json::Map::new(); for key in (0..4u32).rev() { let value = match (depth, key) { (0, _) => serde_json::Value::from(format!("leaf {key}")), (_, 0) => serde_json::json!([key, "item", {"z": depth, "a": key}]), _ => nested_json(depth - 1), }; object.insert(format!("key_{key}"), value); } serde_json::Value::Object(object)}/// An agent over a session of `history` messages with [`SECRET`]/// registered, whose provider answers every request with one text delta/// and a clean stop.////// # Errors////// Returns the session error of building the history.pub fn masked_agent(history: usize) -> Result<Agent> { let mut tools = ToolSession::new("."); tools.session = linear_session(history)?; let mut agent = Agent::new(scripted_reply(), tools, "bench-model"); agent.secrets_mut().register("api_key", SECRET); Ok(agent)}/// A provider that streams `ok` and stops, whatever the request.fn scripted_reply() -> StreamFn { Arc::new(|_request, _cancel| { let reply = MessageId::new(); futures::stream::iter([ Ok(StreamEvent::text_delta(reply, "ok")), Ok(StreamEvent::stop(StopReason::EndTurn, Some(Usage::new()))), ]) .boxed() })}/// SSE bytes: one `data:` event per payload.fn sse(payloads: &[&str]) -> Vec<u8> { let mut out = String::new(); for payload in payloads { out.push_str("data: "); out.push_str(payload); out.push_str("\n\n"); } out.into_bytes()}/// An `OpenAI` chat-completions stream: text, fragmented tool arguments,/// usage, done; the shapes of the adapter's conformance fixtures.#[must_use]pub fn openai_sse() -> Vec<u8> { sse(&[ r#"{"choices":[{"delta":{"role":"assistant","content":""}}]}"#, r#"{"choices":[{"delta":{"content":"Hello"}}]}"#, r#"{"choices":[{"delta":{"content":" world"}}]}"#, r#"{"choices":[{"delta":{"tool_calls":[{"index":0,"id":"a","function":{"name":"write","arguments":""}}]}}]}"#, r#"{"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"arguments":"{\"path\""}}]}}]}"#, r#"{"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"arguments":":\"f.txt\",\"content\":\"hi\"}"}}]}}]}"#, r#"{"choices":[{"delta":{},"finish_reason":"tool_calls"}]}"#, r#"{"choices":[],"usage":{"prompt_tokens":9,"completion_tokens":2,"prompt_tokens_details":{"cached_tokens":4}}}"#, "[DONE]", ])}/// An Anthropic Messages stream: text, thinking, assembled tool input,/// usage; the adapter's conformance fixture.#[must_use]pub fn anthropic_sse() -> Vec<u8> { sse(&[ r#"{"type":"message_start","message":{"usage":{"input_tokens":12}}}"#, r#"{"type":"content_block_start","index":0,"content_block":{"type":"text"}}"#, r#"{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"Look"}}"#, r#"{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"ing"}}"#, r#"{"type":"content_block_stop","index":0}"#, r#"{"type":"content_block_start","index":1,"content_block":{"type":"thinking"}}"#, r#"{"type":"content_block_delta","index":1,"delta":{"type":"thinking_delta","thinking":"hmm"}}"#, r#"{"type":"content_block_stop","index":1}"#, r#"{"type":"content_block_start","index":2,"content_block":{"type":"tool_use","id":"t","name":"write"}}"#, r#"{"type":"content_block_delta","index":2,"delta":{"type":"input_json_delta","partial_json":"{\"path\""}}"#, r#"{"type":"content_block_delta","index":2,"delta":{"type":"input_json_delta","partial_json":":[1,2]}"}}"#, r#"{"type":"content_block_stop","index":2}"#, r#"{"type":"message_delta","delta":{"stop_reason":"tool_use"},"usage":{"output_tokens":7,"cache_read_input_tokens":3}}"#, r#"{"type":"message_stop"}"#, ])}/// A Gemini stream: text around a complete function call, usage, stop;/// the adapter's conformance fixture.#[must_use]pub fn gemini_sse() -> Vec<u8> { sse(&[ r#"{"candidates":[{"content":{"parts":[{"text":"Writing"}]}}]}"#, r#"{"candidates":[{"content":{"parts":[{"functionCall":{"name":"write","args":{"path":"f","content":"hi"}}}]}}],"usageMetadata":{"promptTokenCount":5,"candidatesTokenCount":9,"cachedContentTokenCount":2}}"#, r#"{"candidates":[{"content":{"parts":[{"text":" now"}]}}]}"#, r#"{"candidates":[{"content":{},"finishReason":"STOP"}]}"#, ])}#[cfg(test)]#[expect( clippy::unwrap_used, reason = "tests may panic on invariant violations")]mod tests { use super::*; use smith_ai::{AnthropicDecoder, GeminiDecoder, OpenAiDecoder, StreamDecoder}; #[test] fn fixtures_have_the_sizes_benches_name() { let linear = linear_session(1000).unwrap(); assert_eq!(linear.active_branch().entries().len(), 1000); assert_eq!(frames_of(&linear).len(), 1001); let calls = tool_call_session(500).unwrap(); assert_eq!(calls.active_branch().entries().len(), 1000); } #[test] fn nested_json_is_not_canonical() { let value = nested_json(2); let keys: Vec<&String> = value.as_object().unwrap().keys().collect(); assert_eq!(keys, ["key_3", "key_2", "key_1", "key_0"]); } #[test] fn every_sse_fixture_decodes_to_a_clean_stop() { let cases: [(Box<dyn StreamDecoder>, Vec<u8>); 3] = [ (Box::new(OpenAiDecoder::new()), openai_sse()), (Box::new(AnthropicDecoder::new()), anthropic_sse()), (Box::new(GeminiDecoder::new()), gemini_sse()), ]; for (mut decoder, bytes) in cases { let mut events = decoder.push(&bytes).unwrap(); events.extend(decoder.finish().unwrap()); assert!( matches!(events.last(), Some(StreamEvent::Stop { .. })), "{events:?}" ); } } #[test] fn masked_agent_answers_a_turn() { let mut agent = masked_agent(10).unwrap(); agent.run_turn(format!("use {SECRET}")).unwrap(); let entries = agent.session().active_branch().entries(); assert_eq!(entries.len(), 12); let input = agent.session().content(&entries[10]).unwrap(); assert!(!format!("{input:?}").contains(SECRET), "{input:?}"); }}+0 / −5 text lines
deleted file mode 100644+0 / −26 text lines
//! Message-construction benchmarks.use criterion::{Criterion, criterion_main};use smith::{Message, MessageId, Role};use std::hint::black_box;fn message_creation(criterion: &mut Criterion) { let mut group = criterion.benchmark_group("message_creation"); group.bench_function("message_id", |bencher| { bencher.iter(|| black_box(MessageId::new())); }); group.bench_function("empty_message", |bencher| { bencher.iter(|| black_box(Message::new(Role::Assistant))); }); group.bench_function("text_message", |bencher| { bencher.iter(|| black_box(Message::with_text(Role::User, "benchmark text"))); }); group.finish();}fn benches() { let mut criterion = Criterion::default().configure_from_args(); message_creation(&mut criterion);}criterion_main!(benches);+568 / −57 text lines
"usage: cargo x <check|lint|fmt|test|e2e|coverage|report|doc|arch|mutants [args...]|audit|ci|release|bootstrap>\n",/// Version of `gungraun-runner`; must match the `gungraun` crate in the lockfile.const GUNGRAUN_VERSION: &str = "0.19.4";/// gungraun bench targets of `smith-bench`, gated by `cargo x perf`.const INSTRUCTION_BENCHES: &[&str] = &["instructions", "startup"];/// criterion bench target of `smith-bench`, run by `cargo x bench`.const WALL_CLOCK_BENCH: &str = "wall_clock";/// Instruction pins, one per gungraun bench.const BUDGETS: &str = "smith-bench/budgets.toml";/// Allowed deviation of a measured `Ir` from its pin, either direction.const BAND_PERCENT: u64 = 2;/// Provider selection and credential variables that never reach a/// measured `smith` run.const PROVIDER_VARS: &[&str] = &[ "SMITH_PROVIDER", "SMITH_MODEL", "SMITH_BASE_URL", "ANTHROPIC_API_KEY", "OPENAI_API_KEY", "GEMINI_API_KEY",]; "smith-bench", let installed = tool_present_bin("cargo-mutants", MUTANTS_VERSION, || { cargo(&[ "binstall", "--no-confirm", &format!("cargo-mutants@{MUTANTS_VERSION}"), ]) }); let installed = install_mutants(&[]); // `cargo x mutants -- -f x` and `cargo x mutants -f x` are equivalent: // a leading separator is stripped so cargo-run habits cannot turn // scope flags into stray nextest test filters. let extra: Vec<OsString> = if extra.first().is_some_and(|arg| arg == "--") { extra[1..].to_vec() } else { extra.to_vec() };/// Instruction budgets: every gungraun bench's callgrind `Ir` against its/// pin in `smith-bench/budgets.toml`, within ±2 % in either direction, so/// a regression fails and an improvement fails until re-pinned.////// `--pin` rewrites the pins from this run instead of gating. Other/// arguments go to the gungraun runner; a filter narrows the run, and pins/// of benches it skipped are kept rather than reported stale. Every run/// writes `target/report/perf.md`.fn perf(extra: &[OsString]) -> ExitCode { let repin = extra.iter().any(|arg| arg == "--pin"); let passthrough: Vec<OsString> = without_separator(extra) .iter() .filter(|arg| *arg != "--pin") .cloned() .collect(); let installed = install_gungraun_runner(&[]); if installed != ExitCode::SUCCESS { return installed; } let smith = match release_smith() { Ok(path) => path, Err(code) => return code, }; let measured = match instruction_counts(&smith, &passthrough) { Ok(measured) => measured, Err(message) => return fail(&message), }; let pins = match fs::read_to_string(BUDGETS) { Ok(text) => parse_budgets(&text), Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(BTreeMap::new()), Err(error) => Err(format!("cannot read {BUDGETS}: {error}")), }; let pins = match pins { Ok(pins) => pins, Err(message) => return fail(&format!("{message}\n")), }; let complete = passthrough.is_empty(); let toolchain = toolchain(); let written = write_perf_report(&measured, &pins, complete, &toolchain); if written != ExitCode::SUCCESS { return written; } if repin { let mut pinned = if complete { BTreeMap::new() } else { pins }; pinned.extend(measured); if fs::write(BUDGETS, render_budgets(&pinned, &toolchain)).is_err() { return fail(&format!("cannot write {BUDGETS}\n")); } note(&format!( "perf: pinned {} benches in {BUDGETS}\n", pinned.len() )); return ExitCode::SUCCESS; } let violations = budget_violations(&measured, &pins, complete); if violations.is_empty() { note(&format!( "perf: {} benches within ±{BAND_PERCENT} % of their pins\n", measured.len() )); ExitCode::SUCCESS } else { fail(&format!( "instruction budgets violated (re-pin deliberately with `cargo x perf --pin`):\n{}", violations.concat() )) }}/// Wall clock: the criterion benches, for A/B comparisons of two builds/// on one machine in one session. Numbers are never committed and never/// gate. Arguments go to criterion, e.g. `--save-baseline <change>`.fn bench(extra: &[OsString]) -> ExitCode { let mut args: Vec<OsString> = [ "bench", "--locked", "-p", "smith-bench", "--bench", WALL_CLOCK_BENCH, "--", ] .map(OsString::from) .to_vec(); args.extend_from_slice(without_separator(extra)); run_os("cargo", &args)}/// Build the release `smith` binary and return its absolute path.fn release_smith() -> Result<PathBuf, ExitCode> { let built = cargo(&[ "build", "--locked", "--release", "-p", "smith-cli", "--bin", "smith", ]); if built != ExitCode::SUCCESS { return Err(built); } let binary = target_dir().join("release").join(binary_name()); std::path::absolute(&binary) .map_err(|error| fail(&format!("cannot resolve {}: {error}\n", binary.display())))}/// Run the gungraun benches against `smith` and collect every bench's/// `Ir` from the JSON summary lines on standard output.fn instruction_counts( smith: &Path, passthrough: &[OsString],) -> Result<BTreeMap<String, u64>, String> { let mut command = Command::new("cargo"); command.args(["bench", "--locked", "-p", "smith-bench"]); for bench in INSTRUCTION_BENCHES { command.args(["--bench", bench]); } command .args(["--", "--save-summary=json", "--output-format=json"]) .args(passthrough) .env("SMITH_BIN", smith) .stderr(std::process::Stdio::inherit()); let output = command .output() .map_err(|error| format!("failed to run cargo bench: {error}\n"))?; if !output.status.success() { // Exit code 3 is gungraun's own regression verdict from limits // passed through; anything else is a build or runner failure. return Err(format!("cargo bench exited with {}\n", output.status)); } let stdout = String::from_utf8_lossy(&output.stdout); let mut measured = BTreeMap::new(); for line in stdout.lines().filter(|line| line.starts_with('{')) { let Some((bench, ir)) = bench_ir(line) else { return Err(format!("unrecognized gungraun summary line: {line}\n")); }; measured.insert(bench, ir); } if measured.is_empty() { return Err("gungraun reported no benches\n".to_string()); } Ok(measured)}/// `(<module_path>::<id>, Ir)` of one gungraun `--output-format=json`/// line (summary schema v6). `module_path` and `id` are top-level strings;/// the total `Ir` is the first integer under `total` → `Ir` → `metrics`,/// which reads `{"Left":{"Int":n}}` on a first run and/// `{"Both":[{"Int":n},{"Int":previous}]}` once a previous run exists.fn bench_ir(line: &str) -> Option<(String, u64)> { let module = json_string(line, "module_path")?; let id = json_string(line, "id")?; let after = |text: &'_ str, anchor: &str| -> Option<usize> { text.find(anchor).map(|at| at + anchor.len()) }; let total = &line[after(line, "\"total\":")?..]; let ir = &total[after(total, "\"Ir\":")?..]; let metrics = &ir[after(ir, "\"metrics\":")?..]; let int = &metrics[after(metrics, "{\"Int\":")?..]; let digits = &int[..int.find(|c: char| !c.is_ascii_digit())?]; Some((format!("{module}::{id}"), digits.parse().ok()?))}/// The first string value of `key`; bench names carry no escapes.fn json_string<'a>(line: &'a str, key: &str) -> Option<&'a str> { let anchor = format!("\"{key}\":\""); let rest = &line[line.find(&anchor)? + anchor.len()..]; rest.find('"').map(|end| &rest[..end])}/// Pins of `budgets.toml`: a `[budgets]` table of/// `"<file>::<group>::<function>::<id>" = { ir = <n> }` lines, the shape/// `--pin` writes; any other line is rejected rather than guessed at.fn parse_budgets(text: &str) -> Result<BTreeMap<String, u64>, String> { let mut pins = BTreeMap::new(); let mut in_table = false; for (number, line) in text.lines().enumerate() { let line = line.trim(); if line.is_empty() || line.starts_with('#') { continue; } if line == "[budgets]" { in_table = true; continue; } let Some((bench, ir)) = in_table.then(|| budget_line(line)).flatten() else { return Err(format!( "{BUDGETS}:{}: expected `\"<bench>\" = {{ ir = <n> }}` under [budgets]", number + 1 )); }; if pins.insert(bench.to_string(), ir).is_some() { return Err(format!("{BUDGETS}:{}: {bench} pinned twice", number + 1)); } } Ok(pins)}fn budget_line(line: &str) -> Option<(&str, u64)> { let (bench, rest) = line.strip_prefix('"')?.split_once('"')?; let table = rest.trim_start().strip_prefix('=')?.trim(); let fields = table.strip_prefix('{')?.strip_suffix('}')?.trim(); let ir = fields .strip_prefix("ir")? .trim_start() .strip_prefix('=')? .trim(); Some((bench, ir.parse().ok()?))}fn render_budgets(pins: &BTreeMap<String, u64>, toolchain: &str) -> String { use std::fmt::Write as _; let mut out = format!( "# Callgrind instruction budgets (Ir) per bench, gated within ±{BAND_PERCENT} % by `cargo x perf`.\n\ # Written by `cargo x perf --pin`; a re-pin is a deliberate commit that says why.\n\ # Pinned with {toolchain}.\n\n[budgets]\n" ); for (bench, ir) in pins { let _ = writeln!(out, "\"{bench}\" = {{ ir = {ir} }}"); } out}/// One line per bench outside its band, without a pin, or, when every/// bench ran, pinned but no longer measured.fn budget_violations( measured: &BTreeMap<String, u64>, pins: &BTreeMap<String, u64>, complete: bool,) -> Vec<String> { let mut violations = Vec::new(); for (bench, ir) in measured { match pins.get(bench) { None => violations.push(format!(" {bench}: measured {ir}, no pin\n")), Some(pin) if !within_band(*pin, *ir) => violations.push(format!( " {bench}: pin {pin}, measured {ir}, delta {} (band ±{BAND_PERCENT} %)\n", delta(*pin, *ir) )), Some(_) => {} } } if complete { for (bench, pin) in pins { if !measured.contains_key(bench) { violations.push(format!(" {bench}: pin {pin}, not measured (stale pin)\n")); } } } violations}fn within_band(pin: u64, ir: u64) -> bool { u128::from(ir.abs_diff(pin)) * 100 <= u128::from(pin) * u128::from(BAND_PERCENT)}/// Signed change of `ir` against `pin` in percent, two decimals.fn delta(pin: u64, ir: u64) -> String { if pin == 0 { return "n/a".to_string(); } let basis_points = (i128::from(ir) - i128::from(pin)) * 10_000 / i128::from(pin); let sign = if basis_points < 0 { '-' } else { '+' }; let magnitude = basis_points.unsigned_abs(); format!("{sign}{}.{:02} %", magnitude / 100, magnitude % 100)}/// `target/report/perf.md`: every measured bench against its pin, with the/// toolchain the counts belong to.fn write_perf_report( measured: &BTreeMap<String, u64>, pins: &BTreeMap<String, u64>, complete: bool, toolchain: &str,) -> ExitCode { use std::fmt::Write as _; let mut table = format!( "Callgrind instruction counts (`Ir`) against `{BUDGETS}`, band ±{BAND_PERCENT} %.\n\n\ Toolchain: `{toolchain}`.\n\n| bench | ir | pin | delta |\n|---|---|---|---|\n" ); for (bench, ir) in measured { let (pin, change) = pins.get(bench).map_or_else( || ("none".to_string(), "n/a".to_string()), |pin| (pin.to_string(), delta(*pin, *ir)), ); let _ = writeln!(table, "| `{bench}` | {ir} | {pin} | {change} |"); } if complete { for (bench, pin) in pins .iter() .filter(|(bench, _)| !measured.contains_key(*bench)) { let _ = writeln!(table, "| `{bench}` | not measured | {pin} | n/a |"); } } let out = target_dir().join("report"); if fs::create_dir_all(&out).is_err() || fs::write(out.join("perf.md"), table).is_err() { return fail("cannot write target/report/perf.md\n"); } ExitCode::SUCCESS}/// `rustc --version` of the toolchain building the benches.fn toolchain() -> String { Command::new("rustc") .arg("--version") .output() .ok() .filter(|output| output.status.success()) .map_or_else( || "rustc version unavailable".to_string(), |output| String::from_utf8_lossy(&output.stdout).trim().to_string(), )}/// `extra` without one leading `--`: `cargo x cmd -- args` and/// `cargo x cmd args` pass the same arguments on.fn without_separator(extra: &[OsString]) -> &[OsString] { match extra.split_first() { Some((first, rest)) if first == "--" => rest, _ => extra, }} index.push_str("\n## Instructions\n\n"); match perf { Some(table) => { let _ = std::fs::write(out.join("perf.md"), &table); index.push_str(&table); } None => index.push_str("No perf run found; run `cargo x perf` first.\n"), } index.push_str("\n## Wall clock\n\n"); index.push_str(&wall_clock(&out));/// Wall-clock rows of the release binary through hyperfine, isolated like/// the e2e tests. Informational only: the numbers hold for this machine/// and this run, so a missing tool or a failed run is a note, never a/// report failure.fn wall_clock(out: &Path) -> String { let present = Command::new("hyperfine") .arg("--version") .stdout(std::process::Stdio::null()) .stderr(std::process::Stdio::null()) .status() .is_ok_and(|status| status.success()); if !present { return "hyperfine not on PATH; no wall-clock rows.\n".to_string(); } let Ok(smith) = release_smith() else { return "release build of smith failed; no wall-clock rows.\n".to_string(); }; let home = target_dir().join("wall-clock-home"); let markdown = out.join("hyperfine.md"); let mut command = Command::new("hyperfine"); command .args(["--warmup", "3", "--runs", "20", "--export-json"]) .arg(out.join("hyperfine.json")) .arg("--export-markdown") .arg(&markdown) // A fresh profile per run: `eval` appends to its session otherwise. .arg("--prepare") .arg(format!("rm -rf '{}'", home.display())) .args(["--command-name", "smith --help"]) .args(["--command-name", "smith eval --mock hello"]) .arg(format!("'{}' --help", smith.display())) .arg(format!("'{}' eval --mock hello", smith.display())); for (key, dir) in dev_home_dirs() { command.env(key, home.join(dir)); } for var in PROVIDER_VARS { command.env_remove(var); } let ran = command.status().is_ok_and(|status| status.success()); match fs::read_to_string(&markdown) { Ok(rows) if ran => format!( "Informational, never a gate: {}-{}, {} hardware threads, this run only; raw data in `hyperfine.json`.\n\n{rows}", env::consts::OS, env::consts::ARCH, std::thread::available_parallelism().map_or(0, std::num::NonZero::get), ), _ => "hyperfine run failed; no wall-clock rows.\n".to_string(), }} install_gungraun_runner, tool_present_bin("cargo-deny", DENY_VERSION, || { cargo(&[ "binstall", "--no-confirm", &format!("cargo-deny@{DENY_VERSION}"), ]) }) binstall("cargo-deny", DENY_VERSION) tool_present_bin("cargo-audit", AUDIT_VERSION, || { cargo(&[ "binstall", "--no-confirm", &format!("cargo-audit@{AUDIT_VERSION}"), ]) }) binstall("cargo-audit", AUDIT_VERSION) let tool = tool_present_bin("cargo-llvm-cov", LLVM_COV_VERSION, || { cargo(&[ "binstall", "--no-confirm", &format!("cargo-llvm-cov@{LLVM_COV_VERSION}"), ]) }); let tool = binstall("cargo-llvm-cov", LLVM_COV_VERSION); tool_present_bin("cargo-nextest", NEXTEST_VERSION, || { cargo(&[ "binstall", &format!("cargo-nextest@{NEXTEST_VERSION}"), "--no-confirm", ]) binstall("cargo-nextest", NEXTEST_VERSION)}/// Install the prebuilt `tool` at `version` through `cargo-binstall`/// unless that version is already on PATH.fn binstall(tool: &str, version: &str) -> ExitCode { tool_present_bin(tool, version, || { cargo(&["binstall", "--no-confirm", &format!("{tool}@{version}")])/// Whether any dependency table of `manifest`, dev and target tables/// included, names `crate_name`.fn names_dependency(manifest: &str, crate_name: &str) -> bool { let assignment = format!("{crate_name} ="); let table = format!(".{crate_name}]"); manifest.lines().any(|line| { let trimmed = line.trim(); trimmed.starts_with(&assignment) || (trimmed.starts_with('[') && trimmed.ends_with(&table)) })} std::env::var_os("CARGO_TARGET_DIR").map_or_else(|| PathBuf::from("target"), PathBuf::from) use super::{ BTreeMap, bench_ir, budget_violations, delta, names_dependency, parse_budgets, render_budgets, without_separator, }; const FIRST_RUN: &str = r#"{"baselines":[null,null],"details":"(linear(1000))","function_name":"encode","id":"linear_1000","kind":"LibraryBenchmark","module_path":"instructions::session::encode","profiles":[{"summaries":{"parts":[{"details":{"Left":{"pid":1,"thread":1}},"metrics_summary":{"Callgrind":{"Ir":{"diffs":null,"metrics":{"Left":{"Int":999}}}}}}],"total":{"regressions":[],"summary":{"Callgrind":{"Ir":{"diffs":null,"metrics":{"Left":{"Int":5736448}}}}}}},"tool":"Callgrind"}],"version":"6"}"#; #[test] fn bench_ir_reads_the_total_of_first_and_repeated_runs() { assert_eq!( bench_ir(FIRST_RUN), Some(( "instructions::session::encode::linear_1000".to_string(), 5_736_448 )) ); let repeated = FIRST_RUN.replace( r#""total":{"regressions":[],"summary":{"Callgrind":{"Ir":{"diffs":null,"metrics":{"Left":{"Int":5736448}}}}}}"#, r#""total":{"regressions":[],"summary":{"Callgrind":{"Ir":{"diffs":{"diff_pct":0.1},"metrics":{"Both":[{"Int":5736500},{"Int":5736448}]}}}}}"#, ); assert_eq!(bench_ir(&repeated).map(|(_, ir)| ir), Some(5_736_500)); assert_eq!(bench_ir(r#"{"module_path":"a","id":"b"}"#), None); } #[test] fn budgets_round_trip_sorted_and_reject_other_shapes() { let pins = BTreeMap::from([ ("b::g::f::x".to_string(), 7), ("a::g::f::y".to_string(), 42), ]); let text = render_budgets(&pins, "rustc 1.0.0"); assert!(text.find("a::g::f::y").unwrap() < text.find("b::g::f::x").unwrap()); assert_eq!(parse_budgets(&text).unwrap(), pins); assert!( parse_budgets("\"a\" = { ir = 1 }\n").is_err(), "outside [budgets]" ); assert!(parse_budgets("[budgets]\n\"a\" = 1\n").is_err()); assert!(parse_budgets("[budgets]\n\"a\" = { ir = 1 }\n\"a\" = { ir = 2 }\n").is_err()); } #[test] fn violations_cover_both_directions_missing_and_stale_pins() { let pins = BTreeMap::from([ ("low".to_string(), 1000), ("edge".to_string(), 1000), ("high".to_string(), 1000), ("stale".to_string(), 5), ]); let measured = BTreeMap::from([ ("low".to_string(), 979), ("edge".to_string(), 1020), ("high".to_string(), 1021), ("new".to_string(), 3), ]); let found = budget_violations(&measured, &pins, true).concat(); for bench in ["low:", "high:", "new:", "stale:"] { assert!(found.contains(bench), "{bench} in {found}"); } assert!(!found.contains("edge:"), "{found}"); let filtered = budget_violations(&measured, &pins, false).concat(); assert!(!filtered.contains("stale:"), "{filtered}"); } #[test] fn delta_keeps_the_sign_below_one_percent() { assert_eq!(delta(1000, 995), "-0.50 %"); assert_eq!(delta(1000, 1025), "+2.50 %"); assert_eq!(delta(0, 5), "n/a"); } #[test] fn separator_is_stripped_once() { let args = ["--", "--", "x"].map(std::ffi::OsString::from); assert_eq!(without_separator(&args), &args[1..]); assert_eq!(without_separator(&args[2..]), &args[2..]); } #[test] fn names_dependency_sees_dev_and_target_tables() { assert!(names_dependency( "[dev-dependencies]\nsmith-bench = { path = \"..\" }", "smith-bench" )); assert!(names_dependency( "[target.'cfg(unix)'.dev-dependencies.smith-bench]", "smith-bench" )); assert!(!names_dependency("name = \"smith-bench\"", "smith-bench")); }