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.

73.8 KB
Raw Blame
//! Live differential testing: fresh inputs from a new seed, run through the original and the
//! port, mismatches reported and optionally kept in the recording.
//!
//! Every language's record and diff drivers read and write `cases.jsonl`, so a round records
//! its fresh cases there, diffs them, and puts the recording back. Whatever happens, the file
//! the round started from is restored before anything is kept.

use std::collections::{BTreeMap, HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};

use anyhow::{Context as _, Result, bail};
use serde::Serialize;
use serde_json::Value;

use crate::bridge::{Manifest, RType};
use crate::harness::{self, CASES, DiffOptions, RecordOptions, WORK_DIR};
use crate::ts::exports::{LocalType, Param};
use crate::ts::shape::{self, Shape};

/// Which fresh cases `--keep` appends to the recording.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, clap::ValueEnum)]
#[serde(rename_all = "lowercase")]
pub enum Keep {
    /// Only the cases where the port differs from the original.
    Mismatches,
    /// Every fresh case.
    All,
}

pub struct FuzzOptions<'a> {
    pub crate_dir: &'a Path,
    /// Fresh cases per function and class in each round.
    pub cases: usize,
    /// The first round's seed; later rounds count up from it. Random when `None`.
    pub seed: Option<u64>,
    /// Keep starting rounds until this much time has passed; one round when `None`.
    pub time: Option<Duration>,
    pub keep: Option<Keep>,
    pub resolve_from: Option<&'a Path>,
    pub node_args: &'a [String],
    /// Run the original in the sandbox `record --sandbox` uses, in every round.
    pub sandbox: bool,
    /// A command that prints each round's inputs in the `record --inputs` format, in place of the
    /// built-in generator. It runs with `RUST_ANYTHING_SEED` (the round's seed) and
    /// `RUST_ANYTHING_CASES` set.
    pub generator: Option<&'a str>,
}

#[derive(Debug, Serialize)]
pub struct FuzzOutcome {
    /// Replays this run with `--seed`.
    pub seed: u64,
    pub rounds: u64,
    /// Fresh cases run on both sides (inputs the original timed out on are left out).
    pub cases: usize,
    pub passed: usize,
    pub failed: usize,
    /// Exports the port does not provide.
    pub missing: Vec<String>,
    /// The first mismatches: `{ fn, args, expected, actual }`.
    pub mismatches: Vec<Value>,
    /// Cases appended to `cases.jsonl` (`--keep`).
    pub kept: usize,
    pub recording: PathBuf,
    /// Fresh inputs the original could not be recorded on (its result could not be encoded, or it
    /// ended the run): they were not compared.
    #[serde(skip_serializing_if = "is_zero")]
    pub dropped: usize,
}

fn is_zero(n: &usize) -> bool {
    *n == 0
}

const SHOWN: usize = 20;

/// The copy of the round's files, under `.rust-anything/`, and the list of which were present.
const RESTORE_DIR: &str = "fuzz-restore";
const RESTORE_LIST: &str = "present.txt";

/// Puts `cases.jsonl` and the timed-out list back as they were, also on an error.
struct Restore(Vec<(PathBuf, Option<Vec<u8>>)>);

impl Restore {
    fn new(paths: &[PathBuf]) -> Self {
        Self(
            paths
                .iter()
                .map(|p| (p.clone(), std::fs::read(p).ok()))
                .collect(),
        )
    }
}

impl Drop for Restore {
    fn drop(&mut self) {
        for (path, saved) in &self.0 {
            let _ = match saved {
                Some(bytes) => std::fs::write(path, bytes),
                None => std::fs::remove_file(path),
            };
        }
    }
}

/// The files a round writes into and puts back: the recording and the two lists the drivers write.
fn round_files(crate_dir: &Path) -> Vec<PathBuf> {
    let work = crate_dir.join(WORK_DIR);
    vec![
        crate_dir.join(CASES),
        work.join(harness::TIMED_OUT),
        work.join(harness::DROPPED),
    ]
}

fn restore_dir(crate_dir: &Path) -> PathBuf {
    crate_dir.join(WORK_DIR).join(RESTORE_DIR)
}

/// A copy of the files a round writes, kept in `.rust-anything/fuzz-restore/` while `fuzz` and
/// `held-out` run. `Restore` puts them back when the run returns, but a run that is killed
/// (SIGINT, SIGTERM, a CI timeout) runs no `Drop`: the copy stays, and the next command that
/// reads the recording puts it back ([`put_back_locked`]). The list of present files is written
/// last, so a copy without one was still being made and the recording was never touched.
struct RestorePoint(PathBuf);

impl RestorePoint {
    fn save(crate_dir: &Path) -> Result<Self> {
        let dir = restore_dir(crate_dir);
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir)?;
        let mut present = Vec::new();
        for path in round_files(crate_dir) {
            if path.is_file() {
                let name = file_name(&path);
                std::fs::copy(&path, dir.join(&name))?;
                present.push(name);
            }
        }
        let list_tmp = dir.join(format!("{RESTORE_LIST}.tmp"));
        std::fs::write(&list_tmp, present.join("\n"))?;
        std::fs::rename(list_tmp, dir.join(RESTORE_LIST))?;
        Ok(Self(dir))
    }
}

impl Drop for RestorePoint {
    fn drop(&mut self) {
        let _ = std::fs::remove_dir_all(&self.0);
    }
}

fn file_name(path: &Path) -> String {
    path.file_name()
        .unwrap_or_default()
        .to_string_lossy()
        .into_owned()
}

/// Puts the files of an interrupted round back from its copy, and says so. Caller holds the
/// recording lock.
fn put_back_locked(crate_dir: &Path) -> Result<Option<String>> {
    let dir = restore_dir(crate_dir);
    if !dir.exists() {
        return Ok(None);
    }
    let Ok(list) = std::fs::read_to_string(dir.join(RESTORE_LIST)) else {
        // The copy was still being made, so the recording was not touched yet.
        std::fs::remove_dir_all(&dir)?;
        return Ok(None);
    };
    for path in round_files(crate_dir) {
        let name = file_name(&path);
        if list.lines().any(|l| l == name) {
            std::fs::copy(dir.join(&name), &path)?;
        } else {
            match std::fs::remove_file(&path) {
                Ok(()) => {}
                Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
                Err(e) => return Err(e.into()),
            }
        }
    }
    std::fs::remove_dir_all(&dir)?;
    Ok(Some(format!(
        "restored {CASES} and its lists from the copy an interrupted `fuzz` or `held-out` left in {}",
        dir.display()
    )))
}

/// Puts back what an interrupted `fuzz` or `held-out` left in the recording. Does nothing while
/// a run holds the recording lock (a live run is not interrupted). Called by every command that
/// reads the recording before it reads it.
pub fn recover_interrupted(crate_dir: &Path) -> Result<Option<String>> {
    if !restore_dir(crate_dir).exists() {
        return Ok(None);
    }
    let Some(_lock) = RecordingLock::try_take(crate_dir)? else {
        return Ok(None);
    };
    put_back_locked(crate_dir)
}

/// Removes the driver's scratch files (the inputs it was given, what it recorded so far, the
/// diff it wrote) when dropped, also on an error, so inputs the recording does not hold are not
/// left in `.rust-anything/`. Each run writes them again, and nothing reads them in between.
struct Leftovers(Vec<PathBuf>);

impl Leftovers {
    fn of(crate_dir: &Path) -> Self {
        let work = crate_dir.join(WORK_DIR);
        Self(
            [
                "record-inputs.json",
                "record-part.jsonl",
                "record-progress",
                "record-stderr",
                "diff.json",
            ]
            .iter()
            .map(|name| work.join(name))
            .collect(),
        )
    }
}

impl Drop for Leftovers {
    fn drop(&mut self) {
        for path in &self.0 {
            let _ = std::fs::remove_file(path);
        }
    }
}

/// An exclusive lock on one crate's recording for as long as it lives. `fuzz` and `held_out`
/// put their cases into `cases.jsonl` and put the recording back, and `record` replaces it, so
/// none of them may overlap another, nor a command that reads the recording more than once
/// (`diff`, `bench`, `gate`, `report`): it would see a round's temporary cases, or a recording
/// put back over a newer one. The MCP server runs each call on its own thread, so the lock is a
/// file lock; a thread that already holds it takes it again at no cost, so `gate` can hold it
/// across its checks and still call `diff` and `held_out`.
pub struct RecordingLock(Option<(std::fs::File, PathBuf)>);

thread_local! {
    static HELD: std::cell::RefCell<Vec<PathBuf>> = const { std::cell::RefCell::new(Vec::new()) };
}

fn lock_file(crate_dir: &Path) -> Result<PathBuf> {
    let work = crate_dir.join(WORK_DIR);
    std::fs::create_dir_all(&work)?;
    Ok(work.canonicalize()?.join("recording.lock"))
}

fn held_here(path: &Path) -> bool {
    HELD.with(|held| held.borrow().iter().any(|p| p == path))
}

fn open_lock(path: &Path) -> Result<std::fs::File> {
    Ok(std::fs::OpenOptions::new()
        .create(true)
        .truncate(false)
        .write(true)
        .open(path)?)
}

impl RecordingLock {
    /// Waits for the lock on `crate_dir`'s recording. A folder that is no bridged crate has no
    /// recording to hold, and nothing is written in it.
    pub fn take(crate_dir: &Path) -> Result<Self> {
        if !crate_dir.join(crate::bridge::MANIFEST).is_file() {
            return Ok(Self(None));
        }
        let path = lock_file(crate_dir)?;
        if held_here(&path) {
            return Ok(Self(None));
        }
        let file = open_lock(&path)?;
        loop {
            match file.try_lock() {
                Ok(()) => break,
                Err(std::fs::TryLockError::WouldBlock) if crate::mcp::cancelled() => {
                    bail!("the wait for the recording lock was stopped: the call was cancelled")
                }
                Err(std::fs::TryLockError::WouldBlock) => {
                    std::thread::sleep(Duration::from_millis(50))
                }
                Err(std::fs::TryLockError::Error(e)) => return Err(e.into()),
            }
        }
        HELD.with(|held| held.borrow_mut().push(path.clone()));
        Ok(Self(Some((file, path))))
    }

    /// [`RecordingLock::take`], then puts back what an interrupted `fuzz` or `held-out` left in
    /// the recording, unless this thread already held the lock (its own run is not interrupted).
    pub fn take_recovered(crate_dir: &Path) -> Result<Self> {
        let lock = Self::take(crate_dir)?;
        if lock.0.is_some() && crate::mcp::cancelled() {
            bail!("the recording was left as it was: the call was cancelled");
        }
        if lock.0.is_some()
            && let Some(msg) = put_back_locked(crate_dir)?
        {
            eprintln!("{msg}");
        }
        Ok(lock)
    }

    /// [`RecordingLock::take`] without waiting: `None` when another run holds the lock, this
    /// thread's own included.
    fn try_take(crate_dir: &Path) -> Result<Option<Self>> {
        let path = lock_file(crate_dir)?;
        if held_here(&path) {
            return Ok(None);
        }
        let file = open_lock(&path)?;
        match file.try_lock() {
            Ok(()) => {
                HELD.with(|held| held.borrow_mut().push(path.clone()));
                Ok(Some(Self(Some((file, path)))))
            }
            Err(std::fs::TryLockError::WouldBlock) => Ok(None),
            Err(std::fs::TryLockError::Error(e)) => Err(e.into()),
        }
    }
}

impl Drop for RecordingLock {
    fn drop(&mut self) {
        if let Some((file, path)) = self.0.take() {
            HELD.with(|held| held.borrow_mut().retain(|p| *p != path));
            let _ = file.unlock();
        }
    }
}

fn splitmix(mut x: u64) -> u64 {
    x = x.wrapping_add(0x9E37_79B9_7F4A_7C15);
    x = (x ^ (x >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
    x = (x ^ (x >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
    x ^ (x >> 31)
}

fn random_seed() -> u64 {
    let nanos = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map_or(0, |d| d.as_nanos());
    splitmix((nanos as u64) ^ u64::from(std::process::id())) % 1_000_000_000
}

/// Numbers compared by value and object keys sorted, so the same value from two runtimes (`1`
/// and `1.0`, or the keys of one object in a different order) is one key.
fn norm(v: &Value) -> Value {
    match v {
        Value::Number(n) => n
            .as_f64()
            .and_then(serde_json::Number::from_f64)
            .map_or_else(|| v.clone(), Value::Number),
        Value::Array(a) => Value::Array(a.iter().map(norm).collect()),
        Value::Object(o) => Value::Object(
            o.iter()
                .map(|(k, x)| (k.clone(), norm(x)))
                .collect::<BTreeMap<_, _>>()
                .into_iter()
                .collect(),
        ),
        other => other.clone(),
    }
}

fn key(name: &Value, args: &Value) -> String {
    serde_json::to_string(&(norm(name), norm(args))).unwrap_or_default()
}

fn non_empty_kwargs(c: &Value) -> Option<&Value> {
    c.get("kwargs")
        .filter(|k| k.as_object().is_some_and(|o| !o.is_empty()))
}

/// Structural identity used to deduplicate cases in `seen`, keeping positional `args` and
/// `kwargs` separate so calls with different argument styles stay distinct.
fn case_id(c: &Value) -> String {
    if let Some(class) = c.get("class") {
        return serde_json::to_string(&("class", norm(class), norm(&c["ctor"]), norm(&c["calls"])))
            .unwrap_or_default();
    }
    serde_json::to_string(&(
        "fn",
        norm(&c["fn"]),
        norm(&c["args"]),
        non_empty_kwargs(c).map(norm),
    ))
    .unwrap_or_default()
}

/// The key a case is reported under by the language drivers' mismatches: the function and its
/// arguments (with non-empty keyword arguments appended, as Python and Ruby show them), or the
/// class with its constructor arguments and calls.
fn case_keys(c: &Value) -> Vec<String> {
    if let Some(class) = c.get("class") {
        return vec![key(
            class,
            &Value::Array(vec![c["ctor"].clone(), c["calls"].clone()]),
        )];
    }
    if let (Some(args), Some(kwargs)) = (c["args"].as_array(), non_empty_kwargs(c)) {
        let mut shown = args.clone();
        shown.push(kwargs.clone());
        return vec![key(&c["fn"], &Value::Array(shown))];
    }
    vec![key(&c["fn"], &c["args"])]
}

fn lines(text: &str) -> impl Iterator<Item = (&str, Value)> {
    text.lines()
        .filter(|l| !l.trim().is_empty())
        .filter_map(|l| harness::parse_deep(l).ok().map(|v| (l, v)))
}

/// The options `record_with` and `diff_exact` take for a round of `count` cases per function.
fn drivers<'a>(
    crate_dir: &'a Path,
    count: usize,
    resolve_from: Option<&'a Path>,
    node_args: &'a [String],
    sandbox: bool,
) -> (RecordOptions<'a>, DiffOptions<'a>) {
    (
        RecordOptions {
            crate_dir,
            count,
            inputs: None,
            module: None,
            resolve_from,
            node_args,
            sandbox,
        },
        DiffOptions {
            crate_dir,
            module: None,
            ignore_key_order: false,
            node_args,
            float_tolerance: None,
        },
    )
}

/// Records `cases` with the original (into `cases.jsonl`, which the caller restores) and diffs
/// them against the port. Returns what was recorded, and the diff.
///
/// When not one of the inputs could be recorded (the original timed out on all of them, or the
/// driver dropped them), the returned recording is empty and nothing is diffed: the caller says
/// what that means for its run, since an empty diff reads as "0 of 0 match", a pass.
fn record_and_diff(
    record_opts: &RecordOptions,
    diff_opts: &DiffOptions,
    manifest: &Manifest,
    cases: &[Value],
) -> Result<(String, harness::DiffOutcome)> {
    let _leftovers = Leftovers::of(record_opts.crate_dir);
    harness::record_with(record_opts, manifest, cases)?;
    let recording = record_opts.crate_dir.join(CASES);
    let ran = std::fs::read_to_string(&recording).unwrap_or_default();
    if lines(&ran).next().is_none() {
        return Ok((ran, harness::DiffOutcome::default()));
    }
    // A port that loops on an input the recording never had must fail the check, not hang it.
    // `RUST_ANYTHING_COMMAND_TIMEOUT` replaces the default, as for every outside program.
    let limit = crate::process::limit(harness::case_timeout() * 12);
    let exact = harness::diff_exact_within(diff_opts, Some(limit)).with_context(|| {
        format!(
            "running the port on {} inputs not in the recording (a port that loops on one is \
             stopped after {}s)",
            cases.len(),
            limit.as_secs()
        )
    })?;
    let d = harness::settle(diff_opts, exact)?;
    Ok((ran, d))
}

/// The error for a held-out run that generated inputs and recorded none.
fn nothing_recorded(crate_dir: &Path, generated: usize, seed: u64) -> anyhow::Error {
    let timed_out = std::fs::read_to_string(crate_dir.join(WORK_DIR).join(harness::TIMED_OUT))
        .ok()
        .and_then(|t| serde_json::from_str::<Vec<Value>>(&t).ok())
        .map_or(0, |t| t.len());
    let dropped = harness::last_dropped(crate_dir);
    anyhow::anyhow!(
        "{generated} input{} generated, and none could be recorded ({timed_out} timed out in the \
         original, {dropped} could not be recorded: its result could not be encoded, or it ended \
         the run): nothing was compared, so this is not a pass (seed {seed}, replay with \
         --held-out-seed {seed}). Raise RUST_ANYTHING_CASE_TIMEOUT (seconds), or check that the \
         original runs",
        if generated == 1 { " was" } else { "s were" },
    )
}

pub fn fuzz(opts: &FuzzOptions) -> Result<FuzzOutcome> {
    let crate_dir = std::path::absolute(opts.crate_dir)?;
    let manifest = Manifest::load(&crate_dir)?;
    crate::harness::ensure_built(&crate_dir, &manifest)?;
    if opts.cases == 0 {
        bail!("`--cases` must be at least 1");
    }
    if opts.sandbox {
        crate::process::sandbox_tool()?;
    }
    let _lock = RecordingLock::take_recovered(&crate_dir)?;
    let _point = RestorePoint::save(&crate_dir)?;
    let seed = opts.seed.unwrap_or_else(random_seed);
    let recording = crate_dir.join(CASES);
    let original = std::fs::read_to_string(&recording).unwrap_or_default();
    let recorded: Vec<Value> = lines(&original).map(|(_, c)| c).collect();
    let mut seen: HashSet<String> = recorded.iter().map(case_id).collect();
    let (record_opts, diff_opts) = drivers(
        &crate_dir,
        opts.cases,
        opts.resolve_from,
        opts.node_args,
        opts.sandbox,
    );
    let mut outcome = FuzzOutcome {
        seed,
        rounds: 0,
        cases: 0,
        passed: 0,
        failed: 0,
        missing: Vec::new(),
        mismatches: Vec::new(),
        kept: 0,
        recording: recording.clone(),
        dropped: 0,
    };
    let mut keep = String::new();
    let mut empty_rounds = 0;
    let mut unrecorded = 0;
    let started = Instant::now();
    let rounds = {
        let _restore = Restore::new(&round_files(&crate_dir));
        (|| -> Result<()> {
            loop {
                if crate::mcp::cancelled() {
                    bail!("fuzz was stopped: the call was cancelled");
                }
                let round_seed = seed.wrapping_add(outcome.rounds);
                outcome.rounds += 1;
                let generated = match opts.generator {
                    Some(command) => {
                        from_generator(command, &record_opts, &manifest, round_seed, opts.cases)?
                    }
                    None => {
                        let salt = splitmix(round_seed) | 0x100;
                        harness::generate_cases_salted(&record_opts, &manifest, salt, &recorded)?
                            .cases
                    }
                };
                let fresh: Vec<Value> = generated
                    .into_iter()
                    .filter(|c| seen.insert(case_id(c)))
                    .collect();
                if fresh.is_empty() {
                    // This round's seed made nothing new. With a time budget the next round has
                    // another seed; a generator that stays exhausted is given up on.
                    empty_rounds += 1;
                    let more = opts.time.is_some_and(|budget| started.elapsed() < budget);
                    if more && empty_rounds < 1000 {
                        continue;
                    }
                    break;
                }
                let (ran, d) = record_and_diff(&record_opts, &diff_opts, &manifest, &fresh)?;
                if lines(&ran).next().is_none() {
                    // Nothing of this round could be recorded: keep what earlier rounds found, and
                    // let the check after the loop say so if no round compared anything.
                    unrecorded += fresh.len();
                }
                outcome.dropped += harness::last_dropped(&crate_dir);
                outcome.cases += d.total;
                outcome.passed += d.passed;
                outcome.failed += d.failed;
                for m in &d.missing {
                    if !outcome.missing.contains(m) {
                        outcome.missing.push(m.clone());
                    }
                }
                let failing: HashSet<String> = d
                    .mismatches
                    .iter()
                    .map(|m| key(&m["fn"], &m["args"]))
                    .collect();
                for (line, c) in lines(&ran) {
                    let wanted = match opts.keep {
                        Some(Keep::All) => true,
                        Some(Keep::Mismatches) => case_keys(&c).iter().any(|k| failing.contains(k)),
                        None => false,
                    };
                    if wanted {
                        keep.push_str(line);
                        keep.push('\n');
                        outcome.kept += 1;
                    }
                }
                let room = SHOWN.saturating_sub(outcome.mismatches.len());
                outcome
                    .mismatches
                    .extend(d.mismatches.into_iter().take(room));
                if opts.time.is_none_or(|budget| started.elapsed() >= budget) {
                    break;
                }
            }
            Ok(())
        })()
    };
    let _ = std::fs::remove_dir_all(crate_dir.join(WORK_DIR).join("coverage"));
    if let Err(e) = rounds {
        if outcome.kept == 0 {
            return Err(e);
        }
        append_kept(&recording, original, &keep, harness::unicode_env())?;
        return Err(e.context(format!(
            "round {} failed; the {} case{} kept from the rounds before it {} appended to {}",
            outcome.rounds,
            outcome.kept,
            if outcome.kept == 1 { "" } else { "s" },
            if outcome.kept == 1 { "was" } else { "were" },
            CASES,
        )));
    }
    // Inputs were generated but none could be recorded and compared: nothing was verified, and
    // that is a failure of the run, not "nothing new to try" (which `main` reports as such).
    if outcome.cases == 0 && (outcome.dropped > 0 || unrecorded > 0) {
        let n = outcome.dropped.max(unrecorded);
        bail!(
            "no fresh cases were compared: {n} generated input{} could not be recorded (the \
             original timed out, its result could not be encoded, or it ended the run). Check \
             the original on those inputs, raise RUST_ANYTHING_CASE_TIMEOUT, or try another \
             --seed",
            if n == 1 { "" } else { "s" },
        );
    }
    append_kept(&recording, original, &keep, harness::unicode_env())?;
    Ok(outcome)
}

/// Runs `fuzz --generator`'s command for one round and reads its output as `record --inputs`
/// reads a file. Its output goes to a file, not a pipe: a pipe keeps only the last MiB.
fn from_generator(
    command: &str,
    record_opts: &RecordOptions,
    manifest: &Manifest,
    seed: u64,
    cases: usize,
) -> Result<Vec<Value>> {
    let words = crate::app::shell_split(command)?;
    let Some((program, args)) = words.split_first() else {
        bail!("`--generator` is empty: give the command that prints the inputs");
    };
    let work = record_opts.crate_dir.join(WORK_DIR);
    let (out_path, err_path) = (work.join("generator-out"), work.join("generator-err"));
    let _leftovers = Leftovers(vec![out_path.clone(), err_path.clone()]);
    let mut cmd = std::process::Command::new(program);
    cmd.args(args)
        .env("RUST_ANYTHING_SEED", seed.to_string())
        .env("RUST_ANYTHING_CASES", cases.to_string())
        .stdout(std::fs::File::create(&out_path)?)
        .stderr(std::fs::File::create(&err_path)?);
    let status = crate::process::status(&mut cmd, crate::process::QUICK)
        .with_context(|| format!("running the generator `{command}`"))?;
    if !status.success() {
        let stderr = std::fs::read_to_string(&err_path).unwrap_or_default();
        let said = match stderr.trim() {
            "" => String::new(),
            text => format!(": {text}"),
        };
        bail!("the generator `{command}` failed ({status}) with seed {seed}{said}");
    }
    let text = std::fs::read_to_string(&out_path)
        .with_context(|| format!("the generator `{command}` printed text that is not UTF-8"))?;
    let inputs = harness::parse_inputs(record_opts, manifest, &text, |n| {
        format!("line {n} of the generator `{command}` (seed {seed})")
    })?;
    if inputs.is_empty() {
        bail!("the generator `{command}` printed no inputs with seed {seed}");
    }
    Ok(inputs)
}

/// Why `gate` does not run the held-out check for this unit, `None` when it does. `fuzz` drives
/// every language's record and diff drivers, and `gate` runs this check only on the paths run end
/// to end against a real port (`tests/fuzz.rs`, `tests/held_out.rs`): TypeScript/JavaScript napi
/// and Python PyO3. A check that fails a gate on a path nobody has run would block ports for the
/// wrong reason, so the others skip and say so.
pub fn unsupported(language: crate::lang::Lang, kind: crate::bridge::Kind) -> Option<String> {
    use crate::bridge::Kind;
    use crate::lang::Lang;
    if matches!(
        (language, kind),
        (Lang::Ts, Kind::Napi) | (Lang::Python, Kind::Pyo3)
    ) {
        return None;
    }
    Some(format!(
        "fuzz is only tested for TypeScript/JavaScript napi and Python PyO3 ports, and this one is \
         {} ({}); the recorded cases are the only inputs checked",
        language.name(),
        kind.label(),
    ))
}

pub struct HeldOutOptions<'a> {
    pub crate_dir: &'a Path,
    /// Fresh inputs per function (and scenarios per class), and perturbed ones per function.
    pub cases: usize,
    /// Random (from the clock) when `None`.
    pub seed: Option<u64>,
    pub node_args: &'a [String],
}

#[derive(Debug, Serialize)]
pub struct HeldOutOutcome {
    /// `fuzz --seed` replays the fresh half of this run.
    pub seed: u64,
    /// Fresh inputs recorded on the original and run on both sides.
    pub fresh: usize,
    pub fresh_failed: usize,
    /// Recorded arguments with one change, run on both sides.
    pub perturbed: usize,
    pub perturbed_failed: usize,
    /// Exports the port does not provide.
    pub missing: Vec<String>,
    /// Inputs whose difference `known-diffs.jsonl` explains: not in `fresh_failed` or
    /// `perturbed_failed`.
    pub accepted: usize,
    /// The `known-diffs.jsonl` entries that explained one of these inputs, as `stale_known` lists
    /// them.
    pub used_known: Vec<Value>,
    /// Every mismatch, the one with the shortest arguments first.
    pub mismatches: Vec<Value>,
    /// Inputs left out because an argument does not fit its parameter's declared type (a
    /// non-array for an array parameter): a call outside the signature, not one the port owes.
    pub ill_typed: usize,
}

impl HeldOutOutcome {
    pub fn total(&self) -> usize {
        self.fresh + self.perturbed
    }

    pub fn failed(&self) -> usize {
        self.fresh_failed + self.perturbed_failed
    }
}

/// A small seeded source of choices.
struct Pick(u64);

impl Pick {
    fn below(&mut self, n: usize) -> usize {
        self.0 = splitmix(self.0);
        (self.0 % n.max(1) as u64) as usize
    }
}

/// The original string with one character replaced by another, or `"a"` for an empty one.
fn change_char(s: &str, pick: &mut Pick) -> Option<String> {
    let mut chars: Vec<char> = s.chars().collect();
    if chars.is_empty() {
        return Some("a".into());
    }
    let at = pick.below(chars.len());
    let old = chars[at];
    let toggled = if old.is_ascii_lowercase() {
        old.to_ascii_uppercase()
    } else {
        old.to_ascii_lowercase()
    };
    let pool = [toggled, 'a', 'Z', '0', ' ', '-', '/', '\u{e9}'];
    let options: Vec<char> = pool.into_iter().filter(|c| *c != old).collect();
    chars[at] = options[pick.below(options.len())];
    Some(chars.into_iter().collect())
}

/// An integer with its sign flipped; zero becomes 1.
fn flip_sign(n: &serde_json::Number) -> Option<Value> {
    let i = n.as_i64()?;
    Some(Value::from(if i == 0 { 1 } else { i.checked_neg()? }))
}

/// A float with its sign flipped; zero becomes 1.0. An integer recorded for a `float` parameter
/// (a Python caller may pass one) is read as its `f64` value, so the result stays a float.
fn flip_sign_float(n: &serde_json::Number) -> Option<Value> {
    let f = n.as_f64()?;
    serde_json::Number::from_f64(if f == 0.0 { 1.0 } else { -f }).map(Value::Number)
}

/// One change to a list: two different items swapped, one element removed, one element added
/// (a copy of another, so it has the list's type), or one element perturbed.
fn change_list(items: &[Value], inner: &RType, pick: &mut Pick) -> Option<Value> {
    for _ in 0..8 {
        let mut out = items.to_vec();
        let changed = match pick.below(4) {
            0 if items.len() >= 2 => {
                let (i, j) = (pick.below(items.len()), pick.below(items.len()));
                let differ = i != j && norm(&items[i]) != norm(&items[j]);
                if differ {
                    out.swap(i, j);
                }
                differ
            }
            1 if !items.is_empty() => {
                out.remove(pick.below(items.len()));
                true
            }
            2 if !items.is_empty() => {
                let copy = items[pick.below(items.len())].clone();
                out.insert(pick.below(items.len() + 1), copy);
                true
            }
            3 if !items.is_empty() => {
                let i = pick.below(items.len());
                perturb_value(&items[i], inner, pick).is_some_and(|v| {
                    out[i] = v;
                    true
                })
            }
            _ => false,
        };
        if changed {
            return Some(Value::Array(out));
        }
    }
    None
}

/// Whether `v` is one of the record codec's markers (`{"$undefined": true}`, `{"$num": "NaN"}`,
/// `{"$utf16": [..]}`): the key it carries says which kind of value it stands for.
fn marker(v: &Value) -> Option<&str> {
    let o = v.as_object().filter(|o| o.len() == 1)?;
    o.keys().next().and_then(|k| k.strip_prefix('$'))
}

/// Whether `v` is a value of the TypeScript type `shape`, as far as the type says. A type this
/// module does not model (`unknown`, a library type, a name not in scope) accepts anything: only
/// what the signature rules out is ruled out. Deeper than a few levels nothing is judged.
fn conforms(v: &Value, shape: &Shape, types: &[LocalType], depth: usize) -> bool {
    if depth > 8 {
        return true;
    }
    let undefined = marker(v) == Some("undefined");
    let next = depth + 1;
    match shape {
        Shape::Any | Shape::Bytes | Shape::Path => true,
        Shape::Union(items) => {
            items.is_empty() || items.iter().any(|i| conforms(v, i, types, next))
        }
        Shape::Ref(name, args) => match shape::resolve(name, args, types) {
            Shape::Any => true,
            resolved => conforms(v, &resolved, types, next),
        },
        Shape::Undefined => undefined,
        Shape::Null => v.is_null(),
        _ if undefined => false,
        Shape::Str => v.is_string() || marker(v) == Some("utf16"),
        Shape::Num | Shape::Int => v.is_number() || marker(v) == Some("num"),
        Shape::Bool => v.is_boolean(),
        Shape::LitStr(text) => v.as_str() == Some(text.as_str()),
        Shape::LitNum(n) => v.as_f64() == Some(*n),
        Shape::LitBool(b) => v.as_bool() == Some(*b),
        Shape::Array(item) => v
            .as_array()
            .is_some_and(|a| a.iter().all(|x| conforms(x, item, types, next))),
        Shape::Tuple(items) => v.as_array().is_some_and(|a| {
            a.iter()
                .zip(items)
                .all(|(x, i)| conforms(x, i, types, next))
        }),
        Shape::Object(props, index) => {
            let Some(o) = v.as_object().filter(|_| marker(v).is_none()) else {
                return false;
            };
            let absent = serde_json::json!({ "$undefined": true });
            props
                .iter()
                .all(|(name, optional, prop)| match o.get(name) {
                    Some(x) => conforms(x, prop, types, next),
                    None => *optional || conforms(&absent, prop, types, next),
                })
                && index.as_ref().is_none_or(|item| {
                    o.iter()
                        .filter(|(k, _)| !props.iter().any(|(name, _, _)| name == *k))
                        .all(|(_, x)| conforms(x, item, types, next))
                })
        }
    }
}

/// Whether every argument is a value of its parameter's declared type. A rest parameter and
/// arguments beyond the declared ones are not judged; an optional parameter also takes `null`
/// and `undefined`.
fn call_conforms(args: &[Value], params: &[Param], types: &[LocalType]) -> bool {
    args.iter().zip(params).all(|(a, p)| {
        p.rest
            || (p.optional && (a.is_null() || marker(a) == Some("undefined")))
            || conforms(a, &shape::parse(&p.ts_type), types, 0)
    })
}

/// The declared parameters of each export, with the types of its file in scope, to tell a call
/// the signature allows from one it does not.
struct Signatures(HashMap<String, (Vec<Param>, Vec<LocalType>)>);

impl Signatures {
    fn of(manifest: &Manifest) -> Self {
        let mut types: HashMap<&str, Vec<LocalType>> = HashMap::new();
        let mut by_fn = HashMap::new();
        for f in &manifest.exports {
            let in_scope = types.entry(f.file.as_str()).or_insert_with(|| {
                let text = std::fs::read_to_string(manifest.root.join(&f.file)).unwrap_or_default();
                crate::bridge::types_in_scope(&manifest.root, &f.file, &text)
            });
            by_fn.insert(f.name.clone(), (f.params.clone(), in_scope.clone()));
        }
        Self(by_fn)
    }

    /// Whether a call to `name` with `args` is within its signature. A function this does not
    /// know is not judged.
    fn allows(&self, name: &str, args: &[Value]) -> bool {
        self.0
            .get(name)
            .is_none_or(|(params, types)| call_conforms(args, params, types))
    }

    /// Whether each keyword argument of a call to `name` is within the parameter of the same
    /// name. A function or a name this does not know is not judged.
    fn allows_kwargs(&self, name: &str, kwargs: Option<&Value>) -> bool {
        let Some(kwargs) = kwargs.and_then(Value::as_object) else {
            return true;
        };
        self.0.get(name).is_none_or(|(params, types)| {
            kwargs.iter().all(|(key, value)| {
                params.iter().find(|p| &p.name == key).is_none_or(|p| {
                    call_conforms(std::slice::from_ref(value), std::slice::from_ref(p), types)
                })
            })
        })
    }

    /// [`Self::allows`] for a generated case; class scenarios are not judged.
    fn allows_case(&self, case: &Value) -> bool {
        match (case["fn"].as_str(), case["args"].as_array()) {
            (Some(name), Some(args)) => self.allows(name, args),
            _ => true,
        }
    }
}

/// One change to a value of type `ty`, or `None` when it cannot be changed without leaving the
/// type (structured values, byte buffers, encoded `NaN` or `undefined`): changing a value's
/// content is a held-out input, changing its type is a different function call.
fn perturb_value(v: &Value, ty: &RType, pick: &mut Pick) -> Option<Value> {
    match (ty, v) {
        (RType::Opt(inner), _) if !v.is_null() => perturb_value(v, inner, pick),
        (RType::Str, Value::String(s)) => change_char(s, pick).map(Value::String),
        (RType::Int, Value::Number(n)) => flip_sign(n),
        (RType::F64, Value::Number(n)) => flip_sign_float(n),
        (RType::Bool, Value::Bool(b)) => Some(Value::Bool(!b)),
        (RType::Vec(inner), Value::Array(items)) if plain(inner) => change_list(items, inner, pick),
        _ => None,
    }
}

/// Whether a list of `ty` is made of values `perturb_value` understands (strings, numbers,
/// booleans, and lists or optionals of those): adding or removing an element of a structured
/// type would be a change to a value this check does not know the shape of.
fn plain(ty: &RType) -> bool {
    match ty {
        RType::Str | RType::F64 | RType::Int | RType::Bool => true,
        RType::Opt(inner) | RType::Vec(inner) => plain(inner),
        _ => false,
    }
}

/// `args` with one argument changed, trying each argument from a random one on.
fn perturb_args(
    args: &[Value],
    params: &[crate::ts::exports::Param],
    pick: &mut Pick,
) -> Option<Vec<Value>> {
    let start = pick.below(args.len());
    (0..args.len()).find_map(|k| {
        let i = (start + k) % args.len();
        // A type with a string literal in it (`"fast" | "safe"`, a template literal) is a
        // smaller set than `string`: changing a character would leave it.
        let p = params
            .get(i)
            .filter(|p| !p.rest && !p.ts_type.contains(['\'', '"', '`']))?;
        let changed = perturb_value(&args[i], &crate::bridge::param_type(p), pick)?;
        let mut out = args.to_vec();
        out[i] = changed;
        Some(out)
    })
}

/// Up to `per_function` new cases for each function, each a recorded call with one positional
/// argument changed, or a keyword argument when no positional argument can change. Other
/// bindings are kept as recorded. Keys already in `seen` (recorded, or generated fresh) are left out.
fn perturbed_cases(
    recorded: &str,
    manifest: &Manifest,
    signatures: &Signatures,
    per_function: usize,
    seed: u64,
    seen: &mut HashSet<String>,
) -> Vec<Value> {
    let mut pick = Pick(splitmix(seed ^ 0x005E_ED0F_C0DE));
    let mut cases = Vec::new();
    for f in &manifest.exports {
        let calls: Vec<Value> = lines(recorded)
            .filter(|(_, c)| c["fn"].as_str() == Some(f.name.as_str()))
            .filter(|(_, c)| {
                c["args"].as_array().is_some_and(|a| {
                    (!a.is_empty() || non_empty_kwargs(c).is_some())
                        && signatures.allows(&f.name, a)
                        && signatures.allows_kwargs(&f.name, non_empty_kwargs(c))
                })
            })
            .map(|(_, c)| c)
            .collect();
        if calls.is_empty() {
            continue;
        }
        let module = manifest.root.join(&f.file).to_string_lossy().into_owned();
        let mut made = 0;
        for _ in 0..per_function.saturating_mul(8) {
            if made == per_function {
                break;
            }
            let base = &calls[pick.below(calls.len())];
            let Some(args) = base["args"].as_array() else {
                continue;
            };
            let mut kwargs = non_empty_kwargs(base).cloned();
            let perturbed = perturb_args(args, &f.params, &mut pick).or_else(|| {
                let kwargs = kwargs.as_mut()?.as_object_mut()?;
                let params: Vec<_> = f
                    .params
                    .iter()
                    .filter(|p| kwargs.contains_key(&p.name))
                    .cloned()
                    .collect();
                let values: Vec<_> = params.iter().map(|p| kwargs[&p.name].clone()).collect();
                let changed = perturb_args(&values, &params, &mut pick)?;
                for (p, value) in params.iter().zip(changed) {
                    kwargs.insert(p.name.clone(), value);
                }
                Some(args.clone())
            });
            let Some(perturbed) = perturbed else {
                continue;
            };
            let mut case = serde_json::json!({ "fn": f.name, "module": module, "args": perturbed });
            if let Some(kwargs) = kwargs {
                case["kwargs"] = kwargs;
            }
            if seen.insert(case_id(&case)) {
                cases.push(case);
                made += 1;
            }
        }
    }
    cases
}

/// Inputs the recording does not hold, run through the original and the port: fresh ones from a
/// new seed (what `fuzz` generates) and recorded arguments with one change each (a character, two
/// list items swapped, a sign, an element added or removed). A port that memorised or
/// approximated the recorded cases passes `diff`; it cannot pass these.
///
/// `cases.jsonl` is put back as it was, and nothing is kept.
pub fn held_out(opts: &HeldOutOptions) -> Result<HeldOutOutcome> {
    let crate_dir = std::path::absolute(opts.crate_dir)?;
    let manifest = Manifest::load(&crate_dir)?;
    harness::ensure_built(&crate_dir, &manifest)?;
    anyhow::ensure!(opts.cases > 0, "held-out cases must be at least 1");
    let _lock = RecordingLock::take_recovered(&crate_dir)?;
    let _point = RestorePoint::save(&crate_dir)?;
    let seed = opts.seed.unwrap_or_else(random_seed);
    let recording = crate_dir.join(CASES);
    let original = std::fs::read_to_string(&recording).unwrap_or_default();
    let mut seen: HashSet<String> = lines(&original).map(|(_, c)| case_id(&c)).collect();
    let (record_opts, diff_opts) = drivers(&crate_dir, opts.cases, None, opts.node_args, false);
    let mut outcome = HeldOutOutcome {
        seed,
        fresh: 0,
        fresh_failed: 0,
        perturbed: 0,
        perturbed_failed: 0,
        missing: Vec::new(),
        accepted: 0,
        used_known: Vec::new(),
        mismatches: Vec::new(),
        ill_typed: 0,
    };
    // The same salt as the first round of `fuzz --seed`, so the fresh half replays with it.
    let salt = splitmix(seed) | 0x100;
    let recorded: Vec<Value> = lines(&original).map(|(_, c)| c).collect();
    let generated = harness::generate_cases_salted(&record_opts, &manifest, salt, &recorded)?;
    let signatures = Signatures::of(&manifest);
    let mut fresh_ids = HashSet::new();
    let mut cases: Vec<Value> = generated
        .cases
        .into_iter()
        .filter(|c| {
            let fits = signatures.allows_case(c);
            outcome.ill_typed += usize::from(!fits);
            fits
        })
        .filter(|c| {
            let id = case_id(c);
            let new = seen.insert(id.clone());
            if new {
                fresh_ids.insert(id);
            }
            new
        })
        .collect();
    cases.extend(perturbed_cases(
        &original,
        &manifest,
        &signatures,
        opts.cases,
        seed,
        &mut seen,
    ));
    if cases.is_empty() {
        return Ok(outcome);
    }
    let ran;
    let d;
    {
        let _restore = Restore::new(&round_files(&crate_dir));
        (ran, d) = record_and_diff(&record_opts, &diff_opts, &manifest, &cases)?;
        if lines(&ran).next().is_none() {
            return Err(nothing_recorded(&crate_dir, cases.len(), seed));
        }
    }
    let _ = std::fs::remove_dir_all(crate_dir.join(WORK_DIR).join("coverage"));
    let failing: HashSet<String> = d
        .mismatches
        .iter()
        .map(|m| key(&m["fn"], &m["args"]))
        .collect();
    for (_, c) in lines(&ran) {
        let failed = case_keys(&c).iter().any(|k| failing.contains(k));
        if fresh_ids.contains(&case_id(&c)) {
            outcome.fresh += 1;
            outcome.fresh_failed += usize::from(failed);
        } else {
            outcome.perturbed += 1;
            outcome.perturbed_failed += usize::from(failed);
        }
    }
    outcome.missing = d.missing;
    outcome.accepted = d.accepted;
    if d.accepted > 0 {
        outcome.used_known = crate::recording::known_diffs(&crate_dir)?
            .iter()
            .map(crate::recording::listed)
            .filter(|e| !d.stale_known.contains(e))
            .collect();
    }
    outcome.mismatches = d.mismatches;
    outcome
        .mismatches
        .sort_by_key(|m| serde_json::to_string(&m["args"]).map_or(usize::MAX, |a| a.len()));
    Ok(outcome)
}

/// Appends kept fuzz cases to `recording`, refusing before writing if any kept case holds the
/// value of a secret-looking environment variable. Existing cases in `recording` stay untouched.
fn append_kept(
    recording: &Path,
    original: String,
    keep: &str,
    environment: impl IntoIterator<Item = (String, String)>,
) -> Result<()> {
    if keep.is_empty() {
        return Ok(());
    }
    let found = harness::recorded_secrets(keep, environment);
    if !found.is_empty() {
        let listed: Vec<String> = found
            .iter()
            .map(|(name, functions)| format!("{name} (in {})", functions.join(", ")))
            .collect();
        bail!(
            "the kept cases held the value of {}, and {} is meant to be committed: nothing was \
             appended. Run `fuzz` without those variables (`env -u NAME rust-anything fuzz ...`), \
             or change the functions or inputs that return them",
            listed.join("; "),
            CASES,
        );
    }
    let mut text = original;
    if !text.is_empty() && !text.ends_with('\n') {
        text.push('\n');
    }
    text.push_str(keep);
    std::fs::write(recording, text)?;
    Ok(())
}

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

    #[test]
    fn mismatches_find_their_cases_across_driver_shapes() {
        let ruby = json!({ "fn": "f", "args": [1, "a"], "kwargs": { "sep": "-" }, "ok": 2 });
        let shown = json!({ "fn": "f", "args": [1.0, "a", { "sep": "-" }] });
        assert!(case_keys(&ruby).contains(&key(&shown["fn"], &shown["args"])));
        let class = json!({ "class": "C", "ctor": [1], "calls": [], "results": [] });
        let reported = json!({ "fn": "C", "args": [[1], []] });
        assert_eq!(
            case_keys(&class),
            vec![key(&reported["fn"], &reported["args"])]
        );
    }

    #[test]
    fn kwargs_cases_with_identical_positional_args_have_distinct_keys() {
        let first = json!({ "fn": "f", "args": [1], "kwargs": { "c": 2 } });
        let second = json!({ "fn": "f", "args": [1], "kwargs": { "c": 3 } });
        let positional_dict = json!({ "fn": "f", "args": [1, { "c": 2 }] });
        let empty = json!({ "fn": "f", "args": [1], "kwargs": {} });
        let absent = json!({ "fn": "f", "args": [1] });

        assert_eq!(
            case_keys(&first),
            vec![key(&json!("f"), &json!([1, { "c": 2 }]))]
        );
        assert_eq!(
            case_keys(&second),
            vec![key(&json!("f"), &json!([1, { "c": 3 }]))]
        );
        assert_ne!(case_keys(&first).first(), case_keys(&second).first());
        assert_ne!(case_keys(&first).first(), case_keys(&absent).first());
        assert_eq!(case_keys(&empty), case_keys(&absent));

        assert_ne!(case_id(&first), case_id(&second));
        assert_ne!(case_id(&first), case_id(&positional_dict));
        assert_ne!(case_id(&first), case_id(&absent));
        assert_eq!(case_id(&empty), case_id(&absent));
    }

    #[test]
    fn a_case_key_ignores_the_order_of_object_keys() {
        // The original and the port are different runtimes: the same value comes back with its
        // keys in a different order, and a case must still match its own report.
        let left = json!({ "fn": "f", "args": [{ "a": 1, "b": [2, { "c": 3, "d": 4 }] }] });
        let right = json!({ "fn": "f", "args": [{ "b": [2, { "d": 4, "c": 3 }], "a": 1 }] });
        assert_eq!(
            key(&left["fn"], &left["args"]),
            key(&right["fn"], &right["args"])
        );
    }

    #[test]
    fn restore_puts_files_back_or_removes_new_ones() {
        let dir =
            std::env::temp_dir().join(format!("rust-anything-restore-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let kept = dir.join("a");
        let fresh = dir.join("b");
        std::fs::write(&kept, "old").unwrap();
        {
            let _r = Restore::new(&[kept.clone(), fresh.clone()]);
            std::fs::write(&kept, "new").unwrap();
            std::fs::write(&fresh, "new").unwrap();
        }
        assert_eq!(std::fs::read_to_string(&kept).unwrap(), "old");
        assert!(!fresh.exists());
        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn incomplete_restore_list_does_not_change_recording() {
        let dir = std::env::temp_dir().join(format!(
            "rust-anything-incomplete-restore-{}",
            std::process::id()
        ));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(restore_dir(&dir)).unwrap();
        let cases = dir.join(CASES);
        let original = b"original recording\n";
        std::fs::write(&cases, original).unwrap();
        // A crash during the temporary list write must not make recovery treat the
        // (not yet published) empty list as a completed snapshot.
        std::fs::write(restore_dir(&dir).join(format!("{RESTORE_LIST}.tmp")), "").unwrap();

        assert!(put_back_locked(&dir).unwrap().is_none());
        assert_eq!(std::fs::read(&cases).unwrap(), original);
        assert!(!restore_dir(&dir).exists());
        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn completed_empty_restore_list_removes_files_created_by_interrupted_round() {
        let dir = std::env::temp_dir().join(format!(
            "rust-anything-empty-restore-{}",
            std::process::id()
        ));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(restore_dir(&dir)).unwrap();
        let cases = dir.join(CASES);
        std::fs::write(&cases, "created by interrupted round\n").unwrap();
        std::fs::write(restore_dir(&dir).join(RESTORE_LIST), "").unwrap();

        assert!(put_back_locked(&dir).unwrap().is_some());
        assert!(!cases.exists());
        assert!(!restore_dir(&dir).exists());
        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn append_kept_refuses_secrets_and_leaves_existing_recording_untouched() {
        let dir =
            std::env::temp_dir().join(format!("rust-anything-fuzz-secret-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        let recording = dir.join(CASES);
        let original = "{\"fn\":\"ok\",\"args\":[1],\"ok\":2}\n";
        std::fs::write(&recording, original).unwrap();

        let canary = "example-secret-canary";
        let kept = format!(
            "{{\"fn\":\"leak\",\"args\":[],\"ok\":\"{canary}\"}}\n\
             {{\"class\":\"Vault\",\"ctor\":[],\"calls\":[],\"results\":[\"{canary}\"]}}\n"
        );
        let env = vec![("MY_API_TOKEN".to_string(), canary.to_string())];
        let err = append_kept(&recording, original.to_string(), &kept, env)
            .unwrap_err()
            .to_string();
        assert!(err.contains("MY_API_TOKEN"), "{err}");
        assert!(err.contains("leak"), "{err}");
        assert!(err.contains("Vault"), "{err}");
        assert!(
            !err.contains(canary),
            "secret value must never appear: {err}"
        );
        assert_eq!(std::fs::read_to_string(&recording).unwrap(), original);

        let clean = "{\"fn\":\"add\",\"args\":[1,2],\"ok\":3}\n";
        append_kept(
            &recording,
            original.trim_end().to_string(),
            clean,
            vec![("MY_API_TOKEN".to_string(), canary.to_string())],
        )
        .unwrap();
        assert_eq!(
            std::fs::read_to_string(&recording).unwrap(),
            format!("{original}{clean}")
        );

        std::fs::remove_dir_all(&dir).unwrap();
    }

    fn param(ty: &str) -> crate::ts::exports::Param {
        crate::ts::exports::Param {
            name: "p".into(),
            ts_type: ty.into(),
            ..Default::default()
        }
    }

    #[test]
    fn two_runs_on_one_crate_do_not_overlap() {
        let dir = std::env::temp_dir().join(format!("rust-anything-lock-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(dir.join(crate::bridge::MANIFEST), "{}").unwrap();
        let first = RecordingLock::take(&dir).unwrap();
        let entered = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
        let waiter = {
            let (dir, entered) = (dir.clone(), entered.clone());
            std::thread::spawn(move || {
                let _second = RecordingLock::take(&dir).unwrap();
                entered.store(true, std::sync::atomic::Ordering::SeqCst);
            })
        };
        std::thread::sleep(Duration::from_millis(300));
        assert!(
            !entered.load(std::sync::atomic::Ordering::SeqCst),
            "the second run waits while the first holds the recording"
        );
        drop(first);
        waiter.join().unwrap();
        assert!(entered.load(std::sync::atomic::Ordering::SeqCst));
        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn a_cancelled_call_stops_waiting_for_the_lock_and_puts_nothing_back() {
        let dir =
            std::env::temp_dir().join(format!("rust-anything-lock-cancel-{}", 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 first = RecordingLock::take(&dir).unwrap();
        let waiter = {
            let dir = dir.clone();
            std::thread::spawn(move || {
                let call = crate::mcp::as_call();
                let cancel = call.canceller();
                std::thread::spawn(move || {
                    std::thread::sleep(Duration::from_millis(200));
                    cancel();
                });
                let taken = RecordingLock::take_recovered(&dir).map(|_| ());
                drop(call);
                taken
            })
        };
        let (done_tx, done_rx) = std::sync::mpsc::channel();
        std::thread::spawn(move || done_tx.send(waiter.join().unwrap()).unwrap());
        let taken = done_rx
            .recv_timeout(Duration::from_secs(5))
            .expect("the cancelled call still waits for the lock");
        assert!(
            taken.unwrap_err().to_string().contains("cancelled"),
            "a cancelled call does not go on with the lock"
        );
        drop(first);
        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn a_folder_that_is_no_crate_gets_no_lock_file() {
        let dir = std::env::temp_dir().join(format!("rust-anything-nolock-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        let _lock = RecordingLock::take_recovered(&dir).unwrap();
        assert!(!dir.exists(), "taking the lock made the folder");
    }

    #[test]
    fn a_thread_that_holds_the_lock_takes_it_again_and_others_still_wait() {
        let dir = std::env::temp_dir().join(format!("rust-anything-relock-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(dir.join(crate::bridge::MANIFEST), "{}").unwrap();
        let outer = RecordingLock::take(&dir).unwrap();
        let inner = RecordingLock::take_recovered(&dir).unwrap();
        assert!(
            RecordingLock::try_take(&dir).unwrap().is_none(),
            "a try from the holding thread does not recover a live run"
        );
        drop(inner);
        let entered = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
        let waiter = {
            let (dir, entered) = (dir.clone(), entered.clone());
            std::thread::spawn(move || {
                let _other = RecordingLock::take(&dir).unwrap();
                entered.store(true, std::sync::atomic::Ordering::SeqCst);
            })
        };
        std::thread::sleep(Duration::from_millis(300));
        assert!(
            !entered.load(std::sync::atomic::Ordering::SeqCst),
            "dropping the inner take keeps the outer one"
        );
        drop(outer);
        waiter.join().unwrap();
        assert!(entered.load(std::sync::atomic::Ordering::SeqCst));
        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn each_perturbation_changes_the_value_and_keeps_its_type() {
        let mut pick = Pick(1);
        for _ in 0..200 {
            let s = perturb_value(&json!("Hello"), &RType::Str, &mut pick).unwrap();
            let s = s.as_str().unwrap();
            assert_ne!(s, "Hello");
            assert_eq!(s.chars().count(), 5, "one character changes: {s}");
            assert_eq!(
                s.chars()
                    .zip("Hello".chars())
                    .filter(|(a, b)| a != b)
                    .count(),
                1
            );
            assert_eq!(
                perturb_value(&json!(7), &RType::F64, &mut pick),
                Some(json!(-7.0))
            );
            assert_eq!(
                perturb_value(&json!(7), &RType::Int, &mut pick),
                Some(json!(-7))
            );
            assert_eq!(
                perturb_value(&json!(-2.5), &RType::F64, &mut pick),
                Some(json!(2.5))
            );
            assert_eq!(
                perturb_value(&json!(true), &RType::Bool, &mut pick),
                Some(json!(false))
            );
            let list = json!(["a", "b", "c"]);
            let changed =
                perturb_value(&list, &RType::Vec(Box::new(RType::Str)), &mut pick).unwrap();
            assert_ne!(changed, list);
            let items = changed.as_array().unwrap();
            assert!((2..=4).contains(&items.len()), "{changed}");
            assert!(items.iter().all(Value::is_string), "{changed}");
        }
    }

    #[test]
    fn a_value_is_not_perturbed_when_that_would_change_its_type() {
        let mut pick = Pick(2);
        // Structured values, byte buffers, a missing optional, encoded NaN/undefined and a
        // string for a number stay as recorded: the type is the function's, not ours to change.
        for (v, ty) in [
            (json!({ "a": 1 }), RType::Json),
            (json!([1, 2]), RType::Bytes),
            (json!(null), RType::Opt(Box::new(RType::Str))),
            (json!({ "$num": "NaN" }), RType::F64),
            (
                json!({ "$undefined": true }),
                RType::Opt(Box::new(RType::F64)),
            ),
            (json!("7"), RType::F64),
        ] {
            assert_eq!(perturb_value(&v, &ty, &mut pick), None, "{v}");
        }
        // An empty list has nothing to swap, remove or copy; an empty string gains a character.
        assert_eq!(
            perturb_value(&json!([]), &RType::Vec(Box::new(RType::Str)), &mut pick),
            None
        );
        assert_eq!(
            perturb_value(&json!(""), &RType::Str, &mut pick),
            Some(json!("a"))
        );
        assert_eq!(
            perturb_value(&json!(0), &RType::Int, &mut pick),
            Some(json!(1))
        );
        // A list of equal items cannot be swapped, but it can lose or gain one.
        let same = json!(["x", "x"]);
        for _ in 0..50 {
            let c = perturb_value(&same, &RType::Vec(Box::new(RType::Str)), &mut pick);
            assert_ne!(c.unwrap(), same);
        }
    }

    #[test]
    fn a_call_outside_its_declared_types_is_not_a_held_out_input() {
        // The demo fixture's signature: `normalize(entries: readonly Entry[], prefix?: string)`.
        let types = [LocalType {
            name: "Entry".into(),
            text: "export interface Entry { readonly key: string; readonly value: string | null }"
                .into(),
            alias: false,
        }];
        let params = [
            param("readonly Entry[]"),
            Param {
                optional: true,
                ..param("string")
            },
        ];
        let ok = |args: &[Value]| call_conforms(args, &params, &types);
        let entry = json!({ "key": "k", "value": null });
        assert!(ok(&[json!([]), json!("p")]));
        assert!(ok(&[
            json!([entry.clone(), { "key": "a", "value": "b" }]),
            json!("p")
        ]));
        assert!(ok(&[json!([entry]), json!({ "$undefined": true })]));
        assert!(ok(&[json!([]), json!(null)]));
        // A non-list for a list, a list of things that are not entries, a number for a string.
        for bad in [json!(0), json!(true), json!({}), json!("x"), json!(null)] {
            assert!(!ok(&[bad.clone(), json!("p")]), "{bad}");
        }
        for bad in [
            json!(["a", 1]),
            json!([null]),
            json!([1]),
            json!([{ "key": 1, "value": null }]),
        ] {
            assert!(!ok(&[bad.clone(), json!("p")]), "{bad}");
        }
        assert!(
            !ok(&[json!([{ "value": "v" }]), json!("p")]),
            "a required property is missing"
        );
        assert!(!ok(&[json!([]), json!(3)]));
        // A type nobody models accepts anything, so nothing is dropped for lack of knowledge: an
        // unknown element type takes any element, though the parameter is still a list.
        let unknown_list = [param("readonly Unknown[]")];
        assert!(call_conforms(&[json!([0, "x", null])], &unknown_list, &[]));
        assert!(!call_conforms(&[json!(0)], &unknown_list, &[]));
        assert!(call_conforms(&[json!(0)], &[param("unknown")], &[]));
        assert!(call_conforms(&[json!(0)], &[param("Unknown")], &[]));
        // Literals, unions and numbers; the record codec's markers stand for what they encode.
        assert!(call_conforms(
            &[json!("fast")],
            &[param("'fast' | 'safe'")],
            &[]
        ));
        assert!(!call_conforms(
            &[json!("slow")],
            &[param("'fast' | 'safe'")],
            &[]
        ));
        assert!(call_conforms(
            &[json!({ "$num": "NaN" })],
            &[param("number")],
            &[]
        ));
        assert!(call_conforms(
            &[json!({ "$utf16": [55357] })],
            &[param("string")],
            &[]
        ));
        assert!(!call_conforms(
            &[json!({ "$num": "NaN" })],
            &[param("string")],
            &[]
        ));
        assert!(!call_conforms(
            &[json!({ "$undefined": true })],
            &[param("string")],
            &[]
        ));
        assert!(!call_conforms(
            &[json!([1, "2"])],
            &[param("number[]")],
            &[]
        ));
        // A rest parameter and extra arguments are not judged.
        let rest = [Param {
            rest: true,
            ..param("number")
        }];
        assert!(call_conforms(&[json!("anything")], &rest, &[]));
        assert!(call_conforms(
            &[json!("a"), json!(1)],
            &[param("string")],
            &[]
        ));
    }

    #[test]
    fn lists_of_structured_values_and_literal_typed_strings_are_left_alone() {
        let mut pick = Pick(5);
        // A list is only edited when its elements are values this check understands.
        let objects = json!([{ "id": 1 }, { "id": 2 }]);
        assert_eq!(
            perturb_value(&objects, &RType::Vec(Box::new(RType::Json)), &mut pick),
            None
        );
        let nested = json!([["a", "b"], ["c"]]);
        let ty = RType::Vec(Box::new(RType::Vec(Box::new(RType::Str))));
        assert!(perturb_value(&nested, &ty, &mut pick).is_some());
        // A string typed as a union of literals is a smaller set than `string`.
        for literal in ["'fast' | 'safe'", "\"a\" | \"b\"", "`id-${number}`"] {
            let params = [param(literal)];
            for _ in 0..20 {
                assert_eq!(perturb_args(&[json!("fast")], &params, &mut pick), None);
            }
        }
        assert!(perturb_args(&[json!("fast")], &[param("string")], &mut pick).is_some());
    }

    #[test]
    fn a_call_keeps_its_arity_and_changes_one_argument() {
        let params = [param("string"), param("number[]"), param("Opts")];
        let args = vec![json!("abc"), json!([1, 2, 3]), json!({ "k": 1 })];
        let mut pick = Pick(3);
        let mut touched = HashSet::new();
        for _ in 0..100 {
            let out = perturb_args(&args, &params, &mut pick).unwrap();
            assert_eq!(out.len(), 3);
            let differing: Vec<usize> = (0..3).filter(|&i| out[i] != args[i]).collect();
            assert_eq!(differing.len(), 1, "{out:?}");
            touched.extend(differing);
        }
        assert_eq!(
            touched,
            HashSet::from([0, 1]),
            "the object argument is left alone"
        );
        // Only an argument that cannot change: no perturbation.
        assert_eq!(
            perturb_args(&[json!({ "k": 1 })], &[param("Opts")], &mut pick),
            None
        );
    }

    #[test]
    fn perturbing_is_a_function_of_the_seed() {
        let params = [param("string"), param("number")];
        let args = vec![json!("some text"), json!(41)];
        let run = |seed| {
            let mut pick = Pick(seed);
            (0..10)
                .map(|_| perturb_args(&args, &params, &mut pick))
                .collect::<Vec<_>>()
        };
        assert_eq!(run(9), run(9));
        assert_ne!(run(9), run(10));
    }

    #[test]
    fn the_ports_run_end_to_end_are_the_only_ones_supported() {
        use crate::bridge::Kind;
        use crate::lang::Lang;
        assert_eq!(unsupported(Lang::Ts, Kind::Napi), None);
        assert_eq!(unsupported(Lang::Python, Kind::Pyo3), None);
        assert!(unsupported(Lang::Ts, Kind::Wasm).is_some());
        let why = unsupported(Lang::Python, Kind::Ffi).unwrap();
        assert!(
            why.contains("only tested for TypeScript/JavaScript napi and Python PyO3"),
            "{why}"
        );
        assert!(why.contains("Python"), "{why}");
        assert!(why.contains("JSON dispatcher"), "{why}");
    }

    #[test]
    fn perturbed_cases_deduplicates_with_case_id_and_keeps_kwargs_separate() {
        let manifest: Manifest = serde_json::from_value(json!({
            "schema": "1",
            "root": ".",
            "unit": "flip.py",
            "language": "python",
            "kind": "pyo3",
            "crate_name": "flip-rs",
            "exports": [{
                "name": "flip",
                "file": "flip.py",
                "line": 1,
                "params": [{ "name": "flag", "ts_type": "boolean", "optional": false, "rest": false }],
                "returns": "boolean",
                "is_async": false
            }]
        }))
        .unwrap();
        let signatures = Signatures::of(&manifest);
        let recorded = "{\"fn\":\"flip\",\"args\":[true],\"ok\":false}\n";

        let mut blocked = HashSet::from([
            case_id(&json!({ "fn": "flip", "args": [true] })),
            case_id(&json!({ "fn": "flip", "args": [false] })),
        ]);
        assert!(
            perturbed_cases(recorded, &manifest, &signatures, 1, 7, &mut blocked).is_empty(),
            "positional case already in seen is not regenerated"
        );

        let mut kwargs_only = HashSet::from([
            case_id(&json!({ "fn": "flip", "args": [true] })),
            case_id(&json!({ "fn": "flip", "args": [false], "kwargs": { "k": 1 } })),
        ]);
        let generated = perturbed_cases(recorded, &manifest, &signatures, 1, 7, &mut kwargs_only);
        assert_eq!(generated.len(), 1, "{generated:?}");
        assert_eq!(generated[0]["args"], json!([false]));
    }

    #[test]
    fn perturbed_cases_preserves_kwargs_and_perturbs_a_keyword_only_function() {
        let manifest: Manifest = serde_json::from_value(json!({
            "schema": "1",
            "root": ".",
            "unit": "tag.py",
            "language": "python",
            "kind": "pyo3",
            "crate_name": "tag-rs",
            "exports": [{
                "name": "tag",
                "file": "tag.py",
                "line": 1,
                "params": [
                    { "name": "text", "ts_type": "string", "optional": false, "rest": false },
                    { "name": "suffix", "ts_type": "string", "optional": true, "rest": false, "keyword_only": true }
                ],
                "returns": "string",
                "is_async": false
            }]
        }))
        .unwrap();
        let signatures = Signatures::of(&manifest);
        let recorded = "{\"fn\":\"tag\",\"module\":\"tag.py\",\"args\":[\"hi\"],\"kwargs\":{\"suffix\":\"!\"},\"ok\":\"hi!\"}\n";
        let mut seen = HashSet::new();
        let generated = perturbed_cases(recorded, &manifest, &signatures, 1, 7, &mut seen);
        assert_eq!(generated.len(), 1, "{generated:?}");
        assert_eq!(generated[0]["fn"], json!("tag"));
        assert_eq!(
            generated[0]["kwargs"],
            json!({ "suffix": "!" }),
            "keyword binding is preserved"
        );
        assert_ne!(
            generated[0]["args"],
            json!(["hi"]),
            "the positional argument was perturbed"
        );
    }

    #[test]
    fn perturbed_cases_skip_a_call_whose_keyword_argument_is_outside_its_parameter() {
        let manifest: Manifest = serde_json::from_value(json!({
            "schema": "1",
            "root": ".",
            "unit": "tag.py",
            "language": "python",
            "kind": "pyo3",
            "crate_name": "tag-rs",
            "exports": [{
                "name": "tag",
                "file": "tag.py",
                "line": 1,
                "params": [
                    { "name": "text", "ts_type": "string", "optional": false, "rest": false },
                    { "name": "suffix", "ts_type": "string", "optional": true, "rest": false, "keyword_only": true }
                ],
                "returns": "string",
                "is_async": false
            }]
        }))
        .unwrap();
        let signatures = Signatures::of(&manifest);
        let recorded = "{\"fn\":\"tag\",\"module\":\"tag.py\",\"args\":[\"hi\"],\"kwargs\":{\"suffix\":5},\"ok\":null}\n";
        let generated =
            perturbed_cases(recorded, &manifest, &signatures, 1, 7, &mut HashSet::new());
        assert!(generated.is_empty(), "{generated:?}");
        let fitting = recorded.replace("\"suffix\":5", "\"suffix\":\"!\"");
        let generated =
            perturbed_cases(&fitting, &manifest, &signatures, 1, 7, &mut HashSet::new());
        assert_eq!(generated.len(), 1, "{generated:?}");
    }

    #[test]
    fn all_keyword_calls_change_one_named_binding_and_keep_the_others() {
        let mut manifest: Manifest = serde_json::from_value(json!({
            "schema": "1", "root": ".", "unit": "tag.py", "language": "python",
            "kind": "pyo3", "crate_name": "tag-rs",
            "exports": [{
                "name": "tag", "file": "tag.py", "line": 1, "params": [],
                "returns": "string", "is_async": false
            }]
        }))
        .unwrap();
        for (ty, value, expected) in [
            ("string", json!("hi"), None),
            ("number", json!(3), Some(json!(-3.0))),
            ("int", json!(3), Some(json!(-3))),
            ("boolean", json!(true), Some(json!(false))),
        ] {
            manifest.exports[0].params = vec![
                Param {
                    name: "suffix".into(),
                    keyword_only: true,
                    ..param("'!'")
                },
                Param {
                    name: "text".into(),
                    keyword_only: true,
                    ..param(ty)
                },
            ];
            let signatures = Signatures::of(&manifest);
            let base = json!({ "fn": "tag", "args": [], "kwargs": { "text": value, "suffix": "!", "extra": 9 } });
            let mut seen = HashSet::from([case_id(&base)]);
            let generated =
                perturbed_cases(&base.to_string(), &manifest, &signatures, 1, 7, &mut seen);
            assert_eq!(generated.len(), 1, "{ty}: {generated:?}");
            let case = &generated[0];
            assert_eq!(case["fn"], "tag");
            assert_eq!(case["args"], json!([]));
            assert_eq!(case["kwargs"].as_object().unwrap().len(), 3);
            assert_eq!(case["kwargs"]["suffix"], "!");
            assert_eq!(case["kwargs"]["extra"], 9);
            assert_ne!(case["kwargs"]["text"], value);
            if let Some(expected) = expected {
                assert_eq!(case["kwargs"]["text"], expected);
            }
            let mut blocked = HashSet::from([case_id(case)]);
            // These types have exactly one sign/boolean perturbation.
            if ty != "string" {
                assert!(
                    perturbed_cases(
                        &base.to_string(),
                        &manifest,
                        &signatures,
                        1,
                        7,
                        &mut blocked
                    )
                    .is_empty()
                );
            }
        }
        for p in [
            param("'hi'"),
            param("Opts"),
            Param {
                rest: true,
                ..param("string")
            },
        ] {
            manifest.exports[0].params = vec![Param {
                name: "text".into(),
                keyword_only: true,
                ..p
            }];
            let signatures = Signatures::of(&manifest);
            for kwargs in [
                json!({}),
                json!({ "unknown": "hi" }),
                json!({ "text": "hi" }),
            ] {
                let base = json!({ "fn": "tag", "args": [], "kwargs": kwargs });
                assert!(
                    perturbed_cases(
                        &base.to_string(),
                        &manifest,
                        &signatures,
                        1,
                        7,
                        &mut HashSet::new()
                    )
                    .is_empty()
                );
            }
        }
    }
}