1use std::collections::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#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, clap::ValueEnum)]
21#[serde(rename_all = "lowercase")]
22pub enum Keep {
23 Mismatches,
25 All,
27}
28
29pub struct FuzzOptions<'a> {
30 pub crate_dir: &'a Path,
31 pub cases: usize,
33 pub seed: Option<u64>,
35 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 pub seed: u64,
46 pub rounds: u64,
47 pub cases: usize,
49 pub passed: usize,
50 pub failed: usize,
51 pub missing: Vec<String>,
53 pub mismatches: Vec<Value>,
55 pub kept: usize,
57 pub recording: PathBuf,
58}
59
60const SHOWN: usize = 20;
61
62struct 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
101fn norm(v: &Value) -> Value {
103 match v {
104 Value::Number(n) => n
105 .as_f64()
106 .and_then(serde_json::Number::from_f64)
107 .map_or_else(|| v.clone(), Value::Number),
108 Value::Array(a) => Value::Array(a.iter().map(norm).collect()),
109 Value::Object(o) => Value::Object(o.iter().map(|(k, x)| (k.clone(), norm(x))).collect()),
110 other => other.clone(),
111 }
112}
113
114fn key(name: &Value, args: &Value) -> String {
115 serde_json::to_string(&(norm(name), norm(args))).unwrap_or_default()
116}
117
118fn case_keys(c: &Value) -> Vec<String> {
122 if let Some(class) = c.get("class") {
123 return vec![key(
124 class,
125 &Value::Array(vec![c["ctor"].clone(), c["calls"].clone()]),
126 )];
127 }
128 let mut keys = vec![key(&c["fn"], &c["args"])];
129 if let (Some(args), Some(kwargs)) = (
130 c["args"].as_array(),
131 c.get("kwargs")
132 .filter(|k| k.as_object().is_some_and(|o| !o.is_empty())),
133 ) {
134 let mut shown = args.clone();
135 shown.push(kwargs.clone());
136 keys.push(key(&c["fn"], &Value::Array(shown)));
137 }
138 keys
139}
140
141fn lines(text: &str) -> impl Iterator<Item = (&str, Value)> {
142 text.lines()
143 .filter(|l| !l.trim().is_empty())
144 .filter_map(|l| harness::parse_deep(l).ok().map(|v| (l, v)))
145}
146
147pub fn fuzz(opts: &FuzzOptions) -> Result<FuzzOutcome> {
148 let crate_dir = std::path::absolute(opts.crate_dir)?;
149 let manifest = Manifest::load(&crate_dir)?;
150 if opts.cases == 0 {
151 bail!("`--cases` must be at least 1");
152 }
153 let seed = opts.seed.unwrap_or_else(random_seed);
154 let recording = crate_dir.join(CASES);
155 let original = std::fs::read_to_string(&recording).unwrap_or_default();
156 let mut seen: HashSet<String> = lines(&original)
157 .filter_map(|(_, c)| case_keys(&c).into_iter().next())
158 .collect();
159 let record_opts = RecordOptions {
160 crate_dir: &crate_dir,
161 count: opts.cases,
162 inputs: None,
163 module: None,
164 resolve_from: opts.resolve_from,
165 node_args: opts.node_args,
166 };
167 let diff_opts = DiffOptions {
168 crate_dir: &crate_dir,
169 module: None,
170 ignore_key_order: false,
171 node_args: opts.node_args,
172 float_tolerance: None,
173 };
174 let mut outcome = FuzzOutcome {
175 seed,
176 rounds: 0,
177 cases: 0,
178 passed: 0,
179 failed: 0,
180 missing: Vec::new(),
181 mismatches: Vec::new(),
182 kept: 0,
183 recording: recording.clone(),
184 };
185 let mut keep = String::new();
186 let started = Instant::now();
187 {
188 let _restore = Restore::new(&[
189 recording.clone(),
190 crate_dir.join(WORK_DIR).join(harness::TIMED_OUT),
191 ]);
192 loop {
193 let salt = splitmix(seed.wrapping_add(outcome.rounds)) | 0x100;
194 outcome.rounds += 1;
195 let (generated, _, _) = harness::generate_cases_salted(&record_opts, &manifest, salt)?;
196 let fresh: Vec<Value> = generated
197 .into_iter()
198 .filter(|c| {
199 case_keys(c)
200 .into_iter()
201 .next()
202 .is_some_and(|k| seen.insert(k))
203 })
204 .collect();
205 if fresh.is_empty() {
206 break;
207 }
208 harness::record_with(&record_opts, &manifest, &fresh)?;
209 let ran = std::fs::read_to_string(&recording).unwrap_or_default();
210 let d = harness::settle(&diff_opts, harness::diff_exact(&diff_opts)?)?;
211 outcome.cases += d.total;
212 outcome.passed += d.passed;
213 outcome.failed += d.failed;
214 for m in &d.missing {
215 if !outcome.missing.contains(m) {
216 outcome.missing.push(m.clone());
217 }
218 }
219 let failing: HashSet<String> = d
220 .mismatches
221 .iter()
222 .map(|m| key(&m["fn"], &m["args"]))
223 .collect();
224 for (line, c) in lines(&ran) {
225 let wanted = match opts.keep {
226 Some(Keep::All) => true,
227 Some(Keep::Mismatches) => case_keys(&c).iter().any(|k| failing.contains(k)),
228 None => false,
229 };
230 if wanted {
231 keep.push_str(line);
232 keep.push('\n');
233 outcome.kept += 1;
234 }
235 }
236 let room = SHOWN.saturating_sub(outcome.mismatches.len());
237 outcome
238 .mismatches
239 .extend(d.mismatches.into_iter().take(room));
240 if opts.time.is_none_or(|budget| started.elapsed() >= budget) {
241 break;
242 }
243 }
244 }
245 let _ = std::fs::remove_dir_all(crate_dir.join(WORK_DIR).join("coverage"));
246 if !keep.is_empty() {
247 let mut text = original;
248 if !text.is_empty() && !text.ends_with('\n') {
249 text.push('\n');
250 }
251 text.push_str(&keep);
252 std::fs::write(&recording, text)?;
253 }
254 Ok(outcome)
255}
256
257#[cfg(test)]
258mod tests {
259 use super::*;
260 use serde_json::json;
261
262 #[test]
263 fn mismatches_find_their_cases_across_driver_shapes() {
264 let ruby = json!({ "fn": "f", "args": [1, "a"], "kwargs": { "sep": "-" }, "ok": 2 });
265 let shown = json!({ "fn": "f", "args": [1.0, "a", { "sep": "-" }] });
266 assert!(case_keys(&ruby).contains(&key(&shown["fn"], &shown["args"])));
267 let class = json!({ "class": "C", "ctor": [1], "calls": [], "results": [] });
268 let reported = json!({ "fn": "C", "args": [[1], []] });
269 assert_eq!(
270 case_keys(&class),
271 vec![key(&reported["fn"], &reported["args"])]
272 );
273 }
274
275 #[test]
276 fn restore_puts_files_back_or_removes_new_ones() {
277 let dir =
278 std::env::temp_dir().join(format!("rust-anything-restore-{}", std::process::id()));
279 std::fs::create_dir_all(&dir).unwrap();
280 let kept = dir.join("a");
281 let fresh = dir.join("b");
282 std::fs::write(&kept, "old").unwrap();
283 {
284 let _r = Restore::new(&[kept.clone(), fresh.clone()]);
285 std::fs::write(&kept, "new").unwrap();
286 std::fs::write(&fresh, "new").unwrap();
287 }
288 assert_eq!(std::fs::read_to_string(&kept).unwrap(), "old");
289 assert!(!fresh.exists());
290 std::fs::remove_dir_all(&dir).unwrap();
291 }
292}