Skip to main content

rust_anything/
fuzz.rs

1//! Live differential testing: fresh inputs from a new seed, run through the original and the
2//! port, mismatches reported and optionally kept in the recording.
3//!
4//! Every language's record and diff drivers read and write `cases.jsonl`, so a round records
5//! its fresh cases there, diffs them, and puts the recording back. Whatever happens, the file
6//! the round started from is restored before anything is kept.
7
8use std::collections::{BTreeMap, HashSet};
9use std::path::{Path, PathBuf};
10use std::time::{Duration, Instant};
11
12use anyhow::{Result, bail};
13use serde::Serialize;
14use serde_json::Value;
15
16use crate::bridge::Manifest;
17use crate::harness::{self, CASES, DiffOptions, RecordOptions, WORK_DIR};
18
19/// Which fresh cases `--keep` appends to the recording.
20#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, clap::ValueEnum)]
21#[serde(rename_all = "lowercase")]
22pub enum Keep {
23    /// Only the cases where the port differs from the original.
24    Mismatches,
25    /// Every fresh case.
26    All,
27}
28
29pub struct FuzzOptions<'a> {
30    pub crate_dir: &'a Path,
31    /// Fresh cases per function and class in each round.
32    pub cases: usize,
33    /// The first round's seed; later rounds count up from it. Random when `None`.
34    pub seed: Option<u64>,
35    /// Keep starting rounds until this much time has passed; one round when `None`.
36    pub time: Option<Duration>,
37    pub keep: Option<Keep>,
38    pub resolve_from: Option<&'a Path>,
39    pub node_args: &'a [String],
40}
41
42#[derive(Debug, Serialize)]
43pub struct FuzzOutcome {
44    /// Replays this run with `--seed`.
45    pub seed: u64,
46    pub rounds: u64,
47    /// Fresh cases run on both sides (inputs the original timed out on are left out).
48    pub cases: usize,
49    pub passed: usize,
50    pub failed: usize,
51    /// Exports the port does not provide.
52    pub missing: Vec<String>,
53    /// The first mismatches: `{ fn, args, expected, actual }`.
54    pub mismatches: Vec<Value>,
55    /// Cases appended to `cases.jsonl` (`--keep`).
56    pub kept: usize,
57    pub recording: PathBuf,
58}
59
60const SHOWN: usize = 20;
61
62/// Puts `cases.jsonl` and the timed-out list back as they were, also on an error.
63struct Restore(Vec<(PathBuf, Option<Vec<u8>>)>);
64
65impl Restore {
66    fn new(paths: &[PathBuf]) -> Self {
67        Self(
68            paths
69                .iter()
70                .map(|p| (p.clone(), std::fs::read(p).ok()))
71                .collect(),
72        )
73    }
74}
75
76impl Drop for Restore {
77    fn drop(&mut self) {
78        for (path, saved) in &self.0 {
79            let _ = match saved {
80                Some(bytes) => std::fs::write(path, bytes),
81                None => std::fs::remove_file(path),
82            };
83        }
84    }
85}
86
87fn splitmix(mut x: u64) -> u64 {
88    x = x.wrapping_add(0x9E37_79B9_7F4A_7C15);
89    x = (x ^ (x >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
90    x = (x ^ (x >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
91    x ^ (x >> 31)
92}
93
94fn random_seed() -> u64 {
95    let nanos = std::time::SystemTime::now()
96        .duration_since(std::time::UNIX_EPOCH)
97        .map_or(0, |d| d.as_nanos());
98    splitmix((nanos as u64) ^ u64::from(std::process::id())) % 1_000_000_000
99}
100
101/// Numbers compared by value and object keys sorted, so the same value from two runtimes (`1`
102/// and `1.0`, or the keys of one object in a different order) is one key.
103fn norm(v: &Value) -> Value {
104    match v {
105        Value::Number(n) => n
106            .as_f64()
107            .and_then(serde_json::Number::from_f64)
108            .map_or_else(|| v.clone(), Value::Number),
109        Value::Array(a) => Value::Array(a.iter().map(norm).collect()),
110        Value::Object(o) => Value::Object(
111            o.iter()
112                .map(|(k, x)| (k.clone(), norm(x)))
113                .collect::<BTreeMap<_, _>>()
114                .into_iter()
115                .collect(),
116        ),
117        other => other.clone(),
118    }
119}
120
121fn key(name: &Value, args: &Value) -> String {
122    serde_json::to_string(&(norm(name), norm(args))).unwrap_or_default()
123}
124
125/// The keys a case can be reported under by the language drivers' mismatches: the function
126/// and its arguments (with keyword arguments appended, as Ruby shows them), or the class with
127/// its constructor arguments and calls.
128fn case_keys(c: &Value) -> Vec<String> {
129    if let Some(class) = c.get("class") {
130        return vec![key(
131            class,
132            &Value::Array(vec![c["ctor"].clone(), c["calls"].clone()]),
133        )];
134    }
135    let mut keys = vec![key(&c["fn"], &c["args"])];
136    if let (Some(args), Some(kwargs)) = (
137        c["args"].as_array(),
138        c.get("kwargs")
139            .filter(|k| k.as_object().is_some_and(|o| !o.is_empty())),
140    ) {
141        let mut shown = args.clone();
142        shown.push(kwargs.clone());
143        keys.push(key(&c["fn"], &Value::Array(shown)));
144    }
145    keys
146}
147
148fn lines(text: &str) -> impl Iterator<Item = (&str, Value)> {
149    text.lines()
150        .filter(|l| !l.trim().is_empty())
151        .filter_map(|l| harness::parse_deep(l).ok().map(|v| (l, v)))
152}
153
154pub fn fuzz(opts: &FuzzOptions) -> Result<FuzzOutcome> {
155    let crate_dir = std::path::absolute(opts.crate_dir)?;
156    let manifest = Manifest::load(&crate_dir)?;
157    crate::harness::ensure_built(&crate_dir, &manifest)?;
158    if opts.cases == 0 {
159        bail!("`--cases` must be at least 1");
160    }
161    let seed = opts.seed.unwrap_or_else(random_seed);
162    let recording = crate_dir.join(CASES);
163    let original = std::fs::read_to_string(&recording).unwrap_or_default();
164    let mut seen: HashSet<String> = lines(&original)
165        .filter_map(|(_, c)| case_keys(&c).into_iter().next())
166        .collect();
167    let record_opts = RecordOptions {
168        crate_dir: &crate_dir,
169        count: opts.cases,
170        inputs: None,
171        module: None,
172        resolve_from: opts.resolve_from,
173        node_args: opts.node_args,
174    };
175    let diff_opts = DiffOptions {
176        crate_dir: &crate_dir,
177        module: None,
178        ignore_key_order: false,
179        node_args: opts.node_args,
180        float_tolerance: None,
181    };
182    let mut outcome = FuzzOutcome {
183        seed,
184        rounds: 0,
185        cases: 0,
186        passed: 0,
187        failed: 0,
188        missing: Vec::new(),
189        mismatches: Vec::new(),
190        kept: 0,
191        recording: recording.clone(),
192    };
193    let mut keep = String::new();
194    let started = Instant::now();
195    {
196        let _restore = Restore::new(&[
197            recording.clone(),
198            crate_dir.join(WORK_DIR).join(harness::TIMED_OUT),
199        ]);
200        loop {
201            let salt = splitmix(seed.wrapping_add(outcome.rounds)) | 0x100;
202            outcome.rounds += 1;
203            let (generated, _, _) = harness::generate_cases_salted(&record_opts, &manifest, salt)?;
204            let fresh: Vec<Value> = generated
205                .into_iter()
206                .filter(|c| {
207                    case_keys(c)
208                        .into_iter()
209                        .next()
210                        .is_some_and(|k| seen.insert(k))
211                })
212                .collect();
213            if fresh.is_empty() {
214                break;
215            }
216            harness::record_with(&record_opts, &manifest, &fresh)?;
217            let ran = std::fs::read_to_string(&recording).unwrap_or_default();
218            let d = harness::settle(&diff_opts, harness::diff_exact(&diff_opts)?)?;
219            outcome.cases += d.total;
220            outcome.passed += d.passed;
221            outcome.failed += d.failed;
222            for m in &d.missing {
223                if !outcome.missing.contains(m) {
224                    outcome.missing.push(m.clone());
225                }
226            }
227            let failing: HashSet<String> = d
228                .mismatches
229                .iter()
230                .map(|m| key(&m["fn"], &m["args"]))
231                .collect();
232            for (line, c) in lines(&ran) {
233                let wanted = match opts.keep {
234                    Some(Keep::All) => true,
235                    Some(Keep::Mismatches) => case_keys(&c).iter().any(|k| failing.contains(k)),
236                    None => false,
237                };
238                if wanted {
239                    keep.push_str(line);
240                    keep.push('\n');
241                    outcome.kept += 1;
242                }
243            }
244            let room = SHOWN.saturating_sub(outcome.mismatches.len());
245            outcome
246                .mismatches
247                .extend(d.mismatches.into_iter().take(room));
248            if opts.time.is_none_or(|budget| started.elapsed() >= budget) {
249                break;
250            }
251        }
252    }
253    let _ = std::fs::remove_dir_all(crate_dir.join(WORK_DIR).join("coverage"));
254    if !keep.is_empty() {
255        let mut text = original;
256        if !text.is_empty() && !text.ends_with('\n') {
257            text.push('\n');
258        }
259        text.push_str(&keep);
260        std::fs::write(&recording, text)?;
261    }
262    Ok(outcome)
263}
264
265#[cfg(test)]
266mod tests {
267    use super::*;
268    use serde_json::json;
269
270    #[test]
271    fn mismatches_find_their_cases_across_driver_shapes() {
272        let ruby = json!({ "fn": "f", "args": [1, "a"], "kwargs": { "sep": "-" }, "ok": 2 });
273        let shown = json!({ "fn": "f", "args": [1.0, "a", { "sep": "-" }] });
274        assert!(case_keys(&ruby).contains(&key(&shown["fn"], &shown["args"])));
275        let class = json!({ "class": "C", "ctor": [1], "calls": [], "results": [] });
276        let reported = json!({ "fn": "C", "args": [[1], []] });
277        assert_eq!(
278            case_keys(&class),
279            vec![key(&reported["fn"], &reported["args"])]
280        );
281    }
282
283    #[test]
284    fn a_case_key_ignores_the_order_of_object_keys() {
285        // The original and the port are different runtimes: the same value comes back with its
286        // keys in a different order, and a case must still match its own report.
287        let left = json!({ "fn": "f", "args": [{ "a": 1, "b": [2, { "c": 3, "d": 4 }] }] });
288        let right = json!({ "fn": "f", "args": [{ "b": [2, { "d": 4, "c": 3 }], "a": 1 }] });
289        assert_eq!(
290            key(&left["fn"], &left["args"]),
291            key(&right["fn"], &right["args"])
292        );
293    }
294
295    #[test]
296    fn restore_puts_files_back_or_removes_new_ones() {
297        let dir =
298            std::env::temp_dir().join(format!("rust-anything-restore-{}", std::process::id()));
299        std::fs::create_dir_all(&dir).unwrap();
300        let kept = dir.join("a");
301        let fresh = dir.join("b");
302        std::fs::write(&kept, "old").unwrap();
303        {
304            let _r = Restore::new(&[kept.clone(), fresh.clone()]);
305            std::fs::write(&kept, "new").unwrap();
306            std::fs::write(&fresh, "new").unwrap();
307        }
308        assert_eq!(std::fs::read_to_string(&kept).unwrap(), "old");
309        assert!(!fresh.exists());
310        std::fs::remove_dir_all(&dir).unwrap();
311    }
312}