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