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