Skip to main content

rust_anything/
card.rs

1//! `report`: a unit's result as Markdown and an SVG card, for a pull request or a README.
2//!
3//! Every number comes from a run made for the report: `diff` for the recorded cases that
4//! match, `bench` for the speedup, and the cases of functions the Rust module does not provide
5//! for the fallback rate. The machine and its core count go next to the timing.
6
7use std::collections::BTreeMap;
8use std::fmt::Write as _;
9use std::path::{Path, PathBuf};
10
11use anyhow::{Context, Result};
12use serde::Serialize;
13
14use crate::bridge::Manifest;
15use crate::harness::{self, BenchRow};
16use crate::walk::Canonical;
17
18pub const SCHEMA: &str = "rust-anything/report@1";
19
20#[derive(Debug, Serialize)]
21pub struct Card {
22    pub schema: &'static str,
23    pub crate_name: String,
24    pub unit: String,
25    pub language: String,
26    pub functions: Vec<String>,
27    pub cases: usize,
28    pub matched: usize,
29    /// Geometric mean of `original_ns / rust_ns` over the timed functions, call included.
30    pub speedup: f64,
31    pub bench: Vec<BenchRow>,
32    /// Recorded cases whose function the Rust module does not provide, so the original answers.
33    pub fallback_cases: usize,
34    /// `Some(true)` while `enable` has switched the unit on; `None` where `enable` does not apply.
35    pub enabled: Option<bool>,
36    pub machine: String,
37    pub markdown: PathBuf,
38    pub svg: PathBuf,
39}
40
41impl Card {
42    pub fn fallback_rate(&self) -> f64 {
43        if self.cases == 0 {
44            0.0
45        } else {
46            self.fallback_cases as f64 / self.cases as f64
47        }
48    }
49}
50
51pub struct Options<'a> {
52    pub crate_dir: &'a Path,
53    pub out: Option<&'a Path>,
54    pub min_ms: u64,
55    pub node_args: &'a [String],
56}
57
58pub fn report(opts: &Options) -> Result<Card> {
59    let crate_dir = opts
60        .crate_dir
61        .canonical()
62        .with_context(|| format!("resolving {}", opts.crate_dir.display()))?;
63    let manifest = Manifest::load(&crate_dir)?;
64    harness::build(&crate_dir)?;
65    let diff = harness::diff(&harness::DiffOptions {
66        crate_dir: &crate_dir,
67        module: None,
68        ignore_key_order: false,
69        node_args: opts.node_args,
70        float_tolerance: None,
71    })?;
72    let bench = harness::bench(&harness::BenchOptions {
73        crate_dir: &crate_dir,
74        min_ms: opts.min_ms,
75        resolve_from: None,
76        node_args: opts.node_args,
77    })?;
78    let verdict = harness::verdict(&bench, manifest.language);
79    let per_function = cases_per_function(&crate_dir);
80    let fallback_cases = diff
81        .missing
82        .iter()
83        .map(|f| per_function.get(f).copied().unwrap_or(0))
84        .sum();
85    let out = opts
86        .out
87        .map_or_else(|| crate_dir.join("report"), Path::to_path_buf);
88    std::fs::create_dir_all(&out).with_context(|| format!("creating {}", out.display()))?;
89    let mut card = Card {
90        schema: SCHEMA,
91        crate_name: manifest.crate_name.clone(),
92        unit: manifest.unit.clone(),
93        language: manifest.language.name().to_string(),
94        functions: manifest.exports.iter().map(|f| f.name.clone()).collect(),
95        cases: diff.total,
96        matched: diff.passed,
97        speedup: verdict.speedup,
98        bench,
99        fallback_cases,
100        enabled: crate::enable::is_enabled(&crate_dir).ok(),
101        machine: machine(),
102        markdown: out.join("REPORT.md"),
103        svg: out.join("card.svg"),
104    };
105    card.enabled = card
106        .enabled
107        .filter(|_| crate::enable::is_supported(&manifest));
108    std::fs::write(&card.svg, svg(&card))?;
109    std::fs::write(&card.markdown, markdown(&card))?;
110    Ok(card)
111}
112
113fn cases_per_function(crate_dir: &Path) -> BTreeMap<String, usize> {
114    let mut out = BTreeMap::new();
115    let text = std::fs::read_to_string(crate_dir.join(harness::CASES)).unwrap_or_default();
116    for line in text.lines() {
117        if let Ok(case) = serde_json::from_str::<serde_json::Value>(line)
118            && let Some(name) = case["fn"].as_str()
119        {
120            *out.entry(name.to_string()).or_default() += 1;
121        }
122    }
123    out
124}
125
126/// The CPU's name and its core count, as `bench` numbers must be published with.
127pub fn machine() -> String {
128    let cores = std::thread::available_parallelism().map_or(0, std::num::NonZero::get);
129    let mut cmd = std::process::Command::new("sysctl");
130    cmd.args(["-n", "machdep.cpu.brand_string"]);
131    let name = crate::process::output(&mut cmd, crate::process::QUICK)
132        .ok()
133        .filter(crate::process::Output::success)
134        .map(|o| o.stdout_text().trim().to_string())
135        .filter(|s| !s.is_empty())
136        .or_else(|| {
137            std::fs::read_to_string("/proc/cpuinfo").ok().and_then(|t| {
138                t.lines()
139                    .find(|l| l.starts_with("model name"))
140                    .and_then(|l| l.split_once(':'))
141                    .map(|(_, v)| v.trim().to_string())
142            })
143        })
144        .unwrap_or_else(|| std::env::consts::ARCH.to_string());
145    let os = match std::env::consts::OS {
146        "macos" => "macOS",
147        "linux" => "Linux",
148        "windows" => "Windows",
149        other => other,
150    };
151    format!("{name}, {cores} cores, {os}")
152}
153
154fn times(x: f64) -> String {
155    if x >= 10.0 {
156        format!("{x:.0}x")
157    } else {
158        format!("{x:.1}x")
159    }
160}
161
162fn ns(v: f64) -> String {
163    if v >= 1e9 {
164        format!("{:.2} s", v / 1e9)
165    } else if v >= 1e6 {
166        format!("{:.1} ms", v / 1e6)
167    } else if v >= 1e3 {
168        format!("{:.1} µs", v / 1e3)
169    } else {
170        format!("{v:.0} ns")
171    }
172}
173
174fn state(card: &Card) -> &'static str {
175    match card.enabled {
176        Some(true) => "on",
177        Some(false) => "off",
178        None => "not switched by `enable`",
179    }
180}
181
182pub fn markdown(card: &Card) -> String {
183    let mut out = format!(
184        "## `{}` in Rust\n\n![{} report card](card.svg)\n\n\
185         | | |\n| --- | --- |\n\
186         | Unit | `{}` ({}) |\n\
187         | Recorded cases matched | {} / {} |\n\
188         | Speedup, call included | {} (geometric mean) |\n\
189         | Fallback to the original | {:.1}% ({} of {} cases) |\n\
190         | Switched on | {} |\n\n",
191        card.crate_name,
192        card.crate_name,
193        card.unit,
194        card.language,
195        card.matched,
196        card.cases,
197        times(card.speedup),
198        100.0 * card.fallback_rate(),
199        card.fallback_cases,
200        card.cases,
201        state(card),
202    );
203    if !card.bench.is_empty() {
204        out.push_str(
205            "| Function | Cases | Original per call | Rust per call | Speedup |\n| --- | ---: | ---: | ---: | ---: |\n",
206        );
207        for r in &card.bench {
208            let _ = writeln!(
209                out,
210                "| `{}` | {} | {} | {} | {} |",
211                r.name,
212                r.cases,
213                ns(r.original_ns),
214                ns(r.rust_ns),
215                times(r.speedup)
216            );
217        }
218        out.push('\n');
219    }
220    let _ = writeln!(
221        out,
222        "Measured with `rust-anything report` on {}: `diff` replays every recorded case, `bench` \
223         times them on both sides as callers call them. Reproduce: `rust-anything diff` and \
224         `rust-anything bench` in the crate folder.",
225        card.machine
226    );
227    out
228}
229
230fn esc(s: &str) -> String {
231    s.replace('&', "&amp;")
232        .replace('<', "&lt;")
233        .replace('>', "&gt;")
234        .replace('"', "&quot;")
235}
236
237/// Light card in the v3 style: white, an outlined panel for the original, a tinted orange one
238/// for Rust, the headline result below.
239pub fn svg(card: &Card) -> String {
240    const W: u32 = 1200;
241    const H: u32 = 600;
242    let font = "-apple-system, BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial, sans-serif";
243    let mono = "ui-monospace, SFMono-Regular, Menlo, Consolas, monospace";
244    let (orig, rust) = card
245        .bench
246        .iter()
247        .fold((0.0, 0.0), |(o, r), b| (o + b.original_ns, r + b.rust_ns));
248    let max = orig.max(rust).max(1.0);
249    let bar = |v: f64| (5.0_f64).max(470.0 * v / max);
250    let all = card.matched == card.cases && card.cases > 0;
251    let headline = if all {
252        format!(
253            "Same result as the original on all {} recorded cases",
254            card.cases
255        )
256    } else {
257        format!(
258            "{} of {} recorded cases match the original",
259            card.matched, card.cases
260        )
261    };
262    let per_call = if card.bench.len() == 1 {
263        "per call"
264    } else {
265        "per call, all functions"
266    };
267    format!(
268        r##"<svg xmlns="http://www.w3.org/2000/svg" width="{W}" height="{H}" viewBox="0 0 {W} {H}" role="img" aria-label="{label}">
269<rect width="{W}" height="{H}" fill="#ffffff"/>
270<g font-family="{font}">
271<svg x="64" y="52" width="60" height="60" viewBox="0 0 200 200">{crab}</svg>
272<text x="140" y="94" font-size="34" font-weight="700" fill="#1a1a1a">rust-anything</text>
273<text x="380" y="94" font-size="{title_size}" font-weight="700" fill="#1a1a1a">{name}, ported to <tspan fill="#e8561a">Rust</tspan></text>
274<text x="64" y="140" font-size="18" fill="#666666">{unit} ({lang}) · {functions}</text>
275<rect x="64" y="172" width="520" height="230" rx="20" fill="#ffffff" stroke="#e5e5e5" stroke-width="3"/>
276<text x="96" y="218" font-size="26" font-weight="700" fill="#1a1a1a">Original</text>
277<text x="552" y="218" font-size="17" fill="#666666" text-anchor="end">{per_call}</text>
278<text x="96" y="318" font-family="{mono}" font-size="64" font-weight="700" fill="#1a1a1a">{orig_t}</text>
279<rect x="96" y="360" width="{orig_w:.0}" height="14" rx="7" fill="#9e9e9e"/>
280<rect x="616" y="172" width="520" height="230" rx="20" fill="#fdf4ef" stroke="#f2b89a" stroke-width="3"/>
281<text x="648" y="218" font-size="26" font-weight="700" fill="#1a1a1a">Rust port</text>
282<text x="1104" y="218" font-size="17" fill="#666666" text-anchor="end">switched {state}</text>
283<text x="648" y="318" font-family="{mono}" font-size="64" font-weight="700" fill="#e8561a">{rust_t}</text>
284<rect x="648" y="360" width="{rust_w:.0}" height="14" rx="7" fill="#e8561a"/>
285<text x="600" y="460" font-size="28" fill="#1a1a1a" text-anchor="middle">{headline}: <tspan font-weight="700" fill="#e8561a">{speed}</tspan></text>
286<text x="600" y="500" font-size="18" fill="#777777" text-anchor="middle">Fallback to the original: {fallback:.1}% of cases · call included · {machine}</text>
287<text x="600" y="556" font-size="17" fill="#888888" text-anchor="middle">github.com/erkamyaman/rust-anything</text>
288</g>
289</svg>
290"##,
291        label = esc(&format!(
292            "{}: {} of {} recorded cases match, {} faster",
293            card.crate_name,
294            card.matched,
295            card.cases,
296            times(card.speedup)
297        )),
298        name = esc(&card.crate_name),
299        title_size = if card.crate_name.chars().count() > 22 {
300            24
301        } else {
302            34
303        },
304        unit = esc(&card.unit),
305        lang = esc(&card.language),
306        functions = esc(&card.functions.join(", ")),
307        orig_t = esc(&ns(orig)),
308        rust_t = esc(&ns(rust)),
309        orig_w = bar(orig),
310        rust_w = bar(rust),
311        state = if card.enabled == Some(true) {
312            "on"
313        } else {
314            "off"
315        },
316        speed = if card.speedup >= 1.0 {
317            format!("{} faster", times(card.speedup))
318        } else {
319            format!("{} slower", times(1.0 / card.speedup.max(1e-9)))
320        },
321        crab = include_str!("card_crab.svg").trim(),
322        fallback = 100.0 * card.fallback_rate(),
323        machine = esc(&card.machine),
324    )
325}
326
327#[cfg(test)]
328mod tests {
329    use super::*;
330
331    fn card() -> Card {
332        Card {
333            schema: SCHEMA,
334            crate_name: "fuzzy-rs".into(),
335            unit: "app.py".into(),
336            language: "Python".into(),
337            functions: vec!["dedupe".into()],
338            cases: 412,
339            matched: 412,
340            speedup: 31.4,
341            bench: vec![BenchRow {
342                name: "dedupe".into(),
343                cases: 412,
344                original_ns: 9_120_000.0,
345                rust_ns: 290_000.0,
346                speedup: 31.4,
347            }],
348            fallback_cases: 0,
349            enabled: Some(true),
350            machine: "Apple M4, 10 cores, macOS".into(),
351            markdown: "REPORT.md".into(),
352            svg: "card.svg".into(),
353        }
354    }
355
356    #[test]
357    fn the_card_shows_what_was_measured() {
358        let svg = svg(&card());
359        assert!(svg.starts_with("<svg"), "{svg}");
360        for want in [
361            "fuzzy-rs",
362            "9.1 ms",
363            "290.0 µs",
364            "all 412 recorded cases",
365            "31x faster",
366            "switched on",
367            "0.0% of cases",
368            "Apple M4, 10 cores",
369        ] {
370            assert!(svg.contains(want), "{want} missing:\n{svg}");
371        }
372        let md = markdown(&card());
373        assert!(
374            md.contains("| Recorded cases matched | 412 / 412 |"),
375            "{md}"
376        );
377        assert!(
378            md.contains("| `dedupe` | 412 | 9.1 ms | 290.0 µs | 31x |"),
379            "{md}"
380        );
381    }
382
383    #[test]
384    fn text_from_the_project_is_escaped() {
385        let mut c = card();
386        c.unit = "src/<a&b>.ts".into();
387        c.matched = 400;
388        let svg = svg(&c);
389        assert!(svg.contains("src/&lt;a&amp;b&gt;.ts"));
390        assert!(svg.contains("400 of 412 recorded cases match"));
391    }
392}