veerdiff 0.1.0

Semantic diff engine for LLM and agent execution traces — find exactly where two runs veer apart.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
//! Alignment: the core diff algorithm.
//!
//! Two traces are aligned with a Wagner–Fischer edit-distance dynamic program
//! generalized to steps. The novelty over a line-based `diff` is the
//! substitution cost: instead of "equal or not", pairing step `a` with step `b`
//! costs `1 - similarity(a, b)`, and pairing is only permitted when similarity
//! clears [`Config::align_floor`]. This makes the optimal edit script prefer to
//! *pair* a step with its closest counterpart (reporting a field-level change)
//! and only fall back to insert/delete when nothing close enough exists.
//!
//! For each paired-but-changed step, a nested diff is computed: an inline
//! word-level diff for `content` and a JSON-path diff for `args`.

use serde::Serialize;
use serde_json::Value;

use crate::config::Config;
use crate::model::{Step, Trace};
use crate::similarity::step_similarity;

/// One entry in the edit script aligning two traces.
#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(tag = "op", rename_all = "snake_case")]
pub enum Op {
    /// The step is present and equal in both traces.
    Equal {
        /// Index in the left (`a`) trace.
        a: usize,
        /// Index in the right (`b`) trace.
        b: usize,
    },
    /// The step is present in both but its fields differ.
    Change {
        /// Index in the left (`a`) trace.
        a: usize,
        /// Index in the right (`b`) trace.
        b: usize,
        /// Similarity score of the pairing, in `[0, 1]`.
        similarity: f64,
        /// Field-level differences.
        fields: Vec<FieldDiff>,
    },
    /// The step exists only in the right (`b`) trace.
    Insert {
        /// Index in the right (`b`) trace.
        b: usize,
    },
    /// The step exists only in the left (`a`) trace.
    Delete {
        /// Index in the left (`a`) trace.
        a: usize,
    },
}

impl Op {
    /// Whether this op represents no change.
    pub fn is_equal(&self) -> bool {
        matches!(self, Op::Equal { .. })
    }
}

/// A single field-level difference within a changed step.
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct FieldDiff {
    /// Dotted path of the field, e.g. `content`, `name`, or `args.city`.
    pub path: String,
    /// The nature of the change.
    #[serde(flatten)]
    pub change: Change,
}

/// The kind of change applied to a field.
#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(tag = "change", rename_all = "snake_case")]
pub enum Change {
    /// The field was added on the right.
    Added {
        /// New value, rendered as compact JSON / text.
        value: String,
    },
    /// The field was removed on the right.
    Removed {
        /// Previous value.
        value: String,
    },
    /// The field's value changed.
    Modified {
        /// Value in the left trace.
        old: String,
        /// Value in the right trace.
        new: String,
        /// Optional inline token-level diff (populated for text fields).
        #[serde(skip_serializing_if = "Option::is_none")]
        inline: Option<Vec<Inline>>,
    },
}

/// A token in an inline word-level diff.
#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(tag = "t", content = "v", rename_all = "snake_case")]
pub enum Inline {
    /// Present in both.
    Equal(String),
    /// Present only on the right.
    Insert(String),
    /// Present only on the left.
    Delete(String),
}

/// Aggregate counts for a diff.
#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize)]
pub struct Stats {
    /// Number of equal steps.
    pub equal: usize,
    /// Number of changed steps.
    pub changed: usize,
    /// Number of inserted steps.
    pub inserted: usize,
    /// Number of deleted steps.
    pub deleted: usize,
}

/// The result of diffing two traces.
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct Diff {
    /// The ordered edit script.
    pub ops: Vec<Op>,
    /// Overall similarity of the two traces, in `[0, 1]`.
    pub similarity: f64,
    /// Index into [`ops`](Self::ops) of the first non-equal op, if any.
    pub first_divergence: Option<usize>,
    /// Aggregate counts.
    pub stats: Stats,
}

impl Diff {
    /// Whether the two traces are identical after normalization.
    pub fn is_identical(&self) -> bool {
        self.first_divergence.is_none()
    }
}

/// Direction taken in the DP, for backtracking.
#[derive(Clone, Copy, PartialEq)]
enum Move {
    Diag, // pair a[i-1] with b[j-1]
    Up,   // delete a[i-1]
    Left, // insert b[j-1]
}

const INF: f64 = f64::INFINITY;

/// Align two normalized traces into an edit script.
///
/// This assumes `a` and `b` have already been normalized; [`crate::diff`] wires
/// normalization and alignment together and is the usual entry point.
pub fn align(a: &Trace, b: &Trace, cfg: &Config) -> Diff {
    let n = a.steps.len();
    let m = b.steps.len();

    // cost[i][j] and back[i][j], stored row-major in flat vectors.
    let idx = |i: usize, j: usize| i * (m + 1) + j;
    let mut cost = vec![0.0f64; (n + 1) * (m + 1)];
    let mut back = vec![Move::Diag; (n + 1) * (m + 1)];

    for i in 1..=n {
        cost[idx(i, 0)] = i as f64;
        back[idx(i, 0)] = Move::Up;
    }
    for j in 1..=m {
        cost[idx(0, j)] = j as f64;
        back[idx(0, j)] = Move::Left;
    }

    for i in 1..=n {
        for j in 1..=m {
            let sim = step_similarity(&a.steps[i - 1], &b.steps[j - 1], &cfg.weights);
            let sub = if sim >= cfg.align_floor {
                cost[idx(i - 1, j - 1)] + (1.0 - sim)
            } else {
                INF
            };
            let del = cost[idx(i - 1, j)] + 1.0;
            let ins = cost[idx(i, j - 1)] + 1.0;

            // Prefer diagonal on ties so equal/near steps stay paired.
            let (best, mv) = if sub <= del && sub <= ins {
                (sub, Move::Diag)
            } else if del <= ins {
                (del, Move::Up)
            } else {
                (ins, Move::Left)
            };
            cost[idx(i, j)] = best;
            back[idx(i, j)] = mv;
        }
    }

    // Backtrack into a reversed op list.
    let mut ops = Vec::new();
    let (mut i, mut j) = (n, m);
    while i > 0 || j > 0 {
        match back[idx(i, j)] {
            Move::Diag if i > 0 && j > 0 => {
                let (sa, sb) = (&a.steps[i - 1], &b.steps[j - 1]);
                let sim = step_similarity(sa, sb, &cfg.weights);
                // Similarity ignores metadata (it is noise for *alignment*), but
                // metadata that survives normalization is meaningful: two steps
                // are only equal if they are similar AND their metadata matches.
                // (`Map` compares order-independently.)
                if sim >= cfg.equal_threshold && sa.meta == sb.meta {
                    ops.push(Op::Equal { a: i - 1, b: j - 1 });
                } else {
                    ops.push(Op::Change {
                        a: i - 1,
                        b: j - 1,
                        similarity: sim,
                        fields: field_diffs(sa, sb),
                    });
                }
                i -= 1;
                j -= 1;
            }
            Move::Up if i > 0 => {
                ops.push(Op::Delete { a: i - 1 });
                i -= 1;
            }
            Move::Left if j > 0 => {
                ops.push(Op::Insert { b: j - 1 });
                j -= 1;
            }
            // Fallbacks for the edges (should not happen given initialization).
            _ if i > 0 => {
                ops.push(Op::Delete { a: i - 1 });
                i -= 1;
            }
            _ => {
                ops.push(Op::Insert { b: j - 1 });
                j -= 1;
            }
        }
    }
    ops.reverse();

    let mut stats = Stats::default();
    let mut first_divergence = None;
    for (k, op) in ops.iter().enumerate() {
        match op {
            Op::Equal { .. } => stats.equal += 1,
            Op::Change { .. } => stats.changed += 1,
            Op::Insert { .. } => stats.inserted += 1,
            Op::Delete { .. } => stats.deleted += 1,
        }
        if first_divergence.is_none() && !op.is_equal() {
            first_divergence = Some(k);
        }
    }

    let total = (n + m) as f64;
    let similarity = if total == 0.0 {
        1.0
    } else {
        (1.0 - cost[idx(n, m)] / total).clamp(0.0, 1.0)
    };

    Diff {
        ops,
        similarity,
        first_divergence,
        stats,
    }
}

/// Render a JSON value compactly for display; strings are shown unquoted.
fn render(v: &Value) -> String {
    match v {
        Value::String(s) => s.clone(),
        other => other.to_string(),
    }
}

/// Compute field-level differences between two paired steps.
fn field_diffs(a: &Step, b: &Step) -> Vec<FieldDiff> {
    let mut out = Vec::new();

    diff_opt_text("role", &a.role, &b.role, false, &mut out);
    diff_opt_text("name", &a.name, &b.name, true, &mut out);
    diff_opt_text("content", &a.content, &b.content, true, &mut out);

    match (&a.args, &b.args) {
        (None, None) => {}
        (Some(x), None) => out.push(FieldDiff {
            path: "args".into(),
            change: Change::Removed { value: render(x) },
        }),
        (None, Some(y)) => out.push(FieldDiff {
            path: "args".into(),
            change: Change::Added { value: render(y) },
        }),
        (Some(x), Some(y)) => diff_value("args", x, y, &mut out),
    }

    // Metadata that survived normalization is worth surfacing too.
    for key in union_keys(a, b) {
        let path = format!("meta.{key}");
        match (a.meta.get(&key), b.meta.get(&key)) {
            (Some(x), Some(y)) if x != y => diff_value(&path, x, y, &mut out),
            (Some(x), None) => out.push(FieldDiff {
                path,
                change: Change::Removed { value: render(x) },
            }),
            (None, Some(y)) => out.push(FieldDiff {
                path,
                change: Change::Added { value: render(y) },
            }),
            _ => {}
        }
    }

    out
}

fn union_keys(a: &Step, b: &Step) -> Vec<String> {
    let mut keys: Vec<String> = a.meta.keys().cloned().collect();
    for k in b.meta.keys() {
        if !a.meta.contains_key(k) {
            keys.push(k.clone());
        }
    }
    keys
}

fn diff_opt_text(
    path: &str,
    a: &Option<String>,
    b: &Option<String>,
    inline: bool,
    out: &mut Vec<FieldDiff>,
) {
    match (a, b) {
        (Some(x), Some(y)) if x != y => out.push(FieldDiff {
            path: path.into(),
            change: Change::Modified {
                old: x.clone(),
                new: y.clone(),
                inline: if inline {
                    Some(inline_diff(x, y))
                } else {
                    None
                },
            },
        }),
        (Some(x), None) => out.push(FieldDiff {
            path: path.into(),
            change: Change::Removed { value: x.clone() },
        }),
        (None, Some(y)) => out.push(FieldDiff {
            path: path.into(),
            change: Change::Added { value: y.clone() },
        }),
        _ => {}
    }
}

/// Recursively diff two JSON values, emitting one [`FieldDiff`] per differing
/// leaf, keyed by dotted/bracketed path.
fn diff_value(path: &str, a: &Value, b: &Value, out: &mut Vec<FieldDiff>) {
    match (a, b) {
        (Value::Object(x), Value::Object(y)) => {
            let mut keys: Vec<&String> = x.keys().collect();
            for k in y.keys() {
                if !x.contains_key(k) {
                    keys.push(k);
                }
            }
            for k in keys {
                let child = format!("{path}.{k}");
                match (x.get(k), y.get(k)) {
                    (Some(va), Some(vb)) if va != vb => diff_value(&child, va, vb, out),
                    (Some(va), None) => out.push(FieldDiff {
                        path: child,
                        change: Change::Removed { value: render(va) },
                    }),
                    (None, Some(vb)) => out.push(FieldDiff {
                        path: child,
                        change: Change::Added { value: render(vb) },
                    }),
                    _ => {}
                }
            }
        }
        (Value::Array(x), Value::Array(y)) => {
            let max = x.len().max(y.len());
            for k in 0..max {
                let child = format!("{path}[{k}]");
                match (x.get(k), y.get(k)) {
                    (Some(va), Some(vb)) if va != vb => diff_value(&child, va, vb, out),
                    (Some(va), None) => out.push(FieldDiff {
                        path: child,
                        change: Change::Removed { value: render(va) },
                    }),
                    (None, Some(vb)) => out.push(FieldDiff {
                        path: child,
                        change: Change::Added { value: render(vb) },
                    }),
                    _ => {}
                }
            }
        }
        _ if a != b => {
            // Leaves (or type mismatch): a text field gets an inline diff.
            let inline = match (a, b) {
                (Value::String(x), Value::String(y)) => Some(inline_diff(x, y)),
                _ => None,
            };
            out.push(FieldDiff {
                path: path.into(),
                change: Change::Modified {
                    old: render(a),
                    new: render(b),
                    inline,
                },
            });
        }
        _ => {}
    }
}

/// Word-level inline diff of two strings via an LCS over whitespace tokens.
pub fn inline_diff(a: &str, b: &str) -> Vec<Inline> {
    let at: Vec<&str> = a.split_whitespace().collect();
    let bt: Vec<&str> = b.split_whitespace().collect();
    let (n, m) = (at.len(), bt.len());

    // LCS length table.
    let mut lcs = vec![0u32; (n + 1) * (m + 1)];
    let at_idx = |i: usize, j: usize| i * (m + 1) + j;
    for i in (0..n).rev() {
        for j in (0..m).rev() {
            lcs[at_idx(i, j)] = if at[i] == bt[j] {
                lcs[at_idx(i + 1, j + 1)] + 1
            } else {
                lcs[at_idx(i + 1, j)].max(lcs[at_idx(i, j + 1)])
            };
        }
    }

    let mut out = Vec::new();
    let (mut i, mut j) = (0, 0);
    while i < n && j < m {
        if at[i] == bt[j] {
            out.push(Inline::Equal(at[i].to_string()));
            i += 1;
            j += 1;
        } else if lcs[at_idx(i + 1, j)] >= lcs[at_idx(i, j + 1)] {
            out.push(Inline::Delete(at[i].to_string()));
            i += 1;
        } else {
            out.push(Inline::Insert(bt[j].to_string()));
            j += 1;
        }
    }
    while i < n {
        out.push(Inline::Delete(at[i].to_string()));
        i += 1;
    }
    while j < m {
        out.push(Inline::Insert(bt[j].to_string()));
        j += 1;
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::model::StepKind;
    use serde_json::json;

    fn msg(role: &str, content: &str) -> Step {
        Step::new(StepKind::Message)
            .with_role(role)
            .with_content(content)
    }

    #[test]
    fn identical_traces_are_all_equal() {
        let t = Trace::from_steps(vec![msg("user", "hi"), msg("assistant", "hello")]);
        let d = align(&t, &t, &Config::default());
        assert!(d.is_identical());
        assert_eq!(d.similarity, 1.0);
        assert_eq!(d.stats.equal, 2);
    }

    #[test]
    fn inserted_step_is_detected() {
        let a = Trace::from_steps(vec![msg("user", "hi")]);
        let b = Trace::from_steps(vec![msg("user", "hi"), msg("assistant", "hello")]);
        let d = align(&a, &b, &Config::default());
        assert_eq!(d.stats.inserted, 1);
        assert_eq!(d.stats.equal, 1);
        assert_eq!(d.first_divergence, Some(1));
    }

    #[test]
    fn changed_tool_arg_is_a_change_not_a_replace() {
        let a = Trace::from_steps(vec![
            Step::new(StepKind::ToolCall)
                .with_name("get_weather")
                .with_args(json!({"city": "Paris"})),
        ]);
        let b = Trace::from_steps(vec![
            Step::new(StepKind::ToolCall)
                .with_name("get_weather")
                .with_args(json!({"city": "Berlin"})),
        ]);
        let d = align(&a, &b, &Config::default());
        assert_eq!(d.stats.changed, 1);
        assert_eq!(d.stats.inserted, 0);
        assert_eq!(d.stats.deleted, 0);
        let Op::Change { fields, .. } = &d.ops[0] else {
            panic!("expected change, got {:?}", d.ops[0]);
        };
        assert_eq!(fields.len(), 1);
        assert_eq!(fields[0].path, "args.city");
    }

    #[test]
    fn dissimilar_steps_become_delete_plus_insert() {
        let a = Trace::from_steps(vec![msg("user", "the quick brown fox")]);
        let b = Trace::from_steps(vec![
            Step::new(StepKind::ToolCall)
                .with_name("unrelated")
                .with_args(json!({"x": 1})),
        ]);
        let d = align(&a, &b, &Config::default());
        assert_eq!(d.stats.deleted, 1);
        assert_eq!(d.stats.inserted, 1);
        assert_eq!(d.stats.changed, 0);
    }

    #[test]
    fn inline_diff_marks_word_changes() {
        let d = inline_diff("the quick brown fox", "the slow brown fox");
        assert!(d.contains(&Inline::Delete("quick".into())));
        assert!(d.contains(&Inline::Insert("slow".into())));
        assert!(d.contains(&Inline::Equal("brown".into())));
    }
}