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