Skip to main content

rust_anything/
recording.rs

1//! What a recording was made from, and the differences from it a port is allowed to keep.
2//!
3//! `record` saves a fingerprint of the original's unit (`recorded-from.json`): when the original
4//! changes later, `diff` and `gate` say the recording is stale instead of passing against old
5//! behavior. `known-diffs.jsonl` lists recorded cases where the port is meant to differ, each
6//! with the Rust result it gives and why; any other difference still fails, and so does an entry
7//! that no longer happens, so the list cannot outlive the differences it explains.
8
9use std::path::Path;
10
11use anyhow::{Context, Result};
12use serde_json::{Value, json};
13
14use crate::bridge::Manifest;
15use crate::harness::DiffOutcome;
16
17pub const RECORDED_FROM: &str = "recorded-from.json";
18pub const KNOWN_DIFFS: &str = "known-diffs.jsonl";
19
20/// FNV-1a over the unit's files (relative path and contents, in path order): stable across Rust
21/// versions and platforms, unlike `DefaultHasher`.
22pub fn fingerprint(m: &Manifest) -> Option<(String, usize)> {
23    let unit = m.root.join(&m.unit);
24    let mut files: Vec<std::path::PathBuf> = if unit.is_file() {
25        vec![unit.clone()]
26    } else if unit.is_dir() {
27        crate::walk::filtered(&unit, |e| {
28            !matches!(
29                e.file_name().to_str(),
30                Some("node_modules" | "target" | ".git" | "__pycache__")
31            )
32        })
33        .build()
34        .flatten()
35        .filter(|e| e.file_type().is_some_and(|t| t.is_file()))
36        .map(|e| e.into_path())
37        .collect()
38    } else {
39        return None;
40    };
41    files.sort();
42    let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
43    let mut eat = |bytes: &[u8]| {
44        for b in bytes {
45            hash ^= u64::from(*b);
46            hash = hash.wrapping_mul(0x0100_0000_01b3);
47        }
48    };
49    for file in &files {
50        let relative = file.strip_prefix(&m.root).unwrap_or(file);
51        eat(relative.to_string_lossy().replace('\\', "/").as_bytes());
52        eat(&[0]);
53        eat(&std::fs::read(file).ok()?);
54        eat(&[0]);
55    }
56    Some((format!("{hash:016x}"), files.len()))
57}
58
59/// Saves the fingerprint of the original next to `cases.jsonl`, with how much of it the recorded
60/// cases ran when that was measured.
61pub fn save_fingerprint(crate_dir: &Path, m: &Manifest, coverage: Option<&Value>) -> Result<()> {
62    let path = crate_dir.join(RECORDED_FROM);
63    let Some((hash, files)) = fingerprint(m) else {
64        return Ok(());
65    };
66    let mut saved = json!({ "unit": m.unit, "files": files, "fingerprint": hash });
67    if let Some(c) = coverage {
68        saved["coverage"] = c.clone();
69    }
70    std::fs::write(&path, serde_json::to_string_pretty(&saved)? + "\n")
71        .with_context(|| format!("writing {}", path.display()))
72}
73
74/// The coverage `record` saved: `{"lines", "reached", "files": [{"file", "lines", "reached",
75/// "missed"}]}`.
76pub fn saved_coverage(crate_dir: &Path) -> Option<Value> {
77    let saved: Value =
78        serde_json::from_str(&std::fs::read_to_string(crate_dir.join(RECORDED_FROM)).ok()?).ok()?;
79    saved.get("coverage").filter(|c| c.is_object()).cloned()
80}
81
82/// One line for a person: how much of the original the recorded cases ran, and where they
83/// did not reach.
84pub fn coverage_line(c: &Value) -> Option<String> {
85    let lines = c["lines"].as_u64()?;
86    let reached = c["reached"].as_u64()?;
87    if lines == 0 {
88        return None;
89    }
90    let mut files: Vec<&Value> = c["files"]
91        .as_array()
92        .into_iter()
93        .flatten()
94        .filter(|f| f["missed"].as_str().is_some_and(|m| !m.is_empty()))
95        .collect();
96    files.sort_by_key(|f| {
97        std::cmp::Reverse(f["lines"].as_u64().unwrap_or(0) - f["reached"].as_u64().unwrap_or(0))
98    });
99    let mut missed: Vec<String> = files
100        .iter()
101        .take(4)
102        .map(|f| {
103            format!(
104                "{}: {}",
105                f["file"].as_str().unwrap_or("?"),
106                f["missed"].as_str().unwrap_or_default()
107            )
108        })
109        .collect();
110    if files.len() > 4 {
111        missed.push(format!(
112            "{} more files, listed in {RECORDED_FROM}",
113            files.len() - 4
114        ));
115    }
116    // `{:.0}` rounds 99.9% up to `100%`, which reads as full coverage while a line never ran:
117    // below 100 the share is floored, and it only prints `100%` when every line ran.
118    let mut line = format!(
119        "the recorded cases ran {reached} of the original's {lines} lines ({})",
120        percent(reached, lines)
121    );
122    if !missed.is_empty() {
123        line.push_str(&format!(
124            "; never ran: {} (add inputs that reach them, e.g. `record --from-tests`)",
125            missed.join("; ")
126        ));
127    }
128    Some(line)
129}
130
131/// A whole-number share that never says `100%` unless the counts are equal.
132fn percent(reached: u64, lines: u64) -> String {
133    if reached >= lines {
134        return "100%".into();
135    }
136    // u128: `reached * 100` in u64 would overflow on a hand-edited record near the top of the range.
137    format!("{}%", u128::from(reached) * 100 / u128::from(lines.max(1)))
138}
139
140/// Line coverage of the unit's files from the V8 coverage Node writes to `dir`
141/// (`NODE_V8_COVERAGE`). A line counts when it has code; it was reached when any of its code ran
142/// in any of the record runs. Files Node transformed (not only stripped of types) are left out,
143/// since V8's offsets then point into the transformed text.
144pub fn node_coverage(dir: &Path, m: &Manifest) -> Option<Value> {
145    let mut unit: Vec<std::path::PathBuf> = m
146        .exports
147        .iter()
148        .map(|f| m.root.join(&f.file))
149        .chain(m.classes.iter().map(|c| m.root.join(&c.file)))
150        .collect();
151    unit.sort();
152    unit.dedup();
153    let root = m.root.canonicalize().unwrap_or_else(|_| m.root.clone());
154    let mut files: Vec<std::path::PathBuf> = crate::gate::with_local_imports(&m.root, unit)
155        .into_iter()
156        .filter_map(|p| p.canonicalize().ok())
157        .collect();
158    files.sort();
159    files.dedup();
160    let reports: Vec<Value> = std::fs::read_dir(dir)
161        .ok()?
162        .flatten()
163        .filter_map(|e| serde_json::from_str(&std::fs::read_to_string(e.path()).ok()?).ok())
164        .collect();
165    if reports.is_empty() {
166        return None;
167    }
168    let mut out = Vec::new();
169    let (mut total, mut total_reached) = (0u64, 0u64);
170    for path in files {
171        let file = path
172            .strip_prefix(&root)
173            .unwrap_or(&path)
174            .to_string_lossy()
175            .replace('\\', "/");
176        let Ok(text) = std::fs::read_to_string(&path) else {
177            continue;
178        };
179        let real = &path;
180        let units: usize = text.encode_utf16().count();
181        let mut ran = vec![false; units];
182        let mut seen = false;
183        for report in &reports {
184            let transformed = report["source-map-cache"]
185                .as_object()
186                .is_some_and(|c| c.keys().any(|url| same_file(url, real)));
187            if transformed {
188                continue;
189            }
190            for script in report["result"].as_array().into_iter().flatten() {
191                if !script["url"].as_str().is_some_and(|u| same_file(u, real)) {
192                    continue;
193                }
194                seen = true;
195                let mut counts = vec![0u64; units];
196                for f in script["functions"].as_array().into_iter().flatten() {
197                    for r in f["ranges"].as_array().into_iter().flatten() {
198                        let (Some(s), Some(e), Some(n)) = (
199                            r["startOffset"].as_u64(),
200                            r["endOffset"].as_u64(),
201                            r["count"].as_u64(),
202                        ) else {
203                            continue;
204                        };
205                        let (s, e) = (s as usize, (e as usize).min(units));
206                        if s < e {
207                            counts[s..e].fill(n);
208                        }
209                    }
210                }
211                for (r, c) in ran.iter_mut().zip(&counts) {
212                    *r |= *c > 0;
213                }
214            }
215        }
216        if !seen {
217            continue;
218        }
219        let mut lines: Vec<(usize, bool, bool)> = Vec::new();
220        let (mut line, mut code, mut hit) = (1usize, false, false);
221        let mut at = 0usize;
222        for ch in text.chars() {
223            if ch == '\n' {
224                lines.push((line, code, hit));
225                (line, code, hit) = (line + 1, false, false);
226            } else if !ch.is_whitespace() {
227                code = true;
228                hit |= ran.get(at).copied().unwrap_or(false);
229            }
230            at += ch.len_utf16();
231        }
232        lines.push((line, code, hit));
233        let code_lines: Vec<(usize, bool)> = lines
234            .into_iter()
235            .filter(|(_, code, _)| *code)
236            .map(|(n, _, hit)| (n, hit))
237            .collect();
238        let reached = code_lines.iter().filter(|(_, hit)| *hit).count() as u64;
239        total += code_lines.len() as u64;
240        total_reached += reached;
241        out.push(json!({
242            "file": file,
243            "lines": code_lines.len(),
244            "reached": reached,
245            "missed": spans(code_lines.iter().filter(|(_, hit)| !hit).map(|(n, _)| *n)),
246        }));
247    }
248    (!out.is_empty()).then(|| json!({ "lines": total, "reached": total_reached, "files": out }))
249}
250
251fn same_file(url: &str, real: &Path) -> bool {
252    url.strip_prefix("file://")
253        .map(|p| {
254            percent_encoding::percent_decode_str(p)
255                .decode_utf8_lossy()
256                .into_owned()
257        })
258        .is_some_and(|p| Path::new(&p) == real)
259}
260
261fn spans(lines: impl Iterator<Item = usize>) -> String {
262    let mut out: Vec<(usize, usize)> = Vec::new();
263    for n in lines {
264        match out.last_mut() {
265            Some((_, end)) if *end + 1 == n => *end = n,
266            _ => out.push((n, n)),
267        }
268    }
269    out.iter()
270        .map(|(a, b)| {
271            if a == b {
272                a.to_string()
273            } else {
274                format!("{a}-{b}")
275            }
276        })
277        .collect::<Vec<_>>()
278        .join(", ")
279}
280
281/// Why the recording no longer describes the original, if it does not: the unit's files changed
282/// since `record`. `None` when they did not, or when there is nothing to compare (a recording
283/// made before fingerprints, or the original not at hand).
284pub fn stale(crate_dir: &Path, m: &Manifest) -> Option<String> {
285    let saved: Value =
286        serde_json::from_str(&std::fs::read_to_string(crate_dir.join(RECORDED_FROM)).ok()?).ok()?;
287    let (now, _) = fingerprint(m)?;
288    (saved["fingerprint"].as_str()? != now).then(|| {
289        format!(
290            "{} changed since it was recorded: re-run `rust-anything record {}` so the port is \
291             checked against what the original does now",
292            m.unit,
293            crate_dir.display()
294        )
295    })
296}
297
298const HISTORY: &str = ".rust-anything/diff-history.jsonl";
299/// Changes to `port.rs` in a row that gain no matching case before `diff` calls the port stalled.
300pub const STALL_AFTER: usize = 3;
301
302#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq)]
303pub struct Trend {
304    /// Cases matching after each change to `port.rs`, oldest first (the last ten).
305    pub passed: Vec<usize>,
306    pub total: usize,
307    /// The last `STALL_AFTER` changes gained nothing while cases still fail.
308    pub stalled: bool,
309}
310
311/// Records this diff when `port.rs` changed since the last one, and returns the trend. Rerunning
312/// `diff` on an unchanged port is not another attempt, so it adds nothing.
313pub fn track(crate_dir: &Path, passed: usize, total: usize) -> Option<Trend> {
314    let port = std::fs::read(crate_dir.join("src/port.rs")).ok()?;
315    let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
316    for b in &port {
317        hash ^= u64::from(*b);
318        hash = hash.wrapping_mul(0x0100_0000_01b3);
319    }
320    let hash = format!("{hash:016x}");
321    let path = crate_dir.join(HISTORY);
322    let mut runs: Vec<Value> = std::fs::read_to_string(&path)
323        .unwrap_or_default()
324        .lines()
325        .filter_map(|l| serde_json::from_str(l).ok())
326        .filter(|r: &Value| r["total"].as_u64() == Some(total as u64))
327        .collect();
328    let entry = json!({ "port": hash, "passed": passed, "total": total });
329    match runs.last_mut() {
330        Some(last) if last["port"] == entry["port"] => *last = entry,
331        _ => runs.push(entry),
332    }
333    let keep = runs.len().saturating_sub(10);
334    runs.drain(..keep);
335    if let Some(dir) = path.parent() {
336        let _ = std::fs::create_dir_all(dir);
337    }
338    let text: String = runs.iter().map(|r| format!("{r}\n")).collect();
339    let _ = std::fs::write(&path, text);
340    Some(trend(
341        runs.iter()
342            .filter_map(|r| r["passed"].as_u64().map(|p| p as usize))
343            .collect(),
344        total,
345    ))
346}
347
348pub fn last_diff(crate_dir: &Path) -> Option<(usize, usize)> {
349    let text = std::fs::read_to_string(crate_dir.join(HISTORY)).ok()?;
350    let last: Value = serde_json::from_str(text.lines().last()?).ok()?;
351    Some((
352        usize::try_from(last["passed"].as_u64()?).ok()?,
353        usize::try_from(last["total"].as_u64()?).ok()?,
354    ))
355}
356
357fn trend(passed: Vec<usize>, total: usize) -> Trend {
358    let n = passed.len();
359    let stalled = n > STALL_AFTER
360        && passed[n - 1] < total
361        && passed[n - STALL_AFTER..]
362            .iter()
363            .all(|p| *p <= passed[..n - STALL_AFTER].iter().copied().max().unwrap_or(0));
364    Trend {
365        passed,
366        total,
367        stalled,
368    }
369}
370
371/// The entries of `known-diffs.jsonl`: `{"fn", "args", "actual", "reason"}` per line, `actual`
372/// being the port's result as `diff --json` prints it. An entry without a reason is refused.
373pub fn known_diffs(crate_dir: &Path) -> Result<Vec<Value>> {
374    let path = crate_dir.join(KNOWN_DIFFS);
375    let Ok(text) = std::fs::read_to_string(&path) else {
376        return Ok(Vec::new());
377    };
378    let mut entries = Vec::new();
379    for (i, line) in text.lines().enumerate() {
380        let line = line.trim();
381        if line.is_empty() || line.starts_with("//") {
382            continue;
383        }
384        let entry: Value = serde_json::from_str(line)
385            .with_context(|| format!("{}:{}: not JSON", path.display(), i + 1))?;
386        for key in ["fn", "args", "actual"] {
387            anyhow::ensure!(
388                entry.get(key).is_some(),
389                "{}:{}: an entry needs `{key}`",
390                path.display(),
391                i + 1
392            );
393        }
394        anyhow::ensure!(
395            entry["reason"]
396                .as_str()
397                .is_some_and(|r| !r.trim().is_empty()),
398            "{}:{}: an entry needs a `reason`: why the port is meant to differ here",
399            path.display(),
400            i + 1
401        );
402        entries.push(entry);
403    }
404    Ok(entries)
405}
406
407/// Counts the mismatches a known-diffs entry explains as passed (in `accepted`), and records the
408/// entries no mismatch matched (in `stale_known`). A mismatch is explained only when the port
409/// gives exactly the entry's `actual`: a different wrong result still fails.
410pub fn apply_known(mut outcome: DiffOutcome, entries: &[Value]) -> DiffOutcome {
411    if entries.is_empty() {
412        return outcome;
413    }
414    let mut used = vec![false; entries.len()];
415    outcome.mismatches.retain(|m| {
416        let hit = entries.iter().position(|e| {
417            e["fn"] == m["fn"] && e["args"] == m["args"] && e["actual"] == m["actual"]
418        });
419        match hit {
420            Some(i) => {
421                used[i] = true;
422                false
423            }
424            None => true,
425        }
426    });
427    let accepted = used.iter().filter(|u| **u).count();
428    outcome.accepted = accepted;
429    outcome.failed -= accepted.min(outcome.failed);
430    outcome.passed += accepted;
431    outcome.stale_known = entries
432        .iter()
433        .zip(&used)
434        .filter(|(_, u)| !**u)
435        .map(|(e, _)| json!({ "fn": e["fn"], "args": e["args"], "reason": e["reason"] }))
436        .collect();
437    outcome
438}
439
440#[cfg(test)]
441mod tests {
442    use super::*;
443
444    fn outcome() -> DiffOutcome {
445        DiffOutcome {
446            total: 3,
447            passed: 1,
448            failed: 2,
449            mismatches: vec![
450                json!({"fn": "f", "args": [1], "expected": {"ok": 1}, "actual": {"ok": 2}}),
451                json!({"fn": "f", "args": [2], "expected": {"ok": 1}, "actual": {"ok": 3}}),
452            ],
453            ..DiffOutcome::default()
454        }
455    }
456
457    #[test]
458    fn a_share_just_under_full_never_reads_as_100_percent() {
459        assert_eq!(percent(1000, 1000), "100%");
460        assert_eq!(percent(999, 1000), "99%");
461        assert_eq!(percent(1999, 2000), "99%");
462        assert_eq!(percent(1, 3), "33%");
463        assert_eq!(percent(0, 10), "0%");
464        assert_eq!(percent(5, 0), "100%");
465    }
466
467    #[test]
468    fn covered_lines_run_together_and_gaps_keep_their_own_range() {
469        assert_eq!(spans(std::iter::empty()), "");
470        assert_eq!(spans([5].into_iter()), "5");
471        assert_eq!(spans([1, 2, 3].into_iter()), "1-3");
472        assert_eq!(spans([1, 2, 3, 5, 7, 8].into_iter()), "1-3, 5, 7-8");
473        // A gap of one line still splits the range.
474        assert_eq!(spans([1, 3].into_iter()), "1, 3");
475    }
476
477    #[test]
478    fn known_diffs_pass_only_with_the_listed_result() {
479        let entries = [
480            json!({"fn": "f", "args": [1], "actual": {"ok": 2}, "reason": "fixed a bug"}),
481            json!({"fn": "f", "args": [2], "actual": {"ok": 4}, "reason": "other result"}),
482            json!({"fn": "g", "args": [], "actual": {"ok": 0}, "reason": "gone"}),
483        ];
484        let out = apply_known(outcome(), &entries);
485        assert_eq!((out.passed, out.failed, out.accepted), (2, 1, 1));
486        assert_eq!(out.mismatches.len(), 1);
487        assert_eq!(out.mismatches[0]["args"], json!([2]));
488        assert_eq!(out.stale_known.len(), 2);
489    }
490
491    #[test]
492    fn a_port_stalls_after_changes_that_gain_nothing() {
493        assert!(!trend(vec![10, 12, 15], 20).stalled);
494        assert!(!trend(vec![10, 12, 12, 12], 20).stalled);
495        assert!(trend(vec![10, 12, 12, 11, 12], 20).stalled);
496        assert!(!trend(vec![10, 12, 12, 11, 13], 20).stalled);
497        assert!(!trend(vec![20, 20, 20, 20, 20], 20).stalled);
498    }
499
500    #[test]
501    fn rerunning_diff_on_an_unchanged_port_is_not_an_attempt() {
502        let dir = std::env::temp_dir().join(format!("ra-trend-{}", std::process::id()));
503        std::fs::create_dir_all(dir.join("src")).unwrap();
504        let mut last = None;
505        for (port, passed) in [("a", 1), ("a", 2), ("b", 2), ("c", 2), ("d", 2), ("e", 2)] {
506            std::fs::write(dir.join("src/port.rs"), port).unwrap();
507            last = track(&dir, passed, 5);
508        }
509        std::fs::remove_dir_all(&dir).unwrap();
510        let last = last.unwrap();
511        assert_eq!(last.passed, vec![2, 2, 2, 2, 2]);
512        assert!(last.stalled);
513    }
514
515    #[test]
516    fn entries_need_a_reason() {
517        let dir = std::env::temp_dir().join(format!("ra-known-{}", std::process::id()));
518        std::fs::create_dir_all(&dir).unwrap();
519        std::fs::write(
520            dir.join(KNOWN_DIFFS),
521            "// comment\n{\"fn\": \"f\", \"args\": [1], \"actual\": {\"ok\": 2}}\n",
522        )
523        .unwrap();
524        let err = known_diffs(&dir).unwrap_err();
525        std::fs::remove_dir_all(&dir).unwrap();
526        assert!(format!("{err:#}").contains("reason"), "{err:#}");
527    }
528}