1use 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#[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 {
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
125fn 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 if opts.cases == 0 {
158 bail!("`--cases` must be at least 1");
159 }
160 let seed = opts.seed.unwrap_or_else(random_seed);
161 let recording = crate_dir.join(CASES);
162 let original = std::fs::read_to_string(&recording).unwrap_or_default();
163 let mut seen: HashSet<String> = lines(&original)
164 .filter_map(|(_, c)| case_keys(&c).into_iter().next())
165 .collect();
166 let record_opts = RecordOptions {
167 crate_dir: &crate_dir,
168 count: opts.cases,
169 inputs: None,
170 module: None,
171 resolve_from: opts.resolve_from,
172 node_args: opts.node_args,
173 };
174 let diff_opts = DiffOptions {
175 crate_dir: &crate_dir,
176 module: None,
177 ignore_key_order: false,
178 node_args: opts.node_args,
179 float_tolerance: None,
180 };
181 let mut outcome = FuzzOutcome {
182 seed,
183 rounds: 0,
184 cases: 0,
185 passed: 0,
186 failed: 0,
187 missing: Vec::new(),
188 mismatches: Vec::new(),
189 kept: 0,
190 recording: recording.clone(),
191 };
192 let mut keep = String::new();
193 let started = Instant::now();
194 {
195 let _restore = Restore::new(&[
196 recording.clone(),
197 crate_dir.join(WORK_DIR).join(harness::TIMED_OUT),
198 ]);
199 loop {
200 let salt = splitmix(seed.wrapping_add(outcome.rounds)) | 0x100;
201 outcome.rounds += 1;
202 let (generated, _, _) = harness::generate_cases_salted(&record_opts, &manifest, salt)?;
203 let fresh: Vec<Value> = generated
204 .into_iter()
205 .filter(|c| {
206 case_keys(c)
207 .into_iter()
208 .next()
209 .is_some_and(|k| seen.insert(k))
210 })
211 .collect();
212 if fresh.is_empty() {
213 break;
214 }
215 harness::record_with(&record_opts, &manifest, &fresh)?;
216 let ran = std::fs::read_to_string(&recording).unwrap_or_default();
217 let d = harness::settle(&diff_opts, harness::diff_exact(&diff_opts)?)?;
218 outcome.cases += d.total;
219 outcome.passed += d.passed;
220 outcome.failed += d.failed;
221 for m in &d.missing {
222 if !outcome.missing.contains(m) {
223 outcome.missing.push(m.clone());
224 }
225 }
226 let failing: HashSet<String> = d
227 .mismatches
228 .iter()
229 .map(|m| key(&m["fn"], &m["args"]))
230 .collect();
231 for (line, c) in lines(&ran) {
232 let wanted = match opts.keep {
233 Some(Keep::All) => true,
234 Some(Keep::Mismatches) => case_keys(&c).iter().any(|k| failing.contains(k)),
235 None => false,
236 };
237 if wanted {
238 keep.push_str(line);
239 keep.push('\n');
240 outcome.kept += 1;
241 }
242 }
243 let room = SHOWN.saturating_sub(outcome.mismatches.len());
244 outcome
245 .mismatches
246 .extend(d.mismatches.into_iter().take(room));
247 if opts.time.is_none_or(|budget| started.elapsed() >= budget) {
248 break;
249 }
250 }
251 }
252 let _ = std::fs::remove_dir_all(crate_dir.join(WORK_DIR).join("coverage"));
253 if !keep.is_empty() {
254 let mut text = original;
255 if !text.is_empty() && !text.ends_with('\n') {
256 text.push('\n');
257 }
258 text.push_str(&keep);
259 std::fs::write(&recording, text)?;
260 }
261 Ok(outcome)
262}
263
264#[cfg(test)]
265mod tests {
266 use super::*;
267 use serde_json::json;
268
269 #[test]
270 fn mismatches_find_their_cases_across_driver_shapes() {
271 let ruby = json!({ "fn": "f", "args": [1, "a"], "kwargs": { "sep": "-" }, "ok": 2 });
272 let shown = json!({ "fn": "f", "args": [1.0, "a", { "sep": "-" }] });
273 assert!(case_keys(&ruby).contains(&key(&shown["fn"], &shown["args"])));
274 let class = json!({ "class": "C", "ctor": [1], "calls": [], "results": [] });
275 let reported = json!({ "fn": "C", "args": [[1], []] });
276 assert_eq!(
277 case_keys(&class),
278 vec![key(&reported["fn"], &reported["args"])]
279 );
280 }
281
282 #[test]
283 fn a_case_key_ignores_the_order_of_object_keys() {
284 let left = json!({ "fn": "f", "args": [{ "a": 1, "b": [2, { "c": 3, "d": 4 }] }] });
287 let right = json!({ "fn": "f", "args": [{ "b": [2, { "d": 4, "c": 3 }], "a": 1 }] });
288 assert_eq!(
289 key(&left["fn"], &left["args"]),
290 key(&right["fn"], &right["args"])
291 );
292 }
293
294 #[test]
295 fn restore_puts_files_back_or_removes_new_ones() {
296 let dir =
297 std::env::temp_dir().join(format!("rust-anything-restore-{}", std::process::id()));
298 std::fs::create_dir_all(&dir).unwrap();
299 let kept = dir.join("a");
300 let fresh = dir.join("b");
301 std::fs::write(&kept, "old").unwrap();
302 {
303 let _r = Restore::new(&[kept.clone(), fresh.clone()]);
304 std::fs::write(&kept, "new").unwrap();
305 std::fs::write(&fresh, "new").unwrap();
306 }
307 assert_eq!(std::fs::read_to_string(&kept).unwrap(), "old");
308 assert!(!fresh.exists());
309 std::fs::remove_dir_all(&dir).unwrap();
310 }
311}