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