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