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.

49.6 KB
Raw Blame
//! `record --from-tests -- <test command>`: runs the original's own test suite and keeps every
//! call it makes to the unit's exported functions as recorded inputs, so the cases cover what
//! the project's authors thought worth testing, not only generated values.
//!
//! TS/JS: test runners (Jest, Vitest, ts-jest) load sources through their own module systems, so
//! no Node hook sees the calls. The unit's files get a few lines appended for the run instead,
//! wrapping each exported function declaration, and are restored from a backup afterwards (also
//! at the start of the next run, if a run was killed and the file was not edited since).
//! Python: an import hook on `PYTHONPATH` wraps the functions when their module loads; no file
//! changes.

use std::collections::{BTreeMap, HashSet};
use std::path::{Path, PathBuf};
use std::process::Command;

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

use crate::bridge::Manifest;
use crate::lang::Lang;
use crate::walk::Canonical;

/// Captured calls kept per function: enough to cover a test suite, small enough to record.
const PER_FUNCTION: usize = 1000;

/// A stable hash of one captured line, used to recognise a repeat without keeping the line.
fn seen_key(line: &str) -> u64 {
    let mut h: u64 = 0xcbf2_9ce4_8422_2325;
    for b in line.as_bytes() {
        h ^= u64::from(*b);
        h = h.wrapping_mul(0x0000_0100_0000_01b3);
    }
    h
}

/// A deterministic 64-bit hash of a function name, so a capture is reproducible: the same run keeps
/// the same sample.
fn seed_of(name: &str) -> u64 {
    let mut h: u64 = 0xcbf2_9ce4_8422_2325;
    for b in name.bytes() {
        h ^= u64::from(b);
        h = h.wrapping_mul(0x0000_0100_0000_01b3);
    }
    h
}

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

/// The distinct calls kept for one function: a reservoir over the whole run, not the first
/// `PER_FUNCTION`. Keeping the first N records one data source when a workload walks them in order
/// (issue #1071: 1,000 calls, all from one source, caught 0 of 12 planted bugs).
struct Reservoir {
    seed: u64,
    seen: u64,
    slots: Vec<String>,
}

impl Reservoir {
    fn new(name: &str) -> Self {
        Self {
            seed: seed_of(name),
            seen: 0,
            slots: Vec::new(),
        }
    }

    fn offer(&mut self, line: &str) {
        self.seen += 1;
        if self.slots.len() < PER_FUNCTION {
            self.slots.push(line.to_string());
            return;
        }
        // The `seen`-th call replaces a random slot with probability `PER_FUNCTION / seen`.
        let pick = splitmix64(self.seed ^ self.seen) % self.seen;
        if (pick as usize) < PER_FUNCTION {
            self.slots[pick as usize] = line.to_string();
        }
    }
}
pub const TEST_INPUTS: &str = "test-inputs.jsonl";
pub const MAX_BYTES_ENV: &str = "RUST_ANYTHING_CAPTURE_MAX_BYTES";
const DEFAULT_MAX_BYTES: u64 = 1024 * 1024 * 1024;
const MAX_SEEN_PER_FN: usize = 100_000;
const MAX_SEEN_BYTES: usize = 64 * 1024 * 1024;
const BACKUP: &str = ".rust-anything-backup";
/// Why `record --sandbox` refuses `--from-tests`.
pub const NOT_SANDBOXED: &str = "`--sandbox` does not combine with `--from-tests`: the project's \
     own test suite would run outside the sandbox (and TS/JS capture edits the unit's files for \
     the run). Use one or the other";

fn parse_max_bytes(raw: Option<&str>) -> u64 {
    raw.and_then(|s| s.trim().parse::<u64>().ok())
        .filter(|&n| n > 0)
        .unwrap_or(DEFAULT_MAX_BYTES)
}

pub fn format_bytes(bytes: u64) -> String {
    const KIB: u64 = 1024;
    const MIB: u64 = KIB * 1024;
    const GIB: u64 = MIB * 1024;
    if bytes >= GIB && bytes.is_multiple_of(GIB) {
        format!("{} GiB", bytes / GIB)
    } else if bytes >= MIB && bytes.is_multiple_of(MIB) {
        format!("{} MiB", bytes / MIB)
    } else if bytes >= KIB && bytes.is_multiple_of(KIB) {
        format!("{} KiB", bytes / KIB)
    } else {
        format!("{bytes} B")
    }
}

#[derive(Debug)]
pub struct Capture {
    /// The captured inputs, one `{"fn", "args"}` per line (with `"kwargs"` for Python arguments
    /// passed by keyword), in the `--inputs` format.
    pub inputs: PathBuf,
    pub per_function: BTreeMap<String, usize>,
    /// Exports the capture cannot see (not a function declaration), with why.
    pub skipped: Vec<String>,
    pub tests_passed: bool,
    /// Present when the raw capture file hit its byte cap before the tests finished.
    pub stopped_at_bytes: Option<u64>,
}

impl Capture {
    pub fn capped_notice(&self) -> Option<String> {
        self.stopped_at_bytes.map(|b| {
            format!(
                "capture stopped at {}: later calls were not sampled",
                format_bytes(b)
            )
        })
    }
}

#[cfg_attr(not(test), expect(dead_code))]
#[derive(Debug, Default)]
struct RawStats {
    lines: usize,
    bytes: u64,
}

static NEXT_RUN_ID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);

fn next_run_id() -> String {
    let seq = NEXT_RUN_ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    format!("{}-{seq}", std::process::id())
}

struct RemoveFileOnDrop(Option<PathBuf>);

impl RemoveFileOnDrop {
    fn new(path: PathBuf) -> Self {
        Self(Some(path))
    }

    fn disarm(&mut self) {
        self.0 = None;
    }
}

impl Drop for RemoveFileOnDrop {
    fn drop(&mut self) {
        if let Some(path) = self.0.take() {
            let _ = std::fs::remove_file(path);
        }
    }
}

struct RemoveDirOnDrop(PathBuf);

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

/// Removes temporary per-run input files created under `<crate>/target/from-tests` when dropped.
pub struct RunInputsGuard {
    scope: PathBuf,
    paths: Vec<PathBuf>,
}

impl RunInputsGuard {
    pub fn new(crate_dir: &Path) -> Self {
        Self {
            scope: crate_dir.join("target").join("from-tests"),
            paths: Vec::new(),
        }
    }

    pub fn track(&mut self, path: &Path) {
        if path.starts_with(&self.scope) && !self.paths.iter().any(|p| p == path) {
            self.paths.push(path.to_path_buf());
        }
    }
}

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

/// Atomically publishes `from` (when it still exists) to `<crate>/test-inputs.jsonl` so callers
/// holding the recording lock leave the crate's visible `test-inputs.jsonl` matching their run.
pub fn publish_test_inputs(crate_dir: &Path, from: &Path) -> Result<()> {
    let text =
        std::fs::read_to_string(from).with_context(|| format!("reading {}", from.display()))?;
    write_test_inputs_atomic(crate_dir, &text, &next_run_id())
}

fn write_test_inputs_atomic(crate_dir: &Path, contents: &str, run_id: &str) -> Result<()> {
    let dest = crate_dir.join(TEST_INPUTS);
    let tmp = crate_dir.join(format!(".{TEST_INPUTS}.{run_id}.tmp"));
    let _tmp_guard = RemoveFileOnDrop::new(tmp.clone());
    std::fs::write(&tmp, contents).with_context(|| format!("writing {}", tmp.display()))?;
    std::fs::rename(&tmp, &dest)
        .with_context(|| format!("replacing {} with {}", dest.display(), tmp.display()))?;
    Ok(())
}

pub fn capture(crate_dir: &Path, command: &[String]) -> Result<Capture> {
    let max_bytes = parse_max_bytes(std::env::var(MAX_BYTES_ENV).ok().as_deref());
    let (capture, _) = capture_with_max_bytes(crate_dir, command, max_bytes)?;
    Ok(capture)
}

fn capture_with_max_bytes(
    crate_dir: &Path,
    command: &[String],
    max_bytes: u64,
) -> Result<(Capture, RawStats)> {
    let max_bytes = max_bytes.max(1);
    let m = Manifest::load(crate_dir)?;
    let Some((program, args)) = command.split_first() else {
        bail!("--from-tests needs the test command after `--`, e.g. `-- npx jest`");
    };
    let run_id = next_run_id();
    let run_dir = crate_dir.join("target").join("from-tests");
    std::fs::create_dir_all(&run_dir).with_context(|| format!("creating {}", run_dir.display()))?;
    let raw = std::path::absolute(run_dir.join(format!("test-calls.{run_id}.raw.jsonl")))?;
    let _ = std::fs::remove_file(&raw);
    let _raw_guard = RemoveFileOnDrop::new(raw.clone());
    let mut cmd = Command::new(program);
    cmd.args(args)
        .current_dir(&m.root)
        .stdout(std::io::stderr())
        .env("RUST_ANYTHING_CAPTURE", &raw)
        .env(MAX_BYTES_ENV, max_bytes.to_string())
        .env("CI", "1");
    let mut skipped = Vec::new();
    let mut _hook_guard = None;
    let status = match m.language {
        Lang::Ts => {
            let guard = instrument_js(&m, &mut skipped)?;
            let status = crate::process::status(&mut cmd, crate::process::TESTS);
            drop(guard);
            status
        }
        Lang::Python => {
            let hook = run_dir.join(format!("hook-{run_id}"));
            std::fs::create_dir_all(&hook)?;
            _hook_guard = Some(RemoveDirOnDrop(hook.clone()));
            std::fs::write(hook.join("sitecustomize.py"), python_hook())?;
            let mut want: BTreeMap<String, Vec<String>> = BTreeMap::new();
            for f in &m.exports {
                let path = m.root.join(&f.file).canonical()?;
                want.entry(path.to_string_lossy().into_owned())
                    .or_default()
                    .push(f.name.clone());
            }
            let path = std::env::join_paths(
                std::iter::once(std::path::absolute(&hook)?).chain(
                    std::env::var_os("PYTHONPATH")
                        .map(|p| std::env::split_paths(&p).collect::<Vec<_>>())
                        .unwrap_or_default(),
                ),
            )?;
            cmd.env("PYTHONPATH", path)
                .env("RUST_ANYTHING_CAPTURE_FUNCS", serde_json::to_string(&want)?)
                .env("PYTHONDONTWRITEBYTECODE", "1");
            crate::process::status(&mut cmd, crate::process::TESTS)
        }
        other => bail!(
            "--from-tests captures TS/JS and Python test suites; this unit is {}",
            other.name()
        ),
    }
    .with_context(|| format!("running `{}`", command.join(" ")))?;

    // Read the capture line by line: a long run writes one line per call, and loading a million of
    // them at once is gigabytes (review of #1104). `seen` holds a hash of each distinct line rather
    // than the line itself, so the de-duplication set stays 8 bytes per call.
    let exported: HashSet<&str> = m.exports.iter().map(|f| f.name.as_str()).collect();
    let mut seen: HashSet<u64> = HashSet::new();
    let mut reservoirs: BTreeMap<String, Reservoir> = BTreeMap::new();
    let mut raw_lines = 0usize;
    let mut capped = false;
    {
        let reader: Box<dyn std::io::BufRead> = match std::fs::File::open(&raw) {
            Ok(file) => Box::new(std::io::BufReader::new(file)),
            // The run wrote nothing: no calls to sample.
            Err(_) => Box::new(std::io::BufReader::new(std::io::empty())),
        };
        for line in std::io::BufRead::lines(reader) {
            // A line that is not UTF-8 is skipped: `read_line` has already consumed it. Any other read
            // error ends the capture: `Lines` would keep returning the same failure, and a half-read
            // file is not a sample (review of #1104).
            let line = match line {
                Ok(line) => line,
                Err(e) if e.kind() == std::io::ErrorKind::InvalidData => continue,
                Err(_) => break,
            };
            let line = line.as_str();
            let Ok(call) = serde_json::from_str::<Value>(line) else {
                continue;
            };
            if call.get("__ra_capped").and_then(Value::as_bool) == Some(true) {
                capped = true;
                continue;
            }
            raw_lines += 1;
            let Some(name) = call["fn"].as_str() else {
                continue;
            };
            if !exported.contains(name) || !call["args"].is_array() || !seen.insert(seen_key(line))
            {
                continue;
            }
            reservoirs
                .entry(name.to_string())
                .or_insert_with(|| Reservoir::new(name))
                .offer(line);
        }
    }
    let raw_bytes = std::fs::metadata(&raw).map(|m| m.len()).unwrap_or(0);
    if raw_bytes >= max_bytes {
        capped = true;
    }
    // Sorted by function name, so the file does not depend on the order the capture wrote them.
    let mut out = String::new();
    let mut per_function: BTreeMap<String, usize> = BTreeMap::new();
    for (name, reservoir) in reservoirs {
        per_function.insert(name, reservoir.slots.len());
        for line in reservoir.slots {
            out.push_str(&line);
            out.push('\n');
        }
    }
    let inputs = run_dir.join(format!("test-inputs.{run_id}.jsonl"));
    let mut inputs_guard = RemoveFileOnDrop::new(inputs.clone());
    std::fs::write(&inputs, out).with_context(|| format!("writing {}", inputs.display()))?;
    inputs_guard.disarm();
    Ok((
        Capture {
            inputs,
            per_function,
            skipped,
            tests_passed: status.success(),
            stopped_at_bytes: capped.then_some(max_bytes),
        },
        RawStats {
            lines: raw_lines,
            bytes: raw_bytes,
        },
    ))
}

/// The inputs file `record` takes: the captured calls, after `own` inputs when there are some.
pub fn with_own_inputs(crate_dir: &Path, own: Option<&Path>, captured: &Path) -> Result<PathBuf> {
    let Some(own) = own else {
        return Ok(captured.to_path_buf());
    };
    let mut text =
        std::fs::read_to_string(own).with_context(|| format!("reading {}", own.display()))?;
    if !text.is_empty() && !text.ends_with('\n') {
        text.push('\n');
    }
    text += &std::fs::read_to_string(captured)?;
    let run_dir = crate_dir.join("target").join("from-tests");
    std::fs::create_dir_all(&run_dir)?;
    let combined = run_dir.join(format!("record-inputs.{}.jsonl", next_run_id()));
    let mut combined_guard = RemoveFileOnDrop::new(combined.clone());
    std::fs::write(&combined, text)?;
    combined_guard.disarm();
    Ok(combined)
}

/// Restores the instrumented files when dropped, then lets go of their capture locks.
struct Restore {
    files: Vec<PathBuf>,
    _locks: Vec<std::fs::File>,
}

impl Drop for Restore {
    fn drop(&mut self) {
        for file in &self.files {
            if let Err(e) = restore(file) {
                eprintln!("{e:#}");
            }
        }
    }
}

fn backup_of(file: &Path) -> PathBuf {
    let mut name = file.as_os_str().to_owned();
    name.push(BACKUP);
    PathBuf::from(name)
}

/// Waits for, then holds, the capture lock of one source file: two captures (two MCP calls, two
/// terminals) of units that share the file take turns instead of backing up each other's
/// capture block.
fn lock_source(file: &Path) -> Result<std::fs::File> {
    use sha2::{Digest, Sha256};
    let file = std::path::absolute(file)?;
    let file = file.canonicalize().unwrap_or(file);
    let hash = Sha256::digest(file.as_os_str().as_encoded_bytes());
    let hex: String = hash.iter().take(16).map(|b| format!("{b:02x}")).collect();
    let path = std::env::temp_dir().join(format!("rust-anything-from-tests-{hex}.lock"));
    let lock = std::fs::OpenOptions::new()
        .create(true)
        .truncate(false)
        .write(true)
        .open(&path)
        .with_context(|| format!("opening {}", path.display()))?;
    lock.lock()
        .with_context(|| format!("locking {}", path.display()))?;
    Ok(lock)
}

fn is_ts(file: &Path) -> bool {
    file.extension()
        .is_some_and(|e| e == "ts" || e == "tsx" || e == "mts")
}

/// `text` with the capture `block` appended and, for TypeScript, type checking off (after a
/// `#!` line, which must stay first).
fn instrumented(text: &str, ts: bool, block: &str) -> String {
    let split = if text.starts_with("#!") {
        text.find('\n').map_or(text.len(), |i| i + 1)
    } else {
        0
    };
    let (shebang, rest) = text.split_at(split);
    format!(
        "{shebang}{}{rest}\n{block}",
        if ts { "// @ts-nocheck\n" } else { "" }
    )
}

/// Puts back the copy a capture took (this run's, or a killed run's) when the file is still that
/// copy with the capture block; a file edited since keeps the edits, and the stale copy goes.
fn restore(file: &Path) -> Result<()> {
    let backup = backup_of(file);
    let Ok(saved) = std::fs::read_to_string(&backup) else {
        return Ok(());
    };
    let current = std::fs::read_to_string(file).unwrap_or_default();
    let block = current.rfind(CAPTURE_HEAD).map(|at| &current[at..]);
    if block.is_some_and(|block| {
        block.ends_with(CAPTURE_TAIL) && instrumented(&saved, is_ts(file), block) == current
    }) {
        crate::setup::write(file, &saved)
            .with_context(|| format!("restoring {}", file.display()))?;
    } else if block.is_some() {
        bail!(
            "{} still has the capture block of a `record --from-tests` run that was stopped, and \
             was edited since: remove the block (the file as it was before that run is {}), then \
             run again",
            file.display(),
            backup.display()
        );
    }
    std::fs::remove_file(&backup).with_context(|| format!("removing {}", backup.display()))
}

fn instrument_js(m: &Manifest, skipped: &mut Vec<String>) -> Result<Restore> {
    let mut by_file: BTreeMap<PathBuf, (&str, Vec<&str>)> = BTreeMap::new();
    for f in &m.exports {
        let path = std::path::absolute(m.root.join(&f.file))?;
        let key = path.canonicalize().unwrap_or(path);
        by_file
            .entry(key)
            .or_insert((&f.file, Vec::new()))
            .1
            .push(&f.name);
    }
    let mut guard = Restore {
        files: Vec::new(),
        _locks: Vec::new(),
    };
    let capture = JS_CAPTURE
        .replace("__CODEC__", &js_codec())
        .replace("__MAX_SEEN__", &MAX_SEEN_PER_FN.to_string())
        .replace("__MAX_SEEN_BYTES__", &MAX_SEEN_BYTES.to_string())
        .replace("__DEFAULT_CAP__", &DEFAULT_MAX_BYTES.to_string());
    for (file, names) in by_file.into_values() {
        let path = m.root.join(file);
        guard._locks.push(lock_source(&path)?);
        restore(&path)?;
        let text = std::fs::read_to_string(&path)
            .with_context(|| format!("reading {}", path.display()))?;
        if text.contains(CAPTURE_HEAD) {
            bail!(
                "{} still has the capture block of a `record --from-tests` run that was stopped: \
                 remove it, then run again",
                path.display()
            );
        }
        let wrappable: Vec<&str> = names
            .into_iter()
            .filter(|name| {
                let declared = regex::Regex::new(&format!(
                    r"\bfunction\s*\*?\s*{}\s*[<(]",
                    regex::escape(name)
                ))
                .is_ok_and(|re| re.is_match(&text));
                if !declared {
                    skipped.push(format!(
                        "{name} ({file}): not a function declaration, so its binding cannot be wrapped"
                    ));
                }
                declared
            })
            .collect();
        if wrappable.is_empty() {
            continue;
        }
        std::fs::copy(&path, backup_of(&path))
            .with_context(|| format!("backing up {}", path.display()))?;
        guard.files.push(path.clone());
        let wraps: String = wrappable
            .iter()
            .map(|n| format!("  {n} = __raWrap('{n}', {n})\n"))
            .collect();
        let instrumented = instrumented(&text, is_ts(&path), &capture.replace("__WRAPS__", &wraps));
        crate::setup::write(&path, &instrumented)
            .with_context(|| format!("instrumenting {}", path.display()))?;
    }
    Ok(guard)
}

/// The first and the last line of the capture block.
const CAPTURE_HEAD: &str = "// rust-anything record --from-tests: removed when the tests finish.\n";
const CAPTURE_TAIL: &str = "/* c8 ignore stop */\n";

const JS_CAPTURE: &str = r#"// rust-anything record --from-tests: removed when the tests finish.
/* c8 ignore start */
/* istanbul ignore next */
{
  const __raFs = globalThis.process?.getBuiltinModule?.('node:fs')
  const __raOut = globalThis.process?.env?.RUST_ANYTHING_CAPTURE
  const __raMaxSeen = __MAX_SEEN__
  const __raMaxSeenBytes = __MAX_SEEN_BYTES__
  const __raState = (() => {
    const key = globalThis.Symbol.for('rust-anything.capture')
    const cur = globalThis[key]
    if (cur && cur.out === __raOut) return cur
    const rawCap = globalThis.Number(globalThis.process?.env?.RUST_ANYTHING_CAPTURE_MAX_BYTES)
    const cap = globalThis.Number.isFinite(rawCap) && rawCap > 0 ? rawCap : __DEFAULT_CAP__
    const next = { out: __raOut, fd: null, cap, capped: false, seen: new globalThis.Map(), seenBytes: 0 }
    if (globalThis.process?.once) {
      globalThis.process.once('exit', () => {
        if (next.fd !== null) {
          try { __raFs?.closeSync(next.fd) } catch {}
          next.fd = null
        }
      })
    }
    globalThis[key] = next
    return next
  })()
  const __raOpen = () => {
    if (__raState.fd === null) __raState.fd = __raFs.openSync(__raOut, 'a')
    return __raState.fd
  }
  // The built-in name of a typed array, which a subclass cannot change.
  const __raTypedName = globalThis.Object.getOwnPropertyDescriptor(globalThis.Object.getPrototypeOf(globalThis.Uint8Array.prototype), globalThis.Symbol.toStringTag).get
__CODEC__
  const __raWrap = (name, orig) => {
    if (!__raFs || !__raOut || typeof orig !== 'function') return orig
    const wrapped = function (...args) {
      if (!__raState.capped) {
        try {
          const line = globalThis.JSON.stringify({ fn: name, args: globalThis.Array.from(args, a => __raEnc(a)) })
          let seen = __raState.seen.get(name)
          if (!seen) {
            seen = new globalThis.Set()
            __raState.seen.set(name, seen)
          }
          if (!seen.has(line)) {
            const buf = globalThis.Buffer.from(line + '\n', 'utf8')
            if (seen.size < __raMaxSeen && __raState.seenBytes < __raMaxSeenBytes) {
              seen.add(line)
              __raState.seenBytes += buf.length
            }
            const fd = __raOpen()
            if (__raFs.fstatSync(fd).size + buf.length > __raState.cap) {
              __raState.capped = true
              __raFs.writeSync(fd, '{"__ra_capped":true}\n')
            } else {
              __raFs.writeSync(fd, buf)
            }
          }
        } catch {}
      }
      return new.target ? globalThis.Reflect.construct(orig, args, new.target) : orig.apply(this, args)
    }
    if (typeof exports === 'object' && exports !== null) {
      for (const key of [name, 'default']) if (exports[key] === orig) exports[key] = wrapped
    }
    return wrapped
  }
__WRAPS__}
/* c8 ignore stop */
"#;

/// What the capture hook changes in the `enc` of `CODEC_JS`: a value `dec` cannot give back
/// throws, so the call is left out. That is a function, symbol, cycle, RegExp or Error, an
/// object `dec` would rebuild as a plain one although it is not (a `URL`, an `ArrayBuffer`, a
/// boxed string, anything with `toJSON`, or a RegExp, Error, Map, Set or Date from another
/// realm), and a typed array keeps its built-in kind (a subclass is not a global `dec` can find).
/// Array holes stay `undefined`, as `JSON.stringify` saw them before. A class instance is still
/// captured as its own fields, as before.
const JS_CAPTURE_ENC: &[(&str, &str)] = &[
    ("return { $function: v.name }", NOT_DATA),
    ("return { $symbol: String(v.description) }", NOT_DATA),
    ("return { $cycle: true }", NOT_DATA),
    ("return { $regexp: String(v) }", NOT_DATA),
    ("return { $error: v.message }", NOT_DATA),
    (
        "if (Array.isArray(v)) return v.map(x => enc(x, next))",
        "if (Array.isArray(v)) return Array.from(v, x => enc(x, next))",
    ),
    ("kind: v.constructor.name,", "kind: __raTypedName.call(v),"),
    (
        "const plain = Object.fromEntries(",
        "if (Object.prototype.toString.call(v) !== '[object Object]' || typeof v.toJSON === 'function') throw new Error('not data')\n  const plain = Object.fromEntries(",
    ),
];

const NOT_DATA: &str = "throw new Error('not data')";

/// The `enc` of `CODEC_JS`, which `record` uses, for the capture hook, changed as
/// `JS_CAPTURE_ENC` says. It runs inside the user's module: its names take a `__ra` prefix so
/// they cannot shadow a wrapped function of the same name, and the built-ins it uses are read
/// from `globalThis` so the module's own names cannot shadow them. Strings and comments are left
/// as they are.
fn js_codec() -> String {
    let codec = crate::harness::CODEC_JS;
    let end = codec.find("\nconst dec = ").unwrap_or(codec.len());
    let enc = JS_CAPTURE_ENC
        .iter()
        .fold(codec[..end].to_string(), |enc, (from, to)| {
            enc.replace(from, to)
        });
    js_names()
        .replace_all(&enc, |c: &regex::Captures| {
            match c.get(1).map(|m| m.as_str()) {
                None => c[0].to_string(),
                Some("enc") => "__raEnc".to_string(),
                Some("MARKERS") => "__raMarkers".to_string(),
                Some("looksLikeMarker") => "__raLooksLikeMarker".to_string(),
                Some(global) => format!("globalThis.{global}"),
            }
        })
        .into_owned()
}

/// The built-ins the codec uses.
const JS_GLOBALS: &str =
    "Array|ArrayBuffer|Buffer|DataView|Date|Error|Map|Number|Object|RegExp|Set|String|Uint8Array";

/// The codec's own names and the built-ins it uses, outside strings and `//` comments (those
/// match whole, without a group).
fn js_names() -> regex::Regex {
    regex::Regex::new(&format!(
        r"'[^']*'|//[^\n]*|\b(enc|MARKERS|looksLikeMarker|{JS_GLOBALS})\b"
    ))
    .expect("valid regex")
}

fn python_hook() -> String {
    let driver = crate::harness_py::DRIVER_PY;
    let enc = driver
        .find("def enc(")
        .and_then(|start| {
            driver[start..]
                .find("\ndef dec(")
                .map(|end| &driver[start..start + end])
        })
        .unwrap_or("def enc(v, stack=()):\n    return v\n");
    let tail = PY_HOOK_TAIL
        .replace("__MAX_SEEN__", &MAX_SEEN_PER_FN.to_string())
        .replace("__MAX_SEEN_BYTES__", &MAX_SEEN_BYTES.to_string())
        .replace("__DEFAULT_CAP__", &DEFAULT_MAX_BYTES.to_string());
    format!("{PY_HOOK_HEAD}\n{enc}\n{tail}")
}

const PY_HOOK_HEAD: &str = r#"# rust-anything record --from-tests: wraps the unit's functions when their module loads.
import atexit
import functools
import importlib.abc
import importlib.machinery
import inspect
import json
import math
import os
import sys
import threading

BIG = 2 ** 53
"#;

const PY_HOOK_TAIL: &str = r#"
_OUT = os.environ.get("RUST_ANYTHING_CAPTURE")
_WANT = json.loads(os.environ.get("RUST_ANYTHING_CAPTURE_FUNCS") or "{}")
_MAX_SEEN = __MAX_SEEN__
_MAX_SEEN_BYTES = __MAX_SEEN_BYTES__
try:
    _CAP = int(os.environ.get("RUST_ANYTHING_CAPTURE_MAX_BYTES") or __DEFAULT_CAP__)
    if _CAP <= 0:
        _CAP = __DEFAULT_CAP__
except ValueError:
    _CAP = __DEFAULT_CAP__
_LOCK = threading.Lock()
_SEEN = {}
_FH = None
_PID = None
_SEEN_BYTES = 0
_CAPPED = False


def _close():
    global _FH
    with _LOCK:
        if _FH is not None:
            try:
                _FH.flush()
                _FH.close()
            except Exception:
                pass
            _FH = None


atexit.register(_close)


def _record_line(name, line):
    global _FH, _PID, _SEEN_BYTES, _CAPPED
    with _LOCK:
        if _CAPPED or not _OUT:
            return
        pid = os.getpid()
        if _PID != pid:
            if _FH is not None:
                try:
                    _FH.close()
                except Exception:
                    pass
                _FH = None
            _PID = pid
        seen = _SEEN.get(name)
        if seen is None:
            seen = set()
            _SEEN[name] = seen
        if line in seen:
            return
        nbytes = len(line.encode("utf-8")) + 1
        if len(seen) < _MAX_SEEN and _SEEN_BYTES < _MAX_SEEN_BYTES:
            seen.add(line)
            _SEEN_BYTES += nbytes
        if _FH is None:
            _FH = open(_OUT, "a", encoding="utf-8", newline="\n", buffering=1)
        if os.fstat(_FH.fileno()).st_size + nbytes > _CAP:
            _CAPPED = True
            _FH.write('{"__ra_capped":true}\n')
            return
        _FH.write(line + "\n")


def _wrap(name, orig):
    try:
        sig = inspect.signature(orig)
    except (TypeError, ValueError):
        sig = None

    @functools.wraps(orig)
    def wrapped(*args, **kwargs):
        # Deduplicated identical calls stay in memory; distinct calls write through the open handle
        # up to `_CAP` bytes, and the reservoir in `record` samples across the run (issue #1071).
        if sig is not None and not _CAPPED:
            try:
                bound = sig.bind(*args, **kwargs)
                case = {"fn": name, "args": enc(list(bound.args))}
                # Keyword-only arguments, and those named after a skipped default.
                if bound.kwargs:
                    case["kwargs"] = {k: enc(v) for k, v in bound.kwargs.items()}
                line = json.dumps(case, ensure_ascii=False, allow_nan=False)
                _record_line(name, line)
            except Exception:
                pass
        return orig(*args, **kwargs)

    return wrapped


class _Loader(importlib.abc.Loader):
    def __init__(self, inner, names):
        self.inner = inner
        self.names = names

    def create_module(self, spec):
        return self.inner.create_module(spec)

    def exec_module(self, module):
        self.inner.exec_module(module)
        for name in self.names:
            orig = getattr(module, name, None)
            if callable(orig):
                setattr(module, name, _wrap(name, orig))


class _Finder(importlib.abc.MetaPathFinder):
    def find_spec(self, fullname, path, target=None):
        spec = importlib.machinery.PathFinder.find_spec(fullname, path)
        if spec is None or spec.origin is None or spec.loader is None:
            return None
        names = _WANT.get(os.path.realpath(spec.origin))
        if not names:
            return None
        spec.loader = _Loader(spec.loader, names)
        return spec


if _OUT and _WANT:
    sys.meta_path.insert(0, _Finder())
"#;

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

    const LIB: &str = "export function add(a: number, b: number): number {\n  return a + b\n}\n";

    fn unit(name: &str, source: &str) -> (PathBuf, Manifest) {
        let root = std::env::temp_dir().join(format!(
            "rust-anything-from-tests-{name}-{}",
            std::process::id()
        ));
        let _ = std::fs::remove_dir_all(&root);
        std::fs::create_dir_all(&root).unwrap();
        std::fs::write(root.join("lib.ts"), source).unwrap();
        let manifest = Manifest {
            schema: String::new(),
            root: root.clone(),
            root_written: None,
            unit: "lib.ts".into(),
            language: Lang::Ts,
            kind: crate::bridge::Kind::Napi,
            crate_name: "lib-rs".into(),
            exports: vec![crate::ts::exports::ExportedFn {
                name: "add".into(),
                file: "lib.ts".into(),
                line: 1,
                ..Default::default()
            }],
            classes: Vec::new(),
            js_only: Vec::new(),
            batches: Vec::new(),
            allocator: Default::default(),
            float_tolerance: None,
            ignore_key_order: false,
            messages: false,
            end_state: None,
        };
        (root.join("lib.ts"), manifest)
    }

    fn read(path: &Path) -> String {
        std::fs::read_to_string(path).unwrap()
    }

    /// A run killed in its tests: no `Drop` runs, so the capture block and the backup stay.
    fn killed_run(m: &Manifest) {
        let mut run = instrument_js(m, &mut Vec::new()).unwrap();
        run.files.clear();
    }

    #[cfg(unix)]
    #[test]
    fn two_names_for_one_source_share_one_lock_and_both_are_wrapped() {
        let source = format!(
            "{LIB}export function sub(a: number, b: number): number {{\n  return a - b\n}}\n"
        );
        let (path, mut m) = unit("symlinked", &source);
        std::os::unix::fs::symlink(&path, m.root.join("alias.ts")).unwrap();
        m.exports.push(crate::ts::exports::ExportedFn {
            name: "sub".into(),
            file: "alias.ts".into(),
            line: 4,
            ..Default::default()
        });
        let (tx, rx) = std::sync::mpsc::channel();
        let root = m.root.clone();
        std::thread::spawn(move || {
            let run = instrument_js(&m, &mut Vec::new()).map(|_| read(&path));
            let _ = tx.send(run.map_err(|e| e.to_string()));
        });
        let text = rx.recv_timeout(std::time::Duration::from_secs(20));
        let _ = std::fs::remove_dir_all(root);
        let text = text.expect("the capture waited on its own lock").unwrap();
        assert!(text.contains("add = __raWrap('add', add)"), "{text}");
        assert!(text.contains("sub = __raWrap('sub', sub)"), "{text}");
    }

    #[test]
    fn a_killed_capture_never_puts_its_copy_over_newer_edits() {
        let (path, m) = unit("edited", LIB);
        killed_run(&m);
        assert!(read(&path).contains(CAPTURE_HEAD));
        let edited = format!(
            "{LIB}\nexport function mul(a: number, b: number): number {{\n  return a * b\n}}\n"
        );
        std::fs::write(&path, &edited).unwrap();
        let run = instrument_js(&m, &mut Vec::new()).unwrap();
        assert!(read(&path).contains("function mul"), "{}", read(&path));
        drop(run);
        assert_eq!(read(&path), edited);
        assert!(!backup_of(&path).exists());
        let _ = std::fs::remove_dir_all(m.root);
    }

    #[test]
    fn the_next_capture_puts_back_what_a_killed_one_changed() {
        let (path, m) = unit("untouched", LIB);
        killed_run(&m);
        let run = instrument_js(&m, &mut Vec::new()).unwrap();
        assert_eq!(read(&path).matches(CAPTURE_HEAD).count(), 1);
        drop(run);
        assert_eq!(read(&path), LIB);
        assert!(!backup_of(&path).exists());
        let _ = std::fs::remove_dir_all(m.root);
    }

    #[test]
    fn a_file_edited_with_a_stale_capture_block_is_left_for_the_user() {
        let (path, m) = unit("block-edited", LIB);
        killed_run(&m);
        let edited = format!("{}// mine\n", read(&path));
        std::fs::write(&path, &edited).unwrap();
        let err = instrument_js(&m, &mut Vec::new()).err().expect("refused");
        assert!(format!("{err:#}").contains("capture block"), "{err:#}");
        assert_eq!(read(&path), edited);
        assert_eq!(read(&backup_of(&path)), LIB);
        let _ = std::fs::remove_dir_all(m.root);
    }

    #[test]
    fn the_shebang_stays_the_first_line() {
        let source = format!("#!/usr/bin/env node\n{LIB}");
        let (path, m) = unit("shebang", &source);
        let run = instrument_js(&m, &mut Vec::new()).unwrap();
        assert!(
            read(&path).starts_with("#!/usr/bin/env node\n// @ts-nocheck\n"),
            "{}",
            read(&path)
        );
        drop(run);
        assert_eq!(read(&path), source);
        let _ = std::fs::remove_dir_all(m.root);
    }

    #[test]
    fn two_captures_of_one_file_take_turns() {
        let (path, m) = unit("two", LIB);
        let first = instrument_js(&m, &mut Vec::new()).unwrap();
        let (done_tx, done_rx) = std::sync::mpsc::channel();
        let second_m = m.clone();
        let second = std::thread::spawn(move || {
            let run = instrument_js(&second_m, &mut Vec::new()).unwrap();
            done_tx.send(()).unwrap();
            drop(run);
        });
        assert!(
            done_rx
                .recv_timeout(std::time::Duration::from_millis(100))
                .is_err(),
            "the second capture instrumented the file while the first ran"
        );
        drop(first);
        second.join().unwrap();
        assert_eq!(read(&path), LIB);
        assert!(!backup_of(&path).exists());
        let _ = std::fs::remove_dir_all(m.root);
    }

    #[test]
    fn the_reservoir_keeps_a_sample_of_the_whole_run() {
        // Issue #1071: the first 1,000 calls of a function that walks one source after another all
        // came from the first source. A reservoir keeps the sample spread over the run.
        let mut r = Reservoir::new("translate");
        for i in 0..PER_FUNCTION {
            r.offer(&format!("{{\"fn\":\"translate\",\"args\":[{i}]}}"));
        }
        assert_eq!(r.slots.len(), PER_FUNCTION, "the reservoir fills first");
        // Everything after the fill is a candidate for replacement.
        for i in PER_FUNCTION..(PER_FUNCTION * 4) {
            r.offer(&format!("{{\"fn\":\"translate\",\"args\":[{i}]}}"));
        }
        assert_eq!(r.slots.len(), PER_FUNCTION, "and never grows");
        let kept: Vec<usize> = r
            .slots
            .iter()
            .filter_map(|l| {
                l.split_once("args\":[")
                    .and_then(|(_, rest)| rest.split(']').next())
            })
            .filter_map(|n| n.parse().ok())
            .collect();
        assert_eq!(kept.len(), PER_FUNCTION);
        let late = kept.iter().filter(|i| **i >= PER_FUNCTION).count();
        // Three quarters of the run is after the fill, so most of the sample has to come from there:
        // keeping the first N would give 0.
        assert!(
            late > PER_FUNCTION / 2,
            "{late} of {} came from the tail",
            kept.len()
        );
    }

    #[test]
    fn the_reservoir_is_reproducible_for_the_same_function() {
        let draw = || {
            let mut r = Reservoir::new("slug");
            for i in 0..(PER_FUNCTION * 2) {
                r.offer(&format!("{i}"));
            }
            r.slots
        };
        assert_eq!(draw(), draw(), "the same name keeps the same sample");
    }

    /// `CODEC_JS` and the capture hook's copy of its `enc` must not drift apart in silence.
    #[test]
    fn the_capture_codec_is_the_record_codec_with_its_changes() {
        let codec = crate::harness::CODEC_JS;
        let end = codec.find("\nconst dec = ").expect("CODEC_JS defines dec");
        for (from, _) in JS_CAPTURE_ENC {
            let found = codec[..end].matches(from).count();
            assert_eq!(found, 1, "enc no longer has {from:?}");
        }
        assert!(JS_CAPTURE.starts_with(CAPTURE_HEAD) && JS_CAPTURE.ends_with(CAPTURE_TAIL));
        let capture = js_codec();
        for marker in ["$function", "$symbol", "$cycle", "$regexp", "$error"] {
            assert!(!capture.contains(marker), "{marker} is written:\n{capture}");
        }
        // Every top-level name is prefixed, and nothing after `enc` came along.
        let declared: Vec<&str> = capture
            .lines()
            .filter_map(|l| l.strip_prefix("const "))
            .filter_map(|l| l.split([' ', '=']).next())
            .collect();
        let prefixed = ["__raEnc", "__raMarkers", "__raLooksLikeMarker"];
        assert_eq!(declared, prefixed, "{capture}");
        // Built-ins outside strings and comments are read from `globalThis`; strings stay.
        let globals = regex::Regex::new(&format!(
            r"'[^']*'|//[^\n]*|(globalThis\.)?\b(enc|{JS_GLOBALS})\b"
        ))
        .unwrap();
        for c in globals.captures_iter(&capture) {
            let bare = c.get(2).is_some() && c.get(1).is_none();
            assert!(!bare, "bare {}:\n{capture}", &c[0]);
        }
        assert!(capture.contains("'[object Object]'"), "{capture}");
    }

    fn have_node() -> bool {
        Command::new("node")
            .arg("--version")
            .output()
            .is_ok_and(|o| o.status.success())
    }

    fn find_python() -> Option<&'static str> {
        ["python3", "python"].into_iter().find(|p| {
            Command::new(p)
                .arg("--version")
                .output()
                .is_ok_and(|o| o.status.success())
        })
    }

    fn save_manifest(crate_dir: &Path, m: &Manifest) {
        std::fs::create_dir_all(crate_dir).unwrap();
        m.save(crate_dir).unwrap();
    }

    #[test]
    fn parses_and_formats_byte_caps() {
        assert_eq!(parse_max_bytes(None), DEFAULT_MAX_BYTES);
        assert_eq!(parse_max_bytes(Some("")), DEFAULT_MAX_BYTES);
        assert_eq!(parse_max_bytes(Some("0")), DEFAULT_MAX_BYTES);
        assert_eq!(parse_max_bytes(Some("nope")), DEFAULT_MAX_BYTES);
        assert_eq!(parse_max_bytes(Some(" 4096 ")), 4096);
        assert_eq!(format_bytes(1024 * 1024 * 1024), "1 GiB");
        assert_eq!(format_bytes(2 * 1024 * 1024), "2 MiB");
        assert_eq!(format_bytes(4096), "4 KiB");
        assert_eq!(format_bytes(1500), "1500 B");
    }

    #[test]
    fn js_hook_deduplicates_repeated_calls() {
        if !have_node() {
            return;
        }
        let (_, m) = unit("js-dedup", LIB);
        std::fs::write(m.root.join("package.json"), r#"{"type":"module"}"#).unwrap();
        std::fs::write(
            m.root.join("test.ts"),
            "import { add } from './lib.ts'\n\
             for (let i = 0; i < 100000; i++) add(1, 2)\n\
             for (let i = 0; i < 10; i++) add(1, 100 + i)\n",
        )
        .unwrap();
        let crate_dir = m.root.join("port");
        save_manifest(&crate_dir, &m);
        let (cap, stats) = capture_with_max_bytes(
            &crate_dir,
            &["node".into(), "test.ts".into()],
            DEFAULT_MAX_BYTES,
        )
        .unwrap();
        let _ = std::fs::remove_dir_all(&m.root);
        assert!(cap.tests_passed);
        assert_eq!(stats.lines, 11);
        assert_eq!(cap.per_function.get("add"), Some(&11));
        assert_eq!(cap.stopped_at_bytes, None);
        assert_eq!(cap.capped_notice(), None);
    }

    #[test]
    fn python_hook_deduplicates_repeated_calls() {
        let Some(py) = find_python() else {
            return;
        };
        let root = std::env::temp_dir().join(format!(
            "rust-anything-from-tests-py-dedup-{}",
            std::process::id()
        ));
        let _ = std::fs::remove_dir_all(&root);
        std::fs::create_dir_all(&root).unwrap();
        std::fs::write(
            root.join("lib.py"),
            "def add(a: int, b: int) -> int:\n    return a + b\n",
        )
        .unwrap();
        std::fs::write(
            root.join("test_add.py"),
            "from lib import add\n\
             for _ in range(100000):\n    add(1, 2)\n\
             for i in range(10):\n    add(1, 100 + i)\n",
        )
        .unwrap();
        let m = Manifest {
            schema: String::new(),
            root: root.clone(),
            root_written: None,
            unit: "lib.py".into(),
            language: Lang::Python,
            kind: crate::bridge::Kind::Pyo3,
            crate_name: "lib-rs".into(),
            exports: vec![crate::ts::exports::ExportedFn {
                name: "add".into(),
                file: "lib.py".into(),
                line: 1,
                ..Default::default()
            }],
            classes: Vec::new(),
            js_only: Vec::new(),
            batches: Vec::new(),
            allocator: Default::default(),
            float_tolerance: None,
            ignore_key_order: false,
            messages: false,
            end_state: None,
        };
        let crate_dir = root.join("port");
        save_manifest(&crate_dir, &m);
        let (cap, stats) = capture_with_max_bytes(
            &crate_dir,
            &[py.into(), "test_add.py".into()],
            DEFAULT_MAX_BYTES,
        )
        .unwrap();
        let _ = std::fs::remove_dir_all(&root);
        assert!(cap.tests_passed);
        assert_eq!(stats.lines, 11);
        assert_eq!(cap.per_function.get("add"), Some(&11));
        assert_eq!(cap.stopped_at_bytes, None);
        assert_eq!(cap.capped_notice(), None);
    }

    #[cfg(unix)]
    #[test]
    fn python_hook_keeps_forked_worker_calls_once() {
        let Some(py) = find_python() else {
            return;
        };
        let root = std::env::temp_dir().join(format!(
            "rust-anything-from-tests-py-fork-{}",
            std::process::id()
        ));
        let _ = std::fs::remove_dir_all(&root);
        std::fs::create_dir_all(&root).unwrap();
        std::fs::write(
            root.join("lib.py"),
            "def add(a: int, b: int) -> int:\n    return a + b\n",
        )
        .unwrap();
        std::fs::write(
            root.join("test_fork.py"),
            "import multiprocessing\n\
             from lib import add\n\
             add(1, 2)\n\
             p = multiprocessing.get_context('fork').Process(target=add, args=(3, 4))\n\
             p.start()\n\
             p.join()\n\
             assert p.exitcode == 0\n\
             add(5, 6)\n",
        )
        .unwrap();
        let m = Manifest {
            schema: String::new(),
            root: root.clone(),
            root_written: None,
            unit: "lib.py".into(),
            language: Lang::Python,
            kind: crate::bridge::Kind::Pyo3,
            crate_name: "lib-rs".into(),
            exports: vec![crate::ts::exports::ExportedFn {
                name: "add".into(),
                file: "lib.py".into(),
                line: 1,
                ..Default::default()
            }],
            classes: Vec::new(),
            js_only: Vec::new(),
            batches: Vec::new(),
            allocator: Default::default(),
            float_tolerance: None,
            ignore_key_order: false,
            messages: false,
            end_state: None,
        };
        let crate_dir = root.join("port");
        save_manifest(&crate_dir, &m);
        let (cap, stats) = capture_with_max_bytes(
            &crate_dir,
            &[py.into(), "test_fork.py".into()],
            DEFAULT_MAX_BYTES,
        )
        .unwrap();
        let _ = std::fs::remove_dir_all(&root);
        assert!(cap.tests_passed);
        assert_eq!(stats.lines, 3);
        assert_eq!(cap.per_function.get("add"), Some(&3));
    }

    #[test]
    fn capture_stops_at_byte_cap_and_reports_it() {
        const CAP: u64 = 4096;
        if have_node() {
            let source = "export function echo(s: string): string {\n  return s\n}\n";
            let (_, mut m) = unit("js-cap", source);
            m.exports[0].name = "echo".into();
            std::fs::write(m.root.join("package.json"), r#"{"type":"module"}"#).unwrap();
            std::fs::write(
                m.root.join("test.ts"),
                "import { echo } from './lib.ts'\n\
                 for (let i = 0; i < 500; i++) echo('item-' + String(i).padStart(4, '0') + '-xxxxxxxxxxxxxxxxxxxx')\n",
            )
            .unwrap();
            let crate_dir = m.root.join("port");
            save_manifest(&crate_dir, &m);
            let (cap, stats) =
                capture_with_max_bytes(&crate_dir, &["node".into(), "test.ts".into()], CAP)
                    .unwrap();
            let _ = std::fs::remove_dir_all(&m.root);
            assert!(cap.tests_passed);
            assert!(stats.bytes <= CAP + 64, "bytes={}", stats.bytes);
            assert!(
                stats.lines > 0 && stats.lines < 500,
                "lines={}",
                stats.lines
            );
            assert_eq!(cap.stopped_at_bytes, Some(CAP));
            assert_eq!(
                cap.capped_notice().as_deref(),
                Some("capture stopped at 4 KiB: later calls were not sampled")
            );
        }

        if let Some(py) = find_python() {
            let root = std::env::temp_dir().join(format!(
                "rust-anything-from-tests-py-cap-{}",
                std::process::id()
            ));
            let _ = std::fs::remove_dir_all(&root);
            std::fs::create_dir_all(&root).unwrap();
            std::fs::write(
                root.join("lib.py"),
                "def echo(s: str) -> str:\n    return s\n",
            )
            .unwrap();
            std::fs::write(
                root.join("test_cap.py"),
                "from lib import echo\n\
                 for i in range(500):\n    echo(f'item-{i:04d}-xxxxxxxxxxxxxxxxxxxx')\n",
            )
            .unwrap();
            let m = Manifest {
                schema: String::new(),
                root: root.clone(),
                root_written: None,
                unit: "lib.py".into(),
                language: Lang::Python,
                kind: crate::bridge::Kind::Pyo3,
                crate_name: "lib-rs".into(),
                exports: vec![crate::ts::exports::ExportedFn {
                    name: "echo".into(),
                    file: "lib.py".into(),
                    line: 1,
                    ..Default::default()
                }],
                classes: Vec::new(),
                js_only: Vec::new(),
                batches: Vec::new(),
                allocator: Default::default(),
                float_tolerance: None,
                ignore_key_order: false,
                messages: false,
                end_state: None,
            };
            let crate_dir = root.join("port");
            save_manifest(&crate_dir, &m);
            let (cap, stats) =
                capture_with_max_bytes(&crate_dir, &[py.into(), "test_cap.py".into()], CAP)
                    .unwrap();
            let _ = std::fs::remove_dir_all(&root);
            assert!(cap.tests_passed);
            assert!(stats.bytes <= CAP + 64, "bytes={}", stats.bytes);
            assert!(
                stats.lines > 0 && stats.lines < 500,
                "lines={}",
                stats.lines
            );
            assert_eq!(cap.stopped_at_bytes, Some(CAP));
            assert_eq!(
                cap.capped_notice().as_deref(),
                Some("capture stopped at 4 KiB: later calls were not sampled")
            );
        }
    }
}