1use crate::compare::CompareContext;
2use rewrit_model::{CanonicalValue, CaseId, Divergence, DivergenceKind, Severity};
3use serde::Serialize;
4use std::collections::BTreeSet;
5
6pub fn divergence<T, U>(
7 kind: DivergenceKind,
8 case_id: CaseId,
9 path: impl Into<String>,
10 message: impl Into<String>,
11 reference: Option<&T>,
12 candidate: Option<&U>,
13 ctx: &CompareContext,
14) -> Divergence
15where
16 T: Serialize + ?Sized,
17 U: Serialize + ?Sized,
18{
19 let path = path.into();
20 let hint = divergence_hint(&kind, &path);
21 Divergence {
22 machine_code: format!("{kind:?}").to_ascii_lowercase(),
23 kind,
24 severity: Severity::Blocking,
25 case_id,
26 suite: ctx.suite.clone(),
27 path: Some(path),
28 reference: reference.and_then(|value| serde_json::to_value(value).ok()),
29 candidate: candidate.and_then(|value| serde_json::to_value(value).ok()),
30 message: message.into(),
31 source_location: ctx.source_location.clone(),
32 target_location: ctx.target_location.clone(),
33 policy: Some(ctx.policy.name.clone()),
34 normalizers_applied: ctx.normalizers_applied.clone(),
35 hint,
36 minimal_reproduction: None,
37 }
38}
39
40fn divergence_hint(kind: &DivergenceKind, path: &str) -> Option<String> {
41 let hint = match kind {
42 DivergenceKind::TypeMismatch => format!(
43 "Align the candidate value type at {path} with the reference observation or declare a scoped policy if this type difference is intentional."
44 ),
45 DivergenceKind::OutputMismatch => format!(
46 "Align the candidate output at {path} with the reference observation or add a scoped normalizer for known runtime noise."
47 ),
48 DivergenceKind::SideEffectMismatch => format!(
49 "Align the candidate side effects at {path} with the reference observation or add an explicit effect mapping."
50 ),
51 DivergenceKind::ExitCodeMismatch => {
52 "Make the candidate process exit code match the reference or disable exit-code comparison in policy.".to_string()
53 }
54 DivergenceKind::StdoutMismatch => {
55 "Make stdout deterministic or disable stdout comparison in policy.".to_string()
56 }
57 DivergenceKind::StderrMismatch => {
58 "Make stderr deterministic or disable stderr comparison in policy.".to_string()
59 }
60 DivergenceKind::ErrorMismatch => format!(
61 "Align the candidate error envelope at {path} with the reference error policy."
62 ),
63 _ => return None,
64 };
65 Some(hint)
66}
67
68#[must_use]
69pub fn value_type_name(value: &CanonicalValue) -> &'static str {
70 value.kind_name()
71}
72
73pub fn value_divergences(
74 case_id: &CaseId,
75 reference: &CanonicalValue,
76 candidate: &CanonicalValue,
77 path: &str,
78 ctx: &CompareContext,
79) -> Vec<Divergence> {
80 if path_is_ignored(path, ctx) || ctx.policy.values_equivalent(reference, candidate) {
81 return Vec::new();
82 }
83
84 match (reference, candidate) {
85 (CanonicalValue::Json { value: left }, CanonicalValue::Json { value: right }) => {
86 json_divergences(case_id, left, right, path, ctx)
87 }
88 (CanonicalValue::Object { fields: left }, CanonicalValue::Object { fields: right }) => {
89 let keys = left.keys().chain(right.keys()).collect::<BTreeSet<_>>();
90 keys.into_iter()
91 .flat_map(|key| {
92 let child_path = format!("{path}.{}", escape_path_segment(key));
93 if header_is_ignored(&child_path, key, ctx) {
94 return Vec::new();
95 }
96 match (left.get(key), right.get(key)) {
97 (Some(left), Some(right)) => {
98 value_divergences(case_id, left, right, &child_path, ctx)
99 }
100 (Some(left), None) => vec![divergence(
101 DivergenceKind::OutputMismatch,
102 case_id.clone(),
103 child_path,
104 "Candidate is missing a canonical object field.",
105 Some(left),
106 Some(&CanonicalValue::Absent),
107 ctx,
108 )],
109 (None, Some(right)) => vec![divergence(
110 DivergenceKind::OutputMismatch,
111 case_id.clone(),
112 child_path,
113 "Candidate has an extra canonical object field.",
114 Some(&CanonicalValue::Absent),
115 Some(right),
116 ctx,
117 )],
118 (None, None) => Vec::new(),
119 }
120 })
121 .collect()
122 }
123 (CanonicalValue::Array { items: left }, CanonicalValue::Array { items: right }) => {
124 if path_is_unordered(path, ctx) {
125 return unordered_array_divergences(case_id, left, right, path, ctx);
126 }
127 let len = left.len().max(right.len());
128 (0..len)
129 .flat_map(|idx| {
130 let child_path = format!("{path}[{idx}]");
131 match (left.get(idx), right.get(idx)) {
132 (Some(left), Some(right)) => {
133 value_divergences(case_id, left, right, &child_path, ctx)
134 }
135 (Some(left), None) => vec![divergence(
136 DivergenceKind::OutputMismatch,
137 case_id.clone(),
138 child_path,
139 "Candidate is missing an array item.",
140 Some(left),
141 Some(&CanonicalValue::Absent),
142 ctx,
143 )],
144 (None, Some(right)) => vec![divergence(
145 DivergenceKind::OutputMismatch,
146 case_id.clone(),
147 child_path,
148 "Candidate has an extra array item.",
149 Some(&CanonicalValue::Absent),
150 Some(right),
151 ctx,
152 )],
153 (None, None) => Vec::new(),
154 }
155 })
156 .collect()
157 }
158 _ if value_type_name(reference) != value_type_name(candidate) => vec![divergence(
159 DivergenceKind::TypeMismatch,
160 case_id.clone(),
161 path.to_string(),
162 format!(
163 "Canonical value type differs: reference is {}, candidate is {}.",
164 value_type_name(reference),
165 value_type_name(candidate)
166 ),
167 Some(reference),
168 Some(candidate),
169 ctx,
170 )],
171 _ => vec![divergence(
172 DivergenceKind::OutputMismatch,
173 case_id.clone(),
174 path.to_string(),
175 "Canonical output values differ.",
176 Some(reference),
177 Some(candidate),
178 ctx,
179 )],
180 }
181}
182
183fn json_divergences(
184 case_id: &CaseId,
185 reference: &serde_json::Value,
186 candidate: &serde_json::Value,
187 path: &str,
188 ctx: &CompareContext,
189) -> Vec<Divergence> {
190 if path_is_ignored(path, ctx) || reference == candidate {
191 return Vec::new();
192 }
193
194 match (reference, candidate) {
195 (serde_json::Value::Object(left), serde_json::Value::Object(right)) => {
196 let keys = left.keys().chain(right.keys()).collect::<BTreeSet<_>>();
197 keys.into_iter()
198 .flat_map(|key| {
199 let child_path = format!("{path}.{}", escape_path_segment(key));
200 match (left.get(key), right.get(key)) {
201 (Some(left), Some(right)) => {
202 json_divergences(case_id, left, right, &child_path, ctx)
203 }
204 (Some(left), None) => vec![divergence(
205 DivergenceKind::OutputMismatch,
206 case_id.clone(),
207 child_path,
208 "Candidate JSON object is missing a field.",
209 Some(left),
210 Some(&serde_json::Value::String("<ABSENT>".to_string())),
211 ctx,
212 )],
213 (None, Some(right)) => vec![divergence(
214 DivergenceKind::OutputMismatch,
215 case_id.clone(),
216 child_path,
217 "Candidate JSON object has an extra field.",
218 Some(&serde_json::Value::String("<ABSENT>".to_string())),
219 Some(right),
220 ctx,
221 )],
222 (None, None) => Vec::new(),
223 }
224 })
225 .collect()
226 }
227 (serde_json::Value::Array(left), serde_json::Value::Array(right)) => {
228 if path_is_unordered(path, ctx) {
229 return unordered_json_array_divergences(case_id, left, right, path, ctx);
230 }
231 let len = left.len().max(right.len());
232 (0..len)
233 .flat_map(|idx| {
234 let child_path = format!("{path}[{idx}]");
235 match (left.get(idx), right.get(idx)) {
236 (Some(left), Some(right)) => {
237 json_divergences(case_id, left, right, &child_path, ctx)
238 }
239 (Some(left), None) => vec![divergence(
240 DivergenceKind::OutputMismatch,
241 case_id.clone(),
242 child_path,
243 "Candidate JSON array is missing an item.",
244 Some(left),
245 Some(&serde_json::Value::String("<ABSENT>".to_string())),
246 ctx,
247 )],
248 (None, Some(right)) => vec![divergence(
249 DivergenceKind::OutputMismatch,
250 case_id.clone(),
251 child_path,
252 "Candidate JSON array has an extra item.",
253 Some(&serde_json::Value::String("<ABSENT>".to_string())),
254 Some(right),
255 ctx,
256 )],
257 (None, None) => Vec::new(),
258 }
259 })
260 .collect()
261 }
262 _ if json_kind(reference) != json_kind(candidate) => vec![divergence(
263 DivergenceKind::TypeMismatch,
264 case_id.clone(),
265 path.to_string(),
266 format!(
267 "JSON value type differs: reference is {}, candidate is {}.",
268 json_kind(reference),
269 json_kind(candidate)
270 ),
271 Some(reference),
272 Some(candidate),
273 ctx,
274 )],
275 _ => vec![divergence(
276 DivergenceKind::OutputMismatch,
277 case_id.clone(),
278 path.to_string(),
279 "JSON values differ.",
280 Some(reference),
281 Some(candidate),
282 ctx,
283 )],
284 }
285}
286
287fn json_kind(value: &serde_json::Value) -> &'static str {
288 match value {
289 serde_json::Value::Null => "null",
290 serde_json::Value::Bool(_) => "bool",
291 serde_json::Value::Number(_) => "number",
292 serde_json::Value::String(_) => "string",
293 serde_json::Value::Array(_) => "array",
294 serde_json::Value::Object(_) => "object",
295 }
296}
297
298fn header_is_ignored(path: &str, key: &str, ctx: &CompareContext) -> bool {
299 path.starts_with("$.value.headers.")
300 && ctx
301 .policy
302 .ignored_headers
303 .iter()
304 .any(|ignored| ignored.eq_ignore_ascii_case(key))
305}
306
307fn path_is_ignored(path: &str, ctx: &CompareContext) -> bool {
308 ctx.policy
309 .ignore_paths
310 .iter()
311 .any(|ignored| path_matches_policy(path, ignored))
312}
313
314fn path_is_unordered(path: &str, ctx: &CompareContext) -> bool {
315 ctx.policy
316 .unordered_paths
317 .iter()
318 .any(|unordered| path_matches_policy(path, unordered))
319}
320
321fn path_matches_policy(path: &str, ignored: &str) -> bool {
322 candidate_policy_paths(path)
323 .iter()
324 .any(|path| path == ignored || wildcard_path_matches(path, ignored))
325}
326
327fn candidate_policy_paths(path: &str) -> Vec<String> {
328 let mut paths = vec![path.to_string()];
329 if let Some(suffix) = path.strip_prefix("$.value.body") {
330 if suffix.is_empty() {
331 paths.push("$".to_string());
332 } else if let Some(suffix) = suffix.strip_prefix('.') {
333 paths.push(format!("$.{suffix}"));
334 } else if suffix.starts_with('[') {
335 paths.push(format!("${suffix}"));
336 }
337 }
338 if let Some(suffix) = path.strip_prefix("$.value") {
339 if suffix.is_empty() {
340 paths.push("$".to_string());
341 } else if let Some(suffix) = suffix.strip_prefix('.') {
342 paths.push(format!("$.{suffix}"));
343 } else if suffix.starts_with('[') {
344 paths.push(format!("${suffix}"));
345 }
346 }
347 paths
348}
349
350fn wildcard_path_matches(path: &str, ignored: &str) -> bool {
351 if !ignored.contains("[*]") {
352 return false;
353 }
354 let prefix = ignored.split("[*]").next().unwrap_or_default();
355 let suffix = ignored.split("[*]").nth(1).unwrap_or_default();
356 path.starts_with(prefix) && path.ends_with(suffix)
357}
358
359fn unordered_json_array_divergences(
360 case_id: &CaseId,
361 reference: &[serde_json::Value],
362 candidate: &[serde_json::Value],
363 path: &str,
364 ctx: &CompareContext,
365) -> Vec<Divergence> {
366 if sorted_json_items(reference) == sorted_json_items(candidate) {
367 Vec::new()
368 } else {
369 vec![divergence(
370 DivergenceKind::OutputMismatch,
371 case_id.clone(),
372 path.to_string(),
373 "JSON array items differ after applying unordered array policy.",
374 Some(reference),
375 Some(candidate),
376 ctx,
377 )]
378 }
379}
380
381fn unordered_array_divergences(
382 case_id: &CaseId,
383 reference: &[CanonicalValue],
384 candidate: &[CanonicalValue],
385 path: &str,
386 ctx: &CompareContext,
387) -> Vec<Divergence> {
388 if sorted_serialized_items(reference) == sorted_serialized_items(candidate) {
389 Vec::new()
390 } else {
391 vec![divergence(
392 DivergenceKind::OutputMismatch,
393 case_id.clone(),
394 path.to_string(),
395 "Canonical array items differ after applying unordered array policy.",
396 Some(reference),
397 Some(candidate),
398 ctx,
399 )]
400 }
401}
402
403fn sorted_json_items(items: &[serde_json::Value]) -> Vec<String> {
404 sorted_serialized_items(items)
405}
406
407fn sorted_serialized_items<T: Serialize>(items: &[T]) -> Vec<String> {
408 let mut serialized = items
409 .iter()
410 .map(|item| serde_json::to_string(item).unwrap_or_default())
411 .collect::<Vec<_>>();
412 serialized.sort();
413 serialized
414}
415
416fn escape_path_segment(segment: &str) -> String {
417 if segment
418 .chars()
419 .all(|ch| ch.is_ascii_alphanumeric() || ch == '_' || ch == '-')
420 {
421 segment.to_string()
422 } else {
423 format!("[{}]", serde_json::to_string(segment).unwrap_or_default())
424 }
425}