repositories / smith

smith

There are many coding harnesses - but this one is fast

owned by bugabinga

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

Browse filesCompare with HEAD

Changed files (16)

+1454 / −91 text lines

Diff layout

.ci/perf.kdl

Added
new file mode 100644

+11 / −0 text lines

1job "perf" {
2 image "docker.io/library/rust:latest"
3 trigger {
4 push {
5 branch "trunk"
6 }
7 }
8 run "apt-get update && apt-get install -y valgrind"
9 run "cargo run -p xtask -- bootstrap"
10 run "cargo run -p xtask -- perf"
11}

.system/RULES.md

Modified

+5 / −1 text lines

6565 - conformance kits: providers, plugin guests, frontends; fixtures in, vocabulary out.
6666 - golden corpus: checked-in sessions; replay and trace byte-identical; regenerated only with a frame-version bump.
6767 - bounds: allocation counts and type sizes; exact pins; tighten only.
68 - 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.
69 - wall clock: `criterion` and `hyperfine` compare two builds on one machine in one session; numbers are never committed and never gate.
6870 - mutation: all first-party crates nightly; missed mutants become issues.
6971 - coverage: `cargo-llvm-cov` over every tier; reported per push as a diff, never a percentage gate; uncovered spec sentences are the backlog.
70- 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).
72- 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).
7173- 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.
7274- A dev dependency earns its place by a test that uses it.
8385smith-harness/ orchestration, wasm plugin host, plugin system, SDK, event bridge, built-ins, help
8486smith-cli/ binary entry point, CLI, session commands, eval/rpc/replay
8587smith-alloc/ scope-tagged global allocator, allocation accounting
88smith-bench/ benchmarks: instruction budgets, wall-clock A/B; never shipped
8689xtask/ cargo-only automation
8790```
98101- `smith-harness`: `smith`, `smith-core`, `smith-ai`, `smith-tui`, `smith-ui`.
99102- `smith-cli`: `smith`, `smith-harness`, `smith-rpc`, `smith-alloc`.
100103- `smith-alloc`: none.
104- `smith-bench`: any workspace crate; nothing depends on it.
101105- `xtask`: none.
103107## Dependencies

.system/plans/SMH-PLAN-2_O9OFR0-benchmarking/index.md

Added
new file mode 100644

+49 / −0 text lines

1---
2id: SMH-PLAN-2_O9OFR0
3type: plan
4title: "Benchmarking: Budgets, A/B, Profiling"
5spec: SMH-SPEC-SPEC0001
6status: approved
7depends_on: [SMH-PLAN-DFOG846Z]
8---
9
10# Benchmarking: Budgets, A/B, Profiling
12## Entry
14- RULES `## Testing` names instruction budgets and wall-clock A/B; `## Memory` says the allocator is a benchmark result.
15- Spec targets: help within 100 ms, frames within 16 ms, encoding 1,000 entries within 5 ms.
16- Allocation-count bounds exist (`smith-alloc`); one criterion bench exists (`smith/benches/message_creation.rs`).
17- `target-cpu=native` from the user config is not applied in this repo, so instruction counts depend on the toolchain, not the machine.
19## Decisions
21- 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).
22- 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.
23- 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).
24- `gungraun-runner` is a build tool installed by xtask at a pinned version matching the crate.
25- Wall-clock spec targets are informational rows in the report bundle, never a gate.
27## Order
291. `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`.
302. `budgets.toml`: one `ir` pin per bench id, written by `cargo x perf --pin`.
313. `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.
324. 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`.
335. Research note and TO_DISCUSS cleanup; deslop and compress passes.
35## Interfaces
37- `xtask`: `perf [--pin]`, `bench [args]`; `bootstrap` installs `gungraun-runner`.
38- `smith-bench/budgets.toml`: `[<file>::<group>::<function>::<id>] ir = N`.
39- `.ci/perf.kdl`.
41## Risks
43- Callgrind runs are slow; the set stays small and every bench runs one shot.
44- Toolchain bumps shift counts; the re-pin commit names the toolchain.
45- Binary benches include process start-up; that is the point for `--help`, noise for anything else.
47## Exit
49- `cargo x perf` green with pins; CI `perf` job observed; report bundle carries the perf section.

.system/research/SMH-RESEARCH-UPU3A0HO-benchmarking/index.md

Added
new file mode 100644

+111 / −0 text lines

1---
2id: SMH-RESEARCH-UPU3A0HO
3type: research
4title: "Benchmarking: First Instruction Pins and Measurement Notes"
5---
6
7# Benchmarking: First Instruction Pins and Measurement Notes
8
9Date: 2026-09-26.
10Status: evidence from implementing SMH-PLAN-2_O9OFR0; candidates, not mandates.
12## Setup
14- Machine: AMD Ryzen 5 5600X, CachyOS, kernel 7.2.7, glibc 2.44, valgrind 3.25.1.
15- Toolchain: `rustc 1.98.1 (48a229cea 2026-09-01)`, bench profile (release, thin LTO, one codegen unit, line tables, not stripped).
16- `gungraun` 0.19.4 and `gungraun-runner` 0.19.4 (installed by `cargo x bootstrap` or `cargo x perf` through `cargo-binstall`).
17- Callgrind runs with `--cache-sim=no`: the gate reads only `Ir`, and cache simulation only adds run time.
18- `target-cpu=native` is not applied in this repo (`.cargo/config.toml` sets no `target-cpu`), so codegen is the generic x86-64 baseline.
20## Pinned instruction counts
22Pinned by `cargo x perf --pin`, stored in `smith-bench/budgets.toml`.
24| bench | Ir | spread seen run to run |
25|---|---:|---|
26| `instructions::agent::run_turn::history_1000_masked` | 11270600 | ≈ 0.1 % |
27| `instructions::providers::sse::anthropic` | 109026 | ≤ 0.18 % |
28| `instructions::providers::sse::gemini` | 47234 | ≤ 0.01 % |
29| `instructions::providers::sse::openai` | 81236 | identical |
30| `instructions::rpc::handle_line::ping` | 6885 | ≈ 1.5 % (6861 to 6965) |
31| `instructions::session::canonical_json::nested` | 1138903 | ≤ 0.05 % |
32| `instructions::session::decode::linear_1000` | 11056510 | identical |
33| `instructions::session::decode::tool_calls_1000` | 10284262 | identical |
34| `instructions::session::encode::linear_1000` | 5736448 | identical |
35| `instructions::session::encode::tool_calls_1000` | 5133175 | identical |
36| `instructions::session::fork_at::linear_1000` | 232844 | ≤ 0.03 % |
37| `instructions::session::from_frames::linear_1000` | 1392615 | ≤ 0.07 % |
38| `startup::cli::smith::eval_mock` | 1156689 | ≈ 0.1 % |
39| `startup::cli::smith::help` | 741164 | identical |
41Spreads come from about fifteen runs on the machine above, direct `cargo bench` and `cargo x perf` combined.
42Every bench stays well inside the ±2 % band except `handle_line::ping`, whose 1.5 % spread leaves little margin.
44## Why some library counts are not identical
46Instruction counts are exact only for code whose path does not depend on ambient randomness or time.
47Three sources were found in the measured code, not in the harness:
49- `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`).
50- `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`).
51- glibc `malloc` and `free` paths depend on arena state.
53`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.
55## Environment findings
57- gungraun clears the environment of every bench but keeps `LD_LIBRARY_PATH`.
58 `cargo run` (so every `cargo x` command) prepends library directories to it, and the dynamic loader walks each entry at start-up.
59 The same `smith --help` binary measured 753,965 `Ir` through plain `cargo bench` and 760,523 through `cargo x perf`.
60 `startup.rs` now sets `LD_LIBRARY_PATH` empty for the measured command; both launch paths then read 741,164.
61- `cargo x` children inherit `CARGO_MANIFEST_DIR=xtask` from `cargo run`.
62 `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).
63 The binary stays byte-identical; only time is lost.
64 This predates the change and affects every `cargo x` subcommand that runs cargo.
65- Instruction counts depend on the toolchain, the codegen flags, and the C library.
66 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.
67 Pins taken on this machine are therefore not guaranteed to hold in the `docker.io/library/rust:latest` CI image (Debian glibc).
69## Run time
71- `cargo x perf`, warm (both builds cached): 3.2 s wall, of which the fourteen callgrind runs take about 3 s.
72- `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.
73- `cargo x report` with hyperfine present: 52 s here (coverage tiers dominate).
75## Summary field path
77`--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`.
79- Bench key: top-level `module_path` (`<file>::<group>::<function>`) plus `::` plus top-level `id`.
80- 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`.
82`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":`.
83Bench names carry no escapes, and JSON string escaping keeps these anchors from matching inside the `details` strings.
84A line starting with `{` that the extractor cannot read fails the gate, so schema drift surfaces as a failure rather than a silent pass.
85Reading the per-bench `summary.json` files instead would need the same extractor plus a directory walk; the stdout lines were simpler.
87## Deviations from the plan and assignment
89- 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.
90- `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.
91 The fixture library sets `bench = false` for the same reason.
92- Agent request build is measured through `Agent::run_turn`: `build_request` is private, and `run_turn` is its smallest public seam.
93 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.
94 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.
95- `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.
96- 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.
97- Frame encode and decode are two benches (`encode`, `decode`), each for a linear chat and a tool-call session of 1,000 entries.
98- The criterion bench moved from `smith/benches/message_creation.rs` to `smith-bench/benches/wall_clock.rs`.
99- `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.
100- 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.
102## Candidates
104- 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.
105- Widen `handle_line::ping` only if it ever leaves the band, or measure a batch of lines so hashing noise averages out.
106- Remove `CARGO_MANIFEST_DIR` from the environment of cargo children in xtask to stop the `ring` rebuild ping-pong.
108## Sources
110- [gungraun guide](https://gungraun.github.io/gungraun/latest/html/): default environment clearing, entry points, binary benchmarks, command-line arguments, machine-readable output.
111- `gungraun-runner` 0.19.4 source, `src/runner/args.rs`: environment clearing preserves `LD_PRELOAD` and `LD_LIBRARY_PATH`.

Cargo.lock

Modified

+147 / −1 text lines

155155source = "registry+https://github.com/rust-lang/crates.io-index"
156156checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5"
158[[package]]
159name = "bincode-next"
160version = "3.1.1"
161source = "registry+https://github.com/rust-lang/crates.io-index"
162checksum = "1d6626829353ae29293be5c86f42de5f0468bc758af074b0c7d08f07e538ccbc"
163dependencies = [
164 "pastey",
165 "rapidhash",
166 "serde",
167 "unty-next",
168]
158170[[package]]
159171name = "bit-set"
160172version = "0.8.0"
636648 "typenum",
651[[package]]
652name = "derive_more"
653version = "2.1.1"
654source = "registry+https://github.com/rust-lang/crates.io-index"
655checksum = "d751e9e49156b02b44f9c1815bcb94b984cdcc4396ecc32521c739452808b134"
656dependencies = [
657 "derive_more-impl",
658]
660[[package]]
661name = "derive_more-impl"
662version = "2.1.1"
663source = "registry+https://github.com/rust-lang/crates.io-index"
664checksum = "799a97264921d8623a957f6c3b9011f3b5492f557bbb7a5a19b7fa6d06ba8dcb"
665dependencies = [
666 "proc-macro2",
667 "quote",
668 "rustc_version",
669 "syn 2.0.119",
670]
639672[[package]]
640673name = "difflib"
641674version = "0.4.0"
690723source = "registry+https://github.com/rust-lang/crates.io-index"
691724checksum = "252afb9ae5eaa683babdc6a068b3f5726eb19e05070c731f9b2a23a7c3e8ed34"
726[[package]]
727name = "either-or-both"
728version = "0.3.1"
729source = "registry+https://github.com/rust-lang/crates.io-index"
730checksum = "6717164c227120ba9ddf3e2b32305fc0122741d3ee41a54968eae7573ee01933"
731dependencies = [
732 "indexmap",
733 "serde",
734]
693736[[package]]
694737name = "embedded-io"
695738version = "0.4.0"
9581001 "regex-syntax",
1004[[package]]
1005name = "gungraun"
1006version = "0.19.4"
1007source = "registry+https://github.com/rust-lang/crates.io-index"
1008checksum = "9300d38d30facf6870c15bc9e243edcc47e5ddc270c9d2c1ae824a00b1faea79"
1009dependencies = [
1010 "bincode-next",
1011 "derive_more",
1012 "gungraun-macros",
1013 "gungraun-runner",
1016[[package]]
1017name = "gungraun-macros"
1018version = "0.9.1"
1019source = "registry+https://github.com/rust-lang/crates.io-index"
1020checksum = "d7f3214bae6cfd6739f4f29edb262bae439c6393a7b7b12c4eeb96417c2e50df"
1021dependencies = [
1022 "derive_more",
1023 "proc-macro-error3",
1024 "proc-macro2",
1025 "quote",
1026 "rustc_version",
1027 "serde",
1028 "serde_json",
1029 "syn 2.0.119",
1032[[package]]
1033name = "gungraun-runner"
1034version = "0.19.4"
1035source = "registry+https://github.com/rust-lang/crates.io-index"
1036checksum = "47c68c92812da579a2510a2cc702d5aa3251992b9662d4a98502ca46e0cbe16e"
1037dependencies = [
1038 "either-or-both",
1039 "serde",
9611042[[package]]
9621043name = "half"
9631044version = "2.7.1"
13531434 "winapi",
1437[[package]]
1438name = "pastey"
1439version = "0.2.3"
1440source = "registry+https://github.com/rust-lang/crates.io-index"
1441checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4"
13561443[[package]]
13571444name = "percent-encoding"
13581445version = "2.3.2"
14631550 "syn 3.0.6",
1553[[package]]
1554name = "proc-macro-error-attr3"
1555version = "3.1.1"
1556source = "registry+https://github.com/rust-lang/crates.io-index"
1557checksum = "9e564d14133360e1ae169ffde5da25881b5fa47261665b8e5713c212c27799da"
1558dependencies = [
1559 "proc-macro2",
1560 "quote",
1563[[package]]
1564name = "proc-macro-error3"
1565version = "3.1.1"
1566source = "registry+https://github.com/rust-lang/crates.io-index"
1567checksum = "8f0d4471b3436c22106b21913b1dda531558918ae9b7ec55d58aa84b43552233"
1568dependencies = [
1569 "proc-macro-error-attr3",
1570 "proc-macro2",
1571 "quote",
1572 "syn 3.0.6",
14661575[[package]]
14671576name = "proc-macro2"
14681577version = "1.0.107"
15791688 "rand_core",
1691[[package]]
1692name = "rapidhash"
1693version = "4.5.1"
1694source = "registry+https://github.com/rust-lang/crates.io-index"
1695checksum = "5da7e78a036ce858e8d55b7e7dc8ba3a88b78350fd2155d3591bbd966b58589e"
1696dependencies = [
1697 "rustversion",
15821700[[package]]
15831701name = "rayon"
15841702version = "1.12.0"
16791797source = "registry+https://github.com/rust-lang/crates.io-index"
16801798checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d"
1800[[package]]
1801name = "rustc_version"
1802version = "0.4.1"
1803source = "registry+https://github.com/rust-lang/crates.io-index"
1804checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92"
1805dependencies = [
1806 "semver",
16821809[[package]]
16831810name = "rustix"
16841811version = "1.1.5"
18942021version = "0.1.0"
18952022dependencies = [
18962023 "ciborium",
1897 "criterion",
18982024 "dirs",
18992025 "futures",
19002026 "serde",
19162042name = "smith-alloc"
19172043version = "0.1.0"
2045[[package]]
2046name = "smith-bench"
2047version = "0.1.0"
2048dependencies = [
2049 "criterion",
2050 "futures",
2051 "gungraun",
2052 "serde_json",
2053 "smith",
2054 "smith-ai",
2055 "smith-core",
2056 "smith-rpc",
19192059[[package]]
19202060name = "smith-cli"
19212061version = "0.1.0"
22122352source = "registry+https://github.com/rust-lang/crates.io-index"
22132353checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"
2355[[package]]
2356name = "unty-next"
2357version = "0.1.2"
2358source = "registry+https://github.com/rust-lang/crates.io-index"
2359checksum = "16062d030850f35054e37746427b9febb74a2f24c9c6dd6fa2d0c13c5f53221e"
22152361[[package]]
22162362name = "ureq"
22172363version = "3.4.2"

Cargo.toml

Modified

+9 / −0 text lines

99 "smith-harness",
1010 "smith-cli",
1111 "smith-alloc",
12 "smith-bench",
1213 "plugins/echo",
1314 "xtask",
2627 "smith-harness",
2728 "smith-cli",
2829 "smith-alloc",
30 "smith-bench",
2931 "xtask",
101103predicates = "3"
102104proptest = "1"
103105criterion = "0.8"
106gungraun = "0.19" # smith-bench, callgrind instruction budgets; runner installed by xtask
105108# Mutation-testing profile: lean debug build, many rebuilds.
106109[profile.mutants]
115118strip = "symbols"
116119panic = "abort"
121# Benches keep symbols: callgrind attributes instructions to functions.
122[profile.bench]
123inherits = "release"
124debug = "line-tables-only"
125strip = false
118127[profile.release.package."*"]
119128opt-level = 3

TO_DISCUSS.md

Modified

+1 / −1 text lines

1919- 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.
21- Benchmarking: regression detection + learning, relative comparisons, in-repo baselines, no machine-specific numbers. Trigger: RELS planning.
21- Benchmarking: moved to SMH-PLAN-2_O9OFR0 (`.system/plans/SMH-PLAN-2_O9OFR0-benchmarking/`).
2222- SDK-layer bindings: deferred past 1.0; world must stay comfortable through raw wit-bindgen. Trigger: 1.0 stabilization.
2424## Frontends

smith-bench/Cargo.toml

Added
new file mode 100644

+39 / −0 text lines

1[package]
2name = "smith-bench"
3edition.workspace = true
4version.workspace = true
5license.workspace = true
6publish = false
7
8# No libtest bench harness for the fixture library: it would reject the
9# runner arguments `cargo bench` passes to every selected target.
10[lib]
11path = "src/lib.rs"
12bench = false
14# Fixture builders need the benched crates as library dependencies.
15[dependencies]
16smith = { path = "../smith", version = "0.1.0" }
17smith-core = { path = "../smith-core", version = "0.1.0" }
18smith-ai = { path = "../smith-ai", version = "0.1.0" }
19smith-rpc = { path = "../smith-rpc", version = "0.1.0" }
20futures = { workspace = true }
21serde_json = { workspace = true }
23[dev-dependencies]
24gungraun = { workspace = true }
25criterion = { workspace = true }
27# Instruction budgets: callgrind through gungraun, gated by `cargo x perf`.
28[[bench]]
29name = "instructions"
30harness = false
32[[bench]]
33name = "startup"
34harness = false
36# Wall clock: criterion A/B through `cargo x bench`; never gates.
37[[bench]]
38name = "wall_clock"
39harness = false

smith-bench/benches/instructions.rs

Added
new file mode 100644

+161 / −0 text lines

1//! Instruction budgets per hot path (`SMH-SPEC-SPEC0001`, Performance and
2//! portability): callgrind counts through gungraun, pinned in
3//! `smith-bench/budgets.toml` and gated by `cargo x perf` within ±2 %.
4//!
5//! Sizes follow the spec targets: 1,000 entries for encoding and restore,
6//! one provider stream per adapter, one RPC line. Every bench takes its
7//! input from a setup and returns what it built, so neither construction
8//! nor drop is counted. Process start-up lives in `startup.rs`.
9
10#![expect(
11 missing_docs,
12 reason = "gungraun benchmark macros generate undocumented public modules and items"
13)]
15use gungraun::Callgrind;
16use gungraun::prelude::*;
17use smith_ai::{AnthropicDecoder, GeminiDecoder, OpenAiDecoder, StreamDecoder};
18use smith_bench::{
19 anthropic_sse, frames_of, gemini_sse, linear_session, masked_agent, nested_json, openai_sse,
20 tool_call_session,
21};
22use smith_core::agent::Agent;
23use smith_core::frame::{DEFAULT_MAX_FRAME_BYTES, Frame, Recovery, encode_entry, read_frames};
24use smith_core::session::{EntryContent, EntryFrame, Session};
25use smith_rpc::RpcState;
26use std::hint::black_box;
28fn linear(len: usize) -> Session {
29 linear_session(len).expect("linear session")
30}
32fn tool_calls(pairs: usize) -> Session {
33 tool_call_session(pairs).expect("tool-call session")
34}
36/// A session and its entries encoded back to back, as a store file holds
37/// them.
38fn encoded(session: Session) -> (Session, Vec<u8>) {
39 let bytes = encode_all(&session);
40 (session, bytes)
41}
43fn encode_all(session: &Session) -> Vec<u8> {
44 let mut out = Vec::new();
45 for entry in session.active_branch().entries() {
46 let frame = encode_entry(entry, session.bytes(entry), DEFAULT_MAX_FRAME_BYTES)
47 .expect("entry encodes");
48 out.extend_from_slice(&frame);
49 }
50 out
51}
53#[library_benchmark]
54#[bench::linear_1000(linear(1000))]
55#[bench::tool_calls_1000(tool_calls(500))]
56fn encode(session: Session) -> (Session, Vec<u8>) {
57 let bytes = encode_all(black_box(&session));
58 (session, black_box(bytes))
59}
61#[library_benchmark]
62#[bench::linear_1000(encoded(linear(1000)))]
63#[bench::tool_calls_1000(encoded(tool_calls(500)))]
64fn decode(input: (Session, Vec<u8>)) -> ((Session, Vec<u8>), Recovery) {
65 let recovery = read_frames(&mut black_box(input.1.as_slice()), DEFAULT_MAX_FRAME_BYTES);
66 (input, black_box(recovery))
67}
69#[library_benchmark]
70#[bench::linear_1000(frames_of(&linear(1000)))]
71fn from_frames(frames: Vec<Frame>) -> (Vec<Frame>, Session) {
72 let session = Session::from_frames(black_box(&frames)).expect("frames restore");
73 (frames, black_box(session))
74}
76#[library_benchmark]
77#[bench::linear_1000(linear(1000))]
78fn fork_at(session: Session) -> (Session, Session) {
79 let leaf = session.selected_id().expect("non-empty session");
80 let fork = session.fork_at(black_box(leaf)).expect("leaf is known");
81 (session, black_box(fork))
82}
84/// Tool-call content with a nested, non-canonical input: recording it
85/// canonicalizes the input before encoding (`canonical_json` is private;
86/// `EntryFrame::new` is its public seam).
87fn tool_call_with(input: serde_json::Value) -> EntryContent {
88 EntryContent::ToolCall {
89 name: "write".to_string(),
90 input,
91 call_id: smith::ToolCallId::new(),
92 }
93}
95#[library_benchmark]
96#[bench::nested(tool_call_with(nested_json(4)))]
97fn canonical_json(content: EntryContent) -> (EntryContent, EntryFrame) {
98 let frame = EntryFrame::new(None, black_box(&content)).expect("content encodes");
99 (content, black_box(frame))
100}
102library_benchmark_group!(
103 name = session,
104 benchmarks = [encode, decode, from_frames, fork_at, canonical_json]
105);
107fn masked(history: usize) -> Agent {
108 masked_agent(history).expect("agent history")
109}
111// One turn over a long history: the request build decodes and masks
112// every message since the compaction boundary (`build_request` is
113// private; `run_turn` is its smallest public seam and adds recording the
114// user message and the one-delta reply).
115#[library_benchmark]
116#[bench::history_1000_masked(masked(1000))]
117fn run_turn(mut agent: Agent) -> Agent {
118 let outcome = agent.run_turn(black_box("next step, please"));
119 black_box(outcome.expect("turn settles"));
120 agent
121}
123library_benchmark_group!(name = agent, benchmarks = [run_turn]);
125fn stream_of(decoder: Box<dyn StreamDecoder>, bytes: Vec<u8>) -> (Box<dyn StreamDecoder>, Vec<u8>) {
126 (decoder, bytes)
127}
129// One fixture stream through a fresh adapter, in one chunk, to its stop.
130#[library_benchmark]
131#[bench::openai(stream_of(Box::new(OpenAiDecoder::new()), openai_sse()))]
132#[bench::anthropic(stream_of(Box::new(AnthropicDecoder::new()), anthropic_sse()))]
133#[bench::gemini(stream_of(Box::new(GeminiDecoder::new()), gemini_sse()))]
134fn sse(input: (Box<dyn StreamDecoder>, Vec<u8>)) -> (Vec<u8>, Vec<smith::StreamEvent>) {
135 let (mut decoder, bytes) = input;
136 let mut events = decoder.push(black_box(&bytes)).expect("stream decodes");
137 events.extend(decoder.finish().expect("stream stops"));
138 (bytes, black_box(events))
139}
141library_benchmark_group!(name = providers, benchmarks = [sse]);
143fn rpc_state() -> RpcState {
144 RpcState::new(masked(0))
145}
147// One control line through the reader; the agent worker thread is idle
148// and not counted.
149#[library_benchmark]
150#[bench::ping(rpc_state())]
151fn handle_line(mut state: RpcState) -> (RpcState, Vec<String>) {
152 let lines = smith_rpc::handle_line(&mut state, black_box(r#"{"id":1,"method":"ping"}"#));
153 (state, black_box(lines))
154}
156library_benchmark_group!(name = rpc, benchmarks = [handle_line]);
158main!(
159 config = LibraryBenchmarkConfig::default().tool(Callgrind::with_args(["--cache-sim=no"])),
160 library_benchmark_groups = [session, agent, providers, rpc]
161);

smith-bench/benches/startup.rs

Added
new file mode 100644

+57 / −0 text lines

1//! Instruction budgets of process start-up (`SMH-SPEC-SPEC0001`,
2//! Performance and portability: help within 100 ms): the release binary
3//! under callgrind, pinned in `smith-bench/budgets.toml` and gated by
4//! `cargo x perf`.
5//!
6//! Start-up is the measurement here, so the whole process counts. The
7//! binary comes from `SMITH_BIN`, which `cargo x perf` builds and sets.
8//! Every run gets fresh, empty XDG roots and, gungraun clearing the
9//! environment, no provider variable: the e2e tests' isolation. The
10//! clearing keeps `LD_LIBRARY_PATH`, which `cargo run` (so `cargo x`)
11//! extends; the dynamic loader walks every entry, so it is emptied to
12//! keep start-up counts independent of how the bench was launched.
14#![expect(
15 missing_docs,
16 reason = "gungraun benchmark macros generate undocumented public modules and items"
17)]
19use gungraun::Callgrind;
20use gungraun::prelude::*;
21use std::path::{Path, PathBuf};
23/// Profile root of every run, under cargo's per-target scratch directory.
24fn home() -> PathBuf {
25 Path::new(env!("CARGO_TARGET_TMPDIR")).join("smith-bench-home")
26}
28/// An empty profile, so no run sees what an earlier one left behind.
29fn fresh_home() {
30 let home = home();
31 let _ = std::fs::remove_dir_all(&home);
32 std::fs::create_dir_all(&home).expect("profile root");
33}
35#[binary_benchmark(setup = fresh_home())]
36#[bench::help(&["--help"])]
37#[bench::eval_mock(&["eval", "--mock", "hello"])]
38fn smith(args: &[&str]) -> gungraun::Command {
39 let binary = std::env::var("SMITH_BIN")
40 .expect("SMITH_BIN names the release smith binary; run `cargo x perf`");
41 let home = home();
42 gungraun::Command::new(binary)
43 .args(args)
44 .env("XDG_CONFIG_HOME", home.join("config"))
45 .env("XDG_DATA_HOME", home.join("data"))
46 .env("XDG_STATE_HOME", home.join("state"))
47 .env("XDG_CACHE_HOME", home.join("cache"))
48 .env("LD_LIBRARY_PATH", "")
49 .build()
50}
52binary_benchmark_group!(name = cli, benchmarks = smith);
54main!(
55 config = BinaryBenchmarkConfig::default().tool(Callgrind::with_args(["--cache-sim=no"])),
56 binary_benchmark_groups = cli
57);

smith-bench/benches/wall_clock.rs

Added
new file mode 100644

+31 / −0 text lines

1//! Wall-clock benches for local A/B comparisons (`SMH-SPEC-SPEC0001`,
2//! Performance and portability): criterion through `cargo x bench`.
3//!
4//! Numbers answer "faster here, now" on one machine in one session; they
5//! are never committed and never gate. Compare two builds with
6//! `cargo x bench -- --save-baseline <change>` then `--baseline <change>`.
7
8use criterion::{Criterion, criterion_main};
9use smith::{Message, MessageId, Role};
10use std::hint::black_box;
12fn message_creation(criterion: &mut Criterion) {
13 let mut group = criterion.benchmark_group("message_creation");
14 group.bench_function("message_id", |bencher| {
15 bencher.iter(|| black_box(MessageId::new()));
16 });
17 group.bench_function("empty_message", |bencher| {
18 bencher.iter(|| black_box(Message::new(Role::Assistant)));
19 });
20 group.bench_function("text_message", |bencher| {
21 bencher.iter(|| black_box(Message::with_text(Role::User, "benchmark text")));
22 });
23 group.finish();
24}
26fn benches() {
27 let mut criterion = Criterion::default().configure_from_args();
28 message_creation(&mut criterion);
29}
31criterion_main!(benches);

smith-bench/budgets.toml

Added
new file mode 100644

+19 / −0 text lines

1# Callgrind instruction budgets (Ir) per bench, gated within ±2 % by `cargo x perf`.
2# Written by `cargo x perf --pin`; a re-pin is a deliberate commit that says why.
3# Pinned with rustc 1.98.1 (48a229cea 2026-09-01).
4
5[budgets]
6"instructions::agent::run_turn::history_1000_masked" = { ir = 11270600 }
7"instructions::providers::sse::anthropic" = { ir = 109026 }
8"instructions::providers::sse::gemini" = { ir = 47234 }
9"instructions::providers::sse::openai" = { ir = 81236 }
10"instructions::rpc::handle_line::ping" = { ir = 6885 }
11"instructions::session::canonical_json::nested" = { ir = 1138903 }
12"instructions::session::decode::linear_1000" = { ir = 11056510 }
13"instructions::session::decode::tool_calls_1000" = { ir = 10284262 }
14"instructions::session::encode::linear_1000" = { ir = 5736448 }
15"instructions::session::encode::tool_calls_1000" = { ir = 5133175 }
16"instructions::session::fork_at::linear_1000" = { ir = 232844 }
17"instructions::session::from_frames::linear_1000" = { ir = 1392615 }
18"startup::cli::smith::eval_mock" = { ir = 1156689 }
19"startup::cli::smith::help" = { ir = 741164 }

smith-bench/src/lib.rs

Added
new file mode 100644

+246 / −0 text lines

1//! Shared fixtures for Smith benchmarks (`SMH-SPEC-SPEC0001`, Performance
2//! and portability).
3//!
4//! Benches live in `benches/`: `instructions` counts callgrind instructions
5//! against the pins in `budgets.toml` (`cargo x perf`), `wall_clock` runs
6//! criterion for local A/B comparisons (`cargo x bench`). Builders here run
7//! in bench setup, outside every measured region, and use only public API,
8//! so a bench measures what a caller of the crate gets.
9
10#![forbid(unsafe_code)]
12use futures::StreamExt;
13use smith::error::Result;
14use smith::id::{MessageId, ToolCallId};
15use smith::message::{Message, Role};
16use smith::stream::{StopReason, StreamEvent};
17use smith::{StreamFn, Usage};
18use smith_core::agent::Agent;
19use smith_core::frame::Frame;
20use smith_core::session::{EntryContent, EntryFrame, Session};
21use smith_core::tools::ToolSession;
22use std::sync::Arc;
24/// Plaintext the agent fixture registers as a secret.
25pub const SECRET: &str = "sk-bench-0123456789abcdef";
27/// A session of `len` chat messages, alternating user and assistant.
28///
29/// # Errors
30///
31/// Returns the session error of the first failed append.
32pub fn linear_session(len: usize) -> Result<Session> {
33 let mut session = Session::new();
34 for turn in 0..len {
35 let role = if turn % 2 == 0 {
36 Role::User
37 } else {
38 Role::Assistant
39 };
40 let message = Message::with_text(role, format!("turn {turn}: a short chat message"));
41 session.append(&EntryContent::Message(message))?;
42 }
43 Ok(session)
44}
46/// A session of `pairs` tool calls, each followed by its result.
47///
48/// # Errors
49///
50/// Returns the session error of the first failed append.
51pub fn tool_call_session(pairs: usize) -> Result<Session> {
52 let mut session = Session::new();
53 for call in 0..pairs {
54 let call_id = ToolCallId::new();
55 session.append(&EntryContent::ToolCall {
56 name: "read".to_string(),
57 input: serde_json::json!({"path": format!("src/module_{call}.rs"), "limit": 200}),
58 call_id,
59 })?;
60 session.append(&EntryContent::ToolResult {
61 ok: true,
62 output: format!("pub fn item_{call}() -> u32 {{ {call} }}\n"),
63 call_id,
64 })?;
65 }
66 Ok(session)
67}
69/// The decoded frames a store would read back for `session`: its header,
70/// then one entry frame per record of the active branch.
71#[must_use]
72pub fn frames_of(session: &Session) -> Vec<Frame> {
73 let entries = session.active_branch().entries();
74 let mut frames = Vec::with_capacity(entries.len() + 1);
75 frames.push(Frame::Header {
76 header: session.header(),
77 });
78 frames.extend(entries.iter().map(|entry| Frame::Known {
79 entry: EntryFrame {
80 id: entry.id,
81 parent: entry.parent,
82 timestamp_ms: entry.timestamp_ms,
83 kind: entry.kind,
84 content: session.bytes(entry).to_vec(),
85 },
86 }));
87 frames
88}
90/// A JSON value `depth` levels deep, four keys per object, every object
91/// in reverse key order so canonicalization has to reorder all of them.
92#[must_use]
93pub fn nested_json(depth: u32) -> serde_json::Value {
94 let mut object = serde_json::Map::new();
95 for key in (0..4u32).rev() {
96 let value = match (depth, key) {
97 (0, _) => serde_json::Value::from(format!("leaf {key}")),
98 (_, 0) => serde_json::json!([key, "item", {"z": depth, "a": key}]),
99 _ => nested_json(depth - 1),
100 };
101 object.insert(format!("key_{key}"), value);
102 }
103 serde_json::Value::Object(object)
104}
106/// An agent over a session of `history` messages with [`SECRET`]
107/// registered, whose provider answers every request with one text delta
108/// and a clean stop.
109///
110/// # Errors
111///
112/// Returns the session error of building the history.
113pub fn masked_agent(history: usize) -> Result<Agent> {
114 let mut tools = ToolSession::new(".");
115 tools.session = linear_session(history)?;
116 let mut agent = Agent::new(scripted_reply(), tools, "bench-model");
117 agent.secrets_mut().register("api_key", SECRET);
118 Ok(agent)
119}
121/// A provider that streams `ok` and stops, whatever the request.
122fn scripted_reply() -> StreamFn {
123 Arc::new(|_request, _cancel| {
124 let reply = MessageId::new();
125 futures::stream::iter([
126 Ok(StreamEvent::text_delta(reply, "ok")),
127 Ok(StreamEvent::stop(StopReason::EndTurn, Some(Usage::new()))),
128 ])
129 .boxed()
130 })
131}
133/// SSE bytes: one `data:` event per payload.
134fn sse(payloads: &[&str]) -> Vec<u8> {
135 let mut out = String::new();
136 for payload in payloads {
137 out.push_str("data: ");
138 out.push_str(payload);
139 out.push_str("\n\n");
140 }
141 out.into_bytes()
142}
144/// An `OpenAI` chat-completions stream: text, fragmented tool arguments,
145/// usage, done; the shapes of the adapter's conformance fixtures.
146#[must_use]
147pub fn openai_sse() -> Vec<u8> {
148 sse(&[
149 r#"{"choices":[{"delta":{"role":"assistant","content":""}}]}"#,
150 r#"{"choices":[{"delta":{"content":"Hello"}}]}"#,
151 r#"{"choices":[{"delta":{"content":" world"}}]}"#,
152 r#"{"choices":[{"delta":{"tool_calls":[{"index":0,"id":"a","function":{"name":"write","arguments":""}}]}}]}"#,
153 r#"{"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"arguments":"{\"path\""}}]}}]}"#,
154 r#"{"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"arguments":":\"f.txt\",\"content\":\"hi\"}"}}]}}]}"#,
155 r#"{"choices":[{"delta":{},"finish_reason":"tool_calls"}]}"#,
156 r#"{"choices":[],"usage":{"prompt_tokens":9,"completion_tokens":2,"prompt_tokens_details":{"cached_tokens":4}}}"#,
157 "[DONE]",
158 ])
159}
161/// An Anthropic Messages stream: text, thinking, assembled tool input,
162/// usage; the adapter's conformance fixture.
163#[must_use]
164pub fn anthropic_sse() -> Vec<u8> {
165 sse(&[
166 r#"{"type":"message_start","message":{"usage":{"input_tokens":12}}}"#,
167 r#"{"type":"content_block_start","index":0,"content_block":{"type":"text"}}"#,
168 r#"{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"Look"}}"#,
169 r#"{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"ing"}}"#,
170 r#"{"type":"content_block_stop","index":0}"#,
171 r#"{"type":"content_block_start","index":1,"content_block":{"type":"thinking"}}"#,
172 r#"{"type":"content_block_delta","index":1,"delta":{"type":"thinking_delta","thinking":"hmm"}}"#,
173 r#"{"type":"content_block_stop","index":1}"#,
174 r#"{"type":"content_block_start","index":2,"content_block":{"type":"tool_use","id":"t","name":"write"}}"#,
175 r#"{"type":"content_block_delta","index":2,"delta":{"type":"input_json_delta","partial_json":"{\"path\""}}"#,
176 r#"{"type":"content_block_delta","index":2,"delta":{"type":"input_json_delta","partial_json":":[1,2]}"}}"#,
177 r#"{"type":"content_block_stop","index":2}"#,
178 r#"{"type":"message_delta","delta":{"stop_reason":"tool_use"},"usage":{"output_tokens":7,"cache_read_input_tokens":3}}"#,
179 r#"{"type":"message_stop"}"#,
180 ])
181}
183/// A Gemini stream: text around a complete function call, usage, stop;
184/// the adapter's conformance fixture.
185#[must_use]
186pub fn gemini_sse() -> Vec<u8> {
187 sse(&[
188 r#"{"candidates":[{"content":{"parts":[{"text":"Writing"}]}}]}"#,
189 r#"{"candidates":[{"content":{"parts":[{"functionCall":{"name":"write","args":{"path":"f","content":"hi"}}}]}}],"usageMetadata":{"promptTokenCount":5,"candidatesTokenCount":9,"cachedContentTokenCount":2}}"#,
190 r#"{"candidates":[{"content":{"parts":[{"text":" now"}]}}]}"#,
191 r#"{"candidates":[{"content":{},"finishReason":"STOP"}]}"#,
192 ])
193}
195#[cfg(test)]
196#[expect(
197 clippy::unwrap_used,
198 reason = "tests may panic on invariant violations"
199)]
200mod tests {
201 use super::*;
202 use smith_ai::{AnthropicDecoder, GeminiDecoder, OpenAiDecoder, StreamDecoder};
204 #[test]
205 fn fixtures_have_the_sizes_benches_name() {
206 let linear = linear_session(1000).unwrap();
207 assert_eq!(linear.active_branch().entries().len(), 1000);
208 assert_eq!(frames_of(&linear).len(), 1001);
209 let calls = tool_call_session(500).unwrap();
210 assert_eq!(calls.active_branch().entries().len(), 1000);
211 }
213 #[test]
214 fn nested_json_is_not_canonical() {
215 let value = nested_json(2);
216 let keys: Vec<&String> = value.as_object().unwrap().keys().collect();
217 assert_eq!(keys, ["key_3", "key_2", "key_1", "key_0"]);
218 }
220 #[test]
221 fn every_sse_fixture_decodes_to_a_clean_stop() {
222 let cases: [(Box<dyn StreamDecoder>, Vec<u8>); 3] = [
223 (Box::new(OpenAiDecoder::new()), openai_sse()),
224 (Box::new(AnthropicDecoder::new()), anthropic_sse()),
225 (Box::new(GeminiDecoder::new()), gemini_sse()),
226 ];
227 for (mut decoder, bytes) in cases {
228 let mut events = decoder.push(&bytes).unwrap();
229 events.extend(decoder.finish().unwrap());
230 assert!(
231 matches!(events.last(), Some(StreamEvent::Stop { .. })),
232 "{events:?}"
233 );
234 }
235 }
237 #[test]
238 fn masked_agent_answers_a_turn() {
239 let mut agent = masked_agent(10).unwrap();
240 agent.run_turn(format!("use {SECRET}")).unwrap();
241 let entries = agent.session().active_branch().entries();
242 assert_eq!(entries.len(), 12);
243 let input = agent.session().content(&entries[10]).unwrap();
244 assert!(!format!("{input:?}").contains(SECRET), "{input:?}");
245 }
246}

smith/Cargo.toml

Modified

+0 / −5 text lines

1515futures = { workspace = true }
1717[dev-dependencies]
18criterion = { workspace = true }
1918ciborium = { workspace = true }
21[[bench]]
22name = "message_creation"
23harness = falseNo final newline

smith/benches/message_creation.rs

Deleted
deleted file mode 100644

+0 / −26 text lines

1//! Message-construction benchmarks.
2
3use criterion::{Criterion, criterion_main};
4use smith::{Message, MessageId, Role};
5use std::hint::black_box;
6
7fn message_creation(criterion: &mut Criterion) {
8 let mut group = criterion.benchmark_group("message_creation");
9 group.bench_function("message_id", |bencher| {
10 bencher.iter(|| black_box(MessageId::new()));
11 });
12 group.bench_function("empty_message", |bencher| {
13 bencher.iter(|| black_box(Message::new(Role::Assistant)));
14 });
15 group.bench_function("text_message", |bencher| {
16 bencher.iter(|| black_box(Message::with_text(Role::User, "benchmark text")));
17 });
18 group.finish();
19}
21fn benches() {
22 let mut criterion = Criterion::default().configure_from_args();
23 message_creation(&mut criterion);
24}
26criterion_main!(benches);

xtask/src/main.rs

Modified

+568 / −57 text lines

1818 process::ExitCode,
1919};
21use std::collections::BTreeMap;
2123const HELP: &str = concat!(
2224 "usage: cargo x <check|lint|fmt|test|e2e|coverage|report|doc|arch|mutants [args...]|audit|ci|release|bootstrap>\n",
25 " cargo x perf [--pin] [args...] instruction budgets (callgrind), gated against smith-bench/budgets.toml\n",
26 " cargo x bench [args...] wall-clock criterion benches; never gate\n",
2327 " cargo x dev [args...] build and launch the dev smith binary\n",
2428);
3337const AUDIT_VERSION: &str = "0.22.2";
3438const MUTANTS_VERSION: &str = "27.1.0";
3539const LLVM_COV_VERSION: &str = "0.9.1";
40/// Version of `gungraun-runner`; must match the `gungraun` crate in the lockfile.
41const GUNGRAUN_VERSION: &str = "0.19.4";
42/// gungraun bench targets of `smith-bench`, gated by `cargo x perf`.
43const INSTRUCTION_BENCHES: &[&str] = &["instructions", "startup"];
44/// criterion bench target of `smith-bench`, run by `cargo x bench`.
45const WALL_CLOCK_BENCH: &str = "wall_clock";
46/// Instruction pins, one per gungraun bench.
47const BUDGETS: &str = "smith-bench/budgets.toml";
48/// Allowed deviation of a measured `Ir` from its pin, either direction.
49const BAND_PERCENT: u64 = 2;
50/// Provider selection and credential variables that never reach a
51/// measured `smith` run.
52const PROVIDER_VARS: &[&str] = &[
53 "SMITH_PROVIDER",
54 "SMITH_MODEL",
55 "SMITH_BASE_URL",
56 "ANTHROPIC_API_KEY",
57 "OPENAI_API_KEY",
58 "GEMINI_API_KEY",
59];
3660const CRATES: &[&str] = &[
3761 "smith",
3862 "smith-core",
4367 "smith-harness",
4468 "smith-cli",
4569 "smith-alloc",
70 "smith-bench",
4671 "xtask",
4772];
6792 Some("doc") => cargo_doc(&rest),
6893 Some("arch") => arch(&rest),
6994 Some("mutants") => cargo_mutants(&rest),
95 Some("perf") => perf(&rest),
96 Some("bench") => bench(&rest),
7097 Some("audit") => audit(&rest),
7198 Some("ci") => ci(&rest),
7299 Some("release") => release(&rest),
157184/// count overridable through `CARGO_MUTANTS_JOBS`, and a skipped
158185/// baseline because `cargo x check` owns test verification.
159186fn cargo_mutants(extra: &[OsString]) -> ExitCode {
160 let installed = tool_present_bin("cargo-mutants", MUTANTS_VERSION, || {
161 cargo(&[
162 "binstall",
163 "--no-confirm",
164 &format!("cargo-mutants@{MUTANTS_VERSION}"),
165 ])
166 });
187 let installed = install_mutants(&[]);
167188 if installed != ExitCode::SUCCESS {
168189 return installed;
169190 }
172193 return fail("cannot create target/mutants-tmp\n");
173194 }
174195 let jobs = std::env::var("CARGO_MUTANTS_JOBS").unwrap_or_else(|_| "1".to_string());
175 // `cargo x mutants -- -f x` and `cargo x mutants -f x` are equivalent:
176 // a leading separator is stripped so cargo-run habits cannot turn
177 // scope flags into stray nextest test filters.
178 let extra: Vec<OsString> = if extra.first().is_some_and(|arg| arg == "--") {
179 extra[1..].to_vec()
180 } else {
181 extra.to_vec()
182 };
196 // `cargo x mutants -- -f x` and `cargo x mutants -f x` are equivalent,
197 // so cargo-run habits cannot turn scope flags into stray nextest test
198 // filters.
199 let extra = without_separator(extra);
183200 let mut command = Command::new("cargo-mutants");
184201 command.env("TMPDIR", &scratch).args([
185202 "mutants",
201218 }
221/// Instruction budgets: every gungraun bench's callgrind `Ir` against its
222/// pin in `smith-bench/budgets.toml`, within ±2 % in either direction, so
223/// a regression fails and an improvement fails until re-pinned.
224///
225/// `--pin` rewrites the pins from this run instead of gating. Other
226/// arguments go to the gungraun runner; a filter narrows the run, and pins
227/// of benches it skipped are kept rather than reported stale. Every run
228/// writes `target/report/perf.md`.
229fn perf(extra: &[OsString]) -> ExitCode {
230 let repin = extra.iter().any(|arg| arg == "--pin");
231 let passthrough: Vec<OsString> = without_separator(extra)
232 .iter()
233 .filter(|arg| *arg != "--pin")
234 .cloned()
235 .collect();
236 let installed = install_gungraun_runner(&[]);
237 if installed != ExitCode::SUCCESS {
238 return installed;
239 }
240 let smith = match release_smith() {
241 Ok(path) => path,
242 Err(code) => return code,
243 };
244 let measured = match instruction_counts(&smith, &passthrough) {
245 Ok(measured) => measured,
246 Err(message) => return fail(&message),
247 };
248 let pins = match fs::read_to_string(BUDGETS) {
249 Ok(text) => parse_budgets(&text),
250 Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(BTreeMap::new()),
251 Err(error) => Err(format!("cannot read {BUDGETS}: {error}")),
252 };
253 let pins = match pins {
254 Ok(pins) => pins,
255 Err(message) => return fail(&format!("{message}\n")),
256 };
257 let complete = passthrough.is_empty();
258 let toolchain = toolchain();
259 let written = write_perf_report(&measured, &pins, complete, &toolchain);
260 if written != ExitCode::SUCCESS {
261 return written;
262 }
263 if repin {
264 let mut pinned = if complete { BTreeMap::new() } else { pins };
265 pinned.extend(measured);
266 if fs::write(BUDGETS, render_budgets(&pinned, &toolchain)).is_err() {
267 return fail(&format!("cannot write {BUDGETS}\n"));
268 }
269 note(&format!(
270 "perf: pinned {} benches in {BUDGETS}\n",
271 pinned.len()
272 ));
273 return ExitCode::SUCCESS;
274 }
275 let violations = budget_violations(&measured, &pins, complete);
276 if violations.is_empty() {
277 note(&format!(
278 "perf: {} benches within ±{BAND_PERCENT} % of their pins\n",
279 measured.len()
280 ));
281 ExitCode::SUCCESS
282 } else {
283 fail(&format!(
284 "instruction budgets violated (re-pin deliberately with `cargo x perf --pin`):\n{}",
285 violations.concat()
286 ))
287 }
288}
290/// Wall clock: the criterion benches, for A/B comparisons of two builds
291/// on one machine in one session. Numbers are never committed and never
292/// gate. Arguments go to criterion, e.g. `--save-baseline <change>`.
293fn bench(extra: &[OsString]) -> ExitCode {
294 let mut args: Vec<OsString> = [
295 "bench",
296 "--locked",
297 "-p",
298 "smith-bench",
299 "--bench",
300 WALL_CLOCK_BENCH,
301 "--",
302 ]
303 .map(OsString::from)
304 .to_vec();
305 args.extend_from_slice(without_separator(extra));
306 run_os("cargo", &args)
307}
309/// Build the release `smith` binary and return its absolute path.
310fn release_smith() -> Result<PathBuf, ExitCode> {
311 let built = cargo(&[
312 "build",
313 "--locked",
314 "--release",
315 "-p",
316 "smith-cli",
317 "--bin",
318 "smith",
319 ]);
320 if built != ExitCode::SUCCESS {
321 return Err(built);
322 }
323 let binary = target_dir().join("release").join(binary_name());
324 std::path::absolute(&binary)
325 .map_err(|error| fail(&format!("cannot resolve {}: {error}\n", binary.display())))
326}
328/// Run the gungraun benches against `smith` and collect every bench's
329/// `Ir` from the JSON summary lines on standard output.
330fn instruction_counts(
331 smith: &Path,
332 passthrough: &[OsString],
333) -> Result<BTreeMap<String, u64>, String> {
334 let mut command = Command::new("cargo");
335 command.args(["bench", "--locked", "-p", "smith-bench"]);
336 for bench in INSTRUCTION_BENCHES {
337 command.args(["--bench", bench]);
338 }
339 command
340 .args(["--", "--save-summary=json", "--output-format=json"])
341 .args(passthrough)
342 .env("SMITH_BIN", smith)
343 .stderr(std::process::Stdio::inherit());
344 let output = command
345 .output()
346 .map_err(|error| format!("failed to run cargo bench: {error}\n"))?;
347 if !output.status.success() {
348 // Exit code 3 is gungraun's own regression verdict from limits
349 // passed through; anything else is a build or runner failure.
350 return Err(format!("cargo bench exited with {}\n", output.status));
351 }
352 let stdout = String::from_utf8_lossy(&output.stdout);
353 let mut measured = BTreeMap::new();
354 for line in stdout.lines().filter(|line| line.starts_with('{')) {
355 let Some((bench, ir)) = bench_ir(line) else {
356 return Err(format!("unrecognized gungraun summary line: {line}\n"));
357 };
358 measured.insert(bench, ir);
359 }
360 if measured.is_empty() {
361 return Err("gungraun reported no benches\n".to_string());
362 }
363 Ok(measured)
364}
366/// `(<module_path>::<id>, Ir)` of one gungraun `--output-format=json`
367/// line (summary schema v6). `module_path` and `id` are top-level strings;
368/// the total `Ir` is the first integer under `total` → `Ir` → `metrics`,
369/// which reads `{"Left":{"Int":n}}` on a first run and
370/// `{"Both":[{"Int":n},{"Int":previous}]}` once a previous run exists.
371fn bench_ir(line: &str) -> Option<(String, u64)> {
372 let module = json_string(line, "module_path")?;
373 let id = json_string(line, "id")?;
374 let after = |text: &'_ str, anchor: &str| -> Option<usize> {
375 text.find(anchor).map(|at| at + anchor.len())
376 };
377 let total = &line[after(line, "\"total\":")?..];
378 let ir = &total[after(total, "\"Ir\":")?..];
379 let metrics = &ir[after(ir, "\"metrics\":")?..];
380 let int = &metrics[after(metrics, "{\"Int\":")?..];
381 let digits = &int[..int.find(|c: char| !c.is_ascii_digit())?];
382 Some((format!("{module}::{id}"), digits.parse().ok()?))
383}
385/// The first string value of `key`; bench names carry no escapes.
386fn json_string<'a>(line: &'a str, key: &str) -> Option<&'a str> {
387 let anchor = format!("\"{key}\":\"");
388 let rest = &line[line.find(&anchor)? + anchor.len()..];
389 rest.find('"').map(|end| &rest[..end])
390}
392/// Pins of `budgets.toml`: a `[budgets]` table of
393/// `"<file>::<group>::<function>::<id>" = { ir = <n> }` lines, the shape
394/// `--pin` writes; any other line is rejected rather than guessed at.
395fn parse_budgets(text: &str) -> Result<BTreeMap<String, u64>, String> {
396 let mut pins = BTreeMap::new();
397 let mut in_table = false;
398 for (number, line) in text.lines().enumerate() {
399 let line = line.trim();
400 if line.is_empty() || line.starts_with('#') {
401 continue;
402 }
403 if line == "[budgets]" {
404 in_table = true;
405 continue;
406 }
407 let Some((bench, ir)) = in_table.then(|| budget_line(line)).flatten() else {
408 return Err(format!(
409 "{BUDGETS}:{}: expected `\"<bench>\" = {{ ir = <n> }}` under [budgets]",
410 number + 1
411 ));
412 };
413 if pins.insert(bench.to_string(), ir).is_some() {
414 return Err(format!("{BUDGETS}:{}: {bench} pinned twice", number + 1));
415 }
416 }
417 Ok(pins)
418}
420fn budget_line(line: &str) -> Option<(&str, u64)> {
421 let (bench, rest) = line.strip_prefix('"')?.split_once('"')?;
422 let table = rest.trim_start().strip_prefix('=')?.trim();
423 let fields = table.strip_prefix('{')?.strip_suffix('}')?.trim();
424 let ir = fields
425 .strip_prefix("ir")?
426 .trim_start()
427 .strip_prefix('=')?
428 .trim();
429 Some((bench, ir.parse().ok()?))
430}
432fn render_budgets(pins: &BTreeMap<String, u64>, toolchain: &str) -> String {
433 use std::fmt::Write as _;
434 let mut out = format!(
435 "# Callgrind instruction budgets (Ir) per bench, gated within ±{BAND_PERCENT} % by `cargo x perf`.\n\
436 # Written by `cargo x perf --pin`; a re-pin is a deliberate commit that says why.\n\
437 # Pinned with {toolchain}.\n\n[budgets]\n"
438 );
439 for (bench, ir) in pins {
440 let _ = writeln!(out, "\"{bench}\" = {{ ir = {ir} }}");
441 }
442 out
443}
445/// One line per bench outside its band, without a pin, or, when every
446/// bench ran, pinned but no longer measured.
447fn budget_violations(
448 measured: &BTreeMap<String, u64>,
449 pins: &BTreeMap<String, u64>,
450 complete: bool,
451) -> Vec<String> {
452 let mut violations = Vec::new();
453 for (bench, ir) in measured {
454 match pins.get(bench) {
455 None => violations.push(format!(" {bench}: measured {ir}, no pin\n")),
456 Some(pin) if !within_band(*pin, *ir) => violations.push(format!(
457 " {bench}: pin {pin}, measured {ir}, delta {} (band ±{BAND_PERCENT} %)\n",
458 delta(*pin, *ir)
459 )),
460 Some(_) => {}
461 }
462 }
463 if complete {
464 for (bench, pin) in pins {
465 if !measured.contains_key(bench) {
466 violations.push(format!(" {bench}: pin {pin}, not measured (stale pin)\n"));
467 }
468 }
469 }
470 violations
471}
473fn within_band(pin: u64, ir: u64) -> bool {
474 u128::from(ir.abs_diff(pin)) * 100 <= u128::from(pin) * u128::from(BAND_PERCENT)
475}
477/// Signed change of `ir` against `pin` in percent, two decimals.
478fn delta(pin: u64, ir: u64) -> String {
479 if pin == 0 {
480 return "n/a".to_string();
481 }
482 let basis_points = (i128::from(ir) - i128::from(pin)) * 10_000 / i128::from(pin);
483 let sign = if basis_points < 0 { '-' } else { '+' };
484 let magnitude = basis_points.unsigned_abs();
485 format!("{sign}{}.{:02} %", magnitude / 100, magnitude % 100)
486}
488/// `target/report/perf.md`: every measured bench against its pin, with the
489/// toolchain the counts belong to.
490fn write_perf_report(
491 measured: &BTreeMap<String, u64>,
492 pins: &BTreeMap<String, u64>,
493 complete: bool,
494 toolchain: &str,
495) -> ExitCode {
496 use std::fmt::Write as _;
497 let mut table = format!(
498 "Callgrind instruction counts (`Ir`) against `{BUDGETS}`, band ±{BAND_PERCENT} %.\n\n\
499 Toolchain: `{toolchain}`.\n\n| bench | ir | pin | delta |\n|---|---|---|---|\n"
500 );
501 for (bench, ir) in measured {
502 let (pin, change) = pins.get(bench).map_or_else(
503 || ("none".to_string(), "n/a".to_string()),
504 |pin| (pin.to_string(), delta(*pin, *ir)),
505 );
506 let _ = writeln!(table, "| `{bench}` | {ir} | {pin} | {change} |");
507 }
508 if complete {
509 for (bench, pin) in pins
510 .iter()
511 .filter(|(bench, _)| !measured.contains_key(*bench))
512 {
513 let _ = writeln!(table, "| `{bench}` | not measured | {pin} | n/a |");
514 }
515 }
516 let out = target_dir().join("report");
517 if fs::create_dir_all(&out).is_err() || fs::write(out.join("perf.md"), table).is_err() {
518 return fail("cannot write target/report/perf.md\n");
519 }
520 ExitCode::SUCCESS
521}
523/// `rustc --version` of the toolchain building the benches.
524fn toolchain() -> String {
525 Command::new("rustc")
526 .arg("--version")
527 .output()
528 .ok()
529 .filter(|output| output.status.success())
530 .map_or_else(
531 || "rustc version unavailable".to_string(),
532 |output| String::from_utf8_lossy(&output.stdout).trim().to_string(),
533 )
534}
536/// `extra` without one leading `--`: `cargo x cmd -- args` and
537/// `cargo x cmd args` pass the same arguments on.
538fn without_separator(extra: &[OsString]) -> &[OsString] {
539 match extra.split_first() {
540 Some((first, rest)) if first == "--" => rest,
541 _ => extra,
542 }
543}
204545fn cargo_fmt_step(extra: &[OsString]) -> ExitCode {
205546 let args = scoped(&["fmt", "--check"], extra);
206547 run_os("cargo", &args)
240581 targets
243/// Test targets may assert, panic, and print: outcomes are the point.
244/// Pedantic relaxes too; correctness lints stay on so test quality is
245/// still policed.
584/// Test and bench targets may assert, panic, and print: outcomes are the
585/// point. Pedantic relaxes too; correctness lints stay on so test quality
586/// is still policed.
246587fn clippy_tests(extra: &[OsString]) -> ExitCode {
247588 clippy_phase(
248 &["--tests"],
589 &["--tests", "--benches"],
249590 &[
250591 "-A",
251592 "clippy::unwrap_used",
395736/// Every tier's evidence in one bundle under `target/report/`: `JUnit` per
396/// tier, lcov plus HTML coverage, the last mutation run, and an `index.md`
397/// that summarizes them. Mutation results are read, never run here; the
398/// nightly job runs `mutants` first. Passthrough scopes the test tiers.
737/// tier, lcov plus HTML coverage, the last mutation run, the last
738/// instruction-budget table, hyperfine wall-clock rows, and an `index.md`
739/// that summarizes them. Mutation and perf results are read, never run
740/// here; `mutants` and `perf` run first. Passthrough scopes the test tiers.
399741fn report(extra: &[OsString]) -> ExitCode {
400742 use std::fmt::Write as _;
401743 let ran = coverage_tiers(extra);
403745 return ran;
404746 }
405747 let out = target_dir().join("report");
748 // `cargo x perf` writes into the bundle directory; keep its table
749 // across the reset.
750 let perf = fs::read_to_string(out.join("perf.md")).ok();
406751 let _ = std::fs::remove_dir_all(&out);
407752 if std::fs::create_dir_all(out.join("junit")).is_err() {
408753 return fail("cannot create target/report\n");
460805 }
461806 None => index.push_str("No mutation run found; run `cargo x mutants` first.\n"),
462807 }
808 index.push_str("\n## Instructions\n\n");
809 match perf {
810 Some(table) => {
811 let _ = std::fs::write(out.join("perf.md"), &table);
812 index.push_str(&table);
813 }
814 None => index.push_str("No perf run found; run `cargo x perf` first.\n"),
815 }
816 index.push_str("\n## Wall clock\n\n");
817 index.push_str(&wall_clock(&out));
463818 if std::fs::write(out.join("index.md"), index).is_err() {
464819 return fail("cannot write target/report/index.md\n");
465820 }
467822 ExitCode::SUCCESS
825/// Wall-clock rows of the release binary through hyperfine, isolated like
826/// the e2e tests. Informational only: the numbers hold for this machine
827/// and this run, so a missing tool or a failed run is a note, never a
828/// report failure.
829fn wall_clock(out: &Path) -> String {
830 let present = Command::new("hyperfine")
831 .arg("--version")
832 .stdout(std::process::Stdio::null())
833 .stderr(std::process::Stdio::null())
834 .status()
835 .is_ok_and(|status| status.success());
836 if !present {
837 return "hyperfine not on PATH; no wall-clock rows.\n".to_string();
838 }
839 let Ok(smith) = release_smith() else {
840 return "release build of smith failed; no wall-clock rows.\n".to_string();
841 };
842 let home = target_dir().join("wall-clock-home");
843 let markdown = out.join("hyperfine.md");
844 let mut command = Command::new("hyperfine");
845 command
846 .args(["--warmup", "3", "--runs", "20", "--export-json"])
847 .arg(out.join("hyperfine.json"))
848 .arg("--export-markdown")
849 .arg(&markdown)
850 // A fresh profile per run: `eval` appends to its session otherwise.
851 .arg("--prepare")
852 .arg(format!("rm -rf '{}'", home.display()))
853 .args(["--command-name", "smith --help"])
854 .args(["--command-name", "smith eval --mock hello"])
855 .arg(format!("'{}' --help", smith.display()))
856 .arg(format!("'{}' eval --mock hello", smith.display()));
857 for (key, dir) in dev_home_dirs() {
858 command.env(key, home.join(dir));
859 }
860 for var in PROVIDER_VARS {
861 command.env_remove(var);
862 }
863 let ran = command.status().is_ok_and(|status| status.success());
864 match fs::read_to_string(&markdown) {
865 Ok(rows) if ran => format!(
866 "Informational, never a gate: {}-{}, {} hardware threads, this run only; raw data in `hyperfine.json`.\n\n{rows}",
867 env::consts::OS,
868 env::consts::ARCH,
869 std::thread::available_parallelism().map_or(0, std::num::NonZero::get),
870 ),
871 _ => "hyperfine run failed; no wall-clock rows.\n".to_string(),
872 }
873}
470875/// `tests`, `failures`, `errors` from a `JUnit` `<testsuites>` root.
471876fn junit_counts(xml: &str) -> [u64; 3] {
472877 let root = xml
586991 if !extra.is_empty() {
587992 return fail("bootstrap installs tools and admits no scoping\n");
588993 }
589 let steps: [Step; 7] = [
994 let steps: [Step; 8] = [
590995 install_binstall,
591996 install_nextest,
592997 install_machete,
594999 install_audit,
5951000 install_mutants,
5961001 install_llvm_cov,
1002 install_gungraun_runner,
5971003 ];
5981004 sequence(&steps, extra)
6131019fn install_deny(_extra: &[OsString]) -> ExitCode {
614 tool_present_bin("cargo-deny", DENY_VERSION, || {
615 cargo(&[
616 "binstall",
617 "--no-confirm",
618 &format!("cargo-deny@{DENY_VERSION}"),
619 ])
620 })
1020 binstall("cargo-deny", DENY_VERSION)
6231023fn install_audit(_extra: &[OsString]) -> ExitCode {
624 tool_present_bin("cargo-audit", AUDIT_VERSION, || {
625 cargo(&[
626 "binstall",
627 "--no-confirm",
628 &format!("cargo-audit@{AUDIT_VERSION}"),
629 ])
630 })
1024 binstall("cargo-audit", AUDIT_VERSION)
6331027fn install_mutants(_extra: &[OsString]) -> ExitCode {
634 tool_present_bin("cargo-mutants", MUTANTS_VERSION, || {
635 cargo(&[
636 "binstall",
637 "--no-confirm",
638 &format!("cargo-mutants@{MUTANTS_VERSION}"),
639 ])
640 })
1028 binstall("cargo-mutants", MUTANTS_VERSION)
1031fn install_gungraun_runner(_extra: &[OsString]) -> ExitCode {
1032 binstall("gungraun-runner", GUNGRAUN_VERSION)
6431035fn install_llvm_cov(_extra: &[OsString]) -> ExitCode {
644 let tool = tool_present_bin("cargo-llvm-cov", LLVM_COV_VERSION, || {
645 cargo(&[
646 "binstall",
647 "--no-confirm",
648 &format!("cargo-llvm-cov@{LLVM_COV_VERSION}"),
649 ])
650 });
1036 let tool = binstall("cargo-llvm-cov", LLVM_COV_VERSION);
6511037 if tool != ExitCode::SUCCESS {
6521038 return tool;
6741060fn install_nextest(_extra: &[OsString]) -> ExitCode {
675 tool_present_bin("cargo-nextest", NEXTEST_VERSION, || {
676 cargo(&[
677 "binstall",
678 &format!("cargo-nextest@{NEXTEST_VERSION}"),
679 "--no-confirm",
680 ])
1061 binstall("cargo-nextest", NEXTEST_VERSION)
1064/// Install the prebuilt `tool` at `version` through `cargo-binstall`
1065/// unless that version is already on PATH.
1066fn binstall(tool: &str, version: &str) -> ExitCode {
1067 tool_present_bin(tool, version, || {
1068 cargo(&["binstall", "--no-confirm", &format!("{tool}@{version}")])
6811069 })
8221210 ));
1213 if rule.crate_name != "smith-bench" && names_dependency(&manifest, "smith-bench") {
1214 return fail(&format!(
1215 "{} must not depend on smith-bench, not even from tests\n",
1216 rule.crate_name
1217 ));
1218 }
8251219 if LIBRARY_CRATES.contains(&rule.crate_name)
8261220 && let Some(offender) = mutex_in_production(Path::new(rule.crate_name))
9931387 crate_name: "smith-alloc",
9941388 allowed: &[],
9951389 },
1390 DependencyRule {
1391 crate_name: "smith-bench",
1392 allowed: &[
1393 "smith",
1394 "smith-core",
1395 "smith-ai",
1396 "smith-ui",
1397 "smith-tui",
1398 "smith-rpc",
1399 "smith-harness",
1400 "smith-cli",
1401 "smith-alloc",
1402 "xtask",
1403 ],
1404 },
9961405 DependencyRule {
9971406 crate_name: "xtask",
9981407 allowed: &[],
10131422 })
1425/// Whether any dependency table of `manifest`, dev and target tables
1426/// included, names `crate_name`.
1427fn names_dependency(manifest: &str, crate_name: &str) -> bool {
1428 let assignment = format!("{crate_name} =");
1429 let table = format!(".{crate_name}]");
1430 manifest.lines().any(|line| {
1431 let trimmed = line.trim();
1432 trimmed.starts_with(&assignment) || (trimmed.starts_with('[') && trimmed.ends_with(&table))
1433 })
10161436fn fail(message: &str) -> ExitCode {
10171437 let _ignored = std::io::stderr().write_all(message.as_bytes());
10181438 ExitCode::FAILURE
11241544 std::env::var_os("CARGO_TARGET_DIR").map_or_else(|| PathBuf::from("target"), PathBuf::from)
1547 use super::{
1548 BTreeMap, bench_ir, budget_violations, delta, names_dependency, parse_budgets,
1549 render_budgets, without_separator,
1550 };
1552 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"}"#;
1554 #[test]
1555 fn bench_ir_reads_the_total_of_first_and_repeated_runs() {
1556 assert_eq!(
1557 bench_ir(FIRST_RUN),
1558 Some((
1559 "instructions::session::encode::linear_1000".to_string(),
1560 5_736_448
1561 ))
1562 );
1563 let repeated = FIRST_RUN.replace(
1564 r#""total":{"regressions":[],"summary":{"Callgrind":{"Ir":{"diffs":null,"metrics":{"Left":{"Int":5736448}}}}}}"#,
1565 r#""total":{"regressions":[],"summary":{"Callgrind":{"Ir":{"diffs":{"diff_pct":0.1},"metrics":{"Both":[{"Int":5736500},{"Int":5736448}]}}}}}"#,
1566 );
1567 assert_eq!(bench_ir(&repeated).map(|(_, ir)| ir), Some(5_736_500));
1568 assert_eq!(bench_ir(r#"{"module_path":"a","id":"b"}"#), None);
1569 }
1571 #[test]
1572 fn budgets_round_trip_sorted_and_reject_other_shapes() {
1573 let pins = BTreeMap::from([
1574 ("b::g::f::x".to_string(), 7),
1575 ("a::g::f::y".to_string(), 42),
1576 ]);
1577 let text = render_budgets(&pins, "rustc 1.0.0");
1578 assert!(text.find("a::g::f::y").unwrap() < text.find("b::g::f::x").unwrap());
1579 assert_eq!(parse_budgets(&text).unwrap(), pins);
1580 assert!(
1581 parse_budgets("\"a\" = { ir = 1 }\n").is_err(),
1582 "outside [budgets]"
1583 );
1584 assert!(parse_budgets("[budgets]\n\"a\" = 1\n").is_err());
1585 assert!(parse_budgets("[budgets]\n\"a\" = { ir = 1 }\n\"a\" = { ir = 2 }\n").is_err());
1586 }
1588 #[test]
1589 fn violations_cover_both_directions_missing_and_stale_pins() {
1590 let pins = BTreeMap::from([
1591 ("low".to_string(), 1000),
1592 ("edge".to_string(), 1000),
1593 ("high".to_string(), 1000),
1594 ("stale".to_string(), 5),
1595 ]);
1596 let measured = BTreeMap::from([
1597 ("low".to_string(), 979),
1598 ("edge".to_string(), 1020),
1599 ("high".to_string(), 1021),
1600 ("new".to_string(), 3),
1601 ]);
1602 let found = budget_violations(&measured, &pins, true).concat();
1603 for bench in ["low:", "high:", "new:", "stale:"] {
1604 assert!(found.contains(bench), "{bench} in {found}");
1605 }
1606 assert!(!found.contains("edge:"), "{found}");
1607 let filtered = budget_violations(&measured, &pins, false).concat();
1608 assert!(!filtered.contains("stale:"), "{filtered}");
1609 }
1611 #[test]
1612 fn delta_keeps_the_sign_below_one_percent() {
1613 assert_eq!(delta(1000, 995), "-0.50 %");
1614 assert_eq!(delta(1000, 1025), "+2.50 %");
1615 assert_eq!(delta(0, 5), "n/a");
1616 }
1618 #[test]
1619 fn separator_is_stripped_once() {
1620 let args = ["--", "--", "x"].map(std::ffi::OsString::from);
1621 assert_eq!(without_separator(&args), &args[1..]);
1622 assert_eq!(without_separator(&args[2..]), &args[2..]);
1623 }
1625 #[test]
1626 fn names_dependency_sees_dev_and_target_tables() {
1627 assert!(names_dependency(
1628 "[dev-dependencies]\nsmith-bench = { path = \"..\" }",
1629 "smith-bench"
1630 ));
1631 assert!(names_dependency(
1632 "[target.'cfg(unix)'.dev-dependencies.smith-bench]",
1633 "smith-bench"
1634 ));
1635 assert!(!names_dependency("name = \"smith-bench\"", "smith-bench"));
1636 }
11271638 #[test]
11281639 fn detects_inline_and_table_dependencies() {
11291640 assert!(has_dependency(