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    /// Resolve npm packages the original imports from this folder's `node_modules`, as `bench` does.
57    pub resolve_from: Option<&'a Path>,
58}
59
60pub fn report(opts: &Options) -> Result<Card> {
61    let crate_dir = opts.crate_dir.canonical().with_context(|| {
62        format!(
63            "resolving {} (run `rust-anything bridge` first)",
64            opts.crate_dir.display()
65        )
66    })?;
67    let manifest = Manifest::load(&crate_dir)?;
68    harness::build(&crate_dir)?;
69    let diff = harness::diff(&harness::DiffOptions {
70        crate_dir: &crate_dir,
71        module: None,
72        ignore_key_order: false,
73        node_args: opts.node_args,
74        float_tolerance: None,
75    })?;
76    let bench = harness::bench(&harness::BenchOptions {
77        crate_dir: &crate_dir,
78        min_ms: opts.min_ms,
79        resolve_from: opts.resolve_from,
80        node_args: opts.node_args,
81    })?;
82    let verdict = harness::verdict(&bench, manifest.language);
83    let per_function = cases_per_function(&crate_dir);
84    let fallback_cases = diff
85        .missing
86        .iter()
87        .map(|f| per_function.get(f).copied().unwrap_or(0))
88        .sum();
89    let out = opts
90        .out
91        .map_or_else(|| crate_dir.join("report"), Path::to_path_buf);
92    std::fs::create_dir_all(&out).with_context(|| format!("creating {}", out.display()))?;
93    let mut card = Card {
94        schema: SCHEMA,
95        crate_name: manifest.crate_name.clone(),
96        unit: manifest.unit.clone(),
97        language: manifest.language.name().to_string(),
98        functions: manifest.exports.iter().map(|f| f.name.clone()).collect(),
99        cases: diff.total,
100        matched: diff.passed,
101        speedup: verdict.speedup,
102        bench,
103        fallback_cases,
104        enabled: crate::enable::is_enabled(&crate_dir).ok(),
105        machine: machine(),
106        markdown: out.join("REPORT.md"),
107        svg: out.join("card.svg"),
108    };
109    card.enabled = card
110        .enabled
111        .filter(|_| crate::enable::is_supported(&manifest));
112    std::fs::write(&card.svg, svg(&card))?;
113    std::fs::write(&card.markdown, markdown(&card))?;
114    Ok(card)
115}
116
117fn cases_per_function(crate_dir: &Path) -> BTreeMap<String, usize> {
118    let mut out = BTreeMap::new();
119    let text = std::fs::read_to_string(crate_dir.join(harness::CASES)).unwrap_or_default();
120    for line in text.lines() {
121        if let Ok(case) = serde_json::from_str::<serde_json::Value>(line)
122            && let Some(name) = case["fn"].as_str()
123        {
124            *out.entry(name.to_string()).or_default() += 1;
125        }
126    }
127    out
128}
129
130/// The CPU's name and its core count, as `bench` numbers must be published with.
131pub fn machine() -> String {
132    let cores = std::thread::available_parallelism().map_or(0, std::num::NonZero::get);
133    let mut cmd = std::process::Command::new("sysctl");
134    cmd.args(["-n", "machdep.cpu.brand_string"]);
135    let name = crate::process::output(&mut cmd, crate::process::QUICK)
136        .ok()
137        .filter(crate::process::Output::success)
138        .map(|o| o.stdout_text().trim().to_string())
139        .filter(|s| !s.is_empty())
140        .or_else(|| {
141            std::fs::read_to_string("/proc/cpuinfo").ok().and_then(|t| {
142                t.lines()
143                    .find(|l| l.starts_with("model name"))
144                    .and_then(|l| l.split_once(':'))
145                    .map(|(_, v)| v.trim().to_string())
146            })
147        })
148        .unwrap_or_else(|| std::env::consts::ARCH.to_string());
149    let os = match std::env::consts::OS {
150        "macos" => "macOS",
151        "linux" => "Linux",
152        "windows" => "Windows",
153        other => other,
154    };
155    format!("{name}, {cores} cores, {os}")
156}
157
158fn times(x: f64) -> String {
159    // The boundary is where the one-decimal form would read `10.0x`: print the whole number it
160    // already shows instead of a decimal that adds nothing.
161    if x >= 9.95 {
162        format!("{x:.0}x")
163    } else {
164        format!("{x:.1}x")
165    }
166}
167
168/// "Nx faster" at or above parity, "Nx slower" below it, the way the card's headline reads.
169fn speed_phrase(speedup: f64) -> String {
170    if speedup >= 1.0 {
171        format!("{} faster", times(speedup))
172    } else {
173        format!("{} slower", times(1.0 / speedup.max(1e-9)))
174    }
175}
176
177/// A table cell keeps the bare `Nx` for a faster port; below parity it names the slowdown so a
178/// speedup like 0.04 can never print as `0.0x`.
179fn table_speed(speedup: f64) -> String {
180    if speedup >= 1.0 {
181        times(speedup)
182    } else {
183        speed_phrase(speedup)
184    }
185}
186
187/// Each threshold is the value at which the unit below it would print as `1000` of that unit,
188/// rounded: `999_999 ns` is `1000.0 µs`, so it belongs in `ms`.
189fn ns(v: f64) -> String {
190    if v >= 999_950_000.0 {
191        format!("{:.2} s", v / 1e9)
192    } else if v >= 999_950.0 {
193        format!("{:.1} ms", v / 1e6)
194    } else if v >= 999.5 {
195        format!("{:.1} µs", v / 1e3)
196    } else {
197        format!("{v:.0} ns")
198    }
199}
200
201/// Only none or all of the cases print as `0.0%` or `100.0%`; a share that rounds to either
202/// reads `<0.1%` or `>99.9%`.
203fn fallback_percent(card: &Card) -> String {
204    let share = format!("{:.1}", 100.0 * card.fallback_rate());
205    if card.fallback_cases > 0 && share == "0.0" {
206        "<0.1%".into()
207    } else if card.fallback_cases < card.cases && share == "100.0" {
208        ">99.9%".into()
209    } else {
210        format!("{share}%")
211    }
212}
213
214fn state(card: &Card) -> &'static str {
215    match card.enabled {
216        Some(true) => "on",
217        Some(false) => "off",
218        None => "not switched by `enable`",
219    }
220}
221
222pub fn markdown(card: &Card) -> String {
223    let mut out = format!(
224        "## `{}` in Rust\n\n![{} report card](card.svg)\n\n\
225         | | |\n| --- | --- |\n\
226         | Unit | `{}` ({}) |\n\
227         | Recorded cases matched | {} / {} |\n\
228         | Speedup, call included | {} (geometric mean) |\n\
229         | Fallback to the original | {} ({} of {} cases) |\n\
230         | Switched on | {} |\n\n",
231        card.crate_name,
232        card.crate_name,
233        card.unit,
234        card.language,
235        card.matched,
236        card.cases,
237        table_speed(card.speedup),
238        fallback_percent(card),
239        card.fallback_cases,
240        card.cases,
241        state(card),
242    );
243    if !card.bench.is_empty() {
244        out.push_str(
245            "| Function | Cases | Original per call | Rust per call | Speedup |\n| --- | ---: | ---: | ---: | ---: |\n",
246        );
247        for r in &card.bench {
248            let _ = writeln!(
249                out,
250                "| `{}` | {} | {} | {} | {} |",
251                r.name,
252                r.cases,
253                ns(r.original_ns),
254                ns(r.rust_ns),
255                table_speed(r.speedup)
256            );
257        }
258        out.push('\n');
259    }
260    let _ = writeln!(
261        out,
262        "Measured with `rust-anything report` on {}: `diff` replays every recorded case, `bench` \
263         times them on both sides as callers call them. Reproduce: `rust-anything diff` and \
264         `rust-anything bench` in the crate folder.",
265        card.machine
266    );
267    out
268}
269
270fn esc(s: &str) -> String {
271    s.replace('&', "&amp;")
272        .replace('<', "&lt;")
273        .replace('>', "&gt;")
274        .replace('"', "&quot;")
275}
276
277/// Light card in the v3 style: white, an outlined panel for the original, a tinted orange one
278/// for Rust, the headline result below.
279pub fn svg(card: &Card) -> String {
280    const W: u32 = 1200;
281    const H: u32 = 600;
282    let font = "-apple-system, BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial, sans-serif";
283    let mono = "ui-monospace, SFMono-Regular, Menlo, Consolas, monospace";
284    let (orig, rust) = card
285        .bench
286        .iter()
287        .fold((0.0, 0.0), |(o, r), b| (o + b.original_ns, r + b.rust_ns));
288    let max = orig.max(rust).max(1.0);
289    let bar = |v: f64| (5.0_f64).max(470.0 * v / max);
290    let all = card.matched == card.cases && card.cases > 0;
291    let headline = if all {
292        format!(
293            "Same result as the original on all {} recorded cases",
294            card.cases
295        )
296    } else {
297        format!(
298            "{} of {} recorded cases match the original",
299            card.matched, card.cases
300        )
301    };
302    let per_call = if card.bench.len() == 1 {
303        "per call"
304    } else {
305        "per call, all functions"
306    };
307    format!(
308        r##"<svg xmlns="http://www.w3.org/2000/svg" width="{W}" height="{H}" viewBox="0 0 {W} {H}" role="img" aria-label="{label}">
309<rect width="{W}" height="{H}" fill="#ffffff"/>
310<g font-family="{font}">
311<svg x="64" y="52" width="60" height="60" viewBox="0 0 200 200">{crab}</svg>
312<text x="140" y="94" font-size="34" font-weight="700" fill="#1a1a1a">rust-anything</text>
313<text x="380" y="94" font-size="{title_size}" font-weight="700" fill="#1a1a1a">{name}, ported to <tspan fill="#e8561a">Rust</tspan></text>
314<text x="64" y="140" font-size="18" fill="#666666">{unit} ({lang}) · {functions}</text>
315<rect x="64" y="172" width="520" height="230" rx="20" fill="#ffffff" stroke="#e5e5e5" stroke-width="3"/>
316<text x="96" y="218" font-size="26" font-weight="700" fill="#1a1a1a">Original</text>
317<text x="552" y="218" font-size="17" fill="#666666" text-anchor="end">{per_call}</text>
318<text x="96" y="318" font-family="{mono}" font-size="64" font-weight="700" fill="#1a1a1a">{orig_t}</text>
319<rect x="96" y="360" width="{orig_w:.0}" height="14" rx="7" fill="#9e9e9e"/>
320<rect x="616" y="172" width="520" height="230" rx="20" fill="#fdf4ef" stroke="#f2b89a" stroke-width="3"/>
321<text x="648" y="218" font-size="26" font-weight="700" fill="#1a1a1a">Rust port</text>
322<text x="1104" y="218" font-size="17" fill="#666666" text-anchor="end">switched {state}</text>
323<text x="648" y="318" font-family="{mono}" font-size="64" font-weight="700" fill="#e8561a">{rust_t}</text>
324<rect x="648" y="360" width="{rust_w:.0}" height="14" rx="7" fill="#e8561a"/>
325<text x="600" y="460" font-size="28" fill="#1a1a1a" text-anchor="middle">{headline}: <tspan font-weight="700" fill="#e8561a">{speed}</tspan></text>
326<text x="600" y="500" font-size="18" fill="#777777" text-anchor="middle">Fallback to the original: {fallback} of cases · call included · {machine}</text>
327<text x="600" y="556" font-size="17" fill="#888888" text-anchor="middle">github.com/erkamyaman/rust-anything</text>
328</g>
329</svg>
330"##,
331        label = esc(&format!(
332            "{}: {} of {} recorded cases match, {}",
333            card.crate_name,
334            card.matched,
335            card.cases,
336            speed_phrase(card.speedup)
337        )),
338        name = esc(&card.crate_name),
339        title_size = if card.crate_name.chars().count() > 22 {
340            24
341        } else {
342            34
343        },
344        unit = esc(&card.unit),
345        lang = esc(&card.language),
346        functions = esc(&card.functions.join(", ")),
347        orig_t = esc(&ns(orig)),
348        rust_t = esc(&ns(rust)),
349        orig_w = bar(orig),
350        rust_w = bar(rust),
351        state = if card.enabled == Some(true) {
352            "on"
353        } else {
354            "off"
355        },
356        speed = speed_phrase(card.speedup),
357        crab = include_str!("card_crab.svg").trim(),
358        fallback = esc(&fallback_percent(card)),
359        machine = esc(&card.machine),
360    )
361}
362
363#[cfg(test)]
364mod tests {
365    use super::*;
366
367    #[test]
368    fn a_value_that_rounds_up_to_the_next_unit_prints_in_that_unit() {
369        assert_eq!(ns(999.6), "1.0 µs");
370        assert_eq!(ns(999_999.0), "1.0 ms");
371        assert_eq!(ns(999_999_999.0), "1.00 s");
372        assert_eq!(times(9.96), "10x");
373        // Just under each boundary stays where it is.
374        assert_eq!(ns(999.0), "999 ns");
375        assert_eq!(ns(999_000.0), "999.0 µs");
376        assert_eq!(ns(999_000_000.0), "999.0 ms");
377        assert_eq!(times(9.94), "9.9x");
378        // The ordinary cases are unchanged.
379        assert_eq!(ns(500.0), "500 ns");
380        assert_eq!(ns(1_500_000.0), "1.5 ms");
381        assert_eq!(times(31.4), "31x");
382    }
383
384    fn card() -> Card {
385        Card {
386            schema: SCHEMA,
387            crate_name: "fuzzy-rs".into(),
388            unit: "app.py".into(),
389            language: "Python".into(),
390            functions: vec!["dedupe".into()],
391            cases: 412,
392            matched: 412,
393            speedup: 31.4,
394            bench: vec![BenchRow {
395                name: "dedupe".into(),
396                cases: 412,
397                original_ns: 9_120_000.0,
398                rust_ns: 290_000.0,
399                speedup: 31.4,
400            }],
401            fallback_cases: 0,
402            enabled: Some(true),
403            machine: "Apple M4, 10 cores, macOS".into(),
404            markdown: "REPORT.md".into(),
405            svg: "card.svg".into(),
406        }
407    }
408
409    #[test]
410    fn the_card_shows_what_was_measured() {
411        let svg = svg(&card());
412        assert!(svg.starts_with("<svg"), "{svg}");
413        for want in [
414            "fuzzy-rs",
415            "9.1 ms",
416            "290.0 µs",
417            "all 412 recorded cases",
418            "31x faster",
419            "switched on",
420            "0.0% of cases",
421            "Apple M4, 10 cores",
422        ] {
423            assert!(svg.contains(want), "{want} missing:\n{svg}");
424        }
425        let md = markdown(&card());
426        assert!(
427            md.contains("| Recorded cases matched | 412 / 412 |"),
428            "{md}"
429        );
430        assert!(
431            md.contains("| `dedupe` | 412 | 9.1 ms | 290.0 µs | 31x |"),
432            "{md}"
433        );
434    }
435
436    #[test]
437    fn a_fallback_rate_never_rounds_to_none_or_all() {
438        let mut c = card();
439        c.cases = 2001;
440        c.fallback_cases = 1;
441        assert!(svg(&c).contains("Fallback to the original: &lt;0.1% of cases"));
442        assert!(markdown(&c).contains("| Fallback to the original | <0.1% (1 of 2001 cases) |"));
443        c.cases = 2000;
444        c.fallback_cases = 1999;
445        assert!(svg(&c).contains("Fallback to the original: &gt;99.9% of cases"));
446        assert!(
447            markdown(&c).contains("| Fallback to the original | >99.9% (1999 of 2000 cases) |")
448        );
449        // None and all still print as they are, and so does a share that rounds to neither.
450        c.fallback_cases = 0;
451        assert!(svg(&c).contains("Fallback to the original: 0.0% of cases"));
452        c.fallback_cases = 2000;
453        assert!(svg(&c).contains("Fallback to the original: 100.0% of cases"));
454        c.fallback_cases = 1;
455        assert!(svg(&c).contains("Fallback to the original: 0.1% of cases"));
456    }
457
458    #[test]
459    fn a_slower_port_says_slower_in_the_label_and_tables_too() {
460        let mut c = card();
461        c.speedup = 0.04;
462        c.bench[0].original_ns = 290_000.0;
463        c.bench[0].rust_ns = 9_120_000.0;
464        c.bench[0].speedup = 0.04;
465        let svg = svg(&c);
466        for want in [
467            "aria-label=\"fuzzy-rs: 412 of 412 recorded cases match, 25x slower\"",
468            "<tspan font-weight=\"700\" fill=\"#e8561a\">25x slower</tspan>",
469        ] {
470            assert!(svg.contains(want), "{want} missing:\n{svg}");
471        }
472        assert!(!svg.contains("0.0x"), "{svg}");
473        let md = markdown(&c);
474        assert!(
475            md.contains("| Speedup, call included | 25x slower (geometric mean) |"),
476            "{md}"
477        );
478        assert!(
479            md.contains("| `dedupe` | 412 | 290.0 µs | 9.1 ms | 25x slower |"),
480            "{md}"
481        );
482    }
483
484    #[test]
485    fn text_from_the_project_is_escaped() {
486        let mut c = card();
487        c.unit = "src/<a&b>.ts".into();
488        c.matched = 400;
489        let svg = svg(&c);
490        assert!(svg.contains("src/&lt;a&amp;b&gt;.ts"));
491        assert!(svg.contains("400 of 412 recorded cases match"));
492    }
493}