asupersync 0.3.1

Spec-first, cancel-correct, capability-secure async runtime for Rust.
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
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
//! Formatting utilities for trace output.
//!
//! Provides human-readable and machine-readable formatting for traces.

use super::buffer::TraceBuffer;
use super::canonicalize::{TraceEventKey, canonicalize, trace_event_key, trace_fingerprint};
use super::event::TraceEvent;
use serde::{Deserialize, Serialize};
use std::io::{self, Write};

/// Schema version for golden trace fixtures.
pub const GOLDEN_TRACE_SCHEMA_VERSION: u32 = 1;

/// Minimal configuration snapshot for golden trace fixtures.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct GoldenTraceConfig {
    /// Deterministic seed used to run the workload.
    pub seed: u64,
    /// Entropy seed used for capability randomness.
    pub entropy_seed: u64,
    /// Virtual worker count.
    pub worker_count: usize,
    /// Trace buffer capacity.
    pub trace_capacity: usize,
    /// Maximum steps before termination (if set).
    pub max_steps: Option<u64>,
    /// Maximum number of Foata layers to keep in the canonical prefix.
    pub canonical_prefix_layers: usize,
    /// Maximum number of events to keep in the canonical prefix.
    pub canonical_prefix_events: usize,
}

/// Summary of oracle results for a golden trace run.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct GoldenTraceOracleSummary {
    /// Sorted list of oracle violation tags (empty if all invariants held).
    pub violations: Vec<String>,
}

/// Golden trace fixture for deterministic verification.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct GoldenTraceFixture {
    /// Fixture schema version.
    pub schema_version: u32,
    /// Configuration snapshot.
    pub config: GoldenTraceConfig,
    /// Canonical trace fingerprint.
    pub fingerprint: u64,
    /// Number of events in the trace.
    pub event_count: u64,
    /// Canonicalized prefix (Foata layers of stable event keys).
    pub canonical_prefix: Vec<Vec<TraceEventKey>>,
    /// Oracle summary captured at end of the run.
    pub oracle_summary: GoldenTraceOracleSummary,
}

impl GoldenTraceFixture {
    /// Build a golden trace fixture from a trace event slice.
    #[must_use]
    pub fn from_events(
        config: GoldenTraceConfig,
        events: &[TraceEvent],
        oracle_violations: impl IntoIterator<Item = impl Into<String>>,
    ) -> Self {
        let canonical_prefix = canonical_prefix(
            events,
            config.canonical_prefix_layers,
            config.canonical_prefix_events,
        );
        let mut violations: Vec<String> = oracle_violations.into_iter().map(Into::into).collect();
        violations.sort();
        violations.dedup();

        Self {
            schema_version: GOLDEN_TRACE_SCHEMA_VERSION,
            fingerprint: trace_fingerprint(events),
            event_count: u64::try_from(events.len()).unwrap_or(u64::MAX),
            canonical_prefix,
            oracle_summary: GoldenTraceOracleSummary { violations },
            config,
        }
    }

    /// Compare two fixtures and return a diff if any field changed.
    pub fn verify(&self, actual: &Self) -> Result<(), GoldenTraceDiff> {
        GoldenTraceDiff::from_fixtures(self, actual).into_result()
    }

    /// Build a structured replay-delta report against another fixture.
    #[must_use]
    pub fn delta_report(&self, actual: &Self) -> GoldenTraceDeltaReport {
        GoldenTraceDiff::from_fixtures(self, actual).to_delta_report(self, actual)
    }
}

/// Category of replay-delta mismatch.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum GoldenTraceDeltaClass {
    /// Runtime configuration or schema changed.
    Config,
    /// Timing envelope changed while replay semantics may still match.
    Timing,
    /// Core semantic behavior changed (event stream/fingerprint/prefix).
    Semantic,
    /// Diagnostic or oracle-surface behavior changed.
    Observability,
}

/// Severity for replay-delta mismatch.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum GoldenTraceDeltaSeverity {
    /// Informational drift that does not typically fail a gate.
    Info,
    /// Drift that should trigger review and potential gate escalation.
    Warning,
    /// Drift that should fail verification unless explicitly approved.
    Error,
}

/// Single replay-delta mismatch.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct GoldenTraceDelta {
    /// Logical drift class for this mismatch.
    pub class: GoldenTraceDeltaClass,
    /// Severity assigned to this mismatch.
    pub severity: GoldenTraceDeltaSeverity,
    /// Stable field identifier for machine parsing.
    pub field: String,
    /// Human-readable mismatch summary.
    pub message: String,
}

/// Structured replay-delta report between two fixtures.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[allow(clippy::struct_excessive_bools)]
pub struct GoldenTraceDeltaReport {
    /// Fingerprint recorded in the baseline fixture.
    pub expected_fingerprint: u64,
    /// Fingerprint recorded in the candidate fixture.
    pub actual_fingerprint: u64,
    /// Event count from the baseline fixture.
    pub expected_event_count: u64,
    /// Event count from the candidate fixture.
    pub actual_event_count: u64,
    /// True when schema or configuration changed.
    pub config_drift: bool,
    /// True when core semantic behavior changed.
    pub semantic_drift: bool,
    /// True when replay timing envelope changed.
    pub timing_drift: bool,
    /// True when oracle/diagnostic surface changed.
    pub observability_drift: bool,
    /// Detailed mismatch entries.
    pub deltas: Vec<GoldenTraceDelta>,
}

impl GoldenTraceDeltaReport {
    /// Returns true when no drift is present.
    #[must_use]
    pub fn is_clean(&self) -> bool {
        self.deltas.is_empty()
    }

    /// Serialize the report to pretty JSON for CI artifacts.
    ///
    /// # Errors
    ///
    /// Returns an error if serialization fails.
    pub fn to_json(&self) -> Result<String, serde_json::Error> {
        serde_json::to_string_pretty(self)
    }
}

/// Diff between two golden trace fixtures.
#[derive(Debug, Default)]
pub struct GoldenTraceDiff {
    mismatches: Vec<GoldenTraceMismatch>,
}

impl GoldenTraceDiff {
    /// Returns true if no mismatches were recorded.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.mismatches.is_empty()
    }

    fn push(&mut self, mismatch: GoldenTraceMismatch) {
        self.mismatches.push(mismatch);
    }

    fn from_fixtures(expected: &GoldenTraceFixture, actual: &GoldenTraceFixture) -> Self {
        let mut diff = Self::default();
        if expected.schema_version != actual.schema_version {
            diff.push(GoldenTraceMismatch::SchemaVersion {
                expected: expected.schema_version,
                actual: actual.schema_version,
            });
        }
        if expected.config != actual.config {
            diff.push(GoldenTraceMismatch::Config {
                expected: expected.config.clone(),
                actual: actual.config.clone(),
            });
        }
        if expected.fingerprint != actual.fingerprint {
            diff.push(GoldenTraceMismatch::Fingerprint {
                expected: expected.fingerprint,
                actual: actual.fingerprint,
            });
        }
        if expected.event_count != actual.event_count {
            diff.push(GoldenTraceMismatch::EventCount {
                expected: expected.event_count,
                actual: actual.event_count,
            });
        }
        if expected.canonical_prefix != actual.canonical_prefix {
            diff.push(GoldenTraceMismatch::CanonicalPrefix {
                expected_layers: expected.canonical_prefix.len(),
                actual_layers: actual.canonical_prefix.len(),
                first_mismatch: first_prefix_mismatch(
                    &expected.canonical_prefix,
                    &actual.canonical_prefix,
                ),
            });
        }
        if expected.oracle_summary != actual.oracle_summary {
            diff.push(GoldenTraceMismatch::OracleViolations {
                expected: expected.oracle_summary.violations.clone(),
                actual: actual.oracle_summary.violations.clone(),
            });
        }
        diff
    }

    fn into_result(self) -> Result<(), Self> {
        if self.is_empty() { Ok(()) } else { Err(self) }
    }

    /// Convert mismatch data to a structured replay-delta report.
    #[must_use]
    pub fn to_delta_report(
        &self,
        expected: &GoldenTraceFixture,
        actual: &GoldenTraceFixture,
    ) -> GoldenTraceDeltaReport {
        let mut config_drift = false;
        let mut semantic_drift = false;
        let mut timing_drift = false;
        let mut observability_drift = false;
        let mut deltas = Vec::with_capacity(self.mismatches.len());

        for mismatch in &self.mismatches {
            let (class, severity, field) = classify_delta(mismatch);
            match class {
                GoldenTraceDeltaClass::Config => config_drift = true,
                GoldenTraceDeltaClass::Timing => timing_drift = true,
                GoldenTraceDeltaClass::Semantic => semantic_drift = true,
                GoldenTraceDeltaClass::Observability => observability_drift = true,
            }
            deltas.push(GoldenTraceDelta {
                class,
                severity,
                field: field.to_string(),
                message: mismatch.to_string(),
            });
        }

        GoldenTraceDeltaReport {
            expected_fingerprint: expected.fingerprint,
            actual_fingerprint: actual.fingerprint,
            expected_event_count: expected.event_count,
            actual_event_count: actual.event_count,
            config_drift,
            semantic_drift,
            timing_drift,
            observability_drift,
            deltas,
        }
    }
}

fn classify_delta(
    mismatch: &GoldenTraceMismatch,
) -> (
    GoldenTraceDeltaClass,
    GoldenTraceDeltaSeverity,
    &'static str,
) {
    match mismatch {
        GoldenTraceMismatch::SchemaVersion { .. } => (
            GoldenTraceDeltaClass::Config,
            GoldenTraceDeltaSeverity::Error,
            "schema_version",
        ),
        GoldenTraceMismatch::Config { .. } => (
            GoldenTraceDeltaClass::Config,
            GoldenTraceDeltaSeverity::Error,
            "config",
        ),
        GoldenTraceMismatch::Fingerprint { .. } => (
            GoldenTraceDeltaClass::Semantic,
            GoldenTraceDeltaSeverity::Error,
            "fingerprint",
        ),
        GoldenTraceMismatch::EventCount { .. } => (
            GoldenTraceDeltaClass::Timing,
            GoldenTraceDeltaSeverity::Warning,
            "event_count",
        ),
        GoldenTraceMismatch::CanonicalPrefix { .. } => (
            GoldenTraceDeltaClass::Semantic,
            GoldenTraceDeltaSeverity::Error,
            "canonical_prefix",
        ),
        GoldenTraceMismatch::OracleViolations { .. } => (
            GoldenTraceDeltaClass::Observability,
            GoldenTraceDeltaSeverity::Warning,
            "oracle_violations",
        ),
    }
}

impl std::fmt::Display for GoldenTraceDiff {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        for mismatch in &self.mismatches {
            writeln!(f, "{mismatch}")?;
        }
        Ok(())
    }
}

impl std::error::Error for GoldenTraceDiff {}

#[derive(Debug)]
enum GoldenTraceMismatch {
    SchemaVersion {
        expected: u32,
        actual: u32,
    },
    Config {
        expected: GoldenTraceConfig,
        actual: GoldenTraceConfig,
    },
    Fingerprint {
        expected: u64,
        actual: u64,
    },
    EventCount {
        expected: u64,
        actual: u64,
    },
    CanonicalPrefix {
        expected_layers: usize,
        actual_layers: usize,
        first_mismatch: Option<(usize, usize)>,
    },
    OracleViolations {
        expected: Vec<String>,
        actual: Vec<String>,
    },
}

impl std::fmt::Display for GoldenTraceMismatch {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::SchemaVersion { expected, actual } => {
                write!(
                    f,
                    "schema_version changed (expected {expected}, actual {actual})"
                )
            }
            Self::Config { expected, actual } => {
                write!(
                    f,
                    "config changed (expected {expected:?}, actual {actual:?})"
                )
            }
            Self::Fingerprint { expected, actual } => {
                write!(
                    f,
                    "fingerprint changed (expected 0x{expected:016X}, actual 0x{actual:016X})"
                )
            }
            Self::EventCount { expected, actual } => write!(
                f,
                "event_count changed (expected {expected}, actual {actual})"
            ),
            Self::CanonicalPrefix {
                expected_layers,
                actual_layers,
                first_mismatch,
            } => {
                if let Some((layer, index)) = first_mismatch {
                    write!(
                        f,
                        "canonical_prefix mismatch (layer {layer}, index {index}; expected_layers={expected_layers}, actual_layers={actual_layers})"
                    )
                } else {
                    write!(
                        f,
                        "canonical_prefix mismatch (expected_layers={expected_layers}, actual_layers={actual_layers})"
                    )
                }
            }
            Self::OracleViolations { expected, actual } => {
                write!(
                    f,
                    "oracle violations changed (expected {expected:?}, actual {actual:?})"
                )
            }
        }
    }
}

fn canonical_prefix(
    events: &[TraceEvent],
    max_layers: usize,
    max_events: usize,
) -> Vec<Vec<TraceEventKey>> {
    let foata = canonicalize(events);
    let mut remaining = max_events;
    let mut prefix = Vec::new();

    for layer in foata.layers().iter().take(max_layers) {
        if remaining == 0 {
            break;
        }
        let mut keys = Vec::new();
        for event in layer {
            if remaining == 0 {
                break;
            }
            keys.push(trace_event_key(event));
            remaining = remaining.saturating_sub(1);
        }
        if !keys.is_empty() {
            prefix.push(keys);
        }
    }

    prefix
}

fn first_prefix_mismatch(
    expected: &[Vec<TraceEventKey>],
    actual: &[Vec<TraceEventKey>],
) -> Option<(usize, usize)> {
    let layers = expected.len().min(actual.len());
    for layer_idx in 0..layers {
        let expected_layer = &expected[layer_idx];
        let actual_layer = &actual[layer_idx];
        let events = expected_layer.len().min(actual_layer.len());
        for event_idx in 0..events {
            if expected_layer[event_idx] != actual_layer[event_idx] {
                return Some((layer_idx, event_idx));
            }
        }
        if expected_layer.len() != actual_layer.len() {
            return Some((layer_idx, events));
        }
    }
    if expected.len() != actual.len() {
        return Some((layers, 0));
    }
    None
}

/// Formats a trace buffer as human-readable text.
pub fn format_trace(buffer: &TraceBuffer, w: &mut impl Write) -> io::Result<()> {
    writeln!(w, "=== Trace ({} events) ===", buffer.len())?;
    for event in buffer.iter() {
        writeln!(w, "{event}")?;
    }
    writeln!(w, "=== End Trace ===")?;
    Ok(())
}

/// Formats a trace buffer as a string.
#[must_use]
pub fn trace_to_string(buffer: &TraceBuffer) -> String {
    let mut s = Vec::new();
    format_trace(buffer, &mut s).expect("writing to Vec should not fail");
    String::from_utf8(s).expect("trace should be valid UTF-8")
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::trace::event::{TraceData, TraceEvent, TraceEventKind};
    use crate::types::Time;

    #[test]
    fn format_empty_trace() {
        let buffer = TraceBuffer::new(10);
        let output = trace_to_string(&buffer);
        assert!(output.contains("0 events"));
    }

    #[test]
    fn format_with_events() {
        let mut buffer = TraceBuffer::new(10);
        buffer.push(TraceEvent::new(
            1,
            Time::from_millis(100),
            TraceEventKind::UserTrace,
            TraceData::Message("test".to_string()),
        ));
        let output = trace_to_string(&buffer);
        assert!(output.contains("1 events"));
        assert!(output.contains("test"));
    }

    // Pure data-type tests (wave 14 – CyanBarn)

    #[test]
    fn golden_trace_config_debug_clone_eq() {
        let cfg = GoldenTraceConfig {
            seed: 42,
            entropy_seed: 7,
            worker_count: 4,
            trace_capacity: 1000,
            max_steps: Some(500),
            canonical_prefix_layers: 10,
            canonical_prefix_events: 100,
        };
        let dbg = format!("{cfg:?}");
        assert!(dbg.contains("GoldenTraceConfig"));

        let cloned = cfg.clone();
        assert_eq!(cfg, cloned);
    }

    #[test]
    fn golden_trace_config_ne() {
        let a = GoldenTraceConfig {
            seed: 1,
            entropy_seed: 0,
            worker_count: 1,
            trace_capacity: 10,
            max_steps: None,
            canonical_prefix_layers: 1,
            canonical_prefix_events: 1,
        };
        let mut b = a.clone();
        b.seed = 2;
        assert_ne!(a, b);
    }

    #[test]
    fn golden_trace_oracle_summary_debug_clone_eq() {
        let summary = GoldenTraceOracleSummary {
            violations: vec!["leak".to_string()],
        };
        let dbg = format!("{summary:?}");
        assert!(dbg.contains("GoldenTraceOracleSummary"));

        let cloned = summary.clone();
        assert_eq!(summary, cloned);
    }

    #[test]
    fn golden_trace_oracle_summary_empty() {
        let summary = GoldenTraceOracleSummary { violations: vec![] };
        assert!(summary.violations.is_empty());
    }

    #[test]
    fn golden_trace_diff_default_is_empty() {
        let diff = GoldenTraceDiff::default();
        assert!(diff.is_empty());
    }

    #[test]
    fn golden_trace_diff_debug() {
        let diff = GoldenTraceDiff::default();
        let dbg = format!("{diff:?}");
        assert!(dbg.contains("GoldenTraceDiff"));
    }

    #[test]
    fn golden_trace_diff_display_empty() {
        let diff = GoldenTraceDiff::default();
        let display = diff.to_string();
        assert!(display.is_empty());
    }

    #[test]
    fn golden_trace_diff_error_trait() {
        let diff = GoldenTraceDiff::default();
        let err: &dyn std::error::Error = &diff;
        assert!(err.source().is_none());
    }

    #[test]
    fn golden_trace_mismatch_display_all_variants() {
        let m = GoldenTraceMismatch::SchemaVersion {
            expected: 1,
            actual: 2,
        };
        assert!(m.to_string().contains("schema_version"));

        let m = GoldenTraceMismatch::Fingerprint {
            expected: 0xAB,
            actual: 0xCD,
        };
        assert!(m.to_string().contains("fingerprint"));

        let m = GoldenTraceMismatch::EventCount {
            expected: 10,
            actual: 20,
        };
        assert!(m.to_string().contains("event_count"));

        let m = GoldenTraceMismatch::CanonicalPrefix {
            expected_layers: 3,
            actual_layers: 5,
            first_mismatch: Some((1, 2)),
        };
        let s = m.to_string();
        assert!(s.contains("canonical_prefix"));
        assert!(s.contains("layer 1"));

        let m = GoldenTraceMismatch::CanonicalPrefix {
            expected_layers: 3,
            actual_layers: 5,
            first_mismatch: None,
        };
        assert!(m.to_string().contains("expected_layers=3"));

        let m = GoldenTraceMismatch::OracleViolations {
            expected: vec!["a".into()],
            actual: vec!["b".into()],
        };
        assert!(m.to_string().contains("oracle violations"));
    }

    #[test]
    fn golden_trace_mismatch_config_variant() {
        let cfg1 = GoldenTraceConfig {
            seed: 1,
            entropy_seed: 0,
            worker_count: 1,
            trace_capacity: 10,
            max_steps: None,
            canonical_prefix_layers: 1,
            canonical_prefix_events: 1,
        };
        let cfg2 = GoldenTraceConfig { seed: 2, ..cfg1 };
        let m = GoldenTraceMismatch::Config {
            expected: cfg1,
            actual: cfg2,
        };
        assert!(m.to_string().contains("config changed"));
    }

    #[test]
    fn golden_trace_mismatch_debug() {
        let m = GoldenTraceMismatch::SchemaVersion {
            expected: 1,
            actual: 2,
        };
        let dbg = format!("{m:?}");
        assert!(dbg.contains("SchemaVersion"));
    }

    #[test]
    fn schema_version_constant() {
        assert_eq!(GOLDEN_TRACE_SCHEMA_VERSION, 1);
    }

    #[test]
    fn first_prefix_mismatch_identical() {
        let a: Vec<Vec<TraceEventKey>> = vec![];
        assert!(first_prefix_mismatch(&a, &a).is_none());
    }

    #[test]
    fn first_prefix_mismatch_different_lengths() {
        let a: Vec<Vec<TraceEventKey>> = vec![vec![]];
        let b: Vec<Vec<TraceEventKey>> = vec![];
        let m = first_prefix_mismatch(&a, &b);
        assert!(m.is_some());
    }

    #[test]
    fn golden_trace_delta_report_clean_when_equal() {
        let config = GoldenTraceConfig {
            seed: 1,
            entropy_seed: 1,
            worker_count: 1,
            trace_capacity: 32,
            max_steps: Some(128),
            canonical_prefix_layers: 2,
            canonical_prefix_events: 8,
        };
        let expected = GoldenTraceFixture::from_events(config, &[], std::iter::empty::<String>());
        let report = expected.delta_report(&expected);
        assert!(report.is_clean());
        assert!(!report.config_drift);
        assert!(!report.semantic_drift);
        assert!(!report.timing_drift);
        assert!(!report.observability_drift);
        assert!(report.to_json().expect("json").contains("\"deltas\""));
    }

    #[test]
    fn golden_trace_delta_report_detects_drift_classes() {
        let config = GoldenTraceConfig {
            seed: 1,
            entropy_seed: 1,
            worker_count: 1,
            trace_capacity: 32,
            max_steps: Some(128),
            canonical_prefix_layers: 2,
            canonical_prefix_events: 8,
        };
        let expected = GoldenTraceFixture::from_events(config, &[], std::iter::empty::<String>());
        let mut actual = expected.clone();
        actual.config.seed = 2;
        actual.fingerprint ^= 0xA5A5;
        actual.event_count = actual.event_count.saturating_add(1);
        actual.oracle_summary.violations = vec!["TaskLeak".to_string()];

        let report = expected.delta_report(&actual);
        assert!(!report.is_clean());
        assert!(report.config_drift);
        assert!(report.semantic_drift);
        assert!(report.timing_drift);
        assert!(report.observability_drift);
        assert!(report.deltas.iter().any(|d| d.field == "config"));
        assert!(report.deltas.iter().any(|d| d.field == "fingerprint"));
        assert!(report.deltas.iter().any(|d| d.field == "event_count"));
        assert!(report.deltas.iter().any(|d| d.field == "oracle_violations"));
    }
}