Skip to content

Rewrite your app in Rust, piece by piece, checked against the original at every step. Works with TypeScript, JavaScript, Python, Go, Ruby, Java, C, PHP, C#, Kotlin, PowerShell and Swift.

72.0 KB
Raw Blame
//! What a recording was made from, and the differences from it a port is allowed to keep.
//!
//! `record` saves a fingerprint of the original's unit (`recorded-from.json`): when the original
//! changes later, `diff` and `gate` say the recording is stale instead of passing against old
//! behavior. `known-diffs.jsonl` lists recorded cases where the port is meant to differ, each
//! with the Rust result it gives and why; any other difference still fails, and so does an entry
//! that no longer happens, so the list cannot outlive the differences it explains.

use std::path::Path;

use anyhow::{Context, Result, bail};
use serde_json::{Value, json};

use crate::bridge::Manifest;
use crate::harness::DiffOutcome;
use crate::walk::Canonical;

pub const RECORDED_FROM: &str = "recorded-from.json";
pub const KNOWN_DIFFS: &str = "known-diffs.jsonl";

/// FNV-1a over the unit's files (relative path and contents, in path order): stable across Rust
/// versions and platforms, unlike `DefaultHasher`.
pub fn fingerprint(m: &Manifest) -> Option<(String, usize)> {
    let unit = m.root.join(&m.unit);
    let mut files: Vec<std::path::PathBuf> = if unit.is_file() {
        vec![unit.clone()]
    } else if unit.is_dir() {
        crate::walk::filtered(&unit, |e| {
            !matches!(
                e.file_name().to_str(),
                Some("node_modules" | "target" | ".git" | "__pycache__")
            )
        })
        .build()
        .flatten()
        .filter(|e| e.file_type().is_some_and(|t| t.is_file()))
        .map(|e| e.into_path())
        .collect()
    } else {
        return None;
    };
    // What the unit imports from the rest of the repository is part of what the recording shows.
    files = crate::harness::imported_closure(m, files);
    files.sort();
    let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
    let mut eat = |bytes: &[u8]| {
        for b in bytes {
            hash ^= u64::from(*b);
            hash = hash.wrapping_mul(0x0100_0000_01b3);
        }
    };
    for file in &files {
        let relative = file.strip_prefix(&m.root).unwrap_or(file);
        eat(relative.to_string_lossy().replace('\\', "/").as_bytes());
        eat(&[0]);
        eat(&original_bytes(file)?);
        eat(&[0]);
    }
    Some((format!("{hash:016x}"), files.len()))
}

/// The file as the original wrote it: without any block `enable` put there, this unit's or
/// another's whose file it imports, so switching a unit on or off never makes a recording look
/// stale (`disable` restores the file byte for byte). The last block goes first, as `disable`
/// in the reverse order of `enable` does.
fn original_bytes(file: &Path) -> Option<Vec<u8>> {
    let bytes = std::fs::read(file).ok()?;
    let Ok(text) = std::str::from_utf8(&bytes) else {
        return Some(bytes);
    };
    let mut text = text.to_string();
    while let Some(owner) = last_block_owner(&text)
        && let Some(restored) = crate::enable::remove(&text, &owner)
    {
        text = restored;
    }
    Some(text.into_bytes())
}

/// The crate whose `enable` block starts last in `text`.
fn last_block_owner(text: &str) -> Option<String> {
    const START: &str = ">>> rust-anything: ";
    text.lines().rev().find_map(|line| {
        let after = &line[line.find(START)? + START.len()..];
        Some(after.split_once(" is on.")?.0.to_string())
    })
}

/// FNV-1a over the first `n` lines of `cases.jsonl`, each with its line end.
fn cases_hash(text: &str, n: usize) -> String {
    let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
    for line in text.lines().take(n) {
        for b in line.bytes().chain(*b"\n") {
            hash ^= u64::from(b);
            hash = hash.wrapping_mul(0x0100_0000_01b3);
        }
    }
    format!("{hash:016x}")
}

/// Saves the fingerprint of the original next to `cases.jsonl`, with how much of it the recorded
/// cases ran when that was measured, and the recorded cases' own hash.
pub fn save_fingerprint(crate_dir: &Path, m: &Manifest, coverage: Option<&Value>) -> Result<()> {
    let Some(fingerprint) = fingerprint(m) else {
        return Ok(());
    };
    save_recorded_from(crate_dir, m, &fingerprint, coverage, json!({}))
}

/// Writes `recorded-from.json` in one step: `fingerprint` (taken before the recording ran), the
/// comparison settings, the hash of `cases.jsonl` as it is now, the coverage, and the fields of
/// `counts` (`generated`, `dropped`). A reader sees the old file or the whole new one.
pub(crate) fn save_recorded_from(
    crate_dir: &Path,
    m: &Manifest,
    (hash, files): &(String, usize),
    coverage: Option<&Value>,
    counts: Value,
) -> Result<()> {
    let path = crate_dir.join(RECORDED_FROM);
    let mut saved = json!({ "unit": m.unit, "files": files, "fingerprint": hash });
    // What the comparison allowed when the recording was made: a later change to either setting
    // (a hand edit of rust-anything.json) fails `verify` instead of loosening every diff.
    saved["loosened"] = json!({
        "float_tolerance": m.float_tolerance,
        "ignore_key_order": m.ignore_key_order,
        "messages": m.messages,
    });
    if let Ok(text) = std::fs::read_to_string(crate_dir.join(crate::harness::CASES)) {
        let n = text.lines().count();
        saved["cases"] = json!(n);
        saved["cases_hash"] = json!(cases_hash(&text, n));
    }
    if let Some(c) = coverage {
        saved["coverage"] = c.clone();
    }
    if let Value::Object(fields) = counts {
        for (key, value) in fields {
            saved[key] = value;
        }
    }
    let tmp = crate_dir.join(format!(".{RECORDED_FROM}.{}.tmp", std::process::id()));
    std::fs::write(&tmp, serde_json::to_string_pretty(&saved)? + "\n")
        .with_context(|| format!("writing {}", tmp.display()))?;
    std::fs::rename(&tmp, &path).with_context(|| format!("writing {}", path.display()))
}

/// The coverage `record` saved: `{"lines", "reached", "files": [{"file", "lines", "reached",
/// "missed"}]}`.
pub fn saved_coverage(crate_dir: &Path) -> Option<Value> {
    let saved: Value =
        serde_json::from_str(&std::fs::read_to_string(crate_dir.join(RECORDED_FROM)).ok()?).ok()?;
    saved.get("coverage").filter(|c| c.is_object()).cloned()
}

/// One line for a person: how much of the original the recorded cases ran, and where they
/// did not reach.
pub fn coverage_line(c: &Value) -> Option<String> {
    let lines = c["lines"].as_u64()?;
    let reached = c["reached"].as_u64()?;
    if lines == 0 {
        return None;
    }
    let mut files: Vec<&Value> = c["files"]
        .as_array()
        .into_iter()
        .flatten()
        .filter(|f| f["missed"].as_str().is_some_and(|m| !m.is_empty()))
        .collect();
    files.sort_by_key(|f| {
        std::cmp::Reverse(
            f["lines"]
                .as_u64()
                .unwrap_or(0)
                .saturating_sub(f["reached"].as_u64().unwrap_or(0)),
        )
    });
    let mut missed: Vec<String> = files
        .iter()
        .take(4)
        .map(|f| {
            format!(
                "{}: {}",
                f["file"].as_str().unwrap_or("?"),
                f["missed"].as_str().unwrap_or_default()
            )
        })
        .collect();
    if files.len() > 4 {
        missed.push(format!(
            "{}, listed in {RECORDED_FROM}",
            crate::report::count(files.len() - 4, "more file")
        ));
    }
    // `{:.0}` rounds 99.9% up to `100%`, which reads as full coverage while a line never ran:
    // below 100 the share is floored, and it only prints `100%` when every line ran.
    // A one-line unit reads "1 line", like every other count (issue #855).
    let mut line = format!(
        "the recorded cases ran {reached} of the original's {} ({})",
        crate::report::count(lines as usize, "line"),
        percent(reached, lines)
    );
    if !missed.is_empty() {
        line.push_str(&format!(
            "; never ran: {} (add inputs that reach them, e.g. `record --from-tests`)",
            missed.join("; ")
        ));
    }
    Some(line)
}

/// A whole-number share that never says `100%` unless the counts are equal.
fn percent(reached: u64, lines: u64) -> String {
    if reached >= lines {
        return "100%".into();
    }
    // u128: `reached * 100` in u64 would overflow on a hand-edited record near the top of the range.
    format!("{}%", u128::from(reached) * 100 / u128::from(lines.max(1)))
}

/// Line coverage of the unit's files from the V8 coverage Node writes to `dir`
/// (`NODE_V8_COVERAGE`). A line counts when it has code; it was reached when any of its code ran
/// in any of the record runs. Files Node transformed (not only stripped of types) are left out,
/// since V8's offsets then point into the transformed text.
pub fn node_coverage(dir: &Path, m: &Manifest) -> Option<Value> {
    let mut unit: Vec<std::path::PathBuf> = m
        .exports
        .iter()
        .map(|f| m.root.join(&f.file))
        .chain(m.classes.iter().map(|c| m.root.join(&c.file)))
        .collect();
    unit.sort();
    unit.dedup();
    // `canonical`, not `canonicalize`: on Windows the latter gives `\\?\C:\...`, which no
    // `file:///C:/...` URL in the report would match.
    let root = m.root.canonical().unwrap_or_else(|_| m.root.clone());
    let mut files: Vec<std::path::PathBuf> = crate::gate::with_local_imports(&m.root, unit)
        .into_iter()
        .filter_map(|p| p.canonical().ok())
        .collect();
    files.sort();
    files.dedup();
    let reports: Vec<Value> = std::fs::read_dir(dir)
        .ok()?
        .flatten()
        .filter_map(|e| serde_json::from_str(&std::fs::read_to_string(e.path()).ok()?).ok())
        .collect();
    if reports.is_empty() {
        return None;
    }
    let mut out = Vec::new();
    let (mut total, mut total_reached) = (0u64, 0u64);
    for path in files {
        let file = path
            .strip_prefix(&root)
            .unwrap_or(&path)
            .to_string_lossy()
            .replace('\\', "/");
        let Ok(text) = std::fs::read_to_string(&path) else {
            continue;
        };
        let real = &path;
        let units: usize = text.encode_utf16().count();
        let mut ran = vec![false; units];
        let mut seen = false;
        for report in &reports {
            let transformed = report["source-map-cache"]
                .as_object()
                .is_some_and(|c| c.keys().any(|url| same_file(url, real)));
            if transformed {
                continue;
            }
            for script in report["result"].as_array().into_iter().flatten() {
                if !script["url"].as_str().is_some_and(|u| same_file(u, real)) {
                    continue;
                }
                seen = true;
                let mut counts = vec![0u64; units];
                for f in script["functions"].as_array().into_iter().flatten() {
                    for r in f["ranges"].as_array().into_iter().flatten() {
                        let (Some(s), Some(e), Some(n)) = (
                            r["startOffset"].as_u64(),
                            r["endOffset"].as_u64(),
                            r["count"].as_u64(),
                        ) else {
                            continue;
                        };
                        let (s, e) = (s as usize, (e as usize).min(units));
                        if s < e {
                            counts[s..e].fill(n);
                        }
                    }
                }
                for (r, c) in ran.iter_mut().zip(&counts) {
                    *r |= *c > 0;
                }
            }
        }
        if !seen {
            continue;
        }
        let mut lines: Vec<(usize, bool, bool)> = Vec::new();
        let (mut line, mut code, mut hit) = (1usize, false, false);
        let mut at = 0usize;
        for ch in text.chars() {
            if ch == '\n' {
                lines.push((line, code, hit));
                (line, code, hit) = (line + 1, false, false);
            } else if !ch.is_whitespace() {
                code = true;
                hit |= ran.get(at).copied().unwrap_or(false);
            }
            at += ch.len_utf16();
        }
        lines.push((line, code, hit));
        let code_lines: Vec<(usize, bool)> = lines
            .into_iter()
            .filter(|(_, code, _)| *code)
            .map(|(n, _, hit)| (n, hit))
            .collect();
        let reached = code_lines.iter().filter(|(_, hit)| *hit).count() as u64;
        total += code_lines.len() as u64;
        total_reached += reached;
        out.push(json!({
            "file": file,
            "lines": code_lines.len(),
            "reached": reached,
            "missed": spans(code_lines.iter().filter(|(_, hit)| !hit).map(|(n, _)| *n)),
        }));
    }
    (!out.is_empty()).then(|| json!({ "lines": total, "reached": total_reached, "files": out }))
}

/// Line coverage of the unit's files from the reports the Python driver writes to `dir`, one per
/// record run (`python-<pid>.json`: for each file, the lines that hold code and the ones the cases
/// ran). A line counts as reached when any run reached it.
pub fn python_coverage(dir: &Path, m: &Manifest) -> Option<Value> {
    use std::collections::{BTreeMap, BTreeSet};
    let root = m.root.canonical().unwrap_or_else(|_| m.root.clone());
    let mut files: BTreeMap<String, (BTreeSet<u64>, BTreeSet<u64>)> = BTreeMap::new();
    for entry in std::fs::read_dir(dir).ok()?.flatten() {
        if !entry.file_name().to_string_lossy().starts_with("python-") {
            continue;
        }
        let Some(report) = std::fs::read_to_string(entry.path())
            .ok()
            .and_then(|t| serde_json::from_str::<Value>(&t).ok())
        else {
            continue;
        };
        for (path, f) in report.as_object().into_iter().flatten() {
            let path = Path::new(path);
            let file = path
                .strip_prefix(&root)
                .unwrap_or(path)
                .to_string_lossy()
                .replace('\\', "/");
            let (lines, reached) = files.entry(file).or_default();
            let numbers = |key: &str| {
                f[key]
                    .as_array()
                    .into_iter()
                    .flatten()
                    .filter_map(Value::as_u64)
                    .collect::<Vec<u64>>()
            };
            lines.extend(numbers("lines"));
            reached.extend(numbers("reached"));
        }
    }
    let (mut total, mut total_reached) = (0u64, 0u64);
    let mut out = Vec::new();
    for (file, (lines, reached)) in files {
        let reached: BTreeSet<u64> = reached.intersection(&lines).copied().collect();
        total += lines.len() as u64;
        total_reached += reached.len() as u64;
        out.push(json!({
            "file": file,
            "lines": lines.len(),
            "reached": reached.len(),
            "missed": spans(lines.difference(&reached).map(|n| *n as usize)),
        }));
    }
    (!out.is_empty()).then(|| json!({ "lines": total, "reached": total_reached, "files": out }))
}

/// Whether a V8 `file://` URL names `real`. On Windows the URL is `file:///C:/...`, so the slash
/// before the drive letter goes (`walk::file_url_path`) and `/` and `\` compare as separators.
fn same_file(url: &str, real: &Path) -> bool {
    crate::walk::file_url_path(url, real).is_some_and(|p| Path::new(&p) == real)
}

fn spans(lines: impl Iterator<Item = usize>) -> String {
    let mut out: Vec<(usize, usize)> = Vec::new();
    for n in lines {
        match out.last_mut() {
            Some((_, end)) if *end + 1 == n => *end = n,
            _ => out.push((n, n)),
        }
    }
    out.iter()
        .map(|(a, b)| {
            if a == b {
                a.to_string()
            } else {
                format!("{a}-{b}")
            }
        })
        .collect::<Vec<_>>()
        .join(", ")
}

/// Why the recording no longer describes the original, if it does not: the unit's files changed
/// since `record`. `None` when they did not, or when there is nothing to compare (a recording
/// made before fingerprints, or the original not at hand).
pub fn stale(crate_dir: &Path, m: &Manifest) -> Option<String> {
    let saved: Value =
        serde_json::from_str(&std::fs::read_to_string(crate_dir.join(RECORDED_FROM)).ok()?).ok()?;
    let (now, _) = fingerprint(m)?;
    (saved["fingerprint"].as_str()? != now).then(|| {
        format!(
            "{} changed since it was recorded: re-run `rust-anything record {}` so the port is \
             checked against what the original does now",
            m.unit,
            crate::app::cli_path(crate_dir)
        )
    })
}

/// Why `cases.jsonl` is no longer what `record` wrote, if it is not: its recorded lines were
/// edited or removed. Cases appended after them (`fuzz --keep`) are fine. `None` for a recording
/// made before cases were hashed.
pub fn cases_tampered(crate_dir: &Path) -> Option<String> {
    let saved: Value =
        serde_json::from_str(&std::fs::read_to_string(crate_dir.join(RECORDED_FROM)).ok()?).ok()?;
    let n = usize::try_from(saved["cases"].as_u64()?).ok()?;
    let hash = saved["cases_hash"].as_str()?;
    let text = std::fs::read_to_string(crate_dir.join(crate::harness::CASES)).unwrap_or_default();
    (text.lines().count() < n || cases_hash(&text, n) != hash).then(|| {
        format!(
            "{} changed since `record` wrote it: its {} recorded lines were edited or removed \
             (appending cases is fine); record again instead of editing the recording",
            crate::harness::CASES,
            n
        )
    })
}

/// What `verify` found out about a recording.
#[derive(Debug, Default, Clone, serde::Serialize)]
pub struct Verification {
    /// Reasons the recording cannot be trusted; any one fails the caller.
    pub problems: Vec<String>,
    /// Things the verdict must say although they do not fail it (a legacy recording, a check
    /// that could not run).
    pub notes: Vec<String>,
    /// Recorded cases in `cases.jsonl`.
    pub cases: usize,
    /// Cases `record` asked the generator for and cases it could not record, when `record` said
    /// (`generated` and `dropped` in `recorded-from.json`; `None` in an older recording).
    pub generated: Option<u64>,
    pub dropped: Option<u64>,
    /// The recording is marked as one made before fingerprints, so the stale and edit checks did
    /// not run.
    pub legacy: bool,
}

impl Verification {
    pub fn ok(&self) -> bool {
        self.problems.is_empty()
    }

    /// The problems as one error text for a command that refuses to go on.
    pub fn refusal(&self) -> String {
        self.problems.join("\n")
    }
}

/// What a caller allows `verify` to let through, each of which the verdict then prints.
#[derive(Debug, Default, Clone, Copy)]
pub struct VerifyOptions {
    /// Also fail an exported function or class with no recorded case (gate, enable).
    pub per_export: bool,
    /// `record` dropped this many cases and the caller has looked at them
    /// (`gate --accept-dropped N`).
    pub accept_dropped: Option<u64>,
}

/// Marks a recording made before `recorded-from.json` kept fingerprints: `"legacy_recording":
/// true` in `rust-anything.json`. The recording is then used as it is and every verdict says so.
fn legacy_marked(crate_dir: &Path) -> bool {
    std::fs::read_to_string(crate_dir.join(crate::bridge::MANIFEST))
        .ok()
        .and_then(|t| serde_json::from_str::<Value>(&t).ok())
        .is_some_and(|m| m["legacy_recording"].as_bool() == Some(true))
}

/// Whether the recording can be trusted: `recorded-from.json` is there and readable, the original
/// has not changed since, no recorded line was edited or removed, the recording is not empty, no
/// case was dropped, and with `per_export` every exported function has a case. A missing or
/// unreadable `recorded-from.json` is a failure, not "nothing to check": deleting it must not
/// switch the other checks off. `Verification::default()` (no problem) when there is no
/// `cases.jsonl` at all; the caller reports "no recorded cases" itself.
pub fn verify(crate_dir: &Path, m: &Manifest, opts: VerifyOptions) -> Verification {
    let mut v = Verification::default();
    // A `fuzz` or `held-out` run that was killed left its fresh cases in `cases.jsonl`; put the
    // recording back before it is read.
    match crate::fuzz::recover_interrupted(crate_dir) {
        Ok(Some(msg)) => eprintln!("{msg}"),
        Ok(None) => {}
        Err(e) => {
            v.problems.push(format!(
                "the recording could not be restored from the copy an interrupted `fuzz` left: {e:#}"
            ));
            return v;
        }
    }
    let text = match std::fs::read_to_string(crate_dir.join(crate::harness::CASES)) {
        Ok(text) => text,
        // A recording that was made and whose cases are gone is not "nothing recorded": deleting
        // `cases.jsonl` must not switch the checks off. With neither file, the caller reports
        // "no recorded cases" itself.
        Err(_) if crate_dir.join(RECORDED_FROM).exists() => {
            v.problems.push(format!(
                "{} is missing although {RECORDED_FROM} says a recording was made: run \
                 `rust-anything record {}` again",
                crate::harness::CASES,
                crate::app::cli_path(crate_dir)
            ));
            return v;
        }
        Err(_) => return v,
    };
    let lines: Vec<&str> = text.lines().filter(|l| !l.trim().is_empty()).collect();
    v.cases = lines.len();
    let dir = crate::app::cli_path(crate_dir);
    let legacy = legacy_marked(crate_dir);
    let saved: Option<Value> = std::fs::read_to_string(crate_dir.join(RECORDED_FROM))
        .ok()
        .and_then(|t| serde_json::from_str(&t).ok());
    let unverifiable = |what: &str| {
        format!(
            "{what}, so the recording cannot be verified: the original may have changed or \
             {} may have been edited. Run `rust-anything record {dir}` again; only a recording \
             made by an older rust-anything may be marked `\"legacy_recording\": true` in {}",
            crate::harness::CASES,
            crate::bridge::MANIFEST
        )
    };
    match &saved {
        None => {
            if legacy {
                v.legacy = true;
            } else {
                v.problems.push(unverifiable(&format!(
                    "{RECORDED_FROM} is missing or unreadable"
                )));
            }
        }
        Some(saved) => {
            v.generated = saved["generated"].as_u64();
            v.dropped = saved["dropped"].as_u64();
            let has_hash = saved["fingerprint"].is_string()
                && saved["cases"].is_u64()
                && saved["cases_hash"].is_string();
            if !has_hash {
                if legacy {
                    v.legacy = true;
                } else {
                    v.problems.push(unverifiable(&format!(
                        "{RECORDED_FROM} has no fingerprint or case hash"
                    )));
                }
            } else {
                match fingerprint(m) {
                    // `try_exists`: a parent folder that denies access makes `exists()` say
                    // false, which would read as an absent unit; only `Ok(false)` is absent.
                    None if !matches!(m.root.join(&m.unit).try_exists(), Ok(false)) => v.problems.push(format!(
                        "the original unit {} exists but could not be read, so the stale-recording \
                         check could not run",
                        m.unit
                    )),
                    None => v.notes.push(format!(
                        "the original unit {} was not found, so the stale-recording check did not run",
                        m.unit
                    )),
                    Some((now, _)) if saved["fingerprint"].as_str() != Some(now.as_str()) => {
                        v.problems.push(format!(
                            "{} changed since it was recorded: re-run `rust-anything record {dir}` so the \
                             port is checked against what the original does now",
                            m.unit
                        ));
                    }
                    Some(_) => {}
                }
                let n = usize::try_from(saved["cases"].as_u64().unwrap_or(0)).unwrap_or(0);
                let hash = saved["cases_hash"].as_str().unwrap_or_default();
                if text.lines().count() < n || cases_hash(&text, n) != hash {
                    v.problems.push(format!(
                        "{} changed since `record` wrote it: its {n} recorded lines were edited or \
                         removed (appending cases is fine); record again instead of editing the \
                         recording",
                        crate::harness::CASES
                    ));
                }
            }
            if let Some(was) = saved["loosened"].as_object() {
                let tolerance = was.get("float_tolerance").and_then(Value::as_f64);
                let key_order = was.get("ignore_key_order").and_then(Value::as_bool) == Some(true);
                if tolerance != m.float_tolerance || key_order != m.ignore_key_order {
                    v.problems.push(format!(
                        "the comparison was loosened after `record`: float tolerance {} -> {}, key \
                         order ignored {key_order} -> {}; record again with the setting you mean, \
                         so the recording and its verdicts agree",
                        tolerance.map_or("none".into(), |t| t.to_string()),
                        m.float_tolerance.map_or("none".into(), |t| t.to_string()),
                        m.ignore_key_order
                    ));
                }
                if was.get("messages").and_then(Value::as_bool) == Some(true) && !m.messages {
                    v.problems.push(
                        "the comparison was loosened after `record`: error messages were compared \
                         and no longer are; record again with the setting you mean, so the \
                         recording and its verdicts agree"
                            .into(),
                    );
                }
            }
        }
    }
    if lines.is_empty() {
        v.problems.push(format!(
            "{} holds no recorded case: run `rust-anything record {dir}` (a port checked against \
             nothing proves nothing)",
            crate::harness::CASES
        ));
    }
    if let Some(dropped) = v.dropped.filter(|d| *d > opts.accept_dropped.unwrap_or(0)) {
        v.problems.push(format!(
            "`record` could not record {dropped} of the {} cases it generated (the driver could not \
             encode, decode or finish them), so the port is not checked on them: change the inputs \
             or the original so they record, then `rust-anything record {dir}` again; if you have \
             looked at them and they cannot be recorded, `gate --accept-dropped {dropped}` says so \
             in the verdict and the audit log",
            v.generated
                .map_or_else(|| "some".to_string(), |g| g.to_string())
        ));
    }
    if opts.per_export && !lines.is_empty() {
        let mut have_fn = std::collections::BTreeSet::new();
        let mut have_class = std::collections::BTreeSet::new();
        for line in &lines {
            if let Ok(case) = crate::harness::parse_deep(line) {
                if let Some(f) = case["fn"].as_str() {
                    have_fn.insert(f.to_string());
                }
                if let Some(c) = case["class"].as_str() {
                    have_class.insert(c.to_string());
                }
            }
        }
        let missing: Vec<&str> = m
            .exports
            .iter()
            .map(|f| f.name.as_str())
            .filter(|n| !have_fn.contains(*n))
            .chain(
                m.classes
                    .iter()
                    .map(|c| c.name.as_str())
                    .filter(|n| !have_class.contains(*n)),
            )
            .collect();
        if !missing.is_empty() {
            v.problems.push(format!(
                "no recorded case for {}: a port nothing checks proves nothing; give inputs with \
                 `rust-anything record {dir} --inputs <file>`, or keep the function in the original",
                missing.join(", ")
            ));
        }
    }
    if v.legacy {
        v.notes.push(
            "legacy recording: no fingerprint or case hash, so the stale and edited-recording \
             checks did not run"
                .into(),
        );
    }
    v
}

/// The files `record --float-tolerance`, `--ignore-key-order` and `--pin-clock` change, as they
/// were before, to put back when the record fails and the old recording stays.
pub struct Settings(Vec<(std::path::PathBuf, Option<Vec<u8>>)>);

impl Settings {
    pub fn save(crate_dir: &Path) -> Result<Self> {
        [
            crate::bridge::MANIFEST,
            crate::pin::FILE,
            crate::pin::HELPER,
        ]
        .iter()
        .map(|f| crate_dir.join(f))
        .map(|p| match std::fs::read(&p) {
            Ok(bytes) => Ok((p, Some(bytes))),
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok((p, None)),
            Err(e) => Err(e).with_context(|| format!("cannot read {}", p.display())),
        })
        .collect::<Result<_>>()
        .map(Self)
    }

    pub fn put_back(self) -> Result<()> {
        let mut failed = Vec::new();
        for (path, bytes) in self.0 {
            let restored = match bytes {
                Some(bytes) => crate::setup::write_bytes(&path, &bytes),
                None => match std::fs::remove_file(&path) {
                    Err(e) if e.kind() != std::io::ErrorKind::NotFound => Err(e.into()),
                    _ => Ok(()),
                },
            };
            if let Err(e) = restored {
                failed.push(format!("{} ({e:#})", path.display()));
            }
        }
        if failed.is_empty() {
            Ok(())
        } else {
            bail!(
                "the settings this run changed were not put back, restore them by hand: {}",
                failed.join(", ")
            )
        }
    }

    pub fn put_back_after(self, error: anyhow::Error) -> anyhow::Error {
        match self.put_back() {
            Ok(()) => error,
            Err(restore) => error.context(format!("{restore:#}")),
        }
    }
}

/// The comparison settings a recording is judged under, for the first lines of every verdict.
#[derive(Debug, Default, Clone, PartialEq, serde::Serialize)]
pub struct Loosening {
    pub float_tolerance: Option<f64>,
    pub ignore_key_order: bool,
    /// Error messages are compared as well as error classes (`record --messages`).
    pub messages: bool,
    /// Recorded errors whose message was not compared, only their class: 0 with `messages` on,
    /// and for languages whose errors always match on their text (Go, C, Swift).
    pub unchecked_messages: usize,
    /// Entries in `known-diffs.jsonl`.
    pub known_diffs: usize,
    /// Generated inputs `record` could not record (`recorded-from.json`): nothing compared them.
    pub dropped: usize,
}

impl Loosening {
    pub fn read(crate_dir: &Path) -> Self {
        let m = Manifest::load(crate_dir).ok();
        let messages = m.as_ref().is_some_and(|m| m.messages);
        let by_class = m.as_ref().is_some_and(|m| {
            !matches!(
                m.language,
                crate::lang::Lang::Go | crate::lang::Lang::C | crate::lang::Lang::Swift
            )
        });
        Self {
            float_tolerance: m.as_ref().and_then(|m| m.float_tolerance),
            ignore_key_order: m.as_ref().is_some_and(|m| m.ignore_key_order),
            messages,
            unchecked_messages: if by_class && !messages {
                recorded_errors(crate_dir)
            } else {
                0
            },
            known_diffs: known_diffs(crate_dir).map_or(0, |e| e.len()),
            dropped: std::fs::read_to_string(crate_dir.join(RECORDED_FROM))
                .ok()
                .and_then(|t| serde_json::from_str::<Value>(&t).ok())
                .and_then(|v| v["dropped"].as_u64())
                .map_or(0, |n| usize::try_from(n).unwrap_or(usize::MAX)),
        }
    }

    pub fn is_exact(&self) -> bool {
        self.float_tolerance.is_none()
            && !self.ignore_key_order
            && self.known_diffs == 0
            && self.dropped == 0
    }

    /// `comparison: exact`, or what was loosened.
    pub fn line(&self) -> String {
        if self.is_exact() {
            return "comparison: exact".into();
        }
        let mut parts = Vec::new();
        if let Some(t) = self.float_tolerance {
            parts.push(format!("float tolerance {t}"));
        }
        if self.ignore_key_order {
            parts.push("key order ignored".into());
        }
        if self.known_diffs > 0 {
            parts.push(format!(
                "{} in {KNOWN_DIFFS}",
                crate::report::count(self.known_diffs, "known difference")
            ));
        }
        if self.dropped > 0 {
            parts.push(format!(
                "{} left out of the recording",
                crate::report::count(self.dropped, "input")
            ));
        }
        format!("comparison loosened: {}", parts.join(", "))
    }

    /// One line when recorded errors were matched on their class only.
    pub fn messages_line(&self) -> Option<String> {
        (self.unchecked_messages > 0).then(|| {
            format!(
                "error messages not compared: {} checked by class only (`record --messages` \
                 compares the text too)",
                crate::report::count(self.unchecked_messages, "recorded error")
            )
        })
    }
}

/// Recorded cases that end in an error, a class scenario counting once when any step threw.
fn recorded_errors(crate_dir: &Path) -> usize {
    let Ok(text) = std::fs::read_to_string(crate_dir.join(crate::harness::CASES)) else {
        return 0;
    };
    text.lines()
        .filter(|l| !l.trim().is_empty())
        .filter_map(|l| crate::harness::parse_deep(l).ok())
        .filter(|c| {
            c.get("error").is_some()
                || c["results"]
                    .as_array()
                    .is_some_and(|r| r.iter().any(|step| step.get("error").is_some()))
        })
        .count()
}

const HISTORY: &str = ".rust-anything/diff-history.jsonl";
/// Changes to `port.rs` in a row that gain no matching case before `diff` calls the port stalled.
pub const STALL_AFTER: usize = 3;

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq)]
pub struct Trend {
    /// Cases matching after each change to `port.rs`, oldest first (the last ten).
    pub passed: Vec<usize>,
    pub total: usize,
    /// The last `STALL_AFTER` changes gained nothing while cases still fail.
    pub stalled: bool,
}

/// Records this diff when `port.rs` changed since the last one, and returns the trend. Rerunning
/// `diff` on an unchanged port is not another attempt, so it adds nothing.
pub fn track(crate_dir: &Path, passed: usize, total: usize) -> Option<Trend> {
    let port = std::fs::read(crate_dir.join("src/port.rs")).ok()?;
    let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
    for b in &port {
        hash ^= u64::from(*b);
        hash = hash.wrapping_mul(0x0100_0000_01b3);
    }
    Some(track_in(
        &crate_dir.join(HISTORY),
        &format!("{hash:016x}"),
        passed,
        total,
    ))
}

pub(crate) fn track_in(path: &Path, hash: &str, passed: usize, total: usize) -> Trend {
    let mut runs: Vec<Value> = std::fs::read_to_string(path)
        .unwrap_or_default()
        .lines()
        .filter_map(|l| serde_json::from_str(l).ok())
        .filter(|r: &Value| r["total"].as_u64() == Some(total as u64))
        .collect();
    let entry = json!({ "port": hash, "passed": passed, "total": total });
    match runs.last_mut() {
        Some(last) if last["port"] == entry["port"] => *last = entry,
        _ => runs.push(entry),
    }
    let keep = runs.len().saturating_sub(10);
    runs.drain(..keep);
    if let Some(dir) = path.parent() {
        let _ = std::fs::create_dir_all(dir);
    }
    let text: String = runs.iter().map(|r| format!("{r}\n")).collect();
    let _ = std::fs::write(path, text);
    trend(
        runs.iter()
            .filter_map(|r| r["passed"].as_u64().map(|p| p as usize))
            .collect(),
        total,
    )
}

pub fn last_diff(crate_dir: &Path) -> Option<(usize, usize)> {
    let text = std::fs::read_to_string(crate_dir.join(HISTORY)).ok()?;
    let last: Value = serde_json::from_str(text.lines().last()?).ok()?;
    Some((
        usize::try_from(last["passed"].as_u64()?).ok()?,
        usize::try_from(last["total"].as_u64()?).ok()?,
    ))
}

fn trend(passed: Vec<usize>, total: usize) -> Trend {
    let n = passed.len();
    let stalled = n > STALL_AFTER
        && passed[n - 1] < total
        && passed[n - STALL_AFTER..]
            .iter()
            .all(|p| *p <= passed[..n - STALL_AFTER].iter().copied().max().unwrap_or(0));
    Trend {
        passed,
        total,
        stalled,
    }
}

/// The one `when` an entry may name: every mismatch of `fn` whose original result holds a Python
/// int outside the `i64` range (`{"$int": "..."}`), whatever the arguments were.
pub const INT_BEYOND_I64: &str = "int-beyond-i64";

/// The entries of `known-diffs.jsonl`: `{"fn", "args", "actual", "reason"}` per line, `actual`
/// being the port's result as `diff --json` prints it, or `{"fn", "when", "reason"}` for a class
/// of inputs (see [`INT_BEYOND_I64`]). An entry without a reason is refused.
pub fn known_diffs(crate_dir: &Path) -> Result<Vec<Value>> {
    let path = crate_dir.join(KNOWN_DIFFS);
    let text = match std::fs::read_to_string(&path) {
        Ok(text) => text,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
        Err(e) if e.kind() == std::io::ErrorKind::InvalidData => anyhow::bail!(
            "{} is not UTF-8 (UTF-16 from PowerShell?): save it as UTF-8",
            path.display()
        ),
        Err(e) => return Err(e).with_context(|| format!("cannot read {}", path.display())),
    };
    let mut entries = Vec::new();
    for (i, line) in crate::lang::without_bom(&text).lines().enumerate() {
        let line = line.trim();
        if line.is_empty() || line.starts_with("//") {
            continue;
        }
        let entry: Value = serde_json::from_str(line)
            .with_context(|| format!("{}:{}: not JSON", path.display(), i + 1))?;
        if let Some(when) = entry.get("when") {
            anyhow::ensure!(
                entry.get("fn").is_some(),
                "{}:{}: an entry needs `fn`",
                path.display(),
                i + 1
            );
            anyhow::ensure!(
                when.as_str() == Some(INT_BEYOND_I64),
                "{}:{}: `when` can only be \"{INT_BEYOND_I64}\"",
                path.display(),
                i + 1
            );
            anyhow::ensure!(
                entry.get("args").is_none() && entry.get("actual").is_none(),
                "{}:{}: an entry with `when` covers a class of inputs: drop its `args` and `actual`",
                path.display(),
                i + 1
            );
        } else {
            for key in ["fn", "args", "actual"] {
                anyhow::ensure!(
                    entry.get(key).is_some(),
                    "{}:{}: an entry needs `{key}`",
                    path.display(),
                    i + 1
                );
            }
        }
        anyhow::ensure!(
            entry["reason"]
                .as_str()
                .is_some_and(|r| !r.trim().is_empty()),
            "{}:{}: an entry needs a `reason`: why the port is meant to differ here",
            path.display(),
            i + 1
        );
        entries.push(entry);
    }
    Ok(entries)
}

/// How an entry is named in a message: `f(args)`, or `f when int-beyond-i64`. A stale entry as
/// `--redact` leaves it has a `case` hash in place of its arguments.
pub fn entry_label(entry: &Value) -> String {
    let name = entry["fn"].as_str().unwrap_or("?");
    match entry.get("when").and_then(Value::as_str) {
        Some(when) => format!("{name} when {when}"),
        None => format!("{name}({})", entry.get("args").unwrap_or(&entry["case"])),
    }
}

/// Whether `v` holds an int outside the `i64` range, which a Python result writes as
/// `{"$int": "digits"}` (ints beyond 2**53 cross that way, so one that fits in `i64` does not count).
fn holds_int_beyond_i64(v: &Value) -> bool {
    match v {
        Value::Object(o) if o.len() == 1 && o.contains_key("$int") => {
            o["$int"].as_str().is_some_and(|digits| {
                let n = digits.strip_prefix('-').unwrap_or(digits);
                !n.is_empty()
                    && n.bytes().all(|b| b.is_ascii_digit())
                    && digits.parse::<i64>().is_err()
            })
        }
        Value::Object(o) => o.values().any(holds_int_beyond_i64),
        Value::Array(a) => a.iter().any(holds_int_beyond_i64),
        _ => false,
    }
}

/// The keys the Python harness adds next to `ok`/`error` for a call's effects on its arguments and
/// output. They are not the call's result, so an int in them does not excuse a mismatch.
const EFFECT_KEYS: [&str; 3] = ["args_after", "kwargs_after", "stdout"];

fn result_holds_int_beyond_i64(expected: &Value) -> bool {
    match expected {
        Value::Array(calls) => calls.iter().any(result_holds_int_beyond_i64),
        Value::Object(o) if !o.contains_key("$int") => o
            .iter()
            .any(|(k, v)| !EFFECT_KEYS.contains(&k.as_str()) && holds_int_beyond_i64(v)),
        other => holds_int_beyond_i64(other),
    }
}

fn explains(entry: &Value, mismatch: &Value) -> bool {
    if entry["fn"] != mismatch["fn"] {
        return false;
    }
    if entry.get("when").is_some() {
        return result_holds_int_beyond_i64(&mismatch["expected"]);
    }
    entry["args"] == mismatch["args"] && entry["actual"] == mismatch["actual"]
}

/// Counts the mismatches a known-diffs entry explains as passed (in `accepted`), and records the
/// entries no mismatch matched (in `stale_known`). A mismatch is explained only when the port
/// gives exactly the entry's `actual`: a different wrong result still fails. An entry with `when`
/// explains every mismatch of its function, whatever the arguments, whose expected result (the
/// `ok`/`error` part, not `args_after`, `kwargs_after` or `stdout`) holds an int beyond `i64`; one whose expected result fits still fails. `accepted` counts
/// cases, not entries: one entry explains every recorded copy of its case, and every entry that
/// matches a mismatch is in use.
pub fn apply_known(mut outcome: DiffOutcome, entries: &[Value]) -> DiffOutcome {
    if entries.is_empty() {
        return outcome;
    }
    let mut used = vec![false; entries.len()];
    let before = outcome.mismatches.len();
    outcome.mismatches.retain(|m| {
        let mut explained = false;
        for (e, u) in entries.iter().zip(used.iter_mut()) {
            if explains(e, m) {
                *u = true;
                explained = true;
            }
        }
        !explained
    });
    let accepted = before - outcome.mismatches.len();
    outcome.accepted = accepted;
    outcome.failed -= accepted.min(outcome.failed);
    outcome.passed += accepted;
    outcome.stale_known = entries
        .iter()
        .zip(&used)
        .filter(|(_, u)| !**u)
        .map(|(e, _)| listed(e))
        .collect();
    outcome
}

/// An entry as `stale_known` lists it: without its `actual`.
pub fn listed(entry: &Value) -> Value {
    match entry.get("when") {
        Some(when) => json!({ "fn": entry["fn"], "when": when, "reason": entry["reason"] }),
        None => json!({ "fn": entry["fn"], "args": entry["args"], "reason": entry["reason"] }),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn settings_refuse_a_file_they_cannot_read_and_put_back_a_missing_one() {
        let dir = std::env::temp_dir().join(format!("ra-settings-{}", std::process::id()));
        std::fs::create_dir_all(dir.join(crate::bridge::MANIFEST)).unwrap();
        let err = Settings::save(&dir).err().map(|e| e.to_string());
        std::fs::remove_dir_all(dir.join(crate::bridge::MANIFEST)).unwrap();
        let saved = Settings::save(&dir).unwrap();
        std::fs::write(dir.join(crate::pin::FILE), "x").unwrap();
        saved.put_back().unwrap();
        let left = dir.join(crate::pin::FILE).exists();
        std::fs::remove_dir_all(&dir).unwrap();
        assert!(err.is_some_and(|e| e.contains("cannot read")));
        assert!(!left);
    }
    #[test]
    fn a_setting_that_cannot_be_put_back_is_part_of_the_error() {
        let dir = std::env::temp_dir().join(format!("ra-settings-back-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(dir.join(crate::bridge::MANIFEST), "{}").unwrap();
        let saved = Settings::save(&dir).unwrap();
        std::fs::remove_file(dir.join(crate::bridge::MANIFEST)).unwrap();
        std::fs::create_dir_all(dir.join(crate::bridge::MANIFEST).join("in-the-way")).unwrap();
        let error = format!(
            "{:#}",
            saved.put_back_after(anyhow::anyhow!("recording failed"))
        );
        std::fs::remove_dir_all(&dir).unwrap();
        assert!(error.contains("recording failed"), "{error}");
        assert!(error.contains("not put back"), "{error}");
        assert!(error.contains(crate::bridge::MANIFEST), "{error}");
    }

    #[test]
    fn the_coverage_line_counts_one_line_in_the_singular() {
        assert_eq!(
            coverage_line(&json!({"lines": 1, "reached": 1})).as_deref(),
            Some("the recorded cases ran 1 of the original's 1 line (100%)")
        );
        assert_eq!(
            coverage_line(&json!({"lines": 4, "reached": 3})).as_deref(),
            Some("the recorded cases ran 3 of the original's 4 lines (75%)")
        );
    }

    #[test]
    fn the_coverage_line_counts_one_more_file_in_the_singular() {
        let line = |n: usize| {
            let files: Vec<_> = (1..=n)
                .map(|i| json!({"file": format!("src/f{i}.ts"), "lines": 10, "reached": 9, "missed": "3"}))
                .collect();
            coverage_line(&json!({"lines": 10 * n, "reached": 9 * n, "files": files})).unwrap()
        };
        let five = line(5);
        assert!(
            five.contains("; 1 more file, listed in recorded-from.json"),
            "{five}"
        );
        let six = line(6);
        assert!(
            six.contains("; 2 more files, listed in recorded-from.json"),
            "{six}"
        );
    }

    fn outcome() -> DiffOutcome {
        DiffOutcome {
            total: 3,
            passed: 1,
            failed: 2,
            mismatches: vec![
                json!({"fn": "f", "args": [1], "expected": {"ok": 1}, "actual": {"ok": 2}}),
                json!({"fn": "f", "args": [2], "expected": {"ok": 1}, "actual": {"ok": 3}}),
            ],
            ..DiffOutcome::default()
        }
    }

    #[test]
    fn a_share_just_under_full_never_reads_as_100_percent() {
        assert_eq!(percent(1000, 1000), "100%");
        assert_eq!(percent(999, 1000), "99%");
        assert_eq!(percent(1999, 2000), "99%");
        assert_eq!(percent(1, 3), "33%");
        assert_eq!(percent(0, 10), "0%");
        assert_eq!(percent(5, 0), "100%");
    }

    #[test]
    fn covered_lines_run_together_and_gaps_keep_their_own_range() {
        assert_eq!(spans(std::iter::empty()), "");
        assert_eq!(spans([5].into_iter()), "5");
        assert_eq!(spans([1, 2, 3].into_iter()), "1-3");
        assert_eq!(spans([1, 2, 3, 5, 7, 8].into_iter()), "1-3, 5, 7-8");
        // A gap of one line still splits the range.
        assert_eq!(spans([1, 3].into_iter()), "1, 3");
    }

    #[test]
    fn known_diffs_pass_only_with_the_listed_result() {
        let entries = [
            json!({"fn": "f", "args": [1], "actual": {"ok": 2}, "reason": "fixed a bug"}),
            json!({"fn": "f", "args": [2], "actual": {"ok": 4}, "reason": "other result"}),
            json!({"fn": "g", "args": [], "actual": {"ok": 0}, "reason": "gone"}),
        ];
        let out = apply_known(outcome(), &entries);
        assert_eq!((out.passed, out.failed, out.accepted), (2, 1, 1));
        assert_eq!(out.mismatches.len(), 1);
        assert_eq!(out.mismatches[0]["args"], json!([2]));
        assert_eq!(out.stale_known.len(), 2);
    }

    #[test]
    fn one_known_diffs_entry_explains_every_copy_of_a_case_recorded_twice() {
        let mismatch = json!({"fn": "f", "args": [1], "expected": {"ok": 1}, "actual": {"ok": 2}});
        let twice = || DiffOutcome {
            total: 3,
            passed: 1,
            failed: 2,
            mismatches: vec![mismatch.clone(), mismatch.clone()],
            ..DiffOutcome::default()
        };
        let entry = json!({"fn": "f", "args": [1], "actual": {"ok": 2}, "reason": "fixed a bug"});
        let out = apply_known(twice(), std::slice::from_ref(&entry));
        assert_eq!((out.passed, out.failed, out.accepted), (3, 0, 2));
        assert!(out.mismatches.is_empty());
        assert!(out.stale_known.is_empty());
        // A second entry for the same case is not stale: it explains the same mismatches.
        let out = apply_known(twice(), &[entry.clone(), entry]);
        assert_eq!((out.passed, out.failed, out.accepted), (3, 0, 2));
        assert!(out.stale_known.is_empty());
    }

    #[test]
    fn an_int_beyond_i64_entry_explains_a_mismatch_whose_expected_result_holds_such_an_int() {
        let entry = json!({"fn": "add", "when": "int-beyond-i64", "reason": "i64 is enough"});
        let mismatch = |expected: Value| json!({"fn": "add", "args": [9223372036854775807i64, 41], "expected": expected, "actual": {"ok": -9223372036854775768i64}});
        let outcome = |mismatches: Vec<Value>| DiffOutcome {
            total: 4,
            passed: 4 - mismatches.len(),
            failed: mismatches.len(),
            mismatches,
            ..DiffOutcome::default()
        };
        let beyond = |digits: &str| json!({"$int": digits});
        for expected in [
            beyond("9223372036854775848"),
            json!({"ok": beyond("9223372036854775848")}),
            json!({"ok": [1, {"n": beyond("-9223372036854775809")}]}),
            json!({"error": beyond("9223372036854775848")}),
            json!({"ok": beyond("9223372036854775848"), "args_after": [1]}),
            json!({"ok": {"stdout": beyond("9223372036854775848")}}),
            json!([{"ok": true}, {"ok": beyond("9223372036854775848")}]),
        ] {
            let out = apply_known(
                outcome(vec![mismatch(expected.clone())]),
                std::slice::from_ref(&entry),
            );
            assert_eq!(
                (out.passed, out.failed, out.accepted),
                (4, 0, 1),
                "{expected}"
            );
            assert!(out.stale_known.is_empty(), "{expected}");
        }
        for expected in [
            json!(5),
            json!({"ok": 5}),
            json!({"ok": beyond("9223372036854775807")}),
            json!({"ok": beyond("-9223372036854775808")}),
            json!({"ok": "9223372036854775848"}),
            json!({"ok": {"$int": "9223372036854775848", "other": 1}}),
            json!({"ok": 5, "args_after": [beyond("9223372036854775848")]}),
            json!({"ok": 5, "kwargs_after": {"n": beyond("9223372036854775848")}}),
            json!({"ok": 5, "stdout": beyond("9223372036854775848")}),
            json!([{"ok": true}, {"ok": 5}]),
        ] {
            let out = apply_known(
                outcome(vec![mismatch(expected.clone())]),
                std::slice::from_ref(&entry),
            );
            assert_eq!(
                (out.passed, out.failed, out.accepted),
                (3, 1, 0),
                "{expected}"
            );
            assert_eq!(out.stale_known.len(), 1, "{expected}");
        }
        let other_fn = json!({"fn": "sub", "args": [], "expected": beyond("9223372036854775848"), "actual": 1});
        let out = apply_known(outcome(vec![other_fn]), std::slice::from_ref(&entry));
        assert_eq!((out.failed, out.accepted), (1, 0));
    }

    #[test]
    fn an_entry_with_a_when_needs_a_known_class_and_no_args() {
        let dir = std::env::temp_dir().join(format!("ra-known-when-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let read = |line: &str| {
            std::fs::write(dir.join(KNOWN_DIFFS), line).unwrap();
            known_diffs(&dir)
        };
        let ok = read("{\"fn\": \"add\", \"when\": \"int-beyond-i64\", \"reason\": \"r\"}\n");
        let unknown = read("{\"fn\": \"add\", \"when\": \"big\", \"reason\": \"r\"}\n");
        let mixed = read(
            "{\"fn\": \"add\", \"when\": \"int-beyond-i64\", \"args\": [1], \"reason\": \"r\"}\n",
        );
        let reasonless = read("{\"fn\": \"add\", \"when\": \"int-beyond-i64\"}\n");
        std::fs::remove_dir_all(&dir).unwrap();
        assert_eq!(ok.unwrap().len(), 1);
        let unknown = format!("{:#}", unknown.unwrap_err());
        assert!(unknown.contains("int-beyond-i64"), "{unknown}");
        let mixed = format!("{:#}", mixed.unwrap_err());
        assert!(
            mixed.contains("`when`") && mixed.contains("`args`"),
            "{mixed}"
        );
        let reasonless = format!("{:#}", reasonless.unwrap_err());
        assert!(reasonless.contains("reason"), "{reasonless}");
    }

    #[test]
    fn an_unused_when_entry_is_stale_and_keeps_its_name_through_redact() {
        let entry = json!({"fn": "add", "when": "int-beyond-i64", "reason": "i64 is enough"});
        let out = apply_known(outcome(), std::slice::from_ref(&entry));
        assert_eq!(out.stale_known.len(), 1);
        assert_eq!(entry_label(&out.stale_known[0]), "add when int-beyond-i64");
        let mut redacted = out;
        crate::mismatch::redact_diff(&mut redacted);
        assert_eq!(redacted.stale_known[0]["when"], "int-beyond-i64");
        assert_eq!(
            entry_label(&redacted.stale_known[0]),
            "add when int-beyond-i64"
        );
    }

    #[test]
    fn a_port_stalls_after_changes_that_gain_nothing() {
        assert!(!trend(vec![10, 12, 15], 20).stalled);
        assert!(!trend(vec![10, 12, 12, 12], 20).stalled);
        assert!(trend(vec![10, 12, 12, 11, 12], 20).stalled);
        assert!(!trend(vec![10, 12, 12, 11, 13], 20).stalled);
        assert!(!trend(vec![20, 20, 20, 20, 20], 20).stalled);
    }

    #[test]
    fn rerunning_diff_on_an_unchanged_port_is_not_an_attempt() {
        let dir = std::env::temp_dir().join(format!("ra-trend-{}", std::process::id()));
        std::fs::create_dir_all(dir.join("src")).unwrap();
        let mut last = None;
        for (port, passed) in [("a", 1), ("a", 2), ("b", 2), ("c", 2), ("d", 2), ("e", 2)] {
            std::fs::write(dir.join("src/port.rs"), port).unwrap();
            last = track(&dir, passed, 5);
        }
        std::fs::remove_dir_all(&dir).unwrap();
        let last = last.unwrap();
        assert_eq!(last.passed, vec![2, 2, 2, 2, 2]);
        assert!(last.stalled);
    }

    #[test]
    fn entries_need_a_reason() {
        let dir = std::env::temp_dir().join(format!("ra-known-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(
            dir.join(KNOWN_DIFFS),
            "// comment\n{\"fn\": \"f\", \"args\": [1], \"actual\": {\"ok\": 2}}\n",
        )
        .unwrap();
        let err = known_diffs(&dir).unwrap_err();
        std::fs::remove_dir_all(&dir).unwrap();
        assert!(format!("{err:#}").contains("reason"), "{err:#}");
    }

    #[test]
    fn a_byte_order_mark_at_the_start_of_known_diffs_is_skipped() {
        // Windows PowerShell 5 (`-Encoding utf8`) and older Notepad save a UTF-8 file with one.
        let dir = std::env::temp_dir().join(format!("ra-known-bom-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let entry = "{\"fn\": \"f\", \"args\": [1], \"actual\": 2, \"reason\": \"intended\"}\n";
        std::fs::write(dir.join(KNOWN_DIFFS), format!("\u{feff}{entry}")).unwrap();
        let found = known_diffs(&dir).unwrap();
        std::fs::remove_dir_all(&dir).unwrap();
        assert_eq!(found.len(), 1);
        assert_eq!(found[0]["fn"], "f");
    }

    #[test]
    fn a_known_diffs_file_that_is_not_utf8_is_refused_by_name() {
        // Windows PowerShell 5's `>` and `Out-File` save UTF-16 LE with a byte-order mark.
        let dir = std::env::temp_dir().join(format!("ra-known-utf16-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let entry = "{\"fn\": \"f\", \"args\": [1], \"actual\": 2, \"reason\": \"intended\"}\n";
        let utf16: Vec<u8> = format!("\u{feff}{entry}")
            .encode_utf16()
            .flat_map(u16::to_le_bytes)
            .collect();
        std::fs::write(dir.join(KNOWN_DIFFS), utf16).unwrap();
        let err = known_diffs(&dir).unwrap_err().to_string();
        std::fs::remove_dir_all(&dir).unwrap();
        assert!(err.contains(KNOWN_DIFFS), "{err}");
        assert!(err.contains("not UTF-8"), "{err}");
    }

    #[test]
    fn a_missing_known_diffs_file_has_no_entries() {
        let dir = std::env::temp_dir().join(format!("ra-known-missing-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let found = known_diffs(&dir).unwrap();
        std::fs::remove_dir_all(&dir).unwrap();
        assert!(found.is_empty());
    }
}

#[cfg(test)]
mod verify_tests {
    use super::*;

    #[test]
    fn inputs_left_out_of_the_recording_are_named_on_the_comparison_line() {
        let (dir, _) = recorded("loosening-dropped");
        assert_eq!(Loosening::read(&dir).line(), "comparison: exact");
        let path = dir.join(RECORDED_FROM);
        let mut saved: Value =
            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
        saved["dropped"] = json!(2);
        std::fs::write(&path, saved.to_string()).unwrap();
        let line = Loosening::read(&dir).line();
        assert_eq!(
            line,
            "comparison loosened: 2 inputs left out of the recording"
        );
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// A unit `lib.ts` with one export `f`, three recorded cases and the fingerprint file `record`
    /// writes for them.
    fn recorded(tag: &str) -> (std::path::PathBuf, Manifest) {
        let dir = crate::app::temp_dir(tag).unwrap();
        std::fs::write(
            dir.join("lib.ts"),
            "export function f(x: number) { return x }\n",
        )
        .unwrap();
        std::fs::write(
            dir.join(crate::harness::CASES),
            "{\"fn\":\"f\",\"args\":[1],\"ok\":1}\n{\"fn\":\"f\",\"args\":[2],\"ok\":2}\n{\"fn\":\"f\",\"args\":[3],\"ok\":3}\n",
        )
        .unwrap();
        let m: Manifest = serde_json::from_value(json!({
            "schema": crate::bridge::SCHEMA,
            "root": dir,
            "unit": "lib.ts",
            "crate_name": "demo",
            "kind": "napi",
            "exports": [{"name": "f", "file": "lib.ts", "line": 1, "params": [], "returns": "number", "is_async": false}],
        }))
        .unwrap();
        save_fingerprint(&dir, &m, None).unwrap();
        (dir, m)
    }

    #[test]
    fn another_units_block_in_an_imported_file_leaves_the_fingerprint_as_it_was() {
        let dir = crate::app::temp_dir("fingerprint-other-block").unwrap();
        std::fs::write(dir.join("b.py"), "def g(x):\n    return x\n").unwrap();
        std::fs::write(
            dir.join("a.py"),
            "from b import g\n\ndef f(x):\n    return g(x)\n",
        )
        .unwrap();
        let m: Manifest = serde_json::from_value(json!({
            "schema": crate::bridge::SCHEMA,
            "root": dir,
            "unit": "a.py",
            "language": "python",
            "kind": "pyo3",
            "crate_name": "a-rs",
            "exports": [{"name": "f", "file": "a.py", "line": 3, "params": [], "returns": "unknown", "is_async": false}],
        }))
        .unwrap();
        let (before, files) = fingerprint(&m).unwrap();
        assert_eq!(files, 2, "a.py's fingerprint covers the b.py it imports");
        let block = |name: &str| {
            format!(
                "# >>> rust-anything: {name} is on. `rust-anything disable {name}` removes this block.\nfrom {name} import *\n# <<< rust-anything: {name}\n"
            )
        };
        std::fs::write(
            dir.join("b.py"),
            format!(
                "def g(x):\n    return x\n{}{}",
                block("b-rs"),
                block("c-rs")
            ),
        )
        .unwrap();
        let (after, _) = fingerprint(&m).unwrap();
        std::fs::remove_dir_all(&dir).unwrap();
        assert_eq!(before, after, "switching other units on is not a change");
    }

    #[test]
    fn the_counts_are_saved_in_the_same_write_as_the_fingerprint() {
        let (dir, m) = recorded("fingerprint-counts");
        let fingerprint = fingerprint(&m).unwrap();
        std::fs::write(
            dir.join("lib.ts"),
            "export function f(x: number) { return -x }\n",
        )
        .unwrap();
        save_recorded_from(
            &dir,
            &m,
            &fingerprint,
            None,
            json!({"generated": 4, "dropped": 1}),
        )
        .unwrap();
        let saved: Value =
            serde_json::from_str(&std::fs::read_to_string(dir.join(RECORDED_FROM)).unwrap())
                .unwrap();
        let v = verify(&dir, &m, VerifyOptions::default());
        std::fs::remove_dir_all(&dir).unwrap();
        assert_eq!(saved["fingerprint"], json!(fingerprint.0));
        assert_eq!(
            (saved["generated"].as_u64(), saved["dropped"].as_u64()),
            (Some(4), Some(1))
        );
        assert!(
            v.problems
                .iter()
                .any(|p| p.contains("changed since it was recorded")),
            "the fingerprint taken before the edit makes the recording stale: {:?}",
            v.problems
        );
    }

    fn per_export() -> VerifyOptions {
        VerifyOptions {
            per_export: true,
            accept_dropped: None,
        }
    }

    #[test]
    fn an_untouched_recording_verifies() {
        let (dir, m) = recorded("verify-ok");
        let v = verify(&dir, &m, per_export());
        assert!(v.ok(), "{:?}", v.problems);
        assert_eq!(v.cases, 3);
        assert!(v.notes.is_empty(), "{:?}", v.notes);
    }

    #[test]
    fn deleting_recorded_from_json_fails_instead_of_switching_the_checks_off() {
        // The audit's top finding: with the file gone, `stale` and `cases_tampered` both say
        // `None`, and an agent could then delete the failing lines of cases.jsonl.
        let (dir, m) = recorded("verify-deleted");
        std::fs::remove_file(dir.join(RECORDED_FROM)).unwrap();
        std::fs::write(
            dir.join(crate::harness::CASES),
            "{\"fn\":\"f\",\"args\":[1],\"ok\":1}\n",
        )
        .unwrap();
        assert_eq!(cases_tampered(&dir), None, "the old check saw nothing");
        let v = verify(&dir, &m, per_export());
        assert!(!v.ok());
        assert!(
            v.problems[0].contains("cannot be verified"),
            "{:?}",
            v.problems
        );
        assert!(
            v.problems[0].contains("rust-anything record"),
            "{:?}",
            v.problems
        );
    }

    #[test]
    fn deleting_cases_jsonl_fails_when_a_recording_was_made() {
        let (dir, m) = recorded("verify-no-cases");
        std::fs::remove_file(dir.join(crate::harness::CASES)).unwrap();
        let v = verify(&dir, &m, per_export());
        assert!(!v.ok(), "a deleted recording must not pass");
        assert!(
            v.problems[0].contains("rust-anything record"),
            "{:?}",
            v.problems
        );
        // With neither file there is simply no recording: the caller says so itself.
        std::fs::remove_file(dir.join(RECORDED_FROM)).unwrap();
        assert!(verify(&dir, &m, per_export()).ok());
    }

    #[test]
    fn an_original_replaced_by_something_else_fails() {
        let (dir, m) = recorded("verify-unreadable");
        // A directory with the name of the unit file: it exists, and reading it fails.
        let unit = m.root.join(&m.unit);
        std::fs::remove_file(&unit).unwrap();
        std::fs::create_dir_all(unit.join("sub")).unwrap();
        std::fs::write(unit.join("sub").join("a.bin"), [0xff, 0xfe]).unwrap();
        let v = verify(&dir, &m, per_export());
        assert!(
            !v.ok()
                && v.problems
                    .iter()
                    .any(|p| p.contains("changed") || p.contains("could not be read")),
            "{:?} {:?}",
            v.problems,
            v.notes
        );
    }

    #[test]
    fn a_recording_without_a_case_hash_fails_unless_marked_legacy() {
        let (dir, m) = recorded("verify-legacy");
        let mut saved: Value =
            serde_json::from_str(&std::fs::read_to_string(dir.join(RECORDED_FROM)).unwrap())
                .unwrap();
        saved.as_object_mut().unwrap().remove("cases_hash");
        std::fs::write(dir.join(RECORDED_FROM), saved.to_string()).unwrap();
        assert!(!verify(&dir, &m, per_export()).ok());
        // A recording made before fingerprints is accepted only when it says so, and the
        // verdict carries the note.
        std::fs::write(
            dir.join(crate::bridge::MANIFEST),
            "{\"legacy_recording\": true}\n",
        )
        .unwrap();
        let v = verify(&dir, &m, per_export());
        assert!(v.ok(), "{:?}", v.problems);
        assert!(v.legacy);
        assert!(
            v.notes.iter().any(|n| n.contains("legacy recording")),
            "{:?}",
            v.notes
        );
    }

    #[test]
    fn an_edited_removed_or_stale_recording_fails() {
        let (dir, m) = recorded("verify-edited");
        let cases = dir.join(crate::harness::CASES);
        let original = std::fs::read_to_string(&cases).unwrap();
        // One line removed.
        std::fs::write(
            &cases,
            original.lines().skip(1).collect::<Vec<_>>().join("\n") + "\n",
        )
        .unwrap();
        let v = verify(&dir, &m, per_export());
        assert!(
            v.problems.iter().any(|p| p.contains("edited or removed")),
            "{:?}",
            v.problems
        );
        // One value edited in place, same number of lines.
        std::fs::write(&cases, original.replace("\"ok\":2", "\"ok\":9")).unwrap();
        assert!(!verify(&dir, &m, per_export()).ok());
        // Restored, then the original changes.
        std::fs::write(&cases, &original).unwrap();
        assert!(verify(&dir, &m, per_export()).ok());
        std::fs::write(
            dir.join("lib.ts"),
            "export function f(x: number) { return x + 1 }\n",
        )
        .unwrap();
        let v = verify(&dir, &m, per_export());
        assert!(
            v.problems
                .iter()
                .any(|p| p.contains("changed since it was recorded")),
            "{:?}",
            v.problems
        );
    }

    #[test]
    fn switching_a_unit_on_does_not_make_its_recording_stale() {
        // `enable` writes a block into the original; the fingerprint is of the file without it.
        let (dir, m) = recorded("verify-enabled");
        let text = std::fs::read_to_string(dir.join("lib.ts")).unwrap();
        let block = "// >>> rust-anything: demo is on. `rust-anything disable x` removes this block.\nf = native.f\n// <<< rust-anything: demo\n";
        std::fs::write(dir.join("lib.ts"), format!("{block}{text}")).unwrap();
        assert_eq!(stale(&dir, &m), None);
        assert!(verify(&dir, &m, per_export()).ok());
    }

    #[test]
    fn an_empty_recording_and_an_export_without_a_case_fail() {
        let (dir, m) = recorded("verify-thin");
        std::fs::write(
            dir.join(crate::harness::CASES),
            "{\"fn\":\"g\",\"args\":[],\"ok\":1}\n",
        )
        .unwrap();
        save_fingerprint(&dir, &m, None).unwrap();
        let v = verify(&dir, &m, per_export());
        assert!(
            v.problems
                .iter()
                .any(|p| p.contains("no recorded case for f")),
            "{:?}",
            v.problems
        );
        // `diff` and `map` do not ask for a case per export.
        assert!(verify(&dir, &m, VerifyOptions::default()).ok());
        std::fs::write(dir.join(crate::harness::CASES), "").unwrap();
        save_fingerprint(&dir, &m, None).unwrap();
        let v = verify(&dir, &m, VerifyOptions::default());
        assert!(
            v.problems
                .iter()
                .any(|p| p.contains("holds no recorded case")),
            "{:?}",
            v.problems
        );
    }

    #[test]
    fn cases_record_dropped_fail_until_accepted_by_number() {
        let (dir, m) = recorded("verify-dropped");
        let mut saved: Value =
            serde_json::from_str(&std::fs::read_to_string(dir.join(RECORDED_FROM)).unwrap())
                .unwrap();
        saved["generated"] = json!(10);
        saved["dropped"] = json!(7);
        std::fs::write(dir.join(RECORDED_FROM), saved.to_string()).unwrap();
        let v = verify(&dir, &m, per_export());
        assert!(
            v.problems
                .iter()
                .any(|p| p.contains("could not record 7 of the 10")),
            "{:?}",
            v.problems
        );
        let accepted = VerifyOptions {
            accept_dropped: Some(7),
            ..per_export()
        };
        assert!(verify(&dir, &m, accepted).ok());
        // A recording that does not say (older than the counts) is not failed for it.
        saved.as_object_mut().unwrap().remove("dropped");
        std::fs::write(dir.join(RECORDED_FROM), saved.to_string()).unwrap();
        assert!(verify(&dir, &m, per_export()).ok());
    }

    #[test]
    fn loosening_the_comparison_after_record_fails_the_recording() {
        let (dir, mut m) = recorded("verify-loosened");
        m.float_tolerance = Some(0.5);
        let v = verify(&dir, &m, per_export());
        assert!(
            v.problems
                .iter()
                .any(|p| p.contains("loosened after `record`")),
            "{:?}",
            v.problems
        );
        // Recorded under that setting, it verifies, and says so on every verdict.
        save_fingerprint(&dir, &m, None).unwrap();
        assert!(verify(&dir, &m, per_export()).ok());
        assert!(
            Loosening {
                float_tolerance: Some(0.5),
                ..Loosening::default()
            }
            .line()
            .contains("float tolerance 0.5")
        );
        assert_eq!(Loosening::default().line(), "comparison: exact");
    }

    #[test]
    fn turning_messages_off_after_record_fails_the_recording() {
        let (dir, mut m) = recorded("verify-messages");
        m.messages = true;
        save_fingerprint(&dir, &m, None).unwrap();
        assert!(verify(&dir, &m, per_export()).ok());
        m.messages = false;
        let v = verify(&dir, &m, per_export());
        assert!(
            v.problems
                .iter()
                .any(|p| p.contains("error messages were compared")),
            "{:?}",
            v.problems
        );
        // Turning them on after `record` only holds the port to more.
        save_fingerprint(&dir, &m, None).unwrap();
        m.messages = true;
        assert!(verify(&dir, &m, per_export()).ok());
    }

    #[test]
    fn recorded_errors_are_counted_where_only_their_class_is_compared() {
        let (dir, mut m) = recorded("loosening-messages");
        std::fs::write(
            dir.join(crate::harness::CASES),
            "{\"fn\":\"f\",\"args\":[1],\"ok\":1}\n\
             {\"fn\":\"f\",\"args\":[2],\"error\":\"bad\",\"error_type\":\"RangeError\"}\n\
             {\"class\":\"C\",\"ctor\":[],\"calls\":[],\"results\":[{\"ok\":true},{\"error\":\"x\"}]}\n",
        )
        .unwrap();
        m.save(&dir).unwrap();
        let read = Loosening::read(&dir);
        assert_eq!((read.messages, read.unchecked_messages), (false, 2));
        assert!(read.messages_line().unwrap().contains("2 recorded errors"));
        assert_eq!(read.line(), "comparison: exact");
        m.messages = true;
        m.save(&dir).unwrap();
        let read = Loosening::read(&dir);
        assert_eq!((read.messages, read.messages_line()), (true, None));
        // Go, C and Swift compare an error's text already: nothing to say.
        m.messages = false;
        m.language = crate::lang::Lang::Go;
        m.save(&dir).unwrap();
        assert_eq!(Loosening::read(&dir).messages_line(), None);
    }
}