1use crate::compare::diff::{divergence, value_divergences};
2use crate::compare::effects::effects_equivalent;
3use crate::compare::error::errors_equivalent;
4use crate::policy::Policy;
5use rewrit_model::{CaseId, Divergence, DivergenceKind, Observation, Severity, SourceLocation};
6
7#[derive(Debug, Clone)]
8pub struct CompareContext {
9 pub policy: Policy,
10 pub suite: Option<String>,
11 pub source_location: Option<SourceLocation>,
12 pub target_location: Option<SourceLocation>,
13 pub normalizers_applied: Vec<String>,
14}
15
16#[derive(Debug, Clone)]
17pub struct Comparison {
18 pub case_id: CaseId,
19 pub equivalent: bool,
20 pub divergences: Vec<Divergence>,
21}
22
23pub trait Comparator: Send + Sync {
24 fn name(&self) -> &'static str;
25
26 fn compare(
27 &self,
28 reference: &Observation,
29 candidate: &Observation,
30 ctx: &CompareContext,
31 ) -> Comparison;
32}
33
34#[derive(Debug, Default)]
35pub struct StrictComparator;
36
37impl Comparator for StrictComparator {
38 fn name(&self) -> &'static str {
39 "strict"
40 }
41
42 fn compare(
43 &self,
44 reference: &Observation,
45 candidate: &Observation,
46 ctx: &CompareContext,
47 ) -> Comparison {
48 let mut divergences = Vec::new();
49
50 if reference.status != candidate.status {
51 divergences.push(divergence(
52 DivergenceKind::OutputMismatch,
53 reference.case_id.clone(),
54 "$.status",
55 "Runtime statuses differ.",
56 Some(&reference.status),
57 Some(&candidate.status),
58 ctx,
59 ));
60 }
61
62 if ctx.policy.compare_exit_code && reference.exit_code != candidate.exit_code {
63 divergences.push(divergence(
64 DivergenceKind::ExitCodeMismatch,
65 reference.case_id.clone(),
66 "$.exit_code",
67 "Runtime exit codes differ.",
68 Some(&reference.exit_code),
69 Some(&candidate.exit_code),
70 ctx,
71 ));
72 }
73
74 match (&reference.value, &candidate.value) {
75 (Some(left), Some(right)) => divergences.extend(value_divergences(
76 &reference.case_id,
77 left,
78 right,
79 "$.value",
80 ctx,
81 )),
82 (Some(left), None) => divergences.push(divergence(
83 DivergenceKind::OutputMismatch,
84 reference.case_id.clone(),
85 "$.value",
86 "Reference produced a value but candidate did not.",
87 Some(left),
88 Option::<&serde_json::Value>::None,
89 ctx,
90 )),
91 (None, Some(right)) => divergences.push(divergence(
92 DivergenceKind::OutputMismatch,
93 reference.case_id.clone(),
94 "$.value",
95 "Candidate produced a value but reference did not.",
96 Option::<&serde_json::Value>::None,
97 Some(right),
98 ctx,
99 )),
100 _ => {}
101 }
102
103 if !errors_equivalent(
104 reference.error.as_ref(),
105 candidate.error.as_ref(),
106 &ctx.policy,
107 ) {
108 divergences.push(divergence(
109 DivergenceKind::ErrorMismatch,
110 reference.case_id.clone(),
111 "$.error",
112 "Canonical errors differ.",
113 reference.error.as_ref(),
114 candidate.error.as_ref(),
115 ctx,
116 ));
117 }
118
119 if !effects_equivalent(&reference.effects, &candidate.effects, &ctx.policy) {
120 divergences.push(divergence(
121 DivergenceKind::SideEffectMismatch,
122 reference.case_id.clone(),
123 "$.effects",
124 "Observed side effects differ.",
125 Some(&reference.effects),
126 Some(&candidate.effects),
127 ctx,
128 ));
129 }
130
131 if ctx.policy.compare_stdout && reference.stdout != candidate.stdout {
132 divergences.push(divergence(
133 DivergenceKind::StdoutMismatch,
134 reference.case_id.clone(),
135 "$.stdout",
136 "Captured stdout differs.",
137 Some(&reference.stdout),
138 Some(&candidate.stdout),
139 ctx,
140 ));
141 }
142
143 if ctx.policy.compare_stderr && reference.stderr != candidate.stderr {
144 divergences.push(divergence(
145 DivergenceKind::StderrMismatch,
146 reference.case_id.clone(),
147 "$.stderr",
148 "Captured stderr differs.",
149 Some(&reference.stderr),
150 Some(&candidate.stderr),
151 ctx,
152 ));
153 }
154
155 for divergence in &mut divergences {
156 if matches!(
157 divergence.kind,
158 DivergenceKind::Timeout | DivergenceKind::AdapterError | DivergenceKind::InfraError
159 ) {
160 divergence.severity = Severity::Blocking;
161 }
162 }
163
164 Comparison {
165 case_id: reference.case_id.clone(),
166 equivalent: divergences.is_empty(),
167 divergences,
168 }
169 }
170}
171
172#[cfg(test)]
173mod tests {
174 use super::{Comparator, CompareContext, StrictComparator};
175 use crate::policy::Policy;
176 use rewrit_model::{
177 CanonicalValue, CapturedText, CaseId, CaseStatus, DivergenceKind, Observation, RuntimeId,
178 };
179 use std::collections::BTreeMap;
180
181 #[test]
182 fn detects_json_type_mismatch_at_path() {
183 let comparison = StrictComparator.compare(
184 &observation(json_value(serde_json::json!({"amount": "199.90"}))),
185 &observation(json_value(serde_json::json!({"amount": 199.9}))),
186 &ctx(Policy::default()),
187 );
188
189 assert_eq!(comparison.divergences.len(), 1);
190 assert_eq!(comparison.divergences[0].kind, DivergenceKind::TypeMismatch);
191 assert_eq!(
192 comparison.divergences[0].path.as_deref(),
193 Some("$.value.amount")
194 );
195 assert!(comparison.divergences[0]
196 .hint
197 .as_deref()
198 .is_some_and(|hint| hint.contains("$.value.amount")));
199 }
200
201 #[test]
202 fn ignores_configured_json_path() {
203 let comparison = StrictComparator.compare(
204 &observation(json_value(serde_json::json!({"trace_id": "a", "ok": true}))),
205 &observation(json_value(serde_json::json!({"trace_id": "b", "ok": true}))),
206 &ctx(Policy {
207 ignore_paths: vec!["$.trace_id".to_string()],
208 ..Policy::default()
209 }),
210 );
211
212 assert!(comparison.equivalent);
213 assert!(comparison.divergences.is_empty());
214 }
215
216 #[test]
217 fn treats_configured_json_array_path_as_unordered() {
218 let comparison = StrictComparator.compare(
219 &observation(json_value(serde_json::json!({
220 "items": [{"id": 2}, {"id": 1}]
221 }))),
222 &observation(json_value(serde_json::json!({
223 "items": [{"id": 1}, {"id": 2}]
224 }))),
225 &ctx(Policy {
226 unordered_paths: vec!["$.items".to_string()],
227 ..Policy::default()
228 }),
229 );
230
231 assert!(comparison.equivalent);
232 assert!(comparison.divergences.is_empty());
233 }
234
235 #[test]
236 fn ignores_configured_http_header_noise() {
237 let reference = CanonicalValue::Object {
238 fields: BTreeMap::from([
239 (
240 "headers".to_string(),
241 CanonicalValue::Object {
242 fields: BTreeMap::from([(
243 "date".to_string(),
244 CanonicalValue::String {
245 value: "Mon, 01 Jan 2024 00:00:00 GMT".to_string(),
246 },
247 )]),
248 },
249 ),
250 (
251 "body".to_string(),
252 json_value(serde_json::json!({"ok": true})),
253 ),
254 ]),
255 };
256 let candidate = CanonicalValue::Object {
257 fields: BTreeMap::from([
258 (
259 "headers".to_string(),
260 CanonicalValue::Object {
261 fields: BTreeMap::from([(
262 "date".to_string(),
263 CanonicalValue::String {
264 value: "Tue, 02 Jan 2024 00:00:00 GMT".to_string(),
265 },
266 )]),
267 },
268 ),
269 (
270 "body".to_string(),
271 json_value(serde_json::json!({"ok": true})),
272 ),
273 ]),
274 };
275
276 let comparison = StrictComparator.compare(
277 &observation(reference),
278 &observation(candidate),
279 &ctx(Policy::default()),
280 );
281
282 assert!(comparison.equivalent);
283 assert!(comparison.divergences.is_empty());
284 }
285
286 fn ctx(policy: Policy) -> CompareContext {
287 CompareContext {
288 policy,
289 suite: None,
290 source_location: None,
291 target_location: None,
292 normalizers_applied: Vec::new(),
293 }
294 }
295
296 fn observation(value: CanonicalValue) -> Observation {
297 Observation {
298 case_id: CaseId::new("case.one"),
299 runtime_id: RuntimeId::new("runtime"),
300 status: CaseStatus::Passed,
301 value: Some(value),
302 error: None,
303 stdout: CapturedText::default(),
304 stderr: CapturedText::default(),
305 exit_code: Some(0),
306 duration_ms: 1,
307 effects: Vec::new(),
308 artifacts: Vec::new(),
309 metadata: BTreeMap::new(),
310 }
311 }
312
313 fn json_value(value: serde_json::Value) -> CanonicalValue {
314 CanonicalValue::Json { value }
315 }
316}