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    let mut line = format!(
117        "the recorded cases ran {reached} of the original's {lines} lines ({:.0}%)",
118        reached as f64 * 100.0 / lines as f64
119    );
120    if !missed.is_empty() {
121        line.push_str(&format!(
122            "; never ran: {} (add inputs that reach them, e.g. `record --from-tests`)",
123            missed.join("; ")
124        ));
125    }
126    Some(line)
127}
128
129/// Line coverage of the unit's files from the V8 coverage Node writes to `dir`
130/// (`NODE_V8_COVERAGE`). A line counts when it has code; it was reached when any of its code ran
131/// in any of the record runs. Files Node transformed (not only stripped of types) are left out,
132/// since V8's offsets then point into the transformed text.
133pub fn node_coverage(dir: &Path, m: &Manifest) -> Option<Value> {
134    let mut unit: Vec<std::path::PathBuf> = m
135        .exports
136        .iter()
137        .map(|f| m.root.join(&f.file))
138        .chain(m.classes.iter().map(|c| m.root.join(&c.file)))
139        .collect();
140    unit.sort();
141    unit.dedup();
142    let root = m.root.canonicalize().unwrap_or_else(|_| m.root.clone());
143    let mut files: Vec<std::path::PathBuf> = crate::gate::with_local_imports(&m.root, unit)
144        .into_iter()
145        .filter_map(|p| p.canonicalize().ok())
146        .collect();
147    files.sort();
148    files.dedup();
149    let reports: Vec<Value> = std::fs::read_dir(dir)
150        .ok()?
151        .flatten()
152        .filter_map(|e| serde_json::from_str(&std::fs::read_to_string(e.path()).ok()?).ok())
153        .collect();
154    if reports.is_empty() {
155        return None;
156    }
157    let mut out = Vec::new();
158    let (mut total, mut total_reached) = (0u64, 0u64);
159    for path in files {
160        let file = path
161            .strip_prefix(&root)
162            .unwrap_or(&path)
163            .to_string_lossy()
164            .replace('\\', "/");
165        let Ok(text) = std::fs::read_to_string(&path) else {
166            continue;
167        };
168        let real = &path;
169        let units: usize = text.encode_utf16().count();
170        let mut ran = vec![false; units];
171        let mut seen = false;
172        for report in &reports {
173            let transformed = report["source-map-cache"]
174                .as_object()
175                .is_some_and(|c| c.keys().any(|url| same_file(url, real)));
176            if transformed {
177                continue;
178            }
179            for script in report["result"].as_array().into_iter().flatten() {
180                if !script["url"].as_str().is_some_and(|u| same_file(u, real)) {
181                    continue;
182                }
183                seen = true;
184                let mut counts = vec![0u64; units];
185                for f in script["functions"].as_array().into_iter().flatten() {
186                    for r in f["ranges"].as_array().into_iter().flatten() {
187                        let (Some(s), Some(e), Some(n)) = (
188                            r["startOffset"].as_u64(),
189                            r["endOffset"].as_u64(),
190                            r["count"].as_u64(),
191                        ) else {
192                            continue;
193                        };
194                        let (s, e) = (s as usize, (e as usize).min(units));
195                        if s < e {
196                            counts[s..e].fill(n);
197                        }
198                    }
199                }
200                for (r, c) in ran.iter_mut().zip(&counts) {
201                    *r |= *c > 0;
202                }
203            }
204        }
205        if !seen {
206            continue;
207        }
208        let mut lines: Vec<(usize, bool, bool)> = Vec::new();
209        let (mut line, mut code, mut hit) = (1usize, false, false);
210        let mut at = 0usize;
211        for ch in text.chars() {
212            if ch == '\n' {
213                lines.push((line, code, hit));
214                (line, code, hit) = (line + 1, false, false);
215            } else if !ch.is_whitespace() {
216                code = true;
217                hit |= ran.get(at).copied().unwrap_or(false);
218            }
219            at += ch.len_utf16();
220        }
221        lines.push((line, code, hit));
222        let code_lines: Vec<(usize, bool)> = lines
223            .into_iter()
224            .filter(|(_, code, _)| *code)
225            .map(|(n, _, hit)| (n, hit))
226            .collect();
227        let reached = code_lines.iter().filter(|(_, hit)| *hit).count() as u64;
228        total += code_lines.len() as u64;
229        total_reached += reached;
230        out.push(json!({
231            "file": file,
232            "lines": code_lines.len(),
233            "reached": reached,
234            "missed": spans(code_lines.iter().filter(|(_, hit)| !hit).map(|(n, _)| *n)),
235        }));
236    }
237    (!out.is_empty()).then(|| json!({ "lines": total, "reached": total_reached, "files": out }))
238}
239
240fn same_file(url: &str, real: &Path) -> bool {
241    url.strip_prefix("file://")
242        .map(|p| {
243            percent_encoding::percent_decode_str(p)
244                .decode_utf8_lossy()
245                .into_owned()
246        })
247        .is_some_and(|p| Path::new(&p) == real)
248}
249
250fn spans(lines: impl Iterator<Item = usize>) -> String {
251    let mut out: Vec<(usize, usize)> = Vec::new();
252    for n in lines {
253        match out.last_mut() {
254            Some((_, end)) if *end + 1 == n => *end = n,
255            _ => out.push((n, n)),
256        }
257    }
258    out.iter()
259        .map(|(a, b)| {
260            if a == b {
261                a.to_string()
262            } else {
263                format!("{a}-{b}")
264            }
265        })
266        .collect::<Vec<_>>()
267        .join(", ")
268}
269
270/// Why the recording no longer describes the original, if it does not: the unit's files changed
271/// since `record`. `None` when they did not, or when there is nothing to compare (a recording
272/// made before fingerprints, or the original not at hand).
273pub fn stale(crate_dir: &Path, m: &Manifest) -> Option<String> {
274    let saved: Value =
275        serde_json::from_str(&std::fs::read_to_string(crate_dir.join(RECORDED_FROM)).ok()?).ok()?;
276    let (now, _) = fingerprint(m)?;
277    (saved["fingerprint"].as_str()? != now).then(|| {
278        format!(
279            "{} changed since it was recorded: re-run `rust-anything record {}` so the port is \
280             checked against what the original does now",
281            m.unit,
282            crate_dir.display()
283        )
284    })
285}
286
287const HISTORY: &str = ".rust-anything/diff-history.jsonl";
288/// Changes to `port.rs` in a row that gain no matching case before `diff` calls the port stalled.
289pub const STALL_AFTER: usize = 3;
290
291#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq)]
292pub struct Trend {
293    /// Cases matching after each change to `port.rs`, oldest first (the last ten).
294    pub passed: Vec<usize>,
295    pub total: usize,
296    /// The last `STALL_AFTER` changes gained nothing while cases still fail.
297    pub stalled: bool,
298}
299
300/// Records this diff when `port.rs` changed since the last one, and returns the trend. Rerunning
301/// `diff` on an unchanged port is not another attempt, so it adds nothing.
302pub fn track(crate_dir: &Path, passed: usize, total: usize) -> Option<Trend> {
303    let port = std::fs::read(crate_dir.join("src/port.rs")).ok()?;
304    let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
305    for b in &port {
306        hash ^= u64::from(*b);
307        hash = hash.wrapping_mul(0x0100_0000_01b3);
308    }
309    let hash = format!("{hash:016x}");
310    let path = crate_dir.join(HISTORY);
311    let mut runs: Vec<Value> = std::fs::read_to_string(&path)
312        .unwrap_or_default()
313        .lines()
314        .filter_map(|l| serde_json::from_str(l).ok())
315        .filter(|r: &Value| r["total"].as_u64() == Some(total as u64))
316        .collect();
317    let entry = json!({ "port": hash, "passed": passed, "total": total });
318    match runs.last_mut() {
319        Some(last) if last["port"] == entry["port"] => *last = entry,
320        _ => runs.push(entry),
321    }
322    let keep = runs.len().saturating_sub(10);
323    runs.drain(..keep);
324    if let Some(dir) = path.parent() {
325        let _ = std::fs::create_dir_all(dir);
326    }
327    let text: String = runs.iter().map(|r| format!("{r}\n")).collect();
328    let _ = std::fs::write(&path, text);
329    Some(trend(
330        runs.iter()
331            .filter_map(|r| r["passed"].as_u64().map(|p| p as usize))
332            .collect(),
333        total,
334    ))
335}
336
337pub fn last_diff(crate_dir: &Path) -> Option<(usize, usize)> {
338    let text = std::fs::read_to_string(crate_dir.join(HISTORY)).ok()?;
339    let last: Value = serde_json::from_str(text.lines().last()?).ok()?;
340    Some((
341        usize::try_from(last["passed"].as_u64()?).ok()?,
342        usize::try_from(last["total"].as_u64()?).ok()?,
343    ))
344}
345
346fn trend(passed: Vec<usize>, total: usize) -> Trend {
347    let n = passed.len();
348    let stalled = n > STALL_AFTER
349        && passed[n - 1] < total
350        && passed[n - STALL_AFTER..]
351            .iter()
352            .all(|p| *p <= passed[..n - STALL_AFTER].iter().copied().max().unwrap_or(0));
353    Trend {
354        passed,
355        total,
356        stalled,
357    }
358}
359
360/// The entries of `known-diffs.jsonl`: `{"fn", "args", "actual", "reason"}` per line, `actual`
361/// being the port's result as `diff --json` prints it. An entry without a reason is refused.
362pub fn known_diffs(crate_dir: &Path) -> Result<Vec<Value>> {
363    let path = crate_dir.join(KNOWN_DIFFS);
364    let Ok(text) = std::fs::read_to_string(&path) else {
365        return Ok(Vec::new());
366    };
367    let mut entries = Vec::new();
368    for (i, line) in text.lines().enumerate() {
369        let line = line.trim();
370        if line.is_empty() || line.starts_with("//") {
371            continue;
372        }
373        let entry: Value = serde_json::from_str(line)
374            .with_context(|| format!("{}:{}: not JSON", path.display(), i + 1))?;
375        for key in ["fn", "args", "actual"] {
376            anyhow::ensure!(
377                entry.get(key).is_some(),
378                "{}:{}: an entry needs `{key}`",
379                path.display(),
380                i + 1
381            );
382        }
383        anyhow::ensure!(
384            entry["reason"]
385                .as_str()
386                .is_some_and(|r| !r.trim().is_empty()),
387            "{}:{}: an entry needs a `reason`: why the port is meant to differ here",
388            path.display(),
389            i + 1
390        );
391        entries.push(entry);
392    }
393    Ok(entries)
394}
395
396/// Counts the mismatches a known-diffs entry explains as passed (in `accepted`), and records the
397/// entries no mismatch matched (in `stale_known`). A mismatch is explained only when the port
398/// gives exactly the entry's `actual`: a different wrong result still fails.
399pub fn apply_known(mut outcome: DiffOutcome, entries: &[Value]) -> DiffOutcome {
400    if entries.is_empty() {
401        return outcome;
402    }
403    let mut used = vec![false; entries.len()];
404    outcome.mismatches.retain(|m| {
405        let hit = entries.iter().position(|e| {
406            e["fn"] == m["fn"] && e["args"] == m["args"] && e["actual"] == m["actual"]
407        });
408        match hit {
409            Some(i) => {
410                used[i] = true;
411                false
412            }
413            None => true,
414        }
415    });
416    let accepted = used.iter().filter(|u| **u).count();
417    outcome.accepted = accepted;
418    outcome.failed -= accepted.min(outcome.failed);
419    outcome.passed += accepted;
420    outcome.stale_known = entries
421        .iter()
422        .zip(&used)
423        .filter(|(_, u)| !**u)
424        .map(|(e, _)| json!({ "fn": e["fn"], "args": e["args"], "reason": e["reason"] }))
425        .collect();
426    outcome
427}
428
429#[cfg(test)]
430mod tests {
431    use super::*;
432
433    fn outcome() -> DiffOutcome {
434        DiffOutcome {
435            total: 3,
436            passed: 1,
437            failed: 2,
438            mismatches: vec![
439                json!({"fn": "f", "args": [1], "expected": {"ok": 1}, "actual": {"ok": 2}}),
440                json!({"fn": "f", "args": [2], "expected": {"ok": 1}, "actual": {"ok": 3}}),
441            ],
442            ..DiffOutcome::default()
443        }
444    }
445
446    #[test]
447    fn known_diffs_pass_only_with_the_listed_result() {
448        let entries = [
449            json!({"fn": "f", "args": [1], "actual": {"ok": 2}, "reason": "fixed a bug"}),
450            json!({"fn": "f", "args": [2], "actual": {"ok": 4}, "reason": "other result"}),
451            json!({"fn": "g", "args": [], "actual": {"ok": 0}, "reason": "gone"}),
452        ];
453        let out = apply_known(outcome(), &entries);
454        assert_eq!((out.passed, out.failed, out.accepted), (2, 1, 1));
455        assert_eq!(out.mismatches.len(), 1);
456        assert_eq!(out.mismatches[0]["args"], json!([2]));
457        assert_eq!(out.stale_known.len(), 2);
458    }
459
460    #[test]
461    fn a_port_stalls_after_changes_that_gain_nothing() {
462        assert!(!trend(vec![10, 12, 15], 20).stalled);
463        assert!(!trend(vec![10, 12, 12, 12], 20).stalled);
464        assert!(trend(vec![10, 12, 12, 11, 12], 20).stalled);
465        assert!(!trend(vec![10, 12, 12, 11, 13], 20).stalled);
466        assert!(!trend(vec![20, 20, 20, 20, 20], 20).stalled);
467    }
468
469    #[test]
470    fn rerunning_diff_on_an_unchanged_port_is_not_an_attempt() {
471        let dir = std::env::temp_dir().join(format!("ra-trend-{}", std::process::id()));
472        std::fs::create_dir_all(dir.join("src")).unwrap();
473        let mut last = None;
474        for (port, passed) in [("a", 1), ("a", 2), ("b", 2), ("c", 2), ("d", 2), ("e", 2)] {
475            std::fs::write(dir.join("src/port.rs"), port).unwrap();
476            last = track(&dir, passed, 5);
477        }
478        std::fs::remove_dir_all(&dir).unwrap();
479        let last = last.unwrap();
480        assert_eq!(last.passed, vec![2, 2, 2, 2, 2]);
481        assert!(last.stalled);
482    }
483
484    #[test]
485    fn entries_need_a_reason() {
486        let dir = std::env::temp_dir().join(format!("ra-known-{}", std::process::id()));
487        std::fs::create_dir_all(&dir).unwrap();
488        std::fs::write(
489            dir.join(KNOWN_DIFFS),
490            "// comment\n{\"fn\": \"f\", \"args\": [1], \"actual\": {\"ok\": 2}}\n",
491        )
492        .unwrap();
493        let err = known_diffs(&dir).unwrap_err();
494        std::fs::remove_dir_all(&dir).unwrap();
495        assert!(format!("{err:#}").contains("reason"), "{err:#}");
496    }
497}