1use std::collections::BTreeSet;
10
11use serde::{Deserialize, Serialize};
12use serde_json::{Value, json};
13
14use crate::app::{Failure, ReplayOutcome};
15use crate::harness::DiffOutcome;
16
17const CONTEXT: usize = 16;
19
20#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
21pub struct At {
22 pub channel: String,
24 #[serde(default, skip_serializing_if = "Option::is_none")]
26 pub path: Option<String>,
27 pub kind: String,
31 #[serde(default, skip_serializing_if = "Option::is_none")]
32 pub line: Option<usize>,
33 #[serde(default, skip_serializing_if = "Option::is_none")]
34 pub column: Option<usize>,
35 #[serde(default, skip_serializing_if = "Option::is_none")]
36 pub offset: Option<Offset>,
37 #[serde(default, skip_serializing_if = "Option::is_none")]
38 pub expected_type: Option<String>,
39 #[serde(default, skip_serializing_if = "Option::is_none")]
40 pub actual_type: Option<String>,
41 #[serde(default, skip_serializing_if = "Option::is_none")]
42 pub expected_len: Option<usize>,
43 #[serde(default, skip_serializing_if = "Option::is_none")]
44 pub actual_len: Option<usize>,
45 #[serde(default, skip_serializing_if = "Option::is_none")]
47 pub context: Option<Context>,
48}
49
50#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
51pub struct Offset {
52 pub char: usize,
53 pub byte: usize,
54}
55
56#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
57pub struct Context {
58 pub expected: String,
59 pub actual: String,
60}
61
62impl At {
63 pub fn new(kind: &str) -> At {
64 At {
65 kind: kind.to_string(),
66 ..At::default()
67 }
68 }
69
70 pub fn label(&self) -> String {
72 let mut out = self.channel.clone();
73 if let Some(path) = &self.path {
74 out += &format!(" {path}");
75 }
76 format!("{out} ({})", self.kind)
77 }
78
79 pub fn describe(&self) -> String {
82 let place = match &self.path {
83 Some(path) => format!("{} {path}", self.channel),
84 None => self.channel.clone(),
85 };
86 match (&self.context, &self.offset) {
87 (Some(c), Some(o)) => format!(
88 "at {place}{}, char {}: expected {:?}, got {:?}",
89 self.line
90 .zip(self.column)
91 .filter(|(l, _)| *l > 1 || self.path.is_none())
92 .map(|(l, c)| format!(", line {l}, column {c}"))
93 .unwrap_or_default(),
94 o.char,
95 c.expected,
96 c.actual
97 ),
98 (Some(c), None) => format!(
99 "at {place} ({}): expected {}, got {}",
100 self.kind, c.expected, c.actual
101 ),
102 _ => format!("at {}", self.shape()),
103 }
104 }
105
106 pub fn shape(&self) -> String {
108 let mut out = self.label();
109 if let Some(line) = self.line {
110 out += &format!(", line {line}");
111 }
112 if let Some(column) = self.column {
113 out += &format!(", column {column}");
114 }
115 if let Some(o) = &self.offset {
116 out += &format!(", char {}", o.char);
117 }
118 if let (Some(e), Some(a)) = (&self.expected_type, &self.actual_type)
119 && e != a
120 {
121 out += &format!(", expected {e}, got {a}");
122 }
123 if let (Some(e), Some(a)) = (self.expected_len, self.actual_len) {
124 out += &format!(", length {e} expected, {a} got");
125 }
126 out
127 }
128}
129
130fn type_name(v: &Value) -> &'static str {
131 match v {
132 Value::Null => "null",
133 Value::Bool(_) => "boolean",
134 Value::Number(_) => "number",
135 Value::String(_) => "string",
136 Value::Array(_) => "array",
137 Value::Object(_) => "object",
138 }
139}
140
141fn key_path(path: &str, key: &str) -> String {
142 let plain = !key.is_empty()
143 && !key.starts_with(|c: char| c.is_ascii_digit())
144 && key
145 .chars()
146 .all(|c| c.is_alphanumeric() || c == '_' || c == '$');
147 if plain {
148 format!("{path}.{key}")
149 } else {
150 format!("{path}[{}]", Value::String(key.to_string()))
151 }
152}
153
154fn first_difference(expected: &str, actual: &str) -> (usize, usize) {
156 let mut a = actual.chars();
157 for (i, (byte, e)) in expected.char_indices().enumerate() {
158 if a.next() != Some(e) {
159 return (i, byte);
160 }
161 }
162 (expected.chars().count(), expected.len())
163}
164
165fn around(text: &str, at: usize) -> String {
166 let chars: Vec<char> = text.chars().collect();
167 let start = at.saturating_sub(CONTEXT);
168 let end = (at + 1 + CONTEXT).min(chars.len());
169 let mut out = String::new();
170 if start > 0 {
171 out.push('…');
172 }
173 out.extend(&chars[start..at.min(chars.len())]);
174 out.push('⟨');
175 if let Some(c) = chars.get(at) {
176 out.push(*c);
177 }
178 out.push('⟩');
179 if at < chars.len() {
180 out.extend(&chars[at + 1..end]);
181 }
182 if end < chars.len() {
183 out.push('…');
184 }
185 out
186}
187
188pub(crate) fn text_at(kind: &str, expected: &str, actual: &str) -> At {
190 let (char, byte) = first_difference(expected, actual);
191 let before = &expected[..byte];
192 let line = before.matches('\n').count() + 1;
193 let column = before
194 .rsplit_once('\n')
195 .map_or(before, |(_, l)| l)
196 .chars()
197 .count()
198 + 1;
199 At {
200 kind: kind.to_string(),
201 line: Some(line),
202 column: Some(column),
203 offset: Some(Offset { char, byte }),
204 expected_len: Some(expected.chars().count()),
205 actual_len: Some(actual.chars().count()),
206 context: Some(Context {
207 expected: around(expected, char),
208 actual: around(actual, char),
209 }),
210 ..At::default()
211 }
212}
213
214fn strings_match(expected: &str, actual: &str) -> bool {
215 expected == actual || (expected.contains("[..]") && crate::app::line_matches(expected, actual))
216}
217
218fn walk(expected: &Value, actual: &Value, path: &str) -> Option<At> {
219 let at = |kind: &str| At {
220 path: Some(path.to_string()),
221 kind: kind.to_string(),
222 expected_type: Some(type_name(expected).to_string()),
223 actual_type: Some(type_name(actual).to_string()),
224 ..At::default()
225 };
226 match (expected, actual) {
227 (Value::String(e), Value::String(a)) => {
228 if strings_match(e, a) {
229 return None;
230 }
231 Some(At {
232 path: Some(path.to_string()),
233 expected_type: Some("string".into()),
234 actual_type: Some("string".into()),
235 ..text_at("value", e, a)
236 })
237 }
238 _ if expected == actual => None,
239 (Value::Object(e), Value::Object(a)) => {
240 for (k, ev) in e {
241 match a.get(k) {
242 None => {
243 return Some(At {
244 path: Some(key_path(path, k)),
245 kind: "missing key".into(),
246 expected_type: Some(type_name(ev).into()),
247 ..At::default()
248 });
249 }
250 Some(av) => {
251 if let Some(found) = walk(ev, av, &key_path(path, k)) {
252 return Some(found);
253 }
254 }
255 }
256 }
257 if let Some((k, av)) = a.iter().find(|(k, _)| !e.contains_key(*k)) {
258 return Some(At {
259 path: Some(key_path(path, k)),
260 kind: "extra key".into(),
261 actual_type: Some(type_name(av).into()),
262 ..At::default()
263 });
264 }
265 Some(at("value"))
266 }
267 (Value::Array(e), Value::Array(a)) => {
268 for (i, (ev, av)) in e.iter().zip(a).enumerate() {
269 if let Some(found) = walk(ev, av, &format!("{path}[{i}]")) {
270 return Some(found);
271 }
272 }
273 if e.len() != a.len() {
274 return Some(At {
275 expected_len: Some(e.len()),
276 actual_len: Some(a.len()),
277 ..at("length")
278 });
279 }
280 Some(at("value"))
281 }
282 _ if type_name(expected) != type_name(actual) => Some(at("type")),
283 _ => Some(At {
284 context: Some(Context {
285 expected: expected.to_string(),
286 actual: actual.to_string(),
287 }),
288 ..at("value")
289 }),
290 }
291}
292
293pub fn locate_in(expected: &Value, actual: &Value) -> At {
295 walk(expected, actual, "$").unwrap_or_else(|| At {
296 path: Some("$".into()),
297 ..At::new("value")
298 })
299}
300
301fn is_error(step: &Value) -> bool {
302 step.get("error").is_some()
303}
304
305pub fn locate_value(expected: &Value, actual: &Value) -> At {
308 if let (Value::Array(e), Value::Array(a)) = (expected, actual) {
309 let differs = |i: &usize| e[*i] != a[*i];
310 let n = e.len().min(a.len());
311 let step = (0..n)
312 .find(|i| differs(i) && !(is_error(&e[*i]) && is_error(&a[*i])))
313 .or_else(|| (0..n).find(differs));
314 return match step {
315 Some(i) => At {
316 channel: format!("call {i}"),
317 ..locate_value(&e[i], &a[i])
318 },
319 None => At {
320 channel: format!("call {n}"),
321 expected_len: Some(e.len()),
322 actual_len: Some(a.len()),
323 ..At::new("length")
324 },
325 };
326 }
327 let (e_ok, a_ok) = (expected.get("ok"), actual.get("ok"));
328 let (e_err, a_err) = (expected.get("error"), actual.get("error"));
329 match (e_ok, a_ok, e_err, a_err) {
330 (Some(e), Some(a), _, _) => At {
331 channel: "return".into(),
332 ..locate_in(e, a)
333 },
334 (_, _, Some(e), Some(a)) => At {
335 channel: "throw".into(),
336 ..locate_in(e, a)
337 },
338 (Some(_), None, _, Some(_)) | (None, Some(_), Some(_), _) => At {
339 channel: "return vs throw".into(),
340 expected_type: Some(if e_ok.is_some() { "return" } else { "throw" }.into()),
341 actual_type: Some(if a_ok.is_some() { "return" } else { "throw" }.into()),
342 ..At::new("type")
343 },
344 _ if actual.get("missing").is_some() => At {
345 channel: "return".into(),
346 ..At::new("no response")
347 },
348 _ => At {
349 channel: "return".into(),
350 ..locate_in(expected, actual)
351 },
352 }
353}
354
355pub fn annotate(outcome: &mut DiffOutcome) {
357 for m in &mut outcome.mismatches {
358 if m.get("at").is_some() {
359 continue;
360 }
361 let at = locate_value(&m["expected"], &m["actual"]);
362 if let (Value::Object(map), Ok(at)) = (m, serde_json::to_value(at)) {
363 map.insert("at".into(), at);
364 }
365 }
366}
367
368#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
370pub struct Group {
371 pub id: String,
372 #[serde(rename = "fn", default, skip_serializing_if = "Option::is_none")]
373 pub function: Option<String>,
374 pub channel: String,
375 #[serde(default, skip_serializing_if = "Option::is_none")]
376 pub path: Option<String>,
377 pub kind: String,
378 pub cases: usize,
379 pub example: Value,
381}
382
383impl Group {
384 pub fn label(&self) -> String {
386 let mut out = String::new();
387 if let Some(f) = &self.function {
388 out += &format!("{f}: ");
389 }
390 out += &self.channel;
391 if let Some(path) = &self.path {
392 out += &format!(" {path}");
393 }
394 format!("{out} ({})", self.kind)
395 }
396}
397
398fn without_indices(path: &str) -> String {
400 let mut out = String::new();
401 let mut chars = path.chars().peekable();
402 while let Some(c) = chars.next() {
403 out.push(c);
404 if c == '[' && chars.peek().is_some_and(char::is_ascii_digit) {
405 while chars.peek().is_some_and(char::is_ascii_digit) {
406 chars.next();
407 }
408 }
409 }
410 out
411}
412
413fn fnv(bytes: &[u8]) -> u64 {
414 let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
415 for b in bytes {
416 hash ^= u64::from(*b);
417 hash = hash.wrapping_mul(0x0100_0000_01b3);
418 }
419 hash
420}
421
422fn group_id(function: Option<&str>, at: &At, path: Option<&str>) -> String {
423 let key = format!(
424 "{}\0{}\0{}\0{}",
425 function.unwrap_or_default(),
426 at.channel,
427 path.unwrap_or_default(),
428 at.kind
429 );
430 format!("{:016x}", fnv(key.as_bytes()))[..8].to_string()
431}
432
433struct Builder {
434 groups: Vec<(Group, BTreeSet<usize>)>,
435}
436
437impl Builder {
438 fn add(&mut self, function: Option<&str>, at: &At, case: usize, example: impl Fn() -> Value) {
439 let path = at.path.as_deref().map(without_indices);
440 let id = group_id(function, at, path.as_deref());
441 match self.groups.iter_mut().find(|(g, _)| g.id == id) {
442 Some((g, cases)) => {
443 if cases.insert(case) {
444 g.cases += 1;
445 }
446 }
447 None => self.groups.push((
448 Group {
449 id,
450 function: function.map(str::to_string),
451 channel: at.channel.clone(),
452 path,
453 kind: at.kind.clone(),
454 cases: 1,
455 example: example(),
456 },
457 BTreeSet::from([case]),
458 )),
459 }
460 }
461
462 fn finish(self) -> Vec<Group> {
463 let mut out: Vec<Group> = self.groups.into_iter().map(|(g, _)| g).collect();
464 out.sort_by_key(|g| std::cmp::Reverse(g.cases));
465 out
466 }
467}
468
469pub fn group_mismatches(mismatches: &[Value]) -> Vec<Group> {
471 let mut b = Builder { groups: Vec::new() };
472 for (i, m) in mismatches.iter().enumerate() {
473 let at = serde_json::from_value::<At>(m["at"].clone())
474 .unwrap_or_else(|_| locate_value(&m["expected"], &m["actual"]));
475 b.add(m["fn"].as_str(), &at, i, || m.clone());
476 }
477 b.finish()
478}
479
480pub fn replay_groups(failures: &[Failure]) -> Vec<Group> {
482 let mut b = Builder { groups: Vec::new() };
483 for (i, f) in failures.iter().enumerate() {
484 for p in &f.problems {
485 let at = p.at.clone().unwrap_or_else(|| At {
486 channel: p.field.clone(),
487 ..At::new("value")
488 });
489 b.add(None, &at, i, || Value::String(f.case.clone()));
490 }
491 }
492 b.finish()
493}
494
495fn canonical(v: &Value) -> Value {
496 match v {
497 Value::Object(map) => {
498 let mut keys: Vec<&String> = map.keys().collect();
499 keys.sort();
500 Value::Object(
501 keys.into_iter()
502 .map(|k| (k.clone(), canonical(&map[k])))
503 .collect(),
504 )
505 }
506 Value::Array(items) => Value::Array(items.iter().map(canonical).collect()),
507 other => other.clone(),
508 }
509}
510
511pub fn hash(v: &Value) -> String {
513 format!("{:016x}", fnv(canonical(v).to_string().as_bytes()))
514}
515
516fn hashable(v: &Value) -> Option<String> {
519 matches!(v, Value::String(_) | Value::Array(_) | Value::Object(_)).then(|| hash(v))
520}
521
522fn inner(result: &Value) -> &Value {
523 result
524 .get("ok")
525 .or_else(|| result.get("error"))
526 .unwrap_or(result)
527}
528
529fn without_context(at: &Value) -> Value {
530 let mut at = at.clone();
531 if let Value::Object(map) = &mut at {
532 map.remove("context");
533 }
534 at
535}
536
537pub fn redact_mismatch(m: &Value) -> Value {
540 let mut out = json!({ "fn": m["fn"], "case": hash(&m["args"]) });
541 for (key, side) in [("expected_hash", "expected"), ("actual_hash", "actual")] {
542 if let Some(h) = hashable(inner(&m[side])) {
543 out[key] = Value::String(h);
544 }
545 }
546 let at = if m.get("at").is_some() {
547 m["at"].clone()
548 } else {
549 serde_json::to_value(locate_value(&m["expected"], &m["actual"])).unwrap_or_default()
550 };
551 out["at"] = without_context(&at);
552 out
553}
554
555pub fn redact_diff(outcome: &mut DiffOutcome) {
557 for m in &mut outcome.mismatches {
558 *m = redact_mismatch(m);
559 }
560 for e in &mut outcome.stale_known {
561 *e = json!({ "fn": e["fn"], "case": hash(&e["args"]) });
562 }
563 for g in &mut outcome.groups {
564 g.example = redact_mismatch(&g.example);
565 }
566}
567
568fn is_request(args: &[String]) -> bool {
569 args.len() == 2
570 && args[1].starts_with('/')
571 && !args[0].is_empty()
572 && args[0].chars().all(|c| c.is_ascii_uppercase())
573}
574
575pub fn redact_replay(outcome: &mut ReplayOutcome) {
577 for f in &mut outcome.failures {
578 f.args = if is_request(&f.args) {
579 vec![f.args[0].clone(), hash(&Value::String(f.args[1].clone()))]
580 } else {
581 vec![hash(&json!(f.args))]
582 };
583 for p in &mut f.problems {
584 if let Some(at) = &mut p.at {
585 at.context = None;
586 }
587 p.detail = match &p.at {
588 Some(at) => format!("{}\n", at.shape()),
589 None => "differs\n".to_string(),
590 };
591 }
592 }
593}
594
595#[cfg(test)]
596mod tests {
597 use super::*;
598
599 #[test]
600 fn a_nested_value_names_its_path_and_the_character() {
601 let at = locate_value(
602 &json!({ "ok": { "items": [{ "name": "abc" }, { "name": "abcdef" }] } }),
603 &json!({ "ok": { "items": [{ "name": "abc" }, { "name": "abXdef" }] } }),
604 );
605 assert_eq!(at.channel, "return");
606 assert_eq!(at.path.as_deref(), Some("$.items[1].name"));
607 assert_eq!(at.kind, "value");
608 assert_eq!(at.offset, Some(Offset { char: 2, byte: 2 }));
609 assert_eq!(at.column, Some(3));
610 let c = at.context.unwrap();
611 assert_eq!(c.expected, "ab⟨c⟩def");
612 assert_eq!(c.actual, "ab⟨X⟩def");
613 }
614
615 #[test]
616 fn unequal_arrays_and_keys() {
617 let at = locate_in(&json!([1, 2, 3]), &json!([1, 2]));
618 assert_eq!(
619 (at.kind.as_str(), at.path.as_deref()),
620 ("length", Some("$"))
621 );
622 assert_eq!((at.expected_len, at.actual_len), (Some(3), Some(2)));
623 let at = locate_in(&json!({ "a": 1, "b": 2 }), &json!({ "a": 1 }));
624 assert_eq!(
625 (at.kind.as_str(), at.path.as_deref()),
626 ("missing key", Some("$.b"))
627 );
628 let at = locate_in(&json!({ "a": 1 }), &json!({ "a": 1, "my key": 2 }));
629 assert_eq!(at.kind, "extra key");
630 assert_eq!(at.path.as_deref(), Some(r#"$["my key"]"#));
631 let at = locate_in(&json!({ "a": 1 }), &json!({ "a": "1" }));
632 assert_eq!(at.kind, "type");
633 assert_eq!(at.expected_type.as_deref(), Some("number"));
634 assert_eq!(at.actual_type.as_deref(), Some("string"));
635 }
636
637 #[test]
638 fn an_error_against_a_value_is_return_vs_throw() {
639 let at = locate_value(&json!({ "error": "boom" }), &json!({ "ok": 3 }));
640 assert_eq!(at.channel, "return vs throw");
641 assert_eq!(at.kind, "type");
642 assert_eq!(at.expected_type.as_deref(), Some("throw"));
643 let at = locate_value(&json!({ "error": "bad x" }), &json!({ "error": "bad y" }));
644 assert_eq!((at.channel.as_str(), at.kind.as_str()), ("throw", "value"));
645 let at = locate_value(
646 &json!([{ "ok": true }, { "ok": 1 }, { "ok": 2 }]),
647 &json!([{ "ok": true }, { "ok": 1 }, { "ok": 5 }]),
648 );
649 assert_eq!(at.channel, "call 2");
650 assert_eq!(at.path.as_deref(), Some("$"));
651 }
652
653 #[test]
654 fn unicode_offsets_count_chars_and_bytes() {
655 let at = locate_in(&json!("héllo wörld"), &json!("héllo wørld"));
656 assert_eq!(at.offset, Some(Offset { char: 7, byte: 8 }));
657 let c = at.context.unwrap();
658 assert_eq!(c.expected, "héllo w⟨ö⟩rld");
659 assert_eq!(c.actual, "héllo w⟨ø⟩rld");
660 let at = locate_in(&json!("ab"), &json!("abc"));
661 assert_eq!(at.context.unwrap().expected, "ab⟨⟩");
662 let long = "x".repeat(40);
663 let at = locate_in(
664 &json!(format!("{long}a{long}")),
665 &json!(format!("{long}b{long}")),
666 );
667 let c = at.context.unwrap();
668 assert!(
669 c.expected.starts_with('…') && c.expected.ends_with('…'),
670 "{c:?}"
671 );
672 assert_eq!(c.expected.chars().count(), 2 * CONTEXT + 5);
673 }
674
675 #[test]
676 fn the_same_bug_at_other_indices_is_one_group() {
677 let mut outcome = DiffOutcome {
678 mismatches: (0..4)
679 .map(|i| {
680 let mut items = vec![json!("a"); 5];
681 let mut wrong = items.clone();
682 wrong[i] = json!("b");
683 items[i] = json!("c");
684 json!({ "fn": "f", "args": [i], "expected": { "ok": items }, "actual": { "ok": wrong } })
685 })
686 .chain([json!({ "fn": "g", "args": [], "expected": { "ok": 1 }, "actual": { "ok": 2 } })])
687 .collect(),
688 ..DiffOutcome::default()
689 };
690 annotate(&mut outcome);
691 let groups = group_mismatches(&outcome.mismatches);
692 assert_eq!(groups.len(), 2, "{groups:?}");
693 assert_eq!(groups[0].cases, 4);
694 assert_eq!(groups[0].path.as_deref(), Some("$[]"));
695 assert_eq!(groups[0].label(), "f: return $[] (value)");
696 assert_eq!(groups[0].id.len(), 8);
697 assert_eq!(groups[1].label(), "g: return $ (value)");
698 assert_ne!(groups[0].id, groups[1].id);
699 }
700
701 #[test]
702 fn a_redacted_mismatch_keeps_its_shape_only() {
703 let m = json!({ "fn": "f", "args": ["secret input"], "expected": { "ok": { "name": "Ada" } }, "actual": { "ok": { "name": "Bob" } } });
704 let r = redact_mismatch(&m);
705 let text = r.to_string();
706 for value in ["secret", "Ada", "Bob"] {
707 assert!(!text.contains(value), "{text}");
708 }
709 assert_eq!(r["at"]["path"], "$.name");
710 assert_eq!(r["case"], hash(&json!(["secret input"])));
711 assert!(r["expected_hash"].is_string());
712 let n = redact_mismatch(
713 &json!({ "fn": "f", "args": [1], "expected": { "ok": 1 }, "actual": { "ok": 2 } }),
714 );
715 assert!(n.get("expected_hash").is_none(), "{n}");
716 assert_eq!(n["at"]["expected_type"], "number");
717 assert_eq!(
718 hash(&json!({ "a": 1, "b": 2 })),
719 hash(&json!({ "b": 2, "a": 1 }))
720 );
721 }
722}